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 ...
<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...
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(l...
<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') ...
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: ...
<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...
# 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)...
<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) ...
<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: ...
# 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 ...
<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 RegisterDelt...
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()):...
<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 initial...
# 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) # lo...
<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: ...
<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. ...
# 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: ...
<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...
# 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_...
<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 suc...
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 overri...
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 ...
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 `sta...
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...
# 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)) ...
<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 recu...
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(gra...
<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...
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 ...
<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 n...
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 do...
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 :...
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) ...
<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: ...
# 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 ...
<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. ...
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): ...
<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)...
<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 exec...
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, ...
<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:...
if sim_successors.sort == 'IRSB' and input_state.thumb: successors = self._arm_thumb_filter_jump_successors(sim_successors.addr, sim_successors.artifacts['irsb'].size, su...
<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 r...
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 ...
<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 fun...
# 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: ...
<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 up...
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 == cur...
<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=N...
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...
<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 unreliabl...
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...
<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 in...
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. ...
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 c...
<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...
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 ...
<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. ...
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: ...
<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(...
<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 r...
<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...
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 analys...
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 i...
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: ...
<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 bloc...
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: ...
<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 ...
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...
<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 ...
<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: ...
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 star...
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: Th...
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 specif...
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=n...
<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_thun...
<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. ...
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 '...
<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 memo...
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 ...
<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...
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.ar...
<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 i...
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: ...
<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. ...
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_ba...
<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 Me...
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 ...
<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...
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 Tho...
# 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 buc...
<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)...
<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 le...
# 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...
<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 inst...
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...
<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', s...
<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. ...
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) ...
<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. :retur...
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))...
<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. ...
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 na...
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...
<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')) ...
<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.micro...
<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 ...
<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 reg...
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].bas...
<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 hea...
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_ad...
<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 S...
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 = stac...
<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 in...
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 ...
<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 ...
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.le...
<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...
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...
<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 e...
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=disabl...
<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 ...
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 st...
self._regions[key] = MemoryRegion(key, state=state, is_stack=is_stack, related_function_addr=related_function_addr, endness=endness, ...
<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 regio...
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(...
<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 addresse...
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(...
<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 t...
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.ad...
<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 ...
<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. ...
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_ mai...
<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 f...
<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 statement...
<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: ...