text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Get a dict of phi variables and their corresponding variables. <END_TASK> <USER_TASK:> Description: def get_phi_variables(self, block_addr): """ Get a dict of phi variables and their corresponding variables. :param int block_addr: Address of the block. :return: ...
if block_addr not in self._phi_variables_by_block: return dict() variables = { } for phi in self._phi_variables_by_block[block_addr]: variables[phi] = self._phi_variables[phi] return variables
<SYSTEM_TASK:> Get all variables that have never been written to. <END_TASK> <USER_TASK:> Description: def input_variables(self, exclude_specials=True): """ Get all variables that have never been written to. :return: A list of variables that are never written to. """
def has_write_access(accesses): return any(acc for acc in accesses if acc.access_type == 'write') def has_read_access(accesses): return any(acc for acc in accesses if acc.access_type == 'read') input_variables = [ ] for variable, accesses in self._variable_ac...
<SYSTEM_TASK:> Assign default names to all variables. <END_TASK> <USER_TASK:> Description: def assign_variable_names(self): """ Assign default names to all variables. :return: None """
for var in self._variables: if isinstance(var, SimStackVariable): if var.name is not None: continue if var.ident.startswith('iarg'): var.name = 'arg_%x' % var.offset else: var.name = 's_%x' ...
<SYSTEM_TASK:> Get a list of all references to the given variable. <END_TASK> <USER_TASK:> Description: def get_variable_accesses(self, variable, same_name=False): """ Get a list of all references to the given variable. :param SimVariable variable: The variable. :param bool same...
if variable.region == 'global': return self.global_manager.get_variable_accesses(variable, same_name=same_name) elif variable.region in self.function_managers: return self.function_managers[variable.region].get_variable_accesses(variable, same_name=same_name) l.warnin...
<SYSTEM_TASK:> Call this Callable with a string of C-style arguments. <END_TASK> <USER_TASK:> Description: def call_c(self, c_args): """ Call this Callable with a string of C-style arguments. :param str c_args: C-style arguments. :return: The return value from the call. ...
c_args = c_args.strip() if c_args[0] != "(": c_args = "(" + c_args if c_args[-1] != ")": c_args += ")" # Parse arguments content = "int main() { func%s; }" % c_args ast = pycparser.CParser().parse(content) if not ast.ext or not isinstan...
<SYSTEM_TASK:> Discard the ancestry of this state. <END_TASK> <USER_TASK:> Description: def trim(self): """ Discard the ancestry of this state. """
new_hist = self.copy({}) new_hist.parent = None self.state.register_plugin('history', new_hist)
<SYSTEM_TASK:> Filter self.actions based on some common parameters. <END_TASK> <USER_TASK:> Description: def filter_actions(self, block_addr=None, block_stmt=None, insn_addr=None, read_from=None, write_to=None): """ Filter self.actions based on some common parameters. :param block_addr: Only r...
if read_from is not None: if write_to is not None: raise ValueError("Can't handle read_from and write_to at the same time!") if read_from in ('reg', 'mem'): read_type = read_from read_offset = None elif isinstance(read_from, st...
<SYSTEM_TASK:> Find the common ancestor between this history node and 'other'. <END_TASK> <USER_TASK:> Description: def closest_common_ancestor(self, other): """ Find the common ancestor between this history node and 'other'. :param other: the PathHistory to find a common ancestor with. ...
our_history_iter = reversed(HistoryIter(self)) their_history_iter = reversed(HistoryIter(other)) sofar = set() while True: our_done = False their_done = False try: our_next = next(our_history_iter) if our_next in sofa...
<SYSTEM_TASK:> Returns the constraints that have been accumulated since `other`. <END_TASK> <USER_TASK:> Description: def constraints_since(self, other): """ Returns the constraints that have been accumulated since `other`. :param other: a prior PathHistory object :returns: a list of co...
constraints = [ ] cur = self while cur is not other and cur is not None: constraints.extend(cur.recent_constraints) cur = cur.parent return constraints
<SYSTEM_TASK:> Generate a slice of the graph from the head node to the given frontier. <END_TASK> <USER_TASK:> Description: def slice_graph(graph, node, frontier, include_frontier=False): """ Generate a slice of the graph from the head node to the given frontier. :param networkx.DiGraph graph: ...
subgraph = networkx.DiGraph() for frontier_node in frontier: for simple_path in networkx.all_simple_paths(graph, node, frontier_node): for src, dst in zip(simple_path, simple_path[1:]): if include_frontier or (src not in frontier and dst not in frontier...
<SYSTEM_TASK:> Translates an integer, set, list or function into a lambda that checks if state's current basic block matches <END_TASK> <USER_TASK:> Description: def condition_to_lambda(condition, default=False): """ Translates an integer, set, list or function into a lambda that checks if state's current basic...
if condition is None: condition_function = lambda state: default static_addrs = set() elif isinstance(condition, int): return condition_to_lambda((condition,)) elif isinstance(condition, (tuple, set, list)): static_addrs = set(condition) def condition_function(stat...
<SYSTEM_TASK:> Determines a persistent ID for an object. <END_TASK> <USER_TASK:> Description: def _get_persistent_id(self, o): """ Determines a persistent ID for an object. Does NOT do stores. """
if type(o) in self.hash_dedup: oid = o.__class__.__name__ + "-" + str(hash(o)) self._object_cache[oid] = o return oid if any(isinstance(o,c) for c in self.unsafe_key_baseclasses): return None try: return self._uuid_cache[o] e...
<SYSTEM_TASK:> Checks if the provided id is already in the vault. <END_TASK> <USER_TASK:> Description: def is_stored(self, i): """ Checks if the provided id is already in the vault. """
if i in self.stored: return True try: with self._read_context(i): return True except (AngrVaultError, EOFError): return False
<SYSTEM_TASK:> Retrieves one object from the pickler with the provided id. <END_TASK> <USER_TASK:> Description: def load(self, id): #pylint:disable=redefined-builtin """ Retrieves one object from the pickler with the provided id. :param id: an ID to use """
l.debug("LOAD: %s", id) try: l.debug("... trying cached") return self._object_cache[id] except KeyError: l.debug("... cached failed") with self._read_context(id) as u: return VaultUnpickler(self, u).load()
<SYSTEM_TASK:> Stores an object and returns its ID. <END_TASK> <USER_TASK:> Description: def store(self, o, id=None): #pylint:disable=redefined-builtin """ Stores an object and returns its ID. :param o: the object :param id: an ID to use """
actual_id = id or self._get_persistent_id(o) or "TMP-"+str(uuid.uuid4()) l.debug("STORE: %s %s", o, actual_id) # this handles recursive objects if actual_id in self.storing: return actual_id if self.is_stored(actual_id): l.debug("... already stored") ...
<SYSTEM_TASK:> Returns a serialized string representing the object, post-deduplication. <END_TASK> <USER_TASK:> Description: def dumps(self, o): """ Returns a serialized string representing the object, post-deduplication. :param o: the object """
f = io.BytesIO() VaultPickler(self, f).dump(o) f.seek(0) return f.read()
<SYSTEM_TASK:> Deserializes a string representation of the object. <END_TASK> <USER_TASK:> Description: def loads(self, s): """ Deserializes a string representation of the object. :param s: the string """
f = io.BytesIO(s) return VaultUnpickler(self, f).load()
<SYSTEM_TASK:> Checks that the specified state options result in the same states over the next `depth` states. <END_TASK> <USER_TASK:> Description: def set_state_options(self, left_add_options=None, left_remove_options=None, right_add_options=None, right_remove_options=None): """ Checks that the specifi...
s_right = self.project.factory.full_init_state( add_options=right_add_options, remove_options=right_remove_options, args=[], ) s_left = self.project.factory.full_init_state( add_options=left_add_options, remove_options=left_remove_options, args=[]...
<SYSTEM_TASK:> Checks that the specified paths stay the same over the next `depth` states. <END_TASK> <USER_TASK:> Description: def set_states(self, left_state, right_state): """ Checks that the specified paths stay the same over the next `depth` states. """
simgr = self.project.factory.simulation_manager(right_state) simgr.stash(to_stash='right') simgr.active.append(left_state) simgr.stash(to_stash='left') simgr.stash(to_stash='stashed_left') simgr.stash(to_stash='stashed_right') return self.set_simgr(simgr)
<SYSTEM_TASK:> Checks that a detected incongruency is not caused by translation backends having a different <END_TASK> <USER_TASK:> Description: def _validate_incongruency(self): """ Checks that a detected incongruency is not caused by translation backends having a different idea of what constit...
ot = self._throw try: self._throw = False l.debug("Validating incongruency.") if ("UNICORN" in self.simgr.right[0].options) ^ ("UNICORN" in self.simgr.left[0].options): if "UNICORN" in self.simgr.right[0].options: unicorn_stash ...
<SYSTEM_TASK:> Checks state `state` to see if the breakpoint should fire. <END_TASK> <USER_TASK:> Description: def check(self, state, when): """ Checks state `state` to see if the breakpoint should fire. :param state: The state. :param when: Whether the check is happening before or...
ok = self.enabled and (when == self.when or self.when == BP_BOTH) if not ok: return ok l.debug("... after enabled and when: %s", ok) for a in [ _ for _ in self.kwargs if not _.endswith("_unique") ]: current_expr = getattr(state.inspect, a) needed = s...
<SYSTEM_TASK:> Trigger the breakpoint. <END_TASK> <USER_TASK:> Description: def fire(self, state): """ Trigger the breakpoint. :param state: The state. """
if self.action is None or self.action == BP_IPDB: import ipdb; ipdb.set_trace() #pylint:disable=F0401 elif self.action == BP_IPYTHON: import IPython shell = IPython.terminal.embed.InteractiveShellEmbed() shell.mainloop(display_banner="This is an ipython s...
<SYSTEM_TASK:> Called from within SimuVEX when events happens. This function checks all breakpoints registered for that event <END_TASK> <USER_TASK:> Description: def action(self, event_type, when, **kwargs): """ Called from within SimuVEX when events happens. This function checks all breakpoints regist...
l.debug("Event %s (%s) firing...", event_type, when) for k,v in kwargs.items(): if k not in inspect_attributes: raise ValueError("Invalid inspect attribute %s passed in. Should be one of: %s" % (k, inspect_attributes)) #l.debug("... %s = %r", k, v) l....
<SYSTEM_TASK:> Adds a breakpoint which would trigger on `event_type`. <END_TASK> <USER_TASK:> Description: def add_breakpoint(self, event_type, bp): """ Adds a breakpoint which would trigger on `event_type`. :param event_type: The event type to trigger on :param bp: The breakp...
if event_type not in event_types: raise ValueError("Invalid event type %s passed in. Should be one of: %s" % (event_type, ", ".join(event_types)) ) self._breakpoints[event_ty...
<SYSTEM_TASK:> Removes a breakpoint. <END_TASK> <USER_TASK:> Description: def remove_breakpoint(self, event_type, bp=None, filter_func=None): """ Removes a breakpoint. :param bp: The breakpoint to remove. :param filter_func: A filter function to specify whether each breakpoint should b...
if bp is None and filter_func is None: raise ValueError('remove_breakpoint(): You must specify either "bp" or "filter".') try: if bp is not None: self._breakpoints[event_type].remove(bp) else: self._breakpoints[event_type] = [ b for ...
<SYSTEM_TASK:> Given a state, return the procedure corresponding to the current syscall. <END_TASK> <USER_TASK:> Description: def syscall(self, state, allow_unsupported=True): """ Given a state, return the procedure corresponding to the current syscall. This procedure will have .syscall_number, ...
abi = self.syscall_abi(state) if state.os_name in SYSCALL_CC[state.arch.name]: cc = SYSCALL_CC[state.arch.name][state.os_name](state.arch) else: # Use the default syscall calling convention - it may bring problems _l.warning("No syscall calling convention av...
<SYSTEM_TASK:> Return whether or not the given address corresponds to a syscall implementation. <END_TASK> <USER_TASK:> Description: def is_syscall_addr(self, addr): """ Return whether or not the given address corresponds to a syscall implementation. """
if self.kernel_base is None or addr < self.kernel_base: return False addr -= self.kernel_base if addr % self.syscall_addr_alignment != 0: return False addr //= self.syscall_addr_alignment return addr <= self.unknown_syscall_number
<SYSTEM_TASK:> Get a syscall SimProcedure from an address. <END_TASK> <USER_TASK:> Description: def syscall_from_addr(self, addr, allow_unsupported=True): """ Get a syscall SimProcedure from an address. :param addr: The address to convert to a syscall SimProcedure :param allow_unsupport...
if not self.is_syscall_addr(addr): return None number = (addr - self.kernel_base) // self.syscall_addr_alignment for abi in self.syscall_abis: baseno, minno, maxno = self.syscall_abis[abi] if baseno <= number <= baseno + maxno - minno: number...
<SYSTEM_TASK:> Get a syscall SimProcedure from its number. <END_TASK> <USER_TASK:> Description: def syscall_from_number(self, number, allow_unsupported=True, abi=None): """ Get a syscall SimProcedure from its number. :param number: The syscall number :param allow_unsupporte...
abilist = self.syscall_abis if abi is None else [abi] if self.syscall_library is None: if not allow_unsupported: raise AngrUnsupportedSyscallError("%s does not have a library of syscalls implemented" % self.name) proc = P['stubs']['syscall']() elif not a...
<SYSTEM_TASK:> Convert from a windows memory protection constant to an angr bitmask <END_TASK> <USER_TASK:> Description: def convert_prot(prot): """ Convert from a windows memory protection constant to an angr bitmask """
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx if prot & 0x10: return 4 if prot & 0x20: return 5 if prot & 0x40: return 7 if prot & 0x80: return 7 if prot & 0x01: return 0 if prot & 0x02: return 1 if prot...
<SYSTEM_TASK:> Add a new definition of variable. <END_TASK> <USER_TASK:> Description: def add_def(self, variable, location, size_threshold=32): """ Add a new definition of variable. :param SimVariable variable: The variable being defined. :param CodeLocation location: Location of the va...
new_defs_added = False if isinstance(variable, SimRegisterVariable): if variable.reg is None: l.warning('add_def: Got a None for a SimRegisterVariable. Consider fixing.') return new_defs_added size = min(variable.size, size_threshold) ...
<SYSTEM_TASK:> Add a collection of new definitions of a variable. <END_TASK> <USER_TASK:> Description: def add_defs(self, variable, locations, size_threshold=32): """ Add a collection of new definitions of a variable. :param SimVariable variable: The variable being defined. :param itera...
new_defs_added = False for loc in locations: new_defs_added |= self.add_def(variable, loc, size_threshold=size_threshold) return new_defs_added
<SYSTEM_TASK:> Add a new definition for variable and kill all previous definitions. <END_TASK> <USER_TASK:> Description: def kill_def(self, variable, location, size_threshold=32): """ Add a new definition for variable and kill all previous definitions. :param SimVariable variable: The variable ...
if isinstance(variable, SimRegisterVariable): if variable.reg is None: l.warning('kill_def: Got a None for a SimRegisterVariable. Consider fixing.') return None size = min(variable.size, size_threshold) offset = variable.reg whil...
<SYSTEM_TASK:> Find all definitions of the varaible <END_TASK> <USER_TASK:> Description: def lookup_defs(self, variable, size_threshold=32): """ Find all definitions of the varaible :param SimVariable variable: The variable to lookup for. :param int size_threshold: The maximum bytes to ...
live_def_locs = set() if isinstance(variable, SimRegisterVariable): if variable.reg is None: l.warning('lookup_defs: Got a None for a SimRegisterVariable. Consider fixing.') return live_def_locs size = min(variable.size, size_threshold) ...
<SYSTEM_TASK:> Convert a ProgramVariable instance to a DDGViewItem object. <END_TASK> <USER_TASK:> Description: def _to_viewitem(self, prog_var): """ Convert a ProgramVariable instance to a DDGViewItem object. :param ProgramVariable prog_var: The ProgramVariable object to convert. :retu...
return DDGViewItem(self._ddg, prog_var, simplified=self._simplified)
<SYSTEM_TASK:> Get all definitions located at the current instruction address. <END_TASK> <USER_TASK:> Description: def definitions(self): """ Get all definitions located at the current instruction address. :return: A list of ProgramVariable instances. :rtype: list """
defs = set() if self._simplified: graph = self._ddg.simplified_data_graph else: graph = self._ddg.data_graph for n in graph.nodes(): # type: ProgramVariable if n.location.ins_addr == self._insn_addr: defs.add(DDGViewItem(self._ddg,...
<SYSTEM_TASK:> Get a dependency graph for the function `func`. <END_TASK> <USER_TASK:> Description: def function_dependency_graph(self, func): """ Get a dependency graph for the function `func`. :param func: The Function object in CFG.function_manager. :returns: A networkx.DiGr...
if self._function_data_dependencies is None: self._build_function_dependency_graphs() if func in self._function_data_dependencies: return self._function_data_dependencies[func] # Not found return None
<SYSTEM_TASK:> Get a subgraph from the data graph or the simplified data graph that starts from node pv. <END_TASK> <USER_TASK:> Description: def data_sub_graph(self, pv, simplified=True, killing_edges=False, excluding_types=None): """ Get a subgraph from the data graph or the simplified data graph that...
result = networkx.MultiDiGraph() result.add_node(pv) base_graph = self.simplified_data_graph if simplified else self.data_graph if pv not in base_graph: return result # traverse all edges and add them to the result graph if needed queue = [ pv ] tr...
<SYSTEM_TASK:> This is a backward lookup in the previous defs. Note that, as we are using VSA, it is possible that `variable` <END_TASK> <USER_TASK:> Description: def _def_lookup(self, variable): # pylint:disable=no-self-use """ This is a backward lookup in the previous defs. Note that, as we are using...
prevdefs = {} for code_loc in self._live_defs.lookup_defs(variable): # Label edges with cardinality or actual sets of addresses if isinstance(variable, SimMemoryVariable): type_ = 'mem' elif isinstance(variable, SimRegisterVariable): ...
<SYSTEM_TASK:> Get the size of a register. <END_TASK> <USER_TASK:> Description: def _get_register_size(self, reg_offset): """ Get the size of a register. :param int reg_offset: Offset of the register. :return: Size in bytes. :rtype: int """
# TODO: support registers that are not aligned if reg_offset in self.project.arch.register_names: reg_name = self.project.arch.register_names[reg_offset] reg_size = self.project.arch.registers[reg_name][1] return reg_size l.warning("_get_register_size(): un...
<SYSTEM_TASK:> For memory actions, get a list of addresses it operates on. <END_TASK> <USER_TASK:> Description: def _get_actual_addrs(action, state): """ For memory actions, get a list of addresses it operates on. :param SimAction action: The action object to work with. :return: ...
if action.actual_addrs is None: # For now, mem reads don't necessarily have actual_addrs set properly try: addr_list = {state.solver.eval(action.addr.ast)} except (SimSolverModeError, SimUnsatError, ZeroDivisionError): # FIXME: ZeroDivisionEr...
<SYSTEM_TASK:> Create a SimStackVariable or SimMemoryVariable based on action objects and its address. <END_TASK> <USER_TASK:> Description: def _create_memory_variable(self, action, addr, addrs): """ Create a SimStackVariable or SimMemoryVariable based on action objects and its address. :param ...
variable = None if len(addrs) == 1 and len(action.addr.tmp_deps) == 1: addr_tmp = list(action.addr.tmp_deps)[0] if addr_tmp in self._temp_register_symbols: # it must be a stack variable sort, offset = self._temp_register_symbols[addr_tmp] ...
<SYSTEM_TASK:> Add an edge in the data dependence graph. <END_TASK> <USER_TASK:> Description: def _data_graph_add_edge(self, src, dst, **edge_labels): """ Add an edge in the data dependence graph. :param ProgramVariable src: Source node. :param ProgramVariable dst: Destination node. ...
if src in self._data_graph and dst in self._data_graph[src]: return self._data_graph.add_edge(src, dst, **edge_labels) self._simplified_data_graph = None
<SYSTEM_TASK:> Add an edge in the statement dependence graph from a program location `src` to another program location `dst`. <END_TASK> <USER_TASK:> Description: def _stmt_graph_add_edge(self, src, dst, **edge_labels): """ Add an edge in the statement dependence graph from a program location `src` to a...
# Is that edge already in the graph ? # If at least one is new, then we are not redoing the same path again if src in self._stmt_graph and dst in self._stmt_graph[src]: return self._stmt_graph.add_edge(src, dst, **edge_labels)
<SYSTEM_TASK:> Add new annotations to edges in the statement dependence graph. <END_TASK> <USER_TASK:> Description: def _stmt_graph_annotate_edges(self, edges_to_annotate, **new_labels): """ Add new annotations to edges in the statement dependence graph. :param list edges_to_annotate: A li...
graph = self.graph for src, dst in edges_to_annotate: if src not in graph: continue if dst not in graph[src]: continue data = graph[src][dst] for k, v in new_labels.items(): if k in data: ...
<SYSTEM_TASK:> Simplify a data graph by removing all temp variable nodes on the graph. <END_TASK> <USER_TASK:> Description: def _simplify_data_graph(self, data_graph): # pylint:disable=no-self-use """ Simplify a data graph by removing all temp variable nodes on the graph. :param networkx.DiGra...
graph = networkx.MultiDiGraph(data_graph) all_nodes = [ n for n in graph.nodes() if isinstance(n.variable, SimTemporaryVariable) ] for tmp_node in all_nodes: # remove each tmp node by linking their successors and predecessors directly in_edges = graph.in_edges(tmp_nod...
<SYSTEM_TASK:> Append a CFGNode and its successors into the work-list, and respect the call-depth limit <END_TASK> <USER_TASK:> Description: def _worklist_append(self, node_wrapper, worklist, worklist_set): """ Append a CFGNode and its successors into the work-list, and respect the call-depth limit ...
if node_wrapper.cfg_node in worklist_set: # It's already in the work-list return worklist.append(node_wrapper) worklist_set.add(node_wrapper.cfg_node) stack = [ node_wrapper ] traversed_nodes = { node_wrapper.cfg_node } inserted = { node_wrappe...
<SYSTEM_TASK:> Build dependency graphs for each function, and save them in self._function_data_dependencies. <END_TASK> <USER_TASK:> Description: def _build_function_dependency_graphs(self): """ Build dependency graphs for each function, and save them in self._function_data_dependencies. """
# This is a map between functions and its corresponding dependencies self._function_data_dependencies = defaultdict(networkx.DiGraph) # Group all dependencies first block_addr_to_func = { } for _, func in self.kb.functions.items(): for block in func.blocks: ...
<SYSTEM_TASK:> If we are not tracing into the function that are called in a real execution, we should properly filter the defs <END_TASK> <USER_TASK:> Description: def _filter_defs_at_call_sites(self, defs): """ If we are not tracing into the function that are called in a real execution, we should prope...
# TODO: make definition killing architecture independent and calling convention independent # TODO: use information from a calling convention analysis filtered_defs = LiveDefinitions() for variable, locs in defs.items(): if isinstance(variable, SimRegisterVariable): ...
<SYSTEM_TASK:> Find all definitions of the given variable. <END_TASK> <USER_TASK:> Description: def find_definitions(self, variable, location=None, simplified_graph=True): """ Find all definitions of the given variable. :param SimVariable variable: :param bool simplified_graph: True if ...
if simplified_graph: graph = self.simplified_data_graph else: graph = self.data_graph defs = [] for n in graph.nodes(): # type: ProgramVariable if n.variable == variable: if location is None: defs.append(n) ...
<SYSTEM_TASK:> Find all consumers to the specified variable definition. <END_TASK> <USER_TASK:> Description: def find_consumers(self, var_def, simplified_graph=True): """ Find all consumers to the specified variable definition. :param ProgramVariable var_def: The variable definition. :p...
if simplified_graph: graph = self.simplified_data_graph else: graph = self.data_graph if var_def not in graph: return [] consumers = [] srcs = [var_def] traversed = set() while srcs: src = srcs.pop() ...
<SYSTEM_TASK:> Find all killers to the specified variable definition. <END_TASK> <USER_TASK:> Description: def find_killers(self, var_def, simplified_graph=True): """ Find all killers to the specified variable definition. :param ProgramVariable var_def: The variable definition. :param b...
if simplified_graph: graph = self.simplified_data_graph else: graph = self.data_graph if var_def not in graph: return [] killers = [] out_edges = graph.out_edges(var_def, data=True) for _, dst, data in out_edges: if 'typ...
<SYSTEM_TASK:> Find all sources to the specified variable definition. <END_TASK> <USER_TASK:> Description: def find_sources(self, var_def, simplified_graph=True): """ Find all sources to the specified variable definition. :param ProgramVariable var_def: The variable definition. :param b...
if simplified_graph: graph = self.simplified_data_graph else: graph = self.data_graph if var_def not in graph: return [] sources = [] defs = [ var_def ] traversed = set() while defs: definition = defs.pop() ...
<SYSTEM_TASK:> Allocates a new multi array in memory and returns the reference to the base. <END_TASK> <USER_TASK:> Description: def new_array(state, element_type, size, default_value_generator=None): """ Allocates a new multi array in memory and returns the reference to the base. """
size_bounded = SimSootExpr_NewMultiArray._bound_multi_array_size(state, size) # return the reference of the array base # => elements getting lazy initialized in the javavm memory return SimSootValue_ArrayBaseRef(heap_alloc_id=state.javavm_memory.get_new_uuid(), ...
<SYSTEM_TASK:> Gets the minimum solution of an address. <END_TASK> <USER_TASK:> Description: def _min(self, memory, addr, **kwargs): """ Gets the minimum solution of an address. """
return memory.state.solver.min(addr, exact=kwargs.pop('exact', self._exact), **kwargs)
<SYSTEM_TASK:> Gets the maximum solution of an address. <END_TASK> <USER_TASK:> Description: def _max(self, memory, addr, **kwargs): """ Gets the maximum solution of an address. """
return memory.state.solver.max(addr, exact=kwargs.pop('exact', self._exact), **kwargs)
<SYSTEM_TASK:> Gets any solution of an address. <END_TASK> <USER_TASK:> Description: def _any(self, memory, addr, **kwargs): """ Gets any solution of an address. """
return memory.state.solver.eval(addr, exact=kwargs.pop('exact', self._exact), **kwargs)
<SYSTEM_TASK:> Gets n solutions for an address. <END_TASK> <USER_TASK:> Description: def _eval(self, memory, addr, n, **kwargs): """ Gets n solutions for an address. """
return memory.state.solver.eval_upto(addr, n, exact=kwargs.pop('exact', self._exact), **kwargs)
<SYSTEM_TASK:> Concretizes the address into a list of values. <END_TASK> <USER_TASK:> Description: def concretize(self, memory, addr): """ Concretizes the address into a list of values. If this strategy cannot handle this address, returns None. """
if self._filter is None or self._filter(memory, addr): return self._concretize(memory, addr)
<SYSTEM_TASK:> Given a local transition graph of a function, find all merge points inside, and then perform a <END_TASK> <USER_TASK:> Description: def find_merge_points(function_addr, function_endpoints, graph): # pylint:disable=unused-argument """ Given a local transition graph of a function, find all...
merge_points = set() for node in graph.nodes(): if graph.in_degree(node) > 1: merge_points.add(node) ordered_merge_points = CFGUtils.quasi_topological_sort_nodes(graph, merge_points) addrs = [n.addr for n in ordered_merge_points] return addrs
<SYSTEM_TASK:> Given a local transition graph of a function, find all widening points inside. <END_TASK> <USER_TASK:> Description: def find_widening_points(function_addr, function_endpoints, graph): # pylint: disable=unused-argument """ Given a local transition graph of a function, find all widening po...
sccs = networkx.strongly_connected_components(graph) widening_addrs = set() for scc in sccs: if len(scc) == 1: node = next(iter(scc)) if graph.has_edge(node, node): # self loop widening_addrs.add(node.addr) ...
<SYSTEM_TASK:> Sort a given set of nodes in reverse post ordering. <END_TASK> <USER_TASK:> Description: def reverse_post_order_sort_nodes(graph, nodes=None): """ Sort a given set of nodes in reverse post ordering. :param networkx.DiGraph graph: A local transition graph of a function. :p...
post_order = networkx.dfs_postorder_nodes(graph) if nodes is None: return reversed(list(post_order)) addrs_to_index = {} for i, n in enumerate(post_order): addrs_to_index[n.addr] = i return sorted(nodes, key=lambda n: addrs_to_index[n.addr], reverse=Tr...
<SYSTEM_TASK:> Append all nodes from a strongly connected component to a list of ordered nodes and ensure the topological <END_TASK> <USER_TASK:> Description: def _append_scc(graph, ordered_nodes, scc): """ Append all nodes from a strongly connected component to a list of ordered nodes and ensure the to...
# find the first node in the strongly connected component that is the successor to any node in ordered_nodes loop_head = None for parent_node in reversed(ordered_nodes): for n in scc: if n in graph[parent_node]: loop_head = n ...
<SYSTEM_TASK:> Mulpyplex across several stashes. <END_TASK> <USER_TASK:> Description: def mulpyplex(self, *stashes): """ Mulpyplex across several stashes. :param stashes: the stashes to mulpyplex :return: a mulpyplexed list of states from the stashes in question, in the specified order ...
return mulpyplexer.MP(list(itertools.chain.from_iterable(self._stashes[s] for s in stashes)))
<SYSTEM_TASK:> Make a copy of this simulation manager. Pass ``deep=True`` to copy all the states in it as well. <END_TASK> <USER_TASK:> Description: def copy(self, deep=False): # pylint: disable=arguments-differ """ Make a copy of this simulation manager. Pass ``deep=True`` to copy all the states in it ...
simgr = SimulationManager(self._project, stashes=self._copy_stashes(deep=deep), hierarchy=self._hierarchy, resilience=self._resilience, auto_drop=self._auto_drop, ...
<SYSTEM_TASK:> Use an exploration technique with this SimulationManager. <END_TASK> <USER_TASK:> Description: def use_technique(self, tech): """ Use an exploration technique with this SimulationManager. Techniques can be found in :mod:`angr.exploration_techniques`. :param tech: An E...
if not isinstance(tech, ExplorationTechnique): raise SimulationManagerError # XXX: as promised tech.project = self._project tech.setup(self) HookSet.install_hooks(self, **tech._get_hooks()) self._techniques.append(tech) return tech
<SYSTEM_TASK:> Remove an exploration technique from a list of active techniques. <END_TASK> <USER_TASK:> Description: def remove_technique(self, tech): """ Remove an exploration technique from a list of active techniques. :param tech: An ExplorationTechnique object. :type tech: E...
if not isinstance(tech, ExplorationTechnique): raise SimulationManagerError def _is_overriden(name): return getattr(tech, name).__code__ is not getattr(ExplorationTechnique, name).__code__ overriden = filter(_is_overriden, ('step', 'filter', 'selector', 'step_state', '...
<SYSTEM_TASK:> Run until the SimulationManager has reached a completed state, according to <END_TASK> <USER_TASK:> Description: def run(self, stash='active', n=None, until=None, **kwargs): """ Run until the SimulationManager has reached a completed state, according to the current exploration tec...
for _ in (itertools.count() if n is None else range(0, n)): if not self.complete() and self._stashes[stash]: self.step(stash=stash, **kwargs) if not (until and until(self)): continue break return self
<SYSTEM_TASK:> Returns whether or not this manager has reached a "completed" state. <END_TASK> <USER_TASK:> Description: def complete(self): """ Returns whether or not this manager has reached a "completed" state. """
if not self._techniques: return False if not any(tech._is_overriden('complete') for tech in self._techniques): return False return self.completion_mode(tech.complete(self) for tech in self._techniques if tech._is_overriden('complete'))
<SYSTEM_TASK:> Step a stash of states forward and categorize the successors appropriately. <END_TASK> <USER_TASK:> Description: def step(self, stash='active', n=None, selector_func=None, step_func=None, successor_func=None, until=None, filter_func=None, **run_args): """ Step a stash of stat...
l.info("Stepping %s of %s", stash, self) # 8<----------------- Compatibility layer ----------------- if n is not None or until is not None: if once('simgr_step_n_until'): print("\x1b[31;1mDeprecation warning: the use of `n` and `until` arguments is deprecated. " ...
<SYSTEM_TASK:> Prune unsatisfiable states from a stash. <END_TASK> <USER_TASK:> Description: def prune(self, 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 differe...
def _prune_filter(state): to_prune = not filter_func or filter_func(state) if to_prune and not state.satisfiable(): if self._hierarchy: self._hierarchy.unreachable_state(state) self._hierarchy.simplify() return True...
<SYSTEM_TASK:> Move states from one stash to another. <END_TASK> <USER_TASK:> Description: def move(self, from_stash, to_stash, filter_func=None): """ Move states from one stash to another. :param from_stash: Take matching states from this stash. :param to_stash: Put matching states...
filter_func = filter_func or (lambda s: True) stash_splitter = lambda states: reversed(self._filter_states(filter_func, states)) return self.split(stash_splitter, from_stash=from_stash, to_stash=to_stash)
<SYSTEM_TASK:> Applies a given function to a given stash. <END_TASK> <USER_TASK:> Description: def apply(self, state_func=None, stash_func=None, stash='active', to_stash=None): """ Applies a given function to a given stash. :param state_func: A function to apply to every state. Should take a s...
to_stash = to_stash or stash def _stash_splitter(states): keep, split = [], [] if state_func is not None: for s in states: ns = state_func(s) if isinstance(ns, SimState): split.append(ns) ...
<SYSTEM_TASK:> Split a stash of states into two stashes depending on the specified options. <END_TASK> <USER_TASK:> Description: def split(self, stash_splitter=None, stash_ranker=None, state_ranker=None, limit=8, from_stash='active', to_stash='stashed'): """ Split a stash of states into tw...
states = self._fetch_states(stash=from_stash) if stash_splitter is not None: keep, split = stash_splitter(states) elif stash_ranker is not None: ranked_paths = stash_ranker(states) keep, split = ranked_paths[:limit], ranked_paths[limit:] elif state_r...
<SYSTEM_TASK:> Merge the states in a given stash. <END_TASK> <USER_TASK:> Description: def merge(self, merge_func=None, merge_key=None, stash='active'): """ Merge the states in a given stash. :param stash: The stash (default: 'active') :param merge_func: If provided, instead of u...
self.prune(from_stash=stash) to_merge = self._fetch_states(stash=stash) not_to_merge = [] if merge_key is None: merge_key = self._merge_key merge_groups = [ ] while to_merge: base_key = merge_key(to_merge[0]) g, to_merge = self._filter_states(lam...
<SYSTEM_TASK:> Merges a list of states. <END_TASK> <USER_TASK:> Description: def _merge_states(self, states): """ Merges a list of states. :param states: the states to merge :returns SimState: the resulting state """
if self._hierarchy: optimal, common_history, others = self._hierarchy.most_mergeable(states) else: optimal, common_history, others = states, None, [] if len(optimal) >= 2: # We found optimal states (states that share a common ancestor) to merge. ...
<SYSTEM_TASK:> Launch a postmortem debug shell at the site of the error. <END_TASK> <USER_TASK:> Description: def debug(self): """ Launch a postmortem debug shell at the site of the error. """
try: __import__('ipdb').post_mortem(self.traceback) except ImportError: __import__('pdb').post_mortem(self.traceback)
<SYSTEM_TASK:> Calculate the complement of `self` and `other`. <END_TASK> <USER_TASK:> Description: def complement(self, other): """ Calculate the complement of `self` and `other`. :param other: Another SimVariableSet instance. :return: The complement result. """
s = SimVariableSet() s.register_variables = self.register_variables - other.register_variables s.register_variable_offsets = self.register_variable_offsets - other.register_variable_offsets s.memory_variables = self.memory_variables - other.memory_variables s.memory_variable_ad...
<SYSTEM_TASK:> Get the CFGNode object on the control flow graph given an angr state. <END_TASK> <USER_TASK:> Description: def _get_cfg_node(cfg, state): """ Get the CFGNode object on the control flow graph given an angr state. :param angr.analyses.CFGEmulated cfg: An instance of CFGEmulated. ...
call_stack_suffix = state.callstack.stack_suffix(cfg.context_sensitivity_level) is_syscall = state.history.jumpkind is not None and state.history.jumpkind.startswith('Ijk_Sys') block_id = cfg._generate_block_id(call_stack_suffix, state.addr, is_syscall) return cfg.get_node(block_id)
<SYSTEM_TASK:> Perform a depth-first search on the given DiGraph, with a limit on maximum steps. <END_TASK> <USER_TASK:> Description: def _dfs_edges(graph, source, max_steps=None): """ Perform a depth-first search on the given DiGraph, with a limit on maximum steps. :param networkx.DiGraph grap...
if max_steps is None: yield networkx.dfs_edges(graph, source) else: steps_map = defaultdict(int) traversed = { source } stack = [ source ] while stack: src = stack.pop() for dst in graph.successors(src): ...
<SYSTEM_TASK:> Check if the specified address will be executed <END_TASK> <USER_TASK:> Description: def check(self, cfg, state, peek_blocks): """ Check if the specified address will be executed :param cfg: :param state: :param int peek_blocks: :return: :rtype: bo...
# Get the current CFGNode from the CFG node = self._get_cfg_node(cfg, state) if node is None: # Umm it doesn't exist on the control flow graph - why? l.error('Failed to find CFGNode for state %s on the control flow graph.', state) return False # cr...
<SYSTEM_TASK:> Check if the specified function will be reached with certain arguments. <END_TASK> <USER_TASK:> Description: def check(self, cfg, state, peek_blocks): """ Check if the specified function will be reached with certain arguments. :param cfg: :param state: :param peek...
# Get the current CFGNode node = self._get_cfg_node(cfg, state) if node is None: l.error("Failed to find CFGNode for state %s on the control flow graph.", state) return False # crawl the graph to see if we can reach the target function within the limited steps...
<SYSTEM_TASK:> Check if the specific function is reached with certain arguments <END_TASK> <USER_TASK:> Description: def check_state(self, state): """ Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the fun...
if state.addr == self.function.addr: arch = state.arch if self._check_arguments(arch, state): return True return False
<SYSTEM_TASK:> Make sure all current basic block on each state shows up in the CFG. For blocks that are not in the CFG, start <END_TASK> <USER_TASK:> Description: def _peek_forward(self, simgr): """ Make sure all current basic block on each state shows up in the CFG. For blocks that are not in the CFG, ...
if self._cfg is None: starts = list(simgr.active) self._cfg_kb = KnowledgeBase(self.project) self._cfg = self.project.analyses.CFGEmulated(kb=self._cfg_kb, starts=starts, max_steps=self._peek_blocks, keep_state=sel...
<SYSTEM_TASK:> Load the last N deprioritized states will be extracted from the "deprioritized" stash and put to "active" stash. <END_TASK> <USER_TASK:> Description: def _load_fallback_states(self, pg): """ Load the last N deprioritized states will be extracted from the "deprioritized" stash and put to "...
# take back some of the deprioritized states l.debug("No more active states. Load some deprioritized states to 'active' stash.") if 'deprioritized' in pg.stashes and pg.deprioritized: pg.active.extend(pg.deprioritized[-self._num_fallback_states : ]) pg.stashes['depriori...
<SYSTEM_TASK:> Detects if there is any xor operation in the function. <END_TASK> <USER_TASK:> Description: def has_xor(self): """ Detects if there is any xor operation in the function. :return: Tags """
def _has_xor(expr): return isinstance(expr, pyvex.IRExpr.Binop) and expr.op.startswith("Iop_Xor") found_xor = False for block in self._function.blocks: if block.size == 0: continue for stmt in block.vex.statements: if isinst...
<SYSTEM_TASK:> Detects if there is any bitwise operation in the function. <END_TASK> <USER_TASK:> Description: def has_bitshifts(self): """ Detects if there is any bitwise operation in the function. :return: Tags. """
def _has_bitshifts(expr): if isinstance(expr, pyvex.IRExpr.Binop): return expr.op.startswith("Iop_Shl") or expr.op.startswith("Iop_Shr") \ or expr.op.startswith("Iop_Sar") return False found_bitops = False for block in self._func...
<SYSTEM_TASK:> Merge another KeyedRegion into this KeyedRegion. <END_TASK> <USER_TASK:> Description: def merge(self, other, replacements=None): """ Merge another KeyedRegion into this KeyedRegion. :param KeyedRegion other: The other instance to merge with. :return: None """
# TODO: is the current solution not optimal enough? for _, item in other._storage.items(): # type: RegionObject for so in item.stored_objects: # type: StoredObject if replacements and so.obj in replacements: so = StoredObject(so.start, replacements[so....
<SYSTEM_TASK:> Replace variables with other variables. <END_TASK> <USER_TASK:> Description: def replace(self, replacements): """ Replace variables with other variables. :param dict replacements: A dict of variable replacements. :return: self """
for old_var, new_var in replacements.items(): old_var_id = id(old_var) if old_var_id in self._object_mapping: # FIXME: we need to check if old_var still exists in the storage old_so = self._object_mapping[old_var_id] # type: StoredObject ...
<SYSTEM_TASK:> Add a variable to this region at the given offset. <END_TASK> <USER_TASK:> Description: def add_variable(self, start, variable): """ Add a variable to this region at the given offset. :param int start: :param SimVariable variable: :return: None """
size = variable.size if variable.size is not None else 1 self.add_object(start, variable, size)
<SYSTEM_TASK:> Add a variable to this region at the given offset, and remove all other variables that are fully covered by <END_TASK> <USER_TASK:> Description: def set_variable(self, start, variable): """ Add a variable to this region at the given offset, and remove all other variables that are fully co...
size = variable.size if variable.size is not None else 1 self.set_object(start, variable, size)
<SYSTEM_TASK:> Add an object to this region at the given offset, and remove all other objects that are fully covered by this <END_TASK> <USER_TASK:> Description: def set_object(self, start, obj, object_size): """ Add an object to this region at the given offset, and remove all other objects that are ful...
self._store(start, obj, object_size, overwrite=True)
<SYSTEM_TASK:> Find variables covering the given region offset. <END_TASK> <USER_TASK:> Description: def get_variables_by_offset(self, start): """ Find variables covering the given region offset. :param int start: :return: A list of stack variables. :rtype: set """
_, container = self._get_container(start) if container is None: return [] else: return container.internal_objects
<SYSTEM_TASK:> Find objects covering the given region offset. <END_TASK> <USER_TASK:> Description: def get_objects_by_offset(self, start): """ Find objects covering the given region offset. :param start: :return: """
_, container = self._get_container(start) if container is None: return set() else: return container.internal_objects
<SYSTEM_TASK:> Update the progress with a percentage, including updating the progressbar as well as calling the progress <END_TASK> <USER_TASK:> Description: def _update_progress(self, percentage, **kwargs): """ Update the progress with a percentage, including updating the progressbar as well as calling...
if self._show_progressbar: if self._progressbar is None: self._initialize_progressbar() self._progressbar.update(percentage * 10000) if self._progress_callback is not None: self._progress_callback(percentage, **kwargs)
<SYSTEM_TASK:> Convert an address to a stack offset. <END_TASK> <USER_TASK:> Description: def _addr_to_stack_offset(self, addr): """ Convert an address to a stack offset. :param claripy.ast.Base addr: The address to convert from. :return: A stack offset if the add...
def _parse(addr): if addr.op == '__add__': # __add__ might have multiple arguments parsed = [ _parse(arg) for arg in addr.args ] annotated = [ True for annotated, _ in parsed if annotated is True ] if len(annotated) != 1: ...
<SYSTEM_TASK:> Take an input abstract state, execute the node, and derive an output state. <END_TASK> <USER_TASK:> Description: def _run_on_node(self, node, state): """ Take an input abstract state, execute the node, and derive an output state. :param angr.Block node: The node to wo...
l.debug('Analyzing block %#x, iteration %d.', node.addr, self._node_iterations[node]) concrete_state = state.get_concrete_state(node.addr) if concrete_state is None: # didn't find any state going to here l.error("_run_on_node(): cannot find any state for address %#x."...
<SYSTEM_TASK:> Copy self attributes to the new object. <END_TASK> <USER_TASK:> Description: def make_copy(self, copy_to): """ Copy self attributes to the new object. :param CFGBase copy_to: The target to copy to. :return: None """
for attr, value in self.__dict__.items(): if attr.startswith('__') and attr.endswith('__'): continue setattr(copy_to, attr, value)
<SYSTEM_TASK:> Merge two adjacent CFGNodes into one. <END_TASK> <USER_TASK:> Description: def _merge_cfgnodes(self, cfgnode_0, cfgnode_1): """ Merge two adjacent CFGNodes into one. :param CFGNode cfgnode_0: The first CFGNode. :param CFGNode cfgnode_1: The second CFGNode. :re...
assert cfgnode_0.addr + cfgnode_0.size == cfgnode_1.addr addr0, addr1 = cfgnode_0.addr, cfgnode_1.addr new_node = cfgnode_0.merge(cfgnode_1) # Update the graph and the nodes dict accordingly if addr1 in self._nodes_by_addr: self._nodes_by_addr[addr1].remove(cfgnode...
<SYSTEM_TASK:> Convert a CFGNode instance to a CodeNode object. <END_TASK> <USER_TASK:> Description: def _to_snippet(self, cfg_node=None, addr=None, size=None, thumb=False, jumpkind=None, base_state=None): """ Convert a CFGNode instance to a CodeNode object. :param angr.analyses.CFGNode cfg_nod...
if cfg_node is not None: addr = cfg_node.addr size = cfg_node.size thumb = cfg_node.thumb else: addr = addr size = size thumb = thumb if addr is None: raise ValueError('_to_snippet(): Either cfg_node or addr m...