Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def dstk_parse(self, address, parser, pre_parsed_address=None): if pre_parsed_address: dstk_address = pre_parsed_address else: if self.logger: self.logger.debug("Asking DSTK for address parse {0}".format(address.encode("ascii"...
[ "\n Given an address string, use DSTK to parse the address and then coerce it to a normal Address object.\n pre_parsed_address for multi parsed string. Gives the value part for single dstk return value. If\n pre_parsed_address is None, parse it via dstk on its own.\n " ]
Please provide a description of the function:def _get_dstk_intersections(self, address, dstk_address): # Normalize both addresses normalized_address = self._normalize(address) normalized_dstk_address = self._normalize(dstk_address) address_uniques = set(normalized_address) - set...
[ "\n Find the unique tokens in the original address and the returned address.\n " ]
Please provide a description of the function:def _normalize(self, address): normalized_address = [] if self.logger: self.logger.debug("Normalizing Address: {0}".format(address)) for token in address.split(): if token.upper() in self.parser.suffixes.keys(): no...
[ "\n Normalize prefixes, suffixes and other to make matching original to returned easier.\n " ]
Please provide a description of the function:def empty(): if not hasattr(empty, '_instance'): empty._instance = Interval(AtomicInterval(OPEN, inf, -inf, OPEN)) return empty._instance
[ "\n Create an empty set.\n " ]
Please provide a description of the function:def from_string(string, conv, bound=r'.+?', disj=r' ?\| ?', sep=r', ?', left_open=r'\(', left_closed=r'\[', right_open=r'\)', right_closed=r'\]', pinf=r'\+inf', ninf=r'-inf'): re_left_boundary = r'(?P<left>{}|{})'.format(left_open, left_closed) ...
[ "\n Parse given string and create an Interval instance.\n A converter function has to be provided to convert a bound (as string) to a value.\n\n :param string: string to parse.\n :param conv: function that converts a bound (as string) to an object.\n :param bound: pattern that matches a value.\n :...
Please provide a description of the function:def to_string(interval, conv=repr, disj=' | ', sep=',', left_open='(', left_closed='[', right_open=')', right_closed=']', pinf='+inf', ninf='-inf'): interval = Interval(interval) if isinstance(interval, AtomicInterval) else interval if interval.is...
[ "\n Export given interval (or atomic interval) to string.\n\n :param interval: an Interval or AtomicInterval instance.\n :param conv: function that is used to represent a bound (default is `repr`).\n :param disj: string representing disjunctive operator (default is ' | ').\n :param sep: string repres...
Please provide a description of the function:def from_data(data, conv=None, pinf=float('inf'), ninf=float('-inf')): intervals = [] conv = (lambda v: v) if conv is None else conv def _convert(bound): if bound == pinf: return inf elif bound == ninf: return -inf ...
[ "\n Import an interval from a piece of data.\n\n :param data: a list of 4-uples (left, lower, upper, right).\n :param conv: function that is used to convert \"lower\" and \"upper\" to bounds, default to identity.\n :param pinf: value used to represent positive infinity.\n :param ninf: value used to r...
Please provide a description of the function:def to_data(interval, conv=None, pinf=float('inf'), ninf=float('-inf')): interval = Interval(interval) if isinstance(interval, AtomicInterval) else interval conv = (lambda v: v) if conv is None else conv data = [] def _convert(bound): if bound ...
[ "\n Export given interval (or atomic interval) to a list of 4-uples (left, lower,\n upper, right).\n\n :param interval: an Interval or AtomicInterval instance.\n :param conv: function that convert bounds to \"lower\" and \"upper\", default to identity.\n :param pinf: value used to encode positive inf...
Please provide a description of the function:def is_empty(self): return ( self._lower > self._upper or (self._lower == self._upper and (self._left == OPEN or self._right == OPEN)) )
[ "\n Test interval emptiness.\n\n :return: True if interval is empty, False otherwise.\n " ]
Please provide a description of the function:def replace(self, left=None, lower=None, upper=None, right=None, ignore_inf=True): if callable(left): left = left(self._left) else: left = self._left if left is None else left if callable(lower): lower = s...
[ "\n Create a new interval based on the current one and the provided values.\n\n Callable can be passed instead of values. In that case, it is called with the current\n corresponding value except if ignore_inf if set (default) and the corresponding\n bound is an infinity.\n\n :para...
Please provide a description of the function:def overlaps(self, other, permissive=False): if not isinstance(other, AtomicInterval): raise TypeError('Only AtomicInterval instances are supported.') if self._lower > other.lower: first, second = other, self else: ...
[ "\n Test if intervals have any overlapping value.\n\n If 'permissive' is set to True (default is False), then [1, 2) and [2, 3] are considered as having\n an overlap on value 2 (but not [1, 2) and (2, 3]).\n\n :param other: an atomic interval.\n :param permissive: set to True to c...
Please provide a description of the function:def to_atomic(self): lower = self._intervals[0].lower left = self._intervals[0].left upper = self._intervals[-1].upper right = self._intervals[-1].right return AtomicInterval(left, lower, upper, right)
[ "\n Return the smallest atomic interval containing this interval.\n\n :return: an AtomicInterval instance.\n " ]
Please provide a description of the function:def replace(self, left=None, lower=None, upper=None, right=None, ignore_inf=True): enclosure = self.to_atomic() if callable(left): left = left(enclosure._left) else: left = enclosure._left if left is None else left ...
[ "\n Create a new interval based on the current one and the provided values.\n\n If current interval is not atomic, it is extended or restricted such that\n its enclosure satisfies the new bounds. In other words, its new enclosure\n will be equal to self.to_atomic().replace(left, lower, u...
Please provide a description of the function:def apply(self, func): intervals = [] for interval in self: value = func(interval) if isinstance(value, (Interval, AtomicInterval)): intervals.append(value) elif isinstance(value, tuple): ...
[ "\n Apply given function on each of the underlying AtomicInterval instances and return a new\n Interval instance. The function is expected to return an AtomicInterval, an Interval\n or a 4-uple (left, lower, upper, right).\n\n :param func: function to apply on each of the underlying Atom...
Please provide a description of the function:def overlaps(self, other, permissive=False): if isinstance(other, AtomicInterval): for interval in self._intervals: if interval.overlaps(other, permissive=permissive): return True return False ...
[ "\n Test if intervals have any overlapping value.\n\n If 'permissive' is set to True (default is False), then intervals that are contiguous \n are considered as overlapping intervals as well (e.g. [1, 2) and [2, 3], \n but not [1, 2) and (2, 3] because 2 is not part of their union). \n\n...
Please provide a description of the function:def register_graphql_handlers( app: "Application", engine_sdl: str = None, engine_schema_name: str = "default", executor_context: dict = None, executor_http_endpoint: str = "/graphql", executor_http_methods: List[str] = None, engine: Engine = None...
[ "Register a Tartiflette Engine to an app\n\n Pass a SDL or an already initialized Engine, not both, not neither.\n\n Keyword Arguments:\n app {aiohttp.web.Application} -- The application to register to.\n engine_sdl {str} -- The SDL defining your API (default: {None})\n engine_schema_name...
Please provide a description of the function:async def on_shutdown(app): for method in app.get("close_methods", []): logger.debug("Calling < %s >", method) if asyncio.iscoroutinefunction(method): await method() else: method()
[ "app SHUTDOWN event handler\n " ]
Please provide a description of the function:def _load_from_file(path): config = [] try: with open(path, 'r') as config_file: config = yaml.load(config_file)['normalizations'] except EnvironmentError as e: raise ConfigError('Problem while loading...
[ "Load a config file from the given path.\n\n Load all normalizations from the config file received as\n argument. It expects to find a YAML file with a list of\n normalizations and arguments under the key 'normalizations'.\n\n Args:\n path: Path to YAML file.\n " ]
Please provide a description of the function:def _parse_normalization(normalization): parsed_normalization = None if isinstance(normalization, dict): if len(normalization.keys()) == 1: items = list(normalization.items())[0] if len(items) == 2: # Two ...
[ "Parse a normalization item.\n\n Transform dicts into a tuple containing the normalization\n options. If a string is found, the actual value is used.\n\n Args:\n normalization: Normalization to parse.\n\n Returns:\n Tuple or string containing the parsed normalizatio...
Please provide a description of the function:def _parse_normalizations(self, normalizations): parsed_normalizations = [] if isinstance(normalizations, list): for item in normalizations: normalization = self._parse_normalization(item) if normalization...
[ "Returns a list of parsed normalizations.\n\n Iterates over a list of normalizations, removing those\n not correctly defined. It also transform complex items\n to have a common format (list of tuples and strings).\n\n Args:\n normalizations: List of normalizations to parse.\n\...
Please provide a description of the function:def initialize_logger(debug): level = logging.DEBUG if debug else logging.INFO logger = logging.getLogger('cucco') logger.setLevel(level) formatter = logging.Formatter('%(asctime)s %(levelname).1s %(message)s') console_handler = logging.StreamHandler...
[ "Set up logger to be used by the library.\n\n Args:\n debug: Wheter to use debug level or not.\n\n Returns:\n A logger ready to be used.\n " ]
Please provide a description of the function:def batch(ctx, path, recursive, watch): batch = Batch(ctx.obj['config'], ctx.obj['cucco']) if os.path.exists(path): if watch: batch.watch(path, recursive) elif os.path.isfile(path): batch.process_file(path) else: ...
[ "\n Normalize files in a path.\n\n Apply normalizations over all files found in a given path.\n The normalizations applied will be those defined in the config\n file. If no config is specified, the default normalizations will\n be used.\n " ]
Please provide a description of the function:def normalize(ctx, text): if text: click.echo(ctx.obj['cucco'].normalize(text)) else: for line in sys.stdin: click.echo(ctx.obj['cucco'].normalize(line))
[ "\n Normalize text or piped input.\n\n Normalize text passed as an argument to this command using\n the specified config (default values if --config option is\n not used).\n\n Pipes can be used along this command to process the output\n of another cli. This is the default behaviour when no text\n ...
Please provide a description of the function:def cli(ctx, config, debug, language, verbose): ctx.obj = {} try: ctx.obj['config'] = Config(normalizations=config, language=language, debug=debug, ...
[ "\n Cucco allows to apply normalizations to a given text or file.\n This normalizations include, among others, removal of accent\n marks, stop words an extra white spaces, replacement of\n punctuation symbols, emails, emojis, etc.\n\n For more info on how to use and configure Cucco, check the\n pr...
Please provide a description of the function:def files_generator(path, recursive): if recursive: for (path, _, files) in os.walk(path): for file in files: if not file.endswith(BATCH_EXTENSION): yield (path, file) else: for file in os.listdir(p...
[ "Yield files found in a given path.\n\n Walk over a given path finding and yielding all\n files found on it. This can be done only on the root\n directory or recursively.\n\n Args:\n path: Path to the directory.\n recursive: Whether to find files recursively or not.\n\n Yields:\n ...
Please provide a description of the function:def process_file(self, path): if self._config.verbose: self._logger.info('Processing file "%s"', path) output_path = '%s%s' % (path, BATCH_EXTENSION) with open(output_path, 'w') as file: for line in lines_generator(p...
[ "Process a file applying normalizations.\n\n Get a file as input and generate a new file with the\n result of applying normalizations to every single line\n in the original file. The extension for the new file\n will be the one defined in BATCH_EXTENSION.\n\n Args:\n pa...
Please provide a description of the function:def process_files(self, path, recursive=False): self._logger.info('Processing files in "%s"', path) for (path, file) in files_generator(path, recursive): if not file.endswith(BATCH_EXTENSION): self.process_file(os.path.jo...
[ "Apply normalizations over all files in the given directory.\n\n Iterate over all files in a given directory. Normalizations\n will be applied to each file, storing the result in a new file.\n The extension for the new file will be the one defined in\n BATCH_EXTENSION.\n\n Args:\n...
Please provide a description of the function:def stop_watching(self): self._watch = False if self._observer: self._logger.info('Stopping watcher') self._observer.stop() self._logger.info('Watcher stopped')
[ "Stop watching for files.\n\n Stop the observer started by watch function and finish\n thread life.\n " ]
Please provide a description of the function:def watch(self, path, recursive=False): self._logger.info('Initializing watcher for path "%s"', path) handler = FileHandler(self) self._observer = Observer() self._observer.schedule(handler, path, recursive) self._logger.inf...
[ "Watch for files in a directory and apply normalizations.\n\n Watch for new or changed files in a directory and apply\n normalizations over them.\n\n Args:\n path: Path to the directory.\n recursive: Whether to find files recursively or not.\n " ]
Please provide a description of the function:def _process_event(self, event): if (not event.is_directory and not event.src_path.endswith(BATCH_EXTENSION)): self._logger.info('Detected file change: %s', event.src_path) self._batch.process_file(event.src_path)
[ "Process received events.\n\n Process events received, applying normalization for those\n events referencing a new or changed file and only if it's\n not the result of a previous normalization.\n\n Args:\n event: Event to process.\n " ]
Please provide a description of the function:def on_created(self, event): self._logger.debug('Detected create event on watched path: %s', event.src_path) self._process_event(event)
[ "Function called everytime a new file is created.\n\n Args:\n event: Event to process.\n " ]
Please provide a description of the function:def on_modified(self, event): self._logger.debug('Detected modify event on watched path: %s', event.src_path) self._process_event(event)
[ "Function called everytime a new file is modified.\n\n Args:\n event: Event to process.\n " ]
Please provide a description of the function:def _load_stop_words(self, language=None): self._logger.debug('Loading stop words') loaded = False if language: file_path = 'data/stop-' + language loaded = self._parse_stop_words_file(os.path.join(PATH, file_path)) ...
[ "Load stop words into __stop_words set.\n\n Stop words will be loaded according to the language code\n received during instantiation.\n\n Args:\n language: Language code.\n\n Returns:\n A boolean indicating whether a file was loaded.\n " ]
Please provide a description of the function:def _parse_normalizations(normalizations): str_type = str if sys.version_info[0] > 2 else (str, unicode) for normalization in normalizations: yield (normalization, {}) if isinstance(normalization, str_type) else normalization
[ "Parse and yield normalizations.\n\n Parse normalizations parameter that yield all normalizations and\n arguments found on it.\n\n Args:\n normalizations: List of normalizations.\n\n Yields:\n A tuple with a parsed normalization. The first item will\n con...
Please provide a description of the function:def _parse_stop_words_file(self, path): language = None loaded = False if os.path.isfile(path): self._logger.debug('Loading stop words in %s', path) language = path.split('-')[-1] if not language in self...
[ "Load stop words from the given path.\n\n Parse the stop words file, saving each word found in it in a set\n for the language of the file. This language is obtained from\n the file name. If the file doesn't exist, the method will have\n no effect.\n\n Args:\n path: Path...
Please provide a description of the function:def normalize(self, text, normalizations=None): for normalization, kwargs in self._parse_normalizations( normalizations or self._config.normalizations): try: text = getattr(self, normalization)(text, **kwargs) ...
[ "Normalize a given text applying all normalizations.\n\n Normalizations to apply can be specified through a list of\n parameters and will be executed in that order.\n\n Args:\n text: The text to be processed.\n normalizations: List of normalizations to apply.\n\n Re...
Please provide a description of the function:def remove_accent_marks(text, excluded=None): if excluded is None: excluded = set() return unicodedata.normalize( 'NFKC', ''.join( c for c in unicodedata.normalize( 'NFKD', text) if unicode...
[ "Remove accent marks from input text.\n\n This function removes accent marks in the text, but leaves\n unicode characters defined in the 'excluded' parameter.\n\n Args:\n text: The text to be processed.\n excluded: Set of unicode characters to exclude.\n\n Returns:\...
Please provide a description of the function:def remove_stop_words(self, text, ignore_case=True, language=None): if not language: language = self._config.language if language not in self.__stop_words: if not self._load_stop_words(language): self._logger....
[ "Remove stop words.\n\n Stop words are loaded on class instantiation according\n to the specified language.\n\n Args:\n text: The text to be processed.\n ignore_case: Whether or not to ignore case.\n language: Code of the language to use (defaults to 'en').\n\n ...
Please provide a description of the function:def replace_characters(self, text, characters, replacement=''): if not characters: return text characters = ''.join(sorted(characters)) if characters in self._characters_regexes: characters_regex = self._characters_re...
[ "Remove characters from text.\n\n Removes custom characters from input text or replaces them\n with a string if specified.\n\n Args:\n text: The text to be processed.\n characters: Characters that will be replaced.\n replacement: New text that will replace the c...
Please provide a description of the function:def replace_punctuation(self, text, excluded=None, replacement=''): if excluded is None: excluded = set() elif not isinstance(excluded, set): excluded = set(excluded) punct = ''.join(self.__punctuation.difference(exclu...
[ "Replace punctuation symbols in text.\n\n Removes punctuation from input text or replaces them with a\n string if specified. Characters replaced will be those\n in string.punctuation.\n\n Args:\n text: The text to be processed.\n excluded: Set of characters to exclu...
Please provide a description of the function:def replace_symbols( text, form='NFKD', excluded=None, replacement=''): if excluded is None: excluded = set() categories = set(['Mn', 'Sc', 'Sk', 'Sm', 'So']) return ''.join(c if u...
[ "Replace symbols in text.\n\n Removes symbols from input text or replaces them with a\n string if specified.\n\n Args:\n text: The text to be processed.\n form: Unicode form.\n excluded: Set of unicode characters to exclude.\n replacement: New text th...
Please provide a description of the function:def get_cases(self, target): if target in self.targets: return self._reverse_map[target] raise KeyError("Target 0x{:08X} does not exist.".format(target))
[ "switch.get_cases(target) -> [case]" ]
Please provide a description of the function:def get_idb_graph(): digraph = nx.DiGraph() for function in functions(): for xref in itertools.chain(function.xrefs_from, function.xrefs_to): frm = _try_get_function_start(xref.frm) to = _try_get_function_start(xref.to) ...
[ "Export IDB to a NetworkX graph.\n\n Use xrefs to and from functions to build a DiGraph containing all\n the functions in the IDB and all the links between them.\n The graph can later be used to perform analysis on the IDB.\n\n :return: nx.DiGraph()\n " ]
Please provide a description of the function:def name(self): return self.TYPES.get(self._type, self.TYPES[idaapi.o_idpspec0])
[ "Name of the xref type." ]
Please provide a description of the function:def reg(self): if self.type.is_displ or self.type.is_phrase: size = core.get_native_size() return base.get_register_name(self.reg_id, size) if self.type.is_reg: return base.get_register_name(self.reg_id, self.size...
[ "Name of the register used in the operand." ]
Please provide a description of the function:def has_reg(self, reg_name): return any(operand.has_reg(reg_name) for operand in self.operands)
[ "Check if a register is used in the instruction." ]
Please provide a description of the function:def regs(self): regs = set() for operand in self.operands: if not operand.type.has_reg: continue regs.update(operand.regs) return regs
[ "Names of all registers used by the instruction." ]
Please provide a description of the function:def _pad(self, text): top_bottom = ("\n" * self._padding) + " " right_left = " " * self._padding * self.PAD_WIDTH return top_bottom + right_left + text + right_left + top_bottom
[ "Pad the text." ]
Please provide a description of the function:def _make_unique_title(self, title): unique_title = title for counter in itertools.count(): unique_title = "{}-{}".format(title, counter) if not idaapi.find_tform(unique_title): break return unique_ti...
[ "Make the title unique.\n\n Adds a counter to the title to prevent duplicates.\n\n Prior to IDA 6.8, two graphs with the same title could crash IDA.\n This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml).\n The code will not change for support of older versions and...
Please provide a description of the function:def _get_handler(self, node_id): handler = self._get_attrs(node_id).get(self.HANDLER, self._default_handler) # Here we make sure the handler is an instance of `BasicNodeHandler` or inherited # types. While generally being bad Python practice...
[ "Get the handler of a given node." ]
Please provide a description of the function:def _get_handling_triplet(self, node_id): handler = self._get_handler(node_id) value = self[node_id] attrs = self._get_attrs(node_id) return handler, value, attrs
[ "_get_handling_triplet(node_id) -> (handler, value, attrs)" ]
Please provide a description of the function:def _OnNodeInfo(self, node_id): handler, value, attrs = self._get_handling_triplet(node_id) frame_color = handler.on_frame_color(value, attrs) node_info = idaapi.node_info_t() if frame_color is not None: node_info.frame_...
[ "Sets the node info based on its attributes." ]
Please provide a description of the function:def get_string(ea): # We get the item-head because the `GetStringType` function only works on the head of an item. string_type = idc.GetStringType(idaapi.get_item_head(ea)) if string_type is None: raise exceptions.SarkNoString("No string at 0x{:08X}...
[ "Read the string at the given ea.\n\n This function uses IDA's string APIs and does not implement any special logic.\n " ]
Please provide a description of the function:def copy_current_file_offset(): start, end = sark.get_selection() try: file_offset = sark.core.get_fileregion_offset(start) clipboard.copy("0x{:08X}".format(file_offset)) except sark.exceptions.NoFileOffset: message("The current add...
[ "Get the file-offset mapped to the current address." ]
Please provide a description of the function:def get_func(func_ea): if isinstance(func_ea, idaapi.func_t): return func_ea func = idaapi.get_func(func_ea) if func is None: raise exceptions.SarkNoFunction("No function at 0x{:08X}".format(func_ea)) return func
[ "get_func(func_t or ea) -> func_t\n\n Take an IDA function (``idaapi.func_t``) or an address (EA) and return\n an IDA function object.\n\n Use this when APIs can take either a function or an address.\n\n Args:\n func_ea: ``idaapi.func_t`` or ea of the function.\n\n Returns:\n An ``idaap...
Please provide a description of the function:def fix_addresses(start=None, end=None): if start in (None, idaapi.BADADDR): start = idaapi.cvar.inf.minEA if end in (None, idaapi.BADADDR): end = idaapi.cvar.inf.maxEA return start, end
[ "Set missing addresses to start and end of IDB.\n\n Take a start and end addresses. If an address is None or `BADADDR`,\n return start or end addresses of the IDB instead.\n\n Args\n start: Start EA. Use `None` to get IDB start.\n end: End EA. Use `None` to get IDB end.\n\n Returns:\n ...
Please provide a description of the function:def set_name(address, name, anyway=False): success = idaapi.set_name(address, name, idaapi.SN_NOWARN | idaapi.SN_NOCHECK) if success: return if anyway: success = idaapi.do_name_anyway(address, name) if success: return ...
[ "Set the name of an address.\n\n Sets the name of an address in IDA.\n If the name already exists, check the `anyway` parameter:\n\n True - Add `_COUNTER` to the name (default IDA behaviour)\n False - Raise an `exceptions.SarkErrorNameAlreadyExists` exception.\n\n\n Args\n address: The...
Please provide a description of the function:def is_same_function(ea1, ea2): func1 = idaapi.get_func(ea1) func2 = idaapi.get_func(ea2) # This is bloated code. `None in (func1, func2)` will not work because of a # bug in IDAPython in the way functions are compared. if any(func is None for func i...
[ "Are both addresses in the same function?" ]
Please provide a description of the function:def get_nx_graph(ea): nx_graph = networkx.DiGraph() func = idaapi.get_func(ea) flowchart = FlowChart(func) for block in flowchart: # Make sure all nodes are added (including edge-less nodes) nx_graph.add_node(block.startEA) for p...
[ "Convert an IDA flowchart to a NetworkX graph." ]
Please provide a description of the function:def codeblocks(start=None, end=None, full=True): if full: for function in functions(start, end): fc = FlowChart(f=function.func_t) for block in fc: yield block else: start, end = fix_addresses(start, end) ...
[ "Get all `CodeBlock`s in a given range.\n\n Args:\n start - start address of the range. If `None` uses IDB start.\n end - end address of the range. If `None` uses IDB end.\n full - `True` is required to change node info (e.g. color). `False` causes faster iteration.\n " ]
Please provide a description of the function:def struct_member_error(err, sid, name, offset, size): exception, msg = STRUCT_ERROR_MAP[err] struct_name = idc.GetStrucName(sid) return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) ' 'failed: {}').format( ...
[ "Create and format a struct member exception.\n\n Args:\n err: The error value returned from struct member creation\n sid: The struct id\n name: The member name\n offset: Memeber offset\n size: Member size\n\n Returns:\n A ``SarkErrorAddStructMemeberFailed`` derivativ...
Please provide a description of the function:def create_struct(name): sid = idc.GetStrucIdByName(name) if sid != idaapi.BADADDR: # The struct already exists. raise exceptions.SarkStructAlreadyExists("A struct names {!r} already exists.".format(name)) sid = idc.AddStrucEx(-1, name, 0) ...
[ "Create a structure.\n\n Args:\n name: The structure's name\n\n Returns:\n The sturct ID\n\n Raises:\n exceptions.SarkStructAlreadyExists: A struct with the same name already exists\n exceptions.SarkCreationFailed: Struct creation failed\n " ]
Please provide a description of the function:def get_struct(name): sid = idc.GetStrucIdByName(name) if sid == idaapi.BADADDR: raise exceptions.SarkStructNotFound() return sid
[ "Get a struct by it's name.\n\n Args:\n name: The name of the struct\n\n Returns:\n The struct's id\n\n Raises:\n exceptions.SarkStructNotFound: is the struct does not exist.\n " ]
Please provide a description of the function:def get_common_register(start, end): registers = defaultdict(int) for line in lines(start, end): insn = line.insn for operand in insn.operands: if not operand.type.has_phrase: continue if not operand.bas...
[ "Get the register most commonly used in accessing structs.\n\n Access to is considered for every opcode that accesses memory\n in an offset from a register::\n\n mov eax, [ebx + 5]\n\n For every access, the struct-referencing registers, in this case\n `ebx`, are counted. The most used one is retu...
Please provide a description of the function:def _enum_member_error(err, eid, name, value, bitmask): exception, msg = ENUM_ERROR_MAP[err] enum_name = idaapi.get_enum_name(eid) return exception(('add_enum_member(enum="{}", member="{}", value={}, bitmask=0x{:08X}) ' 'failed: {}').fo...
[ "Format enum member error." ]
Please provide a description of the function:def _get_enum(name): eid = idaapi.get_enum(name) if eid == idaapi.BADADDR: raise exceptions.EnumNotFound('Enum "{}" does not exist.'.format(name)) return eid
[ "Get an existing enum ID" ]
Please provide a description of the function:def add_enum(name=None, index=None, flags=idaapi.hexflag(), bitfield=False): if name is not None: with ignored(exceptions.EnumNotFound): _get_enum(name) raise exceptions.EnumAlreadyExists() if index is None or index < 0: ...
[ "Create a new enum.\n\n Args:\n name: Name of the enum to create.\n index: The index of the enum. Leave at default to append the enum as the last enum.\n flags: Enum type flags.\n bitfield: Is the enum a bitfield.\n\n Returns:\n An `Enum` object.\n " ]
Please provide a description of the function:def _add_enum_member(enum, name, value, bitmask=DEFMASK): error = idaapi.add_enum_member(enum, name, value, bitmask) if error: raise _enum_member_error(error, enum, name, value, bitmask)
[ "Add an enum member." ]
Please provide a description of the function:def _iter_bitmasks(eid): bitmask = idaapi.get_first_bmask(eid) yield bitmask while bitmask != DEFMASK: bitmask = idaapi.get_next_bmask(eid, bitmask) yield bitmask
[ "Iterate all bitmasks in a given enum.\n\n Note that while `DEFMASK` indicates no-more-bitmasks, it is also a\n valid bitmask value. The only way to tell if it exists is when iterating\n the serials.\n " ]
Please provide a description of the function:def _iter_enum_member_values(eid, bitmask): value = idaapi.get_first_enum_member(eid, bitmask) yield value while value != DEFMASK: value = idaapi.get_next_enum_member(eid, value, bitmask) yield value
[ "Iterate member values with given bitmask inside the enum\n\n Note that `DEFMASK` can either indicate end-of-values or a valid value.\n Iterate serials to tell apart.\n " ]
Please provide a description of the function:def _iter_serial_enum_member(eid, value, bitmask): cid, serial = idaapi.get_first_serial_enum_member(eid, value, bitmask) while cid != idaapi.BADNODE: yield cid, serial cid, serial = idaapi.get_next_serial_enum_member(cid, serial)
[ "Iterate serial and CID of enum members with given value and bitmask.\n\n Here only valid values are returned, as `idaapi.BADNODE` always indicates\n an invalid member.\n " ]
Please provide a description of the function:def _iter_enum_constant_ids(eid): for bitmask in _iter_bitmasks(eid): for value in _iter_enum_member_values(eid, bitmask): for cid, serial in _iter_serial_enum_member(eid, value, bitmask): yield cid
[ "Iterate the constant IDs of all members in the given enum" ]
Please provide a description of the function:def add(self, name, value, bitmask=DEFMASK): _add_enum_member(self._eid, name, value, bitmask)
[ "Add an enum member\n\n Args:\n name: Name of the member\n value: value of the member\n bitmask: bitmask. Only use if enum is a bitfield.\n " ]
Please provide a description of the function:def remove(self, name): member = self[name] serial = member.serial value = member.value bmask = member.bmask success = idaapi.del_enum_member(self._eid, value, serial, bmask) if not success: raise exceptio...
[ "Remove an enum member by name" ]
Please provide a description of the function:def name(self, name): success = idaapi.set_enum_name(self.eid, name) if not success: raise exceptions.CantRenameEnum("Cant rename enum {!r} to {!r}.".format(self.name, name))
[ "Set the enum name." ]
Please provide a description of the function:def name(self, name): success = idaapi.set_enum_member_name(self.cid, name) if not success: raise exceptions.CantRenameEnumMember( "Failed renaming {!r} to {!r}. Does the name exist somewhere else?".format(self.name, name)...
[ "Set the member name.\n\n Note that a member name cannot appear in other enums, or generally\n anywhere else in the IDB.\n " ]
Please provide a description of the function:def hex_encode(input, errors='strict'): assert errors == 'strict' temp = binascii.b2a_hex(input) output = " ".join(temp[i:i + 2] for i in xrange(0, len(temp), 2)) return (output, len(input))
[ " Encodes the object input and returns a tuple (output\n object, length consumed).\n\n errors defines the error handling to apply. It defaults to\n 'strict' handling which is the only currently supported\n error handling for this codec.\n\n " ]
Please provide a description of the function:def hex_decode(input, errors='strict'): assert errors == 'strict' output = binascii.a2b_hex("".join(char for char in input if char in hexdigits)) return (output, len(input))
[ " Decodes the object input and returns a tuple (output\n object, length consumed).\n\n input must be an object which provides the bf_getreadbuf\n buffer slot. Python strings, buffer objects and memory\n mapped files are examples of objects providing this slot.\n\n errors defines t...
Please provide a description of the function:def functions(start=None, end=None): start, end = fix_addresses(start, end) for func_t in idautils.Functions(start, end): yield Function(func_t)
[ "Get all functions in range.\n\n Args:\n start: Start address of the range. Defaults to IDB start.\n end: End address of the range. Defaults to IDB end.\n\n Returns:\n This is a generator that iterates over all the functions in the IDB.\n " ]
Please provide a description of the function:def xrefs_from(self): for line in self.lines: for xref in line.xrefs_from: if xref.type.is_flow: continue if xref.to in self and xref.iscode: continue yield...
[ "Xrefs from the function.\n\n This includes the xrefs from every line in the function, as `Xref` objects.\n Xrefs are filtered to exclude code references that are internal to the function. This\n means that every xrefs to the function's code will NOT be returned (yet, references\n to the...
Please provide a description of the function:def set_name(self, name, anyway=False): set_name(self.startEA, name, anyway=anyway)
[ "Set Function Name.\n\n Default behavior throws an exception when setting to a name that already exists in\n the IDB. to make IDA automatically add a counter to the name (like in the GUI,)\n use `anyway=True`.\n\n Args:\n name: Desired name.\n anyway: `True` to set ...
Please provide a description of the function:def color(self): color = idc.GetColor(self.ea, idc.CIC_FUNC) if color == 0xFFFFFFFF: return None return color
[ "Function color in IDA View" ]
Please provide a description of the function:def color(self, color): if color is None: color = 0xFFFFFFFF idc.SetColor(self.ea, idc.CIC_FUNC, color)
[ "Function Color in IDA View.\n\n Set color to `None` to clear the color.\n " ]
Please provide a description of the function:def lines(start=None, end=None, reverse=False, selection=False): if selection: start, end = get_selection() else: start, end = fix_addresses(start, end) if not reverse: item = idaapi.get_item_head(start) while item < end: ...
[ "Iterate lines in range.\n\n Args:\n start: Starting address, start of IDB if `None`.\n end: End address, end of IDB if `None`.\n reverse: Set to true to iterate in reverse order.\n selection: If set to True, replaces start and end with current selection.\n\n Returns:\n iter...
Please provide a description of the function:def type(self): properties = {self.is_code: "code", self.is_data: "data", self.is_string: "string", self.is_tail: "tail", self.is_unknown: "unknown"} for k, v in ...
[ "return the type of the Line " ]
Please provide a description of the function:def color(self): color = idc.GetColor(self.ea, idc.CIC_ITEM) if color == 0xFFFFFFFF: return None return color
[ "Line color in IDA View" ]
Please provide a description of the function:def color(self, color): if color is None: color = 0xFFFFFFFF idc.SetColor(self.ea, idc.CIC_ITEM, color)
[ "Line Color in IDA View.\n\n Set color to `None` to clear the color.\n " ]
Please provide a description of the function:def capture_widget(widget, path=None): if use_qt5: pixmap = widget.grab() else: pixmap = QtGui.QPixmap.grabWidget(widget) if path: pixmap.save(path) else: image_buffer = QtCore.QBuffer() image_buffer.open(QtCore....
[ "Grab an image of a Qt widget\n\n Args:\n widget: The Qt Widget to capture\n path (optional): The path to save to. If not provided - will return image data.\n\n Returns:\n If a path is provided, the image will be saved to it.\n If not, the PNG buffer will be returned.\n " ]
Please provide a description of the function:def get_widget(title): tform = idaapi.find_tform(title) if not tform: raise exceptions.FormNotFound("No form titled {!r} found.".format(title)) return form_to_widget(tform)
[ "Get the Qt widget of the IDA window with the given title." ]
Please provide a description of the function:def get_window(): tform = idaapi.get_current_tform() # Required sometimes when closing IDBs and not IDA. if not tform: tform = idaapi.find_tform("Output window") widget = form_to_widget(tform) window = widget.window() return window
[ "Get IDA's top level window." ]
Please provide a description of the function:def add_menu(self, name): if name in self._menus: raise exceptions.MenuAlreadyExists("Menu name {!r} already exists.".format(name)) menu = self._menu.addMenu(name) self._menus[name] = menu
[ "Add a top-level menu.\n\n The menu manager only allows one menu of the same name. However, it does\n not make sure that there are no pre-existing menus of that name.\n " ]
Please provide a description of the function:def remove_menu(self, name): if name not in self._menus: raise exceptions.MenuNotFound( "Menu {!r} was not found. It might be deleted, or belong to another menu manager.".format(name)) self._menu.removeAction(self._menus[...
[ "Remove a top-level menu.\n\n Only removes menus created by the same menu manager.\n " ]
Please provide a description of the function:def clear(self): for menu in self._menus.itervalues(): self._menu.removeAction(menu.menuAction()) self._menus = {}
[ "Clear all menus created by this manager." ]
Please provide a description of the function:def get_by_flags(self, flags): for reg in self._reg_infos: if reg.flags & flags == flags: yield reg
[ "Iterate all register infos matching the given flags." ]
Please provide a description of the function:def get_single_by_flags(self, flags): regs = list(self.get_by_flags(flags)) if len(regs) != 1: raise ValueError("Flags do not return unique resigter. {!r}", regs) return regs[0]
[ "Get the register info matching the flag. Raises ValueError if more than one are found." ]
Please provide a description of the function:def segments(seg_type=None): for index in xrange(idaapi.get_segm_qty()): seg = Segment(index=index) if (seg_type is None) or (seg.type == seg_type): yield Segment(index=index)
[ "Iterate segments based on type\n\n Args:\n seg_type: type of segment e.g. SEG_CODE\n\n Returns:\n iterator of `Segment` objects. if seg_type is None , returns all segments\n otherwise returns only the relevant ones\n " ]
Please provide a description of the function:def next(self): seg = Segment(segment_t=idaapi.get_next_seg(self.ea)) if seg.ea <= self.ea: raise exceptions.NoMoreSegments("This is the last segment. No segments exist after it.") return seg
[ "Get the next segment." ]
Please provide a description of the function:def prev(self): seg = Segment(segment_t=idaapi.get_prev_seg(self.ea)) if seg.ea >= self.ea: raise exceptions.NoMoreSegments("This is the first segment. no segments exist before it.") return seg
[ "Get the previous segment." ]
Please provide a description of the function:def compare_version(a, b): # Ignore PyDocStyleBear def _range(q): r = [] for n in q.replace("-", ".").split("."): try: r.append(int(n)) except ValueError: # sort rc*, alpha, beta etc....
[ "Compare two version strings.\n\n :param a: str\n :param b: str\n :return: -1 / 0 / 1\n ", "Convert a version string to array of integers.\n\n \"1.2.3\" -> [1, 2, 3]\n\n :param q: str\n :return: List[int]\n ", "Append `num_zeros` zeros to a copy of `x` and return it.\n\n ...
Please provide a description of the function:def get_ecosystem_solver(ecosystem_name, parser_kwargs=None, fetcher_kwargs=None): from .python import PythonSolver if ecosystem_name.lower() == "pypi": source = Source(url="https://pypi.org/simple", warehouse_api_url="https://pypi.org/pypi", warehouse=...
[ "Get Solver subclass instance for particular ecosystem.\n\n :param ecosystem_name: name of ecosystem for which solver should be get\n :param parser_kwargs: parser key-value arguments for constructor\n :param fetcher_kwargs: fetcher key-value arguments for constructor\n :return: Solver\n " ]