text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Extract the actual formats from the format string `fmt`. <END_TASK> <USER_TASK:> Description: def _get_fmt(self, fmt): """ Extract the actual formats from the format string `fmt`. :param list fmt: A list of format chars. :returns: a FormatString object """
# iterate over the format string looking for format specifiers components = [ ] i = 0 while i < len(fmt): if type(fmt[i]) is bytes and fmt[i] == b"%": # Note that we only support concrete format specifiers # grab the specifier # go to the space specifier = b"" for c in fmt[i+1:]: if type(c) is bytes: specifier += c else: break specifier = self._match_spec(specifier) if specifier is not None: i += len(specifier) components.append(specifier) else: # if we get here we didn't match any specs, the first char will be thrown away # and we'll add the percent i += 1 components.append(b'%') else: # claripy ASTs, which are usually symbolic variables # They will be kept as they are - even if those chars can be evaluated to "%" components.append(fmt[i]) i += 1 return FormatString(self, components)
<SYSTEM_TASK:> Return the result of invoking the atoi simprocedure on `str_addr`. <END_TASK> <USER_TASK:> Description: def _sim_atoi_inner(self, str_addr, region, base=10, read_length=None): """ Return the result of invoking the atoi simprocedure on `str_addr`. """
from .. import SIM_PROCEDURES strtol = SIM_PROCEDURES['libc']['strtol'] return strtol.strtol_inner(str_addr, self.state, region, base, True, read_length=read_length)
<SYSTEM_TASK:> Parse format strings. <END_TASK> <USER_TASK:> Description: def _parse(self, fmt_idx): """ Parse format strings. :param fmt_idx: The index of the (pointer to the) format string in the arguments list. :returns: A FormatString object which can be used for replacing the format specifiers with arguments or for scanning into arguments. """
fmtstr_ptr = self.arg(fmt_idx) if self.state.solver.symbolic(fmtstr_ptr): raise SimProcedureError("Symbolic pointer to (format) string :(") length = self._sim_strlen(fmtstr_ptr) if self.state.solver.symbolic(length): all_lengths = self.state.solver.eval_upto(length, 2) if len(all_lengths) != 1: raise SimProcedureError("Symbolic (format) string, game over :(") length = all_lengths[0] if self.state.solver.is_true(length == 0): return FormatString(self, [b""]) fmt_xpr = self.state.memory.load(fmtstr_ptr, length) fmt = [ ] for i in range(fmt_xpr.size(), 0, -8): char = fmt_xpr[i - 1 : i - 8] try: conc_char = self.state.solver.eval_one(char) except SimSolverError: # For symbolic chars, just keep them symbolic fmt.append(char) else: # Concrete chars are directly appended to the list fmt.append(bytes([conc_char])) # make a FormatString object fmt_str = self._get_fmt(fmt) l.debug("Fmt: %r", fmt_str) return fmt_str
<SYSTEM_TASK:> Pre-process an AST for insertion into unicorn. <END_TASK> <USER_TASK:> Description: def _process_value(self, d, from_where): """ Pre-process an AST for insertion into unicorn. :param d: the AST :param from_where: the ID of the memory region it comes from ('mem' or 'reg') :returns: the value to be inserted into Unicorn, or None """
if len(d.annotations): l.debug("Blocking annotated AST.") return None elif not d.symbolic: return d else: l.debug("Processing AST with variables %s.", d.variables) dd = self._symbolic_passthrough(d) if not dd.symbolic: if d.symbolic: l.debug("... concretized") return dd elif from_where == 'reg' and options.UNICORN_SYM_REGS_SUPPORT in self.state.options: l.debug("... allowing symbolic register") return dd else: l.debug("... denied") return None
<SYSTEM_TASK:> This callback is called when unicorn needs to access data that's not yet present in memory. <END_TASK> <USER_TASK:> Description: def _hook_mem_unmapped(self, uc, access, address, size, value, user_data, size_extension=True): #pylint:disable=unused-argument """ This callback is called when unicorn needs to access data that's not yet present in memory. """
# FIXME check angr hooks at `address` if size_extension: start = address & (0xfffffffffffff0000) length = ((address + size + 0xffff) & (0xfffffffffffff0000)) - start else: start = address & (0xffffffffffffff000) length = ((address + size + 0xfff) & (0xffffffffffffff000)) - start if (start == 0 or ((start + length) & ((1 << self.state.arch.bits) - 1)) == 0) and options.UNICORN_ZEROPAGE_GUARD in self.state.options: # sometimes it happens because of %fs is not correctly set self.error = 'accessing zero page [%#x, %#x] (%#x)' % (address, address + length - 1, access) l.warning(self.error) # tell uc_state to rollback _UC_NATIVE.stop(self._uc_state, STOP.STOP_ZEROPAGE) return False ret = False try: best_effort_read = size_extension ret = self._hook_mem_unmapped_core(uc, access, start, length, best_effort_read=best_effort_read) except AccessingZeroPageError: # raised when STRICT_PAGE_ACCESS is enabled if not size_extension: _UC_NATIVE.stop(self._uc_state, STOP.STOP_SEGFAULT) ret = False except FetchingZeroPageError: # raised when trying to execute code on an unmapped page if not size_extension: self.error = 'fetching empty page [%#x, %#x]' % (start, start + length - 1) l.warning(self.error) _UC_NATIVE.stop(self._uc_state, STOP.STOP_EXECNONE) ret = False except SimMemoryError: if not size_extension: raise except SegfaultError: if not size_extension: _UC_NATIVE.stop(self._uc_state, STOP.STOP_SEGFAULT) ret = False except MixedPermissonsError: if not size_extension: # weird... it shouldn't be raised at all l.error('MixedPermissionsError is raised when size-extension is disabled. Please report it.') _UC_NATIVE.stop(self._uc_state, STOP.STOP_SEGFAULT) ret = False except unicorn.UcError as ex: if not size_extension: if ex.errno == 11: # Mapping failed. Probably because of size extension... let's try to redo it without size extension pass else: # just raise the exception raise finally: if size_extension and not ret: # retry without size-extension if size-extension was enabled # any exception will not be caught ret = self._hook_mem_unmapped(uc, access, address, size, value, user_data, size_extension=False) return ret
<SYSTEM_TASK:> For each instruction, track its stack pointer offset and stack base pointer offset. <END_TASK> <USER_TASK:> Description: def _track_stack_pointers(self): """ For each instruction, track its stack pointer offset and stack base pointer offset. :return: None """
regs = {self.project.arch.sp_offset} if hasattr(self.project.arch, 'bp_offset') and self.project.arch.bp_offset is not None: regs.add(self.project.arch.bp_offset) spt = self.project.analyses.StackPointerTracker(self.function, regs, track_memory=self._sp_tracker_track_memory) if spt.inconsistent_for(self.project.arch.sp_offset): l.warning("Inconsistency found during stack pointer tracking. Decompilation results might be incorrect.") return spt
<SYSTEM_TASK:> Simplify all blocks in self._blocks. <END_TASK> <USER_TASK:> Description: def _simplify_blocks(self, stack_pointer_tracker=None): """ Simplify all blocks in self._blocks. :param stack_pointer_tracker: The RegisterDeltaTracker analysis instance. :return: None """
# First of all, let's simplify blocks one by one for key in self._blocks: ail_block = self._blocks[key] simplified = self._simplify_block(ail_block, stack_pointer_tracker=stack_pointer_tracker) self._blocks[key] = simplified # Update the function graph so that we can use reaching definitions self._update_graph()
<SYSTEM_TASK:> Simplify a single AIL block. <END_TASK> <USER_TASK:> Description: def _simplify_block(self, ail_block, stack_pointer_tracker=None): """ Simplify a single AIL block. :param ailment.Block ail_block: The AIL block to simplify. :param stack_pointer_tracker: The RegisterDeltaTracker analysis instance. :return: A simplified AIL block. """
simp = self.project.analyses.AILBlockSimplifier(ail_block, stack_pointer_tracker=stack_pointer_tracker) return simp.result_block
<SYSTEM_TASK:> Simplify the entire function. <END_TASK> <USER_TASK:> Description: def _simplify_function(self): """ Simplify the entire function. :return: None """
# Computing reaching definitions rd = self.project.analyses.ReachingDefinitions(func=self.function, func_graph=self.graph, observe_all=True) simp = self.project.analyses.AILSimplifier(self.function, func_graph=self.graph, reaching_definitions=rd) for key in list(self._blocks.keys()): old_block = self._blocks[key] if old_block in simp.blocks: self._blocks[key] = simp.blocks[old_block] self._update_graph()
<SYSTEM_TASK:> Get a class descriptor for the class. <END_TASK> <USER_TASK:> Description: def get_class(self, class_name, init_class=False, step_func=None): """ Get a class descriptor for the class. :param str class_name: Name of class. :param bool init_class: Whether the class initializer <clinit> should be executed. :param func step_func: Callback function executed at every step of the simulation manager during the execution of the main <clinit> method """
# try to get the soot class object from CLE java_binary = self.state.javavm_registers.load('ip_binary') soot_class = java_binary.get_soot_class(class_name, none_if_missing=True) # create class descriptor class_descriptor = SootClassDescriptor(class_name, soot_class) # load/initialize class if init_class: self.init_class(class_descriptor, step_func=step_func) return class_descriptor
<SYSTEM_TASK:> Get the superclass of the class. <END_TASK> <USER_TASK:> Description: def get_superclass(self, class_): """ Get the superclass of the class. """
if not class_.is_loaded or class_.superclass_name is None: return None return self.get_class(class_.superclass_name)
<SYSTEM_TASK:> Backward slicing. <END_TASK> <USER_TASK:> Description: def _backward_slice(self): """ Backward slicing. We support the following IRStmts: # WrTmp # Put We support the following IRExprs: # Get # RdTmp # Const :return: """
temps = set() regs = set() # Retrieve the target: are we slicing from a register(IRStmt.Put), or a temp(IRStmt.WrTmp)? try: stmts = self._get_irsb(self._dst_run).statements except SimTranslationError: return if self._dst_stmt_idx != -1: dst_stmt = stmts[self._dst_stmt_idx] if type(dst_stmt) is pyvex.IRStmt.Put: regs.add(dst_stmt.offset) elif type(dst_stmt) is pyvex.IRStmt.WrTmp: temps.add(dst_stmt.tmp) else: raise AngrBladeError('Incorrect type of the specified target statement. We only support Put and WrTmp.') prev = (self._get_addr(self._dst_run), self._dst_stmt_idx) else: next_expr = self._get_irsb(self._dst_run).next if type(next_expr) is pyvex.IRExpr.RdTmp: temps.add(next_expr.tmp) elif type(next_expr) is pyvex.IRExpr.Const: # A const doesn't rely on anything else! pass else: raise AngrBladeError('Unsupported type for irsb.next: %s' % type(next_expr)) # Then we gotta start from the very last statement! self._dst_stmt_idx = len(stmts) - 1 prev = (self._get_addr(self._dst_run), DEFAULT_STATEMENT) slicer = SimSlicer(self.project.arch, stmts, target_tmps=temps, target_regs=regs, target_stack_offsets=None, inslice_callback=self._inslice_callback, inslice_callback_infodict={ 'irsb_addr': self._get_irsb(self._dst_run).addr, 'prev': prev, }) regs = slicer.final_regs if self._ignore_sp and self.project.arch.sp_offset in regs: regs.remove(self.project.arch.sp_offset) if self._ignore_bp and self.project.arch.bp_offset in regs: regs.remove(self.project.arch.bp_offset) for offset in self._ignored_regs: if offset in regs: regs.remove(offset) stack_offsets = slicer.final_stack_offsets prev = slicer.inslice_callback_infodict['prev'] if regs or stack_offsets: cfgnode = self._get_cfgnode(self._dst_run) in_edges = self._graph.in_edges(cfgnode, data=True) for pred, _, data in in_edges: if 'jumpkind' in data and data['jumpkind'] == 'Ijk_FakeRet': continue if self.project.is_hooked(pred.addr): # Skip SimProcedures continue self._backward_slice_recursive(self._max_level - 1, pred, regs, stack_offsets, prev, data.get('stmt_idx', None) )
<SYSTEM_TASK:> Parse a bytes object and create a class object. <END_TASK> <USER_TASK:> Description: def parse(cls, s, **kwargs): """ Parse a bytes object and create a class object. :param bytes s: A bytes object. :return: A class object. :rtype: cls """
pb2_obj = cls._get_cmsg() pb2_obj.ParseFromString(s) return cls.parse_from_cmessage(pb2_obj, **kwargs)
<SYSTEM_TASK:> Stores either a single element or a range of elements in the array. <END_TASK> <USER_TASK:> Description: def store_array_elements(self, array, start_idx, data): """ Stores either a single element or a range of elements in the array. :param array: Reference to the array. :param start_idx: Starting index for the store. :param data: Either a single value or a list of values. """
# we process data as a list of elements # => if there is only a single element, wrap it in a list data = data if isinstance(data, list) else [data] # concretize start index concrete_start_idxes = self.concretize_store_idx(start_idx) if len(concrete_start_idxes) == 1: # only one start index # => concrete store concrete_start_idx = concrete_start_idxes[0] for i, value in enumerate(data): self._store_array_element_on_heap(array=array, idx=concrete_start_idx+i, value=value, value_type=array.element_type) # if the index was symbolic before concretization, this # constraint it to concrete start idx self.state.solver.add(concrete_start_idx == start_idx) else: # multiple start indexes # => symbolic store start_idx_options = [] for concrete_start_idx in concrete_start_idxes: start_idx_options.append(concrete_start_idx == start_idx) # we store elements condtioned with the start index: # => if concrete_start_idx == start_idx # then store the value # else keep the current value for i, value in enumerate(data): self._store_array_element_on_heap(array=array, idx=concrete_start_idx+i, value=value, value_type=array.element_type, store_condition=start_idx_options[-1]) # constraint start_idx, s.t. it evals to one of the concretized indexes constraint_on_start_idx = self.state.solver.Or(*start_idx_options) self.state.add_constraints(constraint_on_start_idx)
<SYSTEM_TASK:> Loads either a single element or a range of elements from the array. <END_TASK> <USER_TASK:> Description: def load_array_elements(self, array, start_idx, no_of_elements): """ Loads either a single element or a range of elements from the array. :param array: Reference to the array. :param start_idx: Starting index for the load. :param no_of_elements: Number of elements to load. """
# concretize start index concrete_start_idxes = self.concretize_load_idx(start_idx) if len(concrete_start_idxes) == 1: # only one start index # => concrete load concrete_start_idx = concrete_start_idxes[0] load_values = [self._load_array_element_from_heap(array, idx) for idx in range(concrete_start_idx, concrete_start_idx+no_of_elements)] # if the index was symbolic before concretization, this # constraint it to concrete start idx self.state.solver.add(start_idx == concrete_start_idx) else: # multiple start indexes # => symbolic load # start with load values for the first concrete index concrete_start_idx = concrete_start_idxes[0] load_values = [self._load_array_element_from_heap(array, idx) for idx in range(concrete_start_idx, concrete_start_idx+no_of_elements)] start_idx_options = [concrete_start_idx == start_idx] # update load values with all remaining start indexes for concrete_start_idx in concrete_start_idxes[1:]: # load values for this start index values = [self._load_array_element_from_heap(array, idx) for idx in range(concrete_start_idx, concrete_start_idx+no_of_elements)] # update load values with the new ones for i, value in enumerate(values): # condition every value with the start idx # => if concrete_start_idx == start_idx # then use new value # else use the current value load_values[i] = self.state.solver.If( concrete_start_idx == start_idx, value, load_values[i] ) start_idx_options.append(start_idx == concrete_start_idx) # constraint start_idx, s.t. it evals to one of the concretized indexes constraint_on_start_idx = self.state.solver.Or(*start_idx_options) self.state.add_constraints(constraint_on_start_idx) return load_values
<SYSTEM_TASK:> Applies concretization strategies on the index, until one of them succeeds. <END_TASK> <USER_TASK:> Description: def _apply_concretization_strategies(self, idx, strategies, action): # pylint: disable=unused-argument """ Applies concretization strategies on the index, until one of them succeeds. """
for s in strategies: try: idxes = s.concretize(self, idx) except SimUnsatError: idxes = None if idxes: return idxes raise SimMemoryAddressError("Unable to concretize index %s" % idx)
<SYSTEM_TASK:> Concretizes a store index. <END_TASK> <USER_TASK:> Description: def concretize_store_idx(self, idx, strategies=None): """ Concretizes a store index. :param idx: An expression for the index. :param strategies: A list of concretization strategies (to override the default). :param min_idx: Minimum value for a concretized index (inclusive). :param max_idx: Maximum value for a concretized index (exclusive). :returns: A list of concrete indexes. """
if isinstance(idx, int): return [idx] elif not self.state.solver.symbolic(idx): return [self.state.solver.eval(idx)] strategies = self.store_strategies if strategies is None else strategies return self._apply_concretization_strategies(idx, strategies, 'store')
<SYSTEM_TASK:> Concretizes a load index. <END_TASK> <USER_TASK:> Description: def concretize_load_idx(self, idx, strategies=None): """ Concretizes a load index. :param idx: An expression for the index. :param strategies: A list of concretization strategies (to override the default). :param min_idx: Minimum value for a concretized index (inclusive). :param max_idx: Maximum value for a concretized index (exclusive). :returns: A list of concrete indexes. """
if isinstance(idx, int): return [idx] elif not self.state.solver.symbolic(idx): return [self.state.solver.eval(idx)] strategies = self.load_strategies if strategies is None else strategies return self._apply_concretization_strategies(idx, strategies, 'load')
<SYSTEM_TASK:> Resume a paused or terminated control flow graph recovery. <END_TASK> <USER_TASK:> Description: def resume(self, starts=None, max_steps=None): """ Resume a paused or terminated control flow graph recovery. :param iterable starts: A collection of new starts to resume from. If `starts` is None, we will resume CFG recovery from where it was paused before. :param int max_steps: The maximum number of blocks on the longest path starting from each start before pausing the recovery. :return: None """
self._starts = starts self._max_steps = max_steps self._sanitize_starts() self._analyze()
<SYSTEM_TASK:> Forces graph to become acyclic, removes all loop back edges and edges between overlapped loop headers and their <END_TASK> <USER_TASK:> Description: def remove_cycles(self): """ Forces graph to become acyclic, removes all loop back edges and edges between overlapped loop headers and their successors. """
# loop detection # only detect loops after potential graph normalization if not self._loop_back_edges: l.debug("Detecting loops...") self._detect_loops() l.debug("Removing cycles...") l.debug("There are %d loop back edges.", len(self._loop_back_edges)) l.debug("And there are %d overlapping loop headers.", len(self._overlapped_loop_headers)) # First break all detected loops for b1, b2 in self._loop_back_edges: if self._graph.has_edge(b1, b2): l.debug("Removing loop back edge %s -> %s", b1, b2) self._graph.remove_edge(b1, b2) # Then remove all outedges from overlapped loop headers for b in self._overlapped_loop_headers: successors = self._graph.successors(b) for succ in successors: self._graph.remove_edge(b, succ) l.debug("Removing partial loop header edge %s -> %s", b, succ)
<SYSTEM_TASK:> Unroll loops for each function. The resulting CFG may still contain loops due to recursion, function calls, etc. <END_TASK> <USER_TASK:> Description: def unroll_loops(self, max_loop_unrolling_times): """ Unroll loops for each function. The resulting CFG may still contain loops due to recursion, function calls, etc. :param int max_loop_unrolling_times: The maximum iterations of unrolling. :return: None """
if not isinstance(max_loop_unrolling_times, int) or \ max_loop_unrolling_times < 0: raise AngrCFGError('Max loop unrolling times must be set to an integer greater than or equal to 0 if ' + 'loop unrolling is enabled.') def _unroll(graph, loop): """ The loop callback method where loops are unrolled. :param networkx.DiGraph graph: The control flow graph. :param angr.analyses.loopfinder.Loop loop: The loop instance. :return: None """ for back_edge in loop.continue_edges: loop_body_addrs = {n.addr for n in loop.body_nodes} src_blocknode = back_edge[0] # type: angr.knowledge.codenode.BlockNode dst_blocknode = back_edge[1] # type: angr.knowledge.codenode.BlockNode for src in self.get_all_nodes(src_blocknode.addr): for dst in graph.successors(src): if dst.addr != dst_blocknode.addr: continue # Duplicate the dst node new_dst = dst.copy() new_dst.looping_times = dst.looping_times + 1 if (new_dst not in graph and # If the new_dst is already in the graph, we don't want to keep unrolling # the this loop anymore since it may *create* a new loop. Of course we # will lose some edges in this way, but in general it is acceptable. new_dst.looping_times <= max_loop_unrolling_times ): # Log all successors of the dst node dst_successors = graph.successors(dst) # Add new_dst to the graph edge_data = graph.get_edge_data(src, dst) graph.add_edge(src, new_dst, **edge_data) for ds in dst_successors: if ds.looping_times == 0 and ds.addr not in loop_body_addrs: edge_data = graph.get_edge_data(dst, ds) graph.add_edge(new_dst, ds, **edge_data) graph.remove_edge(src, dst) self._detect_loops(loop_callback=_unroll)
<SYSTEM_TASK:> Unroll loops globally. The resulting CFG does not contain any loop, but this method is slow on large graphs. <END_TASK> <USER_TASK:> Description: def force_unroll_loops(self, max_loop_unrolling_times): """ Unroll loops globally. The resulting CFG does not contain any loop, but this method is slow on large graphs. :param int max_loop_unrolling_times: The maximum iterations of unrolling. :return: None """
if not isinstance(max_loop_unrolling_times, int) or \ max_loop_unrolling_times < 0: raise AngrCFGError('Max loop unrolling times must be set to an integer greater than or equal to 0 if ' + 'loop unrolling is enabled.') # Traverse the CFG and try to find the beginning of loops loop_backedges = [] start = self._starts[0] if isinstance(start, tuple): start, _ = start # pylint: disable=unpacking-non-sequence start_node = self.get_any_node(start) if start_node is None: raise AngrCFGError('Cannot find start node when trying to unroll loops. The CFG might be empty.') graph_copy = networkx.DiGraph(self.graph) while True: cycles_iter = networkx.simple_cycles(graph_copy) try: cycle = next(cycles_iter) except StopIteration: break loop_backedge = (None, None) for n in networkx.dfs_preorder_nodes(graph_copy, source=start_node): if n in cycle: idx = cycle.index(n) if idx == 0: loop_backedge = (cycle[-1], cycle[idx]) else: loop_backedge = (cycle[idx - 1], cycle[idx]) break if loop_backedge not in loop_backedges: loop_backedges.append(loop_backedge) # Create a common end node for all nodes whose out_degree is 0 end_nodes = [n for n in graph_copy.nodes() if graph_copy.out_degree(n) == 0] new_end_node = "end_node" if not end_nodes: # We gotta randomly break a loop cycles = sorted(networkx.simple_cycles(graph_copy), key=len) first_cycle = cycles[0] if len(first_cycle) == 1: graph_copy.remove_edge(first_cycle[0], first_cycle[0]) else: graph_copy.remove_edge(first_cycle[0], first_cycle[1]) end_nodes = [n for n in graph_copy.nodes() if graph_copy.out_degree(n) == 0] for en in end_nodes: graph_copy.add_edge(en, new_end_node) # postdoms = self.immediate_postdominators(new_end_node, target_graph=graph_copy) # reverse_postdoms = defaultdict(list) # for k, v in postdoms.items(): # reverse_postdoms[v].append(k) # Find all loop bodies # for src, dst in loop_backedges: # nodes_in_loop = { src, dst } # while True: # new_nodes = set() # for n in nodes_in_loop: # if n in reverse_postdoms: # for node in reverse_postdoms[n]: # if node not in nodes_in_loop: # new_nodes.add(node) # if not new_nodes: # break # nodes_in_loop |= new_nodes # Unroll the loop body # TODO: Finish the implementation graph_copy.remove_node(new_end_node) src, dst = loop_backedge if graph_copy.has_edge(src, dst): # It might have been removed before # Duplicate the dst node new_dst = dst.copy() new_dst.looping_times = dst.looping_times + 1 if ( new_dst not in graph_copy and # If the new_dst is already in the graph, we don't want to keep unrolling # the this loop anymore since it may *create* a new loop. Of course we # will lose some edges in this way, but in general it is acceptable. new_dst.looping_times <= max_loop_unrolling_times): # Log all successors of the dst node dst_successors = list(graph_copy.successors(dst)) # Add new_dst to the graph edge_data = graph_copy.get_edge_data(src, dst) graph_copy.add_edge(src, new_dst, **edge_data) for ds in dst_successors: if ds.looping_times == 0 and ds not in cycle: edge_data = graph_copy.get_edge_data(dst, ds) graph_copy.add_edge(new_dst, ds, **edge_data) # Remove the original edge graph_copy.remove_edge(src, dst) # Update loop backedges self._loop_back_edges = loop_backedges self.model.graph = graph_copy
<SYSTEM_TASK:> Get all immediate postdominators of sub graph from given node upwards. <END_TASK> <USER_TASK:> Description: def immediate_postdominators(self, end, target_graph=None): """ Get all immediate postdominators of sub graph from given node upwards. :param str start: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.graph. :return: each node of graph as index values, with element as respective node's immediate dominator. :rtype: dict """
return self._immediate_dominators(end, target_graph=target_graph, reverse_graph=True)
<SYSTEM_TASK:> Get the topological order of a CFG Node. <END_TASK> <USER_TASK:> Description: def get_topological_order(self, cfg_node): """ Get the topological order of a CFG Node. :param cfg_node: A CFGNode instance. :return: An integer representing its order, or None if the CFGNode does not exist in the graph. """
if not self._quasi_topological_order: self._quasi_topological_sort() return self._quasi_topological_order.get(cfg_node, None)
<SYSTEM_TASK:> Get a sub-graph out of a bunch of basic block addresses. <END_TASK> <USER_TASK:> Description: def get_subgraph(self, starting_node, block_addresses): """ Get a sub-graph out of a bunch of basic block addresses. :param CFGNode starting_node: The beginning of the subgraph :param iterable block_addresses: A collection of block addresses that should be included in the subgraph if there is a path between `starting_node` and a CFGNode with the specified address, and all nodes on the path should also be included in the subgraph. :return: A new CFG that only contain the specific subgraph. :rtype: CFGEmulated """
graph = networkx.DiGraph() if starting_node not in self.graph: raise AngrCFGError('get_subgraph(): the specified "starting_node" %s does not exist in the current CFG.' % starting_node ) addr_set = set(block_addresses) graph.add_node(starting_node) queue = [ starting_node ] while queue: node = queue.pop() for _, dst, data in self.graph.out_edges([node], data=True): if dst not in graph and dst.addr in addr_set: graph.add_edge(node, dst, **data) queue.append(dst) cfg = self.copy() cfg._graph = graph cfg._starts = (starting_node.addr, ) return cfg
<SYSTEM_TASK:> Get a sub-graph of a certain function. <END_TASK> <USER_TASK:> Description: def get_function_subgraph(self, start, max_call_depth=None): """ Get a sub-graph of a certain function. :param start: The function start. Currently it should be an integer. :param max_call_depth: Call depth limit. None indicates no limit. :return: A CFG instance which is a sub-graph of self.graph """
# FIXME: syscalls are not supported # FIXME: start should also take a CFGNode instance start_node = self.get_any_node(start) node_wrapper = (start_node, 0) stack = [node_wrapper] traversed_nodes = {start_node} subgraph_nodes = set([start_node]) while stack: nw = stack.pop() n, call_depth = nw[0], nw[1] # Get successors edges = self.graph.out_edges(n, data=True) for _, dst, data in edges: if dst not in traversed_nodes: # We see a new node! traversed_nodes.add(dst) if data['jumpkind'] == 'Ijk_Call': if max_call_depth is None or (max_call_depth is not None and call_depth < max_call_depth): subgraph_nodes.add(dst) new_nw = (dst, call_depth + 1) stack.append(new_nw) elif data['jumpkind'] == 'Ijk_Ret': if call_depth > 0: subgraph_nodes.add(dst) new_nw = (dst, call_depth - 1) stack.append(new_nw) else: subgraph_nodes.add(dst) new_nw = (dst, call_depth) stack.append(new_nw) #subgraph = networkx.subgraph(self.graph, subgraph_nodes) subgraph = self.graph.subgraph(subgraph_nodes).copy() # Make it a CFG instance subcfg = self.copy() subcfg._graph = subgraph subcfg._starts = (start,) return subcfg
<SYSTEM_TASK:> Get all CFGNodes that has an out-degree of 0 <END_TASK> <USER_TASK:> Description: def deadends(self): """ Get all CFGNodes that has an out-degree of 0 :return: A list of CFGNode instances :rtype: list """
if self.graph is None: raise AngrCFGError('CFG hasn\'t been generated yet.') deadends = [i for i in self.graph if self.graph.out_degree(i) == 0] return deadends
<SYSTEM_TASK:> Get the sorting key of a CFGJob instance. <END_TASK> <USER_TASK:> Description: def _job_sorting_key(self, job): """ Get the sorting key of a CFGJob instance. :param CFGJob job: the CFGJob object. :return: An integer that determines the order of this job in the queue. :rtype: int """
if self._base_graph is None: # we don't do sorting if there is no base_graph return 0 MAX_JOBS = 1000000 if job.addr not in self._node_addr_visiting_order: return MAX_JOBS return self._node_addr_visiting_order.index(job.addr)
<SYSTEM_TASK:> Initialization work. Executed prior to the analysis. <END_TASK> <USER_TASK:> Description: def _pre_analysis(self): """ Initialization work. Executed prior to the analysis. :return: None """
# Fill up self._starts for item in self._starts: callstack = None if isinstance(item, tuple): # (addr, jumpkind) ip = item[0] state = self._create_initial_state(item[0], item[1]) elif isinstance(item, SimState): # SimState state = item.copy() # pylint: disable=no-member ip = state.solver.eval_one(state.ip) self._reset_state_mode(state, 'fastpath') else: raise AngrCFGError('Unsupported CFG start type: %s.' % str(type(item))) self._symbolic_function_initial_state[ip] = state path_wrapper = CFGJob(ip, state, self._context_sensitivity_level, None, None, call_stack=callstack) key = path_wrapper.block_id if key not in self._start_keys: self._start_keys.append(key) self._insert_job(path_wrapper) self._register_analysis_job(path_wrapper.func_addr, path_wrapper)
<SYSTEM_TASK:> A callback method called when the job queue is empty. <END_TASK> <USER_TASK:> Description: def _job_queue_empty(self): """ A callback method called when the job queue is empty. :return: None """
self._iteratively_clean_pending_exits() while self._pending_jobs: # We don't have any exits remaining. Let's pop out a pending exit pending_job = self._get_one_pending_job() if pending_job is None: continue self._insert_job(pending_job) self._register_analysis_job(pending_job.func_addr, pending_job) break
<SYSTEM_TASK:> Obtain a SimState object for a specific address <END_TASK> <USER_TASK:> Description: def _create_initial_state(self, ip, jumpkind): """ Obtain a SimState object for a specific address Fastpath means the CFG generation will work in an IDA-like way, in which it will not try to execute every single statement in the emulator, but will just do the decoding job. This is much faster than the old way. :param int ip: The instruction pointer :param str jumpkind: The jumpkind upon executing the block :return: The newly-generated state :rtype: SimState """
jumpkind = "Ijk_Boring" if jumpkind is None else jumpkind if self._initial_state is None: state = self.project.factory.blank_state(addr=ip, mode="fastpath", add_options=self._state_add_options, remove_options=self._state_remove_options, ) self._initial_state = state else: # FIXME: self._initial_state is deprecated. This branch will be removed soon state = self._initial_state state.history.jumpkind = jumpkind self._reset_state_mode(state, 'fastpath') state._ip = state.solver.BVV(ip, self.project.arch.bits) if jumpkind is not None: state.history.jumpkind = jumpkind # THIS IS A HACK FOR MIPS if ip is not None and self.project.arch.name in ('MIPS32', 'MIPS64'): # We assume this is a function start state.regs.t9 = ip # TODO there was at one point special logic for the ppc64 table of contents but it seems to have bitrotted return state
<SYSTEM_TASK:> Filter the list of successors <END_TASK> <USER_TASK:> Description: def _post_process_successors(self, input_state, sim_successors, successors): """ Filter the list of successors :param SimState input_state: Input state. :param SimSuccessors sim_successors: The SimSuccessors instance. :param list successors: A list of successors generated after processing the current block. :return: A list of successors. :rtype: list """
if sim_successors.sort == 'IRSB' and input_state.thumb: successors = self._arm_thumb_filter_jump_successors(sim_successors.addr, sim_successors.artifacts['irsb'].size, successors, lambda state: state.scratch.ins_addr, lambda state: state.scratch.exit_stmt_idx ) # If there is a call exit, we shouldn't put the default exit (which # is artificial) into the CFG. The exits will be Ijk_Call and # Ijk_FakeRet, and Ijk_Call always goes first extra_info = {'is_call_jump': False, 'call_target': None, 'return_target': None, 'last_call_exit_target': None, 'skip_fakeret': False, } # Post-process jumpkind before touching all_successors for suc in sim_successors.all_successors: # we process all successors here to include potential unsat successors suc_jumpkind = suc.history.jumpkind if self._is_call_jumpkind(suc_jumpkind): extra_info['is_call_jump'] = True break return successors, extra_info
<SYSTEM_TASK:> Iteratively update the completed functions set, analyze whether each function returns or not, and remove <END_TASK> <USER_TASK:> Description: def _iteratively_clean_pending_exits(self): """ Iteratively update the completed functions set, analyze whether each function returns or not, and remove pending exits if the callee function does not return. We do this iteratively so that we come to a fixed point in the end. In most cases, the number of outer iteration equals to the maximum levels of wrapped functions whose "returningness" is determined by the very last function it calls. :return: None """
while True: # did we finish analyzing any function? # fill in self._completed_functions self._make_completed_functions() if self._pending_jobs: # There are no more remaining jobs, but only pending jobs left. Each pending job corresponds to # a previous job that does not return properly. # Now it's a good time to analyze each function (that we have so far) and determine if it is a) # returning, b) not returning, or c) unknown. For those functions that are definitely not returning, # remove the corresponding pending exits from `pending_jobs` array. Perform this procedure iteratively # until no new not-returning functions appear. Then we pick a pending exit based on the following # priorities: # - Job pended by a returning function # - Job pended by an unknown function new_changes = self._iteratively_analyze_function_features() functions_do_not_return = new_changes['functions_do_not_return'] self._update_function_callsites(functions_do_not_return) if not self._clean_pending_exits(): # no more pending exits are removed. we are good to go! break else: break
<SYSTEM_TASK:> A block without successors should still be handled so it can be added to the function graph correctly. <END_TASK> <USER_TASK:> Description: def _handle_job_without_successors(self, job, irsb, insn_addrs): """ A block without successors should still be handled so it can be added to the function graph correctly. :param CFGJob job: The current job that do not have any successor. :param IRSB irsb: The related IRSB. :param insn_addrs: A list of instruction addresses of this IRSB. :return: None """
# it's not an empty block # handle all conditional exits ins_addr = job.addr for stmt_idx, stmt in enumerate(irsb.statements): if type(stmt) is pyvex.IRStmt.IMark: ins_addr = stmt.addr + stmt.delta elif type(stmt) is pyvex.IRStmt.Exit: successor_jumpkind = stmt.jk self._update_function_transition_graph( job.block_id, None, jumpkind = successor_jumpkind, ins_addr=ins_addr, stmt_idx=stmt_idx, ) # handle the default exit successor_jumpkind = irsb.jumpkind successor_last_ins_addr = insn_addrs[-1] self._update_function_transition_graph(job.block_id, None, jumpkind=successor_jumpkind, ins_addr=successor_last_ins_addr, stmt_idx=DEFAULT_STATEMENT, )
<SYSTEM_TASK:> For a given state and current location of of execution, will update a function by adding the offets of <END_TASK> <USER_TASK:> Description: def _handle_actions(self, state, current_run, func, sp_addr, accessed_registers): """ For a given state and current location of of execution, will update a function by adding the offets of appropriate actions to the stack variable or argument registers for the fnc. :param SimState state: upcoming state. :param SimSuccessors current_run: possible result states. :param knowledge.Function func: current function. :param int sp_addr: stack pointer address. :param set accessed_registers: set of before accessed registers. """
se = state.solver if func is not None and sp_addr is not None: # Fix the stack pointer (for example, skip the return address on the stack) new_sp_addr = sp_addr + self.project.arch.call_sp_fix actions = [a for a in state.history.recent_actions if a.bbl_addr == current_run.addr] for a in actions: if a.type == "mem" and a.action == "read": try: addr = se.eval_one(a.addr.ast, default=0) except (claripy.ClaripyError, SimSolverModeError): continue if (self.project.arch.call_pushes_ret and addr >= new_sp_addr) or \ (not self.project.arch.call_pushes_ret and addr >= new_sp_addr): # TODO: What if a variable locates higher than the stack is modified as well? We probably want # TODO: to make sure the accessing address falls in the range of stack offset = addr - new_sp_addr func._add_argument_stack_variable(offset) elif a.type == "reg": offset = a.offset if a.action == "read" and offset not in accessed_registers: func._add_argument_register(offset) elif a.action == "write": accessed_registers.add(offset) else: l.error( "handle_actions: Function not found, or stack pointer is None. It might indicates unbalanced stack.")
<SYSTEM_TASK:> Update transition graphs of functions in function manager based on information passed in. <END_TASK> <USER_TASK:> Description: def _update_function_transition_graph(self, src_node_key, dst_node_key, jumpkind='Ijk_Boring', ins_addr=None, stmt_idx=None, confirmed=None): """ Update transition graphs of functions in function manager based on information passed in. :param str jumpkind: Jumpkind. :param CFGNode src_node: Source CFGNode :param CFGNode dst_node: Destionation CFGNode :param int ret_addr: The theoretical return address for calls :return: None """
if dst_node_key is not None: dst_node = self._graph_get_node(dst_node_key, terminator_for_nonexistent_node=True) dst_node_addr = dst_node.addr dst_codenode = dst_node.to_codenode() dst_node_func_addr = dst_node.function_address else: dst_node = None dst_node_addr = None dst_codenode = None dst_node_func_addr = None if src_node_key is None: if dst_node is None: raise ValueError("Either src_node_key or dst_node_key must be specified.") self.kb.functions.function(dst_node.function_address, create=True)._register_nodes(True, dst_codenode ) return src_node = self._graph_get_node(src_node_key, terminator_for_nonexistent_node=True) # Update the transition graph of current function if jumpkind == "Ijk_Call": ret_addr = src_node.return_target ret_node = self.kb.functions.function( src_node.function_address, create=True )._get_block(ret_addr).codenode if ret_addr else None self.kb.functions._add_call_to( function_addr=src_node.function_address, from_node=src_node.to_codenode(), to_addr=dst_node_addr, retn_node=ret_node, syscall=False, ins_addr=ins_addr, stmt_idx=stmt_idx, ) if jumpkind.startswith('Ijk_Sys'): self.kb.functions._add_call_to( function_addr=src_node.function_address, from_node=src_node.to_codenode(), to_addr=dst_node_addr, retn_node=src_node.to_codenode(), # For syscalls, they are returning to the address of themselves syscall=True, ins_addr=ins_addr, stmt_idx=stmt_idx, ) elif jumpkind == 'Ijk_Ret': # Create a return site for current function self.kb.functions._add_return_from( function_addr=src_node.function_address, from_node=src_node.to_codenode(), to_node=dst_codenode, ) if dst_node is not None: # Create a returning edge in the caller function self.kb.functions._add_return_from_call( function_addr=dst_node_func_addr, src_function_addr=src_node.function_address, to_node=dst_codenode, ) elif jumpkind == 'Ijk_FakeRet': self.kb.functions._add_fakeret_to( function_addr=src_node.function_address, from_node=src_node.to_codenode(), to_node=dst_codenode, confirmed=confirmed, ) elif jumpkind in ('Ijk_Boring', 'Ijk_InvalICache'): src_obj = self.project.loader.find_object_containing(src_node.addr) dest_obj = self.project.loader.find_object_containing(dst_node.addr) if dst_node is not None else None if src_obj is dest_obj: # Jump/branch within the same object. Might be an outside jump. to_outside = src_node.function_address != dst_node_func_addr else: # Jump/branch between different objects. Must be an outside jump. to_outside = True if not to_outside: self.kb.functions._add_transition_to( function_addr=src_node.function_address, from_node=src_node.to_codenode(), to_node=dst_codenode, ins_addr=ins_addr, stmt_idx=stmt_idx, ) else: self.kb.functions._add_outside_transition_to( function_addr=src_node.function_address, from_node=src_node.to_codenode(), to_node=dst_codenode, to_function_addr=dst_node_func_addr, ins_addr=ins_addr, stmt_idx=stmt_idx, )
<SYSTEM_TASK:> Throw away all successors whose target doesn't make sense <END_TASK> <USER_TASK:> Description: def _filter_insane_successors(self, successors): """ Throw away all successors whose target doesn't make sense This method is called after we resolve an indirect jump using an unreliable method (like, not through one of the indirect jump resolvers, but through either pure concrete execution or backward slicing) to filter out the obviously incorrect successors. :param list successors: A collection of successors. :return: A filtered list of successors :rtype: list """
old_successors = successors[::] successors = [ ] for i, suc in enumerate(old_successors): if suc.solver.symbolic(suc.ip): # It's symbolic. Take it, and hopefully we can resolve it later successors.append(suc) else: ip_int = suc.solver.eval_one(suc.ip) if self._is_address_executable(ip_int) or \ self.project.is_hooked(ip_int) or \ self.project.simos.is_syscall_addr(ip_int): successors.append(suc) else: l.debug('An obviously incorrect successor %d/%d (%#x) is ditched', i + 1, len(old_successors), ip_int ) return successors
<SYSTEM_TASK:> Convert each concrete indirect jump target into a SimState. <END_TASK> <USER_TASK:> Description: def _convert_indirect_jump_targets_to_states(job, indirect_jump_targets): """ Convert each concrete indirect jump target into a SimState. :param job: The CFGJob instance. :param indirect_jump_targets: A collection of concrete jump targets resolved from a indirect jump. :return: A list of SimStates. :rtype: list """
successors = [ ] for t in indirect_jump_targets: # Insert new successors a = job.sim_successors.all_successors[0].copy() a.ip = t successors.append(a) return successors
<SYSTEM_TASK:> Scan for constants that might be used as exit targets later, and add them into pending_exits. <END_TASK> <USER_TASK:> Description: def _search_for_function_hints(self, successor_state): """ Scan for constants that might be used as exit targets later, and add them into pending_exits. :param SimState successor_state: A successing state. :return: A list of discovered code addresses. :rtype: list """
function_hints = [] for action in successor_state.history.recent_actions: if action.type == 'reg' and action.offset == self.project.arch.ip_offset: # Skip all accesses to IP registers continue elif action.type == 'exit': # only consider read/write actions continue # Enumerate actions if isinstance(action, SimActionData): data = action.data if data is not None: # TODO: Check if there is a proper way to tell whether this const falls in the range of code # TODO: segments # Now let's live with this big hack... try: const = successor_state.solver.eval_one(data.ast) except: # pylint: disable=bare-except continue if self._is_address_executable(const): if self._pending_function_hints is not None and const in self._pending_function_hints: continue # target = const # tpl = (None, None, target) # st = self.project._simos.prepare_call_state(self.project.initial_state(mode='fastpath'), # initial_state=saved_state) # st = self.project.initial_state(mode='fastpath') # exits[tpl] = (st, None, None) function_hints.append(const) l.debug('Got %d possible exits, including: %s', len(function_hints), ", ".join(["0x%x" % f for f in function_hints]) ) return function_hints
<SYSTEM_TASK:> Creates a new call stack, and according to the jumpkind performs appropriate actions. <END_TASK> <USER_TASK:> Description: def _create_new_call_stack(self, addr, all_jobs, job, exit_target, jumpkind): """ Creates a new call stack, and according to the jumpkind performs appropriate actions. :param int addr: Address to create at. :param Simsuccessors all_jobs: Jobs to get stack pointer from or return address. :param CFGJob job: CFGJob to copy current call stack from. :param int exit_target: Address of exit target. :param str jumpkind: The type of jump performed. :returns: New call stack for target block. :rtype: CallStack """
if self._is_call_jumpkind(jumpkind): new_call_stack = job.call_stack_copy() # Notice that in ARM, there are some freaking instructions # like # BLEQ <address> # It should give us three exits: Ijk_Call, Ijk_Boring, and # Ijk_Ret. The last exit is simulated. # Notice: We assume the last exit is the simulated one if len(all_jobs) > 1 and all_jobs[-1].history.jumpkind == "Ijk_FakeRet": se = all_jobs[-1].solver retn_target_addr = se.eval_one(all_jobs[-1].ip, default=0) sp = se.eval_one(all_jobs[-1].regs.sp, default=0) new_call_stack = new_call_stack.call(addr, exit_target, retn_target=retn_target_addr, stack_pointer=sp) elif jumpkind.startswith('Ijk_Sys') and len(all_jobs) == 1: # This is a syscall. It returns to the same address as itself (with a different jumpkind) retn_target_addr = exit_target se = all_jobs[0].solver sp = se.eval_one(all_jobs[0].regs.sp, default=0) new_call_stack = new_call_stack.call(addr, exit_target, retn_target=retn_target_addr, stack_pointer=sp) else: # We don't have a fake return exit available, which means # this call doesn't return. new_call_stack = CallStack() se = all_jobs[-1].solver sp = se.eval_one(all_jobs[-1].regs.sp, default=0) new_call_stack = new_call_stack.call(addr, exit_target, retn_target=None, stack_pointer=sp) elif jumpkind == "Ijk_Ret": # Normal return new_call_stack = job.call_stack_copy() try: new_call_stack = new_call_stack.ret(exit_target) except SimEmptyCallStackError: pass se = all_jobs[-1].solver sp = se.eval_one(all_jobs[-1].regs.sp, default=0) old_sp = job.current_stack_pointer # Calculate the delta of stack pointer if sp is not None and old_sp is not None: delta = sp - old_sp func_addr = job.func_addr if self.kb.functions.function(func_addr) is None: # Create the function if it doesn't exist # FIXME: But hell, why doesn't it exist in the first place? l.error("Function 0x%x doesn't exist in function manager although it should be there." "Look into this issue later.", func_addr) self.kb.functions.function(func_addr, create=True) # Set sp_delta of the function self.kb.functions.function(func_addr, create=True).sp_delta = delta elif jumpkind == 'Ijk_FakeRet': # The fake return... new_call_stack = job.call_stack else: # although the jumpkind is not Ijk_Call, it may still jump to a new function... let's see if self.project.is_hooked(exit_target): hooker = self.project.hooked_by(exit_target) if not hooker is procedures.stubs.UserHook.UserHook: # if it's not a UserHook, it must be a function # Update the function address of the most recent call stack frame new_call_stack = job.call_stack_copy() new_call_stack.current_function_address = exit_target else: # TODO: We need a way to mark if a user hook is a function or not # TODO: We can add a map in Project to store this information # For now we are just assuming they are not functions, which is mostly the case new_call_stack = job.call_stack else: # Normal control flow transition new_call_stack = job.call_stack return new_call_stack
<SYSTEM_TASK:> Create a context-sensitive CFGNode instance for a specific block. <END_TASK> <USER_TASK:> Description: def _create_cfgnode(self, sim_successors, call_stack, func_addr, block_id=None, depth=None, exception_info=None): """ Create a context-sensitive CFGNode instance for a specific block. :param SimSuccessors sim_successors: The SimSuccessors object. :param CallStack call_stack_suffix: The call stack. :param int func_addr: Address of the current function. :param BlockID block_id: The block ID of this CFGNode. :param int or None depth: Depth of this CFGNode. :return: A CFGNode instance. :rtype: CFGNode """
sa = sim_successors.artifacts # shorthand # Determine if this is a SimProcedure, and further, if this is a syscall syscall = None is_syscall = False if sim_successors.sort == 'SimProcedure': is_simprocedure = True if sa['is_syscall'] is True: is_syscall = True syscall = sim_successors.artifacts['procedure'] else: is_simprocedure = False if is_simprocedure: simproc_name = sa['name'].split('.')[-1] if simproc_name == "ReturnUnconstrained" and sa['resolves'] is not None: simproc_name = sa['resolves'] no_ret = False if syscall is not None and sa['no_ret']: no_ret = True cfg_node = CFGENode(sim_successors.addr, None, self.model, callstack_key=call_stack.stack_suffix(self.context_sensitivity_level), input_state=None, simprocedure_name=simproc_name, syscall_name=syscall, no_ret=no_ret, is_syscall=is_syscall, function_address=sim_successors.addr, block_id=block_id, depth=depth, creation_failure_info=exception_info, thumb=(isinstance(self.project.arch, ArchARM) and sim_successors.addr & 1), ) else: cfg_node = CFGENode(sim_successors.addr, sa['irsb_size'], self.model, callstack_key=call_stack.stack_suffix(self.context_sensitivity_level), input_state=None, is_syscall=is_syscall, function_address=func_addr, block_id=block_id, depth=depth, irsb=sim_successors.artifacts['irsb'], creation_failure_info=exception_info, thumb=(isinstance(self.project.arch, ArchARM) and sim_successors.addr & 1), ) return cfg_node
<SYSTEM_TASK:> Loop detection. <END_TASK> <USER_TASK:> Description: def _detect_loops(self, loop_callback=None): """ Loop detection. :param func loop_callback: A callback function for each detected loop backedge. :return: None """
loop_finder = self.project.analyses.LoopFinder(kb=self.kb, normalize=False, fail_fast=self._fail_fast) if loop_callback is not None: graph_copy = networkx.DiGraph(self._graph) for loop in loop_finder.loops: # type: angr.analyses.loopfinder.Loop loop_callback(graph_copy, loop) self.model.graph = graph_copy # Update loop backedges and graph self._loop_back_edges = list(itertools.chain.from_iterable(loop.continue_edges for loop in loop_finder.loops))
<SYSTEM_TASK:> Determine if this SimIRSB has an indirect jump as its exit <END_TASK> <USER_TASK:> Description: def _is_indirect_jump(_, sim_successors): """ Determine if this SimIRSB has an indirect jump as its exit """
if sim_successors.artifacts['irsb_direct_next']: # It's a direct jump return False default_jumpkind = sim_successors.artifacts['irsb_default_jumpkind'] if default_jumpkind not in ('Ijk_Call', 'Ijk_Boring', 'Ijk_InvalICache'): # It's something else, like a ret of a syscall... we don't care about it return False return True
<SYSTEM_TASK:> Check if the specific address is in one of the executable ranges. <END_TASK> <USER_TASK:> Description: def _is_address_executable(self, address): """ Check if the specific address is in one of the executable ranges. :param int address: The address :return: True if it's in an executable range, False otherwise """
for r in self._executable_address_ranges: if r[0] <= address < r[1]: return True return False
<SYSTEM_TASK:> Reset the state mode to the given mode, and apply the custom state options specified with this analysis. <END_TASK> <USER_TASK:> Description: def _reset_state_mode(self, state, mode): """ Reset the state mode to the given mode, and apply the custom state options specified with this analysis. :param state: The state to work with. :param str mode: The state mode. :return: None """
state.set_mode(mode) state.options |= self._state_add_options state.options = state.options.difference(self._state_remove_options)
<SYSTEM_TASK:> Try to classify an immediate as a pointer. <END_TASK> <USER_TASK:> Description: def _imm_to_ptr(self, imm, operand_type, mnemonic): # pylint:disable=no-self-use,unused-argument """ Try to classify an immediate as a pointer. :param int imm: The immediate to test. :param int operand_type: Operand type of this operand, can either be IMM or MEM. :param str mnemonic: Mnemonic of the instruction that this operand belongs to. :return: A tuple of (is code reference, is data reference, base address, offset) :rtype: tuple """
is_coderef, is_dataref = False, False baseaddr = None if not is_coderef and not is_dataref: if self.binary.main_executable_regions_contain(imm): # does it point to the beginning of an instruction? if imm in self.binary.all_insn_addrs: is_coderef = True baseaddr = imm if not is_coderef and not is_dataref: if self.binary.main_nonexecutable_regions_contain(imm): is_dataref = True baseaddr = imm if not is_coderef and not is_dataref: tolerance_before = 1024 if operand_type == OP_TYPE_MEM else 64 contains_, baseaddr_ = self.binary.main_nonexecutable_region_limbos_contain(imm, tolerance_before=tolerance_before, tolerance_after=1024 ) if contains_: is_dataref = True baseaddr = baseaddr_ if not contains_: contains_, baseaddr_ = self.binary.main_executable_region_limbos_contain(imm) if contains_: is_coderef = True baseaddr = baseaddr_ return (is_coderef, is_dataref, baseaddr)
<SYSTEM_TASK:> Get the assembly manifest of the procedure. <END_TASK> <USER_TASK:> Description: def assembly(self, comments=False, symbolized=True): """ Get the assembly manifest of the procedure. :param comments: :param symbolized: :return: A list of tuples (address, basic block assembly), ordered by basic block addresses :rtype: list """
assembly = [ ] header = "\t.section\t{section}\n\t.align\t{alignment}\n".format(section=self.section, alignment=self.binary.section_alignment(self.section) ) if self.addr is not None: procedure_name = "%#x" % self.addr else: procedure_name = self._name header += "\t#Procedure %s\n" % procedure_name if self._output_function_label: if self.addr: function_label = self.binary.symbol_manager.new_label(self.addr) else: function_label = self.binary.symbol_manager.new_label(None, name=procedure_name, is_function=True) header += str(function_label) + "\n" assembly.append((self.addr, header)) if self.asm_code: s = self.asm_code assembly.append((self.addr, s)) elif self.blocks: for b in sorted(self.blocks, key=lambda x:x.addr): # type: BasicBlock s = b.assembly(comments=comments, symbolized=symbolized) assembly.append((b.addr, s)) return assembly
<SYSTEM_TASK:> Get all instruction addresses in the binary. <END_TASK> <USER_TASK:> Description: def instruction_addresses(self): """ Get all instruction addresses in the binary. :return: A list of sorted instruction addresses. :rtype: list """
addrs = [ ] for b in sorted(self.blocks, key=lambda x: x.addr): # type: BasicBlock addrs.extend(b.instruction_addresses()) return sorted(set(addrs), key=lambda x: x[0])
<SYSTEM_TASK:> Determines if we want to output the function label in assembly. We output the function label only when the <END_TASK> <USER_TASK:> Description: def _output_function_label(self): """ Determines if we want to output the function label in assembly. We output the function label only when the original instruction does not output the function label. :return: True if we should output the function label, False otherwise. :rtype: bool """
if self.asm_code: return True if not self.blocks: return True the_block = next((b for b in self.blocks if b.addr == self.addr), None) if the_block is None: return True if not the_block.instructions: return True if not the_block.instructions[0].labels: return True return False
<SYSTEM_TASK:> Reduce the size of this block <END_TASK> <USER_TASK:> Description: def shrink(self, new_size): """ Reduce the size of this block :param int new_size: The new size :return: None """
self.size = new_size if self.sort == 'string': self.null_terminated = False # string without the null byte terminator self._content[0] = self._content[0][ : self.size] elif self.sort == 'pointer-array': pointer_size = self.binary.project.arch.bytes if self.size % pointer_size != 0: # it's not aligned? raise BinaryError('Fails at Data.shrink()') pointers = self.size // pointer_size self._content = self._content[ : pointers] else: # unknown self._content = [ self._content[0][ : self.size ] ]
<SYSTEM_TASK:> We believe this was a pointer and symbolized it before. Now we want to desymbolize it. <END_TASK> <USER_TASK:> Description: def desymbolize(self): """ We believe this was a pointer and symbolized it before. Now we want to desymbolize it. The following actions are performed: - Reload content from memory - Mark the sort as 'unknown' :return: None """
self.sort = 'unknown' content = self.binary.fast_memory_load(self.addr, self.size, bytes) self.content = [ content ]
<SYSTEM_TASK:> Add a new label to the symbol manager. <END_TASK> <USER_TASK:> Description: def add_label(self, name, addr): """ Add a new label to the symbol manager. :param str name: Name of the label. :param int addr: Address of the label. :return: None """
# set the label self._symbolization_needed = True self.symbol_manager.new_label(addr, name=name, force=True)
<SYSTEM_TASK:> Insert some assembly code at the specific address. There must be an instruction starting at that address. <END_TASK> <USER_TASK:> Description: def insert_asm(self, addr, asm_code, before_label=False): """ Insert some assembly code at the specific address. There must be an instruction starting at that address. :param int addr: Address of insertion :param str asm_code: The assembly code to insert :return: None """
if before_label: self._inserted_asm_before_label[addr].append(asm_code) else: self._inserted_asm_after_label[addr].append(asm_code)
<SYSTEM_TASK:> Add a new procedure with specific name and assembly code. <END_TASK> <USER_TASK:> Description: def append_procedure(self, name, asm_code): """ Add a new procedure with specific name and assembly code. :param str name: The name of the new procedure. :param str asm_code: The assembly code of the procedure :return: None """
proc = Procedure(self, name=name, asm_code=asm_code) self.procedures.append(proc)
<SYSTEM_TASK:> Append a new data entry into the binary with specific name, content, and size. <END_TASK> <USER_TASK:> Description: def append_data(self, name, initial_content, size, readonly=False, sort="unknown"): # pylint:disable=unused-argument """ Append a new data entry into the binary with specific name, content, and size. :param str name: Name of the data entry. Will be used as the label. :param bytes initial_content: The initial content of the data entry. :param int size: Size of the data entry. :param bool readonly: If the data entry belongs to the readonly region. :param str sort: Type of the data. :return: None """
if readonly: section_name = ".rodata" else: section_name = '.data' if initial_content is None: initial_content = b"" initial_content = initial_content.ljust(size, b"\x00") data = Data(self, memory_data=None, section_name=section_name, name=name, initial_content=initial_content, size=size, sort=sort ) if section_name == '.rodata': self.extra_rodata.append(data) else: self.extra_data.append(data)
<SYSTEM_TASK:> Remove unnecessary functions and data <END_TASK> <USER_TASK:> Description: def remove_unnecessary_stuff(self): """ Remove unnecessary functions and data :return: None """
glibc_functions_blacklist = { '_start', '_init', '_fini', '__gmon_start__', '__do_global_dtors_aux', 'frame_dummy', 'atexit', 'deregister_tm_clones', 'register_tm_clones', '__x86.get_pc_thunk.bx', '__libc_csu_init', '__libc_csu_fini', } glibc_data_blacklist = { '__TMC_END__', '_GLOBAL_OFFSET_TABLE_', '__JCR_END__', '__dso_handle', '__init_array_start', '__init_array_end', # 'stdout', 'stderr', 'stdin', 'program_invocation_short_', 'program_invocation_short_name', 'program_invocation_name', '__progname_full', '_IO_stdin_used', 'obstack_alloc_failed_hand', 'optind', 'optarg', '__progname', '_environ', 'environ', '__environ', } glibc_references_blacklist = { 'frame_dummy', '__do_global_dtors_aux', } self.procedures = [p for p in self.procedures if p.name not in glibc_functions_blacklist and not p.is_plt] self.data = [d for d in self.data if not any(lbl.name in glibc_data_blacklist for _, lbl in d.labels)] for d in self.data: if d.sort == 'pointer-array': for i in range(len(d.content)): ptr = d.content[i] if isinstance(ptr, Label) and ptr.name in glibc_references_blacklist: d.content[i] = 0
<SYSTEM_TASK:> Find sequences in binary data. <END_TASK> <USER_TASK:> Description: def _sequence_handler(self, cfg, irsb, irsb_addr, stmt_idx, data_addr, max_size): # pylint:disable=unused-argument """ Find sequences in binary data. :param angr.analyses.CFG cfg: The control flow graph. :param pyvex.IRSB irsb: The IRSB object. :param int irsb_addr: Address of the block. :param int stmt_idx: Statement ID. :param int data_addr: Address of the data in memory. :param int max_size: Maximum size possible. :return: A 2-tuple of data type and size. :rtype: tuple """
if not self._is_sequence(cfg, data_addr, 5): # fail-fast return None, None sequence_max_size = min(256, max_size) for i in range(5, min(256, max_size)): if not self._is_sequence(cfg, data_addr, i): return 'sequence', i - 1 return 'sequence', sequence_max_size
<SYSTEM_TASK:> Identifies the CGC package list associated with the CGC binary. <END_TASK> <USER_TASK:> Description: def _cgc_package_list_identifier(self, data_addr, data_size): """ Identifies the CGC package list associated with the CGC binary. :param int data_addr: Address of the data in memory. :param int data_size: Maximum size possible. :return: A 2-tuple of data type and size. :rtype: tuple """
if data_size < 100: return None, None data = self.fast_memory_load(data_addr, data_size, str) if data[:10] != 'The DECREE': return None, None if not all(i in string.printable for i in data): return None, None if not re.match(r"The DECREE packages used in the creation of this challenge binary were:", data): return None, None return 'cgc-package-list', data_size
<SYSTEM_TASK:> Return the maximum number of bytes until a potential pointer or a potential sequence is found. <END_TASK> <USER_TASK:> Description: def _unknown_data_size_handler(self, cfg, irsb, irsb_addr, stmt_idx, data_addr, max_size): # pylint:disable=unused-argument """ Return the maximum number of bytes until a potential pointer or a potential sequence is found. :param angr.analyses.CFG cfg: The control flow graph. :param pyvex.IRSB irsb: The IRSB object. :param int irsb_addr: Address of the block. :param int stmt_idx: Statement ID. :param int data_addr: Address of the data in memory. :param int max_size: Maximum size possible. :return: A 2-tuple of data type and size. :rtype: tuple """
sequence_offset = None for offset in range(1, max_size): if self._is_sequence(cfg, data_addr + offset, 5): # a potential sequence is found sequence_offset = offset break if sequence_offset is not None: if self.project.arch.bits == 32: max_size = min(max_size, sequence_offset) elif self.project.arch.bits == 64: max_size = min(max_size, sequence_offset + 5) # high 5 bytes might be all zeros... ptr_size = cfg.project.arch.bytes size = None for offset in range(1, max_size - ptr_size + 1): ptr = self.fast_memory_load(data_addr + offset, ptr_size, int, endness=cfg.project.arch.memory_endness) if self._is_pointer(cfg, ptr): size = offset break if size is not None: return "unknown", size elif sequence_offset is not None: return "unknown", sequence_offset else: return None, None
<SYSTEM_TASK:> Load memory bytes from loader's memory backend. <END_TASK> <USER_TASK:> Description: def fast_memory_load(self, addr, size, data_type, endness='Iend_LE'): """ Load memory bytes from loader's memory backend. :param int addr: The address to begin memory loading. :param int size: Size in bytes. :param data_type: Type of the data. :param str endness: Endianness of this memory load. :return: Data read out of the memory. :rtype: int or bytes or str or None """
if data_type is int: try: return self.project.loader.memory.unpack_word(addr, size=size, endness=endness) except KeyError: return None try: data = self.project.loader.memory.load(addr, size) if data_type is str: return "".join(chr(i) for i in data) return data except KeyError: return None
<SYSTEM_TASK:> Do a DFS traversal of the graph, and return with the back edges. <END_TASK> <USER_TASK:> Description: def dfs_back_edges(graph, start_node): """ Do a DFS traversal of the graph, and return with the back edges. Note: This is just a naive recursive implementation, feel free to replace it. I couldn't find anything in networkx to do this functionality. Although the name suggest it, but `dfs_labeled_edges` is doing something different. :param graph: The graph to traverse. :param node: The node where to start the traversal :returns: An iterator of 'backward' edges """
visited = set() finished = set() def _dfs_back_edges_core(node): visited.add(node) for child in iter(graph[node]): if child not in finished: if child in visited: yield node, child else: for s,t in _dfs_back_edges_core(child): yield s,t finished.add(node) for s,t in _dfs_back_edges_core(start_node): yield s,t
<SYSTEM_TASK:> Compute a dominance frontier based on the given post-dominator tree. <END_TASK> <USER_TASK:> Description: def compute_dominance_frontier(graph, domtree): """ Compute a dominance frontier based on the given post-dominator tree. This implementation is based on figure 2 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. :param graph: The graph where we want to compute the dominance frontier. :param domtree: The dominator tree :returns: A dict of dominance frontier """
df = {} # Perform a post-order search on the dominator tree for x in networkx.dfs_postorder_nodes(domtree): if x not in graph: # Skip nodes that are not in the graph continue df[x] = set() # local set for y in graph.successors(x): if x not in domtree.predecessors(y): df[x].add(y) # up set if x is None: continue for z in domtree.successors(x): if z is x: continue if z not in df: continue for y in df[z]: if x not in list(domtree.predecessors(y)): df[x].add(y) return df
<SYSTEM_TASK:> Return the successors of a node in the graph. <END_TASK> <USER_TASK:> Description: def _graph_successors(self, graph, node): """ Return the successors of a node in the graph. This method can be overriden in case there are special requirements with the graph and the successors. For example, when we are dealing with a control flow graph, we may not want to get the FakeRet successors. :param graph: The graph. :param node: The node of which we want to get the successors. :return: An iterator of successors. :rtype: iter """
if self._graph_successors_func is not None: return self._graph_successors_func(graph, node) return graph.successors(node)
<SYSTEM_TASK:> Find post-dominators for each node in the graph. <END_TASK> <USER_TASK:> Description: def _construct(self, graph, entry_node): """ Find post-dominators for each node in the graph. This implementation is based on paper A Fast Algorithm for Finding Dominators in a Flow Graph by Thomas Lengauer and Robert E. Tarjan from Stanford University, ACM Transactions on Programming Languages and Systems, Vol. 1, No. 1, July 1979 """
# Step 1 _prepared_graph, vertices, parent = self._prepare_graph(graph, entry_node) # vertices is a list of ContainerNode instances # parent is a dict storing the mapping from ContainerNode to ContainerNode # Each node in prepared_graph is a ContainerNode instance bucket = defaultdict(set) dom = [None] * (len(vertices)) self._ancestor = [None] * (len(vertices) + 1) for i in range(len(vertices) - 1, 0, -1): w = vertices[i] # Step 2 if w not in parent: # It's one of the start nodes continue predecessors = _prepared_graph.predecessors(w) for v in predecessors: u = self._pd_eval(v) if self._semi[u.index].index < self._semi[w.index].index: self._semi[w.index] = self._semi[u.index] bucket[vertices[self._semi[w.index].index].index].add(w) self._pd_link(parent[w], w) # Step 3 for v in bucket[parent[w].index]: u = self._pd_eval(v) if self._semi[u.index].index < self._semi[v.index].index: dom[v.index] = u else: dom[v.index] = parent[w] bucket[parent[w].index].clear() for i in range(1, len(vertices)): w = vertices[i] if w not in parent: continue if dom[w.index].index != vertices[self._semi[w.index].index].index: dom[w.index] = dom[dom[w.index].index] self.dom = networkx.DiGraph() # The post-dom tree described in a directional graph for i in range(1, len(vertices)): if dom[i] is not None and vertices[i] is not None: self.dom.add_edge(dom[i].obj, vertices[i].obj) # Output self.prepared_graph = _prepared_graph
<SYSTEM_TASK:> A dumb and simple way to conveniently aggregate all loggers. <END_TASK> <USER_TASK:> Description: def load_all_loggers(self): """ A dumb and simple way to conveniently aggregate all loggers. Adds attributes to this instance of each registered logger, replacing '.' with '_' """
for name, logger in logging.Logger.manager.loggerDict.items(): if any(name.startswith(x + '.') or name == x for x in self.IN_SCOPE): self._loggers[name] = logger
<SYSTEM_TASK:> Add a function `func` and all blocks of this function to the blanket. <END_TASK> <USER_TASK:> Description: def add_function(self, func): """ Add a function `func` and all blocks of this function to the blanket. """
for block in func.blocks: self.add_obj(block.addr, block)
<SYSTEM_TASK:> The debugging representation of this CFBlanket. <END_TASK> <USER_TASK:> Description: def dbg_repr(self): """ The debugging representation of this CFBlanket. :return: The debugging representation of this CFBlanket. :rtype: str """
output = [ ] for obj in self.project.loader.all_objects: for section in obj.sections: if section.memsize == 0: continue min_addr, max_addr = section.min_addr, section.max_addr output.append("### Object %s" % repr(section)) output.append("### Range %#x-%#x" % (min_addr, max_addr)) pos = min_addr while pos < max_addr: try: addr, thing = self.floor_item(pos) output.append("%#x: %s" % (addr, repr(thing))) if thing.size == 0: pos += 1 else: pos += thing.size except KeyError: pos += 1 output.append("") return "\n".join(output)
<SYSTEM_TASK:> Test whether a statement is inside the loop body or not. <END_TASK> <USER_TASK:> Description: def _stmt_inside_loop(self, stmt_idx): """ Test whether a statement is inside the loop body or not. :param stmt_idx: :return: """
# TODO: This is slow. Fix the performance issue for node in self.loop.body_nodes: if node.addr.stmt_idx <= stmt_idx < node.addr.stmt_idx + node.size: return True return False
<SYSTEM_TASK:> Iterator based check. <END_TASK> <USER_TASK:> Description: def _is_bounded_iterator_based(self): """ Iterator based check. With respect to a certain variable/value A, - there must be at least one exit condition being A//Iterator//HasNext == 0 - there must be at least one local that ticks the iterator next: A//Iterator//Next """
# Condition 0 check_0 = lambda cond: (isinstance(cond, Condition) and cond.op == Condition.Equal and cond.val1 == 0 and isinstance(cond.val0, AnnotatedVariable) and cond.val0.type == VariableTypes.HasNext ) check_0_results = [ (check_0(stmt[0]), stmt[0]) for stmt in self.loop_exit_stmts ] check_0_conds = [ cond for r, cond in check_0_results if r ] # remove all False ones if not check_0_conds: return None the_iterator = check_0_conds[0].val0.variable # Condition 1 check_1 = lambda local: (isinstance(local, AnnotatedVariable) and local.type == VariableTypes.Next and local.variable == the_iterator ) if not any([ check_1(local) for local in self.locals.values() ]): return None return True
<SYSTEM_TASK:> Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be <END_TASK> <USER_TASK:> Description: def kill_definitions(self, atom, code_loc, data=None, dummy=True): """ Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification. :param Atom atom: :param CodeLocation code_loc: :param object data: :return: None """
if data is None: data = DataSet(Undefined(atom.size), atom.size) self.kill_and_add_definition(atom, code_loc, data, dummy=dummy)
<SYSTEM_TASK:> Create an entry state. <END_TASK> <USER_TASK:> Description: def state_entry(self, args=None, **kwargs): # pylint: disable=arguments-differ """ Create an entry state. :param args: List of SootArgument values (optional). """
state = self.state_blank(**kwargs) # for the Java main method `public static main(String[] args)`, # we add symbolic cmdline arguments if not args and state.addr.method.name == 'main' and \ state.addr.method.params[0] == 'java.lang.String[]': cmd_line_args = SimSootExpr_NewArray.new_array(state, "java.lang.String", BVS('argc', 32)) cmd_line_args.add_default_value_generator(self.generate_symbolic_cmd_line_arg) args = [SootArgument(cmd_line_args, "java.lang.String[]")] # for referencing the Java array, we need to know the array reference # => saves it in the globals dict state.globals['cmd_line_args'] = cmd_line_args # setup arguments SimEngineSoot.setup_arguments(state, args) return state
<SYSTEM_TASK:> Create a native or a Java call state. <END_TASK> <USER_TASK:> Description: def state_call(self, addr, *args, **kwargs): """ Create a native or a Java call state. :param addr: Soot or native addr of the invoke target. :param args: List of SootArgument values. """
state = kwargs.pop('base_state', None) # check if we need to setup a native or a java callsite if isinstance(addr, SootAddressDescriptor): # JAVA CALLSITE # ret addr precedence: ret_addr kwarg > base_state.addr > terminator ret_addr = kwargs.pop('ret_addr', state.addr if state else SootAddressTerminator()) cc = kwargs.pop('cc', SimCCSoot(self.arch)) if state is None: state = self.state_blank(addr=addr, **kwargs) else: state = state.copy() state.regs.ip = addr cc.setup_callsite(state, ret_addr, args) return state else: # NATIVE CALLSITE # setup native argument values native_arg_values = [] for arg in args: if arg.type in ArchSoot.primitive_types or \ arg.type == "JNIEnv": # the value of primitive types and the JNIEnv pointer # are just getting copied into the native memory native_arg_value = arg.value if self.arch.bits == 32 and arg.type == "long": # On 32 bit architecture, long values (w/ 64 bit) are copied # as two 32 bit integer # TODO is this correct? upper = native_arg_value.get_bytes(0, 4) lower = native_arg_value.get_bytes(4, 4) idx = args.index(arg) args = args[:idx] \ + (SootArgument(upper, 'int'), SootArgument(lower, 'int')) \ + args[idx+1:] native_arg_values += [upper, lower] continue else: # argument has a relative type # => map Java reference to an opaque reference, which the native code # can use to access the Java object through the JNI interface native_arg_value = state.jni_references.create_new_reference(obj=arg.value) native_arg_values += [native_arg_value] # setup native return type ret_type = kwargs.pop('ret_type') native_ret_type = self.get_native_type(ret_type) # setup function prototype, so the SimCC know how to init the callsite arg_types = [self.get_native_type(arg.type) for arg in args] prototype = SimTypeFunction(args=arg_types, returnty=native_ret_type) native_cc = self.get_native_cc(func_ty=prototype) # setup native invoke state return self.native_simos.state_call(addr, *native_arg_values, base_state=state, ret_addr=self.native_return_hook_addr, cc=native_cc, **kwargs)
<SYSTEM_TASK:> Java specify defaults values for primitive and reference types. This <END_TASK> <USER_TASK:> Description: def get_default_value_by_type(type_, state=None): """ Java specify defaults values for primitive and reference types. This method returns the default value for a given type. :param str type_: Name of type. :return: Default value for this type. """
if type_ in ['byte', 'char', 'short', 'int', 'boolean']: return BVS('default_value_{}'.format(type_), 32) elif type_ == "long": return BVS('default_value_{}'.format(type_), 64) elif type_ == 'float': return FPS('default_value_{}'.format(type_), FSORT_FLOAT) elif type_ == 'double': return FPS('default_value_{}'.format(type_), FSORT_DOUBLE) elif state is not None: if type_ == 'java.lang.String': return SimSootValue_StringRef.new_string(state, StringS('default_value_{}'.format(type_), 1000)) if type_.endswith('[][]'): raise NotImplementedError # multiarray = SimSootExpr_NewMultiArray.new_array(self.state, element_type, size) # multiarray.add_default_value_generator(lambda s: SimSootExpr_NewMultiArray._generate_inner_array(s, element_type, sizes)) # return multiarray elif type_.endswith('[]'): array = SimSootExpr_NewArray.new_array(state, type_[:-2], BVV(2, 32)) return array else: return SimSootValue_ThisRef.new_object(state, type_, symbolic=True, init_object=False) else: # not a primitive type # => treat it as a reference return SootNullConstant()
<SYSTEM_TASK:> Cast the value of primtive types. <END_TASK> <USER_TASK:> Description: def cast_primitive(state, value, to_type): """ Cast the value of primtive types. :param value: Bitvector storing the primitive value. :param to_type: Name of the targeted type. :return: Resized value. """
if to_type in ['float', 'double']: if value.symbolic: # TODO extend support for floating point types l.warning('No support for symbolic floating-point arguments.' 'Value gets concretized.') value = float(state.solver.eval(value)) sort = FSORT_FLOAT if to_type == 'float' else FSORT_DOUBLE return FPV(value, sort) elif to_type == 'int' and isinstance(value, FP): # TODO fix fpToIEEEBV in claripty l.warning('Converting FP to BV might provide incorrect results.') return fpToIEEEBV(value)[63:32] elif to_type == 'long' and isinstance(value, FP): # TODO fix fpToIEEEBV in claripty l.warning('Converting FP to BV might provide incorrect results.') return fpToIEEEBV(value) else: # lookup the type size and extract value value_size = ArchSoot.sizeof[to_type] value_extracted = value.reversed.get_bytes(index=0, size=value_size//8).reversed # determine size of Soot bitvector and resize bitvector # Note: smaller types than int's are stored in a 32-bit BV value_soot_size = value_size if value_size >= 32 else 32 if to_type in ['char', 'boolean']: # unsigned extend return value_extracted.zero_extend(value_soot_size-value_extracted.size()) # signed extend return value_extracted.sign_extend(value_soot_size-value_extracted.size())
<SYSTEM_TASK:> Initialize the static field with an allocated, but not initialized, <END_TASK> <USER_TASK:> Description: def init_static_field(state, field_class_name, field_name, field_type): """ Initialize the static field with an allocated, but not initialized, object of the given type. :param state: State associated to the field. :param field_class_name: Class containing the field. :param field_name: Name of the field. :param field_type: Type of the field and the new object. """
field_ref = SimSootValue_StaticFieldRef.get_ref(state, field_class_name, field_name, field_type) field_val = SimSootValue_ThisRef.new_object(state, field_type) state.memory.store(field_ref, field_val)
<SYSTEM_TASK:> Get address of the implementation from a native declared Java function. <END_TASK> <USER_TASK:> Description: def get_addr_of_native_method(self, soot_method): """ Get address of the implementation from a native declared Java function. :param soot_method: Method descriptor of a native declared function. :return: CLE address of the given method. """
for name, symbol in self.native_symbols.items(): if soot_method.matches_with_native_name(native_method=name): l.debug("Found native symbol '%s' @ %x matching Soot method '%s'", name, symbol.rebased_addr, soot_method) return symbol.rebased_addr native_symbols = "\n".join(self.native_symbols.keys()) l.warning("No native method found that matches the Soot method '%s'. " "Skipping statement.", soot_method.name) l.debug("Available symbols (prefix + encoded class path + encoded method " "name):\n%s", native_symbols) return None
<SYSTEM_TASK:> Fill the class with constrained symbolic values. <END_TASK> <USER_TASK:> Description: def fill_symbolic(self): """ Fill the class with constrained symbolic values. """
self.wYear = self.state.solver.BVS('cur_year', 16, key=('api', 'GetLocalTime', 'cur_year')) self.wMonth = self.state.solver.BVS('cur_month', 16, key=('api', 'GetLocalTime', 'cur_month')) self.wDayOfWeek = self.state.solver.BVS('cur_dayofweek', 16, key=('api', 'GetLocalTime', 'cur_dayofweek')) self.wDay = self.state.solver.BVS('cur_day', 16, key=('api', 'GetLocalTime', 'cur_day')) self.wHour = self.state.solver.BVS('cur_hour', 16, key=('api', 'GetLocalTime', 'cur_hour')) self.wMinute = self.state.solver.BVS('cur_minute', 16, key=('api', 'GetLocalTime', 'cur_minute')) self.wSecond = self.state.solver.BVS('cur_second', 16, key=('api', 'GetLocalTime', 'cur_second')) self.wMilliseconds = self.state.solver.BVS('cur_millisecond', 16, key=('api', 'GetLocalTime', 'cur_millisecond')) self.state.add_constraints(self.wYear >= 1601) self.state.add_constraints(self.wYear <= 30827) self.state.add_constraints(self.wMonth >= 1) self.state.add_constraints(self.wMonth <= 12) self.state.add_constraints(self.wDayOfWeek <= 6) self.state.add_constraints(self.wDay >= 1) self.state.add_constraints(self.wDay <= 31) self.state.add_constraints(self.wHour <= 23) self.state.add_constraints(self.wMinute <= 59) self.state.add_constraints(self.wSecond <= 59) self.state.add_constraints(self.wMilliseconds <= 999)
<SYSTEM_TASK:> Fill the class with the appropriate values extracted from the given timestamp. <END_TASK> <USER_TASK:> Description: def fill_from_timestamp(self, ts): """ Fill the class with the appropriate values extracted from the given timestamp. :param ts: A POSIX timestamp. """
dt = datetime.datetime.fromtimestamp(ts) self.wYear = dt.year self.wMonth = dt.month self.wDayOfWeek = dt.isoweekday() % 7 # :/ self.wDay = dt.day self.wHour = dt.hour self.wMinute = dt.minute self.wSecond = dt.second self.wMilliseconds = dt.microsecond // 1000
<SYSTEM_TASK:> Pretty-print an IRSB with whitelist information <END_TASK> <USER_TASK:> Description: def dbg_print_irsb(self, irsb_addr, project=None): """ Pretty-print an IRSB with whitelist information """
if project is None: project = self._project if project is None: raise Exception("Dict addr_to_run is empty. " + \ "Give me a project, and I'll recreate the IRSBs for you.") else: vex_block = project.factory.block(irsb_addr).vex statements = vex_block.statements whitelist = self.get_whitelisted_statements(irsb_addr) for i in range(0, len(statements)): if whitelist is True or i in whitelist: line = "+" else: line = "-" line += "[% 3d] " % i # We cannot get data returned by pp(). WTF? print(line, end='') statements[i].pp()
<SYSTEM_TASK:> Given a path, returns True if the path should be kept, False if it should be cut. <END_TASK> <USER_TASK:> Description: def keep_path(self, path): """ Given a path, returns True if the path should be kept, False if it should be cut. """
if len(path.addr_trace) < 2: return True return self.should_take_exit(path.addr_trace[-2], path.addr_trace[-1])
<SYSTEM_TASK:> Removes a mapping based on its absolute address. <END_TASK> <USER_TASK:> Description: def unmap_by_address(self, absolute_address): """ Removes a mapping based on its absolute address. :param absolute_address: An absolute address """
desc = self._address_to_region_id[absolute_address] del self._address_to_region_id[absolute_address] del self._region_id_to_address[desc.region_id]
<SYSTEM_TASK:> Convert a relative address in some memory region to an absolute address. <END_TASK> <USER_TASK:> Description: def absolutize(self, region_id, relative_address): """ Convert a relative address in some memory region to an absolute address. :param region_id: The memory region ID :param relative_address: The relative memory offset in that memory region :return: An absolute address if converted, or an exception is raised when region id does not exist. """
if region_id == 'global': # The global region always bases 0 return relative_address if region_id not in self._region_id_to_address: raise SimRegionMapError('Non-existent region ID "%s"' % region_id) base_address = self._region_id_to_address[region_id].base_address return base_address + relative_address
<SYSTEM_TASK:> Convert an absolute address to the memory offset in a memory region. <END_TASK> <USER_TASK:> Description: def relativize(self, absolute_address, target_region_id=None): """ Convert an absolute address to the memory offset in a memory region. Note that if an address belongs to heap region is passed in to a stack region map, it will be converted to an offset included in the closest stack frame, and vice versa for passing a stack address to a heap region. Therefore you should only pass in address that belongs to the same category (stack or non-stack) of this region map. :param absolute_address: An absolute memory address :return: A tuple of the closest region ID, the relative offset, and the related function address. """
if target_region_id is None: if self.is_stack: # Get the base address of the stack frame it belongs to base_address = next(self._address_to_region_id.irange(minimum=absolute_address, reverse=False)) else: try: base_address = next(self._address_to_region_id.irange(maximum=absolute_address, reverse=True)) except StopIteration: # Not found. It belongs to the global region then. return 'global', absolute_address, None descriptor = self._address_to_region_id[base_address] else: if target_region_id == 'global': # Just return the absolute address return 'global', absolute_address, None if target_region_id not in self._region_id_to_address: raise SimRegionMapError('Trying to relativize to a non-existent region "%s"' % target_region_id) descriptor = self._region_id_to_address[target_region_id] base_address = descriptor.base_address return descriptor.region_id, absolute_address - base_address, descriptor.related_function_address
<SYSTEM_TASK:> Call the set_state method in SimStatePlugin class, and then perform the delayed initialization. <END_TASK> <USER_TASK:> Description: def set_state(self, state): """ Call the set_state method in SimStatePlugin class, and then perform the delayed initialization. :param state: The SimState instance """
SimStatePlugin.set_state(self, state) # Delayed initialization stack_region_map, generic_region_map = self._temp_stack_region_map, self._temp_generic_region_map if stack_region_map or generic_region_map: # Inherited from its parent self._stack_region_map = stack_region_map.copy() self._generic_region_map = generic_region_map.copy() else: if not self._abstract_backer and o.REGION_MAPPING in self.state.options: # Only the top-level SimMemory instance can have region maps. self._stack_region_map = RegionMap(True) self._generic_region_map = RegionMap(False) else: self._stack_region_map = None self._generic_region_map = None
<SYSTEM_TASK:> Remove a stack mapping. <END_TASK> <USER_TASK:> Description: def unset_stack_address_mapping(self, absolute_address): """ Remove a stack mapping. :param absolute_address: An absolute memory address, which is the base address of the stack frame to destroy. """
if self._stack_region_map is None: raise SimMemoryError('Stack region map is not initialized.') self._stack_region_map.unmap_by_address(absolute_address)
<SYSTEM_TASK:> Return a memory region ID for a function. If the default region ID exists in the region mapping, an integer <END_TASK> <USER_TASK:> Description: def stack_id(self, function_address): """ Return a memory region ID for a function. If the default region ID exists in the region mapping, an integer will appended to the region name. In this way we can handle recursive function calls, or a function that appears more than once in the call frame. This also means that `stack_id()` should only be called when creating a new stack frame for a function. You are not supposed to call this function every time you want to map a function address to a stack ID. :param int function_address: Address of the function. :return: ID of the new memory region. :rtype: str """
region_id = 'stack_0x%x' % function_address # deduplication region_ids = self._stack_region_map.region_ids if region_id not in region_ids: return region_id else: for i in range(0, 2000): new_region_id = region_id + '_%d' % i if new_region_id not in region_ids: return new_region_id raise SimMemoryError('Cannot allocate region ID for function %#08x - recursion too deep' % function_address)
<SYSTEM_TASK:> Stores content into memory, conditional by case. <END_TASK> <USER_TASK:> Description: def store_cases(self, addr, contents, conditions, fallback=None, add_constraints=None, endness=None, action=None): """ Stores content into memory, conditional by case. :param addr: A claripy expression representing the address to store at. :param contents: A list of bitvectors, not necessarily of the same size. Use None to denote an empty write. :param conditions: A list of conditions. Must be equal in length to contents. The following parameters are optional. :param fallback: A claripy expression representing what the write should resolve to if all conditions evaluate to false (default: whatever was there before). :param add_constraints: Add constraints resulting from the merge (default: True) :param endness: The endianness for contents as well as fallback. :param action: A SimActionData to fill out with the final written value and constraints. :type action: SimActionData """
if fallback is None and all(c is None for c in contents): l.debug("Avoiding an empty write.") return addr_e = _raw_ast(addr) contents_e = _raw_ast(contents) conditions_e = _raw_ast(conditions) fallback_e = _raw_ast(fallback) max_bits = max(c.length for c in contents_e if isinstance(c, claripy.ast.Bits)) \ if fallback is None else fallback.length # if fallback is not provided by user, load it from memory # remember to specify the endianness! fallback_e = self.load(addr, max_bits//self.state.arch.byte_width, add_constraints=add_constraints, endness=endness) \ if fallback_e is None else fallback_e req = self._store_cases(addr_e, contents_e, conditions_e, fallback_e, endness=endness) add_constraints = self.state._inspect_getattr('address_concretization_add_constraints', add_constraints) if add_constraints: self.state.add_constraints(*req.constraints) if req.completed and o.AUTO_REFS in self.state.options and action is None: region_type = self.category if region_type == 'file': # Special handling for files to keep compatibility # We may use some refactoring later region_type = self.id action = SimActionData(self.state, region_type, 'write', addr=addr_e, data=req.stored_values[-1], size=max_bits, condition=self.state.solver.Or(*conditions), fallback=fallback ) self.state.history.add_action(action) if req.completed and action is not None: action.actual_addrs = req.actual_addresses action.actual_value = action._make_object(req.stored_values[-1]) action.added_constraints = action._make_object(self.state.solver.And(*req.constraints) if len(req.constraints) > 0 else self.state.solver.true)
<SYSTEM_TASK:> Returns the address of bytes equal to 'what', starting from 'start'. Note that, if you don't specify a default <END_TASK> <USER_TASK:> Description: def find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None, step=1, disable_actions=False, inspect=True, chunk_size=None): """ Returns the address of bytes equal to 'what', starting from 'start'. Note that, if you don't specify a default value, this search could cause the state to go unsat if no possible matching byte exists. :param addr: The start address. :param what: What to search for; :param max_search: Search at most this many bytes. :param max_symbolic_bytes: Search through at most this many symbolic bytes. :param default: The default value, if what you're looking for wasn't found. :param step: The stride that the search should use while scanning memory :param disable_actions: Whether to inhibit the creation of SimActions for memory access :param inspect: Whether to trigger SimInspect breakpoints :returns: An expression representing the address of the matching byte. """
addr = _raw_ast(addr) what = _raw_ast(what) default = _raw_ast(default) if isinstance(what, bytes): # Convert it to a BVV what = claripy.BVV(what, len(what) * self.state.arch.byte_width) r,c,m = self._find(addr, what, max_search=max_search, max_symbolic_bytes=max_symbolic_bytes, default=default, step=step, disable_actions=disable_actions, inspect=inspect, chunk_size=chunk_size) if o.AST_DEPS in self.state.options and self.category == 'reg': r = SimActionObject(r, reg_deps=frozenset((addr,))) return r,c,m
<SYSTEM_TASK:> Copies data within a memory. <END_TASK> <USER_TASK:> Description: def copy_contents(self, dst, src, size, condition=None, src_memory=None, dst_memory=None, inspect=True, disable_actions=False): """ Copies data within a memory. :param dst: A claripy expression representing the address of the destination :param src: A claripy expression representing the address of the source The following parameters are optional. :param src_memory: Copy data from this SimMemory instead of self :param src_memory: Copy data to this SimMemory instead of self :param size: A claripy expression representing the size of the copy :param condition: A claripy expression representing a condition, if the write should be conditional. If this is determined to be false, the size of the copy will be 0. """
dst = _raw_ast(dst) src = _raw_ast(src) size = _raw_ast(size) condition = _raw_ast(condition) return self._copy_contents(dst, src, size, condition=condition, src_memory=src_memory, dst_memory=dst_memory, inspect=inspect, disable_actions=disable_actions)
<SYSTEM_TASK:> Pretty print the graph. @imarks determine whether the printed graph <END_TASK> <USER_TASK:> Description: def pp(self, imarks=False): """ Pretty print the graph. @imarks determine whether the printed graph represents instructions (coarse grained) for easier navigation, or exact statements. """
for e in self.graph.edges(): data = dict(self.graph.get_edge_data(e[0], e[1])) data['label'] = str(data['label']) + " ; " + self._simproc_info(e[0]) + self._simproc_info(e[1]) self._print_edge(e, data, imarks)
<SYSTEM_TASK:> Get the base address of a memory region. <END_TASK> <USER_TASK:> Description: def _region_base(self, region): """ Get the base address of a memory region. :param str region: ID of the memory region :return: Address of the memory region :rtype: int """
if region == 'global': region_base_addr = 0 elif region.startswith('stack_'): region_base_addr = self._stack_region_map.absolutize(region, 0) else: region_base_addr = self._generic_region_map.absolutize(region, 0) return region_base_addr
<SYSTEM_TASK:> Create a new MemoryRegion with the region key specified, and store it to self._regions. <END_TASK> <USER_TASK:> Description: def create_region(self, key, state, is_stack, related_function_addr, endness, backer_dict=None): """ Create a new MemoryRegion with the region key specified, and store it to self._regions. :param key: a string which is the region key :param state: the SimState instance :param bool is_stack: Whether this memory region is on stack. True/False :param related_function_addr: Which function first creates this memory region. Just for reference. :param endness: The endianness. :param backer_dict: The memory backer object. :return: None """
self._regions[key] = MemoryRegion(key, state=state, is_stack=is_stack, related_function_addr=related_function_addr, endness=endness, backer_dict=backer_dict, )
<SYSTEM_TASK:> If this is a stack address, we convert it to a correct region and address <END_TASK> <USER_TASK:> Description: def _normalize_address(self, region_id, relative_address, target_region=None): """ If this is a stack address, we convert it to a correct region and address :param region_id: a string indicating which region the address is relative to :param relative_address: an address that is relative to the region parameter :param target_region: the ideal target region that address is normalized to. None means picking the best fit. :return: an AddressWrapper object """
if self._stack_region_map.is_empty and self._generic_region_map.is_empty: # We don't have any mapped region right now return AddressWrapper(region_id, 0, relative_address, False, None) # We wanna convert this address to an absolute address first if region_id.startswith('stack_'): absolute_address = self._stack_region_map.absolutize(region_id, relative_address) else: absolute_address = self._generic_region_map.absolutize(region_id, relative_address) stack_base = self._stack_region_map.stack_base if stack_base - self._stack_size < relative_address <= stack_base and \ (target_region is not None and target_region.startswith('stack_')): # The absolute address seems to be in the stack region. # Map it to stack new_region_id, new_relative_address, related_function_addr = self._stack_region_map.relativize( absolute_address, target_region_id=target_region ) return AddressWrapper(new_region_id, self._region_base(new_region_id), new_relative_address, True, related_function_addr ) else: new_region_id, new_relative_address, related_function_addr = self._generic_region_map.relativize( absolute_address, target_region_id=target_region ) return AddressWrapper(new_region_id, self._region_base(new_region_id), new_relative_address, False, None)
<SYSTEM_TASK:> Convert a ValueSet object into a list of addresses. <END_TASK> <USER_TASK:> Description: def normalize_address(self, addr, is_write=False, convert_to_valueset=False, target_region=None, condition=None): #pylint:disable=arguments-differ """ Convert a ValueSet object into a list of addresses. :param addr: A ValueSet object (which describes an address) :param is_write: Is this address used in a write or not :param convert_to_valueset: True if you want to have a list of ValueSet instances instead of AddressWrappers, False otherwise :param target_region: Which region to normalize the address to. To leave the decision to SimuVEX, set it to None :return: A list of AddressWrapper or ValueSet objects """
targets_limit = WRITE_TARGETS_LIMIT if is_write else READ_TARGETS_LIMIT if type(addr) is not int: for constraint in self.state.solver.constraints: if getattr(addr, 'variables', set()) & constraint.variables: addr = self._apply_condition_to_symbolic_addr(addr, constraint) # Apply the condition if necessary if condition is not None: addr = self._apply_condition_to_symbolic_addr(addr, condition) if type(addr) is int: addr = self.state.solver.BVV(addr, self.state.arch.bits) addr_with_regions = self._normalize_address_type(addr) address_wrappers = [ ] for region, addr_si in addr_with_regions: concrete_addrs = addr_si.eval(targets_limit) if len(concrete_addrs) == targets_limit and HYBRID_SOLVER in self.state.options: exact = True if APPROXIMATE_FIRST not in self.state.options else None solutions = self.state.solver.eval_upto(addr, targets_limit, exact=exact) if len(solutions) < len(concrete_addrs): concrete_addrs = [addr_si.intersection(s).eval(1)[0] for s in solutions] if len(concrete_addrs) == targets_limit: self.state.history.add_event('mem', message='concretized too many targets. address = %s' % addr_si) for c in concrete_addrs: aw = self._normalize_address(region, c, target_region=target_region) address_wrappers.append(aw) if convert_to_valueset: return [ i.to_valueset(self.state) for i in address_wrappers ] else: return address_wrappers
<SYSTEM_TASK:> Get a segmented memory region based on AbstractLocation information available from VSA. <END_TASK> <USER_TASK:> Description: def get_segments(self, addr, size): """ Get a segmented memory region based on AbstractLocation information available from VSA. Here are some assumptions to make this method fast: - The entire memory region [addr, addr + size] is located within the same MemoryRegion - The address 'addr' has only one concrete value. It cannot be concretized to multiple values. :param addr: An address :param size: Size of the memory area in bytes :return: An ordered list of sizes each segment in the requested memory region """
address_wrappers = self.normalize_address(addr, is_write=False) # assert len(address_wrappers) > 0 aw = address_wrappers[0] region_id = aw.region if region_id in self.regions: region = self.regions[region_id] alocs = region.get_abstract_locations(aw.address, size) # Collect all segments and sort them segments = [ ] for aloc in alocs: segments.extend(aloc.segments) segments = sorted(segments, key=lambda x: x.offset) # Remove all overlapping segments processed_segments = [ ] last_seg = None for seg in segments: if last_seg is None: last_seg = seg processed_segments.append(seg) else: # Are they overlapping? if seg.offset >= last_seg.offset and seg.offset <= last_seg.offset + size: continue processed_segments.append(seg) # Make it a list of sizes sizes = [ ] next_pos = aw.address for seg in processed_segments: if seg.offset > next_pos: gap = seg.offset - next_pos assert gap > 0 sizes.append(gap) next_pos += gap if seg.size + next_pos > aw.address + size: sizes.append(aw.address + size - next_pos) next_pos += aw.address + size - next_pos else: sizes.append(seg.size) next_pos += seg.size if not sizes: return [ size ] return sizes else: # The region doesn't exist. Then there is only one segment! return [ size ]
<SYSTEM_TASK:> Merge this guy with another SimAbstractMemory instance <END_TASK> <USER_TASK:> Description: def merge(self, others, merge_conditions, common_ancestor=None): """ Merge this guy with another SimAbstractMemory instance """
merging_occurred = False for o in others: for region_id, region in o._regions.items(): if region_id in self._regions: merging_occurred |= self._regions[region_id].merge( [region], merge_conditions, common_ancestor=common_ancestor ) else: merging_occurred = True self._regions[region_id] = region return merging_occurred
<SYSTEM_TASK:> Extract arguments and set them to <END_TASK> <USER_TASK:> Description: def _extract_args(state, main, argc, argv, init, fini): """ Extract arguments and set them to :param angr.sim_state.SimState state: The program state. :param main: An argument to __libc_start_main. :param argc: An argument to __libc_start_main. :param argv: An argument to __libc_start_main. :param init: An argument to __libc_start_main. :param fini: An argument to __libc_start_main. :return: A tuple of five elements: (main, argc, argv, init, fini) :rtype: tuple """
main_ = main argc_ = argc argv_ = argv init_ = init fini_ = fini if state.arch.name == "PPC32": # for some dumb reason, PPC passes arguments to libc_start_main in some completely absurd way argv_ = argc_ argc_ = main_ main_ = state.mem[state.regs.r8 + 4:].int.resolved init_ = state.mem[state.regs.r8 + 8:].int.resolved fini_ = state.mem[state.regs.r8 + 12:].int.resolved elif state.arch.name == "PPC64": main_ = state.mem[state.regs.r8 + 8:].long.resolved init_ = state.mem[state.regs.r8 + 16:].long.resolved fini_ = state.mem[state.regs.r8 + 24:].long.resolved return main_, argc_, argv_, init_, fini_
<SYSTEM_TASK:> Debugging output of this slice. <END_TASK> <USER_TASK:> Description: def dbg_repr(self, max_display=10): """ Debugging output of this slice. :param max_display: The maximum number of SimRun slices to show. :return: A string representation. """
s = repr(self) + "\n" if len(self.chosen_statements) > max_display: s += "%d SimRuns in program slice, displaying %d.\n" % (len(self.chosen_statements), max_display) else: s += "%d SimRuns in program slice.\n" % len(self.chosen_statements) # Pretty-print the first `max_display` basic blocks if max_display is None: # Output all run_addrs = sorted(self.chosen_statements.keys()) else: # Only output the first "max_display" ones run_addrs = sorted(self.chosen_statements.keys())[ : max_display] for run_addr in run_addrs: s += self.dbg_repr_run(run_addr) + "\n" return s
<SYSTEM_TASK:> Debugging output of a single SimRun slice. <END_TASK> <USER_TASK:> Description: def dbg_repr_run(self, run_addr): """ Debugging output of a single SimRun slice. :param run_addr: Address of the SimRun. :return: A string representation. """
if self.project.is_hooked(run_addr): ss = "%#x Hooked\n" % run_addr else: ss = "%#x\n" % run_addr # statements chosen_statements = self.chosen_statements[run_addr] vex_block = self.project.factory.block(run_addr).vex statements = vex_block.statements for i in range(0, len(statements)): if i in chosen_statements: line = "+" else: line = "-" line += "[% 3d] " % i line += str(statements[i]) ss += line + "\n" # exits targets = self.chosen_exits[run_addr] addr_strs = [ ] for exit_stmt_id, target_addr in targets: if target_addr is None: addr_strs.append("default") else: addr_strs.append("%#x" % target_addr) ss += "Chosen exits: " + ", ".join(addr_strs) return ss
<SYSTEM_TASK:> Returns an AnnotatedCFG based on slicing result. <END_TASK> <USER_TASK:> Description: def annotated_cfg(self, start_point=None): """ Returns an AnnotatedCFG based on slicing result. """
# TODO: Support context-sensitivity targets = [ ] for simrun, stmt_idx in self._targets: targets.append((simrun.addr, stmt_idx)) l.debug("Initializing AnnoCFG...") anno_cfg = AnnotatedCFG(self.project, self._cfg) for simrun, stmt_idx in self._targets: if stmt_idx is not -1: anno_cfg.set_last_statement(simrun.addr, stmt_idx) for n in self._cfg.graph.nodes(): run = n if run.addr in self.chosen_statements: if self.chosen_statements[run.addr] is True: anno_cfg.add_block_to_whitelist(run.addr) else: anno_cfg.add_statements_to_whitelist(run.addr, self.chosen_statements[run.addr]) for src, dst in self._cfg.graph.edges(): run = src if dst.addr in self.chosen_statements and src.addr in self.chosen_statements: anno_cfg.add_exit_to_whitelist(run.addr, dst.addr) return anno_cfg