text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Filter successors for THUMB mode basic blocks, and remove those successors that won't be taken normally. <END_TASK> <USER_TASK:> Description: def _arm_thumb_filter_jump_successors(self, addr, size, successors, get_ins_addr, get_exit_stmt_idx): """ Filter successors for THUMB mode basic bl...
if not successors: return [ ] it_counter = 0 conc_temps = {} can_produce_exits = set() bb = self._lift(addr, size=size, thumb=True, opt_level=0) for stmt in bb.vex.statements: if stmt.tag == 'Ist_IMark': if it_counter > 0: ...
<SYSTEM_TASK:> Check whether the given memory region is extremely sparse, i.e., all bytes are the same value. <END_TASK> <USER_TASK:> Description: def _is_region_extremely_sparse(self, start, end, base_state=None): """ Check whether the given memory region is extremely sparse, i.e., all bytes are the sa...
all_bytes = None if base_state is not None: all_bytes = base_state.memory.load(start, end - start + 1) try: all_bytes = base_state.solver.eval(all_bytes, cast_to=bytes) except SimError: all_bytes = None size = end - start + ...
<SYSTEM_TASK:> Some regions usually do not contain any executable code, but are still marked as executable. We should skip <END_TASK> <USER_TASK:> Description: def _should_skip_region(self, region_start): """ Some regions usually do not contain any executable code, but are still marked as executable. We...
obj = self.project.loader.find_object_containing(region_start, membership_check=False) if obj is None: return False if isinstance(obj, PE): section = obj.find_section_containing(region_start) if section is None: return False if se...
<SYSTEM_TASK:> Get all executable memory regions from the binaries <END_TASK> <USER_TASK:> Description: def _executable_memory_regions(self, objects=None, force_segment=False): """ Get all executable memory regions from the binaries :param objects: A collection of binary objects to collect regi...
if objects is None: binaries = self.project.loader.all_objects else: binaries = objects memory_regions = [ ] for b in binaries: if isinstance(b, ELF): # If we have sections, we get result from sections if not force_s...
<SYSTEM_TASK:> Test if the address belongs to an executable memory region. <END_TASK> <USER_TASK:> Description: def _addr_in_exec_memory_regions(self, addr): """ Test if the address belongs to an executable memory region. :param int addr: The address to test :return: True if the address...
for start, end in self._exec_mem_regions: if start <= addr < end: return True return False
<SYSTEM_TASK:> Test if two addresses belong to the same section. <END_TASK> <USER_TASK:> Description: def _addrs_belong_to_same_section(self, addr_a, addr_b): """ Test if two addresses belong to the same section. :param int addr_a: The first address to test. :param int addr_b: The sec...
obj = self.project.loader.find_object_containing(addr_a, membership_check=False) if obj is None: # test if addr_b also does not belong to any object obj_b = self.project.loader.find_object_containing(addr_b, membership_check=False) if obj_b is None: ...
<SYSTEM_TASK:> Check whether the address belongs to a hook or a syscall. <END_TASK> <USER_TASK:> Description: def _addr_hooked_or_syscall(self, addr): """ Check whether the address belongs to a hook or a syscall. :param int addr: The address to check. :return: True if the ...
return self.project.is_hooked(addr) or self.project.simos.is_syscall_addr(addr)
<SYSTEM_TASK:> Perform a fast memory loading of some data. <END_TASK> <USER_TASK:> Description: def _fast_memory_load_bytes(self, addr, length): """ Perform a fast memory loading of some data. :param int addr: Address to read from. :param int length: Size of the string to load. ...
try: return self.project.loader.memory.load(addr, length) except KeyError: return None
<SYSTEM_TASK:> Perform a fast memory loading of a pointer. <END_TASK> <USER_TASK:> Description: def _fast_memory_load_pointer(self, addr, size=None): """ Perform a fast memory loading of a pointer. :param int addr: Address to read from. :param int size: Size of the pointer. Default to m...
try: return self.project.loader.memory.unpack_word(addr, size=size) except KeyError: return None
<SYSTEM_TASK:> Determine if a function returns or not. <END_TASK> <USER_TASK:> Description: def _determine_function_returning(self, func, all_funcs_completed=False): """ Determine if a function returns or not. A function does not return if a) it is a SimProcedure that has NO_RET being T...
# If there is at least one return site, then this function is definitely returning if func.has_return: return True # Let's first see if it's a known SimProcedure that does not return if self.project.is_hooked(func.addr): procedure = self.project.hooked_by(func....
<SYSTEM_TASK:> For each function in the function_manager, try to determine if it returns or not. A function does not return if <END_TASK> <USER_TASK:> Description: def _analyze_function_features(self, all_funcs_completed=False): """ For each function in the function_manager, try to determine if it retur...
changes = { 'functions_return': [], 'functions_do_not_return': [] } if self._updated_nonreturning_functions is not None: all_func_addrs = self._updated_nonreturning_functions # Convert addresses to objects all_functions = [ self.kb....
<SYSTEM_TASK:> Iteratively analyze function features until a fixed point is reached. <END_TASK> <USER_TASK:> Description: def _iteratively_analyze_function_features(self, all_funcs_completed=False): """ Iteratively analyze function features until a fixed point is reached. :return: the "changes"...
changes = { 'functions_do_not_return': set(), 'functions_return': set() } while True: new_changes = self._analyze_function_features(all_funcs_completed=all_funcs_completed) changes['functions_do_not_return'] |= set(new_changes['functions_do_not...
<SYSTEM_TASK:> Normalize the CFG, making sure that there are no overlapping basic blocks. <END_TASK> <USER_TASK:> Description: def normalize(self): """ Normalize the CFG, making sure that there are no overlapping basic blocks. Note that this method will not alter transition graphs of each funct...
graph = self.graph smallest_nodes = { } # indexed by end address of the node end_addresses_to_nodes = defaultdict(set) for n in graph.nodes(): if n.is_simprocedure: continue end_addr = n.addr + n.size key = (end_addr, n.callstack_k...
<SYSTEM_TASK:> From job manager, remove all functions of which we have finished analysis. <END_TASK> <USER_TASK:> Description: def _cleanup_analysis_jobs(self, finished_func_addrs=None): """ From job manager, remove all functions of which we have finished analysis. :param list or None finished_...
if finished_func_addrs is None: finished_func_addrs = self._get_finished_functions() for func_addr in finished_func_addrs: if func_addr in self._jobs_to_analyze_per_function: del self._jobs_to_analyze_per_function[func_addr]
<SYSTEM_TASK:> Fill in self._completed_functions list and clean up job manager. <END_TASK> <USER_TASK:> Description: def _make_completed_functions(self): """ Fill in self._completed_functions list and clean up job manager. :return: None """
finished = self._get_finished_functions() for func_addr in finished: self._completed_functions.add(func_addr) self._cleanup_analysis_jobs(finished_func_addrs=finished)
<SYSTEM_TASK:> Convert an address to a Function object, and store the mapping in a dict. If the block is known to be part of a <END_TASK> <USER_TASK:> Description: def _addr_to_function(self, addr, blockaddr_to_function, known_functions): """ Convert an address to a Function object, and store the mappin...
if addr in blockaddr_to_function: f = blockaddr_to_function[addr] else: is_syscall = self.project.simos.is_syscall_addr(addr) n = self.model.get_any_node(addr, is_syscall=is_syscall) if n is None: node = addr else: node = self._to_snippet(n)...
<SYSTEM_TASK:> Check if the block is a no-op block by checking VEX statements. <END_TASK> <USER_TASK:> Description: def _is_noop_block(arch, block): """ Check if the block is a no-op block by checking VEX statements. :param block: The VEX block instance. :return: True if the entire bloc...
if arch.name == "MIPS32": if arch.memory_endness == "Iend_BE": MIPS32_BE_NOOPS = { b"\x00\x20\x08\x25", # move $at, $at } insns = set(block.bytes[i:i+4] for i in range(0, block.size, 4)) if MIPS32_BE_NOOPS.issuper...
<SYSTEM_TASK:> Check if the instruction does nothing. <END_TASK> <USER_TASK:> Description: def _is_noop_insn(insn): """ Check if the instruction does nothing. :param insn: The capstone insn object. :return: True if the instruction does no-op, False otherwise. """
if insn.insn_name() == 'nop': # nops return True if insn.insn_name() == 'lea': # lea reg, [reg + 0] op0, op1 = insn.operands if op0.type == 1 and op1.type == 3: # reg and mem if op0.reg == op1.mem.base and op1....
<SYSTEM_TASK:> Calculate the total size of leading nop instructions. <END_TASK> <USER_TASK:> Description: def _get_nop_length(cls, insns): """ Calculate the total size of leading nop instructions. :param insns: A list of capstone insn objects. :return: Number of bytes of leading nop ins...
nop_length = 0 if insns and cls._is_noop_insn(insns[0]): # see where those nop instructions terminate for insn in insns: if cls._is_noop_insn(insn): nop_length += insn.size else: break return nop_...
<SYSTEM_TASK:> Lift a basic block of code. Will use the base state as a source of bytes if possible. <END_TASK> <USER_TASK:> Description: def _lift(self, *args, **kwargs): """ Lift a basic block of code. Will use the base state as a source of bytes if possible. """
if 'backup_state' not in kwargs: kwargs['backup_state'] = self._base_state return self.project.factory.block(*args, **kwargs)
<SYSTEM_TASK:> Checks if MIPS32 and calls MIPS32 check, otherwise false <END_TASK> <USER_TASK:> Description: def _resolve_indirect_jump_timelessly(self, addr, block, func_addr, jumpkind): """ Checks if MIPS32 and calls MIPS32 check, otherwise false :param int addr: irsb address :param p...
if block.statements is None: block = self.project.factory.block(block.addr, size=block.size).vex for res in self.timeless_indirect_jump_resolvers: if res.filter(self, addr, func_addr, block, jumpkind): r, resolved_targets = res.resolve(self, addr, func_addr, bl...
<SYSTEM_TASK:> Resolve all unresolved indirect jumps found in previous scanning. <END_TASK> <USER_TASK:> Description: def _process_unresolved_indirect_jumps(self): """ Resolve all unresolved indirect jumps found in previous scanning. Currently we support resolving the following types of indirec...
l.info("%d indirect jumps to resolve.", len(self._indirect_jumps_to_resolve)) all_targets = set() for idx, jump in enumerate(self._indirect_jumps_to_resolve): # type:int,IndirectJump if self._low_priority: self._release_gil(idx, 20, 0.0001) all_targets...
<SYSTEM_TASK:> Resolve a given indirect jump. <END_TASK> <USER_TASK:> Description: def _process_one_indirect_jump(self, jump): """ Resolve a given indirect jump. :param IndirectJump jump: The IndirectJump instance. :return: A set of resolved indirect jump targets (ints). ...
resolved = False resolved_by = None targets = None block = self._lift(jump.addr, opt_level=1) for resolver in self.indirect_jump_resolvers: resolver.base_state = self._base_state if not resolver.filter(self, jump.addr, jump.func_addr, block, jump.jump...
<SYSTEM_TASK:> Parse a memory load VEX statement and get the jump target addresses. <END_TASK> <USER_TASK:> Description: def _parse_load_statement(load_stmt, state): """ Parse a memory load VEX statement and get the jump target addresses. :param load_stmt: The VEX statement for loading the ju...
# The jump table address is stored in a tmp. In this case, we find the jump-target loading tmp. load_addr_tmp = None if isinstance(load_stmt, pyvex.IRStmt.WrTmp): if type(load_stmt.data.addr) is pyvex.IRExpr.RdTmp: load_addr_tmp = load_stmt.data.addr.tmp ...
<SYSTEM_TASK:> Checks which segment that the address `addr` should belong to, and, returns the offset of that segment. <END_TASK> <USER_TASK:> Description: def _search(self, addr): """ Checks which segment that the address `addr` should belong to, and, returns the offset of that segment. Note th...
start = 0 end = len(self._list) while start != end: mid = (start + end) // 2 segment = self._list[mid] if addr < segment.start: end = mid elif addr >= segment.end: start = mid + 1 else: ...
<SYSTEM_TASK:> Returns a string representation of the segments that form this SegmentList <END_TASK> <USER_TASK:> Description: def _dbg_output(self): """ Returns a string representation of the segments that form this SegmentList :return: String representation of contents :rtype: str ...
s = "[" lst = [] for segment in self._list: lst.append(repr(segment)) s += ", ".join(lst) s += "]" return s
<SYSTEM_TASK:> Iterates over list checking segments with same sort do not overlap <END_TASK> <USER_TASK:> Description: def _debug_check(self): """ Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort """
# old_start = 0 old_end = 0 old_sort = "" for segment in self._list: if segment.start <= old_end and segment.sort == old_sort: raise AngrCFGError("Error in SegmentList: blocks are not merged") # old_start = start old_end = segment.end ...
<SYSTEM_TASK:> Returns the next free position with respect to an address, including that address itself <END_TASK> <USER_TASK:> Description: def next_free_pos(self, address): """ Returns the next free position with respect to an address, including that address itself :param address: The address...
idx = self._search(address) if idx < len(self._list) and self._list[idx].start <= address < self._list[idx].end: # Occupied i = idx while i + 1 < len(self._list) and self._list[i].end == self._list[i + 1].start: i += 1 if i == len(self._l...
<SYSTEM_TASK:> Returns the address of the next occupied block whose sort is not one of the specified ones. <END_TASK> <USER_TASK:> Description: def next_pos_with_sort_not_in(self, address, sorts, max_distance=None): """ Returns the address of the next occupied block whose sort is not one of the specifie...
list_length = len(self._list) idx = self._search(address) if idx < list_length: # Occupied block = self._list[idx] if max_distance is not None and address + max_distance < block.start: return None if block.start <= address < bl...
<SYSTEM_TASK:> Check if an address belongs to any segment <END_TASK> <USER_TASK:> Description: def is_occupied(self, address): """ Check if an address belongs to any segment :param address: The address to check :return: True if this address belongs to a segment, False otherwise ...
idx = self._search(address) if len(self._list) <= idx: return False if self._list[idx].start <= address < self._list[idx].end: return True if idx > 0 and address < self._list[idx - 1].end: # TODO: It seems that this branch is never reached. Should it...
<SYSTEM_TASK:> Check if an address belongs to any segment, and if yes, returns the sort of the segment <END_TASK> <USER_TASK:> Description: def occupied_by_sort(self, address): """ Check if an address belongs to any segment, and if yes, returns the sort of the segment :param int address: The ad...
idx = self._search(address) if len(self._list) <= idx: return None if self._list[idx].start <= address < self._list[idx].end: return self._list[idx].sort if idx > 0 and address < self._list[idx - 1].end: # TODO: It seems that this branch is never rea...
<SYSTEM_TASK:> Make a copy of this SimLibrary, allowing it to be mutated without affecting the global version. <END_TASK> <USER_TASK:> Description: def copy(self): """ Make a copy of this SimLibrary, allowing it to be mutated without affecting the global version. :return: A new SimLibrary ob...
o = SimLibrary() o.procedures = dict(self.procedures) o.non_returning = set(self.non_returning) o.prototypes = dict(self.prototypes) o.default_ccs = dict(self.default_ccs) o.names = list(self.names) return o
<SYSTEM_TASK:> Set some common names of this library by which it may be referred during linking <END_TASK> <USER_TASK:> Description: def set_library_names(self, *names): """ Set some common names of this library by which it may be referred during linking :param names: Any number of string lib...
for name in names: self.names.append(name) SIM_LIBRARIES[name] = self
<SYSTEM_TASK:> Set the default calling convention used for this library under a given architecture <END_TASK> <USER_TASK:> Description: def set_default_cc(self, arch_name, cc_cls): """ Set the default calling convention used for this library under a given architecture :param arch_name: The st...
arch_name = archinfo.arch_from_id(arch_name).name self.default_ccs[arch_name] = cc_cls
<SYSTEM_TASK:> Set the prototype of a function in the form of a C-style function declaration. <END_TASK> <USER_TASK:> Description: def set_c_prototype(self, c_decl): """ Set the prototype of a function in the form of a C-style function declaration. :param str c_decl: The C-style declaration of ...
parsed = parse_file(c_decl) parsed_decl = parsed[0] if not parsed_decl: raise ValueError('Cannot parse the function prototype.') func_name, func_proto = next(iter(parsed_decl.items())) self.set_prototype(func_name, func_proto) return func_name, func_proto
<SYSTEM_TASK:> Add a function implementation fo the library. <END_TASK> <USER_TASK:> Description: def add(self, name, proc_cls, **kwargs): """ Add a function implementation fo the library. :param name: The name of the function as a string :param proc_cls: The implementation of...
self.procedures[name] = proc_cls(display_name=name, **kwargs)
<SYSTEM_TASK:> Batch-add function implementations to the library. <END_TASK> <USER_TASK:> Description: def add_all_from_dict(self, dictionary, **kwargs): """ Batch-add function implementations to the library. :param dictionary: A mapping from name to procedure class, i.e. the first two argumen...
for name, procedure in dictionary.items(): self.add(name, procedure, **kwargs)
<SYSTEM_TASK:> Add some duplicate names for a given function. The original function's implementation must already be <END_TASK> <USER_TASK:> Description: def add_alias(self, name, *alt_names): """ Add some duplicate names for a given function. The original function's implementation must already be ...
old_procedure = self.procedures[name] for alt in alt_names: new_procedure = copy.deepcopy(old_procedure) new_procedure.display_name = alt self.procedures[alt] = new_procedure
<SYSTEM_TASK:> Get an implementation of the given function specialized for the given arch, or a stub procedure if none exists. <END_TASK> <USER_TASK:> Description: def get(self, name, arch): """ Get an implementation of the given function specialized for the given arch, or a stub procedure if none exist...
if type(arch) is str: arch = archinfo.arch_from_id(arch) if name in self.procedures: proc = copy.deepcopy(self.procedures[name]) self._apply_metadata(proc, arch) return proc else: return self.get_stub(name, arch)
<SYSTEM_TASK:> Get a stub procedure for the given function, regardless of if a real implementation is available. This will <END_TASK> <USER_TASK:> Description: def get_stub(self, name, arch): """ Get a stub procedure for the given function, regardless of if a real implementation is available. This will ...
proc = self.fallback_proc(display_name=name, is_stub=True) self._apply_metadata(proc, arch) return proc
<SYSTEM_TASK:> Check if a function has either an implementation or any metadata associated with it <END_TASK> <USER_TASK:> Description: def has_metadata(self, name): """ Check if a function has either an implementation or any metadata associated with it :param name: The name of the function ...
return self.has_implementation(name) or \ name in self.non_returning or \ name in self.prototypes
<SYSTEM_TASK:> Associate a syscall number with the name of a function present in the underlying SimLibrary <END_TASK> <USER_TASK:> Description: def add_number_mapping(self, abi, number, name): """ Associate a syscall number with the name of a function present in the underlying SimLibrary :param...
self.syscall_number_mapping[abi][number] = name self.syscall_name_mapping[abi][name] = number
<SYSTEM_TASK:> Batch-associate syscall numbers with names of functions present in the underlying SimLibrary <END_TASK> <USER_TASK:> Description: def add_number_mapping_from_dict(self, abi, mapping): """ Batch-associate syscall numbers with names of functions present in the underlying SimLibrary ...
self.syscall_number_mapping[abi].update(mapping) self.syscall_name_mapping[abi].update(dict(reversed(i) for i in mapping.items()))
<SYSTEM_TASK:> Returns the Claripy expression of a VEX temp value. <END_TASK> <USER_TASK:> Description: def tmp_expr(self, tmp): """ Returns the Claripy expression of a VEX temp value. :param tmp: the number of the tmp :param simplify: simplify the tmp before returning it :retur...
self.state._inspect('tmp_read', BP_BEFORE, tmp_read_num=tmp) try: v = self.temps[tmp] if v is None: raise SimValueError('VEX temp variable %d does not exist. This is usually the result of an incorrect ' 'slicing.' % tmp) ...
<SYSTEM_TASK:> Stores a Claripy expression in a VEX temp value. <END_TASK> <USER_TASK:> Description: def store_tmp(self, tmp, content, reg_deps=None, tmp_deps=None, deps=None): """ Stores a Claripy expression in a VEX temp value. If in symbolic mode, this involves adding a constraint for the tmp...
self.state._inspect('tmp_write', BP_BEFORE, tmp_write_num=tmp, tmp_write_expr=content) tmp = self.state._inspect_getattr('tmp_write_num', tmp) content = self.state._inspect_getattr('tmp_write_expr', content) if o.SYMBOLIC_TEMPS not in self.state.options: # Non-symbolic ...
<SYSTEM_TASK:> Takes a path and returns a simple absolute path as a list of directories from the root <END_TASK> <USER_TASK:> Description: def _normalize_path(self, path): """ Takes a path and returns a simple absolute path as a list of directories from the root """
if type(path) is str: path = path.encode() path = path.split(b'\0')[0] if path[0:1] != self.pathsep: path = self.cwd + self.pathsep + path keys = path.split(self.pathsep) i = 0 while i < len(keys): if keys[i] == b'': k...
<SYSTEM_TASK:> Changes the current directory to the given path <END_TASK> <USER_TASK:> Description: def chdir(self, path): """ Changes the current directory to the given path """
self.cwd = self._join_chunks(self._normalize_path(path))
<SYSTEM_TASK:> Get a file from the filesystem. Returns a SimFile or None. <END_TASK> <USER_TASK:> Description: def get(self, path): """ Get a file from the filesystem. Returns a SimFile or None. """
mountpoint, chunks = self.get_mountpoint(path) if mountpoint is None: return self._files.get(self._join_chunks(chunks)) else: return mountpoint.get(chunks)
<SYSTEM_TASK:> Insert a file into the filesystem. Returns whether the operation was successful. <END_TASK> <USER_TASK:> Description: def insert(self, path, simfile): """ Insert a file into the filesystem. Returns whether the operation was successful. """
if self.state is not None: simfile.set_state(self.state) mountpoint, chunks = self.get_mountpoint(path) if mountpoint is None: self._files[self._join_chunks(chunks)] = simfile return True else: return mountpoint.insert(chunks, simfile)
<SYSTEM_TASK:> Remove a file from the filesystem. Returns whether the operation was successful. <END_TASK> <USER_TASK:> Description: def delete(self, path): """ Remove a file from the filesystem. Returns whether the operation was successful. This will add a ``fs_unlink`` event with the path of ...
mountpoint, chunks = self.get_mountpoint(path) apath = self._join_chunks(chunks) if mountpoint is None: try: simfile = self._files.pop(apath) except KeyError: return False else: self.state.history.add_event('fs...
<SYSTEM_TASK:> Add a mountpoint to the filesystem. <END_TASK> <USER_TASK:> Description: def mount(self, path, mount): """ Add a mountpoint to the filesystem. """
self._mountpoints[self._join_chunks(self._normalize_path(path))] = mount
<SYSTEM_TASK:> Remove a mountpoint from the filesystem. <END_TASK> <USER_TASK:> Description: def unmount(self, path): """ Remove a mountpoint from the filesystem. """
del self._mountpoints[self._join_chunks(self._normalize_path(path))]
<SYSTEM_TASK:> Look up the mountpoint servicing the given path. <END_TASK> <USER_TASK:> Description: def get_mountpoint(self, path): """ Look up the mountpoint servicing the given path. :return: A tuple of the mount and a list of path elements traversing from the mountpoint to the specified fil...
path_chunks = self._normalize_path(path) for i in range(len(path_chunks) - 1, -1, -1): partial_path = self._join_chunks(path_chunks[:-i]) if partial_path in self._mountpoints: mountpoint = self._mountpoints[partial_path] if mountpoint is None: ...
<SYSTEM_TASK:> Store in native memory. <END_TASK> <USER_TASK:> Description: def _store_in_native_memory(self, data, data_type, addr=None): """ Store in native memory. :param data: Either a single value or a list. Lists get interpreted as an array. :param d...
# check if addr is symbolic if addr is not None and self.state.solver.symbolic(addr): raise NotImplementedError('Symbolic addresses are not supported.') # lookup native size of the type type_size = ArchSoot.sizeof[data_type] native_memory_endness = self.state.arch.me...
<SYSTEM_TASK:> Load from native memory. <END_TASK> <USER_TASK:> Description: def _load_from_native_memory(self, addr, data_type=None, data_size=None, no_of_elements=1, return_as_list=False): """ Load from native memory. :param addr: Native load address...
# check if addr is symbolic if addr is not None and self.state.solver.symbolic(addr): raise NotImplementedError('Symbolic addresses are not supported.') # if data size is not set, derive it from the type if not data_size: if data_type: data_size =...
<SYSTEM_TASK:> Load zero terminated UTF-8 string from native memory. <END_TASK> <USER_TASK:> Description: def _load_string_from_native_memory(self, addr_): """ Load zero terminated UTF-8 string from native memory. :param addr_: Native load address. :return: Loaded string. "...
# check if addr is symbolic if self.state.solver.symbolic(addr_): l.error("Loading strings from symbolic addresses is not implemented. " "Continue execution with an empty string.") return "" addr = self.state.solver.eval(addr_) # load chars o...
<SYSTEM_TASK:> Store given string UTF-8 encoded and zero terminated in native memory. <END_TASK> <USER_TASK:> Description: def _store_string_in_native_memory(self, string, addr=None): """ Store given string UTF-8 encoded and zero terminated in native memory. :param str string: String :...
if addr is None: addr = self._allocate_native_memory(size=len(string)+1) else: # check if addr is symbolic if self.state.solver.symbolic(addr): l.error("Storing strings at symbolic addresses is not implemented. " "Continue exec...
<SYSTEM_TASK:> In Java, all array indices are represented by a 32 bit integer and <END_TASK> <USER_TASK:> Description: def _normalize_array_idx(self, idx): """ In Java, all array indices are represented by a 32 bit integer and consequently we are using in the Soot engine a 32bit bitvector for th...
if isinstance(idx, SimActionObject): idx = idx.to_claripy() if self.arch.memory_endness == "Iend_LE": return idx.reversed.get_bytes(index=0, size=4).reversed else: return idx.get_bytes(index=0, size=4)
<SYSTEM_TASK:> Given the target `target`, apply the hooks given as keyword arguments to it. <END_TASK> <USER_TASK:> Description: def install_hooks(target, **hooks): """ Given the target `target`, apply the hooks given as keyword arguments to it. If any targeted method has already been hooked, th...
for name, hook in hooks.items(): func = getattr(target, name) if not isinstance(func, HookedMethod): func = HookedMethod(func) setattr(target, name, func) func.pending.append(hook)
<SYSTEM_TASK:> Remove the given hooks from the given target. <END_TASK> <USER_TASK:> Description: def remove_hooks(target, **hooks): """ Remove the given hooks from the given target. :param target: The object from which to remove hooks. If all hooks are removed from a given method, the ...
for name, hook in hooks.items(): hooked = getattr(target, name) if hook in hooked.pending: try: hooked.pending.remove(hook) except ValueError as e: raise ValueError("%s is not hooked by %s" % (target, hook)) from e ...
<SYSTEM_TASK:> Reset the internal node traversal state. Must be called prior to visiting future nodes. <END_TASK> <USER_TASK:> Description: def reset(self): """ Reset the internal node traversal state. Must be called prior to visiting future nodes. :return: None """
self._sorted_nodes.clear() self._node_to_index.clear() self._reached_fixedpoint.clear() for i, n in enumerate(self.sort_nodes()): self._node_to_index[n] = i self._sorted_nodes.add(n)
<SYSTEM_TASK:> Returns all successors to the specific node. <END_TASK> <USER_TASK:> Description: def all_successors(self, node, skip_reached_fixedpoint=False): """ Returns all successors to the specific node. :param node: A node in the graph. :return: A set of nodes that are all suc...
successors = set() stack = [ node ] while stack: n = stack.pop() successors.add(n) stack.extend(succ for succ in self.successors(n) if succ not in successors and (not skip_reached_fixedpoint or succ not i...
<SYSTEM_TASK:> Revisit a node in the future. As a result, the successors to this node will be revisited as well. <END_TASK> <USER_TASK:> Description: def revisit(self, node, include_self=True): """ Revisit a node in the future. As a result, the successors to this node will be revisited as well. ...
successors = self.successors(node) #, skip_reached_fixedpoint=True) if include_self: self._sorted_nodes.add(node) for succ in successors: self._sorted_nodes.add(succ) # reorder it self._sorted_nodes = OrderedSet(sorted(self._sorted_nodes, key=lambda n...
<SYSTEM_TASK:> Add the input state to all successors of the given node. <END_TASK> <USER_TASK:> Description: def _add_input_state(self, node, input_state): """ Add the input state to all successors of the given node. :param node: The node whose successors' input states will be touched. ...
successors = self._graph_visitor.successors(node) for succ in successors: if succ in self._state_map: self._state_map[succ] = self._merge_states(succ, *([ self._state_map[succ], input_state ])) else: self._state_map[succ] = input_state
<SYSTEM_TASK:> Get the input abstract state for this node, and remove it from the state map. <END_TASK> <USER_TASK:> Description: def _pop_input_state(self, node): """ Get the input abstract state for this node, and remove it from the state map. :param node: The node in graph. :return: ...
if node in self._state_map: return self._state_map.pop(node) return None
<SYSTEM_TASK:> Get abstract states for all predecessors of the node, merge them, and return the merged state. <END_TASK> <USER_TASK:> Description: def _merge_state_from_predecessors(self, node): """ Get abstract states for all predecessors of the node, merge them, and return the merged state. :...
preds = self._graph_visitor.predecessors(node) states = [ self._state_map[n] for n in preds if n in self._state_map ] if not states: return None return reduce(lambda s0, s1: self._merge_states(node, s0, s1), states[1:], states[0])
<SYSTEM_TASK:> Insert a new job into the job queue. If the job queue is ordered, this job will be inserted at the correct <END_TASK> <USER_TASK:> Description: def _insert_job(self, job): """ Insert a new job into the job queue. If the job queue is ordered, this job will be inserted at the correct ...
key = self._job_key(job) if self._allow_merging: if key in self._job_map: job_info = self._job_map[key] # decide if we want to trigger a widening # if not, we'll simply do the merge # TODO: save all previous jobs for the sak...
<SYSTEM_TASK:> Return the job currently at position `pos`, but still keep it in the job queue. An IndexError will be raised <END_TASK> <USER_TASK:> Description: def _peek_job(self, pos): """ Return the job currently at position `pos`, but still keep it in the job queue. An IndexError will be raised ...
if pos < len(self._job_info_queue): return self._job_info_queue[pos].job raise IndexError()
<SYSTEM_TASK:> Insert an element into a sorted list, and keep the list sorted. <END_TASK> <USER_TASK:> Description: def _binary_insert(lst, elem, key, lo=0, hi=None): """ Insert an element into a sorted list, and keep the list sorted. The major difference from bisect.bisect_left is that this fu...
if lo < 0: raise ValueError("lo must be a non-negative number") if hi is None: hi = len(lst) while lo < hi: mid = (lo + hi) // 2 if key(lst[mid]) < key(elem): lo = mid + 1 else: hi = mid lst....
<SYSTEM_TASK:> Merge this SimMemory with the other SimMemory <END_TASK> <USER_TASK:> Description: def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument """ Merge this SimMemory with the other SimMemory """
changed_bytes = self._changes_to_merge(others) l.info("Merging %d bytes", len(changed_bytes)) l.info("... %s has changed bytes %s", self.id, changed_bytes) self.read_strategies = self._merge_strategies(self.read_strategies, *[ o.read_strategies for o in others ]) ...
<SYSTEM_TASK:> Replaces `length` bytes starting at `addr` with a symbolic variable named name. Adds a constraint equaling that <END_TASK> <USER_TASK:> Description: def make_symbolic(self, name, addr, length=None): """ Replaces `length` bytes starting at `addr` with a symbolic variable named name. Adds a...
l.debug("making %s bytes symbolic", length) if isinstance(addr, str): addr, length = self.state.arch.registers[addr] else: if length is None: raise Exception("Unspecified length!") r = self.load(addr, length) v = self.get_unconstrained_...
<SYSTEM_TASK:> Applies concretization strategies on the address until one of them succeeds. <END_TASK> <USER_TASK:> Description: def _apply_concretization_strategies(self, addr, strategies, action): """ Applies concretization strategies on the address until one of them succeeds. """
# we try all the strategies in order for s in strategies: # first, we trigger the SimInspect breakpoint and give it a chance to intervene e = addr self.state._inspect( 'address_concretization', BP_BEFORE, address_concretization_strategy=s, ...
<SYSTEM_TASK:> Concretizes an address meant for writing. <END_TASK> <USER_TASK:> Description: def concretize_write_addr(self, addr, strategies=None): """ Concretizes an address meant for writing. :param addr: An expression for the address. :param strategies: A li...
if isinstance(addr, int): return [ addr ] elif not self.state.solver.symbolic(addr): return [ self.state.solver.eval(addr) ] strategies = self.write_strategies if strategies is None else strategies return self._apply_concretization_strategies(addr, strategies, ...
<SYSTEM_TASK:> Concretizes an address meant for reading. <END_TASK> <USER_TASK:> Description: def concretize_read_addr(self, addr, strategies=None): """ Concretizes an address meant for reading. :param addr: An expression for the address. :param strategies: A lis...
if isinstance(addr, int): return [ addr ] elif not self.state.solver.symbolic(addr): return [ self.state.solver.eval(addr) ] strategies = self.read_strategies if strategies is None else strategies return self._apply_concretization_strategies(addr, strategies, '...
<SYSTEM_TASK:> Retrieve the permissions of the page at address `addr`. <END_TASK> <USER_TASK:> Description: def permissions(self, addr, permissions=None): """ Retrieve the permissions of the page at address `addr`. :param addr: address to get the page permissions :param permissio...
out = self.mem.permissions(addr, permissions) # if unicorn is in play and we've marked a page writable, it must be uncached if permissions is not None and self.state.solver.is_true(permissions & 2 == 2): if self.state.has_plugin('unicorn'): self.state.unicorn.uncache...
<SYSTEM_TASK:> Perform execution using any applicable engine. Enumerate the current engines and use the <END_TASK> <USER_TASK:> Description: def successors(self, *args, **kwargs): """ Perform execution using any applicable engine. Enumerate the current engines and use the first one that works. R...
return self.project.engines.successors(*args, **kwargs)
<SYSTEM_TASK:> Returns a state object initialized to the start of a given function, as if it were called with given parameters. <END_TASK> <USER_TASK:> Description: def call_state(self, addr, *args, **kwargs): """ Returns a state object initialized to the start of a given function, as if it were called ...
return self.project.simos.state_call(addr, *args, **kwargs)
<SYSTEM_TASK:> Constructs a new simulation manager. <END_TASK> <USER_TASK:> Description: def simulation_manager(self, thing=None, **kwargs): """ Constructs a new simulation manager. :param thing: Optional - What to put in the new SimulationManager's active stash (either a SimState or ...
if thing is None: thing = [ self.entry_state() ] elif isinstance(thing, (list, tuple)): if any(not isinstance(val, SimState) for val in thing): raise AngrError("Bad type to initialize SimulationManager") elif isinstance(thing, SimState): thing...
<SYSTEM_TASK:> A Callable is a representation of a function in the binary that can be interacted with like a native python <END_TASK> <USER_TASK:> Description: def callable(self, addr, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None): """ A Callable is a representation of a f...
return Callable(self.project, addr=addr, concrete_only=concrete_only, perform_merge=perform_merge, base_state=base_state, toc=toc, cc=cc)
<SYSTEM_TASK:> An iterator of all local blocks in the current function. <END_TASK> <USER_TASK:> Description: def blocks(self): """ An iterator of all local blocks in the current function. :return: angr.lifter.Block instances. """
for block_addr, block in self._local_blocks.items(): try: yield self._get_block(block_addr, size=block.size, byte_string=block.bytestr if isinstance(block, BlockNode) else None) except (SimEngineError, SimMemoryError): ...
<SYSTEM_TASK:> All of the operations that are done by this functions. <END_TASK> <USER_TASK:> Description: def operations(self): """ All of the operations that are done by this functions. """
return [op for block in self.blocks for op in block.vex.operations]
<SYSTEM_TASK:> All of the constants that are used by this functions's code. <END_TASK> <USER_TASK:> Description: def code_constants(self): """ All of the constants that are used by this functions's code. """
# TODO: remove link register values return [const.value for block in self.blocks for const in block.vex.constants]
<SYSTEM_TASK:> All of the constant string references used by this function. <END_TASK> <USER_TASK:> Description: def string_references(self, minimum_length=2, vex_only=False): """ All of the constant string references used by this function. :param minimum_length: The minimum length of strings ...
strings = [] memory = self._project.loader.memory # get known instruction addresses and call targets # these addresses cannot be string references, but show up frequently in the runtime values known_executable_addresses = set() for block in self.blocks: know...
<SYSTEM_TASK:> Tries to find all runtime values of this function which do not come from inputs. <END_TASK> <USER_TASK:> Description: def local_runtime_values(self): """ Tries to find all runtime values of this function which do not come from inputs. These values are generated by starting from a ...
constants = set() if not self._project.loader.main_object.contains_addr(self.addr): return constants # FIXME the old way was better for architectures like mips, but we need the initial irsb # reanalyze function with a new initial state (use persistent registers) # ...
<SYSTEM_TASK:> Add a custom jumpout site. <END_TASK> <USER_TASK:> Description: def add_jumpout_site(self, node): """ Add a custom jumpout site. :param node: The address of the basic block that control flow leaves during this transition. :return: None """
self._register_nodes(True, node) self._jumpout_sites.add(node) self._add_endpoint(node, 'transition')
<SYSTEM_TASK:> Add a custom retout site. <END_TASK> <USER_TASK:> Description: def add_retout_site(self, node): """ Add a custom retout site. Retout (returning to outside of the function) sites are very rare. It mostly occurs during CFG recovery when we incorrectly identify the beginning...
self._register_nodes(True, node) self._retout_sites.add(node) self._add_endpoint(node, 'return')
<SYSTEM_TASK:> Determine the most suitable name of the function. <END_TASK> <USER_TASK:> Description: def _get_initial_name(self): """ Determine the most suitable name of the function. :return: The initial function name. :rtype: string """
name = None addr = self.addr # Try to get a name from existing labels if self._function_manager is not None: if addr in self._function_manager._kb.labels: name = self._function_manager._kb.labels[addr] # try to get the name from a hook if n...
<SYSTEM_TASK:> Determine the name of the binary where this function is. <END_TASK> <USER_TASK:> Description: def _get_initial_binary_name(self): """ Determine the name of the binary where this function is. :return: None """
binary_name = None # if this function is a simprocedure but not a syscall, use its library name as # its binary name # if it is a syscall, fall back to use self.binary.binary which explicitly says cle##kernel if self.project and self.is_simprocedure and not self.is_syscall: ...
<SYSTEM_TASK:> Registers an edge between basic blocks in this function's transition graph. <END_TASK> <USER_TASK:> Description: def _transit_to(self, from_node, to_node, outside=False, ins_addr=None, stmt_idx=None): """ Registers an edge between basic blocks in this function's transition graph. ...
if outside: self._register_nodes(True, from_node) if to_node is not None: self._register_nodes(False, to_node) self._jumpout_sites.add(from_node) else: if to_node is not None: self._register_nodes(True, from_node, to_node...
<SYSTEM_TASK:> Registers an edge between the caller basic block and callee function. <END_TASK> <USER_TASK:> Description: def _call_to(self, from_node, to_func, ret_node, stmt_idx=None, ins_addr=None, return_to_outside=False): """ Registers an edge between the caller basic block and callee function. ...
self._register_nodes(True, from_node) if to_func.is_syscall: self.transition_graph.add_edge(from_node, to_func, type='syscall', stmt_idx=stmt_idx, ins_addr=ins_addr) else: self.transition_graph.add_edge(from_node, to_func, type='call', stmt_idx=stmt_idx, ins_addr=ins_a...
<SYSTEM_TASK:> Registers a basic block as a site for control flow to return from this function. <END_TASK> <USER_TASK:> Description: def _add_return_site(self, return_site): """ Registers a basic block as a site for control flow to return from this function. :param CodeNode return_site: The...
self._register_nodes(True, return_site) self._ret_sites.add(return_site) # A return site must be an endpoint of the function - you cannot continue execution of the current function # after returning self._add_endpoint(return_site, 'return')
<SYSTEM_TASK:> Registers a basic block as calling a function and returning somewhere. <END_TASK> <USER_TASK:> Description: def _add_call_site(self, call_site_addr, call_target_addr, retn_addr): """ Registers a basic block as calling a function and returning somewhere. :param call_site_addr: ...
self._call_sites[call_site_addr] = (call_target_addr, retn_addr)
<SYSTEM_TASK:> Iterate through all call edges in transition graph. For each call a non-returning function, mark the source <END_TASK> <USER_TASK:> Description: def mark_nonreturning_calls_endpoints(self): """ Iterate through all call edges in transition graph. For each call a non-returning function, mar...
for src, dst, data in self.transition_graph.edges(data=True): if 'type' in data and data['type'] == 'call': func_addr = dst.addr if func_addr in self._function_manager: function = self._function_manager[func_addr] if function....
<SYSTEM_TASK:> Return a local transition graph that only contain nodes in current function. <END_TASK> <USER_TASK:> Description: def graph(self): """ Return a local transition graph that only contain nodes in current function. """
if self._local_transition_graph is not None: return self._local_transition_graph g = networkx.DiGraph() if self.startpoint is not None: g.add_node(self.startpoint) for block in self._local_blocks.values(): g.add_node(block) for src, dst, dat...
<SYSTEM_TASK:> Generate a sub control flow graph of instruction addresses based on self.graph <END_TASK> <USER_TASK:> Description: def subgraph(self, ins_addrs): """ Generate a sub control flow graph of instruction addresses based on self.graph :param iterable ins_addrs: A collection of instruc...
# find all basic blocks that include those instructions blocks = [] block_addr_to_insns = {} for b in self._local_blocks.values(): # TODO: should I call get_blocks? block = self._get_block(b.addr, size=b.size, byte_string=b.bytestr) common_insns = s...
<SYSTEM_TASK:> Get the size of the instruction specified by `insn_addr`. <END_TASK> <USER_TASK:> Description: def instruction_size(self, insn_addr): """ Get the size of the instruction specified by `insn_addr`. :param int insn_addr: Address of the instruction :return: Size of the instru...
for b in self.blocks: block = self._get_block(b.addr, size=b.size, byte_string=b.bytestr) if insn_addr in block.instruction_addrs: index = block.instruction_addrs.index(insn_addr) if index == len(block.instruction_addrs) - 1: # the ve...
<SYSTEM_TASK:> Draw the graph and save it to a PNG file. <END_TASK> <USER_TASK:> Description: def dbg_draw(self, filename): """ Draw the graph and save it to a PNG file. """
import matplotlib.pyplot as pyplot # pylint: disable=import-error from networkx.drawing.nx_agraph import graphviz_layout # pylint: disable=import-error tmp_graph = networkx.DiGraph() for from_block, to_block in self.transition_graph.edges(): node_a = "%#08x" % from_block....
<SYSTEM_TASK:> Registers a register offset as being used as an argument to the function. <END_TASK> <USER_TASK:> Description: def _add_argument_register(self, reg_offset): """ Registers a register offset as being used as an argument to the function. :param reg_offset: The offset of the...
if reg_offset in self._function_manager._arg_registers and \ reg_offset not in self._argument_registers: self._argument_registers.append(reg_offset)
<SYSTEM_TASK:> Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, <END_TASK> <USER_TASK:> Description: def find_declaration(self): """ Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototy...
# determine the library name if not self.is_plt: binary_name = self.binary_name if binary_name not in SIM_LIBRARIES: return else: binary_name = None # PLT entries must have the same declaration as their jump targets #...
<SYSTEM_TASK:> Reverse look-up. <END_TASK> <USER_TASK:> Description: def _rfind(lst, item): """ Reverse look-up. :param list lst: The list to look up in. :param item: The item to look for. :return: Offset of the item if found. A ValueError is raised if the item is not in the lis...
try: return dropwhile(lambda x: lst[x] != item, next(reversed(range(len(lst))))) except Exception: raise ValueError("%s not in the list" % item)