text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Get predecessors of a node in the control flow graph. <END_TASK> <USER_TASK:> Description: def get_predecessors(self, cfgnode, excluding_fakeret=True, jumpkind=None): """ Get predecessors of a node in the control flow graph. :param CFGNode cfgnode: The node. :...
if excluding_fakeret and jumpkind == 'Ijk_FakeRet': return [ ] if not excluding_fakeret and jumpkind is None: # fast path if cfgnode in self.graph: return list(self.graph.predecessors(cfgnode)) return [ ] predecessors = [] ...
<SYSTEM_TASK:> Get successors of a node in the control flow graph. <END_TASK> <USER_TASK:> Description: def get_successors(self, node, excluding_fakeret=True, jumpkind=None): """ Get successors of a node in the control flow graph. :param CFGNode node: The node. :param boo...
if jumpkind is not None: if excluding_fakeret and jumpkind == 'Ijk_FakeRet': return [ ] if not excluding_fakeret and jumpkind is None: # fast path if node in self.graph: return list(self.graph.successors(node)) return [ ]...
<SYSTEM_TASK:> Get a list of tuples where the first element is the successor of the CFG node and the second element is the <END_TASK> <USER_TASK:> Description: def get_successors_and_jumpkind(self, node, excluding_fakeret=True): """ Get a list of tuples where the first element is the successor of the CF...
successors = [] for _, suc, data in self.graph.out_edges([node], data=True): if not excluding_fakeret or data['jumpkind'] != 'Ijk_FakeRet': successors.append((suc, data['jumpkind'])) return successors
<SYSTEM_TASK:> Get all predecessors of a specific node on the control flow graph. <END_TASK> <USER_TASK:> Description: def get_all_predecessors(self, cfgnode): """ Get all predecessors of a specific node on the control flow graph. :param CFGNode cfgnode: The CFGNode object :return: A li...
s = set() for child, parent in networkx.dfs_predecessors(self.graph, cfgnode).items(): s.add(child) s.add(parent) return list(s)
<SYSTEM_TASK:> Returns all nodes that has an out degree >= 2 <END_TASK> <USER_TASK:> Description: def get_branching_nodes(self): """ Returns all nodes that has an out degree >= 2 """
nodes = set() for n in self.graph.nodes(): if self.graph.out_degree(n) >= 2: nodes.add(n) return nodes
<SYSTEM_TASK:> Get the corresponding exit statement ID for control flow to reach destination block from source block. The exit <END_TASK> <USER_TASK:> Description: def get_exit_stmt_idx(self, src_block, dst_block): """ Get the corresponding exit statement ID for control flow to reach destination block f...
if not self.graph.has_edge(src_block, dst_block): raise AngrCFGError('Edge (%s, %s) does not exist in CFG' % (src_block, dst_block)) return self.graph[src_block][dst_block]['stmt_idx']
<SYSTEM_TASK:> Hook target for native function call returns. <END_TASK> <USER_TASK:> Description: def prepare_native_return_state(native_state): """ Hook target for native function call returns. Recovers and stores the return value from native memory and toggles the state, s.t. executio...
javavm_simos = native_state.project.simos ret_state = native_state.copy() # set successor flags ret_state.regs._ip = ret_state.callstack.ret_addr ret_state.scratch.guard = ret_state.solver.true ret_state.history.jumpkind = 'Ijk_Ret' # if available, lookup the ...
<SYSTEM_TASK:> Return a concretization of the contents of the file, as a flat bytestring. <END_TASK> <USER_TASK:> Description: def concretize(self, **kwargs): """ Return a concretization of the contents of the file, as a flat bytestring. """
size = self.state.solver.min(self._size, **kwargs) data = self.load(0, size) kwargs['cast_to'] = kwargs.get('cast_to', bytes) kwargs['extra_constraints'] = tuple(kwargs.get('extra_constraints', ())) + (self._size == size,) return self.state.solver.eval(data, **kwargs)
<SYSTEM_TASK:> Returns a list of the packets read or written as bytestrings. <END_TASK> <USER_TASK:> Description: def concretize(self, **kwargs): """ Returns a list of the packets read or written as bytestrings. """
lengths = [self.state.solver.eval(x[1], **kwargs) for x in self.content] kwargs['cast_to'] = bytes return [b'' if i == 0 else self.state.solver.eval(x[0][i*self.state.arch.byte_width-1:], **kwargs) for i, x in zip(lengths, self.content)]
<SYSTEM_TASK:> Write a packet to the stream. <END_TASK> <USER_TASK:> Description: def write(self, pos, data, size=None, events=True, **kwargs): """ Write a packet to the stream. :param int pos: The packet number to write in the sequence of the stream. May be None to append to the stream. ...
if events: self.state.history.add_event('fs_write', filename=self.name, data=data, size=size, pos=pos) # sanity check on read/write modes if self.write_mode is None: self.write_mode = True elif self.write_mode is False: raise SimFileError("Cannot rea...
<SYSTEM_TASK:> Reads some data from the file, storing it into memory. <END_TASK> <USER_TASK:> Description: def read(self, pos, size, **kwargs): """ Reads some data from the file, storing it into memory. :param pos: The address to write the read data into memory :param size: The r...
data, realsize = self.read_data(size, **kwargs) if not self.state.solver.is_true(realsize == 0): self.state.memory.store(pos, data, size=realsize) return realsize
<SYSTEM_TASK:> Writes some data, loaded from the state, into the file. <END_TASK> <USER_TASK:> Description: def write(self, pos, size, **kwargs): """ Writes some data, loaded from the state, into the file. :param pos: The address to read the data to write from in memory :param size:...
if type(pos) is str: raise TypeError("SimFileDescriptor.write takes an address and size. Did you mean write_data?") # Find a reasonable concrete size for the load since we don't want to concretize anything # This is copied from SimFile.read # TODO: refactor into a generic c...
<SYSTEM_TASK:> Find a sinkhole which is large enough to support `length` bytes. <END_TASK> <USER_TASK:> Description: def get_max_sinkhole(self, length): """ Find a sinkhole which is large enough to support `length` bytes. This uses first-fit. The first sinkhole (ordered in descending order by t...
ordered_sinks = sorted(list(self.sinkholes), key=operator.itemgetter(0), reverse=True) max_pair = None for addr, sz in ordered_sinks: if sz >= length: max_pair = (addr, sz) break if max_pair is None: return None remainin...
<SYSTEM_TASK:> A decorator function you should apply to ``copy`` <END_TASK> <USER_TASK:> Description: def memo(f): """ A decorator function you should apply to ``copy`` """
def inner(self, memo=None, **kwargs): if memo is None: memo = {} if id(self) in memo: return memo[id(self)] else: c = f(self, memo, **kwargs) memo[id(self)] = c return c return inner
<SYSTEM_TASK:> Get any VFG node corresponding to the basic block at @addr. <END_TASK> <USER_TASK:> Description: def get_any_node(self, addr): """ Get any VFG node corresponding to the basic block at @addr. Note that depending on the context sensitivity level, there might be multiple node...
for n in self.graph.nodes(): if n.addr == addr: return n
<SYSTEM_TASK:> Executed before analysis starts. Necessary initializations are performed here. <END_TASK> <USER_TASK:> Description: def _pre_analysis(self): """ Executed before analysis starts. Necessary initializations are performed here. :return: None """
l.debug("Starting from %#x", self._start) # initialize the task stack self._task_stack = [ ] # initialize the execution counter dict self._execution_counter = defaultdict(int) # Generate a CFG if no CFG is provided if not self._cfg: l.debug("Gener...
<SYSTEM_TASK:> Get the sorting key of a VFGJob instance. <END_TASK> <USER_TASK:> Description: def _job_sorting_key(self, job): """ Get the sorting key of a VFGJob instance. :param VFGJob job: the VFGJob object. :return: An integer that determines the order of this job in the queue. ...
MAX_BLOCKS_PER_FUNCTION = 1000000 task_functions = list(reversed( list(task.function_address for task in self._task_stack if isinstance(task, FunctionAnalysis)) )) try: function_pos = task_functions.index(job.func_addr) except ValueError: ...
<SYSTEM_TASK:> Generate new jobs for all possible successor targets when there are more than one possible concrete value for <END_TASK> <USER_TASK:> Description: def _handle_successor_multitargets(self, job, successor, all_successors): """ Generate new jobs for all possible successor targets when there ...
new_jobs = [ ] # Currently we assume a legit jumping target cannot have more than 256 concrete values # TODO: make it a setting on VFG MAX_NUMBER_OF_CONCRETE_VALUES = 256 all_possible_ips = successor.solver.eval_upto(successor.ip, MAX_NUMBER_OF_CONCRETE_VALUES + 1) i...
<SYSTEM_TASK:> Merge two given states, and return a new one. <END_TASK> <USER_TASK:> Description: def _merge_states(self, old_state, new_state): """ Merge two given states, and return a new one. :param old_state: :param new_state: :returns: The merged state, and whether a mergin...
# print old_state.dbg_print_stack() # print new_state.dbg_print_stack() merged_state, _, merging_occurred = old_state.merge(new_state, plugin_whitelist=self._mergeable_plugins) # print "Merged: " # print merged_state.dbg_print_stack() return merged_state, merging_occ...
<SYSTEM_TASK:> Perform widen operation on the given states, and return a new one. <END_TASK> <USER_TASK:> Description: def _widen_states(old_state, new_state): """ Perform widen operation on the given states, and return a new one. :param old_state: :param new_state: :returns: Th...
# print old_state.dbg_print_stack() # print new_state.dbg_print_stack() l.debug('Widening state at IP %s', old_state.ip) widened_state, widening_occurred = old_state.widen(new_state) # print "Widened: " # print widened_state.dbg_print_stack() return widened_...
<SYSTEM_TASK:> Try to narrow the state! <END_TASK> <USER_TASK:> Description: def _narrow_states(node, old_state, new_state, previously_widened_state): # pylint:disable=unused-argument,no-self-use """ Try to narrow the state! :param old_state: :param new_state: :param previously...
l.debug('Narrowing state at IP %s', previously_widened_state.ip) s = previously_widened_state.copy() narrowing_occurred = False # TODO: Finish the narrowing logic return s, narrowing_occurred
<SYSTEM_TASK:> Get the state to start the analysis for function. <END_TASK> <USER_TASK:> Description: def _prepare_initial_state(self, function_start, state): """ Get the state to start the analysis for function. :param int function_start: Address of the function :param SimState state: ...
if state is None: state = self.project.factory.blank_state(mode="static", remove_options=self._state_options_to_remove ) # make room for arguments passed to the function sp = ...
<SYSTEM_TASK:> Set the return address of the current state to a specific address. We assume we are at the beginning of a <END_TASK> <USER_TASK:> Description: def _set_return_address(self, state, ret_addr): """ Set the return address of the current state to a specific address. We assume we are at the beg...
# TODO: the following code is totally untested other than X86 and AMD64. Don't freak out if you find bugs :) # TODO: Test it ret_bvv = state.solver.BVV(ret_addr, self.project.arch.bits) if self.project.arch.name in ('X86', 'AMD64'): state.stack_push(ret_bvv) elif ...
<SYSTEM_TASK:> Get an existing VFGNode instance from the graph. <END_TASK> <USER_TASK:> Description: def _graph_get_node(self, block_id, terminator_for_nonexistent_node=False): """ Get an existing VFGNode instance from the graph. :param BlockID block_id: The block ID for the...
if block_id not in self._nodes: l.error("Trying to look up a node that we don't have yet. Is this okay????") if not terminator_for_nonexistent_node: return None # Generate a PathTerminator node addr = block_id.addr func_addr = block_i...
<SYSTEM_TASK:> Add an edge onto the graph. <END_TASK> <USER_TASK:> Description: def _graph_add_edge(self, src_block_id, dst_block_id, **kwargs): """ Add an edge onto the graph. :param BlockID src_block_id: The block ID for source node. :param BlockID dst_block_id: The block Id for desti...
dst_node = self._graph_get_node(dst_block_id, terminator_for_nonexistent_node=True) if src_block_id is None: self.graph.add_node(dst_node) else: src_node = self._graph_get_node(src_block_id, terminator_for_nonexistent_node=True) self.graph.add_edge(src_nod...
<SYSTEM_TASK:> Remove all pending returns that are related to the current job. <END_TASK> <USER_TASK:> Description: def _remove_pending_return(self, job, pending_returns): """ Remove all pending returns that are related to the current job. """
# Build the tuples that we want to remove from the dict fake_func_retn_exits tpls_to_remove = [ ] call_stack_copy = job.call_stack_copy() while call_stack_copy.current_return_target is not None: ret_target = call_stack_copy.current_return_target # Remove the cur...
<SYSTEM_TASK:> Print out debugging information after handling a VFGJob and generating the succeeding jobs. <END_TASK> <USER_TASK:> Description: def _post_job_handling_debug(self, job, successors): """ Print out debugging information after handling a VFGJob and generating the succeeding jobs. :p...
func = self.project.loader.find_symbol(job.addr) function_name = func.name if func is not None else None module_name = self.project.loader.find_object_containing(job.addr).provides l.debug("VFGJob @ %#08x with callstack [ %s ]", job.addr, job.callstack_repr(self.kb), ...
<SYSTEM_TASK:> Save the initial state of a function, and merge it with existing ones if there are any. <END_TASK> <USER_TASK:> Description: def _save_function_initial_state(self, function_key, function_address, state): """ Save the initial state of a function, and merge it with existing ones if there ar...
l.debug('Saving the initial state for function %#08x with function key %s', function_address, function_key ) if function_key in self._function_initial_states[function_address]: existing_state = self._function_initial_states[function_address][...
<SYSTEM_TASK:> Save the final state of a function, and merge it with existing ones if there are any. <END_TASK> <USER_TASK:> Description: def _save_function_final_state(self, function_key, function_address, state): """ Save the final state of a function, and merge it with existing ones if there are any....
l.debug('Saving the final state for function %#08x with function key %s', function_address, function_key ) if function_key in self._function_final_states[function_address]: existing_state = self._function_final_states[function_address][funct...
<SYSTEM_TASK:> Return the ordered merge points for a specific function. <END_TASK> <USER_TASK:> Description: def _merge_points(self, function_address): """ Return the ordered merge points for a specific function. :param int function_address: Address of the querying function. :return: A ...
# we are entering a new function. now it's time to figure out how to optimally traverse the control flow # graph by generating the sorted merge points try: new_function = self.kb.functions[function_address] except KeyError: # the function does not exist ...
<SYSTEM_TASK:> Return the ordered widening points for a specific function. <END_TASK> <USER_TASK:> Description: def _widening_points(self, function_address): """ Return the ordered widening points for a specific function. :param int function_address: Address of the querying function. :r...
# we are entering a new function. now it's time to figure out how to optimally traverse the control flow # graph by generating the sorted merge points try: new_function = self.kb.functions[function_address] except KeyError: # the function does not exist ...
<SYSTEM_TASK:> For a given function, return all nodes in an optimal traversal order. If the function does not exist, return an <END_TASK> <USER_TASK:> Description: def _ordered_node_addrs(self, function_address): """ For a given function, return all nodes in an optimal traversal order. If the function d...
try: function = self.kb.functions[function_address] except KeyError: # the function does not exist return [ ] if function_address not in self._function_node_addrs: sorted_nodes = CFGUtils.quasi_topological_sort_nodes(function.graph) ...
<SYSTEM_TASK:> Assign a new region for under-constrained symbolic execution. <END_TASK> <USER_TASK:> Description: def assign(self, dst_addr_ast): """ Assign a new region for under-constrained symbolic execution. :param dst_addr_ast: the symbolic AST which address of the new allocated region wil...
if dst_addr_ast.uc_alloc_depth > self._max_alloc_depth: raise SimUCManagerAllocationError('Current allocation depth %d is greater than the cap (%d)' % \ (dst_addr_ast.uc_alloc_depth, self._max_alloc_depth)) abs_addr = self._region_base + self._pos ptr = self.state....
<SYSTEM_TASK:> Test whether an AST is bounded by any existing constraint in the related solver. <END_TASK> <USER_TASK:> Description: def is_bounded(self, ast): """ Test whether an AST is bounded by any existing constraint in the related solver. :param ast: an claripy.AST object :return:...
return len(ast.variables.intersection(self.state.solver._solver.variables)) != 0
<SYSTEM_TASK:> Return a string representation of all state options. <END_TASK> <USER_TASK:> Description: def tally(self, exclude_false=True, description=False): """ Return a string representation of all state options. :param bool exclude_false: Whether to exclude Boolean switches that are disa...
total = [ ] for o in sorted(self.OPTIONS.values(), key=lambda x: x.name): try: value = self[o.name] except SimStateOptionsError: value = "<Unset>" if exclude_false and o.one_type() is bool and value is False: # Skip ...
<SYSTEM_TASK:> Register a state option. <END_TASK> <USER_TASK:> Description: def register_option(cls, name, types, default=None, description=None): """ Register a state option. :param str name: Name of the state option. :param types: A collection of allowed types of thi...
if name in cls.OPTIONS: raise SimStateOptionsError("A state option with the same name has been registered.") if isinstance(types, type): types = { types } o = StateOption(name, types, default=default, description=description) cls.OPTIONS[name] = o
<SYSTEM_TASK:> For now a lot of naive concretization is done when handling heap metadata to keep things manageable. This idiom <END_TASK> <USER_TASK:> Description: def concretize(x, solver, sym_handler): """ For now a lot of naive concretization is done when handling heap metadata to keep things manageable. Thi...
if solver.symbolic(x): try: return solver.eval_one(x) except SimSolverError: return sym_handler(x) else: return solver.eval(x)
<SYSTEM_TASK:> return a 5-tuple of strings sufficient for formatting with ``%s%s%s%s%s`` to verbosely describe the procedure <END_TASK> <USER_TASK:> Description: def _describe_me(self): """ return a 5-tuple of strings sufficient for formatting with ``%s%s%s%s%s`` to verbosely describe the procedure ...
return ( self.display_name, ' (cont: %s)' % self.run_func if self.is_continuation else '', ' (syscall)' if self.is_syscall else '', ' (inline)' if not self.use_state_arguments else '', ' (stub)' if self.is_stub else '', )
<SYSTEM_TASK:> Returns the ith argument. Raise a SimProcedureArgumentError if we don't have such an argument available. <END_TASK> <USER_TASK:> Description: def arg(self, i): """ Returns the ith argument. Raise a SimProcedureArgumentError if we don't have such an argument available. :param int ...
if self.use_state_arguments: r = self.cc.arg(self.state, i) else: if i >= len(self.arguments): raise SimProcedureArgumentError("Argument %d does not exist." % i) r = self.arguments[i] # pylint: disable=unsubscriptable-object l.debug...
<SYSTEM_TASK:> Call another SimProcedure in-line to retrieve its return value. <END_TASK> <USER_TASK:> Description: def inline_call(self, procedure, *arguments, **kwargs): """ Call another SimProcedure in-line to retrieve its return value. Returns an instance of the procedure with the ret_expr p...
e_args = [ self.state.solver.BVV(a, self.state.arch.bits) if isinstance(a, int) else a for a in arguments ] p = procedure(project=self.project, **kwargs) return p.execute(self.state, None, arguments=e_args)
<SYSTEM_TASK:> Add an exit representing a return from this function. <END_TASK> <USER_TASK:> Description: def ret(self, 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...
self.inhibit_autoret = True if expr is not None: if o.SIMPLIFY_RETS in self.state.options: l.debug("... simplifying") l.debug("... before: %s", expr) expr = self.state.solver.simplify(expr) l.debug("... after: %s", expr) ...
<SYSTEM_TASK:> Add an exit representing calling another function via pointer. <END_TASK> <USER_TASK:> Description: def call(self, addr, args, continue_at, cc=None): """ Add an exit representing calling another function via pointer. :param addr: The address of the function to call ...
self.inhibit_autoret = True if cc is None: cc = self.cc call_state = self.state.copy() ret_addr = self.make_continuation(continue_at) saved_local_vars = list(zip(self.local_vars, map(lambda name: getattr(self, name), self.local_vars))) simcallstack_entry = ...
<SYSTEM_TASK:> Add an exit representing jumping to an address. <END_TASK> <USER_TASK:> Description: def jump(self, addr): """ Add an exit representing jumping to an address. """
self.inhibit_autoret = True self._exit_action(self.state, addr) self.successors.add_successor(self.state, addr, self.state.solver.true, 'Ijk_Boring')
<SYSTEM_TASK:> Add an exit representing terminating the program. <END_TASK> <USER_TASK:> Description: def exit(self, exit_code): """ Add an exit representing terminating the program. """
self.inhibit_autoret = True self.state.options.discard(o.AST_DEPS) self.state.options.discard(o.AUTO_REFS) if isinstance(exit_code, int): exit_code = self.state.solver.BVV(exit_code, self.state.arch.bits) self.state.history.add_event('terminate', exit_code=exit_code...
<SYSTEM_TASK:> This is a backward lookup in the previous defs. <END_TASK> <USER_TASK:> Description: def _def_lookup(self, live_defs, variable): """ This is a backward lookup in the previous defs. :param addr_list: a list of normalized addresses. Note that, as we are usin...
prevdefs = { } if variable in live_defs: code_loc_set = live_defs[variable] for code_loc in code_loc_set: # Label edges with cardinality or actual sets of addresses if isinstance(variable, SimMemoryVariable): type_ = 'mem' ...
<SYSTEM_TASK:> Get all DDG nodes matching the given basic block address and statement index. <END_TASK> <USER_TASK:> Description: def get_all_nodes(self, simrun_addr, stmt_idx): """ Get all DDG nodes matching the given basic block address and statement index. """
nodes=[] for n in self.graph.nodes(): if n.simrun_addr == simrun_addr and n.stmt_idx == stmt_idx: nodes.add(n) return nodes
<SYSTEM_TASK:> Yields each of the individual lane pairs from the arguments, in <END_TASK> <USER_TASK:> Description: def vector_args(self, args): """ Yields each of the individual lane pairs from the arguments, in order from most significan to least significant """
for i in reversed(range(self._vector_count)): pieces = [] for vec in args: pieces.append(vec[(i+1) * self._vector_size - 1 : i * self._vector_size]) yield pieces
<SYSTEM_TASK:> Halving add, for some ARM NEON instructions. <END_TASK> <USER_TASK:> Description: def _op_generic_HAdd(self, args): """ Halving add, for some ARM NEON instructions. """
components = [] for a, b in self.vector_args(args): if self.is_signed: a = a.sign_extend(self._vector_size) b = b.sign_extend(self._vector_size) else: a = a.zero_extend(self._vector_size) b = b.zero_extend(self._vec...
<SYSTEM_TASK:> Return unsigned saturated BV from signed BV. <END_TASK> <USER_TASK:> Description: def _op_generic_StoU_saturation(self, value, min_value, max_value): #pylint:disable=no-self-use """ Return unsigned saturated BV from signed BV. Min and max value should be unsigned. """
return claripy.If( claripy.SGT(value, max_value), max_value, claripy.If(claripy.SLT(value, min_value), min_value, value))
<SYSTEM_TASK:> Sets an instance field. <END_TASK> <USER_TASK:> Description: def set_field(self, state, field_name, field_type, value): """ Sets an instance field. """
field_ref = SimSootValue_InstanceFieldRef.get_ref(state=state, obj_alloc_id=self.heap_alloc_id, field_class_name=self.type, field_name=fi...
<SYSTEM_TASK:> Gets the value of an instance field. <END_TASK> <USER_TASK:> Description: def get_field(self, state, field_name, field_type): """ Gets the value of an instance field. """
# get field reference field_ref = SimSootValue_InstanceFieldRef.get_ref(state=state, obj_alloc_id=self.heap_alloc_id, field_class_name=self.type, ...
<SYSTEM_TASK:> Store a field of a given object, without resolving hierachy <END_TASK> <USER_TASK:> Description: def store_field(self, state, field_name, field_type, value): """ Store a field of a given object, without resolving hierachy :param state: angr state where we want to allocate the obj...
field_ref = SimSootValue_InstanceFieldRef(self.heap_alloc_id, self.type, field_name, field_type) state.memory.store(field_ref, value)
<SYSTEM_TASK:> Load a field of a given object, without resolving hierachy <END_TASK> <USER_TASK:> Description: def load_field(self, state, field_name, field_type): """ Load a field of a given object, without resolving hierachy :param state: angr state where we want to load the object attribute ...
field_ref = SimSootValue_InstanceFieldRef(self.heap_alloc_id, self.type, field_name, field_type) return state.memory.load(field_ref, none_if_missing=False)
<SYSTEM_TASK:> This function prepares a state that is executing a call instruction. <END_TASK> <USER_TASK:> Description: def prepare_call_state(self, calling_state, initial_state=None, preserve_registers=(), preserve_memory=()): """ This function prepares a state that is execu...
if isinstance(self.arch, ArchMIPS32): if initial_state is not None: initial_state = self.state_blank() mips_caller_saves = ('s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 'gp', 'sp', 'bp', 'ra') preserve_registers = preserve_registers + mips_caller_saves + ...
<SYSTEM_TASK:> Prepare the address space with the data necessary to perform relocations pointing to the given symbol <END_TASK> <USER_TASK:> Description: def prepare_function_symbol(self, symbol_name, basic_addr=None): """ Prepare the address space with the data necessary to perform relocations pointing...
if basic_addr is None: basic_addr = self.project.loader.extern_object.get_pseudo_addr(symbol_name) return basic_addr, basic_addr
<SYSTEM_TASK:> Write the GlobalDescriptorTable object in the current state memory <END_TASK> <USER_TASK:> Description: def setup_gdt(self, state, gdt): """ Write the GlobalDescriptorTable object in the current state memory :param state: state in which to write the GDT :param gdt: Global...
state.memory.store(gdt.addr+8, gdt.table) state.regs.gdt = gdt.gdt state.regs.cs = gdt.cs state.regs.ds = gdt.ds state.regs.es = gdt.es state.regs.ss = gdt.ss state.regs.fs = gdt.fs state.regs.gs = gdt.gs
<SYSTEM_TASK:> Generate a GlobalDescriptorTable object and populate it using the value of the gs and fs register <END_TASK> <USER_TASK:> Description: def generate_gdt(self, fs, gs, fs_size=0xFFFFFFFF, gs_size=0xFFFFFFFF): """ Generate a GlobalDescriptorTable object and populate it using the value of the...
A_PRESENT = 0x80 A_DATA = 0x10 A_DATA_WRITABLE = 0x2 A_PRIV_0 = 0x0 A_DIR_CON_BIT = 0x4 F_PROT_32 = 0x4 S_GDT = 0x0 S_PRIV_0 = 0x0 GDT_ADDR = 0x4000 GDT_LIMIT = 0x1000 normal_entry = self._create_gdt_entry(0, 0xFFFFFFFF, ...
<SYSTEM_TASK:> Register a struct definition globally <END_TASK> <USER_TASK:> Description: def define_struct(defn): """ Register a struct definition globally >>> define_struct('struct abcd {int x; int y;}') """
struct = parse_type(defn) ALL_TYPES[struct.name] = struct return struct
<SYSTEM_TASK:> Run a string through the C preprocessor that ships with pycparser but is weirdly inaccessible? <END_TASK> <USER_TASK:> Description: def do_preprocess(defn): """ Run a string through the C preprocessor that ships with pycparser but is weirdly inaccessible? """
from pycparser.ply import lex, cpp lexer = lex.lex(cpp) p = cpp.Preprocessor(lexer) # p.add_path(dir) will add dir to the include search path p.parse(defn) return ''.join(tok.value for tok in p.parser if tok.type not in p.ignore)
<SYSTEM_TASK:> Parse a series of C definitions, returns a tuple of two type mappings, one for variable <END_TASK> <USER_TASK:> Description: def parse_file(defn, preprocess=True): """ Parse a series of C definitions, returns a tuple of two type mappings, one for variable definitions and one for type definiti...
if pycparser is None: raise ImportError("Please install pycparser in order to parse C definitions") defn = '\n'.join(x for x in defn.split('\n') if _include_re.match(x) is None) if preprocess: defn = do_preprocess(defn) preamble, ignoreme = make_preamble() node = pycparser.c_pars...
<SYSTEM_TASK:> The alignment of the type in bytes. <END_TASK> <USER_TASK:> Description: def alignment(self): """ The alignment of the type in bytes. """
if self._arch is None: return NotImplemented return self.size // self._arch.byte_width
<SYSTEM_TASK:> This is a hack to deal with small values being stored at offsets into large registers unpredictably <END_TASK> <USER_TASK:> Description: def _fix_offset(self, state, size, arch=None): """ This is a hack to deal with small values being stored at offsets into large registers unpredictably ...
if state is not None: arch = state.arch if arch is None: raise ValueError('Either "state" or "arch" must be specified.') offset = arch.registers[self.reg_name][0] if size in self.alt_offsets: return offset + self.alt_offsets[size] elif size ...
<SYSTEM_TASK:> Iterate through all the possible arg positions that can only be used to store integer or pointer values <END_TASK> <USER_TASK:> Description: def int_args(self): """ Iterate through all the possible arg positions that can only be used to store integer or pointer values Does not tak...
if self.ARG_REGS is None: raise NotImplementedError() for reg in self.ARG_REGS: # pylint: disable=not-an-iterable yield SimRegArg(reg, self.arch.bytes)
<SYSTEM_TASK:> Iterate through all the possible arg positions that can be used to store any kind of argument <END_TASK> <USER_TASK:> Description: def both_args(self): """ Iterate through all the possible arg positions that can be used to store any kind of argument Does not take into account cust...
turtle = self.STACKARG_SP_BUFF + self.STACKARG_SP_DIFF while True: yield SimStackArg(turtle, self.arch.bytes) turtle += self.arch.bytes
<SYSTEM_TASK:> Iterate through all the possible arg positions that can only be used to store floating point values <END_TASK> <USER_TASK:> Description: def fp_args(self): """ Iterate through all the possible arg positions that can only be used to store floating point values Does not take into ac...
if self.FP_ARG_REGS is None: raise NotImplementedError() for reg in self.FP_ARG_REGS: # pylint: disable=not-an-iterable yield SimRegArg(reg, self.arch.registers[reg][1])
<SYSTEM_TASK:> This should take a SimFunctionArgument instance and return whether or not that argument is a floating-point <END_TASK> <USER_TASK:> Description: def is_fp_arg(self, arg): """ This should take a SimFunctionArgument instance and return whether or not that argument is a floating-point ...
if arg in self.int_args: return False if arg in self.fp_args or arg == self.FP_RETURN_VAL: return True return None
<SYSTEM_TASK:> Returns a bitvector expression representing the nth argument of a function. <END_TASK> <USER_TASK:> Description: def arg(self, state, index, stack_base=None): """ Returns a bitvector expression representing the nth argument of a function. `stack_base` is an optional pointer to th...
session = self.arg_session if self.args is None: arg_loc = [session.next_arg(False) for _ in range(index + 1)][-1] else: arg_loc = self.args[index] return arg_loc.get_value(state, stack_base=stack_base)
<SYSTEM_TASK:> `is_fp` should be a list of booleans specifying whether each corresponding argument is floating-point - <END_TASK> <USER_TASK:> Description: def get_args(self, state, is_fp=None, sizes=None, stack_base=None): """ `is_fp` should be a list of booleans specifying whether each corresponding a...
if sizes is None and self.func_ty is not None: sizes = [arg.size for arg in self.func_ty.args] if is_fp is None: if self.args is None: if self.func_ty is None: raise ValueError("You must either customize this CC or pass a value to is_fp!") ...
<SYSTEM_TASK:> This function performs the actions of the callee as it's getting ready to return. <END_TASK> <USER_TASK:> Description: def teardown_callsite(self, state, return_val=None, arg_types=None, force_callee_cleanup=False): """ This function performs the actions of the callee as it's getting read...
if return_val is not None: self.set_return_val(state, return_val) ret_addr = self.return_addr.get_value(state) if state.arch.sp_offset is not None: if force_callee_cleanup or self.CALLEE_CLEANUP: if arg_types is not None: session = s...
<SYSTEM_TASK:> Get the return value out of the given state <END_TASK> <USER_TASK:> Description: def get_return_val(self, state, is_fp=None, size=None, stack_base=None): """ Get the return value out of the given state """
ty = self.func_ty.returnty if self.func_ty is not None else None if self.ret_val is not None: loc = self.ret_val elif is_fp is not None: loc = self.FP_RETURN_VAL if is_fp else self.RETURN_VAL elif ty is not None: loc = self.FP_RETURN_VAL if isinstance...
<SYSTEM_TASK:> Set the return value into the given state <END_TASK> <USER_TASK:> Description: def set_return_val(self, state, val, is_fp=None, size=None, stack_base=None): """ Set the return value into the given state """
ty = self.func_ty.returnty if self.func_ty is not None else None try: betterval = self._standardize_value(val, ty, state, None) except AttributeError: raise ValueError("Can't fit value %s into a return value" % repr(val)) if self.ret_val is not None: ...
<SYSTEM_TASK:> Pinpoint the best-fit calling convention and return the corresponding SimCC instance, or None if no fit is <END_TASK> <USER_TASK:> Description: def find_cc(arch, args, sp_delta): """ Pinpoint the best-fit calling convention and return the corresponding SimCC instance, or None if no fit is...
if arch.name not in CC: return None possible_cc_classes = CC[arch.name] for cc_cls in possible_cc_classes: if cc_cls._match(arch, args, sp_delta): return cc_cls(arch, args=args, sp_delta=sp_delta) return None
<SYSTEM_TASK:> Add a successor state of the SimRun. <END_TASK> <USER_TASK:> Description: def add_successor(self, 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 sto...
# First, trigger the SimInspect breakpoint state._inspect('exit', BP_BEFORE, exit_target=target, exit_guard=guard, exit_jumpkind=jumpkind) state.scratch.target = state._inspect_getattr("exit_target", target) state.scratch.guard = state._inspect_getattr("exit_guard", guard) stat...
<SYSTEM_TASK:> Preprocesses the successor state. <END_TASK> <USER_TASK:> Description: def _preprocess_successor(self, state, add_guard=True): #pylint:disable=unused-argument """ Preprocesses the successor state. :param state: the successor state """
# Next, simplify what needs to be simplified if o.SIMPLIFY_EXIT_STATE in state.options: state.solver.simplify() if o.SIMPLIFY_EXIT_GUARD in state.options: state.scratch.guard = state.solver.simplify(state.scratch.guard) if o.SIMPLIFY_EXIT_TARGET in state.options...
<SYSTEM_TASK:> Resolve syscall information from the state, get the IP address of the syscall SimProcedure, and set the IP of <END_TASK> <USER_TASK:> Description: def _fix_syscall_ip(state): """ Resolve syscall information from the state, get the IP address of the syscall SimProcedure, and set the IP of ...
try: bypass = o.BYPASS_UNSUPPORTED_SYSCALL in state.options stub = state.project.simos.syscall(state, allow_unsupported=bypass) if stub: # can be None if simos is not a subclass of SimUserspace state.ip = stub.addr # fix the IP except AngrUnsupported...
<SYSTEM_TASK:> Finalizes the request. <END_TASK> <USER_TASK:> Description: def _finalize(self): """ Finalizes the request. """
if len(self.all_successors) == 0: return # do some cleanup if o.DOWNSIZE_Z3 in self.all_successors[0].options: for s in self.all_successors: s.downsize() # record if the exit is unavoidable if len(self.flat_successors) == 1 and len(self....
<SYSTEM_TASK:> The traditional way of evaluating symbolic jump targets. <END_TASK> <USER_TASK:> Description: def _eval_target_brutal(state, ip, limit): """ The traditional way of evaluating symbolic jump targets. :param state: A SimState instance. :param ip: The AST of the instru...
addrs = state.solver.eval_upto(ip, limit) return [ (ip == addr, addr) for addr in addrs ]
<SYSTEM_TASK:> Get a long number for a byte being repeated for many times. This is part of the effort of optimizing <END_TASK> <USER_TASK:> Description: def _repeat_bytes(byt, rep): """ Get a long number for a byte being repeated for many times. This is part of the effort of optimizing performan...
if rep == 1: return byt remainder = rep % 2 quotient = rep // 2 r_ = memset._repeat_bytes(byt, quotient) if remainder == 1: r = r_ << ((quotient + 1) * 8) r |= (r_ << 8) + byt else: r = r_ << (quotient * 8) r...
<SYSTEM_TASK:> Stores a memory object. <END_TASK> <USER_TASK:> Description: def store_mo(self, state, new_mo, overwrite=True): #pylint:disable=unused-argument """ Stores a memory object. :param new_mo: the memory object :param overwrite: whether to overwrite objects already in memory (i...
start, end = self._resolve_range(new_mo) if overwrite: self.store_overwrite(state, new_mo, start, end) else: self.store_underwrite(state, new_mo, start, end)
<SYSTEM_TASK:> Tests if the address is contained in any page of paged memory, without considering memory backers. <END_TASK> <USER_TASK:> Description: def contains_no_backer(self, addr): """ Tests if the address is contained in any page of paged memory, without considering memory backers. :para...
for i, p in self._pages.items(): if i * self._page_size <= addr < (i + 1) * self._page_size: return addr - (i * self._page_size) in p.keys() return False
<SYSTEM_TASK:> Writes a memory object to a `page` <END_TASK> <USER_TASK:> Description: def _apply_object_to_page(self, page_base, mo, page=None, overwrite=True): """ Writes a memory object to a `page` :param page_base: The base address of the page. :param mo: The memory objec...
page_num = page_base // self._page_size try: page = self._get_page(page_num, write=True, create=not self.allow_segv) if page is None else page except KeyError: if self.allow_segv: raise S...
<SYSTEM_TASK:> Replaces the memory object `old` with a new memory object containing `new_content`. <END_TASK> <USER_TASK:> Description: def replace_memory_object(self, old, new_content): """ Replaces the memory object `old` with a new memory object containing `new_content`. :param old: ...
if old.object.size() != new_content.size(): raise SimMemoryError("memory objects can only be replaced by the same length content") new = SimMemoryObject(new_content, old.base, byte_width=self.byte_width) for p in self._containing_pages_mo(old): self._get_page(p//self._...
<SYSTEM_TASK:> Replaces all instances of expression `old` with expression `new`. <END_TASK> <USER_TASK:> Description: def replace_all(self, old, new): """ Replaces all instances of expression `old` with expression `new`. :param old: A claripy expression. Must contain at least one named variable...
if options.REVERSE_MEMORY_NAME_MAP not in self.state.options: raise SimMemoryError("replace_all is not doable without a reverse name mapping. Please add " "sim_options.REVERSE_MEMORY_NAME_MAP to the state options") if not isinstance(old, claripy.ast.BV) or...
<SYSTEM_TASK:> Returns addresses that contain expressions that contain a variable named `n`. <END_TASK> <USER_TASK:> Description: def addrs_for_name(self, n): """ Returns addresses that contain expressions that contain a variable named `n`. """
if n not in self._name_mapping: return self._mark_updated_mapping(self._name_mapping, n) to_discard = set() for e in self._name_mapping[n]: try: if n in self[e].object.variables: yield e else: to_discard.add(e) except...
<SYSTEM_TASK:> Returns addresses that contain expressions that contain a variable with the hash of `h`. <END_TASK> <USER_TASK:> Description: def addrs_for_hash(self, h): """ Returns addresses that contain expressions that contain a variable with the hash of `h`. """
if h not in self._hash_mapping: return self._mark_updated_mapping(self._hash_mapping, h) to_discard = set() for e in self._hash_mapping[h]: try: if h == hash(self[e].object): yield e else: to_discard.add(e) except Key...
<SYSTEM_TASK:> Updates the signal mask. <END_TASK> <USER_TASK:> Description: def sigprocmask(self, how, new_mask, sigsetsize, valid_ptr=True): """ Updates the signal mask. :param how: the "how" argument of sigprocmask (see manpage) :param new_mask: the mask modification to apply ...
oldmask = self.sigmask(sigsetsize) self._sigmask = self.state.solver.If(valid_ptr, self.state.solver.If(how == self.SIG_BLOCK, oldmask | new_mask, self.state.solver.If(how == self.SIG_UNBLOCK, oldmask & (~new_mask), sel...
<SYSTEM_TASK:> Returns the concrete content for a file by path. <END_TASK> <USER_TASK:> Description: def dump_file_by_path(self, path, **kwargs): """ Returns the concrete content for a file by path. :param path: file path as string :param kwargs: passed to state.solver.eval :ret...
file = self.state.fs.get(path) if file is None: return None return file.concretize(**kwargs)
<SYSTEM_TASK:> Returns the concrete content for a file descriptor. <END_TASK> <USER_TASK:> Description: def dumps(self, 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, st...
if 0 <= fd <= 2: data = [self.stdin, self.stdout, self.stderr][fd].concretize(**kwargs) if type(data) is list: data = b''.join(data) return data return self.get_fd(fd).concretize(**kwargs)
<SYSTEM_TASK:> This function receives an initial state and imark and processes a list of pyvex.IRStmts <END_TASK> <USER_TASK:> Description: def _handle_statement(self, state, successors, stmt): """ This function receives an initial state and imark and processes a list of pyvex.IRStmts It annotat...
if type(stmt) == pyvex.IRStmt.IMark: # TODO how much of this could be moved into the imark handler ins_addr = stmt.addr + stmt.delta state.scratch.ins_addr = ins_addr # Raise an exception if we're suddenly in self-modifying code for subaddr in range(...
<SYSTEM_TASK:> Generate a sif file from the call map. <END_TASK> <USER_TASK:> Description: def _genenare_callmap_sif(self, filepath): """ Generate a sif file from the call map. :param filepath: Path of the sif file :return: None """
with open(filepath, "wb") as f: for src, dst in self.callgraph.edges(): f.write("%#x\tDirectEdge\t%#x\n" % (src, dst))
<SYSTEM_TASK:> Return the function who has the least address that is greater than or equal to `addr`. <END_TASK> <USER_TASK:> Description: def ceiling_func(self, addr): """ Return the function who has the least address that is greater than or equal to `addr`. :param int addr: The address to que...
try: next_addr = self._function_map.ceiling_addr(addr) return self._function_map.get(next_addr) except KeyError: return None
<SYSTEM_TASK:> Return the function who has the greatest address that is less than or equal to `addr`. <END_TASK> <USER_TASK:> Description: def floor_func(self, addr): """ Return the function who has the greatest address that is less than or equal to `addr`. :param int addr: The address to query...
try: prev_addr = self._function_map.floor_addr(addr) return self._function_map[prev_addr] except KeyError: return None
<SYSTEM_TASK:> Get a function object from the function manager. <END_TASK> <USER_TASK:> Description: def function(self, addr=None, name=None, create=False, syscall=False, plt=None): """ Get a function object from the function manager. Pass either `addr` or `name` with the appropriate values. ...
if addr is not None: try: f = self._function_map.get(addr) if plt is None or f.is_plt == plt: return f except KeyError: if create: # the function is not found f = self._function_m...
<SYSTEM_TASK:> Return a list of nodes that are control dependent on the given node in the control dependence graph <END_TASK> <USER_TASK:> Description: def get_dependants(self, run): """ Return a list of nodes that are control dependent on the given node in the control dependence graph """
if run in self._graph.nodes(): return list(self._graph.successors(run)) else: return []
<SYSTEM_TASK:> Return a list of nodes on whom the specific node is control dependent in the control dependence graph <END_TASK> <USER_TASK:> Description: def get_guardians(self, run): """ Return a list of nodes on whom the specific node is control dependent in the control dependence graph """
if run in self._graph.nodes(): return list(self._graph.predecessors(run)) else: return []
<SYSTEM_TASK:> Construct a control dependence graph. <END_TASK> <USER_TASK:> Description: def _construct(self): """ Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. ...
self._acyclic_cfg = self._cfg.copy() # TODO: Cycle-removing is not needed - confirm it later # The CFG we use should be acyclic! #self._acyclic_cfg.remove_cycles() # Pre-process the acyclic CFG self._pre_process_cfg() # Construct post-dominator tree se...
<SYSTEM_TASK:> There are cases where a loop has two overlapping loop headers thanks <END_TASK> <USER_TASK:> Description: def _post_process(self): """ There are cases where a loop has two overlapping loop headers thanks to the way VEX is dealing with continuous instructions. As we were br...
# TODO: Verify its correctness loop_back_edges = self._cfg.get_loop_back_edges() for b1, b2 in loop_back_edges: self._graph.add_edge(b1, b2)
<SYSTEM_TASK:> Create a phi variable for variables at block `block_addr`. <END_TASK> <USER_TASK:> Description: def make_phi_node(self, block_addr, *variables): """ Create a phi variable for variables at block `block_addr`. :param int block_addr: The address of the current block. :param...
existing_phis = set() non_phis = set() for var in variables: if self.is_phi_variable(var): existing_phis.add(var) else: non_phis.add(var) if len(existing_phis) == 1: existing_phi = next(iter(existing_phis)) ...
<SYSTEM_TASK:> Get a list of variables. <END_TASK> <USER_TASK:> Description: def get_variables(self, sort=None, collapse_same_ident=False): """ Get a list of variables. :param str or None sort: Sort of the variable to get. :param collapse_same_ident: Whether variables of the same ide...
variables = [ ] if collapse_same_ident: raise NotImplementedError() for var in self._variables: if sort == 'stack' and not isinstance(var, SimStackVariable): continue if sort == 'reg' and not isinstance(var, SimRegisterVariable): ...
<SYSTEM_TASK:> Get sub-variables that phi variable `var` represents. <END_TASK> <USER_TASK:> Description: def get_phi_subvariables(self, var): """ Get sub-variables that phi variable `var` represents. :param SimVariable var: The variable instance. :return: A set of sub-va...
if not self.is_phi_variable(var): return set() return self._phi_variables[var]