text
stringlengths
81
112k
Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str def get_function_name(s): """ Get the function name from a C-style function declaration string. :param str s: A C-style fun...
Convert a C-style function declaration string to its corresponding SimTypes-based Python representation. :param str c_decl: The C-style function declaration string. :return: A tuple of the function name, the prototype, and a string representing the ...
Use this to set the size on a chunk. When the chunk is new (such as when a free chunk is shrunk to form an allocated chunk and a remainder free chunk) it is recommended that the is_free hint be used since setting the size depends on the chunk's freeness, and vice versa. :param size: size of the...
Sets (or unsets) the flag controlling whether the previous chunk is free. :param is_free: if True, sets the previous chunk to be free; if False, sets it to be allocated def set_prev_freeness(self, is_free): """ Sets (or unsets) the flag controlling whether the previous chunk is free. ...
Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free. :returns: True if the previous chunk is free; False otherwise def is_prev_free(self): ...
Returns the size of the previous chunk, masking off what would be the flag bits if it were in the actual size field. Performs NO CHECKING to determine whether the previous chunk size is valid (for example, when the previous chunk is not free, its size cannot be determined). def prev_size(self): ...
Returns the chunk immediately following (and adjacent to) this one, if it exists. :returns: The following chunk, or None if applicable def next_chunk(self): """ Returns the chunk immediately following (and adjacent to) this one, if it exists. :returns: The following chunk, or None if ...
Returns the chunk immediately prior (and adjacent) to this one, if that chunk is free. If the prior chunk is not free, then its base cannot be located and this method raises an error. :returns: If possible, the previous chunk; otherwise, raises an error def prev_chunk(self): """ Return...
Returns the chunk following this chunk in the list of free chunks. If this chunk is not free, then it resides in no such list and this method raises an error. :returns: If possible, the forward chunk; otherwise, raises an error def fwd_chunk(self): """ Returns the chunk following this ...
Given a pointer to a user payload, return the base of the chunk associated with that payload (i.e. the chunk pointer). Returns None if ptr is null. :param ptr: a pointer to the base of a user payload in the heap :returns: a pointer to the base of the associated heap chunk, or None if ptr is nul...
Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head and all other metadata are unaltered by this function. def _find_bck(self, chunk): """ Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hen...
Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages this. Nonetheless, for now it is implemented as if an additional chunk followed the final chunk. def _set_final_freeness(self, flag): """ Sets the freedom of the final chunk. Since no pro...
Takes an allocation size as requested by the user and modifies it to be a suitable chunk size. def _make_chunk_size(self, req_size): """ Takes an allocation size as requested by the user and modifies it to be a suitable chunk size. """ size = req_size size += 2 * self._chunk_siz...
Allocate and initialize a new string in the context of the state passed. The method returns the reference to the newly allocated string :param state: angr state where we want to allocate the string :type SimState :param value: value of the string to initialize :type claripy.Str...
:param s: the string address/offset :param state: SimState :param region: memory, file, etc :param base: the base to use to interpret the number note: all numbers may start with +/- and base 16 may start with 0x :param signed: boolean, true means the result will be signed, otherw...
loads a number from addr, and returns a condition that addr must start with the prefix def _load_num_with_prefix(prefix, addr, region, state, base, signed, read_length=None): """ loads a number from addr, and returns a condition that addr must start with the prefix """ length = len(pref...
reads values from s and generates the symbolic number that it would equal the first char is either a number in the given base, or the result is 0 expression indicates whether or not it was successful def _string_to_int(s, state, region, base, signed, read_length=None): """ reads values ...
converts a symbolic char to a number in the given base returns expression, result expression is a symbolic boolean indicating whether or not it was a valid number result is the value def _char_to_val(char, base): """ converts a symbolic char to a number in the given base ...
Implement printf - based on the stored format specifier information, format the values from the arg getter function `args` into a string. :param startpos: The index of the first argument to be used by the first element of the format string :param args: A function which, given an argum...
implement scanf - extract formatted data from memory or a file according to the stored format specifiers and store them into the pointers extracted from `args`. :param startpos: The index of the first argument corresponding to the first format element :param args: A function which, gi...
Modified length specifiers: mapping between length modifiers and conversion specifiers. This generates all the possibilities, i.e. hhd, etc. def _mod_spec(self): """ Modified length specifiers: mapping between length modifiers and conversion specifiers. This generates all the possibilit...
All specifiers and their lengths. def _all_spec(self): """ All specifiers and their lengths. """ base = self._mod_spec for spec in self.basic_spec: base[spec] = self.basic_spec[spec] return base
match the string `nugget` to a format specifier. def _match_spec(self, nugget): """ match the string `nugget` to a format specifier. """ # TODO: handle positional modifiers and other similar format string tricks. all_spec = self._all_spec # iterate through nugget throwi...
Extract the actual formats from the format string `fmt`. :param list fmt: A list of format chars. :returns: a FormatString object def _get_fmt(self, fmt): """ Extract the actual formats from the format string `fmt`. :param list fmt: A list of format chars. :returns: a ...
Return the result of invoking the atoi simprocedure on `str_addr`. 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']['s...
Return the result of invoking the strlen simprocedure on `str_addr`. def _sim_strlen(self, str_addr): """ Return the result of invoking the strlen simprocedure on `str_addr`. """ from .. import SIM_PROCEDURES strlen = SIM_PROCEDURES['libc']['strlen'] return self.inline...
Parse format strings. :param fmt_idx: The index of the (pointer to the) format string in the arguments list. :returns: A FormatString object which can be used for replacing the format specifiers with arguments or for scanning into arguments. def _parse(self, fmt_idx): ...
Pre-process an AST for insertion into unicorn. :param d: the AST :param from_where: the ID of the memory region it comes from ('mem' or 'reg') :returns: the value to be inserted into Unicorn, or None def _process_value(self, d, from_where): """ Pre-process an AST for insertion ...
This callback is called when unicorn needs to access data that's not yet present in memory. def _hook_mem_unmapped(self, uc, access, address, size, value, user_data, size_extension=True): #pylint:disable=unused-argument """ This callback is called when unicorn needs to access data that's not yet presen...
setting unicorn registers def set_regs(self): ''' setting unicorn registers ''' uc = self.uc if self.state.arch.qemu_name == 'x86_64': fs = self.state.solver.eval(self.state.regs.fs) gs = self.state.solver.eval(self.state.regs.gs) self.write_msr(fs, 0xC00001...
loading registers from unicorn def get_regs(self): ''' loading registers from unicorn ''' # first, get the ignore list (in case of symbolic registers) if options.UNICORN_SYM_REGS_SUPPORT in self.state.options: highest_reg_offset, reg_size = max(self.state.arch.registers.values()) ...
check if this state might be used in unicorn (has no concrete register) def _check_registers(self, report=True): ''' check if this state might be used in unicorn (has no concrete register)''' for r in self.state.arch.uc_regs.keys(): v = getattr(self.state.regs, r) processed_v = ...
For each instruction, track its stack pointer offset and stack base pointer offset. :return: None 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_of...
Convert a VEX block to an AIL block. :param block_node: A BlockNode instance. :return: An converted AIL block. :rtype: ailment.Block def _convert(self, block_node): """ Convert a VEX block to an AIL block. :param block_node: A BlockNode instanc...
Simplify all blocks in self._blocks. :param stack_pointer_tracker: The RegisterDeltaTracker analysis instance. :return: None def _simplify_blocks(self, stack_pointer_tracker=None): """ Simplify all blocks in self._blocks. :param stack_pointer_tracker: ...
Simplify a single AIL block. :param ailment.Block ail_block: The AIL block to simplify. :param stack_pointer_tracker: The RegisterDeltaTracker analysis instance. :return: A simplified AIL block. def _simplify_block(self, ail_block, stack_pointer_tracker=None): ...
Simplify the entire function. :return: None 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, obser...
Simplify all function call statements. :return: None def _make_callsites(self, stack_pointer_tracker=None): """ Simplify all function call statements. :return: None """ # Computing reaching definitions rd = self.project.analyses.ReachingDefinitions(func=...
Link atoms (AIL expressions) in the given block to corresponding variables identified previously. :param ailment.Block block: The AIL block to work on. :return: None def _link_variables_on_block(self, block, kb): """ Link atoms (AIL expressions) in the given block to...
Link atoms (AIL expressions) in the given expression to corresponding variables identified previously. :param variable_manager: Variable manager of the function. :param ailment.Block block: AIL block. :param int stmt_idx: ID of the statement. :param stmt: The AI...
Get a class descriptor for the class. :param str class_name: Name of class. :param bool init_class: Whether the class initializer <clinit> should be executed. :param func step_func: Callback function executed at every step of the simulation manager during ...
Get the superclass of the class. 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)
Walks up the class hierarchy and returns a list of all classes between base class (inclusive) and java.lang.Object (exclusive). def get_class_hierarchy(self, base_class): """ Walks up the class hierarchy and returns a list of all classes between base class (inclusive) and java.lang.Obje...
This method simulates the loading of a class by the JVM, during which parts of the class (e.g. static fields) are initialized. For this, we run the class initializer method <clinit> (if available) and update the state accordingly. Note: Initialization is skipped, if the class has alread...
Get the IRSB object from an address, a SimRun, or a CFGNode. :param v: Can be one of the following: an address, or a CFGNode. :return: The IRSB instance. :rtype: pyvex.IRSB def _get_irsb(self, v): """ Get the IRSB object from an address, a SimRun, or a CFGNode. :param v:...
Get address of the basic block or CFG node specified by v. :param v: Can be one of the following: a CFGNode, or an address. :return: The address. :rtype: int def _get_addr(self, v): """ Get address of the basic block or CFG node specified by v. :param v: Can be one of th...
Backward slicing. We support the following IRStmts: # WrTmp # Put We support the following IRExprs: # Get # RdTmp # Const :return: def _backward_slice(self): """ Backward slicing. We support the following IRStmts: # WrT...
A simplified version of pc_calculate_condition(). Please refer to the documentation of Simplified CCalls above. Limitation: symbolic flags are not supported for now. def pc_calculate_condition_simple(state, cond, cc_op, cc_dep1, cc_dep2, cc_ndep, platform=None): """ A simplified version of pc_calculate_co...
Concatenate different flag BVs to a single BV. Currently used for ARM, X86 and AMD64. :param nbits : platform size in bits. :param flags_vec: vector of flag BVs and their offset in the resulting BV. :type nbits : int :type flags_vec : list :return : the resulting flag BV. :r...
RegionSimplifier performs the following simplifications: - Remove redundant Gotos - Remove redundant If/If-else statements def _simplify(self): """ RegionSimplifier performs the following simplifications: - Remove redundant Gotos - Remove redundant If/If-else statements ...
Parse a bytes object and create a class object. :param bytes s: A bytes object. :return: A class object. :rtype: cls def parse(cls, s, **kwargs): """ Parse a bytes object and create a class object. :param bytes s: A bytes object. :return: ...
Stores either a single element or a range of elements in the array. :param array: Reference to the array. :param start_idx: Starting index for the store. :param data: Either a single value or a list of values. def store_array_elements(self, array, start_idx, data): """ ...
Loads either a single element or a range of elements from the array. :param array: Reference to the array. :param start_idx: Starting index for the load. :param no_of_elements: Number of elements to load. def load_array_elements(self, array, start_idx, no_of_elements): ...
Applies concretization strategies on the index, until one of them succeeds. def _apply_concretization_strategies(self, idx, strategies, action): # pylint: disable=unused-argument """ Applies concretization strategies on the index, until one of them succeeds. """ for s in strategies: ...
Concretizes a store index. :param idx: An expression for the index. :param strategies: A list of concretization strategies (to override the default). :param min_idx: Minimum value for a concretized index (inclusive). :param max_idx: Maximum value for a c...
Concretizes a load index. :param idx: An expression for the index. :param strategies: A list of concretization strategies (to override the default). :param min_idx: Minimum value for a concretized index (inclusive). :param max_idx: Maximum value for a co...
Make a copy of the CFG. :return: A copy of the CFG instance. :rtype: angr.analyses.CFG def copy(self): """ Make a copy of the CFG. :return: A copy of the CFG instance. :rtype: angr.analyses.CFG """ new_cfg = CFGEmulated.__new__(CFGEmulated) supe...
Resume a paused or terminated control flow graph recovery. :param iterable starts: A collection of new starts to resume from. If `starts` is None, we will resume CFG recovery from where it was paused before. :param int max_steps: The maximum number of blocks on the lon...
Forces graph to become acyclic, removes all loop back edges and edges between overlapped loop headers and their successors. def remove_cycles(self): """ Forces graph to become acyclic, removes all loop back edges and edges between overlapped loop headers and their successors. ""...
Unroll loops for each function. The resulting CFG may still contain loops due to recursion, function calls, etc. :param int max_loop_unrolling_times: The maximum iterations of unrolling. :return: None def unroll_loops(self, max_loop_unrolling_times): """ Unroll loops for each function....
Unroll loops globally. The resulting CFG does not contain any loop, but this method is slow on large graphs. :param int max_loop_unrolling_times: The maximum iterations of unrolling. :return: None def force_unroll_loops(self, max_loop_unrolling_times): """ Unroll loops globally. The re...
Get all immediate dominators of sub graph from given node upwards. :param str start: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.graph. :return: each node of graph as index values, with element as respective ...
Get all immediate postdominators of sub graph from given node upwards. :param str start: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.graph. :return: each node of graph as index values, with element as respect...
Get rid of fake returns (i.e., Ijk_FakeRet edges) from this CFG :return: None def remove_fakerets(self): """ Get rid of fake returns (i.e., Ijk_FakeRet edges) from this CFG :return: None """ fakeret_edges = [ (src, dst) for src, dst, data in self.graph.edges(data=True)...
Get the topological order of a CFG Node. :param cfg_node: A CFGNode instance. :return: An integer representing its order, or None if the CFGNode does not exist in the graph. def get_topological_order(self, cfg_node): """ Get the topological order of a CFG Node. :param cfg_node...
Get a sub-graph out of a bunch of basic block addresses. :param CFGNode starting_node: The beginning of the subgraph :param iterable block_addresses: A collection of block addresses that should be included in the subgraph if there is a path between `starting_node...
Get a sub-graph of a certain function. :param start: The function start. Currently it should be an integer. :param max_call_depth: Call depth limit. None indicates no limit. :return: A CFG instance which is a sub-graph of self.graph def get_function_subgraph(self, start, max_call_depth=None): ...
Get all CFGNodes that has an out-degree of 0 :return: A list of CFGNode instances :rtype: list 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: ...
Perform a sanity check on parameters passed in to CFG.__init__(). An AngrCFGError is raised if any parameter fails the sanity check. :return: None def _sanitize_parameters(self): """ Perform a sanity check on parameters passed in to CFG.__init__(). An AngrCFGError is raised if ...
Get the sorting key of a CFGJob instance. :param CFGJob job: the CFGJob object. :return: An integer that determines the order of this job in the queue. :rtype: int def _job_sorting_key(self, job): """ Get the sorting key of a CFGJob instance. :param CFGJob job: the CFG...
Initialization work. Executed prior to the analysis. :return: None 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 ...
A callback method called when the job queue is empty. :return: None 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'...
Obtain a SimState object for a specific address Fastpath means the CFG generation will work in an IDA-like way, in which it will not try to execute every single statement in the emulator, but will just do the decoding job. This is much faster than the old way. :param int ip: The instruction po...
Retrieve a pending job. :return: A CFGJob instance or None def _get_one_pending_job(self): """ Retrieve a pending job. :return: A CFGJob instance or None """ pending_job_key, pending_job = self._pending_jobs.popitem() pending_job_state = pending_job.state ...
Process function hints in the binary. :return: None def _process_hints(self, analyzed_addrs): """ Process function hints in the binary. :return: None """ # Function hints! # Now let's see how many new functions we can get here... while self._pending_fu...
Post-CFG-construction. :return: None def _post_analysis(self): """ Post-CFG-construction. :return: None """ self._make_completed_functions() new_changes = self._iteratively_analyze_function_features() functions_do_not_return = new_changes['functions_do...
Before processing a CFGJob. Right now each block is traced at most once. If it is traced more than once, we will mark it as "should_skip" before tracing it. An AngrForwardAnalysisSkipJob exception is raised in order to skip analyzing the job. :param CFGJob job: The CFG job object. ...
Get a collection of successors out of the current job. :param CFGJob job: The CFGJob instance. :return: A collection of successors. :rtype: list def _get_successors(self, job): """ Get a collection of successors out of the current job. :param CF...
Filter the list of successors :param SimState input_state: Input state. :param SimSuccessors sim_successors: The SimSuccessors instance. :param list successors: A list of successors generated after processing the current block. :return: ...
Post job handling: print debugging information regarding the current job. :param CFGJob job: The current CFGJob instance. :param list successors: All successors of the analysis job. :return: None def _post_handle_job_debug(self, job, successors): """ Post job handling: pri...
Iteratively update the completed functions set, analyze whether each function returns or not, and remove pending exits if the callee function does not return. We do this iteratively so that we come to a fixed point in the end. In most cases, the number of outer iteration equals to the maximum levels of ...
Remove those pending exits if: a) they are the return exits of non-returning SimProcedures b) they are the return exits of non-returning syscalls c) they are the return exits of non-returning functions :return: True if any pending exits are removed, False otherwise :rtype: bool ...
Returns a new CFGJob instance for further analysis, or None if there is no immediate state to perform the analysis on. :param CFGJob job: The current job. def _handle_successor(self, job, successor, successors): """ Returns a new CFGJob instance for further analysis, or None if there i...
A block without successors should still be handled so it can be added to the function graph correctly. :param CFGJob job: The current job that do not have any successor. :param IRSB irsb: The related IRSB. :param insn_addrs: A list of instruction addresses of this IRSB. :return: Non...
For a given state and current location of of execution, will update a function by adding the offets of appropriate actions to the stack variable or argument registers for the fnc. :param SimState state: upcoming state. :param SimSuccessors current_run: possible result states. :param kno...
Update transition graphs of functions in function manager based on information passed in. :param str jumpkind: Jumpkind. :param CFGNode src_node: Source CFGNode :param CFGNode dst_node: Destionation CFGNode :param int ret_addr: The theoretical return address for calls :return: N...
Update the callsites of functions (remove return targets) that are calling functions that are just deemed not returning. :param iterable func_addrs: A collection of functions for newly-recovered non-returning functions. :return: None def _update_function_callsites(self, nore...
Throw away all successors whose target doesn't make sense This method is called after we resolve an indirect jump using an unreliable method (like, not through one of the indirect jump resolvers, but through either pure concrete execution or backward slicing) to filter out the obviously incorre...
Remove those return_from_call edges that actually do not return due to calling some not-returning functions. :return: None def _remove_non_return_edges(self): """ Remove those return_from_call edges that actually do not return due to calling some not-returning functions. ...
Convert each concrete indirect jump target into a SimState. :param job: The CFGJob instance. :param indirect_jump_targets: A collection of concrete jump targets resolved from a indirect jump. :return: A list of SimStates. :rtype: ...
Resolve indirect jumps specified by sim_successors.addr. :param SimSuccessors sim_successors: The SimSuccessors instance. :param CFGNode cfg_node: The CFGNode instance. :param int func_addr: Current function address. :param list successors: ...
Try to resolve an indirect jump by slicing backwards def _backward_slice_indirect(self, cfgnode, sim_successors, current_function_addr): """ Try to resolve an indirect jump by slicing backwards """ # TODO: make this a real indirect jump resolver under the new paradigm irsb = si...
Symbolically executes from ancestor nodes (2-5 times removed) finding paths of execution through the given CFGNode. :param SimSuccessors current_block: SimSuccessor with address to attempt to navigate to. :param dict block_artifacts: Container of IRSB data - specifically used for known persist...
Symbolically execute the first basic block of the specified function, then returns it. We prepares the state using the already existing state in fastpath mode (if avaiable). :param function_addr: The function address :return: A symbolic state if succeeded, None otherwise def _get_symbol...
Scan for constants that might be used as exit targets later, and add them into pending_exits. :param SimState successor_state: A successing state. :return: A list of discovered code addresses. :rtype: list def _search_for_functio...
Create the SimSuccessors instance for a block. :param int addr: Address of the block. :param CFGJob job: The CFG job instance with an input state inside. :param int current_function_addr: Address of the current function. :return: ...
Creates a new call stack, and according to the jumpkind performs appropriate actions. :param int addr: Address to create at. :param Simsuccessors all_jobs: Jobs to get stack pointer from or return address. :param CFGJob job: CFGJob to c...
Create a context-sensitive CFGNode instance for a specific block. :param SimSuccessors sim_successors: The SimSuccessors object. :param CallStack call_stack_suffix: The call stack. :param int func_addr: Address of the current function. :param Bloc...
Loop detection. :param func loop_callback: A callback function for each detected loop backedge. :return: None def _detect_loops(self, loop_callback=None): """ Loop detection. :param func loop_callback: A callback function for each detected loop backedge. :return: None ...
Get all immediate dominators of sub graph from given node upwards. :param str node: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.graph. :param bool reverse_graph: Whether the target graph should be reversed bef...