API 参考手册¶
- class angr.BP(when='before', enabled=None, condition=None, action=None, **kwargs)[源代码]¶
基类:
objectA breakpoint.
- class angr.Analysis[源代码]¶
基类:
objectThis 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.AngrCorruptDBError[源代码]¶
基类:
AngrDBError
- exception angr.AngrIncompatibleDBError[源代码]¶
基类:
AngrDBError
- exception angr.AngrRuntimeError[源代码]¶
基类:
RuntimeError
- exception angr.AngrVFGRestartAnalysisNotice[源代码]¶
基类:
AngrVFGError
- exception angr.AngrValueError[源代码]¶
基类:
AngrError,ValueError
- 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)[源代码]¶
基类:
objectBlade 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.
- 参数:
- __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¶
- 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)[源代码]¶
基类:
SerializableRepresents 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¶
- property vex_nostmt¶
- property disassembly: DisassemblerBlock¶
Provide a disassembly object using whatever disassembler is available
- property capstone¶
- property codenode¶
- property instruction_addrs¶
- class angr.ExplorationTechnique[源代码]¶
基类:
objectAn 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_techniquewith an instance of the technique.- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 withsimgr.completion_mode.- 参数:
simgr (angr.SimulationManager)
- class angr.KnowledgeBase(project, obj=None, name=None)[源代码]¶
基类:
objectRepresents 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¶
- property callgraph¶
- property unresolved_indirect_jumps¶
- property resolved_indirect_jumps¶
- 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
-
functions:
- class angr.PTChunk(base, sim_state, heap=None)[源代码]¶
基类:
ChunkA 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
- get_size()[源代码]¶
Returns the actual size of a chunk (as opposed to the entire size field, which may include some flags).
- 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).
- 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
- 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)[源代码]¶
基类:
objectThis 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.
- 参数:
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).
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.
- 参数:
- __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)[源代码]¶
- property kb¶
- 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.Hookdescribing 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.
- 返回类型:
- 返回:
True if addr is hooked, False otherwise.
- hooked_by(addr)[源代码]¶
Returns the current hook for addr.
- 参数:
addr -- An address.
- 返回类型:
- 返回:
None if the address is not hooked.
- 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.
- 返回类型:
- symbol_hooked_by(symbol_name)[源代码]¶
Return the SimProcedure, if it exists, for the given symbol name.
- 参数:
symbol_name (str) -- Name of the symbol.
- 返回类型:
- 返回:
None if the address is not hooked.
- 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.
- 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)[源代码]¶
基类:
objectServer 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)[源代码]¶
- property active_workers¶
- property stopped¶
- class angr.SimCC(arch)[源代码]¶
基类:
objectA 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)
- STACKARG_SP_BUFF = 0¶
- STACKARG_SP_DIFF = 0¶
-
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)¶
基类:
objectA 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)
- 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)[源代码]¶
- 参数:
session (ArgSession)
arg_type (SimType)
- 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.
- 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)
- 返回类型:
- 返回:
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.SimError[源代码]¶
基类:
Exception- bbl_addr = None¶
- stmt_idx = None¶
- ins_addr = None¶
- executed_instruction_count = None¶
- guard = None¶
- class angr.SimFile(name=None, content=None, size=None, has_end=None, seekable=True, writable=True, ident=None, concrete=None, **kwargs)[源代码]¶
-
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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.SimFileBase(name=None, writable=True, ident=None, concrete=False, file_exists=True, **kwargs)[源代码]¶
-
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
posargument, which may have different semantics per-class.0will 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
.posif 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
posmust 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¶
- 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.memoThe 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)[源代码]¶
-
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
- 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.
- 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.SimFileDescriptorDuplex(read_file, write_file)[源代码]¶
-
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
- 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.SimFileStream(name=None, content=None, pos=0, **kwargs)[源代码]¶
基类:
SimFileA 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
poson 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- class angr.SimHeapBrk(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseSimHeapBrk 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]¶
-
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_pluginwith nameheapin 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
- 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.memoThe 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.
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.SimHostFilesystem(host_path=None, **kwargs)[源代码]¶
-
Simulated mount that makes some piece from the host filesystem available to the guest.
- 参数:
- 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.memoThe 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.SimIRSBNoDecodeError[源代码]¶
基类:
SimIRSBError
- class angr.SimMount[源代码]¶
-
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
- class angr.SimOS(project, name=None)[源代码]¶
基类:
objectA class describing OS/arch-level configuration.
- 参数:
project (angr.Project)
- 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
- 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
- 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.SimPackets(name, write_mode=None, content=None, writable=True, ident=None, **kwargs)[源代码]¶
基类:
SimFileBaseThe 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.
- property size¶
The number of data bytes stored by the file at present. May be a symbolic value.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.SimPacketsStream(name, pos=0, **kwargs)[源代码]¶
基类:
SimPacketsA 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
poson 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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)[源代码]¶
基类:
objectA SimProcedure is a wonderful object which describes a procedure to run on a state.
You may subclass SimProcedure and override
run(), replacing it with mutatingself.statehowever 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
rundisplay_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)[源代码]¶
- 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.
- NO_RET = False¶
- DYNAMIC_RET = False¶
- ADDS_EXITS = False¶
- IS_FUNCTION = True¶
- ARGS_MISMATCH = False¶
- ALT_NAMES = None¶
- 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).
- 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.
- 返回类型:
- 返回:
True if the call returns, False otherwise.
- property should_add_successors¶
- 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
- 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.
- property is_java¶
- property argument_types¶
- property return_type¶
- angr.SimSegfaultError¶
- 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.
- 参数:
project (angr.Project) -- The project instance.
arch (archinfo.Arch|str) -- The architecture of the state.
plugins (dict[str, SimStatePlugin] | None)
mode (str | None)
options (set[str] | list[str] | SimStateOptions | None)
special_memory_filler (Callable[[str, int, int, SimState], Any] | None)
os_name (str | None)
plugin_preset (str)
cle_memory_backer (Clemory | None)
default_permissions (int)
stack_perms (int | None)
stack_end (int | None)
stack_size (int | None)
- 变量:
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.SimMemViewregisters -- 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.SimInspectorlog -- 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)[源代码]¶
- 参数:
project (Project | None)
arch (Arch | None)
plugins (dict[str, SimStatePlugin] | None)
mode (str | None)
options (set[str] | list[str] | SimStateOptions | None)
special_memory_filler (Callable[[str, int, int, SimState], Any] | None)
os_name (str | None)
plugin_preset (str)
cle_memory_backer (Clemory | None)
default_permissions (int)
stack_perms (int | None)
stack_end (int | None)
stack_size (int | None)
- property plugins¶
- property ip¶
Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions. Use
_ipto 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
- 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.
- register_plugin(name, plugin, inhibit_init=False)[源代码]¶
Add a new plugin
pluginwith namenameto 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.
- add_constraints(*constraints)[源代码]¶
Add some constraints to the state.
You may pass in any number of symbolic booleans as variadic positional arguments.
- 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.
- 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.
- 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.
- property thumb¶
- property with_condition¶
- class angr.SimStatePlugin[源代码]¶
基类:
objectThis 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¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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)[源代码]¶
基类:
objectThe 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: seeangr.factory.AngrObjectFactory.The most important methods you should look at are
step,explore, anduse_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
errorelist. 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
unsatstash 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
completehook set will interact. By default, the builtin functionany.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
completehook set will interact. By default, the builtin functionany.
- 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)[源代码]¶
- 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=Trueto 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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
simgrand put them in their corresponding stashes in this manager. This will not modifysimgr.
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- class angr.StateHierarchy[源代码]¶
基类:
objectThe 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"
- angr.UnsupportedSyscallError¶
- 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.
- 返回类型:
- 返回:
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 textarch -- 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
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 textarch -- 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)[源代码]¶
基类:
objectThis 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.
- 参数:
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).
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.
- 参数:
- __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)[源代码]¶
- property kb¶
- 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.Hookdescribing 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.
- 返回类型:
- 返回:
True if addr is hooked, False otherwise.
- hooked_by(addr)[源代码]¶
Returns the current hook for addr.
- 参数:
addr -- An address.
- 返回类型:
- 返回:
None if the address is not hooked.
- 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.
- 返回类型:
- symbol_hooked_by(symbol_name)[源代码]¶
Return the SimProcedure, if it exists, for the given symbol name.
- 参数:
symbol_name (str) -- Name of the symbol.
- 返回类型:
- 返回:
None if the address is not hooked.
- 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.
- class angr.factory.AngrObjectFactory(project, default_engine=None)[源代码]¶
基类:
objectThis factory provides access to important analysis elements.
-
procedure_engine:
ProcedureEngine¶
- property default_engine¶
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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 foraddr.
- 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.
- 返回类型:
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.
- 参数:
- 返回:
The new 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
SimStateis 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.
- 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.
- 返回类型:
- 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)[源代码]¶
-
procedure_engine:
- class angr.block.DisassemblerBlock(addr, insns, thumb, arch)[源代码]¶
基类:
objectHelper class to represent a block of disassembled target architecture instructions
- addr¶
- insns¶
- thumb¶
- arch¶
- class angr.block.DisassemblerInsn[源代码]¶
基类:
objectHelper class to represent a disassembled target architecture instruction
- class angr.block.CapstoneBlock(addr, insns, thumb, arch)[源代码]¶
-
Deep copy of the capstone blocks, which have serious issues with having extended lifespans outside of capstone itself
- 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)[源代码]¶
基类:
SerializableRepresents 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¶
- property vex_nostmt¶
- property disassembly: DisassemblerBlock¶
Provide a disassembly object using whatever disassembler is available
- property capstone¶
- property codenode¶
- property instruction_addrs¶
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.
- 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.
- class angr.misc.plugins.PluginPreset[源代码]¶
基类:
objectA 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.
- class angr.misc.plugins.PluginVendor[源代码]¶
-
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.
- class angr.misc.plugins.VendorPreset[源代码]¶
基类:
PluginPresetA specialized preset class for use with the PluginVendor.
Program State¶
- 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.
- 参数:
project (angr.Project) -- The project instance.
arch (archinfo.Arch|str) -- The architecture of the state.
plugins (dict[str, SimStatePlugin] | None)
mode (str | None)
options (set[str] | list[str] | SimStateOptions | None)
special_memory_filler (Callable[[str, int, int, SimState], Any] | None)
os_name (str | None)
plugin_preset (str)
cle_memory_backer (Clemory | None)
default_permissions (int)
stack_perms (int | None)
stack_end (int | None)
stack_size (int | None)
- 变量:
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.SimMemViewregisters -- 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.SimInspectorlog -- 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)[源代码]¶
- 参数:
project (Project | None)
arch (Arch | None)
plugins (dict[str, SimStatePlugin] | None)
mode (str | None)
options (set[str] | list[str] | SimStateOptions | None)
special_memory_filler (Callable[[str, int, int, SimState], Any] | None)
os_name (str | None)
plugin_preset (str)
cle_memory_backer (Clemory | None)
default_permissions (int)
stack_perms (int | None)
stack_end (int | None)
stack_size (int | None)
- property plugins¶
- property ip¶
Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions. Use
_ipto 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
- 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.
- register_plugin(name, plugin, inhibit_init=False)[源代码]¶
Add a new plugin
pluginwith namenameto 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.
- add_constraints(*constraints)[源代码]¶
Add some constraints to the state.
You may pass in any number of symbolic booleans as variadic positional arguments.
- 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.
- 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.
- 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.
- property thumb¶
- property with_condition¶
- class angr.sim_state_options.StateOption(name, types, default='_NO_DEFAULT_VALUE', description=None)[源代码]¶
基类:
objectDescribes a state option.
- name¶
- types¶
- default¶
- description¶
- property has_default_value¶
- class angr.sim_state_options.SimStateOptions(thing)[源代码]¶
基类:
objectA 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.
- 返回类型:
- tally(exclude_false=True, description=False)[源代码]¶
Return a string representation of all state options.
- classmethod register_option(name, types, default=None, description=None)[源代码]¶
Register a state option.
- class angr.state_plugins.GDB(omit_fp=False, adjust_stack=False)[源代码]¶
-
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 registersin 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.memoThe 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)[源代码]¶
-
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property current_function_address¶
Address of the current function.
- 返回:
the address of the function
- 返回类型:
- property current_stack_pointer¶
Get the value of the stack pointer.
- 返回:
Value of the stack pointer
- 返回类型:
- 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.
- 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.
- 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
- class angr.state_plugins.PTChunk(base, sim_state, heap=None)[源代码]¶
基类:
ChunkA 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
- get_size()[源代码]¶
Returns the actual size of a chunk (as opposed to the entire size field, which may include some flags).
- 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).
- 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
- class angr.state_plugins.PTChunkIterator(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]¶
基类:
object
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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[源代码]¶
基类:
SimMountThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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)[源代码]¶
基类:
SimEventA 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¶
- class angr.state_plugins.SimActionConstraint(state, constraint, condition=None)[源代码]¶
基类:
SimActionA 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)[源代码]¶
基类:
SimActionA 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.
- 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)[源代码]¶
基类:
SimActionAn 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)[源代码]¶
基类:
objectA SimActionObject tracks an AST and its dependencies.
- 参数:
ast (Base)
reg_deps (frozenset[SimActionData | SimActionOperation])
tmp_deps (frozenset[SimActionData | SimActionOperation])
deps (frozenset)
state (SimState | None)
- __init__(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]¶
- 参数:
ast (Base)
reg_deps (frozenset[SimActionData | SimActionOperation])
tmp_deps (frozenset[SimActionData | SimActionOperation])
deps (frozenset)
state (SimState | None)
-
reg_deps:
frozenset[SimActionData|SimActionOperation]¶
-
tmp_deps:
frozenset[SimActionData|SimActionOperation]¶
- property annotations: tuple[Annotation, ...]¶
- class angr.state_plugins.SimActionOperation(state, op, exprs, result)[源代码]¶
基类:
SimActionAn 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)[源代码]¶
基类:
objectA 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.
- 参数:
state (SimState)
var_type (VariableType)
- __init__(state, addr, var_type)[源代码]¶
- 参数:
state (SimState)
var_type (VariableType)
- property mem_untyped: SimMemView¶
- property mem: SimMemView¶
- property string: SimMemView¶
- property resolvable¶
- property resolved¶
- property concrete¶
- property deref: SimDebugVariable¶
- class angr.state_plugins.SimDebugVariablePlugin[源代码]¶
-
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_namebased on the currentstate.ip.- 返回类型:
- 参数:
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)[源代码]¶
基类:
objectA 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.
- class angr.state_plugins.SimFilesystem(files=None, pathsep=None, cwd=None, mountpoints=None)[源代码]¶
-
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.
- 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.memoThe 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 unlinks¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- insert(path, simfile)[源代码]¶
Insert a file into the filesystem. Returns whether the operation was successful.
- class angr.state_plugins.SimHeapBase(heap_base=None, heap_size=None)[源代码]¶
-
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
- 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.memoThe 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.SimHeapBrk(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseSimHeapBrk 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimHeapLibc(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseA 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
- class angr.state_plugins.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]¶
-
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_pluginwith nameheapin 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
- 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.memoThe 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.
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimHostFilesystem(host_path=None, **kwargs)[源代码]¶
-
Simulated mount that makes some piece from the host filesystem available to the guest.
- 参数:
- 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.memoThe 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[源代码]¶
-
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'¶
- 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
BPconstructor.- 返回:
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
BPconstructor.- 返回:
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimJavaVmClassloader(initialized_classes=None)[源代码]¶
-
JavaVM Classloader is used as an interface for resolving and initializing Java classes.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimLightRegisters(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.memoThe 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.SimMemView(ty=None, addr=None, state=None)[源代码]¶
-
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
derefproperty 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
.resolvedor.concrete..resolvedwill return bitvector values, while.concretewill 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 = valwill NOT work, you must says.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)
- 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.- 返回类型:
- 返回:
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property resolvable¶
- property resolved¶
- property concrete¶
- property deref: SimMemView¶
- class angr.state_plugins.SimMount[源代码]¶
-
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
- class angr.state_plugins.SimRegNameView[源代码]¶
-
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimSolver(solver=None, all_variables=None, temporal_tracked_variables=None, eternal_tracked_variables=None)[源代码]¶
-
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 throughsolver.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 throughsolver.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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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
- 返回类型:
- 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
- 返回类型:
- 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.
- class angr.state_plugins.SimStateCGC[源代码]¶
-
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¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.
- class angr.state_plugins.SimStateGlobals(backer=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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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)[源代码]¶
-
This class keeps track of historically-relevant information for paths.
- STRONGREF_STATE = True¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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.
- 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).
- 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
- class angr.state_plugins.SimStateJNIReferences(local_refs=None, global_refs=None)[源代码]¶
-
Management of the mapping between opaque JNI references and the corresponding Java objects.
- 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimStateLibc[源代码]¶
-
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]¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property errno¶
- class angr.state_plugins.SimStateLog(log=None)[源代码]¶
-
- property actions¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimStateLoopData(back_edge_trip_counts=None, header_trip_counts=None, current_loop=None)[源代码]¶
-
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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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[源代码]¶
基类:
objectThis 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¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimStatePreconstrainer(constrained_addrs=None)[源代码]¶
-
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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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 == valueto 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.
- class angr.state_plugins.SimStateScratch(scratch=None)[源代码]¶
-
Implements the scratch state plugin.
- property priv¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimSymbolizer[源代码]¶
-
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).
- 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.memoThe 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)[源代码]¶
-
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¶
- EMLINK = 31¶
- 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.memoThe 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¶
- 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.
modefrom open(2) is unsupported at present.
- 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)
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.SimUCManager(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.memoThe 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.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
- st_nlink¶
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.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)[源代码]¶
-
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property uc¶
- class angr.state_plugins.plugin.SimStatePlugin[源代码]¶
基类:
objectThis 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¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.inspect.BP(when='before', enabled=None, condition=None, action=None, **kwargs)[源代码]¶
基类:
objectA breakpoint.
- class angr.state_plugins.inspect.SimInspector[源代码]¶
-
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'¶
- 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
BPconstructor.- 返回:
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
BPconstructor.- 返回:
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- state: angr.SimState¶
- class angr.state_plugins.libc.SimStateLibc[源代码]¶
-
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]¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property errno¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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[源代码]¶
基类:
SimMountThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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)[源代码]¶
-
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¶
- EMLINK = 31¶
- 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.memoThe 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¶
- 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.
modefrom open(2) is unsupported at present.
- 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)
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.
- 返回类型:
- 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
- st_nlink¶
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)[源代码]¶
-
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.
- 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.memoThe 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 unlinks¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- insert(path, simfile)[源代码]¶
Insert a file into the filesystem. Returns whether the operation was successful.
- class angr.state_plugins.filesystem.SimMount[源代码]¶
-
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
- class angr.state_plugins.filesystem.SimConcreteFilesystem(pathsep='/')[源代码]¶
基类:
SimMountAbstract 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.filesystem.SimHostFilesystem(host_path=None, **kwargs)[源代码]¶
-
Simulated mount that makes some piece from the host filesystem available to the guest.
- 参数:
- 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.memoThe 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.solver.SimSolver(solver=None, all_variables=None, temporal_tracked_variables=None, eternal_tracked_variables=None)[源代码]¶
-
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 throughsolver.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 throughsolver.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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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
- 返回类型:
- 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
- 返回类型:
- 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.
- class angr.state_plugins.log.SimStateLog(log=None)[源代码]¶
-
- property actions¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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)[源代码]¶
-
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property current_function_address¶
Address of the current function.
- 返回:
the address of the function
- 返回类型:
- property current_stack_pointer¶
Get the value of the stack pointer.
- 返回:
Value of the stack pointer
- 返回类型:
- 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.
- 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.
- 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
- class angr.state_plugins.callstack.CallStackAction(callstack_hash, callstack_depth, action, callframe=None, ret_site_addr=None)[源代码]¶
基类:
objectUsed in callstack backtrace, which is a history of callstacks along a path, to record individual actions occurred each time the callstack is changed.
- class angr.state_plugins.light_registers.SimLightRegisters(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.memoThe 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.history.SimStateHistory(parent=None, clone=None)[源代码]¶
-
This class keeps track of historically-relevant information for paths.
- STRONGREF_STATE = True¶
- jump_guard: claripy.ast.BV | None¶
- jumpkind: str | None¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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.
- 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).
- 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
- state: angr.SimState¶
- class angr.state_plugins.gdb.GDB(omit_fp=False, adjust_stack=False)[源代码]¶
-
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 registersin 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.memoThe 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[源代码]¶
-
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¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.FormatInfoStrToInt(addr, func_name, str_arg_num, base, base_arg, allows_negative)[源代码]¶
基类:
FormatInfo
- class angr.state_plugins.trace_additions.FormatInfoIntToStr(addr, func_name, int_arg_num, str_dst_num, base, base_arg)[源代码]¶
基类:
FormatInfo
- class angr.state_plugins.trace_additions.FormatInfoDontConstrain(addr, func_name, check_symbolic_arg)[源代码]¶
基类:
FormatInfo
- class angr.state_plugins.trace_additions.ChallRespInfo[源代码]¶
-
This state plugin keeps track of the reads and writes to symbolic addresses
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.trace_additions.ZenPlugin(max_depth=13)[源代码]¶
-
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.globals.SimStateGlobals(backer=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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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)[源代码]¶
-
- 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.memoThe 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.scratch.SimStateScratch(scratch=None)[源代码]¶
-
Implements the scratch state plugin.
- property priv¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.preconstrainer.SimStatePreconstrainer(constrained_addrs=None)[源代码]¶
-
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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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 == valueto 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.
- class angr.state_plugins.unicorn_engine.MEM_PATCH[源代码]¶
基类:
Structurestruct mem_update_t
- address¶
Structure/Union member
- length¶
Structure/Union member
- next¶
Structure/Union member
- class angr.state_plugins.unicorn_engine.TRANSMIT_RECORD[源代码]¶
基类:
Structurestruct transmit_record_t
- count¶
Structure/Union member
- data¶
Structure/Union member
- fd¶
Structure/Union member
- class angr.state_plugins.unicorn_engine.TaintEntityEnum[源代码]¶
基类:
objecttaint_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[源代码]¶
基类:
Structurestruct 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[源代码]¶
基类:
Structurestruct register_value_t
- offset¶
Structure/Union member
- size¶
Structure/Union member
- value¶
Structure/Union member
- class angr.state_plugins.unicorn_engine.VEXStmtDetails[源代码]¶
基类:
Structurestruct 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[源代码]¶
基类:
Structurestruct 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[源代码]¶
基类:
objectenum 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}¶
- class angr.state_plugins.unicorn_engine.StopDetails[源代码]¶
基类:
Structurestruct 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[源代码]¶
基类:
objectenum simos_t
- SIMOS_CGC = 0¶
- SIMOS_LINUX = 1¶
- SIMOS_OTHER = 2¶
- 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)[源代码]¶
-
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property uc¶
- 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)[源代码]¶
-
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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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)[源代码]¶
-
JavaVM Classloader is used as an interface for resolving and initializing Java classes.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.jni_references.SimStateJNIReferences(local_refs=None, global_refs=None)[源代码]¶
-
Management of the mapping between opaque JNI references and the corresponding Java objects.
- 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.heap.PTChunk(base, sim_state, heap=None)[源代码]¶
基类:
ChunkA 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
- get_size()[源代码]¶
Returns the actual size of a chunk (as opposed to the entire size field, which may include some flags).
- 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).
- 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
- class angr.state_plugins.heap.PTChunkIterator(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]¶
基类:
object
- class angr.state_plugins.heap.SimHeapBase(heap_base=None, heap_size=None)[源代码]¶
-
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
- 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.memoThe 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.heap.SimHeapBrk(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseSimHeapBrk 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.heap.SimHeapLibc(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseA 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
- class angr.state_plugins.heap.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]¶
-
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_pluginwith nameheapin 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
- 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.memoThe 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.
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.heap.heap_base.SimHeapBase(heap_base=None, heap_size=None)[源代码]¶
-
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
- 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.memoThe 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.heap.heap_brk.SimHeapBrk(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseSimHeapBrk 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.heap.heap_freelist.Chunk(base, sim_state)[源代码]¶
基类:
objectThe 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
- get_size()[源代码]¶
Returns the actual size of a chunk (as opposed to the entire size field, which may include some flags).
- class angr.state_plugins.heap.heap_freelist.SimHeapFreelist(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapLibcA 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.
- class angr.state_plugins.heap.heap_libc.SimHeapLibc(heap_base=None, heap_size=None)[源代码]¶
基类:
SimHeapBaseA 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
- class angr.state_plugins.heap.heap_ptmalloc.PTChunk(base, sim_state, heap=None)[源代码]¶
基类:
ChunkA 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
- get_size()[源代码]¶
Returns the actual size of a chunk (as opposed to the entire size field, which may include some flags).
- 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).
- 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
- class angr.state_plugins.heap.heap_ptmalloc.PTChunkIterator(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]¶
基类:
object
- class angr.state_plugins.heap.heap_ptmalloc.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]¶
-
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_pluginwith nameheapin 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
- 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.memoThe 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.
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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[源代码]¶
-
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).
- 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.memoThe 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)[源代码]¶
基类:
objectA 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.
- 参数:
state (SimState)
var_type (VariableType)
- __init__(state, addr, var_type)[源代码]¶
- 参数:
state (SimState)
var_type (VariableType)
- property mem_untyped: SimMemView¶
- property mem: SimMemView¶
- property string: SimMemView¶
- property resolvable¶
- property resolved¶
- property concrete¶
- property deref: SimDebugVariable¶
- class angr.state_plugins.debug_variables.SimDebugVariablePlugin[源代码]¶
-
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_namebased on the currentstate.ip.- 返回类型:
- 参数:
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)[源代码]¶
-
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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.SimMemoryObject(obj, base, endness, length=None, byte_width=8)[源代码]¶
基类:
objectA 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.
- is_bytes¶
- base¶
- length¶
- endness¶
- property variables¶
- property symbolic¶
- property last_addr¶
- class angr.state_plugins.view.SimRegNameView[源代码]¶
-
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.state_plugins.view.SimMemView(ty=None, addr=None, state=None)[源代码]¶
-
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
derefproperty 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
.resolvedor.concrete..resolvedwill return bitvector values, while.concretewill 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 = valwill NOT work, you must says.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'
- 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.- 返回类型:
- 返回:
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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- property resolvable¶
- property resolved¶
- property concrete¶
- property deref: SimMemView¶
- 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)[源代码]¶
-
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
posargument, which may have different semantics per-class.0will 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
.posif 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
posmust 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¶
- 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.memoThe 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)[源代码]¶
-
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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.file.SimFileStream(name=None, content=None, pos=0, **kwargs)[源代码]¶
基类:
SimFileA 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
poson 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- class angr.storage.file.SimPackets(name, write_mode=None, content=None, writable=True, ident=None, **kwargs)[源代码]¶
基类:
SimFileBaseThe 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.
- property size¶
The number of data bytes stored by the file at present. May be a symbolic value.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.file.SimPacketsStream(name, pos=0, **kwargs)[源代码]¶
基类:
SimPacketsA 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
poson 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- class angr.storage.file.SimFileDescriptorBase[源代码]¶
-
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.
- 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)[源代码]¶
-
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
- 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.
- 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.file.SimFileDescriptorDuplex(read_file, write_file)[源代码]¶
-
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
- 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
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.file.SimPacketsSlots(name, read_sizes, ident=None, **kwargs)[源代码]¶
基类:
SimFileBaseSimPacketsSlots 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¶
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.memory_object.SimMemoryObject(obj, base, endness, length=None, byte_width=8)[源代码]¶
基类:
objectA 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.
- is_bytes¶
- base¶
- length¶
- endness¶
- property variables¶
- property symbolic¶
- property last_addr¶
- class angr.storage.memory_object.SimLabeledMemoryObject(obj, base, endness, length=None, byte_width=8, label=None)[源代码]¶
-
SimLabeledMemoryObject is a SimMemoryObject with a label
- 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 sliceoffset (
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-endianbw (
int) -- The byte width
- 返回类型:
- 返回:
The new bitvector
- class angr.concretization_strategies.SimConcretizationStrategy(filter=None, exact=True)[源代码]¶
基类:
objectConcretization 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.
- class angr.concretization_strategies.SimConcretizationStrategyAny(filter=None, exact=True)[源代码]¶
-
Concretization strategy that returns any single solution.
- class angr.concretization_strategies.SimConcretizationStrategyControlledData(limit, fixed_addrs, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
-
Concretization strategy that returns any non-zero solution.
- class angr.concretization_strategies.SimConcretizationStrategyNonzeroRange(limit, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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.
- class angr.concretization_strategies.SimConcretizationStrategyNorepeatsRange(repeat_expr, min=None, granularity=None, **kwargs)[源代码]¶
-
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.
- class angr.concretization_strategies.SimConcretizationStrategyRange(limit, **kwargs)[源代码]¶
-
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)[源代码]¶
-
Concretization strategy that ensures a single solution for an address.
- class angr.concretization_strategies.SimConcretizationStrategySolutions(limit, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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')[源代码]¶
基类:
MemoryMixinAbstractMergerMixin handles merging initialized values.
- class angr.storage.memory_mixins.ActionsMixinHigh(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.ActionsMixinLow(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin- store(addr, data, size=None, *, action=None, **kwargs)[源代码]¶
- 参数:
action (SimActionData | None)
- class angr.storage.memory_mixins.AddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]¶
基类:
MemoryMixinThe 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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.
- class angr.storage.memory_mixins.ClemoryBackerMixin(cle_memory_backer=None, **kwargs)[源代码]¶
-
- 参数:
cle_memory_backer (None | cle.Loader | cle.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.memoThe 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)[源代码]¶
-
- 参数:
cle_memory_backer (None | cle.Loader | cle.Clemory)
- class angr.storage.memory_mixins.ConditionalMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.ConvenientMappingsMixin(**kwargs)[源代码]¶
基类:
MemoryMixinImplements mappings between names and hashes of symbolic variables and these variables themselves.
- 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.memoThe 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.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')[源代码]¶
基类:
MemoryMixinNormalizes the data field for a store and the fallback field for a load to be BVs.
- class angr.storage.memory_mixins.DefaultFillerMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- 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)[源代码]¶
-
- 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.memoThe 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
- class angr.storage.memory_mixins.ExplicitFillerMixin(uninitialized_read_handler=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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- 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,MemoryMixinTracks the history of memory writes.
- 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.memoThe 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.ISPOMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinAn 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.
- class angr.storage.memory_mixins.InspectMixinHigh(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- 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)[源代码]¶
- 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)[源代码]¶
基类:
MemoryMixinA 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).
- property stack¶
- 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_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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.memory_mixins.KeyValueMemoryMixin(*args, **kwargs)[源代码]¶
基类:
MemoryMixinKeyValueMemoryMixin is a mixin that provides a simple key-value store for memory.
- 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.memoThe 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)[源代码]¶
基类:
MemoryMixinA memory mixin for merging labels. Labels come from SimLabeledMemoryObject.
- 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.memoThe 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,PagedMemoryMixinLabeledMemory 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,PageBaseThis class implements a page memory mixin with lists as the main content store.
- 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.memoThe 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.
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- class angr.storage.memory_mixins.ListPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]¶
- class angr.storage.memory_mixins.ListPagesWithLabelsMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]¶
- class angr.storage.memory_mixins.MVListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]¶
基类:
MemoryObjectSetMixin,PageBaseMVListPage 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.
- 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.memoThe 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)[源代码]¶
- 返回类型:
list[tuple[int,Union[SimMemoryObject,SimLabeledMemoryObject]]]
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
others (
list[MVListPage]) -- the other state plugins to merge withmerge_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)
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- compare(other, page_addr=None, memory=None, changed_offsets=None)[源代码]¶
- 返回类型:
- 参数:
other (MVListPage)
page_addr (int | None)
- changed_bytes(other, page_addr=None)[源代码]¶
- 参数:
other (MVListPage)
page_addr (int | None)
- class angr.storage.memory_mixins.MVListPagesMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]¶
-
- PAGE_TYPE¶
MVListPage的别名
- 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.memoThe 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)[源代码]¶
- 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- 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.memoThe 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¶
- 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)[源代码]¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- 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.memoThe 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')[源代码]¶
基类:
MemoryMixinThis mixin allows you to provide register names as load addresses, and will automatically translate this to an offset and size.
- class angr.storage.memory_mixins.PageBase(*args, **kwargs)[源代码]¶
基类:
HistoryTrackingMixin,RefcountMixin,CooperationBase,ISPOMixin,PermissionsMixin,MemoryMixinThis 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=selfbe 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.memoThe 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.
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- compare(other)[源代码]¶
- 返回类型:
- 参数:
other (PagedMemoryMixin)
- 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.
- 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')[源代码]¶
基类:
MemoryMixinImplement optimizations and fast accessors for the MultiValues-variant of Paged Memory.
- class angr.storage.memory_mixins.PermissionsMixin(permissions=None, **kwargs)[源代码]¶
基类:
MemoryMixinThis 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)
- 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.memoThe 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)[源代码]¶
-
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)[源代码]¶
基类:
MemoryMixinThis mixin adds a locked reference counter and methods to manipulate it, to facilitate copy-on-write optimizations.
- 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.memoThe 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.
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.
- 返回类型:
Call this function to indicate that this page has had a shared reference to it released
- 返回类型:
- class angr.storage.memory_mixins.RegionCategoryMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin- 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- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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)[源代码]¶
基类:
MemoryMixinRegioned 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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.
- 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.
- class angr.storage.memory_mixins.SimpleInterfaceMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.SimplificationMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- 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)[源代码]¶
基类:
MemoryMixinThis 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
- 参数:
- __init__(concretize_symbolic_write_size=False, max_concretize_count=256, max_symbolic_size=4194304, raise_memory_limit_error=False, size_limit=257, **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.memoThe 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.SizeNormalizationMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinProvides 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
- class angr.storage.memory_mixins.SlottedMemoryMixin(width=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- class angr.storage.memory_mixins.SmartFindMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinMemory mixin providing basic searching over concrete and symbolic data.
- class angr.storage.memory_mixins.SpecialFillerMixin(special_memory_filler=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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)[源代码]¶
-
This mixin adds automatic allocation for a stack region based on the stack_end and stack_size parameters.
- 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.memoThe 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.StaticFindMixin(memory_id=None, endness='Iend_BE')[源代码]¶
-
Implements data finding for abstract memory.
- class angr.storage.memory_mixins.SymbolicMergerMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.TopMergerMixin(*args, top_func=None, **kwargs)[源代码]¶
基类:
MemoryMixinA memory mixin for merging values in memory to TOP.
- 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.memoThe 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,PageBaseDefault page implementation
- SUPPORTS_CONCRETE_LOAD: bool = True¶
- 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.memoThe 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, endness=None, memory=None, page_addr=None, cooperate=False, **kwargs)[源代码]¶
- 参数:
data (int | SimMemoryObject)
size (int | 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- 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.
- class angr.storage.memory_mixins.UltraPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]¶
- class angr.storage.memory_mixins.UnderconstrainedMixin(*args, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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.UnwrapperMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinThis mixin processes SimActionObjects by passing on their .ast field.
- 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')[源代码]¶
基类:
MemoryMixinThis mixin allows you to provide register names as load addresses, and will automatically translate this to an offset and size.
- class angr.storage.memory_mixins.smart_find_mixin.SmartFindMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinMemory mixin providing basic searching over concrete and symbolic data.
- class angr.storage.memory_mixins.default_filler_mixin.DefaultFillerMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.default_filler_mixin.SpecialFillerMixin(special_memory_filler=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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- 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.memoThe 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')[源代码]¶
基类:
MemoryMixinNormalizes the data field for a store and the fallback field for a load to be BVs.
- class angr.storage.memory_mixins.hex_dumper_mixin.HexDumperMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin- 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- 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.memoThe 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.simple_interface_mixin.SimpleInterfaceMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.actions_mixin.ActionsMixinHigh(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.actions_mixin.ActionsMixinLow(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin- 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
- class angr.storage.memory_mixins.size_resolution_mixin.SizeNormalizationMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinProvides 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
- 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)[源代码]¶
基类:
MemoryMixinThis 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
- 参数:
- __init__(concretize_symbolic_write_size=False, max_concretize_count=256, max_symbolic_size=4194304, raise_memory_limit_error=False, size_limit=257, **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.memoThe 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.dirty_addrs_mixin.DirtyAddrsMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- 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)[源代码]¶
基类:
MemoryMixinThe 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.
- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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.
- class angr.storage.memory_mixins.clouseau_mixin.InspectMixinHigh(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.conditional_store_mixin.ConditionalMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin
- class angr.storage.memory_mixins.label_merger_mixin.LabelMergerMixin(*args, **kwargs)[源代码]¶
基类:
MemoryMixinA memory mixin for merging labels. Labels come from SimLabeledMemoryObject.
- 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.memoThe 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
- class angr.storage.memory_mixins.unwrapper_mixin.UnwrapperMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinThis mixin processes SimActionObjects by passing on their .ast field.
- 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)[源代码]¶
基类:
MemoryMixinImplements mappings between names and hashes of symbolic variables and these variables themselves.
- 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.memoThe 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.pages.mv_list_page.MVListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]¶
基类:
MemoryObjectSetMixin,PageBaseMVListPage 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.
- 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.memoThe 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)[源代码]¶
- 返回类型:
list[tuple[int,Union[SimMemoryObject,SimLabeledMemoryObject]]]
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
others (
list[MVListPage]) -- the other state plugins to merge withmerge_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)
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- compare(other, page_addr=None, memory=None, changed_offsets=None)[源代码]¶
- 返回类型:
- 参数:
other (MVListPage)
page_addr (int | None)
- changed_bytes(other, page_addr=None)[源代码]¶
- 参数:
other (MVListPage)
page_addr (int | None)
- 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.
- 参数:
- merge(mv)[源代码]¶
- 返回类型:
MultiValues[TypeVar(MVType, bound=BV|FP)]- 参数:
mv (MultiValues[MVType])
- extract(offset, length, endness)[源代码]¶
- 返回类型:
- 参数:
self (MultiValues[BV])
offset (int)
length (int)
endness (str)
- concat(other)[源代码]¶
- 返回类型:
- 参数:
self (MultiValues[BV])
other (MultiValues[BV] | BV | bytes)
- 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)[源代码]¶
基类:
MemoryMixinA memory mixin for merging values in memory to TOP.
- 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.memoThe 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.memoThe 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.memoThe 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.
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- compare(other)[源代码]¶
- 返回类型:
- 参数:
other (PagedMemoryMixin)
- 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.
- 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)[源代码]¶
- class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.ListPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]¶
- class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.MVListPagesMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]¶
-
- PAGE_TYPE¶
MVListPage的别名
- 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.memoThe 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)[源代码]¶
- class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.MVListPagesWithLabelsMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]¶
- class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.UltraPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]¶
- class angr.storage.memory_mixins.paged_memory.page_backer_mixins.NotMemoryview(obj, offset, size)[源代码]¶
基类:
object
- class angr.storage.memory_mixins.paged_memory.page_backer_mixins.ClemoryBackerMixin(cle_memory_backer=None, **kwargs)[源代码]¶
-
- 参数:
cle_memory_backer (None | cle.Loader | cle.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.memoThe 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)[源代码]¶
-
- 参数:
cle_memory_backer (None | cle.Loader | cle.Clemory)
- class angr.storage.memory_mixins.paged_memory.page_backer_mixins.DictBackerMixin(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.memoThe 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)[源代码]¶
-
This mixin adds automatic allocation for a stack region based on the stack_end and stack_size parameters.
- 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.memoThe 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.privileged_mixin.PrivilegedPagingMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]¶
-
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,MemoryMixinTracks the history of memory writes.
- 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.memoThe 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.pages.ISPOMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinAn 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.
- class angr.storage.memory_mixins.paged_memory.pages.ListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]¶
基类:
MemoryObjectMixin,PageBaseThis class implements a page memory mixin with lists as the main content store.
- 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.memoThe 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.
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- class angr.storage.memory_mixins.paged_memory.pages.MVListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]¶
基类:
MemoryObjectSetMixin,PageBaseMVListPage 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.
- 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.memoThe 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)[源代码]¶
- 返回类型:
list[tuple[int,Union[SimMemoryObject,SimLabeledMemoryObject]]]
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
others (
list[MVListPage]) -- the other state plugins to merge withmerge_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)
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- compare(other, page_addr=None, memory=None, changed_offsets=None)[源代码]¶
- 返回类型:
- 参数:
other (MVListPage)
page_addr (int | None)
- changed_bytes(other, page_addr=None)[源代码]¶
- 参数:
other (MVListPage)
page_addr (int | None)
- 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,MemoryMixinThis 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=selfbe 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)[源代码]¶
基类:
MemoryMixinThis 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)
- 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.memoThe 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)[源代码]¶
基类:
MemoryMixinThis mixin adds a locked reference counter and methods to manipulate it, to facilitate copy-on-write optimizations.
- 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.memoThe 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.
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.
- 返回类型:
Call this function to indicate that this page has had a shared reference to it released
- 返回类型:
- class angr.storage.memory_mixins.paged_memory.pages.UltraPage(memory=None, init_zero=False, **kwargs)[源代码]¶
基类:
MemoryObjectMixin,PageBaseDefault page implementation
- SUPPORTS_CONCRETE_LOAD: bool = True¶
- 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.memoThe 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, endness=None, memory=None, page_addr=None, cooperate=False, **kwargs)[源代码]¶
- 参数:
data (int | SimMemoryObject)
size (int | 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- 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.
- state: angr.SimState¶
- class angr.storage.memory_mixins.paged_memory.pages.refcount_mixin.RefcountMixin(**kwargs)[源代码]¶
基类:
MemoryMixinThis mixin adds a locked reference counter and methods to manipulate it, to facilitate copy-on-write optimizations.
- 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.memoThe 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.
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.
- 返回类型:
Call this function to indicate that this page has had a shared reference to it released
- 返回类型:
- class angr.storage.memory_mixins.paged_memory.pages.permissions_mixin.PermissionsMixin(permissions=None, **kwargs)[源代码]¶
基类:
MemoryMixinThis 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)
- 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.memoThe 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,MemoryMixinTracks the history of memory writes.
- 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.memoThe 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.pages.ispo_mixin.ISPOMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinAn 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.
- 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[源代码]¶
-
Uses sets of SimMemoryObjects in region storage.
- class angr.storage.memory_mixins.paged_memory.pages.cooperation.BasicClaripyCooperation[源代码]¶
-
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,PageBaseThis class implements a page memory mixin with lists as the main content store.
- 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.memoThe 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.
- 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
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- class angr.storage.memory_mixins.paged_memory.pages.ultra_page.UltraPage(memory=None, init_zero=False, **kwargs)[源代码]¶
基类:
MemoryObjectMixin,PageBaseDefault page implementation
- SUPPORTS_CONCRETE_LOAD: bool = True¶
- 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.memoThe 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, endness=None, memory=None, page_addr=None, cooperate=False, **kwargs)[源代码]¶
- 参数:
data (int | SimMemoryObject)
size (int | 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)- 参数:
- 返回:
True if the state plugins are actually merged.
- 返回类型:
- 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.
- state: angr.SimState¶
- class angr.storage.memory_mixins.regioned_memory.AbstractMergerMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinAbstractMergerMixin handles merging initialized values.
- class angr.storage.memory_mixins.regioned_memory.MemoryRegionMetaMixin(related_function_addr=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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¶
- 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)[源代码]¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.memory_mixins.regioned_memory.RegionCategoryMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixin- 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- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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)[源代码]¶
基类:
MemoryMixinRegioned 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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.
- 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.
- class angr.storage.memory_mixins.regioned_memory.StaticFindMixin(memory_id=None, endness='Iend_BE')[源代码]¶
-
Implements data finding for abstract memory.
- 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)[源代码]¶
基类:
MemoryMixinRegioned 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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.
- 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.
- class angr.storage.memory_mixins.regioned_memory.region_data.AddressWrapper(region, region_base_addr, address, is_on_stack, function_address)[源代码]¶
基类:
objectAddressWrapper is used in SimAbstractMemory, which provides extra meta information for an address (or a ValueSet object) that is normalized from an integer/BVV/StridedInterval.
- __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 regionaddress -- 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¶
- class angr.storage.memory_mixins.regioned_memory.region_data.RegionDescriptor(region_id, base_address, related_function_address=None)[源代码]¶
基类:
objectDescriptor for a memory region ID.
- region_id¶
- base_address¶
- class angr.storage.memory_mixins.regioned_memory.region_data.RegionMap(is_stack)[源代码]¶
基类:
objectMostly 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- 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')[源代码]¶
-
Implements data finding for abstract memory.
- class angr.storage.memory_mixins.regioned_memory.abstract_address_descriptor.AbstractAddressDescriptor[源代码]¶
基类:
objectAbstractAddressDescriptor 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.
- property cardinality¶
- class angr.storage.memory_mixins.regioned_memory.region_meta_mixin.Segment(offset, size=0)[源代码]¶
基类:
objectSegment represents a continuous memory region.
- 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)[源代码]¶
基类:
objectAbstractLocation represents a location in memory.
- property basicblock_key¶
- property statement_id¶
- property region¶
- property segments¶
- class angr.storage.memory_mixins.regioned_memory.region_meta_mixin.MemoryRegionMetaMixin(related_function_addr=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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¶
- 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)[源代码]¶
- 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- 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
mergeshould be followed.- 参数:
others -- the other state plugin
- 返回:
True if the state plugin is actually widened.
- 返回类型:
- class angr.storage.memory_mixins.regioned_memory.abstract_merger_mixin.AbstractMergerMixin(memory_id=None, endness='Iend_BE')[源代码]¶
基类:
MemoryMixinAbstractMergerMixin handles merging initialized values.
- class angr.storage.memory_mixins.regioned_memory.regioned_address_concretization_mixin.RegionedAddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
- class angr.storage.memory_mixins.slotted_memory.SlottedMemoryMixin(width=None, **kwargs)[源代码]¶
基类:
MemoryMixin- 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.memoThe 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
othersand n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, sayzip([self] + others, merge_conditions)When implementing this, make sure that you "deepen" both
othersandcommon_ancestorbefore 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 bullshitThere is a utility
claripy.ite_caseswhich will help with constructing arbitrarily large merged ASTs. Use it likeself.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.
- 返回类型:
Concretization Strategies¶
- class angr.concretization_strategies.single.SimConcretizationStrategySingle(filter=None, exact=True)[源代码]¶
-
Concretization strategy that ensures a single solution for an address.
- class angr.concretization_strategies.eval.SimConcretizationStrategyEval(limit, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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.
- class angr.concretization_strategies.solutions.SimConcretizationStrategySolutions(limit, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
-
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.
- class angr.concretization_strategies.nonzero.SimConcretizationStrategyNonzero(filter=None, exact=True)[源代码]¶
-
Concretization strategy that returns any non-zero solution.
- class angr.concretization_strategies.any.SimConcretizationStrategyAny(filter=None, exact=True)[源代码]¶
-
Concretization strategy that returns any single solution.
- class angr.concretization_strategies.controlled_data.SimConcretizationStrategyControlledData(limit, fixed_addrs, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
基类:
objectThe 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: seeangr.factory.AngrObjectFactory.The most important methods you should look at are
step,explore, anduse_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
errorelist. 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
unsatstash 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
completehook set will interact. By default, the builtin functionany.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
completehook set will interact. By default, the builtin functionany.
- 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)[源代码]¶
- 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=Trueto 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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
simgrand put them in their corresponding stashes in this manager. This will not modifysimgr.
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- class angr.sim_manager.ErrorRecord(state, error, traceback)[源代码]¶
基类:
objectA 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.
- class angr.state_hierarchy.StateHierarchy[源代码]¶
基类:
objectThe 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"
Exploration Techniques¶
- class angr.exploration_techniques.DFS(deferred_stash='deferred')[源代码]¶
-
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.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.Bucketizer[源代码]¶
-
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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.CallFunctionGoal(function, arguments)[源代码]¶
基类:
BaseGoalA 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¶
- 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.
- 返回类型:
- 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)[源代码]¶
-
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.
- class angr.exploration_techniques.DrillerCore(trace, fuzz_bitmap=None)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.ExecuteAddressGoal(addr)[源代码]¶
基类:
BaseGoalA goal that prioritizes states reaching (or are likely to reach) certain address in some specific steps.
- 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.
- 返回类型:
- class angr.exploration_techniques.ExplorationTechnique[源代码]¶
基类:
objectAn 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_techniquewith an instance of the technique.- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 withsimgr.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)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 withsimgr.completion_mode.- 参数:
simgr (angr.SimulationManager)
- class angr.exploration_techniques.LengthLimiter(max_length, drop=False)[源代码]¶
-
Length limiter on paths.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.LocalLoopSeer(bound=None, bound_reached=None, discard_stash='spinning')[源代码]¶
-
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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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)[源代码]¶
-
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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.ManualMergepoint(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
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.MemoryWatcher(min_memory=512, memory_stash='lowmem')[源代码]¶
-
Memory Watcher
- 参数:
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.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.Oppologist[源代码]¶
-
The Oppologist is an exploration technique that forces uncooperative code through qemu.
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.Slicecutor(annotated_cfg, force_taking_exit=False, force_sat=False)[源代码]¶
-
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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.StochasticSearch(start_state, restart_prob=0.0001)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.StubStasher[源代码]¶
-
Stash states that reach a stub SimProcedure.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.Suggestions[源代码]¶
-
An exploration technique which analyzes failure cases and logs suggestions for how to mitigate them in future analyses.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.TechniqueBuilder(setup=None, step_state=None, step=None, successors=None, filter=None, selector=None, complete=None)[源代码]¶
-
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.
- class angr.exploration_techniques.Threading(threads=8, local_stash='thread_local')[源代码]¶
-
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.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.Timeout(timeout=None)[源代码]¶
-
Timeout exploration technique that stops an active exploration if the run time exceeds a predefined timeout
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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)[源代码]¶
-
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)[源代码]¶
- 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 withsimgr.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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.UniqueSearch(similarity_func=None, deferred_stash='deferred')[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.Veritesting(**options)[源代码]¶
-
Enable veritesting. This technique, described in a paper[1] from CMU, attempts to address the problem of state explosions in loops by performing smart merging.
[1] https://users.ece.cmu.edu/~aavgerin/papers/veritesting-icse-2014.pdf
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.timeout.Timeout(timeout=None)[源代码]¶
-
Timeout exploration technique that stops an active exploration if the run time exceeds a predefined timeout
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.dfs.DFS(deferred_stash='deferred')[源代码]¶
-
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.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.explorer.Explorer(find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False)[源代码]¶
-
Search for up to "num_find" paths that satisfy condition "find", avoiding condition "avoid". Stashes found paths into "find_stash' and avoided paths into "avoid_stash".
The "find" and "avoid" parameters may be any of:
An address to find
A set or list of addresses to find
A function that takes a path and returns whether or not it matches.
If an angr CFG is passed in as the "cfg" parameter and "find" is either a number or a list or a set, then any paths which cannot possibly reach a success state without going through a failure state will be preemptively avoided.
If either the "find" or "avoid" parameter is a function returning a boolean, and a path triggers both conditions, it will be added to the find stash, unless "avoid_priority" is set to True.
- __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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 withsimgr.completion_mode.- 参数:
simgr (angr.SimulationManager)
- class angr.exploration_techniques.lengthlimiter.LengthLimiter(max_length, drop=False)[源代码]¶
-
Length limiter on paths.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.manual_mergepoint.ManualMergepoint(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
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.spiller.PickledStatesBase[源代码]¶
基类:
objectThe base class of pickled states
- class angr.exploration_techniques.spiller.PickledStatesList[源代码]¶
-
List-backed pickled state storage.
- class angr.exploration_techniques.spiller.PickledStatesDb(db_str='sqlite:///:memory:')[源代码]¶
-
Database-backed pickled state storage.
- 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)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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')[源代码]¶
-
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.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.veritesting.Veritesting(**options)[源代码]¶
-
Enable veritesting. This technique, described in a paper[1] from CMU, attempts to address the problem of state explosions in loops by performing smart merging.
[1] https://users.ece.cmu.edu/~aavgerin/papers/veritesting-icse-2014.pdf
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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)[源代码]¶
-
An error class to report tracing Tracing desyncronization error
- class angr.exploration_techniques.tracer.RepHook(mnemonic)[源代码]¶
基类:
objectHook rep movs/stos to speed up constraint solving TODO: This should be made an exploration technique later
- 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)[源代码]¶
-
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)[源代码]¶
- 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 withsimgr.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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.driller_core.DrillerCore(trace, fuzz_bitmap=None)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.slicecutor.Slicecutor(annotated_cfg, force_taking_exit=False, force_sat=False)[源代码]¶
-
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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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 callsimgr.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.
- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.director.BaseGoal(sort)[源代码]¶
基类:
object- REQUIRE_CFG_STATES = False¶
- check(cfg, state, peek_blocks)[源代码]¶
- 参数:
cfg (angr.analyses.CFGEmulated) -- An instance of CFGEmulated.
state (angr.SimState) -- The state to check.
peek_blocks (int) -- Number of blocks to peek ahead from the current point.
- 返回:
True if we can determine that this condition is definitely satisfiable if the path is taken, False otherwise.
- 返回类型:
- 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.
- 返回类型:
- class angr.exploration_techniques.director.ExecuteAddressGoal(addr)[源代码]¶
基类:
BaseGoalA goal that prioritizes states reaching (or are likely to reach) certain address in some specific steps.
- 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.
- 返回类型:
- class angr.exploration_techniques.director.CallFunctionGoal(function, arguments)[源代码]¶
基类:
BaseGoalA 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¶
- 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.
- 返回类型:
- 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)[源代码]¶
-
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.
- class angr.exploration_techniques.oppologist.Oppologist[源代码]¶
-
The Oppologist is an exploration technique that forces uncooperative code through qemu.
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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)[源代码]¶
-
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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.local_loop_seer.LocalLoopSeer(bound=None, bound_reached=None, discard_stash='spinning')[源代码]¶
-
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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- 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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.stochastic.StochasticSearch(start_state, restart_prob=0.0001)[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.unique.UniqueSearch(similarity_func=None, deferred_stash='deferred')[源代码]¶
-
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.tech_builder.TechniqueBuilder(setup=None, step_state=None, step=None, successors=None, filter=None, selector=None, complete=None)[源代码]¶
-
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.
- 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')[源代码]¶
-
Memory Watcher
- 参数:
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.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.exploration_techniques.bucketizer.Bucketizer[源代码]¶
-
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. callingproject.factory.successorsmanually) 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_funcin their step or run command, it will appear here.- 参数:
simgr (angr.SimulationManager)
state (angr.SimState)
- class angr.exploration_techniques.suggestions.Suggestions[源代码]¶
-
An exploration technique which analyzes failure cases and logs suggestions for how to mitigate them in future analyses.
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
Simulation Engines¶
- class angr.engines.HeavyVEXMixin(project)[源代码]¶
基类:
SuccessorsMixin,ClaripyDataMixin,SimStateStorageMixin,VEXMixin,VEXLifterExecution 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,ProcedureMixinA 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,SuccessorsMixinA 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[源代码]¶
基类:
objectA mixin for SimEngine which adds the
process_proceduremethod for calling a SimProcedure and adding its results to a SimSuccessors.
- 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)
- 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,ProcedureMixinA 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)[源代码]¶
-
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)
- 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.SimSuccessors(addr, initial_state)[源代码]¶
基类:
objectThis 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)[源代码]¶
- 参数:
addr (int | SootAddressDescriptor | None)
initial_state (SimState[int | SootAddressDescriptor, BV | SootAddressDescriptor] | None)
- 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,ProcedureMixinExecution engine based on Soot.
- 参数:
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.SuccessorsMixin(project)[源代码]¶
基类:
SimEngine[SimState[int|SootAddressDescriptor,BV|SootAddressDescriptor],SimSuccessors]A mixin for SimEngine which implements
processto perform common operations related to symbolic execution and dispatches to aprocess_successorsmethod to fill a SimSuccessors object with the results.- 参数:
project (angr.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
_processmethod 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
- 返回类型:
- 返回:
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)[源代码]¶
-
This mixin implements the superfastpath execution mode, which skips all but the last four instructions.
- class angr.engines.UberEngine(project)[源代码]¶
基类:
SimEngineFailure,SimEngineSyscall,HooksMixin,SimEngineUnicorn,SuperFastpathMixin,TrackActionsMixin,SimInspectMixin,HeavyResilienceMixin,SootMixin,HeavyVEXMixinThe 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)
- 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)
- class angr.engines.engine.SuccessorsMixin(project)[源代码]¶
基类:
SimEngine[SimState[int|SootAddressDescriptor,BV|SootAddressDescriptor],SimSuccessors]A mixin for SimEngine which implements
processto perform common operations related to symbolic execution and dispatches to aprocess_successorsmethod to fill a SimSuccessors object with the results.- 参数:
project (angr.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
_processmethod 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
- 返回类型:
- 返回:
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)[源代码]¶
基类:
objectThis 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)[源代码]¶
- 参数:
addr (int | SootAddressDescriptor | None)
initial_state (SimState[int | SootAddressDescriptor, BV | SootAddressDescriptor] | None)
- 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[源代码]¶
基类:
objectA mixin for SimEngine which adds the
process_proceduremethod for calling a SimProcedure and adding its results to a SimSuccessors.
- class angr.engines.procedure.ProcedureEngine(project)[源代码]¶
基类:
ProcedureMixin,SuccessorsMixinA 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,ProcedureMixinA 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,ProcedureMixinA 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)[源代码]¶
基类:
VEXMixinThis mixin provides methods that makes the vex engine process guest code using claripy ASTs as the data domain.
- class angr.engines.vex.HeavyVEXMixin(project)[源代码]¶
基类:
SuccessorsMixin,ClaripyDataMixin,SimStateStorageMixin,VEXMixin,VEXLifterExecution 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.SuperFastpathMixin(*args, **kwargs)[源代码]¶
-
This mixin implements the superfastpath execution mode, which skips all but the last four instructions.
- 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)[源代码]¶
-
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)[源代码]¶
- 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.soot.SootMixin(project)[源代码]¶
基类:
SuccessorsMixin,ProcedureMixinExecution engine based on Soot.
- 参数:
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.soot.engine.SootMixin(project)[源代码]¶
基类:
SuccessorsMixin,ProcedureMixinExecution engine based on Soot.
- 参数:
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.unicorn.SimEngineUnicorn(project)[源代码]¶
-
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)
- 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,PcodeEmulatorMixinExecution 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.
- 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 outkwargs -- 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)
- 返回类型:
- class angr.engines.pcode.engine.HeavyPcodeMixin(*args, **kwargs)[源代码]¶
基类:
SuccessorsMixin,PcodeLifterEngineMixin,PcodeEmulatorMixinExecution 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.
- 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 outkwargs -- 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)
- 返回类型:
- class angr.engines.pcode.lifter.ExitStatement(dst, jumpkind)[源代码]¶
基类:
objectThis class exists to ease compatibility with CFGFast's processing of exit_statements. See _scan_irsb method.
- class angr.engines.pcode.lifter.PcodeDisassemblerBlock(addr, insns, thumb, arch)[源代码]¶
-
Helper class to represent a block of disassembled target architecture instructions
- addr¶
- arch¶
- insns¶
- thumb¶
- class angr.engines.pcode.lifter.PcodeDisassemblerInsn(pcode_insn)[源代码]¶
-
Helper class to represent a disassembled target architecture instruction
- 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)[源代码]¶
基类:
objectIRSB 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 understatements (list of
IRStmt) -- The statements in this blocknext (
IRExpr) -- The expression for the default exit target of this blockoffsIP (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 lifteropt_level (
int) -- Unused by P-Code lifterstrict_block_end (
bool) -- Unused by P-Code lifterskip_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)[源代码]¶
- copy()[源代码]¶
Copy by creating an empty IRSB and then filling in the leftover attributes. Copy is made as deep as possible
- 返回类型:
- 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
- property tyenv¶
- property expressions¶
Return an iterator of all expressions contained in the IRSB.
- 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 disassembly: PcodeDisassemblerBlock¶
- class angr.engines.pcode.lifter.Lifter(arch, addr)[源代码]¶
基类:
objectA 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¶
- 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.
- 返回类型:
- 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 liftertraceflags (
int) -- Unused by P-Code lifterstrict_block_end (bool)
inner (bool)
skip_stmts (bool)
collect_data_refs (bool)
- 返回类型:
备注
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)[源代码]¶
基类:
objectLifts basic blocks to P-code
- 参数:
arch (archinfo.Arch)
-
behaviors:
BehaviorFactory¶
- class angr.engines.pcode.lifter.PcodeLifter(arch, addr)[源代码]¶
基类:
LifterHandles calling into pypcode to lift a block
- 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.
- 返回类型:
- 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)[源代码]¶
-
Lifter mixin to lift from machine code to P-Code.
- 参数:
- __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)[源代码]¶
- 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)
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.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 lifterstrict_block_end (
Optional[bool]) -- Unused by P-Code lifterload_from_ro_regions (
bool) -- Unused by P-Code lifterarch (Arch | 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)[源代码]¶
-
Mixin for p-code execution.
- angr.engines.pcode.behavior.make_bv_sizes_equal(bv1, bv2)[源代码]¶
Makes two BVs equal in length through sign extension.
- class angr.engines.pcode.behavior.OpBehavior(opcode, is_unary, is_special=False)[源代码]¶
基类:
objectBase class for all operation behaviors.
- class angr.engines.pcode.behavior.OpBehaviorCopy[源代码]¶
基类:
OpBehaviorBehavior for the COPY operation.
- class angr.engines.pcode.behavior.OpBehaviorEqual[源代码]¶
基类:
OpBehaviorBehavior for the INT_EQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorNotEqual[源代码]¶
基类:
OpBehaviorBehavior for the INT_NOTEQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSless[源代码]¶
基类:
OpBehaviorBehavior for the INT_SLESS operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSlessEqual[源代码]¶
基类:
OpBehaviorBehavior for the INT_SLESSEQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorIntLess[源代码]¶
基类:
OpBehaviorBehavior for the INT_LESS operation.
- class angr.engines.pcode.behavior.OpBehaviorIntLessEqual[源代码]¶
基类:
OpBehaviorBehavior for the INT_LESSEQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorIntZext[源代码]¶
基类:
OpBehaviorBehavior for the INT_ZEXT operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSext[源代码]¶
基类:
OpBehaviorBehavior for the INT_SEXT operation.
- class angr.engines.pcode.behavior.OpBehaviorIntAdd[源代码]¶
基类:
OpBehaviorBehavior for the INT_ADD operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSub[源代码]¶
基类:
OpBehaviorBehavior for the INT_SUB operation.
- class angr.engines.pcode.behavior.OpBehaviorIntCarry[源代码]¶
基类:
OpBehaviorBehavior for the INT_CARRY operation.
- class angr.engines.pcode.behavior.OpBehaviorIntScarry[源代码]¶
基类:
OpBehaviorBehavior for the INT_SCARRY operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSborrow[源代码]¶
基类:
OpBehaviorBehavior for the INT_SBORROW operation.
- class angr.engines.pcode.behavior.OpBehaviorInt2Comp[源代码]¶
基类:
OpBehaviorBehavior for the INT_2COMP operation.
- class angr.engines.pcode.behavior.OpBehaviorIntNegate[源代码]¶
基类:
OpBehaviorBehavior for the INT_NEGATE operation.
- class angr.engines.pcode.behavior.OpBehaviorIntXor[源代码]¶
基类:
OpBehaviorBehavior for the INT_XOR operation.
- class angr.engines.pcode.behavior.OpBehaviorIntAnd[源代码]¶
基类:
OpBehaviorBehavior for the INT_AND operation.
- class angr.engines.pcode.behavior.OpBehaviorIntOr[源代码]¶
基类:
OpBehaviorBehavior for the INT_OR operation.
- class angr.engines.pcode.behavior.OpBehaviorIntLeft[源代码]¶
基类:
OpBehaviorBehavior for the INT_LEFT operation.
- class angr.engines.pcode.behavior.OpBehaviorIntRight[源代码]¶
基类:
OpBehaviorBehavior for the INT_RIGHT operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSright[源代码]¶
基类:
OpBehaviorBehavior for the INT_SRIGHT operation.
- class angr.engines.pcode.behavior.OpBehaviorIntMult[源代码]¶
基类:
OpBehaviorBehavior for the INT_MULT operation.
- class angr.engines.pcode.behavior.OpBehaviorIntDiv[源代码]¶
基类:
OpBehaviorBehavior for the INT_DIV operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSdiv[源代码]¶
基类:
OpBehaviorBehavior for the INT_SDIV operation.
- class angr.engines.pcode.behavior.OpBehaviorIntRem[源代码]¶
基类:
OpBehaviorBehavior for the INT_REM operation.
- class angr.engines.pcode.behavior.OpBehaviorIntSrem[源代码]¶
基类:
OpBehaviorBehavior for the INT_SREM operation.
- class angr.engines.pcode.behavior.OpBehaviorBoolNegate[源代码]¶
基类:
OpBehaviorBehavior for the BOOL_NEGATE operation.
- class angr.engines.pcode.behavior.OpBehaviorBoolXor[源代码]¶
基类:
OpBehaviorBehavior for the BOOL_XOR operation.
- class angr.engines.pcode.behavior.OpBehaviorBoolAnd[源代码]¶
基类:
OpBehaviorBehavior for the BOOL_AND operation.
- class angr.engines.pcode.behavior.OpBehaviorBoolOr[源代码]¶
基类:
OpBehaviorBehavior for the BOOL_OR operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatEqual[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_EQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatNotEqual[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_NOTEQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatLess[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_LESS operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatLessEqual[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_LESSEQUAL operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatNan[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_NAN operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatAdd[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_ADD operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatDiv[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_DIV operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatMult[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_MULT operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatSub[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_SUB operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatNeg[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_NEG operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatAbs[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_ABS operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatSqrt[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_SQRT operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatInt2Float[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_INT2FLOAT operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatFloat2Float[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_FLOAT2FLOAT operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatTrunc[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_TRUNC operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatCeil[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_CEIL operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatFloor[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_FLOOR operation.
- class angr.engines.pcode.behavior.OpBehaviorFloatRound[源代码]¶
基类:
OpBehaviorBehavior for the FLOAT_ROUND operation.
- class angr.engines.pcode.behavior.OpBehaviorPiece[源代码]¶
基类:
OpBehaviorBehavior for the PIECE operation.
- class angr.engines.pcode.behavior.OpBehaviorSubpiece[源代码]¶
基类:
OpBehaviorBehavior for the SUBPIECE operation.
- class angr.engines.pcode.behavior.OpBehaviorPopcount[源代码]¶
基类:
OpBehaviorBehavior for the POPCOUNT operation.
- class angr.engines.pcode.behavior.OpBehaviorLzcount[源代码]¶
基类:
OpBehaviorBehavior for the LZCOUNT operation.
- class angr.engines.pcode.behavior.BehaviorFactory[源代码]¶
基类:
objectReturns the behavior object for a given opcode.
- class angr.engines.pcode.cc.SimCCM68k(arch)[源代码]¶
基类:
SimCCDefault 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)[源代码]¶
基类:
SimCCDefault 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)[源代码]¶
基类:
SimCCDefault 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)[源代码]¶
基类:
SimCCDefault 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)[源代码]¶
基类:
SimCCDefault 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)[源代码]¶
基类:
SimCCDefault 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>¶
Simulation Logging¶
- class angr.state_plugins.sim_action.SimAction(state, region_type)[源代码]¶
基类:
SimEventA 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¶
- class angr.state_plugins.sim_action.SimActionExit(state, target, condition=None, exit_type=None)[源代码]¶
基类:
SimActionAn 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)[源代码]¶
基类:
SimActionA 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)[源代码]¶
基类:
SimActionAn 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)[源代码]¶
基类:
SimActionA 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.
- property all_objects¶
- property is_symbolic¶
- property tmp_deps¶
- property reg_deps¶
- property storage¶
- class angr.state_plugins.sim_action_object.SimActionObject(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]¶
基类:
objectA SimActionObject tracks an AST and its dependencies.
- 参数:
ast (Base)
reg_deps (frozenset[SimActionData | SimActionOperation])
tmp_deps (frozenset[SimActionData | SimActionOperation])
deps (frozenset)
state (SimState | None)
- __init__(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]¶
- 参数:
ast (Base)
reg_deps (frozenset[SimActionData | SimActionOperation])
tmp_deps (frozenset[SimActionData | SimActionOperation])
deps (frozenset)
state (SimState | None)
-
reg_deps:
frozenset[SimActionData|SimActionOperation]¶
-
tmp_deps:
frozenset[SimActionData|SimActionOperation]¶
- property annotations: tuple[Annotation, ...]¶
- class angr.state_plugins.sim_event.SimEvent(state, event_type, **kwargs)[源代码]¶
基类:
objectA 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.
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)[源代码]¶
基类:
objectA SimProcedure is a wonderful object which describes a procedure to run on a state.
You may subclass SimProcedure and override
run(), replacing it with mutatingself.statehowever 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
project (Project)
cc (SimCC)
prototype (SimTypeFunction)
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.
- 参数:
project (Project)
cc (SimCC)
prototype (SimTypeFunction)
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
rundisplay_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
- 参数:
project (Project)
cc (SimCC)
prototype (SimTypeFunction)
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.
- 参数:
project (Project)
cc (SimCC)
prototype (SimTypeFunction)
- __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)[源代码]¶
-
prototype:
SimTypeFunction¶
-
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.
- NO_RET = False¶
- DYNAMIC_RET = False¶
- ADDS_EXITS = False¶
- IS_FUNCTION = True¶
- ARGS_MISMATCH = False¶
- ALT_NAMES = None¶
- 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).
- 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.
- 返回类型:
- 返回:
True if the call returns, False otherwise.
- property should_add_successors¶
- 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
- 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.
- property is_java¶
- property argument_types¶
- property return_type¶
- class angr.procedures.stubs.format_parser.FormatString(parser, components)[源代码]¶
基类:
objectDescribes 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)[源代码]¶
基类:
objectDescribes a format specifier within a format string.
- 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)[源代码]¶
基类:
SimProcedureFor SimProcedures relying on printf-style format strings.
- 参数:
project (Project)
cc (SimCC)
prototype (SimTypeFunction)
- 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']¶
- 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)[源代码]¶
基类:
FormatParserFor 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[源代码]¶
基类:
objectA type collection is the mechanism for describing types. Types in a type collection can be referenced using
- class angr.procedures.definitions.SimLibrary[源代码]¶
基类:
objectA 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.definitionspackage will be automatically picked up and added toangr.SIM_LIBRARIESvia 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.
- 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
.namefield 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.
- 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
ReturnUnconstrainedSimProcedure with the appropriate display name and metadata set. This will appear instate.history.descriptionsas<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.
- 返回类型:
- 返回:
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
- class angr.procedures.definitions.SimCppLibrary[源代码]¶
基类:
SimLibrarySimCppLibrary 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.
- 返回类型:
- 返回:
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
- class angr.procedures.definitions.SimSyscallLibrary[源代码]¶
基类:
SimLibrarySimSyscallLibrary 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.
- 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 stringproto (
SimTypeFunction) -- The prototype of the syscall as a SimTypeFunction
- 返回类型:
- 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
- 返回类型:
- 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.
- 参数:
- 返回类型:
- 返回:
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
- 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.
Calling Conventions and Types¶
- angr.calling_conventions.refine_locs_with_struct_type(arch, locs, arg_type, offset=0, treat_bot_as_int=True)[源代码]¶
- class angr.calling_conventions.SerializableCounter(start, stride, mapping=<function SerializableCounter.<lambda>>)[源代码]¶
- class angr.calling_conventions.SimFunctionArgument(size, is_fp=False)[源代码]¶
基类:
objectRepresent a generic function argument.
- 变量:
- 参数:
- class angr.calling_conventions.SimRegArg(reg_name, size, reg_offset=0, is_fp=False, clear_entire_reg=False)[源代码]¶
-
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)
- class angr.calling_conventions.SimStackArg(stack_offset, size, is_fp=False)[源代码]¶
-
Represents a function argument that has been passed on the stack.
- 变量:
- 参数:
- class angr.calling_conventions.SimComboArg(locations, is_fp=False)[源代码]¶
-
An argument which spans multiple storage locations. Locations should be given least-significant first.
- class angr.calling_conventions.SimStructArg(struct, locs)[源代码]¶
-
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
- 参数:
struct (SimStruct)
locs (dict[str, SimFunctionArgument])
- class angr.calling_conventions.SimArrayArg(locs)[源代码]¶
- class angr.calling_conventions.SimReferenceArgument(ptr_loc, main_loc)[源代码]¶
-
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)
- class angr.calling_conventions.ArgSession(cc)[源代码]¶
基类:
objectA class to keep track of the state accumulated in laying parameters out into memory
- cc¶
- fp_iter¶
- int_iter¶
- both_iter¶
- class angr.calling_conventions.UsercallArgSession(cc)[源代码]¶
基类:
objectAn argsession for use with SimCCUsercall
- cc¶
- real_args¶
- class angr.calling_conventions.SimCC(arch)[源代码]¶
基类:
objectA 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)
- STACKARG_SP_BUFF = 0¶
- STACKARG_SP_DIFF = 0¶
-
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)¶
基类:
objectA 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)
- 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)[源代码]¶
- 参数:
session (ArgSession)
arg_type (SimType)
- 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.
- 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)
- 返回类型:
- 返回:
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)[源代码]¶
基类:
SimRegArgA register that LIES about the types it holds
- class angr.calling_conventions.SimCCCdecl(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_DIFF = 4¶
-
RETURN_VAL:
SimFunctionArgument= <eax>¶
-
OVERFLOW_RETURN_VAL:
SimFunctionArgument|None= <edx>¶
-
FP_RETURN_VAL:
SimFunctionArgument|None= <st0>¶
-
RETURN_ADDR:
SimFunctionArgument= [0x0]¶
- STRUCT_RETURN_THRESHOLD = 32¶
- class angr.calling_conventions.SimCCMicrosoftCdecl(arch)[源代码]¶
基类:
SimCCCdecl- 参数:
arch (archinfo.Arch)
- STRUCT_RETURN_THRESHOLD = 64¶
- class angr.calling_conventions.SimCCStdcall(arch)[源代码]¶
-
- 参数:
arch (archinfo.Arch)
- CALLEE_CLEANUP = True¶
- class angr.calling_conventions.SimCCMicrosoftFastcall(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_DIFF = 4¶
-
RETURN_VAL:
SimFunctionArgument= <eax>¶
-
RETURN_ADDR:
SimFunctionArgument= [0x0]¶
- class angr.calling_conventions.SimCCMicrosoftAMD64(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- 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]¶
- STACK_ALIGNMENT = 16¶
- ArgSession¶
- STRUCT_RETURN_THRESHOLD = 64¶
- class angr.calling_conventions.SimCCSyscall(arch)[源代码]¶
基类:
SimCCThe base class of all syscall CCs.
- 参数:
arch (archinfo.Arch)
- SYSCALL_ERRNO_START = None¶
- class angr.calling_conventions.SimCCX86LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <eax>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- class angr.calling_conventions.SimCCX86WindowsSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <eax>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- class angr.calling_conventions.SimCCSystemVAMD64(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_DIFF = 8¶
-
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>¶
- STACK_ALIGNMENT = 16¶
- class angr.calling_conventions.SimCCAMD64LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <rax>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- class angr.calling_conventions.SimCCAMD64WindowsSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <rax>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- class angr.calling_conventions.SimCCARM(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
-
RETURN_ADDR:
SimFunctionArgument= <lr>¶
-
RETURN_VAL:
SimFunctionArgument= <r0>¶
-
OVERFLOW_RETURN_VAL:
SimFunctionArgument|None= <r1>¶
- class angr.calling_conventions.SimCCARMHF(arch)[源代码]¶
基类:
SimCCARM- 参数:
arch (archinfo.Arch)
-
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>¶
-
RETURN_ADDR:
SimFunctionArgument= <lr>¶
-
RETURN_VAL:
SimFunctionArgument= <r0>¶
- class angr.calling_conventions.SimCCARMLinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
-
RETURN_VAL:
SimFunctionArgument= <r0>¶
- class angr.calling_conventions.SimCCAArch64(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
-
RETURN_ADDR:
SimFunctionArgument= <lr>¶
-
RETURN_VAL:
SimFunctionArgument= <x0>¶
- ARCH¶
ArchAArch64的别名
- class angr.calling_conventions.SimCCAArch64LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <x0>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- ARCH¶
ArchAArch64的别名
- class angr.calling_conventions.SimCCRISCV64LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <a0>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- ARCH¶
ArchRISCV64的别名
- class angr.calling_conventions.SimCCO32(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_BUFF = 16¶
-
RETURN_ADDR:
SimFunctionArgument= <ra>¶
-
RETURN_VAL:
SimFunctionArgument= <v0>¶
-
OVERFLOW_RETURN_VAL:
SimFunctionArgument|None= <v1>¶
- ARCH¶
ArchMIPS32的别名
- class angr.calling_conventions.SimCCO32LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <v0>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- ARCH¶
ArchMIPS32的别名
- SYSCALL_ERRNO_START = -1133¶
- class angr.calling_conventions.SimCCN64(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_BUFF = 32¶
-
RETURN_ADDR:
SimFunctionArgument= <ra>¶
-
RETURN_VAL:
SimFunctionArgument= <v0>¶
- ARCH¶
ArchMIPS64的别名
- class angr.calling_conventions.SimCCN64LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <v0>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- ARCH¶
ArchMIPS64的别名
- SYSCALL_ERRNO_START = -1133¶
- class angr.calling_conventions.SimCCPowerPC(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_BUFF = 8¶
-
RETURN_ADDR:
SimFunctionArgument= <lr>¶
-
RETURN_VAL:
SimFunctionArgument= <r3>¶
-
OVERFLOW_RETURN_VAL:
SimFunctionArgument|None= <r4>¶
- class angr.calling_conventions.SimCCPowerPCLinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <r3>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- SYSCALL_ERRNO_START = -515¶
- class angr.calling_conventions.SimCCPowerPC64(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_BUFF = 112¶
-
RETURN_ADDR:
SimFunctionArgument= <lr>¶
-
RETURN_VAL:
SimFunctionArgument= <r3>¶
- class angr.calling_conventions.SimCCPowerPC64LinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <r3>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- SYSCALL_ERRNO_START = -515¶
- class angr.calling_conventions.SimCCSoot(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- 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)[源代码]¶
基类:
SimCCRepresent an unknown calling convention.
- 参数:
arch (archinfo.Arch)
- class angr.calling_conventions.SimCCS390X(arch)[源代码]¶
基类:
SimCC- 参数:
arch (archinfo.Arch)
- STACKARG_SP_BUFF = 160¶
-
RETURN_ADDR:
SimFunctionArgument= <r14>¶
-
RETURN_VAL:
SimFunctionArgument= <r2>¶
- class angr.calling_conventions.SimCCS390XLinuxSyscall(arch)[源代码]¶
基类:
SimCCSyscall- 参数:
arch (archinfo.Arch)
-
RETURN_VAL:
SimFunctionArgument= <r2>¶
-
RETURN_ADDR:
SimFunctionArgument= <ip_at_syscall>¶
- 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.
- 返回类型:
- 返回:
A default calling convention class if we can find one for the architecture, platform, and language combination, or the default if nothing fits.
- class angr.sim_variable.SimVariable(size, ident=None, name=None, region=None, category=None)[源代码]¶
基类:
Serializable- ident¶
- name¶
- renamed¶
- candidate_names¶
- size¶
- property is_function_argument¶
- class angr.sim_variable.SimConstantVariable(size, ident=None, value=None, region=None)[源代码]¶
基类:
SimVariable- value¶
- class angr.sim_variable.SimTemporaryVariable(tmp_id, size)[源代码]¶
基类:
SimVariable- tmp_id¶
- class angr.sim_variable.SimRegisterVariable(reg_offset, size, ident=None, name=None, region=None, category=None)[源代码]¶
基类:
SimVariable- reg¶
- property bits¶
- class angr.sim_variable.SimMemoryVariable(addr, size, ident=None, name=None, region=None, category=None)[源代码]¶
基类:
SimVariable- addr¶
- property bits¶
- class angr.sim_variable.SimStackVariable(offset, size, base='sp', base_addr=None, ident=None, name=None, region=None, category=None)[源代码]¶
-
- __init__(offset, size, base='sp', base_addr=None, ident=None, name=None, region=None, category=None)[源代码]¶
- base¶
- offset¶
- base_addr¶
- class angr.sim_variable.SimVariableSet[源代码]¶
基类:
MutableSetA collection of SimVariables.
- class angr.sim_type.SimType(label=None)[源代码]¶
基类:
objectSimType exists to track type information for SimProcedures.
- property alignment¶
The alignment of the type in bytes.
- class angr.sim_type.TypeRef(name, ty)[源代码]¶
基类:
SimTypeA 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.
- 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.
- class angr.sim_type.NamedTypeMixin(*args, name=None, **kwargs)[源代码]¶
基类:
objectSimType 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)
- class angr.sim_type.SimTypeBottom(label=None)[源代码]¶
基类:
SimTypeSimTypeBottom basically represents a type error.
- class angr.sim_type.SimTypeTop(size=None, label=None)[源代码]¶
基类:
SimTypeSimTypeTop represents any type (mostly used with a pointer for void*).
- 参数:
size (int | None)
- class angr.sim_type.SimTypeReg(size, label=None)[源代码]¶
基类:
SimTypeSimTypeReg is the base type for all types that are register-sized.
- 参数:
size (int | None)
- class angr.sim_type.SimTypeNum(size, signed=True, label=None)[源代码]¶
基类:
SimTypeSimTypeNum is a numeric type of arbitrary length
- 参数:
size (int)
- class angr.sim_type.SimTypeInt(signed=True, label=None)[源代码]¶
基类:
SimTypeRegSimTypeInt 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
- property size¶
The size of the type in bits, or None if no size is computable.
- 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)[源代码]¶
基类:
SimTypeIntThe base class for all fixed-size (i.e., the size stays the same on all platforms) integer types. Do not instantiate this class directly.
- class angr.sim_type.SimTypeChar(signed=True, label=None)[源代码]¶
基类:
SimTypeRegSimTypeChar is a type that specifies a character; this could be represented by a byte, but this is meant to be interpreted as a character.
- class angr.sim_type.SimTypeWideChar(signed=True, label=None)[源代码]¶
基类:
SimTypeRegSimTypeWideChar is a type that specifies a wide character (a UTF-16 character).
- class angr.sim_type.SimTypeBool(signed=True, label=None)[源代码]¶
基类:
SimTypeReg
- class angr.sim_type.SimTypeFd(label=None)[源代码]¶
基类:
SimTypeRegSimTypeFd is a type that specifies a file descriptor.
- property size¶
The size of the type in bits, or None if no size is computable.
- class angr.sim_type.SimTypePointer(pts_to, label=None, offset=0)[源代码]¶
基类:
SimTypeRegSimTypePointer 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.
- property size¶
The size of the type in bits, or None if no size is computable.
- class angr.sim_type.SimTypeReference(refs, label=None)[源代码]¶
基类:
SimTypeRegSimTypeReference 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.).
- property size¶
The size of the type in bits, or None if no size is computable.
- class angr.sim_type.SimTypeArray(elem_type, length=None, label=None)[源代码]¶
基类:
SimTypeSimTypeArray 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.
- 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.
- angr.sim_type.SimTypeFixedSizeArray¶
SimTypeArray的别名
- class angr.sim_type.SimTypeString(length=None, label=None, name=None)[源代码]¶
-
SimTypeString is a type that represents a C-style string, i.e. a NUL-terminated array of bytes.
- 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.
- class angr.sim_type.SimTypeWString(length=None, label=None, name=None)[源代码]¶
-
A wide-character null-terminated string, where each character is 2 bytes.
- 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.
- class angr.sim_type.SimTypeFunction(args, returnty, label=None, arg_names=None, variadic=False)[源代码]¶
基类:
SimTypeSimTypeFunction is a type that specifies an actual function (i.e. not a pointer) with certain types of arguments and a certain return value.
- property size¶
The size of the type in bits, or None if no size is computable.
- class angr.sim_type.SimTypeCppFunction(args, returnty, label=None, arg_names=None, ctor=False, dtor=False)[源代码]¶
-
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.
- 参数:
- class angr.sim_type.SimTypeLength(signed=False, addr=None, length=None, label=None)[源代码]¶
基类:
SimTypeLongSimTypeLength 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.
- class angr.sim_type.SimTypeFloat(size=32)[源代码]¶
基类:
SimTypeRegAn 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¶
- store(state, addr, value)[源代码]¶
- 参数:
value (StoreType | claripy.ast.FP)
- class angr.sim_type.SimTypeDouble(align_double=True)[源代码]¶
基类:
SimTypeFloatAn 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 alignment¶
The alignment of the type in bytes.
- class angr.sim_type.SimStruct(fields, name=None, pack=False, align=None, anonymous=False)[源代码]¶
-
- property packed¶
- 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.
- class angr.sim_type.SimStructValue(struct, values=None)[源代码]¶
基类:
objectA 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¶
- class angr.sim_type.SimUnion(members, name=None, label=None)[源代码]¶
-
- 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.
- class angr.sim_type.SimUnionValue(union, values=None)[源代码]¶
基类:
objectA SimStruct type paired with some real values
- 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¶
- class angr.sim_type.SimCppClassValue(class_type, values)[源代码]¶
-
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)
- class angr.sim_type.SimTypeNumOffset(size, signed=True, label=None, offset=0)[源代码]¶
基类:
SimTypeNumlike SimTypeNum, but supports an offset of 1 to 7 to a byte aligned address to allow structs with bitfields
- class angr.sim_type.SimTypeRef(name, original_type)[源代码]¶
基类:
SimTypeSimTypeRef is a to-be-resolved reference to another SimType.
SimTypeRef is not SimTypeReference.
- 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.
- 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')
- 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)[源代码]¶
基类:
objectCallable 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
Knowledge Base¶
Representing the artifacts of a project.
- class angr.knowledge_base.KnowledgeBase(project, obj=None, name=None)[源代码]¶
基类:
objectRepresents 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¶
- property callgraph¶
- property unresolved_indirect_jumps¶
- property resolved_indirect_jumps¶
- 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
-
functions:
- class angr.knowledge_plugins.CallsitePrototypes(kb)[源代码]¶
-
CallsitePrototypes manages callee prototypes at call sites.
- set_prototype(callsite_block_addr, cc, prototype, manual=False)[源代码]¶
- 返回类型:
- 参数:
callsite_block_addr (int)
cc (SimCC)
prototype (SimTypeFunction)
manual (bool)
- class angr.knowledge_plugins.Comments(kb)[源代码]¶
-
Tracks comments via a Dict of Address -> Text
- 参数:
kb (KnowledgeBase)
- class angr.knowledge_plugins.CustomStrings(kb)[源代码]¶
-
Store new strings that are recovered during various analysis. Each string has a unique ID associated.
- class angr.knowledge_plugins.Data(kb)[源代码]¶
-
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)
- class angr.knowledge_plugins.DebugVariableManager(kb)[源代码]¶
-
Structure to manage and access variables with different visibility scopes.
- 参数:
kb (KnowledgeBase)
- __init__(kb)[源代码]¶
- 参数:
kb (KnowledgeBase)
- from_name(var_name)[源代码]¶
Get the variable container for all variables named var_name
- 参数:
var_name (
str) -- name for a variable- 返回类型:
- add_variable_list(vlist, low_pc, high_pc)[源代码]¶
Add all variables in a list with the same visibility range
- 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)[源代码]¶
基类:
SerializableA representation of a function and various information about it.
- __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.
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¶
- 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¶
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 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_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.
- 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.
- 返回类型:
- 返回:
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.- 返回类型:
- 返回:
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.
- class angr.knowledge_plugins.FunctionManager(kb)[源代码]¶
基类:
KnowledgeBasePlugin,MappingThis is a function boundaries management tool. It takes in intermediate results during CFG generation, and manages a function map of the binary.
- 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.
- floor_func(addr)[源代码]¶
Return the function who has the greatest address that is less than or equal to addr.
- 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>
- 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
- class angr.knowledge_plugins.IndirectJumps(kb)[源代码]¶
-
This plugin tracks the targets of indirect jumps
- class angr.knowledge_plugins.KeyDefinitionManager(kb)[源代码]¶
-
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)
- class angr.knowledge_plugins.KnowledgeBasePlugin(kb)[源代码]¶
基类:
object- 参数:
kb (KnowledgeBase)
- __init__(kb)[源代码]¶
- 参数:
kb (KnowledgeBase)
- class angr.knowledge_plugins.Labels(kb)[源代码]¶
- class angr.knowledge_plugins.Obfuscations(kb)[源代码]¶
-
Store discovered information and artifacts about (string) obfuscation techniques in the project.
- class angr.knowledge_plugins.PatchManager(kb)[源代码]¶
-
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.
- get_all_patches(addr, size)[源代码]¶
Retrieve all patches that cover a region specified by [addr, addr+size).
- property patched_entry_state¶
- class angr.knowledge_plugins.PropagationManager(kb)[源代码]¶
-
Manages the results of Propagator, including intermediate results for unfinished Propagation runs.
- exists(prop_key)[源代码]¶
Internal function to check if a func, specified as a CodeLocation exists in our known propagations
- 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
- 返回类型:
- 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.
- 返回类型:
- 返回:
Dict or None
- class angr.knowledge_plugins.StructuredCodeManager(kb)[源代码]¶
-
A knowledge base plugin to store structured code generator results.
- class angr.knowledge_plugins.TypesStore(kb)[源代码]¶
基类:
KnowledgeBasePlugin,UserDictA kb plugin that stores a mapping from name to TypeRef. It will return types from angr.sim_type.ALL_TYPES as a default.
- class angr.knowledge_plugins.VariableManager(kb)[源代码]¶
-
Manage variables.
- 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.
- 返回类型:
- 返回:
All references to the variable.
- static convert_variable_list(vlist, manager)[源代码]¶
- 参数:
manager (VariableManagerInternal)
- load_from_dwarf(cu_list=None)[源代码]¶
- 参数:
cu_list (list[CompilationUnit] | None)
- class angr.knowledge_plugins.XRefManager(kb)[源代码]¶
基类:
KnowledgeBasePlugin,Serializable- 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.
- class angr.knowledge_plugins.patches.Patch(addr, new_bytes, comment=None)[源代码]¶
基类:
object- 参数:
comment (str | None)
- class angr.knowledge_plugins.patches.PatchManager(kb)[源代码]¶
-
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.
- get_all_patches(addr, size)[源代码]¶
Retrieve all patches that cover a region specified by [addr, addr+size).
- property patched_entry_state¶
- class angr.knowledge_plugins.plugin.KnowledgeBasePlugin(kb)[源代码]¶
基类:
object- 参数:
kb (KnowledgeBase)
- __init__(kb)[源代码]¶
- 参数:
kb (KnowledgeBase)
- class angr.knowledge_plugins.callsite_prototypes.CallsitePrototypes(kb)[源代码]¶
-
CallsitePrototypes manages callee prototypes at call sites.
- set_prototype(callsite_block_addr, cc, prototype, manual=False)[源代码]¶
- 返回类型:
- 参数:
callsite_block_addr (int)
cc (SimCC)
prototype (SimTypeFunction)
manual (bool)
- 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)[源代码]¶
基类:
CFGNodeThe 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¶
- class angr.knowledge_plugins.cfg.CFGModel(ident, cfg_manager=None, is_arm=False)[源代码]¶
基类:
SerializableThis class describes a Control Flow Graph for a specific range of code.
- 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
- remove_node(block_id, node)[源代码]¶
Remove the given CFGNode instance. Note that this method does not remove the node from the graph.
- 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.
- 返回类型:
- 返回:
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.
- get_all_nodes_intersecting_region(addr, size=1)[源代码]¶
Get all CFGNodes that intersect the given region.
- get_predecessors(cfgnode, excluding_fakeret=True, jumpkind=None)[源代码]¶
Get predecessors of a node in the control flow graph.
- 参数:
- 返回类型:
- 返回:
A list of predecessors
- get_successors(node, excluding_fakeret=True, jumpkind=None)[源代码]¶
Get successors of a node in the control flow graph.
- 参数:
- 返回:
A list of successors
- 返回类型:
- 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.
- 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.
- 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.
- 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.
- get_all_predecessors(cfgnode, depth_limit=None)[源代码]¶
Get all predecessors of a specific node on the control flow graph.
- get_all_successors(cfgnode, depth_limit=None)[源代码]¶
Get all successors of a specific node on the control flow graph.
- 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.
- 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.
- 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)[源代码]¶
基类:
SerializableThis 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¶
- is_syscall¶
- instruction_addrs¶
- irsb¶
- soot_block¶
- has_return¶
- property name¶
- property successors¶
- property predecessors¶
- 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
- 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- 参数:
- __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¶
- 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)[源代码]¶
基类:
SerializableMemoryData 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].
- 参数:
- property address¶
- fill_content(loader)[源代码]¶
Load data to fill self.content.
- 参数:
loader -- The project loader.
- 返回:
None
- 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)[源代码]¶
基类:
SerializableThis class describes a Control Flow Graph for a specific range of code.
- 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
- remove_node(block_id, node)[源代码]¶
Remove the given CFGNode instance. Note that this method does not remove the node from the graph.
- 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.
- 返回类型:
- 返回:
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.
- get_all_nodes_intersecting_region(addr, size=1)[源代码]¶
Get all CFGNodes that intersect the given region.
- get_predecessors(cfgnode, excluding_fakeret=True, jumpkind=None)[源代码]¶
Get predecessors of a node in the control flow graph.
- 参数:
- 返回类型:
- 返回:
A list of predecessors
- get_successors(node, excluding_fakeret=True, jumpkind=None)[源代码]¶
Get successors of a node in the control flow graph.
- 参数:
- 返回:
A list of successors
- 返回类型:
- 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.
- 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.
- 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.
- 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.
- get_all_predecessors(cfgnode, depth_limit=None)[源代码]¶
Get all predecessors of a specific node on the control flow graph.
- get_all_successors(cfgnode, depth_limit=None)[源代码]¶
Get all successors of a specific node on the control flow graph.
- 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.
- 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.
- 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)[源代码]¶
基类:
SerializableMemoryData 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].
- 参数:
- property address¶
- fill_content(loader)[源代码]¶
Load data to fill self.content.
- 参数:
loader -- The project loader.
- 返回:
None
- class angr.knowledge_plugins.cfg.cfg_manager.CFGManager(kb)[源代码]¶
-
This is the CFG manager, it manages CFGs
- class angr.knowledge_plugins.cfg.cfg_node.CFGNodeCreationFailure(exc_info=None, to_copy=None)[源代码]¶
基类:
objectThis class contains additional information for whenever creating a CFGNode failed. It includes a full traceback and the exception messages.
- 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)[源代码]¶
基类:
SerializableThis class stands for each single node in CFG.
- 参数:
addr (int | SootAddressDescriptor)
byte_string (bytes | None)
- __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¶
- is_syscall¶
- instruction_addrs¶
- irsb¶
- soot_block¶
- has_return¶
- property name¶
- property successors¶
- property predecessors¶
- 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
- 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)[源代码]¶
基类:
CFGNodeThe CFGNode that is used in CFGEmulated.
- 参数:
addr (int | SootAddressDescriptor)
byte_string (bytes | None)
- __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¶
- 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- 参数:
- __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¶
- 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,UserDictA kb plugin that stores a mapping from name to TypeRef. It will return types from angr.sim_type.ALL_TYPES as a default.
- class angr.knowledge_plugins.propagations.PropagationManager(kb)[源代码]¶
-
Manages the results of Propagator, including intermediate results for unfinished Propagation runs.
- exists(prop_key)[源代码]¶
Internal function to check if a func, specified as a CodeLocation exists in our known propagations
- 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
- 返回类型:
- 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.
- 返回类型:
- 返回:
Dict or None
- 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)[源代码]¶
基类:
SerializableThis class stores the propagation result that comes out of Propagator.
- 参数:
- __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¶
- class angr.knowledge_plugins.comments.Comments(kb)[源代码]¶
-
Tracks comments via a Dict of Address -> Text
- 参数:
kb (KnowledgeBase)
- class angr.knowledge_plugins.data.Data(kb)[源代码]¶
-
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)
- class angr.knowledge_plugins.indirect_jumps.IndirectJumps(kb)[源代码]¶
-
This plugin tracks the targets of indirect jumps
- class angr.knowledge_plugins.labels.Labels(kb)[源代码]¶
- 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)[源代码]¶
基类:
SerializableA representation of a function and various information about it.
- __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.
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¶
- 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¶
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 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_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.
- 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.
- 返回类型:
- 返回:
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.- 返回类型:
- 返回:
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.
- class angr.knowledge_plugins.functions.FunctionManager(kb)[源代码]¶
基类:
KnowledgeBasePlugin,MappingThis is a function boundaries management tool. It takes in intermediate results during CFG generation, and manages a function map of the binary.
- 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.
- floor_func(addr)[源代码]¶
Return the function who has the greatest address that is less than or equal to addr.
- 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>
- 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
- class angr.knowledge_plugins.functions.function_manager.FunctionDict(backref, *args, **kwargs)[源代码]¶
基类:
SortedDictFunctionDict 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
- class angr.knowledge_plugins.functions.function_manager.FunctionManager(kb)[源代码]¶
基类:
KnowledgeBasePlugin,MappingThis is a function boundaries management tool. It takes in intermediate results during CFG generation, and manages a function map of the binary.
- 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.
- floor_func(addr)[源代码]¶
Return the function who has the greatest address that is less than or equal to addr.
- 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>
- 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
- 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)[源代码]¶
基类:
SerializableA representation of a function and various information about it.
- __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.
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¶
- 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¶
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 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_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.
- 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.
- 返回类型:
- 返回:
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.- 返回类型:
- 返回:
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.
- class angr.knowledge_plugins.functions.function_parser.FunctionParser[源代码]¶
基类:
objectThe implementation of the serialization methods for the <Function> class.
- class angr.knowledge_plugins.functions.soot_function.SootFunction(function_manager, addr, name=None, syscall=None)[源代码]¶
基类:
FunctionA 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)[源代码]¶
-
Manage variables.
- 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.
- 返回类型:
- 返回:
All references to the variable.
- static convert_variable_list(vlist, manager)[源代码]¶
- 参数:
manager (VariableManagerInternal)
- load_from_dwarf(cu_list=None)[源代码]¶
- 参数:
cu_list (list[CompilationUnit] | None)
- class angr.knowledge_plugins.variables.VariableType[源代码]¶
基类:
objectDescribes variable types.
- REGISTER = 0¶
- MEMORY = 1¶
- class angr.knowledge_plugins.variables.variable_access.VariableAccessSort[源代码]¶
基类:
objectProvides 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)[源代码]¶
基类:
SerializableDescribes a variable access.
-
variable:
SimVariable¶
-
location:
CodeLocation¶
- 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.
- 参数:
cmsg -- The probobuf cmessage object.
variable_by_ident (dict[str, SimVariable] | None)
- 返回:
A unserialized class object.
- 返回类型:
cls
-
variable:
- class angr.knowledge_plugins.variables.variable_manager.VariableType[源代码]¶
基类:
objectDescribes variable types.
- REGISTER = 0¶
- MEMORY = 1¶
- class angr.knowledge_plugins.variables.variable_manager.LiveVariables(register_region, stack_region)[源代码]¶
基类:
objectA collection of live variables at a program point.
- register_region¶
- stack_region¶
- class angr.knowledge_plugins.variables.variable_manager.VariableManagerInternal(manager, func_addr=None)[源代码]¶
基类:
SerializableManage 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".
- 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
- add_variable(sort, start, variable)[源代码]¶
- 参数:
variable (SimVariable)
- set_variable(sort, start, variable)[源代码]¶
- 参数:
variable (SimVariable)
- record_variable(location, variable, offset, overwrite=False, atom=None)[源代码]¶
- 参数:
location (CodeLocation)
- remove_variable_by_atom(location, variable, atom)[源代码]¶
- 参数:
location (CodeLocation)
variable (SimVariable)
- 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.
- is_variable_used_at(variable, loc)[源代码]¶
- 返回类型:
- 参数:
variable (SimVariable)
- find_variables_by_atom(block_addr, stmt_idx, atom, block_idx=None)[源代码]¶
- 返回类型:
set[tuple[SimVariable,int]]- 参数:
block_idx (int | None)
- get_variable_accesses(variable, same_name=False)[源代码]¶
- 返回类型:
- 参数:
variable (SimVariable)
same_name (bool)
- 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.
- 返回类型:
- 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.
- 返回类型:
- get_variables_without_writes()[源代码]¶
Get all variables that have never been written to.
- 返回类型:
- 返回:
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.
- set_variable_type(var, ty, name=None, override_bot=True, all_unified=False, mark_manual=False)[源代码]¶
- unify_variables()[源代码]¶
Map SSA variables to a unified variable. Fill in self._unified_variables.
- 返回类型:
- set_unified_variable(variable, unified)[源代码]¶
Set the unified variable for a given SSA variable.
- 参数:
variable (
SimVariable) -- The SSA variable.unified (
SimVariable) -- The unified variable.
- 返回类型:
- 返回:
None
- unified_variable(variable)[源代码]¶
Return the unified variable for a given SSA variable,
- 参数:
variable (
SimVariable) -- The SSA variable.- 返回类型:
- 返回:
The unified variable, or None if there is no such SSA variable.
- class angr.knowledge_plugins.variables.variable_manager.VariableManager(kb)[源代码]¶
-
Manage variables.
- 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.
- 返回类型:
- 返回:
All references to the variable.
- static convert_variable_list(vlist, manager)[源代码]¶
- 参数:
manager (VariableManagerInternal)
- load_from_dwarf(cu_list=None)[源代码]¶
- 参数:
cu_list (list[CompilationUnit] | None)
- class angr.knowledge_plugins.debug_variables.DebugVariableContainer[源代码]¶
基类:
objectVariable tree for variables with same name to lock up which variable is visible at a given program counter address.
- class angr.knowledge_plugins.debug_variables.DebugVariable(low_pc, high_pc, cle_variable)[源代码]¶
-
- 变量:
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
- 参数:
- __init__(low_pc, high_pc, cle_variable)[源代码]¶
It is recommended to use DebugVariableManager.add_variable() instead
- contains(dvar)[源代码]¶
- 返回类型:
- 参数:
dvar (DebugVariable)
- test_unsupported_overlap(dvar)[源代码]¶
Test for an unsupported overlapping
- 参数:
dvar (
DebugVariable) -- Second DebugVariable to compare with- 返回类型:
- 返回:
True if there is an unsupported overlapping
- class angr.knowledge_plugins.debug_variables.DebugVariableManager(kb)[源代码]¶
-
Structure to manage and access variables with different visibility scopes.
- 参数:
kb (KnowledgeBase)
- __init__(kb)[源代码]¶
- 参数:
kb (KnowledgeBase)
- from_name(var_name)[源代码]¶
Get the variable container for all variables named var_name
- 参数:
var_name (
str) -- name for a variable- 返回类型:
- add_variable_list(vlist, low_pc, high_pc)[源代码]¶
Add all variables in a list with the same visibility range
- 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)[源代码]¶
-
A knowledge base plugin to store structured code generator results.
- 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.
- 参数:
atom (A)
codeloc (CodeLocation)
dummy (bool)
- __init__(atom, codeloc, dummy=False, tags=None)[源代码]¶
- 参数:
atom (A)
codeloc (CodeLocation)
dummy (bool)
-
codeloc:
CodeLocation¶
- tags¶
- class angr.knowledge_plugins.key_definitions.DerefSize(value)[源代码]¶
基类:
EnumAn 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)[源代码]¶
-
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)
- 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)[源代码]¶
基类:
objectA LiveDefinitions instance contains definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.
- 参数:
arch (archinfo.Arch)
track_tmps (bool)
merge_into_tops (bool)
- 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)[源代码]¶
- 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¶
- 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.
- 返回类型:
- 返回:
True if the expression is TOP, False otherwise.
- static extract_defs_from_annotations(annos)[源代码]¶
- 返回类型:
- 参数:
annos (Iterable[Annotation])
- static extract_defs_from_mv(mv)[源代码]¶
- 返回类型:
- 参数:
mv (MultiValues)
- merge(*others)[源代码]¶
- 返回类型:
- 参数:
others (LiveDefinitions)
- compare(other)[源代码]¶
- 返回类型:
- 参数:
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.
- kill_and_add_definition(atom, code_loc, data, dummy=False, tags=None, endness=None, annotated=False)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
data (MultiValues)
- add_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
expr (Any | None)
- add_use_by_def(definition, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
definition (Definition)
code_loc (CodeLocation)
expr (Any | None)
- get_definitions(thing)[源代码]¶
- 返回类型:
- 参数:
thing (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | MultiValues)
- 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)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
- get_one_value(spec, strip_annotations=False)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
strip_annotations (bool)
- add_register_use(reg_offset, size, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
reg_offset (int)
size (int)
code_loc (CodeLocation)
expr (Any | None)
- add_register_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_stack_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_stack_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_heap_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_heap_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_memory_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_memory_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_tmp_use(atom, code_loc)[源代码]¶
- 返回类型:
- 参数:
atom (Tmp)
code_loc (CodeLocation)
- add_tmp_use_by_def(def_, code_loc)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
- heap_address(offset)[源代码]¶
- 返回类型:
- 参数:
offset (int | HeapAddress)
- class angr.knowledge_plugins.key_definitions.ReachingDefinitionsModel(func_addr=None, track_liveness=True)[源代码]¶
基类:
objectModels the definitions, uses, and memory of a ReachingDefinitionState object
- add_def(d)[源代码]¶
- 返回类型:
- 参数:
d (Definition)
- kill_def(d)[源代码]¶
- 返回类型:
- 参数:
d (Definition)
- at_new_stmt(codeloc)[源代码]¶
- 返回类型:
- 参数:
codeloc (CodeLocation)
- at_new_block(code_loc, pred_codelocs)[源代码]¶
- 返回类型:
- 参数:
code_loc (CodeLocation)
pred_codelocs (list[CodeLocation])
- find_defs_at(code_loc, op=ObservationPointType.OP_BEFORE)[源代码]¶
- 返回类型:
- 参数:
code_loc (CodeLocation)
op (int)
- get_defs(atom, code_loc, op)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
op (int)
- merge(model)[源代码]¶
- 参数:
model (ReachingDefinitionsModel)
- get_observation_by_insn(ins_addr, kind)[源代码]¶
- 返回类型:
- 参数:
ins_addr (int | CodeLocation)
kind (ObservationPointType)
- get_observation_by_node(node_addr, kind, node_idx=None)[源代码]¶
- 返回类型:
- 参数:
node_addr (int | CodeLocation)
kind (ObservationPointType)
node_idx (int | None)
- class angr.knowledge_plugins.key_definitions.Uses(uses_by_definition=None, uses_by_location=None)[源代码]¶
基类:
objectDescribes uses (including the use location and the use expression) for definitions.
- 参数:
uses_by_definition (DefaultChainMapCOW | None)
uses_by_location (DefaultChainMapCOW | None)
- __init__(uses_by_definition=None, uses_by_location=None)[源代码]¶
- 参数:
uses_by_definition (DefaultChainMapCOW | None)
uses_by_location (DefaultChainMapCOW | 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.- 返回类型:
- 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
- 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.
- 参数:
codeloc (
CodeLocation) -- The code location.exprs (bool)
- 返回类型:
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.
- 参数:
- 返回类型:
set[Definition] |set[tuple[Definition,Optional[Any]]]- 返回:
A set of definitions that are used at the given location.
- class angr.knowledge_plugins.key_definitions.atoms.AtomKind(value)[源代码]¶
基类:
EnumAn 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)[源代码]¶
基类:
objectThis class represents a data storage location manipulated by IR instructions.
It could either be a Tmp (temporary variable), a Register, a MemoryLocation.
- size¶
- static from_ail_expr(expr, arch, full_reg=False)[源代码]¶
- 返回类型:
- 参数:
expr (Expression)
arch (Arch)
full_reg (bool)
- 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.
- 返回类型:
- 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.
- 返回类型:
- 返回:
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.
- 返回类型:
- 返回:
The Register Atom object.
- static mem(addr, size, endness=None)[源代码]¶
Create a MemoryLocation atom,
- 参数:
- 返回类型:
- 返回:
The MemoryLocation Atom object.
- static memory(addr, size, endness=None)¶
Create a MemoryLocation atom,
- 参数:
- 返回类型:
- 返回:
The MemoryLocation Atom object.
- class angr.knowledge_plugins.key_definitions.atoms.GuardUse(target)[源代码]¶
基类:
AtomImplements a guard use.
- target¶
- class angr.knowledge_plugins.key_definitions.atoms.ConstantSrc(value, size)[源代码]¶
基类:
AtomRepresents a constant.
- class angr.knowledge_plugins.key_definitions.atoms.Tmp(tmp_idx, size)[源代码]¶
基类:
AtomRepresents a variable used by the IR to store intermediate values.
- tmp_idx¶
- class angr.knowledge_plugins.key_definitions.atoms.Register(reg_offset, size, arch=None)[源代码]¶
基类:
AtomRepresents 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 (RegisterOffset | int)
size (int)
arch (Arch | None)
- __init__(reg_offset, size, arch=None)[源代码]¶
- 参数:
size (
int) -- The size of the atom in bytesreg_offset (RegisterOffset | int)
arch (Arch | None)
- reg_offset¶
- arch¶
- class angr.knowledge_plugins.key_definitions.atoms.VirtualVariable(varid, size, category, oident=None)[源代码]¶
基类:
AtomRepresents a virtual variable.
- 参数:
- __init__(varid, size, category, oident=None)[源代码]¶
- 参数:
size (
int) -- The size of the atom in bytesvarid (int)
category (VirtualVariableCategory)
- varid¶
- category¶
- oident¶
- class angr.knowledge_plugins.key_definitions.atoms.MemoryLocation(addr, size, endness=None)[源代码]¶
基类:
AtomRepresents a memory slice.
It is characterized by its address and its size.
- 参数:
addr (SpOffset | HeapAddress | int)
size (int)
endness (str | None)
- endness¶
- class angr.knowledge_plugins.key_definitions.constants.ObservationPointType(value)[源代码]¶
基类:
IntEnumEnum 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)[源代码]¶
基类:
objectA 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.
- 参数:
-
variable:
SimVariable|None= None¶
-
variable_manager:
Union[VariableManagerInternal,None,Literal[False]] = None¶
- static construct(predicate=None, **kwargs)[源代码]¶
- 返回类型:
- 参数:
predicate (DefinitionMatchPredicate | None)
- matches(defn)[源代码]¶
- 返回类型:
- 参数:
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)¶
- 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.
- 参数:
atom (A)
codeloc (CodeLocation)
dummy (bool)
- __init__(atom, codeloc, dummy=False, tags=None)[源代码]¶
- 参数:
atom (A)
codeloc (CodeLocation)
dummy (bool)
-
codeloc:
CodeLocation¶
- tags¶
- class angr.knowledge_plugins.key_definitions.environment.Environment(environment=None)[源代码]¶
基类:
objectRepresent 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)
- get(names)[源代码]¶
- 参数:
names (
set[str]) -- Potential values for the name of the environment variable to get the pointers of.- 返回类型:
- 返回:
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).
- merge(*others)[源代码]¶
- 返回类型:
- 参数:
others (Environment)
- compare(other)[源代码]¶
- 返回类型:
- 参数:
other (Environment)
- class angr.knowledge_plugins.key_definitions.heap_address.HeapAddress(value)[源代码]¶
基类:
objectThe representation of an address on the heap.
- property value¶
- class angr.knowledge_plugins.key_definitions.key_definition_manager.RDAObserverControl(func_addr, call_site_block_addrs, call_site_ins_addrs)[源代码]¶
基类:
object
- class angr.knowledge_plugins.key_definitions.key_definition_manager.KeyDefinitionManager(kb)[源代码]¶
-
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)
- class angr.knowledge_plugins.key_definitions.live_definitions.DerefSize(value)[源代码]¶
基类:
EnumAn 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)[源代码]¶
基类:
AnnotationAn annotation that attaches a Definition to an AST.
- 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)[源代码]¶
基类:
objectA LiveDefinitions instance contains definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.
- 参数:
arch (archinfo.Arch)
track_tmps (bool)
registers (MultiValuedMemory)
stack (MultiValuedMemory)
memory (MultiValuedMemory)
heap (MultiValuedMemory)
tmps (dict[int, set[Definition]])
others (dict[Atom, MultiValues])
tmp_uses (dict[int, set[CodeLocation]])
merge_into_tops (bool)
- 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)[源代码]¶
- 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¶
- 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.
- 返回类型:
- 返回:
True if the expression is TOP, False otherwise.
- static extract_defs_from_annotations(annos)[源代码]¶
- 返回类型:
- 参数:
annos (Iterable[Annotation])
- static extract_defs_from_mv(mv)[源代码]¶
- 返回类型:
- 参数:
mv (MultiValues)
- merge(*others)[源代码]¶
- 返回类型:
- 参数:
others (LiveDefinitions)
- compare(other)[源代码]¶
- 返回类型:
- 参数:
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.
- kill_and_add_definition(atom, code_loc, data, dummy=False, tags=None, endness=None, annotated=False)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
data (MultiValues)
- add_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
expr (Any | None)
- add_use_by_def(definition, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
definition (Definition)
code_loc (CodeLocation)
expr (Any | None)
- get_definitions(thing)[源代码]¶
- 返回类型:
- 参数:
thing (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | MultiValues)
- 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)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
- get_one_value(spec, strip_annotations=False)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
strip_annotations (bool)
- add_register_use(reg_offset, size, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
reg_offset (int)
size (int)
code_loc (CodeLocation)
expr (Any | None)
- add_register_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_stack_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_stack_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_heap_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_heap_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_memory_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_memory_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_tmp_use(atom, code_loc)[源代码]¶
- 返回类型:
- 参数:
atom (Tmp)
code_loc (CodeLocation)
- add_tmp_use_by_def(def_, code_loc)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
- heap_address(offset)[源代码]¶
- 返回类型:
- 参数:
offset (int | HeapAddress)
- class angr.knowledge_plugins.key_definitions.rd_model.ReachingDefinitionsModel(func_addr=None, track_liveness=True)[源代码]¶
基类:
objectModels the definitions, uses, and memory of a ReachingDefinitionState object
- add_def(d)[源代码]¶
- 返回类型:
- 参数:
d (Definition)
- kill_def(d)[源代码]¶
- 返回类型:
- 参数:
d (Definition)
- at_new_stmt(codeloc)[源代码]¶
- 返回类型:
- 参数:
codeloc (CodeLocation)
- at_new_block(code_loc, pred_codelocs)[源代码]¶
- 返回类型:
- 参数:
code_loc (CodeLocation)
pred_codelocs (list[CodeLocation])
- find_defs_at(code_loc, op=ObservationPointType.OP_BEFORE)[源代码]¶
- 返回类型:
- 参数:
code_loc (CodeLocation)
op (int)
- get_defs(atom, code_loc, op)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
op (int)
- merge(model)[源代码]¶
- 参数:
model (ReachingDefinitionsModel)
- get_observation_by_insn(ins_addr, kind)[源代码]¶
- 返回类型:
- 参数:
ins_addr (int | CodeLocation)
kind (ObservationPointType)
- get_observation_by_node(node_addr, kind, node_idx=None)[源代码]¶
- 返回类型:
- 参数:
node_addr (int | CodeLocation)
kind (ObservationPointType)
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)[源代码]¶
基类:
objectA tag for a Definition that can carry different kinds of metadata.
- 参数:
metadata (object)
- class angr.knowledge_plugins.key_definitions.tag.FunctionTag(function=None, metadata=None)[源代码]¶
基类:
TagA tag for a definition created (or used) in the context of a function.
- class angr.knowledge_plugins.key_definitions.tag.SideEffectTag(function=None, metadata=None)[源代码]¶
基类:
FunctionTagA 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)[源代码]¶
基类:
FunctionTagA tag for a definition of a parameter.
- class angr.knowledge_plugins.key_definitions.tag.LocalVariableTag(function=None, metadata=None)[源代码]¶
基类:
FunctionTagA tag for a definition of a local variable of a function.
- class angr.knowledge_plugins.key_definitions.tag.ReturnValueTag(function=None, metadata=None)[源代码]¶
基类:
FunctionTagA tag for a definition of a return value of a function.
- class angr.knowledge_plugins.key_definitions.tag.InitialValueTag(metadata=None)[源代码]¶
基类:
TagA tag for a definition of an initial value
- 参数:
metadata (object)
- class angr.knowledge_plugins.key_definitions.tag.UnknownSizeTag(metadata=None)[源代码]¶
基类:
TagA tag for a definition of an initial value
- 参数:
metadata (object)
- class angr.knowledge_plugins.key_definitions.undefined.Undefined[源代码]¶
基类:
objectA 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[源代码]¶
基类:
objectA 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)[源代码]¶
基类:
objectDescribes uses (including the use location and the use expression) for definitions.
- 参数:
uses_by_definition (DefaultChainMapCOW | None)
uses_by_location (DefaultChainMapCOW | None)
- __init__(uses_by_definition=None, uses_by_location=None)[源代码]¶
- 参数:
uses_by_definition (DefaultChainMapCOW | None)
uses_by_location (DefaultChainMapCOW | 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.- 返回类型:
- 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
- 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.
- 参数:
codeloc (
CodeLocation) -- The code location.exprs (bool)
- 返回类型:
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.
- 参数:
- 返回类型:
set[Definition] |set[tuple[Definition,Optional[Any]]]- 返回:
A set of definitions that are used at the given location.
- 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)[源代码]¶
基类:
SerializableXRef describes a reference to a MemoryData instance (if a MemoryData instance is available) or just an address.
- 参数:
- __init__(ins_addr=None, block_addr=None, stmt_idx=None, insn_op_idx=None, memory_data=None, dst=None, xref_type=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
- insn_op_type¶
- class angr.knowledge_plugins.xrefs.XRefManager(kb)[源代码]¶
基类:
KnowledgeBasePlugin,Serializable- 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.
- 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)[源代码]¶
基类:
SerializableXRef describes a reference to a MemoryData instance (if a MemoryData instance is available) or just an address.
- 参数:
- __init__(ins_addr=None, block_addr=None, stmt_idx=None, insn_op_idx=None, memory_data=None, dst=None, xref_type=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
- insn_op_type¶
- class angr.knowledge_plugins.xrefs.xref_types.XRefType[源代码]¶
基类:
object- Offset = 0¶
- Read = 1¶
- Write = 2¶
- class angr.knowledge_plugins.xrefs.xref_manager.XRefManager(kb)[源代码]¶
基类:
KnowledgeBasePlugin,Serializable- 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.
- class angr.code_location.CodeLocation(block_addr, stmt_idx, sim_procedure=None, ins_addr=None, context=None, block_idx=None, **kwargs)[源代码]¶
基类:
objectStands for a specific program point by specifying basic block address and statement ID (for IRSBs), or SimProcedure name (for SimProcedures).
- 参数:
- __init__(block_addr, stmt_idx, sim_procedure=None, ins_addr=None, context=None, block_idx=None, **kwargs)[源代码]¶
Constructor.
- 参数:
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.
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)
- sim_procedure¶
- property short_repr¶
- class angr.code_location.ExternalCodeLocation(call_string=None)[源代码]¶
基类:
CodeLocationStands 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.
- __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¶
- class angr.keyed_region.StoredObject(start, obj, size)[源代码]¶
基类:
object- start¶
- obj¶
-
size:
UnknownSize|int¶
- property obj_id¶
- class angr.keyed_region.RegionObject(start, size, objects=None)[源代码]¶
基类:
objectRepresents one or more objects occupying one or more bytes in KeyedRegion.
- start¶
- size¶
- stored_objects¶
- property is_empty¶
- property end¶
- property internal_objects¶
- class angr.keyed_region.KeyedRegion(tree=None, phi_node_contains=None, canonical_size=8)[源代码]¶
基类:
objectKeyedRegion 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.
- 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.
- 参数:
start (int)
variable (SimVariable)
- 返回:
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.
- 参数:
start (int)
variable (SimVariable)
- 返回:
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.
Serialization¶
- class angr.serializable.Serializable[源代码]¶
基类:
objectThe 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
- class angr.vaults.VaultPickler(vault, file, *args, assigned_objects=(), **kwargs)[源代码]¶
基类:
Pickler
- class angr.vaults.Vault[源代码]¶
-
The vault is a serializer for angr.
- class angr.vaults.VaultShelf(path=None)[源代码]¶
基类:
VaultDictA Vault that uses a shelve.Shelf for storage.
Analysis¶
- class angr.analyses.CDG(cfg, start=None, no_construct=False)[源代码]¶
基类:
AnalysisImplements 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¶
- class angr.analyses.CFG(**kwargs)[源代码]¶
基类:
CFGFasttl;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)[源代码]¶
基类:
AnalysisThis 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¶
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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],AnalysisThis 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}.
- 参数:
cfg (CFGEmulated | None)
context_sensitivity_level (int)
start (int | None)
function_start (int | None)
interfunction_level (int)
initial_state (SimState | None)
timeout (int | None)
max_iterations_before_widening (int)
max_iterations (int)
widening_interval (int)
final_state_callback (Callable[[SimState, CallStack], Any] | None)
record_function_final_states (bool)
- __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 beinitial_state (
Optional[SimState]) -- A state to use as the initial oneremove_options (
Optional[set[str]]) -- State options to remove from the initial state. It only works when initial_state is Nonetimeout (int)
final_state_callback (
Optional[Callable[[SimState,CallStack],Any]]) -- callback function when countering final statestatus_callback (
Optional[Callable[[VFG],Any]]) -- callback function used in _analysis_core_baremetalstart (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¶
- class angr.analyses.VSA_DDG(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)[源代码]¶
基类:
AnalysisA 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".
- class angr.analyses.AnalysesHub(project)[源代码]¶
基类:
PluginVendor[A]This class contains functions for all the registered and runnable analyses,
- reload_analyses(**kwargs)¶
- class angr.analyses.Analysis[源代码]¶
基类:
objectThis 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.
-
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)[源代码]¶
基类:
AnalysisRepresents 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.
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)[源代码]¶
基类:
AnalysisThis 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¶
- class angr.analyses.BinaryOptimizer(cfg, techniques)[源代码]¶
基类:
AnalysisThis 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¶
- class angr.analyses.BoyScout(cookiesize=1)[源代码]¶
基类:
AnalysisTry to determine the architecture and endieness of a binary blob
- class angr.analyses.CFGArchOptions(arch, **options)[源代码]¶
基类:
objectStores 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)[源代码]¶
-
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.
- 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.
- 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.
- immediate_postdominators(end, target_graph=None)[源代码]¶
Get all immediate postdominators of sub graph from given node upwards.
- 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.
- 返回类型:
- 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
- 返回类型:
- 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],CFGBaseWe 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.
- 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:
- 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
- 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.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)[源代码]¶
基类:
AnalysisAnalyze 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.
- 参数:
- class angr.analyses.ClassIdentifier[源代码]¶
基类:
AnalysisThis 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
- class angr.analyses.CodeCaveAnalysis[源代码]¶
基类:
AnalysisBest-effort static location of potential vacant code caves for possible code injection: - Padding functions - Unreachable code
- codecaves: list[CodeCave]¶
- 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)[源代码]¶
基类:
AnalysisImplements 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.cc_callback (Callable | None)
skip_other_funcs (bool)
auto_start (bool)
- prioritize_functions(func_addrs_to_prioritize)[源代码]¶
Prioritize the analysis of specified functions.
- 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.
- 返回类型:
- class angr.analyses.CongruencyCheck(throw=False)[源代码]¶
基类:
AnalysisThis 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.
- class angr.analyses.DataDependencyGraphAnalysis(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]¶
基类:
AnalysisThis 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 SimActionDatastart_from (
Optional[int]) -- An address or None, Specifies where to start generation of DDGend_at (
Optional[int]) -- An address or None, Specifies where to end generation of DDGblock_addrs (list[int] | None) -- List of block addresses that the DDG analysis should be run on
block_addrs
- 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)[源代码]¶
基类:
AnalysisThe 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
- 参数:
- __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)[源代码]¶
- 参数:
preset (str | DecompilationPreset | None)
peephole_optimizations (Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]] | None)
update_memory_data (bool)
generate_code (bool)
use_cache (bool)
expr_collapse_depth (int)
- 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.
- find_data_references_and_update_memory_data(seq_node)[源代码]¶
- 参数:
seq_node (SequenceNode)
- class angr.analyses.Disassembly(function=None, ranges=None, thumb=False, include_ir=False, block_bytes=None)[源代码]¶
基类:
AnalysisProduce formatted machine code disassembly.
- 参数:
- class angr.analyses.DominanceFrontier(func, func_graph=None, entry=None, exception_edges=False)[源代码]¶
基类:
AnalysisComputes the dominance frontier of all nodes in a function graph, and provides an easy-to-use interface for querying the frontier information.
- class angr.analyses.FactCollector(func, max_depth=5)[源代码]¶
基类:
AnalysisAn extremely fast analysis that extracts necessary facts of a function for CallingConventionAnalysis to make decision on the calling convention and prototype of a function.
- class angr.analyses.FastConstantPropagation(func, blocks=None, vex_cross_insn_opt=False, load_callback=None)[源代码]¶
基类:
AnalysisAn extremely fast constant propagation analysis that finds function-wide constant values with potentially high false negative rates.
- 参数:
- class angr.analyses.FlirtAnalysis(sig=None)[源代码]¶
基类:
AnalysisFlirtAnalysis 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.
- 参数:
status_callback (Callable[[type[ForwardAnalysis]], Any] | None)
graph_visitor (GraphVisitor[NodeType] | None)
- __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¶
- class angr.analyses.Identifier(cfg=None, require_predecessors=True, only_find=None)[源代码]¶
基类:
Analysis- 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
- class angr.analyses.InitializationFinder(func=None, func_graph=None, block=None, max_iterations=1, replacements=None, overlay=None, pointers_only=False)[源代码]¶
-
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)[源代码]¶
基类:
AnalysisExtracts all the loops from all the functions in a binary.
- class angr.analyses.PackingDetector(cfg=None, region_size_threshold=32)[源代码]¶
基类:
AnalysisThis 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¶
- class angr.analyses.PatchFinderAnalysis[源代码]¶
基类:
AnalysisLooks for binary patches using some basic heuristics: - Looking for interleaved functions - Looking for unaligned functions
- atypical_alignments: list[Function]¶
- possibly_patched_out: list[PatchedOutFunctionality]¶
- class angr.analyses.Pathfinder(start_state, goal_addr, cfg, cache_size=10000)[源代码]¶
基类:
Analysis
- 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)[源代码]¶
-
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
- 参数:
- __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)[源代码]¶
基类:
AnalysisGenerate a proximity graph.
- 参数:
func (Function)
cfg_model (CFGModel)
xrefs (XRefManager)
decompilation (Decompiler | None)
- __init__(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]¶
- 参数:
func (Function)
cfg_model (CFGModel)
xrefs (XRefManager)
decompilation (Decompiler | 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],AnalysisReachingDefinitionsAnalysis 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.
- 参数:
subject (Subject | ailment.Block | Block | Function | str)
observation_points (Iterable[ObservationPoint] | None)
init_state (ReachingDefinitionsState)
state_initializer (RDAStateInitializer | None)
function_handler (FunctionHandler | None)
interfunction_level (int)
track_liveness (bool)
func_addr (int | None)
element_limit (int)
merge_into_tops (bool)
- __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 blockfunc_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 all_definitions¶
- property all_uses¶
- property one_result¶
- property visited_blocks¶
- get_reaching_definitions(**kwargs)¶
- 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.
- 返回类型:
- insn_observe(insn_addr, stmt, block, state, op_type)[源代码]¶
- 参数:
insn_addr (
int) -- Address of the instruction.state (
ReachingDefinitionsState) -- The abstract analysis state.op_type (
ObservationPointType) -- Type of the observation point. Must be one of the following: OP_BEORE, OP_AFTER.
- 返回类型:
- stmt_observe(stmt_idx, stmt, block, state, op_type)[源代码]¶
- 参数:
stmt_idx (
int)state (
ReachingDefinitionsState)op_type (
ObservationPointType)
- 返回类型:
- 返回:
- property subject¶
- class angr.analyses.Reassembler(syntax='intel', remove_cgc_attachments=True, log_relocations=True)[源代码]¶
基类:
AnalysisHigh-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.
- property instructions¶
Get a list of all instructions in the binary
- 返回:
A list of (address, instruction)
- 返回类型:
- 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.
- 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.
- 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.
- 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.
- append_data(name, initial_content, size, readonly=False, sort='unknown')[源代码]¶
Append a new data entry into the binary with specific name, content, and size.
- remove_cgc_attachments()[源代码]¶
Remove CGC attachments.
- 返回:
True if CGC attachments are found and removed, False otherwise
- 返回类型:
- class angr.analyses.SLivenessAnalysis(func, func_graph=None, entry=None, func_addr=None, arg_vvars=None)[源代码]¶
基类:
AnalysisCalculates LiveIn and LiveOut sets for each block in a partial-SSA function.
- 参数:
func_addr (int | None)
arg_vvars (list[VirtualVariable] | None)
- __init__(func, func_graph=None, entry=None, func_addr=None, arg_vvars=None)[源代码]¶
- 参数:
func_addr (int | None)
arg_vvars (list[VirtualVariable] | None)
- class angr.analyses.SPropagatorAnalysis(subject, func_graph=None, only_consts=True, stack_pointer_tracker=None, func_args=None, func_addr=None)[源代码]¶
基类:
AnalysisConstant 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)[源代码]¶
- 返回类型:
- 参数:
varid (int)
gv_addr (int)
gv_size (int)
defloc (CodeLocation)
useloc (CodeLocation)
- class angr.analyses.SReachingDefinitionsAnalysis(subject, func_addr=None, func_graph=None, func_args=None, track_tmps=False)[源代码]¶
基类:
AnalysisConstant and expression propagation that only supports SSA AIL graphs.
- 参数:
func_addr (int | None)
func_graph (networkx.DiGraph[Block] | None)
func_args (set[VirtualVariable] | None)
track_tmps (bool)
- class angr.analyses.SelfModifyingCodeAnalysis(subject, max_bytes=0, state=None)[源代码]¶
基类:
AnalysisDetermine 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.
- regions: list[tuple[int, int]]¶
- result: bool¶
- class angr.analyses.StackPointerTracker(func, reg_offsets, block=None, track_memory=True, cross_insn_opt=True, initial_reg_values=None, resilient=True)[源代码]¶
-
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)[源代码]¶
- property inconsistent¶
- class angr.analyses.StaticHooker(library, binary=None)[源代码]¶
基类:
AnalysisThis 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!
- 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
- class angr.analyses.Typehoon(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]¶
基类:
AnalysisA 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.
- 参数:
var_mapping (dict[SimVariable, set[TypeVariable]] | None)
must_struct (set[TypeVariable] | None)
- __init__(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]¶
- 参数:
constraints
ground_truth -- A set of SimType-style solutions for some or all type variables. They will be respected during type solving.
var_mapping (
Optional[dict[SimVariable,set[TypeVariable]]])must_struct (
Optional[set[TypeVariable]])
- class angr.analyses.VariableRecovery(func, max_iterations=20, store_live_variables=False)[源代码]¶
基类:
ForwardAnalysis,VariableRecoveryBaseRecover "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.
- 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,VariableRecoveryBaseRecover "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.- 参数:
func_graph (networkx.DiGraph | None)
max_iterations (int)
func_args (list[SimVariable] | None)
func_arg_vvars (dict[int, tuple[VirtualVariable, SimVariable]] | None)
- __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
- 参数:
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_graph (DiGraph | None)
max_iterations (int)
func_args (list[SimVariable] | None)
func_arg_vvars (dict[int, tuple[VirtualVariable, SimVariable]] | None)
- 返回:
None
- class angr.analyses.Veritesting(input_state, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None)[源代码]¶
基类:
AnalysisAn 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.
- class angr.analyses.VtableFinder[源代码]¶
基类:
AnalysisThis analysis locates Vtables in a binary based on heuristics taken from - "Reconstruction of Class Hierarchies for Decompilation of C++ Programs"
- class angr.analyses.XRefsAnalysis(func=None, func_graph=None, block=None, max_iterations=1, replacements=None)[源代码]¶
-
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.analysis.AnalysesHub(project)[源代码]¶
基类:
PluginVendor[A]This class contains functions for all the registered and runnable analyses,
- reload_analyses(**kwargs)¶
- class angr.analyses.analysis.KnownAnalysesPlugin(*args, **kwargs)[源代码]¶
基类:
Protocol-
Identifier:
type[Identifier]¶
-
CalleeCleanupFinder:
type[CalleeCleanupFinder]¶
-
CFGEmulated:
type[CFGEmulated]¶
-
StaticHooker:
type[StaticHooker]¶
-
CongruencyCheck:
type[CongruencyCheck]¶
-
Reassembler:
type[Reassembler]¶
-
BackwardSlice:
type[BackwardSlice]¶
-
BinaryOptimizer:
type[BinaryOptimizer]¶
-
LoopFinder:
type[LoopFinder]¶
-
Disassembly:
type[Disassembly]¶
-
Veritesting:
type[Veritesting]¶
-
CodeTagging:
type[CodeTagging]¶
-
VariableRecoveryFast:
type[VariableRecoveryFast]¶
-
VariableRecovery:
type[VariableRecovery]¶
-
ReachingDefinitions:
type[ReachingDefinitionsAnalysis]¶
-
CompleteCallingConventions:
type[CompleteCallingConventionsAnalysis]¶
-
Propagator:
type[PropagatorAnalysis]¶
-
CallingConvention:
type[CallingConventionAnalysis]¶
-
Decompiler:
type[Decompiler]¶
-
XRefs:
type[XRefsAnalysis]¶
- __init__(*args, **kwargs)¶
-
Identifier:
- class angr.analyses.analysis.AnalysesHubWithDefault(project)[源代码]¶
基类:
AnalysesHub,KnownAnalysesPluginThis class has type-hinting for all built-in analyses plugin
- class angr.analyses.analysis.Analysis[源代码]¶
基类:
objectThis 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.
-
kb:
KnowledgeBase¶
-
errors:
list[AnalysisLogEntry] = []¶
-
named_errors:
defaultdict[str,list[AnalysisLogEntry]] = {}¶
- class angr.analyses.forward_analysis.CallGraphVisitor(callgraph)[源代码]¶
基类:
GraphVisitor- 参数:
callgraph (networkx.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.
- 返回类型:
- 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.
- 参数:
status_callback (Callable[[type[ForwardAnalysis]], Any] | None)
graph_visitor (GraphVisitor[NodeType] | None)
- __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¶
- class angr.analyses.forward_analysis.FunctionGraphVisitor(func, graph=None)[源代码]¶
基类:
GraphVisitor- 参数:
func (knowledge.Function)
- 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.
- 返回类型:
- 返回:
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.
- 返回类型:
- predecessors(node)[源代码]¶
Get predecessors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of predecessors.
- class angr.analyses.forward_analysis.LoopVisitor(loop)[源代码]¶
基类:
GraphVisitor- 参数:
loop (angr.analyses.loopfinder.Loop) -- The loop to visit.
- successors(node)[源代码]¶
Get successors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of successors.
- 返回类型:
- class angr.analyses.forward_analysis.SingleNodeGraphVisitor(node)[源代码]¶
基类:
GraphVisitor- 参数:
node -- The single node that should be in the graph.
- node¶
- node_returned¶
- reset()[源代码]¶
Reset the internal node traversal state. Must be called prior to visiting future nodes.
- 返回:
None
- successors(node)[源代码]¶
Get successors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of successors.
- 返回类型:
- 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.
- 参数:
status_callback (Callable[[type[ForwardAnalysis]], Any] | None)
graph_visitor (GraphVisitor[NodeType] | None)
- __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¶
- class angr.analyses.forward_analysis.job_info.JobInfo(key, job)[源代码]¶
基类:
Generic[JobType,JobKey]Stores information of each job.
- 参数:
key (JobKey)
job (JobType)
- property job: JobType¶
Get the latest available job.
- 返回:
The latest available job.
- property merged_jobs¶
- property widened_jobs¶
- class angr.analyses.forward_analysis.visitors.CallGraphVisitor(callgraph)[源代码]¶
基类:
GraphVisitor- 参数:
callgraph (networkx.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.
- 返回类型:
- class angr.analyses.forward_analysis.visitors.FunctionGraphVisitor(func, graph=None)[源代码]¶
基类:
GraphVisitor- 参数:
func (knowledge.Function)
- 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.
- 返回类型:
- 返回:
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.
- 返回类型:
- predecessors(node)[源代码]¶
Get predecessors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of predecessors.
- class angr.analyses.forward_analysis.visitors.LoopVisitor(loop)[源代码]¶
基类:
GraphVisitor- 参数:
loop (angr.analyses.loopfinder.Loop) -- The loop to visit.
- successors(node)[源代码]¶
Get successors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of successors.
- 返回类型:
- class angr.analyses.forward_analysis.visitors.SingleNodeGraphVisitor(node)[源代码]¶
基类:
GraphVisitor- 参数:
node -- The single node that should be in the graph.
- node¶
- node_returned¶
- reset()[源代码]¶
Reset the internal node traversal state. Must be called prior to visiting future nodes.
- 返回:
None
- successors(node)[源代码]¶
Get successors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of successors.
- 返回类型:
- class angr.analyses.forward_analysis.visitors.call_graph.CallGraphVisitor(callgraph)[源代码]¶
基类:
GraphVisitor- 参数:
callgraph (networkx.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.
- 返回类型:
- class angr.analyses.forward_analysis.visitors.function_graph.FunctionGraphVisitor(func, graph=None)[源代码]¶
基类:
GraphVisitor- 参数:
func (knowledge.Function)
- 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.
- 返回类型:
- 返回:
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.
- 返回类型:
- predecessors(node)[源代码]¶
Get predecessors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of predecessors.
- 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.
- back_edges()[源代码]¶
Get a list of back edges. This function is optional. If not overridden, the traverser cannot achieve an optimal graph traversal order.
- nodes_iter(**kwargs)¶
- reset()[源代码]¶
Reset the internal node traversal state. Must be called prior to visiting future nodes.
- 返回:
None
- all_successors(node, skip_reached_fixedpoint=False)[源代码]¶
Returns all successors to the specific node.
- 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.
- class angr.analyses.forward_analysis.visitors.loop.LoopVisitor(loop)[源代码]¶
基类:
GraphVisitor- 参数:
loop (angr.analyses.loopfinder.Loop) -- The loop to visit.
- successors(node)[源代码]¶
Get successors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of successors.
- 返回类型:
- class angr.analyses.forward_analysis.visitors.single_node_graph.SingleNodeGraphVisitor(node)[源代码]¶
基类:
GraphVisitor- 参数:
node -- The single node that should be in the graph.
- node¶
- node_returned¶
- reset()[源代码]¶
Reset the internal node traversal state. Must be called prior to visiting future nodes.
- 返回:
None
- successors(node)[源代码]¶
Get successors of a node. The node should be in the graph.
- 参数:
node -- The node to work with.
- 返回:
A list of successors.
- 返回类型:
- 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)[源代码]¶
基类:
AnalysisRepresents 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.
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.
- 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.
- class angr.analyses.bindiff.FunctionDiff(function_a, function_b, bindiff=None)[源代码]¶
基类:
objectThis class computes the a diff between two functions.
- 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.
- class angr.analyses.bindiff.BinDiff(other_project, enable_advanced_backward_slicing=False, cfg_a=None, cfg_b=None)[源代码]¶
基类:
AnalysisThis 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¶
- class angr.analyses.boyscout.BoyScout(cookiesize=1)[源代码]¶
基类:
AnalysisTry to determine the architecture and endieness of a binary blob
- 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)[源代码]¶
基类:
AnalysisAnalyze 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.
- 参数:
- class angr.analyses.calling_convention.FactCollector(func, max_depth=5)[源代码]¶
基类:
AnalysisAn extremely fast analysis that extracts necessary facts of a function for CallingConventionAnalysis to make decision on the calling convention and prototype of a function.
- class angr.analyses.complete_calling_conventions.CallingConventionAnalysisMode(value)[源代码]¶
基类:
EnumThe 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)[源代码]¶
基类:
AnalysisImplements 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.cc_callback (Callable | None)
skip_other_funcs (bool)
auto_start (bool)
- prioritize_functions(func_addrs_to_prioritize)[源代码]¶
Prioritize the analysis of specified functions.
- 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.
- 返回类型:
- class angr.analyses.soot_class_hierarchy.SootClassHierarchy[源代码]¶
基类:
AnalysisGenerate complete hierarchy.
- class angr.analyses.cfg.CFG(**kwargs)[源代码]¶
基类:
CFGFasttl;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)[源代码]¶
基类:
AnalysisA 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
- property regions¶
Return all memory regions.
- class angr.analyses.cfg.CFGArchOptions(arch, **options)[源代码]¶
基类:
objectStores 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)[源代码]¶
基类:
AnalysisThe 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
- 返回类型:
- make_copy(copy_to)[源代码]¶
Copy self attributes to the new object.
- 参数:
copy_to (CFGBase) -- The target to copy to.
- 返回:
None
- 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_branching_nodes(**kwargs)¶
- get_exit_stmt_idx(**kwargs)¶
- 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_-O00x40541d (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)[源代码]¶
-
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.
- 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.
- 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.
- immediate_postdominators(end, target_graph=None)[源代码]¶
Get all immediate postdominators of sub graph from given node upwards.
- 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.
- 返回类型:
- 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
- 返回类型:
- property deadends¶
Get all CFGNodes that has an out-degree of 0
- 返回:
A list of CFGNode instances
- 返回类型:
- 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],CFGBaseWe 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.
- 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:
- 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
- indirect_jumps: dict[int, IndirectJump]¶
- project: Project¶
- kb: KnowledgeBase¶
- 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)[源代码]¶
基类:
objectA view into the control-flow blanket.
- class angr.analyses.cfg.cfb.Unknown(addr, size, bytes_=None, object_=None, segment=None, section=None)[源代码]¶
基类:
object
- class angr.analyses.cfg.cfb.CFBlanket(exclude_region_types=None, on_object_added=None)[源代码]¶
基类:
AnalysisA 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
- property regions¶
Return all memory regions.
- class angr.analyses.cfg.cfg.CFG(**kwargs)[源代码]¶
基类:
CFGFasttl;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)[源代码]¶
基类:
CFGJobBaseThe job class that CFGEmulated uses.
- 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)[源代码]¶
基类:
objectA 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)[源代码]¶
-
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.
- 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.
- 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.
- immediate_postdominators(end, target_graph=None)[源代码]¶
Get all immediate postdominators of sub graph from given node upwards.
- 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.
- 返回类型:
- 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
- 返回类型:
- property deadends¶
Get all CFGNodes that has an out-degree of 0
- 返回:
A list of CFGNode instances
- 返回类型:
- 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)[源代码]¶
基类:
AnalysisThe 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
- 返回类型:
- make_copy(copy_to)[源代码]¶
Copy self attributes to the new object.
- 参数:
copy_to (CFGBase) -- The target to copy to.
- 返回:
None
- 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_branching_nodes(**kwargs)¶
- get_exit_stmt_idx(**kwargs)¶
- property graph¶
- 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_-O00x40541d (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[源代码]¶
基类:
RuntimeErrorA 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[源代码]¶
基类:
objectEnums indicating decoding mode for ARM code.
- ARM = 0¶
- THUMB = 1¶
- class angr.analyses.cfg.cfg_fast.DecodingAssumption(addr, size, mode)[源代码]¶
基类:
objectDescribes the decoding mode (ARM/THUMB) for a given basic block identified by its address.
- class angr.analyses.cfg.cfg_fast.FunctionReturn(callee_func_addr, caller_func_addr, call_site_addr, return_to)[源代码]¶
基类:
objectFunctionReturn describes a function call in a specific location and its return location. Hashable and equatable
- callee_func_addr¶
- caller_func_addr¶
- call_site_addr¶
- return_to¶
- class angr.analyses.cfg.cfg_fast.PendingJobs(kb, deregister_job_callback)[源代码]¶
基类:
objectA collection of pending jobs during CFG recovery.
- 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.
- 返回类型:
- 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
- class angr.analyses.cfg.cfg_fast.FunctionEdge[源代码]¶
基类:
objectDescribes an edge in functions' transition graphs. Base class for all types of edges.
- 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)[源代码]¶
基类:
FunctionEdgeDescribes 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¶
- class angr.analyses.cfg.cfg_fast.FunctionCallEdge(src_node, dst_addr, ret_addr, src_func_addr, syscall=False, stmt_idx=None, ins_addr=None)[源代码]¶
基类:
FunctionEdgeDescribes 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¶
- class angr.analyses.cfg.cfg_fast.FunctionFakeRetEdge(src_node, dst_addr, src_func_addr, confirmed=None)[源代码]¶
基类:
FunctionEdgeDescribes a FakeReturn (also called fall-through) edge in functions' transition graphs.
- src_node¶
- dst_addr¶
- confirmed¶
- class angr.analyses.cfg.cfg_fast.FunctionReturnEdge(ret_from_addr, ret_to_addr, dst_func_addr)[源代码]¶
基类:
FunctionEdgeDescribes a return (from a function call or a syscall) edge in functions' transition graphs.
- ret_from_addr¶
- ret_to_addr¶
- dst_func_addr¶
- class angr.analyses.cfg.cfg_fast.CFGJobType(value)[源代码]¶
基类:
EnumDefines 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)[源代码]¶
基类:
objectDefines a job to work on during the CFG recovery
- 参数:
- __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¶
- func_addr¶
- jumpkind¶
- ret_target¶
- last_addr¶
- src_node¶
- src_ins_addr¶
- src_stmt_idx¶
- returning_source¶
- syscall¶
- job_type¶
- gp¶
- 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],CFGBaseWe 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.
- 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:
- 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
- indirect_jumps: dict[int, IndirectJump]¶
- project: Project¶
- kb: KnowledgeBase¶
- generate_code_cover(**kwargs)¶
- class angr.analyses.cfg.cfg_arch_options.CFGArchOptions(arch, **options)[源代码]¶
基类:
objectStores 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)[源代码]¶
基类:
objectA context-sensitive key for a SimRun object.
- property func_addr¶
- class angr.analyses.cfg.cfg_job_base.FunctionKey(addr, callsite_tuples)[源代码]¶
基类:
objectA context-sensitive key for a function.
- 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)[源代码]¶
基类:
objectDescribes 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¶
- property func_addr¶
- property current_stack_pointer¶
- class angr.analyses.cfg.indirect_jump_resolvers.amd64_elf_got.AMD64ElfGotResolver(project)[源代码]¶
-
A timeless indirect jump resolver that resolves GOT entries on AMD64 ELF binaries.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.arm_elf_fast.ArmElfFastResolver(project)[源代码]¶
-
Resolves indirect jumps in ARM ELF binaries
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.x86_pe_iat.X86PeIatResolver(project)[源代码]¶
-
A timeless indirect jump resolver for IAT in x86 PEs and xbes.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.mips_elf_fast.Case2Result(value)[源代码]¶
基类:
EnumDescribes 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)[源代码]¶
-
A timeless indirect jump resolver for R9-based indirect function calls in MIPS ELFs.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.x86_elf_pic_plt.X86ElfPicPltResolver(project)[源代码]¶
-
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.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- angr.analyses.cfg.indirect_jump_resolvers.default_resolvers.default_indirect_jump_resolvers(obj, project)[源代码]¶
- exception angr.analyses.cfg.indirect_jump_resolvers.jumptable.NotAJumpTableNotification[源代码]¶
基类:
AngrErrorException raised to indicate this is not (or does not appear to be) a jump table.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.UninitReadMeta[源代码]¶
基类:
objectUninitialized read remapping details.
- uninit_read_base = 201326592¶
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.AddressTransformationTypes(value)[源代码]¶
-
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)[源代码]¶
基类:
objectDescribe and record an address transformation operation.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.AddressOperand[源代码]¶
基类:
objectThe 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)[源代码]¶
基类:
objectFor modeling Tmp variables.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTargetBaseAddr(stmt_loc, stmt, tmp, base_addr=None, tmp_1=None)[源代码]¶
基类:
objectModel for jump targets and their data origin.
- 参数:
stmt (pyvex.stmt.IRStmt)
tmp (int)
base_addr (int | None)
tmp_1 (int | None)
- property base_addr_available¶
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.ConstantValueManager(project, kb, func, ij_addr)[源代码]¶
基类:
objectManages the loading of registers who hold constant values.
- project¶
- kb¶
- func¶
- indirect_jump_addr¶
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTableProcessorState(arch)[源代码]¶
基类:
objectThe state used in JumpTableProcessor.
- arch¶
- stmts_to_instrument¶
- regs_to_initialize¶
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.RegOffsetAnnotation(reg_offset)[源代码]¶
基类:
AnnotationRegister 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.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.StoreHook[源代码]¶
基类:
objectHook for memory stores.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.LoadHook[源代码]¶
基类:
objectHook for memory loads.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.PutHook[源代码]¶
基类:
objectHook for register writes.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.RegisterInitializerHook(reg_offset, reg_bits, initial_value)[源代码]¶
基类:
objectHook for register init.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.BSSHook(project, bss_regions)[源代码]¶
基类:
objectHook for BSS read/write.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.MIPSGPHook(gp_offset, gp)[源代码]¶
基类:
objectHooks all reads from and writes into the gp register for MIPS32 binaries.
- class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTableResolver(project, resolve_calls=True)[源代码]¶
-
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)
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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
- 返回类型:
- 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)[源代码]¶
-
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.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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.
- 参数:
- 返回:
Bool tuple with replacement address
- class angr.analyses.cfg.indirect_jump_resolvers.resolver.IndirectJumpResolver(project, timeless=False, base_state=None)[源代码]¶
基类:
object- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.AMD64ElfGotResolver(project)[源代码]¶
-
A timeless indirect jump resolver that resolves GOT entries on AMD64 ELF binaries.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.AMD64PeIatResolver(project)[源代码]¶
-
A timeless indirect call/jump resolver for IAT in amd64 PEs.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.ArmElfFastResolver(project)[源代码]¶
-
Resolves indirect jumps in ARM ELF binaries
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.ConstantResolver(project)[源代码]¶
-
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.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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.
- 参数:
- 返回:
Bool tuple with replacement address
- class angr.analyses.cfg.indirect_jump_resolvers.JumpTableResolver(project, resolve_calls=True)[源代码]¶
-
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)
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.MemoryLoadResolver(project)[源代码]¶
-
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).
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.MipsElfFastResolver(project)[源代码]¶
-
A timeless indirect jump resolver for R9-based indirect function calls in MIPS ELFs.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.MipsElfGotResolver(project)[源代码]¶
-
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
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.X86ElfPicPltResolver(project)[源代码]¶
-
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.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- class angr.analyses.cfg.indirect_jump_resolvers.X86PeIatResolver(project)[源代码]¶
-
A timeless indirect jump resolver for IAT in x86 PEs and xbes.
- filter(cfg, addr, func_addr, block, jumpkind)[源代码]¶
Check if this resolution method may be able to resolve the indirect jump or not.
- 参数:
- 返回:
True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.
- 返回类型:
- 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).
- 返回类型:
- 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)[源代码]¶
基类:
AnalysisImplements 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¶
- 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.angrdb.AngrDB(project=None)[源代码]¶
基类:
objectAngrDB 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¶
- static save_info(session, key, value)[源代码]¶
Save an information entry to the database.
- 参数:
session
key
value
- 返回:
- db_compatible(version)[源代码]¶
Checks if the given database version is compatible with the current AngrDB class.
- dump(db_path, kbs=None, extra_info=None)[源代码]¶
- 参数:
kbs (list[KnowledgeBase] | None)
- class angr.angrdb.db.AngrDB(project=None)[源代码]¶
基类:
objectAngrDB 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¶
- static save_info(session, key, value)[源代码]¶
Save an information entry to the database.
- 参数:
session
key
value
- 返回:
- db_compatible(version)[源代码]¶
Checks if the given database version is compatible with the current AngrDB class.
- dump(db_path, kbs=None, extra_info=None)[源代码]¶
- 参数:
kbs (list[KnowledgeBase] | None)
- class angr.angrdb.models.DbInformation(**kwargs)[源代码]¶
基类:
BaseStores 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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)[源代码]¶
基类:
BaseModels 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[源代码]¶
基类:
objectSerialize/unserialize a KnowledgeBase object.
- static dump(session, kb)[源代码]¶
- 参数:
session -- The database session object.
kb (KnowledgeBase) -- The KnowledgeBase instance to serialize.
- 返回:
None
- class angr.angrdb.serializers.LoaderSerializer[源代码]¶
基类:
objectSerialize/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'}¶
- class angr.angrdb.serializers.cfg_model.CFGModelSerializer[源代码]¶
基类:
objectSerialize/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
- class angr.angrdb.serializers.comments.CommentsSerializer[源代码]¶
基类:
objectSerialize/unserialize comments to/from a database session.
- static dump(session, db_kb, comments)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
comments (Comments)
- 返回:
None
- static load(session, db_kb, kb)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
kb (KnowledgeBase)
- 返回:
- class angr.angrdb.serializers.funcs.FunctionManagerSerializer[源代码]¶
基类:
objectSerialize/unserialize a function manager and its functions.
- static dump(session, db_kb, func_manager)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
func_manager (FunctionManager)
- 返回:
- static load(session, db_kb, kb)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
kb (KnowledgeBase)
- 返回:
A loaded function manager.
- class angr.angrdb.serializers.kb.KnowledgeBaseSerializer[源代码]¶
基类:
objectSerialize/unserialize a KnowledgeBase object.
- static dump(session, kb)[源代码]¶
- 参数:
session -- The database session object.
kb (KnowledgeBase) -- The KnowledgeBase instance to serialize.
- 返回:
None
- class angr.angrdb.serializers.labels.LabelsSerializer[源代码]¶
基类:
objectSerialize/unserialize labels to/from a database session.
- static dump(session, db_kb, labels)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
labels (Labels)
- 返回:
None
- static load(session, db_kb, kb)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
kb (KnowledgeBase)
- 返回:
- 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)[源代码]¶
基类:
JSONEncoderA 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 aTypeError).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[源代码]¶
基类:
JSONDecoderA 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 givendict. 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 ofobject_pairs_hookwill be used instead of thedict. This feature can be used to implement custom decoders. Ifobject_hookis also defined, theobject_pairs_hooktakes 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
strictis 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[源代码]¶
基类:
objectSerialize/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'}¶
- class angr.angrdb.serializers.xrefs.XRefsSerializer[源代码]¶
基类:
objectSerialize/unserialize an XRefs object to/from a database session.
- static dump(session, db_kb, xrefs)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
xrefs (XRefManager)
- 返回:
- static load(session, db_kb, kb, cfg_model=None)[源代码]¶
- 参数:
session
db_kb (DbKnowledgeBase)
kb (KnowledgeBase)
cfg_model (CFGModel)
- 返回:
- class angr.angrdb.serializers.variables.VariableManagerSerializer[源代码]¶
基类:
objectSerialize/unserialize a variable manager and its variables.
- static dump(session, db_kb, var_manager)[源代码]¶
- 参数:
db_kb (DbKnowledgeBase)
var_manager (VariableManager)
- static dump_internal(session, db_kb, internal_manager, func_addr, ident=None)[源代码]¶
- 参数:
db_kb (DbKnowledgeBase)
internal_manager (VariableManagerInternal)
func_addr (int)
- static load(session, db_kb, kb, ident=None)[源代码]¶
- 参数:
db_kb (DbKnowledgeBase)
kb (KnowledgeBase)
- static load_internal(db_varcoll, variable_manager)[源代码]¶
- 返回类型:
- 参数:
variable_manager (VariableManager)
- class angr.angrdb.serializers.structured_code.StructuredCodeManagerSerializer[源代码]¶
基类:
objectSerialize/unserialize a structured code manager.
- static dump(session, db_kb, code_manager)[源代码]¶
- 参数:
session
db_kb (
DbKnowledgeBase)code_manager (
StructuredCodeManager)
- 返回:
- static load(session, db_kb, kb)[源代码]¶
- 参数:
session
db_kb (
DbKnowledgeBase)kb (
KnowledgeBase)
- 返回类型:
- 返回:
A loaded structured code manager
- class angr.analyses.decompiler.structuring.recursive_structurer.RecursiveStructurer(region, cond_proc=None, func=None, structurer_cls=None, **kwargs)[源代码]¶
基类:
AnalysisRecursively structure a region and all of its subregions.
- 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)[源代码]¶
-
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'¶
- 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)[源代码]¶
-
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.
- 参数:
func (Function | None)
use_multistmtexprs (MultiStmtExprMode)
- 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)[源代码]¶
- 参数:
func (Function | None)
use_multistmtexprs (MultiStmtExprMode)
- class angr.analyses.decompiler.structuring.RecursiveStructurer(region, cond_proc=None, func=None, structurer_cls=None, **kwargs)[源代码]¶
基类:
AnalysisRecursively structure a region and all of its subregions.
- class angr.analyses.decompiler.structuring.SAILRStructurer(region, improve_phoenix=True, **kwargs)[源代码]¶
-
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.
- 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.
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'¶
- 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)[源代码]¶
-
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¶
- class angr.analyses.decompiler.structuring.structurer_nodes.MultiNode(nodes, addr=None, idx=None)[源代码]¶
基类:
object- nodes¶
- addr¶
- idx¶
- class angr.analyses.decompiler.structuring.structurer_nodes.SequenceNode(addr, nodes=None)[源代码]¶
基类:
BaseNode- 参数:
addr (int | None)
- nodes¶
- class angr.analyses.decompiler.structuring.structurer_nodes.CodeNode(node, reaching_condition)[源代码]¶
基类:
BaseNode- node¶
- reaching_condition¶
- property addr¶
- property idx¶
- class angr.analyses.decompiler.structuring.structurer_nodes.ConditionNode(addr, reaching_condition, condition, true_node, false_node=None)[源代码]¶
基类:
BaseNode- 参数:
addr (int | None)
- reaching_condition¶
- condition¶
- true_node¶
- false_node¶
- node¶
- class angr.analyses.decompiler.structuring.structurer_nodes.CascadingConditionNode(addr, condition_and_nodes, else_node=None)[源代码]¶
基类:
BaseNode- 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)
addr (int | None)
continue_addr (int | None)
initializer (Assignment | None)
iterator (Assignment | None)
-
condition:
Expression|None¶
-
sequence_node:
SequenceNode¶
-
initializer:
Assignment|None¶
-
iterator:
Assignment|None¶
- property addr¶
- property continue_addr¶
- class angr.analyses.decompiler.structuring.structurer_nodes.BreakNode(addr, target)[源代码]¶
基类:
BaseNode- 参数:
addr (int | None)
- target¶
- class angr.analyses.decompiler.structuring.structurer_nodes.ContinueNode(addr, target)[源代码]¶
基类:
BaseNode- 参数:
addr (int | None)
- target¶
- class angr.analyses.decompiler.structuring.structurer_nodes.ConditionalBreakNode(addr, condition, target)[源代码]¶
基类:
BreakNode- 参数:
addr (int | None)
- condition¶
- class angr.analyses.decompiler.structuring.structurer_nodes.SwitchCaseNode(switch_expr, cases, default_node, addr=None)[源代码]¶
基类:
BaseNode- 参数:
cases (OrderedDict[int | tuple[int, ...], SequenceNode])
addr (int | None)
- __init__(switch_expr, cases, default_node, addr=None)[源代码]¶
- 参数:
cases (OrderedDict[int | tuple[int, ...], SequenceNode])
- switch_expr¶
-
cases:
OrderedDict[int|tuple[int,...],SequenceNode]¶
- default_node¶
- class angr.analyses.decompiler.structuring.structurer_nodes.IncompleteSwitchCaseNode(addr, head, cases)[源代码]¶
基类:
BaseNodeDescribes 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.
- head¶
- class angr.analyses.decompiler.structuring.structurer_nodes.IncompleteSwitchCaseHeadStatement(*args, **kwargs)[源代码]¶
基类:
StatementDescribes a switch-case head. This is only created by LoweredSwitchSimplifier.
- switch_variable¶
- addr¶
- 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)[源代码]¶
基类:
AnalysisThe 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)[源代码]¶
- exception angr.analyses.decompiler.structuring.phoenix.GraphChangedNotification[源代码]¶
基类:
ExceptionA 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)[源代码]¶
-
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)[源代码]¶
-
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.
- 参数:
func (Function | None)
use_multistmtexprs (MultiStmtExprMode)
- 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)[源代码]¶
- 参数:
func (Function | None)
use_multistmtexprs (MultiStmtExprMode)
- whitelist_edges: set[tuple[int, int]]¶
- switch_case_known_heads: set[Block]¶
- dowhile_known_tail_nodes: set¶
- static switch_case_entry_node_has_common_successor_case_1(graph, jump_table, case_nodes, node_pred)[源代码]¶
- 返回类型:
- static switch_case_entry_node_has_common_successor_case_2(graph, jump_table, case_nodes, node_pred)[源代码]¶
- 返回类型:
- 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)[源代码]¶
基类:
AnalysisPerform 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)[源代码]¶
基类:
AnalysisSimplify an AIL block.
- 参数:
block (Block | None)
func_addr (int | None)
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
- __init__(block, func_addr=None, remove_dead_memdefs=False, stack_pointer_tracker=None, peephole_optimizations=None, cached_reaching_definitions=None, cached_propagator=None)[源代码]¶
- 参数:
block (
Block|None) -- The AIL block to simplify. Setting it to None to skip calling self._analyze(), which is useful in test cases.func_addr (int | None)
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
- 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- 参数:
func_args (list[SimVariable] | None)
binop_depth_cutoff (int)
- __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)[源代码]¶
- 参数:
func_args (list[SimVariable] | None)
binop_depth_cutoff (int)
- RENDER_TYPE¶
tuple[str,PositionMapping,PositionMapping,InstructionMapping,dict[Any,set[Any]]] 的别名
- class angr.analyses.decompiler.CallSiteMaker(block, reaching_definitions=None, stack_pointer_tracker=None, ail_manager=None)[源代码]¶
基类:
AnalysisAdd calling convention, declaration, and args to a call site.
- 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)[源代码]¶
基类:
AnalysisA Clinic deals with AILments.
- 参数:
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
cache (DecompilationCache | None)
mode (ClinicMode)
sp_shift (int)
vvar_id_start (int)
force_loop_single_exit (bool)
complete_successors (bool)
unsound_fix_abnormal_switches (bool)
- __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)[源代码]¶
- 参数:
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
cache (DecompilationCache | None)
mode (ClinicMode)
sp_shift (int)
vvar_id_start (int)
force_loop_single_exit (bool)
complete_successors (bool)
unsound_fix_abnormal_switches (bool)
- 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)[源代码]¶
基类:
AnalysisThe 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
- 参数:
- __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)[源代码]¶
- 参数:
preset (str | DecompilationPreset | None)
peephole_optimizations (Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]] | None)
update_memory_data (bool)
generate_code (bool)
use_cache (bool)
expr_collapse_depth (int)
- 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.
- find_data_references_and_update_memory_data(seq_node)[源代码]¶
- 参数:
seq_node (SequenceNode)
- class angr.analyses.decompiler.GraphDephication(func, ail_graph, vvar_to_vvar_mapping=None, rewrite=False)[源代码]¶
基类:
DephicationBaseGraphDephication removes phi expressions from an AIL graph, essentially transforms a partial-SSA form of AIL graph to a normal AIL graph.
- class angr.analyses.decompiler.ImportSourceCode(function, flavor='source', source_root=None, encoding='utf-8')[源代码]¶
- 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)[源代码]¶
基类:
AnalysisIdentifies 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.
- __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)[源代码]¶
- 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)[源代码]¶
基类:
AnalysisSimplifies a given region.
- class angr.analyses.decompiler.SeqNodeDephication(func, seq_node, vvar_to_vvar_mapping=None, rewrite=False)[源代码]¶
基类:
DephicationBaseSeqNodeDephication removes phi expressions from an AIL SeqNode and its children.
- 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)[源代码]¶
基类:
AnalysisSsailification (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 blockail_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¶
- exception angr.analyses.decompiler.ail_simplifier.HasCallNotification[源代码]¶
基类:
ExceptionNotifies the existence of a call statement.
- exception angr.analyses.decompiler.ail_simplifier.HasVVarNotification[源代码]¶
基类:
ExceptionNotifies the existence of a VirtualVariable.
- class angr.analyses.decompiler.ail_simplifier.AILBlockTempCollector(**kwargs)[源代码]¶
-
Collects any temporaries used in a block.
- 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)[源代码]¶
基类:
AnalysisPerform 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.ailgraph_walker.AILGraphWalker(graph, handler, replace_nodes=False)[源代码]¶
基类:
objectWalks an AIL graph and optionally replaces each node with a new node.
- 参数:
replace_nodes (bool)
- class angr.analyses.decompiler.block_simplifier.HasCallExprWalker[源代码]¶
-
Test if an expression contains a call expression inside.
- 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)[源代码]¶
基类:
AnalysisSimplify an AIL block.
- 参数:
block (Block | None)
func_addr (int | None)
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
- __init__(block, func_addr=None, remove_dead_memdefs=False, stack_pointer_tracker=None, peephole_optimizations=None, cached_reaching_definitions=None, cached_propagator=None)[源代码]¶
- 参数:
block (
Block|None) -- The AIL block to simplify. Setting it to None to skip calling self._analyze(), which is useful in test cases.func_addr (int | None)
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
- class angr.analyses.decompiler.callsite_maker.CallSiteMaker(block, reaching_definitions=None, stack_pointer_tracker=None, ail_manager=None)[源代码]¶
基类:
AnalysisAdd calling convention, declaration, and args to a call site.
- class angr.analyses.decompiler.ccall_rewriters.rewriter_base.CCallRewriterBase(ccall, arch)[源代码]¶
基类:
objectThe 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)[源代码]¶
-
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)[源代码]¶
基类:
EnumAnalysis 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)[源代码]¶
基类:
objectThe fields of this class is compatible with items inside IRSB.data_refs.
- 参数:
- 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)[源代码]¶
基类:
AnalysisA Clinic deals with AILments.
- 参数:
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
cache (DecompilationCache | None)
mode (ClinicMode)
sp_shift (int)
vvar_id_start (int)
force_loop_single_exit (bool)
complete_successors (bool)
unsound_fix_abnormal_switches (bool)
- __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)[源代码]¶
- 参数:
peephole_optimizations (None | Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]])
cache (DecompilationCache | None)
mode (ClinicMode)
sp_shift (int)
vvar_id_start (int)
force_loop_single_exit (bool)
complete_successors (bool)
unsound_fix_abnormal_switches (bool)
- class angr.analyses.decompiler.condition_processor.ConditionProcessor(arch, condition_mapping=None)[源代码]¶
基类:
objectConvert between claripy AST and AIL expressions. Also calculates reaching conditions of all nodes on a graph.
- 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.
- 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.
- EXC_COUNTER = 1000¶
- convert_claripy_bool_ast(cond, memo=None)[源代码]¶
Convert recovered reaching conditions from claripy ASTs to ailment Expressions
- 返回:
None
- 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)[源代码]¶
基类:
objectDescribes a decompilation option.
- angr.analyses.decompiler.decompilation_options.O¶
- class angr.analyses.decompiler.decompilation_cache.DecompilationCache(addr)[源代码]¶
基类:
objectCaches key data structures that can be used later for refining decompilation results, such as retyping variables.
- addr¶
- func_typevar¶
-
codegen:
BaseStructuredCodeGenerator|None¶
-
binop_operators:
dict[OpDescriptor,str] |None¶
- 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)[源代码]¶
基类:
AnalysisThe 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
- 参数:
- __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)[源代码]¶
- 参数:
preset (str | DecompilationPreset | None)
peephole_optimizations (Iterable[type[PeepholeOptimizationStmtBase] | type[PeepholeOptimizationExprBase]] | None)
update_memory_data (bool)
generate_code (bool)
use_cache (bool)
expr_collapse_depth (int)
- 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.
- find_data_references_and_update_memory_data(seq_node)[源代码]¶
- 参数:
seq_node (SequenceNode)
- class angr.analyses.decompiler.empty_node_remover.EmptyNodeRemover(node, claripy_ast_conditions=True)[源代码]¶
基类:
objectRewrites 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)
- class angr.analyses.decompiler.expression_narrower.ExprNarrowingInfo(narrowable, to_size=None, use_exprs=None, phi_vars=None)[源代码]¶
基类:
objectStores the analysis result of _narrowing_needed().
- 参数:
narrowable (bool)
to_size (int | None)
use_exprs (list[tuple[atoms.VirtualVariable, CodeLocation, tuple[str, tuple[Expression, ...]]]] | None)
phi_vars (set[atoms.VirtualVariable] | None)
- __init__(narrowable, to_size=None, use_exprs=None, phi_vars=None)[源代码]¶
- 参数:
narrowable (bool)
to_size (int | None)
use_exprs (list[tuple[VirtualVariable, CodeLocation, tuple[str, tuple[Expression, ...]]]] | None)
phi_vars (set[VirtualVariable] | None)
- narrowable¶
- to_size¶
- use_exprs¶
- phi_vars¶
- class angr.analyses.decompiler.expression_narrower.NarrowingInfoExtractor(target_expr)[源代码]¶
-
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)[源代码]¶
-
Narrows an expression regardless of whether the expression is a definition or a use.
- 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)[源代码]¶
基类:
objectGraphRegion 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.
- 参数:
- __init__(head, graph, successors, graph_with_successors, cyclic, full_graph, cyclic_ancestor=False)[源代码]¶
- head¶
- graph¶
- successors¶
- graph_with_successors¶
- full_graph¶
- cyclic¶
- cyclic_ancestor¶
- property addr¶
- replace_region(sub_region, updated_sub_region, replace_with, virtualized_edges)[源代码]¶
- 参数:
sub_region (GraphRegion)
updated_sub_region (GraphRegion)
- replace_region_with_region(sub_region, replace_with)[源代码]¶
- 参数:
sub_region (GraphRegion)
replace_with (GraphRegion)
- class angr.analyses.decompiler.jump_target_collector.JumpTargetCollector(node)[源代码]¶
基类:
objectCollect all jump targets.
- class angr.analyses.decompiler.jumptable_entry_condition_rewriter.JumpTableEntryConditionRewriter(jumptable_entry_conds)[源代码]¶
-
Remove artificial jump table entry conditions that ConditionProcessor introduced when dealing with jump tables.
- class angr.analyses.decompiler.optimization_passes.BasePointerSaveSimplifier(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.CallStatementRewriter(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.CodeMotionOptimization(func, *args, max_iters=10, node_idx_start=0, **kwargs)[源代码]¶
-
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 '¶
- 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.
- class angr.analyses.decompiler.optimization_passes.ConstPropOptReverter(func, region_identifier=None, reaching_definitions=None, **kwargs)[源代码]¶
-
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)"¶
- class angr.analyses.decompiler.optimization_passes.ConstantDereferencesSimplifier(func, **kwargs)[源代码]¶
-
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'¶
- class angr.analyses.decompiler.optimization_passes.CrossJumpReverter(func, node_idx_start=0, max_opt_iters=3, max_call_duplications=1, **kwargs)[源代码]¶
基类:
StructuringOptimizationPassThis 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.
- 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.'¶
- class angr.analyses.decompiler.optimization_passes.DeadblockRemover(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.DivSimplifier(func, **kwargs)[源代码]¶
-
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".'¶
- class angr.analyses.decompiler.optimization_passes.DuplicationReverter(func, max_guarding_conditions=4, **kwargs)[源代码]¶
基类:
StructuringOptimizationPassThis (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."¶
- 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)
- 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
- create_merged_subgraph(blocks, graph, maximize_similarity=False)[源代码]¶
- 返回类型:
AILMergeGraph- 参数:
graph (DiGraph)
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)[源代码]¶
-
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)[源代码]¶
-
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'¶
- class angr.analyses.decompiler.optimization_passes.ITEExprConverter(func, ite_exprs=None, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.ITERegionConverter(func, max_updates=10, **kwargs)[源代码]¶
-
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`.'¶
- class angr.analyses.decompiler.optimization_passes.InlinedStringTransformationSimplifier(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.LoweredSwitchSimplifier(func, min_distinct_cases=2, **kwargs)[源代码]¶
基类:
StructuringOptimizationPassThis 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.'¶
- static restore_graph(node, last_stmt, graph, full_graph)[源代码]¶
- 参数:
last_stmt (IncompleteSwitchCaseHeadStatement)
graph (DiGraph)
full_graph (DiGraph)
- class angr.analyses.decompiler.optimization_passes.ModSimplifier(func, **kwargs)[源代码]¶
-
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".'¶
- class angr.analyses.decompiler.optimization_passes.OptimizationPassStage(value)[源代码]¶
基类:
EnumEnums 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)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.RetAddrSaveSimplifier(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.ReturnDeduplicator(func, **kwargs)[源代码]¶
-
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']¶
- 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,ReturnDuplicatorBaseThis is a light-level goto-less version of the ReturnDuplicator optimization pass. It will only duplicate return-only blocks.
- 参数:
- 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']¶
- 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,ReturnDuplicatorBaseAn 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)
- 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.'¶
- class angr.analyses.decompiler.optimization_passes.StackCanarySimplifier(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.SwitchDefaultCaseDuplicator(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.SwitchReusedEntryRewriter(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.TagSlicer(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.WinStackCanarySimplifier(func, **kwargs)[源代码]¶
-
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.'¶
- class angr.analyses.decompiler.optimization_passes.X86GccGetPcSimplifier(func, **kwargs)[源代码]¶
-
Simplifies __x86.get_pc_thunk calls.
- ARCHES = ['X86']¶
- PLATFORMS = ['linux']¶
- STAGE: OptimizationPassStage = 1¶
- NAME = 'Simplify getpc()'¶
- DESCRIPTION = 'Simplifies __x86.get_pc_thunk calls.'¶
- angr.analyses.decompiler.optimization_passes.register_optimization_pass(opt_pass, *, presets=None)[源代码]¶
- class angr.analyses.decompiler.optimization_passes.const_derefs.BlockWalker(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)[源代码]¶
-
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'¶
- entry_node_addr: tuple[int, int | None]¶
- out_graph: networkx.DiGraph | None¶
- exception angr.analyses.decompiler.optimization_passes.optimization_pass.MultipleBlocksException[源代码]¶
基类:
ExceptionAn 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)[源代码]¶
基类:
EnumEnums 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)[源代码]¶
基类:
objectThe base class for any optimization pass.
- ARCHES = []¶
- PLATFORMS = []¶
-
STAGE:
OptimizationPassStage¶
- NAME = 'N/A'¶
- DESCRIPTION = 'N/A'¶
- property kb¶
- 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)[源代码]¶
-
The base class for any function-level graph optimization pass.
- 参数:
- class angr.analyses.decompiler.optimization_passes.optimization_pass.SequenceOptimizationPass(func, seq=None, **kwargs)[源代码]¶
-
The base class for any sequence node optimization pass.
- 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)[源代码]¶
-
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¶
-
STAGE:
OptimizationPassStage= 7¶
- class angr.analyses.decompiler.optimization_passes.stack_canary_simplifier.StackCanarySimplifier(func, **kwargs)[源代码]¶
-
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.'¶
- 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)[源代码]¶
-
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.'¶
- entry_node_addr: tuple[int, int | None]¶
- out_graph: networkx.DiGraph | None¶
- class angr.analyses.decompiler.optimization_passes.div_simplifier.DivSimplifierAILEngine(*args, **kwargs)[源代码]¶
-
An AIL pass for the div simplifier
- class angr.analyses.decompiler.optimization_passes.div_simplifier.DivSimplifier(func, **kwargs)[源代码]¶
-
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".'¶
- entry_node_addr: tuple[int, int | None]¶
- out_graph: networkx.DiGraph | None¶
- exception angr.analyses.decompiler.optimization_passes.ite_expr_converter.NodeFoundNotification[源代码]¶
基类:
ExceptionA notification that the target node has been found.
- class angr.analyses.decompiler.optimization_passes.ite_expr_converter.BlockLocator(block)[源代码]¶
基类:
RegionWalkerRecursively locate block in a GraphRegion instance.
It might be reasonable to move this class into its own file.
- class angr.analyses.decompiler.optimization_passes.ite_expr_converter.ExpressionReplacer(block_addr, target_expr, callback)[源代码]¶
-
Replace expressions.
- class angr.analyses.decompiler.optimization_passes.ite_expr_converter.ITEExprConverter(func, ite_exprs=None, **kwargs)[源代码]¶
-
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.'¶
- 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)[源代码]¶
基类:
objectDescribes a case in a switch-case construct.
- original_node¶
- node_type¶
- variable_hash¶
- expr¶
- value¶
- target¶
- target_idx¶
- next_addr¶
- class angr.analyses.decompiler.optimization_passes.lowered_switch_simplifier.StableVarExprHasher(expr)[源代码]¶
-
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)[源代码]¶
基类:
StructuringOptimizationPassThis 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.'¶
- static restore_graph(node, last_stmt, graph, full_graph)[源代码]¶
- 参数:
last_stmt (IncompleteSwitchCaseHeadStatement)
graph (DiGraph)
full_graph (DiGraph)
- entry_node_addr: tuple[int, int | None]¶
- out_graph: networkx.DiGraph | None¶
- class angr.analyses.decompiler.optimization_passes.mod_simplifier.ModSimplifierAILEngine(*args, **kwargs)[源代码]¶
- class angr.analyses.decompiler.optimization_passes.mod_simplifier.ModSimplifier(func, **kwargs)[源代码]¶
-
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".'¶
- entry_node_addr: tuple[int, int | None]¶
- out_graph: networkx.DiGraph | None¶
- class angr.analyses.decompiler.optimization_passes.engine_base.SimplifierAILState(arch, variables=None)[源代码]¶
基类:
objectThe abstract state used in SimplifierAILEngine.
- store_variable(old, new)[源代码]¶
- 参数:
old (VirtualVariable)
- get_variable(old)[源代码]¶
- 参数:
old (VirtualVariable)
- 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)[源代码]¶
-
A sequence walker that finds nodes and invokes expression replacer to replace expressions.
- class angr.analyses.decompiler.optimization_passes.expr_op_swapper.ExpressionReplacer(block_addr, target_expr_predicate, callback)[源代码]¶
-
Replace expressions.
- class angr.analyses.decompiler.optimization_passes.expr_op_swapper.OpDescriptor(block_addr, stmt_idx, ins_addr, op)[源代码]¶
基类:
objectDescribes a specific operator.
- class angr.analyses.decompiler.optimization_passes.expr_op_swapper.ExprOpSwapper(func, binop_operators=None, **kwargs)[源代码]¶
-
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)[源代码]¶
-
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.'¶
- 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)[源代码]¶
-
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.'¶
- 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)[源代码]¶
-
Simplifies __x86.get_pc_thunk calls.
- ARCHES = ['X86']¶
- PLATFORMS = ['linux']¶
- STAGE: OptimizationPassStage = 1¶
- NAME = 'Simplify getpc()'¶
- DESCRIPTION = 'Simplifies __x86.get_pc_thunk calls.'¶
- 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)[源代码]¶
基类:
objectThe base class for all peephole optimizations that are applied on AIL statements.
- 参数:
project (Project | None)
kb (KnowledgeBase | None)
func_addr (int | None)
- 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)
-
kb:
KnowledgeBase|None¶
- class angr.analyses.decompiler.peephole_optimizations.base.PeepholeOptimizationMultiStmtBase(project, kb, func_addr=None)[源代码]¶
基类:
objectThe base class for all peephole optimizations that are applied on multiple AIL statements at once.
- 参数:
project (Project | None)
kb (KnowledgeBase | None)
func_addr (int | None)
- 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)
-
kb:
KnowledgeBase|None¶
- class angr.analyses.decompiler.peephole_optimizations.base.PeepholeOptimizationExprBase(project, kb, func_addr=None)[源代码]¶
基类:
objectThe base class for all peephole optimizations that are applied on AIL expressions.
- 参数:
project (Project | None)
kb (KnowledgeBase | None)
func_addr (int | None)
- 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)
-
kb:
KnowledgeBase|None¶
- static find_definition(ail_expr, stmt_idx, block)[源代码]¶
- 返回类型:
- 参数:
ail_expr (Expression)
stmt_idx (int)
block (Block)
- 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)[源代码]¶
基类:
AnalysisIdentifies 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.
- __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)[源代码]¶
- 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)[源代码]¶
基类:
AnalysisSimplifies a given region.
- class angr.analyses.decompiler.region_simplifiers.cascading_cond_transformer.CascadingConditionTransformer(node)[源代码]¶
-
Identifies and transforms if { ... } else { if { ... } else { ... } } to if { ... } else if { ... } else if { ... }.
- class angr.analyses.decompiler.region_simplifiers.cascading_ifs.CascadingIfsRemover(node)[源代码]¶
-
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 { }
- class angr.analyses.decompiler.region_simplifiers.expr_folding.StatementLocation(block_addr, block_idx, stmt_idx)[源代码]¶
基类:
LocationBase- block_addr¶
- block_idx¶
- stmt_idx¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionLocation(block_addr, block_idx, stmt_idx, expr_idx)[源代码]¶
基类:
LocationBase- block_addr¶
- block_idx¶
- stmt_idx¶
- expr_idx¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ConditionLocation(cond_node_addr, case_idx=None)[源代码]¶
基类:
LocationBase- 参数:
case_idx (int | None)
- node_addr¶
- case_idx¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ConditionalBreakLocation(node_addr)[源代码]¶
基类:
LocationBase- node_addr¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.MultiStatementExpressionAssignmentFinder(stmt_handler)[源代码]¶
-
Process statements in MultiStatementExpression objects and find assignments.
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionUseFinder[源代码]¶
-
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.
- uses: defaultdict[SimVariable, set[tuple[Expression, ExpressionLocation | None]]]¶
- has_load¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionCounter(node, variable_manager)[源代码]¶
-
Find all expressions that are assigned once and only used once.
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionReplacer(assignments, uses, variable_manager)[源代码]¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionFolder(assignments, uses, node, variable_manager)[源代码]¶
- class angr.analyses.decompiler.region_simplifiers.expr_folding.StoreStatementFinder(node, intervals)[源代码]¶
-
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)[源代码]¶
- 返回类型:
- 参数:
start (StatementLocation)
end (StatementLocation)
- class angr.analyses.decompiler.region_simplifiers.goto.GotoSimplifier(node, function=None, kb=None)[源代码]¶
-
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
- class angr.analyses.decompiler.region_simplifiers.if_.IfSimplifier(node)[源代码]¶
-
Remove unnecessary jump or conditional jump statements if they jump to the successor right afterwards.
- class angr.analyses.decompiler.region_simplifiers.ifelse.IfElseFlattener(node, functions)[源代码]¶
-
Remove unnecessary else branches and make the else node a direct successor of the previous If node if the If node always returns.
- class angr.analyses.decompiler.region_simplifiers.loop.LoopSimplifier(node, functions)[源代码]¶
-
Simplifies loops.
- class angr.analyses.decompiler.region_simplifiers.node_address_finder.NodeAddressFinder(node)[源代码]¶
-
Walk the entire node and collect all addresses of nodes.
- class angr.analyses.decompiler.region_simplifiers.region_simplifier.RegionSimplifier(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]¶
基类:
AnalysisSimplifies a given region.
- class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.CmpOp(value)[源代码]¶
基类:
EnumAll 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)[源代码]¶
基类:
objectDescribes a conditional region.
- 参数:
op (CmpOp)
value (int)
node (ConditionNode | ailment.Block)
- __init__(variable, op, value, node, parent=None)[源代码]¶
- 参数:
op (CmpOp)
value (int)
node (ConditionNode | Block)
- variable¶
- op¶
- value¶
- node¶
- parent¶
- class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.SwitchCaseRegion(variable, node, parent=None)[源代码]¶
基类:
objectDescribes 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)[源代码]¶
-
Find comparisons and switches in order to identify switch clusters.
- class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.SwitchClusterReplacer(region, to_replace, replace_with)[源代码]¶
-
Replace an identified switch cluster with a newly created SwitchCase node.
- angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.is_simple_jump_node(node, case_addrs, targets=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).
- 返回类型:
- 参数:
cond_regions (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.
- 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.
- 参数:
region (
SequenceNode) -- The region to simplify.var2condnodes (
dict[Any,list[ConditionalRegion]]) -- A dict that stores the mapping from (potential) switch variables to conditional regions.
- 返回:
None
- angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.simplify_lowered_switches_core(region, var, condnodes, functions)[源代码]¶
- 返回类型:
- 参数:
region (SequenceNode)
- class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.FindFirstNodeInSet(node_set)[源代码]¶
-
Find the first node out of a set of node appearing in a SequenceNode (and its tree).
- class angr.analyses.decompiler.region_simplifiers.switch_expr_simplifier.SwitchExpressionSimplifier(node)[源代码]¶
-
Identifies switch expressions that adds or minuses a constant, removes the constant from the switch expression, and adjust all case expressions accordingly.
- class angr.analyses.decompiler.region_walker.RegionWalker[源代码]¶
基类:
objectA simple traverser class that walks GraphRegion instances.
- walk(region)[源代码]¶
- 参数:
region (GraphRegion)
- class angr.analyses.decompiler.redundant_label_remover.RedundantLabelRemover(node, jump_targets)[源代码]¶
基类:
objectRemove 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.
- class angr.analyses.decompiler.sequence_walker.SequenceWalker(handlers=None, exception_on_unsupported=False, update_seqnode_in_place=True, force_forward_scan=False)[源代码]¶
基类:
objectWalks a SequenceNode and all its nodes, recursively.
- 参数:
force_forward_scan (bool)
- class angr.analyses.decompiler.structured_codegen.BaseStructuredCodeGenerator(flavor=None)[源代码]¶
基类:
object
- 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- 参数:
func_args (list[SimVariable] | None)
binop_depth_cutoff (int)
- __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)[源代码]¶
- 参数:
func_args (list[SimVariable] | None)
binop_depth_cutoff (int)
- RENDER_TYPE¶
tuple[str,PositionMapping,PositionMapping,InstructionMapping,dict[Any,set[Any]]] 的别名
- class angr.analyses.decompiler.structured_codegen.DummyStructuredCodeGenerator(flavor, expr_comments=None, stmt_comments=None, configuration=None, const_formats=None)[源代码]¶
基类:
BaseStructuredCodeGeneratorA dummy structured code generator that only stores user-specified information.
- 参数:
flavor (str)
- class angr.analyses.decompiler.structured_codegen.ImportSourceCode(function, flavor='source', source_root=None, encoding='utf-8')[源代码]¶
- class angr.analyses.decompiler.structured_codegen.InstructionMappingElement(ins_addr, posmap_pos)[源代码]¶
基类:
object
- class angr.analyses.decompiler.structured_codegen.PositionMapping[源代码]¶
基类:
object- DUPLICATION_CHECK = True¶
- class angr.analyses.decompiler.structured_codegen.PositionMappingElement(start, length, obj)[源代码]¶
基类:
object- obj¶
- class angr.analyses.decompiler.structured_codegen.base.PositionMappingElement(start, length, obj)[源代码]¶
基类:
object- obj¶
- class angr.analyses.decompiler.structured_codegen.base.PositionMapping[源代码]¶
基类:
object- DUPLICATION_CHECK = True¶
- class angr.analyses.decompiler.structured_codegen.base.InstructionMappingElement(ins_addr, posmap_pos)[源代码]¶
基类:
object
- class angr.analyses.decompiler.structured_codegen.base.BaseStructuredCodeGenerator(flavor=None)[源代码]¶
基类:
object
- angr.analyses.decompiler.structured_codegen.c.extract_terms(expr)[源代码]¶
- 返回类型:
- 参数:
expr (CExpression)
- 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)[源代码]¶
基类:
objectRepresents a program construct in C. Acts as the base class for all other representation constructions.
-
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.
-
codegen:
- 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)[源代码]¶
基类:
CConstructRepresents a function in C.
- 参数:
functy (SimTypeFunction)
- __init__(addr, name, functy, arg_list, statements, variables_in_use, variable_manager, demangled_name=None, show_demangled_name=True, omit_header=False, **kwargs)[源代码]¶
- 参数:
functy (SimTypeFunction)
- addr¶
- name¶
- functy¶
- arg_list¶
- statements¶
- variables_in_use¶
-
variable_manager:
VariableManagerInternal¶
- demangled_name¶
- show_demangled_name¶
- omit_header¶
- class angr.analyses.decompiler.structured_codegen.c.CStatement(codegen)[源代码]¶
基类:
CConstructRepresents a statement in C.
- 参数:
codegen (CStructuredCodeGenerator)
- class angr.analyses.decompiler.structured_codegen.c.CExpression(collapsed=False, **kwargs)[源代码]¶
基类:
CConstructBase class for C expressions.
- collapsed¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CStatements(statements, addr=None, **kwargs)[源代码]¶
基类:
CStatementRepresents a sequence of statements in C.
- statements¶
- addr¶
- class angr.analyses.decompiler.structured_codegen.c.CAILBlock(block, **kwargs)[源代码]¶
基类:
CStatementRepresents a block of AIL statements.
- block¶
- class angr.analyses.decompiler.structured_codegen.c.CLoop(codegen)[源代码]¶
基类:
CStatementRepresents a loop in C.
- 参数:
codegen (CStructuredCodeGenerator)
- class angr.analyses.decompiler.structured_codegen.c.CWhileLoop(condition, body, tags=None, **kwargs)[源代码]¶
基类:
CLoopRepresents a while loop in C.
- condition¶
- body¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CDoWhileLoop(condition, body, tags=None, **kwargs)[源代码]¶
基类:
CLoopRepresents a do-while loop in C.
- condition¶
- body¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CForLoop(initializer, condition, iterator, body, tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents a for-loop in C.
- initializer¶
- condition¶
- iterator¶
- body¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CIfElse(condition_and_nodes, else_node=None, simplify_else_scope=False, cstyle_ifs=True, tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents 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¶
- class angr.analyses.decompiler.structured_codegen.c.CIfBreak(condition, cstyle_ifs=True, tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents an if-break statement in C.
- condition¶
- cstyle_ifs¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CBreak(tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents a break statement in C.
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CContinue(tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents a continue statement in C.
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CSwitchCase(switch, cases, default, tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents a switch-case statement in C.
- switch¶
- default¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CIncompleteSwitchCase(head, cases, tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents an incomplete switch-case construct; this only appear in the decompilation output when switch-case structuring fails (for whatever reason).
- head¶
-
cases:
list[tuple[int,CStatements]]¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CAssignment(lhs, rhs, tags=None, **kwargs)[源代码]¶
基类:
CStatementa = b
- lhs¶
- rhs¶
- tags¶
- 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)[源代码]¶
-
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().
- 参数:
- __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)[源代码]¶
- callee_target¶
- args¶
- returning¶
- ret_expr¶
- tags¶
- is_expr¶
- show_demangled_name¶
- show_disambiguated_name¶
- property prototype: SimTypeFunction | None¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CReturn(retval, tags=None, **kwargs)[源代码]¶
基类:
CStatement- retval¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CGoto(target, target_idx, tags=None, **kwargs)[源代码]¶
基类:
CStatement-
target:
int|CExpression¶
- target_idx¶
- tags¶
-
target:
- class angr.analyses.decompiler.structured_codegen.c.CUnsupportedStatement(stmt, **kwargs)[源代码]¶
基类:
CStatementA wrapper for unsupported AIL statement.
- stmt¶
- class angr.analyses.decompiler.structured_codegen.c.CDirtyStatement(dirty, **kwargs)[源代码]¶
基类:
CExpression- 参数:
dirty (CDirtyExpression)
- __init__(dirty, **kwargs)[源代码]¶
- 参数:
dirty (CDirtyExpression)
- dirty¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CLabel(name, ins_addr, block_idx, tags=None, **kwargs)[源代码]¶
基类:
CStatementRepresents a label in C code.
- name¶
- ins_addr¶
- block_idx¶
- tags¶
- class angr.analyses.decompiler.structured_codegen.c.CStructField(struct_type, offset, field, tags=None, **kwargs)[源代码]¶
基类:
CExpression- 参数:
struct_type (SimStruct)
- struct_type¶
- offset¶
- field¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CFakeVariable(name, ty, tags=None, **kwargs)[源代码]¶
基类:
CExpressionAn uninterpreted name to display in the decompilation output. Pretty much always represents an error?
- name¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CVariable(variable, unified_variable=None, variable_type=None, tags=None, vvar_id=None, **kwargs)[源代码]¶
基类:
CExpressionCVariable 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¶
- tags¶
- vvar_id¶
- property type¶
- property name¶
- class angr.analyses.decompiler.structured_codegen.c.CIndexedVariable(variable, index, variable_type=None, tags=None, **kwargs)[源代码]¶
基类:
CExpressionRepresent a variable (an array) that is indexed.
- 参数:
variable (CExpression)
index (CExpression)
- __init__(variable, index, variable_type=None, tags=None, **kwargs)[源代码]¶
- 参数:
variable (CExpression)
index (CExpression)
- property type¶
- collapsed¶
- class angr.analyses.decompiler.structured_codegen.c.CVariableField(variable, field, var_is_ptr=False, tags=None, **kwargs)[源代码]¶
基类:
CExpressionRepresent a field of a variable.
- 参数:
variable (CExpression)
field (CStructField)
var_is_ptr (bool)
- __init__(variable, field, var_is_ptr=False, tags=None, **kwargs)[源代码]¶
- 参数:
variable (CExpression)
field (CStructField)
var_is_ptr (bool)
- property type¶
- collapsed¶
- class angr.analyses.decompiler.structured_codegen.c.CUnaryOp(op, operand, tags=None, **kwargs)[源代码]¶
基类:
CExpressionUnary operations.
- 参数:
operand (CExpression)
- __init__(op, operand, tags=None, **kwargs)[源代码]¶
- 参数:
operand (CExpression)
- op¶
- operand¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CBinaryOp(op, lhs, rhs, tags=None, **kwargs)[源代码]¶
基类:
CExpressionBinary operations.
- 参数:
tags (dict | None)
- op¶
- lhs¶
- rhs¶
- tags¶
- common_type¶
- property type¶
- property op_precedence¶
- class angr.analyses.decompiler.structured_codegen.c.CTypeCast(src_type, dst_type, expr, tags=None, **kwargs)[源代码]¶
基类:
CExpression- 参数:
src_type (SimType | None)
dst_type (SimType)
expr (CExpression)
- __init__(src_type, dst_type, expr, tags=None, **kwargs)[源代码]¶
- 参数:
src_type (SimType | None)
dst_type (SimType)
expr (CExpression)
- src_type¶
- dst_type¶
- expr¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CConstant(value, type_, reference_values=None, tags=None, **kwargs)[源代码]¶
基类:
CExpression- value¶
- reference_values¶
- tags¶
- property fmt¶
- property fmt_hex¶
- property fmt_neg¶
- property fmt_char¶
- property fmt_float¶
- property fmt_double¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CRegister(reg, tags=None, **kwargs)[源代码]¶
基类:
CExpression- reg¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CITE(cond, iftrue, iffalse, tags=None, **kwargs)[源代码]¶
基类:
CExpression- cond¶
- iftrue¶
- iffalse¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CMultiStatementExpression(stmts, expr, tags=None, **kwargs)[源代码]¶
基类:
CExpression(stmt0, stmt1, stmt2, expr)
- 参数:
stmts (CStatements)
expr (CExpression)
- __init__(stmts, expr, tags=None, **kwargs)[源代码]¶
- 参数:
stmts (CStatements)
expr (CExpression)
- stmts¶
- expr¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CVEXCCallExpression(callee, operands, tags=None, **kwargs)[源代码]¶
基类:
CExpressionccall_name(arg0, arg1, ...)
- 参数:
callee (str)
operands (list[CExpression])
- __init__(callee, operands, tags=None, **kwargs)[源代码]¶
- 参数:
callee (str)
operands (list[CExpression])
- callee¶
- operands¶
- tags¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CDirtyExpression(dirty, **kwargs)[源代码]¶
基类:
CExpressionIdeally 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.
- dirty¶
- property type¶
- class angr.analyses.decompiler.structured_codegen.c.CClosingObject(opening_symbol)[源代码]¶
基类:
objectA class to represent all objects that can be closed by it's correspodning character. Examples: (), {}, []
- opening_symbol¶
- class angr.analyses.decompiler.structured_codegen.c.CArrayTypeLength(text)[源代码]¶
基类:
objectA class to represent the type information of fixed-size array lengths. Examples: In "char foo[20]", this would be the "[20]".
- text¶
- class angr.analyses.decompiler.structured_codegen.c.CStructFieldNameDef(name)[源代码]¶
基类:
objectA 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".
- 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- 参数:
func_args (list[SimVariable] | None)
binop_depth_cutoff (int)
- __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)[源代码]¶
- 参数:
func_args (list[SimVariable] | None)
binop_depth_cutoff (int)
- RENDER_TYPE¶
tuple[str,PositionMapping,PositionMapping,InstructionMapping,dict[Any,set[Any]]] 的别名
- class angr.analyses.decompiler.structured_codegen.c.MakeTypecastsImplicit[源代码]¶
-
- classmethod collapse(dst_ty, child)[源代码]¶
- 返回类型:
- 参数:
dst_ty (SimType)
child (CExpression)
- handle_CFunctionCall(obj)[源代码]¶
- 参数:
obj (CFunctionCall)
- class angr.analyses.decompiler.structured_codegen.c.PointerArithmeticFixer[源代码]¶
-
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.
- angr.analyses.decompiler.structured_codegen.c.StructuredCodeGenerator¶
- class angr.analyses.decompiler.structured_codegen.dwarf_import.ImportSourceCode(function, flavor='source', source_root=None, encoding='utf-8')[源代码]¶
- class angr.analyses.decompiler.structured_codegen.dummy.DummyStructuredCodeGenerator(flavor, expr_comments=None, stmt_comments=None, configuration=None, const_formats=None)[源代码]¶
基类:
BaseStructuredCodeGeneratorA dummy structured code generator that only stores user-specified information.
- 参数:
flavor (str)
- 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.
- 返回类型:
- 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.
- 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.first_nonlabel_node(seq)[源代码]¶
- 返回类型:
- 参数:
seq (SequenceNode)
- angr.analyses.decompiler.utils.first_nonlabel_nonphi_node(seq)[源代码]¶
- 返回类型:
- 参数:
seq (SequenceNode)
- 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)[源代码]¶
- 返回类型:
- 参数:
node (SequenceNode | MultiNode)
graph (DiGraph)
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.copy_graph(graph)[源代码]¶
Copy AIL Graph.
- 返回:
A copy of the AIl graph.
- 参数:
graph (DiGraph)
- 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.
- 返回类型:
- 返回:
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
- 返回类型:
- 参数:
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.
- 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.
- class angr.analyses.ddg.ProgramVariable(variable, location, initial=False, arch=None)[源代码]¶
基类:
objectDescribes a variable in the program at a specific location.
- 变量:
variable (SimVariable) -- The variable.
location (CodeLocation) -- Location of the variable.
- property short_repr¶
- class angr.analyses.ddg.LiveDefinitions[源代码]¶
基类:
objectA collection of live definitions with some handy interfaces for definition killing and lookups.
- branch()[源代码]¶
Create a branch of the current live definition collection.
- 返回:
A new LiveDefinition instance.
- 返回类型:
- 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
- 返回类型:
- 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
- 返回类型:
- 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.
- 返回类型:
- class angr.analyses.ddg.DDGViewItem(ddg, variable, simplified=False)[源代码]¶
基类:
object- property depends_on¶
- property dependents¶
- class angr.analyses.ddg.DDGViewInstruction(cfg, ddg, insn_addr, simplified=False)[源代码]¶
基类:
object- 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)[源代码]¶
基类:
objectA view of the data dependence graph.
- class angr.analyses.ddg.DDG(cfg, start=None, call_depth=None, block_addrs=None)[源代码]¶
基类:
AnalysisThis 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¶
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- class angr.analyses.flirt.FlirtAnalysis(sig=None)[源代码]¶
基类:
AnalysisFlirtAnalysis 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'>)¶
- op¶
- operands¶
- class angr.engines.light.data.RegisterOffset(bits, reg, offset)[源代码]¶
基类:
object- reg¶
- offset¶
- property bits¶
- property symbolic¶
- 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'>)¶
- op¶
- operands¶
- class angr.engines.light.RegisterOffset(bits, reg, offset)[源代码]¶
基类:
object- 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)¶
- process(state, *, block=None, **kwargs)[源代码]¶
The main entry point for an engine. Should take a state and return a result.
- lift(state)[源代码]¶
- 返回类型:
TypeVar(BlockType, bound=BlockProtocol)- 参数:
state (StateType)
- 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
- 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
- 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.engine.BlockProtocol(*args, **kwargs)[源代码]¶
基类:
ProtocolThe minimum protocol that a block an engine can process should adhere to. Requires just an addr attribute.
- __init__(*args, **kwargs)¶
- class angr.engines.light.engine.IRTop(ty)[源代码]¶
基类:
IRExprA dummy IRExpr used for intra-engine communication and code-reuse.
- 参数:
ty (str)
- 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)¶
- process(state, *, block=None, **kwargs)[源代码]¶
The main entry point for an engine. Should take a state and return a result.
- lift(state)[源代码]¶
- 返回类型:
TypeVar(BlockType, bound=BlockProtocol)- 参数:
state (StateType)
- 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
-
block:
TypeVar(BlockType, bound=BlockProtocol)¶
-
block:
- 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
- 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)[源代码]¶
-
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
- 参数:
- __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.vex_vars.VEXReg(offset, size)[源代码]¶
基类:
VEXVariable- offset¶
- size¶
- 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.
- 参数:
project (Project)
reaching_definitions (ReachingDefinitionsModel | None)
bp_as_gpr (bool)
- __init__(project, stack_pointer_tracker=None, propagate_tmps=True, reaching_definitions=None, bp_as_gpr=False)[源代码]¶
- 参数:
project (Project)
reaching_definitions (ReachingDefinitionsModel | None)
bp_as_gpr (bool)
- 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]- 参数:
project (Project)
reaching_definitions (ReachingDefinitionsModel | None)
bp_as_gpr (bool)
- 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)[源代码]¶
-
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
- 参数:
- __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)[源代码]¶
基类:
objectThis class represents a data storage location manipulated by IR instructions.
It could either be a Tmp (temporary variable), a Register, a MemoryLocation.
- size¶
- static from_ail_expr(expr, arch, full_reg=False)[源代码]¶
- 返回类型:
- 参数:
expr (Expression)
arch (Arch)
full_reg (bool)
- 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.
- 返回类型:
- 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.
- 返回类型:
- 返回:
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.
- 返回类型:
- 返回:
The Register Atom object.
- static mem(addr, size, endness=None)[源代码]¶
Create a MemoryLocation atom,
- 参数:
- 返回类型:
- 返回:
The MemoryLocation Atom object.
- static memory(addr, size, endness=None)¶
Create a MemoryLocation atom,
- 参数:
- 返回类型:
- 返回:
The MemoryLocation Atom object.
- class angr.analyses.reaching_definitions.AtomKind(value)[源代码]¶
基类:
EnumAn 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)[源代码]¶
基类:
AtomRepresents a constant.
- 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.
- 参数:
atom (A)
codeloc (CodeLocation)
dummy (bool)
- __init__(atom, codeloc, dummy=False, tags=None)[源代码]¶
- 参数:
atom (A)
codeloc (CodeLocation)
dummy (bool)
-
codeloc:
CodeLocation¶
- tags¶
- 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)[源代码]¶
基类:
objectA 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 (MultiValues[BV | FP] | None)
address (int | None)
symbol (Symbol | None)
function (Function | None)
name (str | None)
cc (SimCC | None)
prototype (SimTypeFunction | None)
args_values (list[MultiValues[BV | FP]] | None)
redefine_locals (bool)
effects (list[FunctionEffect])
ret_values (MultiValues[BV | FP] | None)
ret_values_deps (set[Definition] | None)
caller_will_handle_single_ret (bool)
guessed_cc (bool)
guessed_prototype (bool)
retaddr_popped (bool)
-
callsite_codeloc:
CodeLocation¶
-
function_codeloc:
CodeLocation¶
-
address_multi:
Optional[MultiValues[BV|FP]]¶
-
prototype:
SimTypeFunction|None= None¶
-
effects:
list[FunctionEffect]¶
-
ret_values:
Optional[MultiValues[BV|FP]] = None¶
-
ret_values_deps:
set[Definition] |None= None¶
- 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)[源代码]¶
- 返回类型:
- 参数:
prototype (SimTypeFunction)
state (ReachingDefinitionsState)
soft_reset (bool)
- __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)¶
- 参数:
callsite_codeloc (CodeLocation)
function_codeloc (CodeLocation)
address_multi (MultiValues[BV | FP] | None)
address (int | None)
symbol (Symbol | None)
function (Function | None)
name (str | None)
cc (SimCC | None)
prototype (SimTypeFunction | None)
args_values (list[MultiValues[BV | FP]] | None)
redefine_locals (bool)
effects (list[FunctionEffect])
ret_values (MultiValues[BV | FP] | None)
ret_values_deps (set[Definition] | None)
caller_will_handle_single_ret (bool)
guessed_cc (bool)
guessed_prototype (bool)
retaddr_popped (bool)
- 返回类型:
None
- class angr.analyses.reaching_definitions.FunctionHandler(interfunction_level=0, extra_impls=None)[源代码]¶
基类:
objectA mechanism for summarizing a function call's effect on a program for ReachingDefinitionsAnalysis.
- 参数:
interfunction_level (int)
extra_impls (Iterable[FunctionHandler] | None)
- __init__(interfunction_level=0, extra_impls=None)[源代码]¶
- 参数:
interfunction_level (int)
extra_impls (Iterable[FunctionHandler] | None)
- hook(analysis)[源代码]¶
Attach this instance of the function handler to an instance of RDA.
- 返回类型:
- 参数:
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.
- 参数:
target (None | int | MultiValues)
callsite (CodeLocation)
callsite_func_addr (int | None)
- 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.
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_generic_function(state, data)[源代码]¶
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_indirect_function(state, data)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_local_function(state, data)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_external_function(state, data)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- recurse_analysis(state, data)[源代码]¶
Precondition:
data.functionMUST NOT BE NONE in order to call this method.- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- static c_args_as_atoms(state, cc, prototype)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
cc (SimCC)
prototype (SimTypeFunction)
- static c_return_as_atoms(state, cc, prototype)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
cc (SimCC)
prototype (SimTypeFunction)
- static caller_saved_regs_as_atoms(state, cc)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
cc (SimCC)
- class angr.analyses.reaching_definitions.GuardUse(target)[源代码]¶
基类:
AtomImplements a guard use.
- 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)[源代码]¶
基类:
objectA LiveDefinitions instance contains definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.
- 参数:
arch (archinfo.Arch)
track_tmps (bool)
registers (MultiValuedMemory)
stack (MultiValuedMemory)
memory (MultiValuedMemory)
heap (MultiValuedMemory)
tmps (dict[int, set[Definition]])
others (dict[Atom, MultiValues])
tmp_uses (dict[int, set[CodeLocation]])
merge_into_tops (bool)
- 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)[源代码]¶
- 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¶
- 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.
- 返回类型:
- 返回:
True if the expression is TOP, False otherwise.
- static extract_defs_from_annotations(annos)[源代码]¶
- 返回类型:
- 参数:
annos (Iterable[Annotation])
- static extract_defs_from_mv(mv)[源代码]¶
- 返回类型:
- 参数:
mv (MultiValues)
- merge(*others)[源代码]¶
- 返回类型:
- 参数:
others (LiveDefinitions)
- compare(other)[源代码]¶
- 返回类型:
- 参数:
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.
- kill_and_add_definition(atom, code_loc, data, dummy=False, tags=None, endness=None, annotated=False)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
data (MultiValues)
- add_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
expr (Any | None)
- add_use_by_def(definition, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
definition (Definition)
code_loc (CodeLocation)
expr (Any | None)
- get_definitions(thing)[源代码]¶
- 返回类型:
- 参数:
thing (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | MultiValues)
- 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)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
- get_one_value(spec, strip_annotations=False)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
strip_annotations (bool)
- add_register_use(reg_offset, size, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
reg_offset (int)
size (int)
code_loc (CodeLocation)
expr (Any | None)
- add_register_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_stack_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_stack_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_heap_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_heap_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_memory_use(atom, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
atom (MemoryLocation)
code_loc (CodeLocation)
expr (Any | None)
- add_memory_use_by_def(def_, code_loc, expr=None)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
expr (Any | None)
- add_tmp_use(atom, code_loc)[源代码]¶
- 返回类型:
- 参数:
atom (Tmp)
code_loc (CodeLocation)
- add_tmp_use_by_def(def_, code_loc)[源代码]¶
- 返回类型:
- 参数:
def_ (Definition)
code_loc (CodeLocation)
- heap_address(offset)[源代码]¶
- 返回类型:
- 参数:
offset (int | HeapAddress)
- class angr.analyses.reaching_definitions.MemoryLocation(addr, size, endness=None)[源代码]¶
基类:
AtomRepresents a memory slice.
It is characterized by its address and its size.
- endness¶
- class angr.analyses.reaching_definitions.ObservationPointType(value)[源代码]¶
基类:
IntEnumEnum 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],AnalysisReachingDefinitionsAnalysis 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.
- 参数:
subject (Subject | ailment.Block | Block | Function | str)
observation_points (Iterable[ObservationPoint] | None)
init_state (ReachingDefinitionsState)
state_initializer (RDAStateInitializer | None)
function_handler (FunctionHandler | None)
interfunction_level (int)
track_liveness (bool)
func_addr (int | None)
element_limit (int)
merge_into_tops (bool)
- __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 blockfunc_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 all_definitions¶
- property all_uses¶
- property one_result¶
- property visited_blocks¶
- get_reaching_definitions(**kwargs)¶
- 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.
- 返回类型:
- insn_observe(insn_addr, stmt, block, state, op_type)[源代码]¶
- 参数:
insn_addr (
int) -- Address of the instruction.state (
ReachingDefinitionsState) -- The abstract analysis state.op_type (
ObservationPointType) -- Type of the observation point. Must be one of the following: OP_BEORE, OP_AFTER.
- 返回类型:
- stmt_observe(stmt_idx, stmt, block, state, op_type)[源代码]¶
- 参数:
stmt_idx (
int)state (
ReachingDefinitionsState)op_type (
ObservationPointType)
- 返回类型:
- 返回:
- property subject¶
- class angr.analyses.reaching_definitions.ReachingDefinitionsModel(func_addr=None, track_liveness=True)[源代码]¶
基类:
objectModels the definitions, uses, and memory of a ReachingDefinitionState object
- add_def(d)[源代码]¶
- 返回类型:
- 参数:
d (Definition)
- kill_def(d)[源代码]¶
- 返回类型:
- 参数:
d (Definition)
- at_new_stmt(codeloc)[源代码]¶
- 返回类型:
- 参数:
codeloc (CodeLocation)
- at_new_block(code_loc, pred_codelocs)[源代码]¶
- 返回类型:
- 参数:
code_loc (CodeLocation)
pred_codelocs (list[CodeLocation])
- find_defs_at(code_loc, op=ObservationPointType.OP_BEFORE)[源代码]¶
- 返回类型:
- 参数:
code_loc (CodeLocation)
op (int)
- get_defs(atom, code_loc, op)[源代码]¶
- 返回类型:
- 参数:
atom (Atom)
code_loc (CodeLocation)
op (int)
- merge(model)[源代码]¶
- 参数:
model (ReachingDefinitionsModel)
- get_observation_by_insn(ins_addr, kind)[源代码]¶
- 返回类型:
- 参数:
ins_addr (int | CodeLocation)
kind (ObservationPointType)
- get_observation_by_node(node_addr, kind, node_idx=None)[源代码]¶
- 返回类型:
- 参数:
node_addr (int | CodeLocation)
kind (ObservationPointType)
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)[源代码]¶
基类:
objectRepresents 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 (CodeLocation)
arch (Arch)
subject (Subject)
analysis (ReachingDefinitionsAnalysis)
track_tmps (bool)
track_consts (bool)
live_definitions (LiveDefinitions | None)
canonical_size (int)
heap_allocator (HeapAllocator | None)
environment (Environment | None)
sp_adjusted (bool)
all_definitions (set[Definition[A]] | None)
initializer (RDAStateInitializer | None)
element_limit (int)
merge_into_tops (bool)
- codeloc¶
- analysis¶
-
all_definitions:
set[Definition[Any]]¶
- heap_allocator¶
-
codeloc_uses:
set[Definition[Any]]¶
- live_definitions¶
- heap_address(offset)[源代码]¶
- 返回类型:
- 参数:
offset (int | HeapAddress)
- annotate_mv_with_def(mv, definition)[源代码]¶
- 返回类型:
MultiValues[TypeVar(MVType, bound=BV|FP)]- 参数:
mv (MultiValues[MVType])
definition (Definition[A])
- 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¶
- property environment¶
- property dep_graph¶
- compare(other)[源代码]¶
- 返回类型:
- 参数:
other (ReachingDefinitionsState)
- move_codelocs(new_codeloc)[源代码]¶
- 返回类型:
- 参数:
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.
- 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)]]]- 参数:
atom (Atom)
data (MultiValues)
annotated (bool)
uses (set[Definition[A]] | None)
override_codeloc (CodeLocation | None)
- add_use_by_def(definition, expr=None)[源代码]¶
- 返回类型:
- 参数:
definition (Definition[A])
expr (Any | None)
- add_tmp_use_by_defs(defs, expr=None)[源代码]¶
- 返回类型:
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_register_use_by_defs(defs, expr=None)[源代码]¶
- 返回类型:
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_stack_use_by_defs(defs, expr=None)[源代码]¶
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_heap_use_by_defs(defs, expr=None)[源代码]¶
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_memory_use_by_def(definition, expr=None)[源代码]¶
- 参数:
definition (Definition[A])
expr (Any | None)
- add_memory_use_by_defs(defs, expr=None)[源代码]¶
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- get_definitions(atom)[源代码]¶
- 返回类型:
- 参数:
atom (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]])
- get_values(spec)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A])
- get_one_value(spec, strip_annotations=False)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
strip_annotations (bool)
- pointer_to_atoms(**kwargs)¶
- pointer_to_atom(**kwargs)¶
- deref(pointer, size, endness=Endness.BE)[源代码]¶
- 参数:
pointer (MultiValues[BV] | Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | int | BV | HeapAddress | SpOffset)
endness (Endness)
- class angr.analyses.reaching_definitions.Register(reg_offset, size, arch=None)[源代码]¶
基类:
AtomRepresents 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 (RegisterOffset | int)
size (int)
arch (Arch | None)
- __init__(reg_offset, size, arch=None)[源代码]¶
- 参数:
size (
int) -- The size of the atom in bytesreg_offset (RegisterOffset | int)
arch (Arch | None)
- reg_offset¶
- arch¶
- class angr.analyses.reaching_definitions.Tmp(tmp_idx, size)[源代码]¶
基类:
AtomRepresents a variable used by the IR to store intermediate values.
- tmp_idx¶
- angr.analyses.reaching_definitions.get_all_definitions(region)[源代码]¶
- 返回类型:
- 参数:
region (MultiValuedMemory)
- class angr.analyses.reaching_definitions.call_trace.CallSite(caller_func_addr, block_addr, callee_func_addr)[源代码]¶
基类:
objectDescribes a call site on a CFG.
- caller_func_addr¶
- callee_func_addr¶
- block_addr¶
- class angr.analyses.reaching_definitions.call_trace.CallTrace(target)[源代码]¶
基类:
objectDescribes a series of functions calls to get from one function (current_function_address()) to another function or a basic block (self.target).
- 参数:
target (int)
- target¶
- 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.
- 参数:
function_handler (FunctionHandler)
functions (FunctionManager)
- __init__(project, function_handler, functions)[源代码]¶
- 参数:
function_handler (FunctionHandler)
functions (FunctionManager)
- 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],AnalysisReachingDefinitionsAnalysis 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.
- 参数:
subject (Subject | ailment.Block | Block | Function | str)
observation_points (Iterable[ObservationPoint] | None)
init_state (ReachingDefinitionsState)
state_initializer (RDAStateInitializer | None)
function_handler (FunctionHandler | None)
interfunction_level (int)
track_liveness (bool)
func_addr (int | None)
element_limit (int)
merge_into_tops (bool)
- __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 blockfunc_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 all_definitions¶
- property all_uses¶
- property one_result¶
- property visited_blocks¶
- get_reaching_definitions(**kwargs)¶
- 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.
- 返回类型:
- insn_observe(insn_addr, stmt, block, state, op_type)[源代码]¶
- 参数:
insn_addr (
int) -- Address of the instruction.state (
ReachingDefinitionsState) -- The abstract analysis state.op_type (
ObservationPointType) -- Type of the observation point. Must be one of the following: OP_BEORE, OP_AFTER.
- 返回类型:
- stmt_observe(stmt_idx, stmt, block, state, op_type)[源代码]¶
- 参数:
stmt_idx (
int)state (
ReachingDefinitionsState)op_type (
ObservationPointType)
- 返回类型:
- 返回:
- property subject¶
- 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])
-
callsite:
CodeLocation¶
-
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)¶
- 参数:
callsite (CodeLocation)
target (int | None)
args_defns (list[set[Definition]])
other_input_defns (set[Definition])
ret_defns (set[Definition])
other_output_defns (set[Definition])
- 返回类型:
None
- class angr.analyses.reaching_definitions.dep_graph.DepGraph(graph=None)[源代码]¶
基类:
objectThe 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.- 返回类型:
- 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.
- 返回类型:
- nodes()[源代码]¶
- 返回类型:
NodeView[Definition]
- predecessors(node)[源代码]¶
- 参数:
node (
Definition) -- The definition to get the predecessors of.- 返回类型:
- 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]]
- 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.
- find_definitions(**kwargs)[源代码]¶
Filter the definitions present in the graph based on various criteria. Parameters can be any valid keyword args to DefinitionMatchPredicate
- 返回类型:
- 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
- 返回类型:
- 参数:
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- 参数:
starts (Definition | Iterable[Definition])
ends (Definition | Iterable[Definition])
- 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.
- 返回类型:
- 参数:
starts (Definition | Iterable[Definition])
ends (Definition | Iterable[Definition])
- class angr.analyses.reaching_definitions.heap_allocator.HeapAllocator(canonical_size)[源代码]¶
基类:
objectA 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.- 返回类型:
- 返回:
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.
- 参数:
func (Function)
rda_model (ReachingDefinitionsModel)
- class angr.analyses.reaching_definitions.function_handler.FunctionEffect(dest, sources, value=None, sources_defns=None, apply_at_callsite=False, tags=None)[源代码]¶
基类:
objectA single effect that a function summary may apply to the state. This is largely an implementation detail; use FunctionCallData.depends instead.
- 参数:
dest (Atom | None)
value (MultiValues | None)
sources_defns (set[Definition] | None)
apply_at_callsite (bool)
-
value:
MultiValues|None= None¶
-
sources_defns:
set[Definition] |None= None¶
- __init__(dest, sources, value=None, sources_defns=None, apply_at_callsite=False, tags=None)¶
- 参数:
dest (Atom | None)
value (MultiValues | None)
sources_defns (set[Definition] | None)
apply_at_callsite (bool)
- 返回类型:
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)[源代码]¶
基类:
objectA 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 (MultiValues[BV | FP] | None)
address (int | None)
symbol (Symbol | None)
function (Function | None)
name (str | None)
cc (SimCC | None)
prototype (SimTypeFunction | None)
args_values (list[MultiValues[BV | FP]] | None)
redefine_locals (bool)
effects (list[FunctionEffect])
ret_values (MultiValues[BV | FP] | None)
ret_values_deps (set[Definition] | None)
caller_will_handle_single_ret (bool)
guessed_cc (bool)
guessed_prototype (bool)
retaddr_popped (bool)
-
callsite_codeloc:
CodeLocation¶
-
function_codeloc:
CodeLocation¶
-
address_multi:
Optional[MultiValues[BV|FP]]¶
-
prototype:
SimTypeFunction|None= None¶
-
effects:
list[FunctionEffect]¶
-
ret_values:
Optional[MultiValues[BV|FP]] = None¶
-
ret_values_deps:
set[Definition] |None= None¶
- 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)[源代码]¶
- 返回类型:
- 参数:
prototype (SimTypeFunction)
state (ReachingDefinitionsState)
soft_reset (bool)
- __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)¶
- 参数:
callsite_codeloc (CodeLocation)
function_codeloc (CodeLocation)
address_multi (MultiValues[BV | FP] | None)
address (int | None)
symbol (Symbol | None)
function (Function | None)
name (str | None)
cc (SimCC | None)
prototype (SimTypeFunction | None)
args_values (list[MultiValues[BV | FP]] | None)
redefine_locals (bool)
effects (list[FunctionEffect])
ret_values (MultiValues[BV | FP] | None)
ret_values_deps (set[Definition] | None)
caller_will_handle_single_ret (bool)
guessed_cc (bool)
guessed_prototype (bool)
retaddr_popped (bool)
- 返回类型:
None
- class angr.analyses.reaching_definitions.function_handler.FunctionCallDataUnwrapped(inner)[源代码]¶
-
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)[源代码]¶
基类:
objectA mechanism for summarizing a function call's effect on a program for ReachingDefinitionsAnalysis.
- 参数:
interfunction_level (int)
extra_impls (Iterable[FunctionHandler] | None)
- __init__(interfunction_level=0, extra_impls=None)[源代码]¶
- 参数:
interfunction_level (int)
extra_impls (Iterable[FunctionHandler] | None)
- hook(analysis)[源代码]¶
Attach this instance of the function handler to an instance of RDA.
- 返回类型:
- 参数:
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.
- 参数:
target (None | int | MultiValues)
callsite (CodeLocation)
callsite_func_addr (int | None)
- 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.
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_generic_function(state, data)[源代码]¶
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_indirect_function(state, data)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_local_function(state, data)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- handle_external_function(state, data)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- recurse_analysis(state, data)[源代码]¶
Precondition:
data.functionMUST NOT BE NONE in order to call this method.- 返回类型:
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- static c_args_as_atoms(state, cc, prototype)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
cc (SimCC)
prototype (SimTypeFunction)
- static c_return_as_atoms(state, cc, prototype)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
cc (SimCC)
prototype (SimTypeFunction)
- static caller_saved_regs_as_atoms(state, cc)[源代码]¶
- 返回类型:
- 参数:
state (ReachingDefinitionsState)
cc (SimCC)
- 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)[源代码]¶
基类:
objectRepresents 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 (CodeLocation)
arch (Arch)
subject (Subject)
analysis (ReachingDefinitionsAnalysis)
track_tmps (bool)
track_consts (bool)
live_definitions (LiveDefinitions | None)
canonical_size (int)
heap_allocator (HeapAllocator | None)
environment (Environment | None)
sp_adjusted (bool)
all_definitions (set[Definition[A]] | None)
initializer (RDAStateInitializer | None)
element_limit (int)
merge_into_tops (bool)
- codeloc¶
- analysis¶
-
all_definitions:
set[Definition[Any]]¶
- heap_allocator¶
-
codeloc_uses:
set[Definition[Any]]¶
- live_definitions¶
- heap_address(offset)[源代码]¶
- 返回类型:
- 参数:
offset (int | HeapAddress)
- annotate_mv_with_def(mv, definition)[源代码]¶
- 返回类型:
MultiValues[TypeVar(MVType, bound=BV|FP)]- 参数:
mv (MultiValues[MVType])
definition (Definition[A])
- 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¶
- property environment¶
- property dep_graph¶
- compare(other)[源代码]¶
- 返回类型:
- 参数:
other (ReachingDefinitionsState)
- move_codelocs(new_codeloc)[源代码]¶
- 返回类型:
- 参数:
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.
- 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)]]]- 参数:
atom (Atom)
data (MultiValues)
annotated (bool)
uses (set[Definition[A]] | None)
override_codeloc (CodeLocation | None)
- add_use_by_def(definition, expr=None)[源代码]¶
- 返回类型:
- 参数:
definition (Definition[A])
expr (Any | None)
- add_tmp_use_by_defs(defs, expr=None)[源代码]¶
- 返回类型:
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_register_use_by_defs(defs, expr=None)[源代码]¶
- 返回类型:
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_stack_use_by_defs(defs, expr=None)[源代码]¶
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_heap_use_by_defs(defs, expr=None)[源代码]¶
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- add_memory_use_by_def(definition, expr=None)[源代码]¶
- 参数:
definition (Definition[A])
expr (Any | None)
- add_memory_use_by_defs(defs, expr=None)[源代码]¶
- 参数:
defs (Iterable[Definition[A]])
expr (Any | None)
- get_definitions(atom)[源代码]¶
- 返回类型:
- 参数:
atom (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]])
- get_values(spec)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A])
- get_one_value(spec, strip_annotations=False)[源代码]¶
- 返回类型:
- 参数:
spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])
strip_annotations (bool)
- pointer_to_atoms(**kwargs)¶
- pointer_to_atom(**kwargs)¶
- deref(pointer, size, endness=Endness.BE)[源代码]¶
- 参数:
pointer (MultiValues[BV] | Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | int | BV | HeapAddress | SpOffset)
endness (Endness)
- class angr.analyses.reaching_definitions.subject.SubjectType(value)[源代码]¶
基类:
EnumAn 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]- 参数:
function_handler (FunctionHandler)
bp_as_gpr (bool)
- __init__(project, function_handler, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, bp_as_gpr=False)[源代码]¶
- 参数:
function_handler (FunctionHandler)
bp_as_gpr (bool)
- class angr.analyses.cfg_slice_to_sink.CFGSliceToSink(target, transitions=None)[源代码]¶
基类:
objectThe 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_as_tuples¶
The list of transitions as pairs of (source, destination).
- property target¶
return angr.knowledge_plugins.functions.function.Function: The targeted sink function, from which the slice is constructed.
- property entrypoints¶
Entrypoints are all source addresses that are not the destination address of any transition.
- Return List[int]:
The list of entrypoints addresses.
- 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.
- 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)[源代码]¶
基类:
objectThe 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_as_tuples¶
The list of transitions as pairs of (source, destination).
- property target¶
return angr.knowledge_plugins.functions.function.Function: The targeted sink function, from which the slice is constructed.
- property entrypoints¶
Entrypoints are all source addresses that are not the destination address of any transition.
- Return List[int]:
The list of entrypoints addresses.
- 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.
- 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.
- class angr.analyses.stack_pointer_tracker.BottomType[源代码]¶
基类:
objectThe bottom value for register values.
- class angr.analyses.stack_pointer_tracker.Constant(val)[源代码]¶
基类:
objectRepresents a constant value.
- val¶
- class angr.analyses.stack_pointer_tracker.Register(offset, bitlen)[源代码]¶
基类:
objectRepresent a register.
- offset¶
- bitlen¶
- class angr.analyses.stack_pointer_tracker.OffsetVal(reg, offset)[源代码]¶
基类:
objectRepresent a value with an offset added.
- property reg¶
- property offset¶
- class angr.analyses.stack_pointer_tracker.Eq(val0, val1)[源代码]¶
基类:
objectRepresent an equivalence condition.
- val0¶
- val1¶
- class angr.analyses.stack_pointer_tracker.FrozenStackPointerTrackerState(regs, memory, is_tracking_memory, resilient)[源代码]¶
基类:
objectAbstract state for StackPointerTracker analysis with registers and memory values being in frozensets.
- regs¶
- memory¶
- is_tracking_memory¶
- resilient¶
- class angr.analyses.stack_pointer_tracker.StackPointerTrackerState(regs, memory, is_tracking_memory, resilient)[源代码]¶
基类:
objectAbstract state for StackPointerTracker analysis.
- 参数:
resilient (bool)
- regs¶
- memory¶
- is_tracking_memory¶
- resilient¶
- exception angr.analyses.stack_pointer_tracker.CouldNotResolveException[源代码]¶
基类:
ExceptionAn 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)[源代码]¶
-
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)[源代码]¶
- property inconsistent¶
- class angr.analyses.variable_recovery.annotations.StackLocationAnnotation(offset)[源代码]¶
基类:
Annotation- 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- 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.
- 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.
- 返回类型:
- class angr.analyses.variable_recovery.variable_recovery_base.VariableAnnotation(addr_and_variables)[源代码]¶
基类:
Annotation- 参数:
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)[源代码]¶
基类:
AnalysisThe base class for VariableRecovery and VariableRecoveryFast.
- 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)[源代码]¶
基类:
objectThe base abstract state for variable recovery analysis.
- 参数:
block_addr (int)
analysis (VariableRecoveryBase)
arch (archinfo.Arch)
func (Function)
project (Project)
- __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)[源代码]¶
- 参数:
block_addr (int)
analysis (VariableRecoveryBase)
arch (Arch)
func (Function)
project (Project)
- 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_for_function(func_typevar, constraint)[源代码]¶
Add a new type constraint for a specified function.
- 参数:
func_typevar
constraint
- 返回:
- 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.- 返回类型:
- 返回:
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)[源代码]¶
-
The abstract state of variable recovery analysis.
- 变量:
stack_region (KeyedRegion) -- The stack store.
register_region (KeyedRegion) -- The register store.
- __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)[源代码]¶
- 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.- 返回类型:
- 返回:
The merged abstract state.
- 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,VariableRecoveryBaseRecover "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.- 参数:
func_graph (networkx.DiGraph | None)
max_iterations (int)
func_args (list[SimVariable] | None)
func_arg_vvars (dict[int, tuple[VirtualVariable, SimVariable]] | None)
- __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
- 参数:
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_graph (DiGraph | None)
max_iterations (int)
func_args (list[SimVariable] | None)
func_arg_vvars (dict[int, tuple[VirtualVariable, SimVariable]] | None)
- 返回:
None
- class angr.analyses.variable_recovery.variable_recovery.VariableRecoveryState(project, block_addr, analysis, arch, func, concrete_states, stack_region=None, register_region=None)[源代码]¶
-
The abstract state of variable recovery analysis.
- 变量:
variable_manager (angr.knowledge.variable_manager.VariableManager) -- The variable manager.
- 参数:
project (angr.Project)
block_addr (int)
arch (archinfo.Arch)
func (Function)
- __init__(project, block_addr, analysis, arch, func, concrete_states, stack_region=None, register_region=None)[源代码]¶
- property 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,VariableRecoveryBaseRecover "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.
- 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.
- 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]¶
- 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.
- 参数:
data (RichRT_co)
typevar (typeconsts.TypeConstant | typevars.TypeVariable | None)
type_constraints (set[typevars.TypeConstraint] | None)
- __init__(data, variable=None, typevar=None, type_constraints=None)[源代码]¶
- 参数:
data (RichRT_co)
typevar (TypeConstant | TypeVariable | None)
type_constraints (set[TypeConstraint] | None)
- data¶
- variable¶
- typevar¶
- type_constraints¶
- 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¶
- property func_addr¶
- 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.
- class angr.analyses.variable_recovery.VariableRecovery(func, max_iterations=20, store_live_variables=False)[源代码]¶
基类:
ForwardAnalysis,VariableRecoveryBaseRecover "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.
- 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,VariableRecoveryBaseRecover "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.- 参数:
func_graph (networkx.DiGraph | None)
max_iterations (int)
func_args (list[SimVariable] | None)
func_arg_vvars (dict[int, tuple[VirtualVariable, SimVariable]] | None)
- __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
- 参数:
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_graph (DiGraph | None)
max_iterations (int)
func_args (list[SimVariable] | None)
func_arg_vvars (dict[int, tuple[VirtualVariable, SimVariable]] | None)
- 返回:
None
- class angr.analyses.typehoon.lifter.TypeLifter(bits)[源代码]¶
基类:
objectLift SimTypes to type constants.
- 参数:
bits (int)
- bits¶
- memo¶
- class angr.analyses.typehoon.simple_solver.SketchNodeBase[源代码]¶
基类:
objectThe base class for nodes in a sketch.
- class angr.analyses.typehoon.simple_solver.SketchNode(typevar)[源代码]¶
-
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)[源代码]¶
-
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)[源代码]¶
基类:
objectDescribes the sketch of a type variable.
- 参数:
solver (SimpleSolver)
root (TypeVariable)
- __init__(solver, root)[源代码]¶
- 参数:
solver (SimpleSolver)
root (TypeVariable)
-
root:
SketchNode¶
- graph¶
-
node_mapping:
dict[TypeVariable|DerivedTypeVariable,SketchNodeBase]¶
- solver¶
- lookup(typevar)[源代码]¶
- 返回类型:
- 参数:
typevar (TypeVariable | DerivedTypeVariable)
- add_edge(src, dst, label)[源代码]¶
- 返回类型:
- 参数:
src (SketchNodeBase)
dst (SketchNodeBase)
- add_constraint(constraint)[源代码]¶
- 返回类型:
- 参数:
constraint (TypeConstraint)
- static flatten_typevar(derived_typevar)[源代码]¶
- 返回类型:
- 参数:
derived_typevar (TypeVariable | TypeConstant | DerivedTypeVariable)
- class angr.analyses.typehoon.simple_solver.ConstraintGraphTag(value)[源代码]¶
基类:
EnumAn enumeration.
- LEFT = 0¶
- RIGHT = 1¶
- UNKNOWN = 2¶
- class angr.analyses.typehoon.simple_solver.FORGOTTEN(value)[源代码]¶
基类:
EnumAn enumeration.
- PRE_FORGOTTEN = 0¶
- POST_FORGOTTEN = 1¶
- class angr.analyses.typehoon.simple_solver.ConstraintGraphNode(typevar, variance, tag, forgotten)[源代码]¶
基类:
object- 参数:
typevar (TypeVariable | DerivedTypeVariable)
variance (Variance)
tag (ConstraintGraphTag)
forgotten (FORGOTTEN)
- __init__(typevar, variance, tag, forgotten)[源代码]¶
- 参数:
typevar (TypeVariable | DerivedTypeVariable)
variance (Variance)
tag (ConstraintGraphTag)
forgotten (FORGOTTEN)
- typevar¶
- variance¶
- tag¶
- forgotten¶
- class angr.analyses.typehoon.simple_solver.SimpleSolver(bits, constraints, typevars)[源代码]¶
基类:
objectSimpleSolver 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)
- 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]]- 参数:
typevars (set[TypeVariable])
constraints (set[TypeConstraint])
- 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)[源代码]¶
- 返回类型:
- 参数:
t1 (TypeConstant | TypeVariable)
t2 (TypeConstant | TypeVariable)
- meet(t1, t2)[源代码]¶
- 返回类型:
- 参数:
t1 (TypeConstant | TypeVariable)
t2 (TypeConstant | TypeVariable)
- static abstract(t)[源代码]¶
- 返回类型:
- 参数:
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
- class angr.analyses.typehoon.translator.SimTypeTempRef(typevar)[源代码]¶
基类:
SimTypeRepresents a temporary reference to another type. TypeVariableReference is translated to SimTypeTempRef.
- class angr.analyses.typehoon.translator.TypeTranslator(arch=None)[源代码]¶
基类:
objectTranslate type variables to SimType equivalence.
- backpatch(st, translated)[源代码]¶
- 参数:
st (sim_type.SimType)
translated (dict)
- 返回:
- class angr.analyses.typehoon.typevars.Subtype(sub_type, super_type)[源代码]¶
-
- 参数:
sub_type (TypeType)
super_type (TypeType)
- __init__(sub_type, super_type)[源代码]¶
- 参数:
sub_type (TypeConstant | TypeVariable | DerivedTypeVariable)
super_type (TypeConstant | TypeVariable | DerivedTypeVariable)
- super_type¶
- sub_type¶
- class angr.analyses.typehoon.typevars.Add(type_0, type_1, type_r)[源代码]¶
-
Describes the constraint that type_r == type0 + type1
- type_0¶
- type_1¶
- type_r¶
- class angr.analyses.typehoon.typevars.Sub(type_0, type_1, type_r)[源代码]¶
-
Describes the constraint that type_r == type0 - type1
- type_0¶
- type_1¶
- type_r¶
- class angr.analyses.typehoon.typevars.DerivedTypeVariable(type_var, label, labels=None, idx=None)[源代码]¶
基类:
TypeVariable- __init__(type_var, label, labels=None, idx=None)[源代码]¶
- 参数:
type_var (TypeConstant | TypeVariable | DerivedTypeVariable)
label (BaseLabel | None)
- type_var¶
- longest_prefix()[源代码]¶
- 返回类型:
Union[TypeConstant,TypeVariable,DerivedTypeVariable,None]
- class angr.analyses.typehoon.typevars.TypeVariables[源代码]¶
基类:
object- add_type_variable(var, codeloc, typevar)[源代码]¶
- 参数:
var (SimVariable)
typevar (TypeConstant | TypeVariable | DerivedTypeVariable)
- has_type_variable_for(var, codeloc)[源代码]¶
- 参数:
var (SimVariable)
- class angr.analyses.typehoon.typevars.ReinterpretAs(to_type, to_bits)[源代码]¶
基类:
BaseLabel- to_type¶
- to_bits¶
- class angr.analyses.typehoon.typehoon.Typehoon(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]¶
基类:
AnalysisA 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.
- 参数:
var_mapping (dict[SimVariable, set[TypeVariable]] | None)
must_struct (set[TypeVariable] | None)
- __init__(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]¶
- 参数:
constraints
ground_truth -- A set of SimType-style solutions for some or all type variables. They will be respected during type solving.
var_mapping (
Optional[dict[SimVariable,set[TypeVariable]]])must_struct (
Optional[set[TypeVariable]])
All type constants used in type inference. They can be mapped, translated, or rewritten to C-style types.
- 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.FloatBase[源代码]¶
基类:
TypeConstant
- class angr.analyses.typehoon.typeconsts.Pointer(basetype)[源代码]¶
基类:
TypeConstant- 参数:
basetype (TypeConstant | None)
- __init__(basetype)[源代码]¶
- 参数:
basetype (TypeConstant | None)
- class angr.analyses.typehoon.typeconsts.Array(element=None, count=None)[源代码]¶
基类:
TypeConstant
- class angr.analyses.typehoon.typeconsts.Struct(fields=None, name=None, field_names=None)[源代码]¶
基类:
TypeConstant
- class angr.analyses.typehoon.typeconsts.Function(params, outputs)[源代码]¶
基类:
TypeConstant
- class angr.analyses.typehoon.typeconsts.TypeVariableReference(typevar)[源代码]¶
基类:
TypeConstant
- class angr.analyses.typehoon.Typehoon(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]¶
基类:
AnalysisA 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.
- 参数:
var_mapping (dict[SimVariable, set[TypeVariable]] | None)
must_struct (set[TypeVariable] | None)
- __init__(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]¶
- 参数:
constraints
ground_truth -- A set of SimType-style solutions for some or all type variables. They will be respected during type solving.
var_mapping (
Optional[dict[SimVariable,set[TypeVariable]]])must_struct (
Optional[set[TypeVariable]])
- class angr.analyses.identifier.identify.Identifier(cfg=None, require_predecessors=True, only_find=None)[源代码]¶
基类:
Analysis- 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
- class angr.analyses.loopfinder.Loop(entry, entry_edges, break_edges, continue_edges, body_nodes, graph, subloops)[源代码]¶
基类:
object
- class angr.analyses.loopfinder.LoopFinder(functions=None, normalize=True)[源代码]¶
基类:
AnalysisExtracts all the loops from all the functions in a binary.
- class angr.analyses.loop_analysis.VariableTypes[源代码]¶
基类:
object- Iterator = 'Iterator'¶
- HasNext = 'HasNext'¶
- Next = 'Next'¶
- class angr.analyses.loop_analysis.AnnotatedVariable(variable, type_)[源代码]¶
基类:
object- variable¶
- type¶
- class angr.analyses.loop_analysis.Condition(op, val0, val1)[源代码]¶
基类:
object- Equal = '=='¶
- NotEqual = '!='¶
- class angr.analyses.loop_analysis.LoopAnalysis(loop, defuse)[源代码]¶
-
Analyze a loop and recover important information about the loop (e.g., invariants, induction variables) in a static manner.
- class angr.analyses.veritesting.CallTracingFilter(project, depth, blacklist=None)[源代码]¶
基类:
objectFilter 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 = {}¶
- class angr.analyses.veritesting.Veritesting(input_state, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None)[源代码]¶
基类:
AnalysisAn 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)[源代码]¶
基类:
CFGJobBaseA job descriptor that contains local variables used during VFG analysis.
- callstack_repr(kb)[源代码]¶
- 参数:
kb (KnowledgeBase)
- class angr.analyses.vfg.PendingJob(block_id, state, call_stack, src_block_id, src_stmt_idx, src_ins_addr)[源代码]¶
基类:
objectDescribes a pending job during VFG analysis.
- 参数:
- block_id¶
- state¶
- call_stack¶
- src_block_id¶
- src_stmt_idx¶
- src_ins_addr¶
- class angr.analyses.vfg.AnalysisTask[源代码]¶
基类:
objectAn analysis task describes a task that should be done before popping this task out of the task stack and discard it.
- property done¶
- class angr.analyses.vfg.FunctionAnalysis(function_address, return_address)[源代码]¶
基类:
AnalysisTaskAnalyze a function, generate fix-point states from all endpoints of that function, and then merge them to one state.
- class angr.analyses.vfg.CallAnalysis(address, return_address, function_analysis_tasks=None, mergeable_plugins=None)[源代码]¶
基类:
AnalysisTaskAnalyze 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.
- 参数:
- register_function_analysis(task)[源代码]¶
- 返回类型:
- 参数:
task (FunctionAnalysis)
- class angr.analyses.vfg.VFGNode(addr, key, state=None)[源代码]¶
基类:
objectA descriptor of nodes in a Value-Flow Graph
- 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],AnalysisThis 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}.
- 参数:
cfg (CFGEmulated | None)
context_sensitivity_level (int)
start (int | None)
function_start (int | None)
interfunction_level (int)
initial_state (SimState | None)
timeout (int | None)
max_iterations_before_widening (int)
max_iterations (int)
widening_interval (int)
final_state_callback (Callable[[SimState, CallStack], Any] | None)
record_function_final_states (bool)
- __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 beinitial_state (
Optional[SimState]) -- A state to use as the initial oneremove_options (
Optional[set[str]]) -- State options to remove from the initial state. It only works when initial_state is Nonetimeout (int)
final_state_callback (
Optional[Callable[[SimState,CallStack],Any]]) -- callback function when countering final statestatus_callback (
Optional[Callable[[VFG],Any]]) -- callback function used in _analysis_core_baremetalstart (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¶
- class angr.analyses.vsa_ddg.DefUseChain(def_loc, use_loc, variable)[源代码]¶
基类:
objectStand for a def-use chain. it is generated by the DDG itself.
- class angr.analyses.vsa_ddg.VSA_DDG(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)[源代码]¶
基类:
AnalysisA 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".
- class angr.analyses.vtable.Vtable(vaddr, size, func_addrs=None)[源代码]¶
基类:
objectThis contains the addr, size and function addresses of a Vtable
- class angr.analyses.vtable.VtableFinder[源代码]¶
基类:
AnalysisThis analysis locates Vtables in a binary based on heuristics taken from - "Reconstruction of Class Hierarchies for Decompilation of C++ Programs"
- class angr.analyses.find_objects_static.PossibleObject(size, addr, class_name=None)[源代码]¶
基类:
objectThis 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
- class angr.analyses.find_objects_static.NewFunctionHandler(max_addr=None, new_func_addr=None, project=None)[源代码]¶
-
- 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)
- handle_local_function(state, data)[源代码]¶
- 参数:
state (ReachingDefinitionsState)
data (FunctionCallData)
- 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
- class angr.analyses.class_identifier.ClassIdentifier[源代码]¶
基类:
AnalysisThis 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
- class angr.analyses.disassembly.IROp(addr, seq, obj, irsb)[源代码]¶
- class angr.analyses.disassembly.Instruction(insn, parentblock, project=None)[源代码]¶
-
- property mnemonic¶
- class angr.analyses.disassembly.SootExpressionInvoke(invoke_type, expr)[源代码]¶
-
- Virtual = 'virtual'¶
- Static = 'static'¶
- Special = 'special'¶
- class angr.analyses.disassembly.RegisterOperand(op_num, children, parentinsn)[源代码]¶
基类:
Operand- property register¶
- class angr.analyses.disassembly.Register(reg, prefix='')[源代码]¶
基类:
OperandPiece
- class angr.analyses.disassembly.Value(val, render_with_sign)[源代码]¶
基类:
OperandPiece- property project¶
- class angr.analyses.disassembly.Disassembly(function=None, ranges=None, thumb=False, include_ir=False, block_bytes=None)[源代码]¶
基类:
AnalysisProduce formatted machine code disassembly.
- 参数:
- exception angr.analyses.reassembler.InstructionError[源代码]¶
基类:
BinaryError
- exception angr.analyses.reassembler.ReassemblerFailureNotice[源代码]¶
基类:
BinaryError
- class angr.analyses.reassembler.Label(binary, name, original_addr=None)[源代码]¶
基类:
object- g_label_ctr = count(0)¶
- property operand_str¶
- property offset¶
- class angr.analyses.reassembler.DataLabel(binary, original_addr, name=None)[源代码]¶
基类:
Label- property operand_str¶
- class angr.analyses.reassembler.FunctionLabel(binary, function_name, original_addr, plt=False)[源代码]¶
基类:
Label- property function_name¶
- property operand_str¶
- class angr.analyses.reassembler.ObjectLabel(binary, symbol_name, original_addr, plt=False)[源代码]¶
基类:
Label- property symbol_name¶
- property operand_str¶
- class angr.analyses.reassembler.NotypeLabel(binary, symbol_name, original_addr, plt=False)[源代码]¶
基类:
Label- property symbol_name¶
- property operand_str¶
- class angr.analyses.reassembler.SymbolManager(binary, cfg)[源代码]¶
基类:
objectSymbolManager manages all symbols in the binary.
- __init__(binary, cfg)[源代码]¶
Constructor.
- 参数:
binary (Reassembler) -- The Binary analysis instance.
cfg (angr.analyses.CFG) -- The CFG analysis instance.
- 返回:
None
- label_got(addr, label)[源代码]¶
Mark a certain label as assigned (to an instruction or a block of data).
- 参数:
addr (int) -- The address of the label.
label (angr.analyses.reassembler.Label) -- The label that is just assigned.
- 返回:
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
- property is_immediate¶
- property symbolized¶
- class angr.analyses.reassembler.Instruction(binary, addr, size, insn_bytes, capstone_instr)[源代码]¶
基类:
objectHigh-level representation of an instruction in the binary
- class angr.analyses.reassembler.BasicBlock(binary, addr, size, x86_getpc_retsite=False)[源代码]¶
基类:
objectBasicBlock represents a basic block in the binary.
- 参数:
x86_getpc_retsite (bool)
- class angr.analyses.reassembler.Procedure(binary, function=None, addr=None, size=None, name=None, section='.text', asm_code=None)[源代码]¶
基类:
objectProcedure 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
- class angr.analyses.reassembler.ProcedureChunk(project, addr, size)[源代码]¶
基类:
ProcedureProcedure chunk.
- 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¶
- class angr.analyses.reassembler.Reassembler(syntax='intel', remove_cgc_attachments=True, log_relocations=True)[源代码]¶
基类:
AnalysisHigh-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.
- property instructions¶
Get a list of all instructions in the binary
- 返回:
A list of (address, instruction)
- 返回类型:
- 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.
- 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.
- 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.
- 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.
- append_data(name, initial_content, size, readonly=False, sort='unknown')[源代码]¶
Append a new data entry into the binary with specific name, content, and size.
- remove_cgc_attachments()[源代码]¶
Remove CGC attachments.
- 返回:
True if CGC attachments are found and removed, False otherwise
- 返回类型:
- class angr.analyses.congruency_check.CongruencyCheck(throw=False)[源代码]¶
基类:
AnalysisThis 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.
- class angr.analyses.static_hooker.StaticHooker(library, binary=None)[源代码]¶
基类:
AnalysisThis 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!
- class angr.analyses.binary_optimizer.ConstantPropagation(constant, constant_assignment_loc, constant_consuming_loc)[源代码]¶
基类:
object
- class angr.analyses.binary_optimizer.RedundantStackVariable(argument, stack_variable, stack_variable_consuming_locs)[源代码]¶
基类:
object
- 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.
- 参数:
stack_variable (SimStackVariable)
register_variable (SimRegisterVariable)
stack_variable_sources (list)
stack_variable_consumers (list)
prologue_addr (int)
prologue_size (int)
epilogue_addr (int)
epilogue_size (int)
- 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)[源代码]¶
基类:
AnalysisThis 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¶
- project: Project¶
- kb: KnowledgeBase¶
- class angr.analyses.callee_cleanup_finder.CalleeCleanupFinder(starts=None, hook_all=False)[源代码]¶
基类:
Analysis
- class angr.analyses.dominance_frontier.DominanceFrontier(func, func_graph=None, entry=None, exception_edges=False)[源代码]¶
基类:
AnalysisComputes the dominance frontier of all nodes in a function graph, and provides an easy-to-use interface for querying the frontier information.
- class angr.analyses.init_finder.SimEngineInitFinderVEX(project, replacements, overlay, pointers_only=False)[源代码]¶
基类:
SimEngineNostmtVEX[None,Base|int|None,None]The VEX engine class for InitFinder.
- class angr.analyses.init_finder.InitializationFinder(func=None, func_graph=None, block=None, max_iterations=1, replacements=None, overlay=None, pointers_only=False)[源代码]¶
-
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.
- class angr.analyses.xrefs.XRefsAnalysis(func=None, func_graph=None, block=None, max_iterations=1, replacements=None)[源代码]¶
-
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[源代码]¶
基类:
objectNode 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)[源代码]¶
基类:
objectBase class for all nodes in a proximity graph.
- class angr.analyses.proximity_graph.FunctionProxiNode(func, ref_at=None)[源代码]¶
-
Proximity node showing current and expanded function calls in graph.
- class angr.analyses.proximity_graph.VariableProxiNode(addr, name, ref_at=None)[源代码]¶
-
Variable arg node
- class angr.analyses.proximity_graph.StringProxiNode(addr, content, ref_at=None)[源代码]¶
-
String arg node
- class angr.analyses.proximity_graph.CallProxiNode(callee, ref_at=None, args=None)[源代码]¶
-
Call node
- 参数:
args (tuple[BaseProxiNode] | None)
- class angr.analyses.proximity_graph.UnknownProxiNode(dummy_value)[源代码]¶
-
Unknown arg node
- 参数:
dummy_value (str)
- class angr.analyses.proximity_graph.ProximityGraphAnalysis(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]¶
基类:
AnalysisGenerate a proximity graph.
- 参数:
func (Function)
cfg_model (CFGModel)
xrefs (XRefManager)
decompilation (Decompiler | None)
- __init__(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]¶
- 参数:
func (Function)
cfg_model (CFGModel)
xrefs (XRefManager)
decompilation (Decompiler | None)
Defines analysis that will generate a dynamic data-dependency graph
- class angr.analyses.data_dep.data_dependency_analysis.NodalAnnotation(node)[源代码]¶
基类:
AnnotationAllows a node to be stored as an annotation to a BV in a DefaultMemory instance
- 参数:
node (BaseDepNode)
- __init__(node)[源代码]¶
- 参数:
node (BaseDepNode)
- 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)[源代码]¶
基类:
AnalysisThis 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 SimActionDatastart_from (
Optional[int]) -- An address or None, Specifies where to start generation of DDGend_at (
Optional[int]) -- An address or None, Specifies where to end generation of DDGblock_addrs (list[int] | None) -- List of block addresses that the DDG analysis should be run on
block_addrs
- class angr.analyses.data_dep.sim_act_location.SimActLocation(bbl_addr, ins_addr, stmt_idx)[源代码]¶
基类:
objectStructure-like class used to bundle the instruction address and statement index of a given SimAction in order to uniquely identify a given SimAction
- class angr.analyses.data_dep.sim_act_location.ParsedInstruction(ins_addr, min_stmt_idx, max_stmt_idx)[源代码]¶
基类:
objectUsed by parser to facilitate linking with recent ancestors in an efficient manner
- class angr.analyses.data_dep.dep_nodes.DepNodeTypes[源代码]¶
基类:
objectEnumeration 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)[源代码]¶
基类:
objectBase class for all nodes in a data-dependency graph
- 参数:
type_ (int)
sim_act (SimActionData)
- __init__(type_, sim_act)[源代码]¶
- 参数:
type_ (int)
sim_act (SimActionData)
- class angr.analyses.data_dep.dep_nodes.ConstantDepNode(sim_act, value)[源代码]¶
基类:
BaseDepNodeUsed to create a DepNode that will hold a constant, numeric value Uniquely identified by its value
- 参数:
sim_act (SimActionData)
value (int)
- __init__(sim_act, value)[源代码]¶
- 参数:
sim_act (SimActionData)
value (int)
- class angr.analyses.data_dep.dep_nodes.MemDepNode(sim_act, addr)[源代码]¶
基类:
BaseDepNodeUsed to represent SimActions of type MEM
- 参数:
sim_act (SimActionData)
addr (int)
- __init__(sim_act, addr)[源代码]¶
- 参数:
sim_act (SimActionData)
addr (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='')[源代码]¶
基类:
BaseDepNodeAbstract class for representing SimActions of TYPE reg or tmp
- 参数:
type_ (int)
sim_act (SimActionData)
reg (int)
arch_name (str)
- class angr.analyses.data_dep.dep_nodes.TmpDepNode(sim_act, reg, arch_name='')[源代码]¶
基类:
VarDepNodeUsed to represent SimActions of type TMP
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- __init__(sim_act, reg, arch_name='')[源代码]¶
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- class angr.analyses.data_dep.dep_nodes.RegDepNode(sim_act, reg, arch_name='')[源代码]¶
基类:
VarDepNodeBase class for representing SimActions of TYPE reg
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- __init__(sim_act, reg, arch_name='')[源代码]¶
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- class angr.analyses.data_dep.BaseDepNode(type_, sim_act)[源代码]¶
基类:
objectBase class for all nodes in a data-dependency graph
- 参数:
type_ (int)
sim_act (SimActionData)
- __init__(type_, sim_act)[源代码]¶
- 参数:
type_ (int)
sim_act (SimActionData)
- class angr.analyses.data_dep.ConstantDepNode(sim_act, value)[源代码]¶
基类:
BaseDepNodeUsed to create a DepNode that will hold a constant, numeric value Uniquely identified by its value
- 参数:
sim_act (SimActionData)
value (int)
- __init__(sim_act, value)[源代码]¶
- 参数:
sim_act (SimActionData)
value (int)
- class angr.analyses.data_dep.DataDependencyGraphAnalysis(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]¶
基类:
AnalysisThis 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 SimActionDatastart_from (
Optional[int]) -- An address or None, Specifies where to start generation of DDGend_at (
Optional[int]) -- An address or None, Specifies where to end generation of DDGblock_addrs (list[int] | None) -- List of block addresses that the DDG analysis should be run on
block_addrs
- class angr.analyses.data_dep.DepNodeTypes[源代码]¶
基类:
objectEnumeration 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)[源代码]¶
基类:
BaseDepNodeUsed to represent SimActions of type MEM
- 参数:
sim_act (SimActionData)
addr (int)
- __init__(sim_act, addr)[源代码]¶
- 参数:
sim_act (SimActionData)
addr (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='')[源代码]¶
基类:
VarDepNodeBase class for representing SimActions of TYPE reg
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- __init__(sim_act, reg, arch_name='')[源代码]¶
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- class angr.analyses.data_dep.TmpDepNode(sim_act, reg, arch_name='')[源代码]¶
基类:
VarDepNodeUsed to represent SimActions of type TMP
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- __init__(sim_act, reg, arch_name='')[源代码]¶
- 参数:
sim_act (SimActionData)
reg (int)
arch_name (str)
- class angr.analyses.data_dep.VarDepNode(type_, sim_act, reg, arch_name='')[源代码]¶
基类:
BaseDepNodeAbstract class for representing SimActions of TYPE reg or tmp
- 参数:
type_ (int)
sim_act (SimActionData)
reg (int)
arch_name (str)
- exception angr.blade.BadJumpkindNotification[源代码]¶
基类:
ExceptionNotifies 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)[源代码]¶
基类:
objectBlade 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.
- 参数:
- __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¶
- class angr.slicer.SimLightState(temps=None, regs=None, stack_offsets=None, options=None)[源代码]¶
基类:
objectRepresents a program state. Only used in SimSlicer.
- 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)[源代码]¶
基类:
objectA super lightweight intra-IRSB slicing class.
- 参数:
include_imarks (bool)
- class angr.annocfg.AnnotatedCFG(project, cfg=None, detect_loops=False)[源代码]¶
基类:
objectAnnotatedCFG 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
- add_loop(loop_tuple)[源代码]¶
A loop tuple contains a series of IRSB addresses that form a loop. Ideally it always starts with the first IRSB that we meet during the execution.
- get_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
- class angr.codenode.CodeNode(addr, size, graph=None, thumb=False)[源代码]¶
基类:
object- thumb¶
- is_hook = None¶
- class angr.codenode.BlockNode(addr, size, bytestr=None, **kwargs)[源代码]¶
基类:
CodeNode- is_hook = False¶
- bytestr¶
SimOS¶
Manage OS-level configuration.
- class angr.simos.SimCGC(project, **kwargs)[源代码]¶
基类:
SimUserlandEnvironment configuration for the CGC DECREE platform
- class angr.simos.SimJavaVM(*args, **kwargs)[源代码]¶
基类:
SimOS- 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.
- 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.
- 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
- class angr.simos.SimLinux(project, **kwargs)[源代码]¶
基类:
SimUserlandOS-specific configuration for *nix-y OSes.
- 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
- 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
- 返回:
- class angr.simos.SimOS(project, name=None)[源代码]¶
基类:
objectA class describing OS/arch-level configuration.
- 参数:
project (angr.Project)
- 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
- 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
- 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)[源代码]¶
基类:
SimOSThis class implements the "OS" for a bare-metal firmware used at an imaginary company.
- 参数:
project (Project)
- class angr.simos.SimUserland(project, syscall_library=None, syscall_addr_alignment=4, **kwargs)[源代码]¶
基类:
SimOSThis 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.
- configure_project(abi_list=None)[源代码]¶
Configure the project to set up global settings (like SimProcedures).
- 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)[源代码]¶
基类:
SimOSEnvironment for the Windows Win32 subsystem. Does not support syscalls currently.
- 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
- class angr.simos.simos.SimOS(project, name=None)[源代码]¶
基类:
objectA class describing OS/arch-level configuration.
- 参数:
project (angr.Project)
- 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
- 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
- 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)[源代码]¶
基类:
objectGlobalDescriptorTable object to store the GDT table and the segment registers values
- class angr.simos.linux.SimLinux(project, **kwargs)[源代码]¶
基类:
SimUserlandOS-specific configuration for *nix-y OSes.
- 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
- 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
- 返回:
- class angr.simos.cgc.SimCGC(project, **kwargs)[源代码]¶
基类:
SimUserlandEnvironment configuration for the CGC DECREE platform
- class angr.simos.userland.SimUserland(project, syscall_library=None, syscall_addr_alignment=4, **kwargs)[源代码]¶
基类:
SimOSThis 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.
- configure_project(abi_list=None)[源代码]¶
Configure the project to set up global settings (like SimProcedures).
- 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)[源代码]¶
基类:
EnumAn enumeration.
- NONE = 0¶
- RANDOM = 1¶
- STATIC = 2¶
- SYMBOLIC = 3¶
- class angr.simos.windows.SimWindows(project)[源代码]¶
基类:
SimOSEnvironment for the Windows Win32 subsystem. Does not support syscalls currently.
- 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
- class angr.simos.javavm.SimJavaVM(*args, **kwargs)[源代码]¶
基类:
SimOS- 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.
- 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.
- 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
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)[源代码]¶
基类:
objectThis class describes a FLIRT signature.
- 参数:
- angr.flirt.FS¶
FlirtSignature的别名
- angr.flirt.build_sig.get_unique_strings(ar_path)[源代码]¶
For Linux libraries, this method requires ar (from binutils), nm (from binutils), and strings.
Utils¶
- angr.utils.is_pyinstaller()[源代码]¶
Detect if we are currently running as a PyInstaller-packaged program.
- 返回类型:
- 返回:
True if we are running as a PyInstaller-packaged program. False if we are running in Python directly (e.g., development mode).
- 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.
- class angr.utils.cowdict.ChainMapCOW(*args, collapse_threshold=None)[源代码]¶
基类:
ChainMapImplements a copy-on-write version of ChainMap that supports auto-collapsing.
- class angr.utils.cowdict.DefaultChainMapCOW(*args, default_factory=None, collapse_threshold=None)[源代码]¶
基类:
ChainMapCOWImplements a copy-on-write version of ChainMap with default values that supports auto-collapsing.
- 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.
- 参数:
max_size (int | None)
content (DynamicDictList | dict[int, VT] | list[VT] | None)
- __init__(max_size=None, content=None)[源代码]¶
- 参数:
max_size (int | None)
content (DynamicDictList | dict[int, VT] | list[VT] | None)
- max_size¶
- angr.utils.env.is_pyinstaller()[源代码]¶
Detect if we are currently running as a PyInstaller-packaged program.
- 返回类型:
- 返回:
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.
- angr.utils.graph.to_acyclic_graph(graph, ordered_nodes=None, loop_heads=None)[源代码]¶
Convert a given DiGraph into an 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.
- 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)[源代码]¶
基类:
objectA temporary node.
Used as the start node and end node in post-dominator tree generation. Also used in some test cases.
- class angr.utils.graph.ContainerNode(obj)[源代码]¶
基类:
objectA container node.
Only used in dominator tree generation. We did this so we can set the index property without modifying the original object.
- index¶
- property obj¶
- class angr.utils.graph.Dominators(graph, entry_node, successors_func=None, reverse=False)[源代码]¶
基类:
objectDescribes dominators in a graph.
-
dom:
DiGraph¶
-
dom:
- class angr.utils.graph.PostDominators(graph, entry_node, successors_func=None)[源代码]¶
基类:
DominatorsDescribe post-dominators in a graph.
- property post_dom: DiGraph¶
- class angr.utils.graph.SCCPlaceholder(scc_id)[源代码]¶
基类:
objectDescribes a placeholder for strongly-connected-components in a graph.
- scc_id¶
- class angr.utils.graph.GraphUtils[源代码]¶
基类:
objectA 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
- 参数:
- 返回:
A list of ordered addresses of merge points.
- 返回类型:
- 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.
- 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.
- 返回类型:
- 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.
- 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.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.
- angr.utils.loader.is_in_readonly_section(project, addr)[源代码]¶
Check if the specified address is inside a read-only section.
- angr.utils.loader.is_in_readonly_segment(project, addr)[源代码]¶
Check if the specified address is inside a read-only segment.
- angr.utils.library.get_function_name(s)[源代码]¶
Get the function name from a C-style function declaration string.
- 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.
- 返回类型:
- 返回:
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.
- 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))
- 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))
- 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.
- 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])[源代码]¶
基类:
NamedTupleA pickle-able lambda; note that f, args, and kwargs must be pickleable
- class angr.utils.mp.Initializer(*, _manual=True)[源代码]¶
基类:
objectA singleton class with global state used to initialize a multiprocessing.Process
- 参数:
_manual (bool)
Errors¶
- exception angr.errors.AngrRuntimeError[源代码]¶
基类:
RuntimeError
- exception angr.errors.AngrValueError[源代码]¶
基类:
AngrError,ValueError
- exception angr.errors.AngrVFGRestartAnalysisNotice[源代码]¶
基类:
AngrVFGError
- exception angr.errors.AngrCorruptDBError[源代码]¶
基类:
AngrDBError
- exception angr.errors.AngrIncompatibleDBError[源代码]¶
基类:
AngrDBError
- exception angr.errors.SimError[源代码]¶
基类:
Exception- bbl_addr = None¶
- stmt_idx = None¶
- ins_addr = None¶
- executed_instruction_count = None¶
- guard = None¶
- exception angr.errors.SimIRSBNoDecodeError[源代码]¶
基类:
SimIRSBError
- angr.errors.UnsupportedSyscallError¶
- angr.errors.SimSegfaultError¶
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)[源代码]¶
基类:
objectServer 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)[源代码]¶
- property active_workers¶
- property stopped¶
- 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)[源代码]¶
基类:
objectServer 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)[源代码]¶
- property active_workers¶
- property stopped¶
- class angr.distributed.worker.BadStatesDropper(vault, db)[源代码]¶
-
Dumps and drops states that are not "active".
- 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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.distributed.worker.ExplorationStatusNotifier(server_state)[源代码]¶
-
Force the exploration to stop if the server.stop is True.
- 参数:
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.- 参数:
simgr (angr.SimulationManager)
stash (str)
- class angr.distributed.worker.Worker(worker_id, server, server_state, recursion_limit=None, techniques=None, add_options=None, remove_options=None)[源代码]¶
基类:
objectWorker 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)[源代码]¶
- run(initializer)[源代码]¶
- 参数:
initializer (Initializer)