# IDA Domain API > IDA Domain API - Python interface for IDA Pro reverse engineering platform This is a pure python package built on top of IDA Python SDK. It provides easy access to the main entities manipulated by IDA Pro. All entities are accessible trough the db handle. # Installation # IDA Domain API The IDA Domain API provides a **Domain Model** on top of the IDA Python SDK. This API will not replace the current low level IDA Python SDK, but will progressively increase in coverage to become the **main entry point** for IDA scripting & plugin development. ## 🚀 Key Features - **Pure Python implementation** - No compilation required, works with any Python 3.9+ - **Domain-driven design** - APIs mirror how reverse engineers think about binaries - **Compatibility** - The Domain API is fully compatible and can be used alongside with the IDA Python SDK - **Comprehensive coverage** - Functions, strings, types, cross-references, and more - **Easy installation** - Single `pip install` command ## ⚙️ Quick Example ``` import argparse from ida_domain import Database parser = argparse.ArgumentParser(description='Quick Usage Example') parser.add_argument('-f', '--input-file', type=str, required=True) args = parser.parse_args() # Open any binary format IDA supports with Database() as db: if db.open(args.input_file): # Pythonic iteration over functions for func in db.functions.get_all(): print(f'{func.name}: {len(list(db.functions.get_instructions(func)))} instructions') ``` ## 📖 Documentation - **[Getting Started](getting_started/)** - Installation and your first script - **[Examples](examples/)** - Practical examples for common tasks - **[API Reference](usage/)** - Complete API documentation ## 🔗 Additional Resources - **PyPI Package**: [ida-domain on PyPI](https://pypi.org/project/ida-domain/) - **Source Code**: [GitHub Repository](https://github.com/HexRaysSA/ida-domain) - **Issues**: [Bug Reports](https://github.com/HexRaysSA/ida-domain/issues) - **License**: MIT License # Usage Welcome to the IDA Domain API reference documentation. This section provides comprehensive documentation for all modules and functions available in the IDA Domain library. The IDA Domain API is organized around the following top level entities: - **[Database](../ref/database/)** - Main database operations and management - **[Entries](../ref/entries/)** - Entry point management and analysis - **[Segments](../ref/segments/)** - Memory segment operations - **[Functions](../ref/functions/)** - Function analysis and manipulation - **[Basic Blocks](../ref/basic_blocks/)** - Basic block operations - **[Instructions](../ref/instructions/)** - Instruction-level analysis - **[Operands](../ref/operands/)** - Operand analysis and manipulation - **[Bytes](../ref/bytes/)** - Raw byte manipulation and analysis - **[Strings](../ref/strings/)** - String detection and analysis - **[Types](../ref/types/)** - Type information and management - **[Heads](../ref/heads/)** - Address head management - **[XRefs](../ref/xrefs/)** - Xref analysis - **[Events](../ref/xrefs/)** - Event handling - **[Names](../ref/names/)** - Symbol name management - **[Comments](../ref/comments/)** - Comment management - **[Signature Files](../ref/signature_files/)** - FLIRT signature file operations ## Accessing the entities The first thing that you will usually want to do is opening a **[Database](../ref/database/)**. Once the database is opened, you can access all other entities from the database handle itself through their respective property. ``` db = Database() db.open('/path/to/your/database.idb') db.functions.get_all() db.segments.get_all() db.entries.get_all() ... ``` ## Event handling Using the events property on the **[Database](../ref/database/)** you can register listener for specific events. ``` from ida_domain import Database db = Database() db.open('/path/to/your/database.idb') events = db.events() # Register event handlers @events.on_function_added def handle_func_added(func_ea): print(f"Function added at 0x{func_ea:X}") @events.on_renamed def handle_renamed(ea, new_name, is_local): print(f"Renamed 0x{ea:X} to {new_name}") # Start listening for events events.hook() # ... perform operations # Stop listening events.unhook() db.close() ``` ## Compatibility with IDA Python SDK The IDA Domain API is fully compatible with the IDA Python SDK shipped with IDA. It means the while we are extending the coverage of IDA Domain API, you can always fallback to using the IDA Python SDK. Here is an example: ``` import ida_domain import ida_funcs db = ida_domain.Database() db.open('/path/to/your/database.idb') for i, func in enumerate(db.functions.get_all()): print(ida_funcs.get_func_name(func.start_ea)) # <== this is calling IDA Python SDK ``` # Examples # Examples This section provides few examples of using the IDA Domain API for common reverse engineering tasks. ## Basic Database Operations ### Opening and Exploring a Database ``` #!/usr/bin/env python3 """ Database exploration example for IDA Domain API. This example demonstrates how to open an IDA database and explore its basic properties. """ import argparse import ida_domain def explore_database(db_path): """Explore basic database information.""" ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) db = ida_domain.Database() if db.open(db_path, ida_options): # Get basic information print(f'Address range: {hex(db.minimum_ea)} - {hex(db.maximum_ea)}') # Get metadata print('Database metadata:') for key, value in db.metadata.items(): print(f' {key}: {value}') # Count functions function_count = 0 for _ in db.functions.get_all(): function_count += 1 print(f'Total functions: {function_count}') db.close(save=False) def main(): """Main entry point with argument parsing.""" parser = argparse.ArgumentParser(description='Database exploration example') parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) args = parser.parse_args() explore_database(args.input_file) if __name__ == '__main__': main() ``` ### Complete Traversal of a Database This example demonstrates a complete traversal of a database: ``` #!/usr/bin/env python3 """ Database Traversal Example for IDA Domain API This example demonstrates how to systematically traverse an IDA database and examine available entities. It provides a structured approach to exploring contents of a binary analysis database. """ import argparse import ida_domain def print_section_header(title: str, char: str = '=') -> None: """Print a formatted section header for better output organization.""" print(f'\n{char * 60}') print(f' {title}') print(f'{char * 60}') def print_subsection_header(title: str) -> None: """Print a formatted subsection header.""" print(f'\n--- {title} ---') def traverse_metadata(db: ida_domain.Database) -> None: """ Traverse and display database metadata. Args: db: The IDA database instance """ print_section_header('DATABASE METADATA') metadata = db.metadata if metadata: for key, value in metadata.items(): print(f' {key:15}: {value}') else: print(' No metadata available') # Additional database properties print(f' {"current_ea":15}: 0x{db.current_ea:x}') print(f' {"minimum_ea":15}: 0x{db.minimum_ea:x}') print(f' {"maximum_ea":15}: 0x{db.maximum_ea:x}') def traverse_segments(db: ida_domain.Database) -> None: """ Traverse and display memory segments. Args: db: The IDA database instance """ print_section_header('MEMORY SEGMENTS') segments = list(db.segments.get_all()) print(f'Total segments: {len(segments)}') for i, segment in enumerate(segments, 1): print( f' [{i:2d}] {segment.name:20} | ' f'Start: 0x{segment.start_ea:08x} | ' f'End: 0x{segment.end_ea:08x} | ' f'Size: {segment.size} | ' f'Type: {segment.type}' ) def traverse_functions(db: ida_domain.Database) -> None: """ Traverse and display functions. Args: db: The IDA database instance """ print_section_header('FUNCTIONS') functions = list(db.functions.get_all()) print(f'Total functions: {len(functions)}') # Show first 20 functions to avoid overwhelming output display_count = min(20, len(functions)) if display_count < len(functions): print(f'Displaying first {display_count} functions:') for i, func in enumerate(functions[:display_count], 1): print( f' [{i:2d}] {func.name:30} | ' f'Start: 0x{func.start_ea:08x} | ' f'End: 0x{func.end_ea:08x} | ' f'Size: {func.size}' ) if display_count < len(functions): print(f' ... and {len(functions) - display_count} more functions') def traverse_entries(db: ida_domain.Database) -> None: """ Traverse and display program entries. Args: db: The IDA database instance """ print_section_header('PROGRAM ENTRIES') entries = list(db.entries.get_all()) print(f'Total entries: {len(entries)}') for i, entry in enumerate(entries, 1): print( f' [{i:2d}] {entry.name:30} | ' f'Address: 0x{entry.address:08x} | ' f'Ordinal: {entry.ordinal}' ) def traverse_heads(db: ida_domain.Database) -> None: """ Traverse and display heads (data and code locations). Args: db: The IDA database instance """ print_section_header('HEADS (Data/Code Locations)') heads = list(db.heads.get_all()) print(f'Total heads: {len(heads)}') # Show first 20 heads to avoid overwhelming output display_count = min(20, len(heads)) if display_count < len(heads): print(f'Displaying first {display_count} heads:') for i, head in enumerate(heads[:display_count], 1): print(f' [{i:2d}] Address: 0x{head:08x}') if display_count < len(heads): print(f' ... and {len(heads) - display_count} more heads') def traverse_strings(db: ida_domain.Database) -> None: """ Traverse and display identified strings. Args: db: The IDA database instance """ print_section_header('STRINGS') strings = list(db.strings.get_all()) print(f'Total strings: {len(strings)}') # Show first 15 strings to avoid overwhelming output display_count = min(15, len(strings)) if display_count < len(strings): print(f'Displaying first {display_count} strings:') for i, (ea, content) in enumerate(strings[:display_count], 1): # Truncate very long strings for display display_str = content[:50] + '...' if len(content) > 50 else content print(f' [{i:2d}] 0x{ea:08x}: "{display_str}"') if display_count < len(strings): print(f' ... and {len(strings) - display_count} more strings') def traverse_names(db: ida_domain.Database) -> None: """ Traverse and display names (symbols and labels). Args: db: The IDA database instance """ print_section_header('NAMES (Symbols & Labels)') names = list(db.names.get_all()) print(f'Total names: {len(names)}') # Show first 20 names to avoid overwhelming output display_count = min(20, len(names)) if display_count < len(names): print(f'Displaying first {display_count} names:') for i, (ea, name) in enumerate(names[:display_count], 1): print(f' [{i:2d}] 0x{ea:08x}: {name}') if display_count < len(names): print(f' ... and {len(names) - display_count} more names') def traverse_types(db: ida_domain.Database) -> None: """ Traverse and display type definitions. Args: db: The IDA database instance """ print_section_header('TYPE DEFINITIONS') types = list(db.types.get_all()) print(f'Total types: {len(types)}') # Show first 15 types to avoid overwhelming output display_count = min(15, len(types)) if display_count < len(types): print(f'Displaying first {display_count} types:') for i, type_def in enumerate(types[:display_count], 1): type_name = type_def.name if type_def.name else f'' print(f' [{i:2d}] {type_name:30} | TID: {type_def.get_tid()}') if display_count < len(types): print(f' ... and {len(types) - display_count} more types') def traverse_comments(db: ida_domain.Database) -> None: """ Traverse and display comments. Args: db: The IDA database instance """ print_section_header('COMMENTS') # Get all comments (regular and repeatable) comments = list(db.comments.get_all()) print(f'Total comments: {len(comments)}') # Show first 10 comments to avoid overwhelming output display_count = min(10, len(comments)) if display_count < len(comments): print(f'Displaying first {display_count} comments:') for i, (ea, comment_text, is_repeatable) in enumerate(comments[:display_count], 1): # Truncate very long comments for display display_comment = comment_text[:60] + '...' if len(comment_text) > 60 else comment_text comment_type = 'REP' if is_repeatable else 'REG' print(f' [{i:2d}] 0x{ea:08x} [{comment_type}]: {display_comment}') if display_count < len(comments): print(f' ... and {len(comments) - display_count} more comments') def traverse_basic_blocks(db: ida_domain.Database) -> None: """ Traverse and display basic blocks. Args: db: The IDA database instance """ print_section_header('BASIC BLOCKS') basic_blocks = list(db.basic_blocks.get_between(db.minimum_ea, db.maximum_ea)) print(f'Total basic blocks: {len(basic_blocks)}') # Show first 15 basic blocks to avoid overwhelming output display_count = min(15, len(basic_blocks)) if display_count < len(basic_blocks): print(f'Displaying first {display_count} basic blocks:') for i, bb in enumerate(basic_blocks[:display_count], 1): print(f' [{i:2d}] Start: 0x{bb.start_ea:08x} | End: 0x{bb.end_ea:08x} | Size: {bb.size}') if display_count < len(basic_blocks): print(f' ... and {len(basic_blocks) - display_count} more basic blocks') def traverse_instructions(db: ida_domain.Database) -> None: """ Traverse and display instructions with disassembly. Args: db: The IDA database instance """ print_section_header('INSTRUCTIONS') instructions = list(db.instructions.get_between(db.minimum_ea, db.maximum_ea)) print(f'Total instructions: {len(instructions)}') # Show first 20 instructions to avoid overwhelming output display_count = min(20, len(instructions)) if display_count < len(instructions): print(f'Displaying first {display_count} instructions:') for i, inst in enumerate(instructions[:display_count], 1): disasm = db.instructions.get_disassembly(inst) if disasm: print(f' [{i:2d}] 0x{inst.ea:08x}: {disasm}') else: print(f' [{i:2d}] 0x{inst.ea:08x}: ') if display_count < len(instructions): print(f' ... and {len(instructions) - display_count} more instructions') def traverse_cross_references(db: ida_domain.Database) -> None: """ Traverse and display cross-references. Args: db: The IDA database instance """ print_section_header('CROSS-REFERENCES') # Get a sample of addresses to check for cross-references sample_addresses = [] # Add function start addresses functions = list(db.functions.get_all()) sample_addresses.extend([f.start_ea for f in functions[:5]]) # Add some heads heads = list(db.heads.get_all()) sample_addresses.extend(heads[:5]) xref_count = 0 print('Sample cross-references:') for addr in sample_addresses[:10]: # Limit to first 10 addresses xrefs_to = list(db.xrefs.get_to(addr)) xrefs_from = list(db.xrefs.get_from(addr)) if xrefs_to or xrefs_from: print(f' Address 0x{addr:08x}:') for xref in xrefs_to[:3]: # Show max 3 xrefs to type_name = db.xrefs.get_ref_type_name(xref.type) print(f' <- FROM 0x{xref.frm:08x} (type: {type_name})') xref_count += 1 for xref in xrefs_from[:3]: # Show max 3 xrefs from type_name = db.xrefs.get_ref_type_name(xref.type) print(f' -> TO 0x{xref.to:08x} (type: {type_name})') xref_count += 1 print(f'Total cross-references displayed: {xref_count}') def traverse_database(db_path: str): """ Main function to traverse the entire IDA database and display all entities. Args: db_path: Path to the binary file to analyze """ print_section_header('IDA DOMAIN DATABASE TRAVERSAL', '=') print(f'Analyzing file: {db_path}') # Configure IDA options for analysis ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) # Create and open database db = ida_domain.Database() db.open(db_path, ida_options) # Traverse all database entities in logical order traverse_metadata(db) traverse_segments(db) traverse_functions(db) traverse_entries(db) traverse_heads(db) traverse_strings(db) traverse_names(db) traverse_types(db) traverse_comments(db) traverse_basic_blocks(db) traverse_instructions(db) traverse_cross_references(db) print_section_header('TRAVERSAL COMPLETE', '=') db.close(save=False) def main(): """Main entry point with argument parsing.""" parser = argparse.ArgumentParser(description='IDA Database Traversal Example') parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) args = parser.parse_args() traverse_database(args.input_file) if __name__ == '__main__': main() ``` ## Function Analysis ### Finding and Analyzing Functions ``` #!/usr/bin/env python3 """ Function analysis example for IDA Domain API. This example demonstrates how to find and analyze functions in an IDA database. """ import argparse import ida_domain def analyze_functions(db_path, pattern='main', max_results=10): """Find and analyze functions matching a pattern.""" ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) db = ida_domain.Database() if db.open(db_path, ida_options): functions = db.functions # Find functions matching a pattern matching_functions = [] for func in functions.get_all(): func_name = functions.get_name(func) if pattern.lower() in func_name.lower(): matching_functions.append((func, func_name)) print(f"Found {len(matching_functions)} functions matching '{pattern}':") # Limit results if requested display_functions = ( matching_functions[:max_results] if max_results > 0 else matching_functions ) for func, name in display_functions: print(f'\nFunction: {name}') print(f'Address: {hex(func.start_ea)} - {hex(func.end_ea)}') # Get signature signature = functions.get_signature(func) print(f'Signature: {signature}') # Get basic blocks bb_count = 0 for _ in functions.get_basic_blocks(func): bb_count += 1 print(f'Basic blocks: {bb_count}') # Show first few lines of disassembly disasm = functions.get_disassembly(func) print('Disassembly (first 5 lines):') for line in disasm[:5]: print(f' {line}') if max_results > 0 and len(matching_functions) > max_results: print(f'\n... (showing first {max_results} of {len(matching_functions)} matches)') db.close(save=False) def main(): """Main entry point with argument parsing.""" parser = argparse.ArgumentParser(description='Database exploration example') parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) parser.add_argument( '-p', '--pattern', default='main', help='Pattern to search for in function names (default: main)', ) parser.add_argument( '-m', '--max-results', type=int, default=10, help='Maximum number of results to display (0 for all, default: 10)', ) args = parser.parse_args() analyze_functions(args.input_file, args.pattern, args.max_results) if __name__ == '__main__': main() ``` ## Signature Files ### Working with FLIRT signature files ``` #!/usr/bin/env python3 """ Using FLIRT signature files example in IDA Domain API. This example demonstrates how to work with signature files: - how to evaluate the matches on your binary - how to actually apply a sig file - how to generate .sig/.pat from your loaded binary - how to use custom signature directories """ import argparse from pathlib import Path import ida_domain from ida_domain.signature_files import FileInfo def probe_signature_files(db: ida_domain.Database, min_matches: int, custom_dir: str = None): """Probe signature files and collect the ones over the minimum number of matches.""" print('Probing signature files...') directories = [Path(custom_dir)] if custom_dir else None files = db.signature_files.get_files(directories=directories) good_matches = [] for sig_file in files: results = db.signature_files.apply(sig_file, probe_only=True) for result in results: if result.matches >= min_matches: good_matches.append(result) print(f'{sig_file.name}: {result.matches} matches') return good_matches def apply_signature_files(db: ida_domain.Database, matches: list[FileInfo], min_matches: int): """Apply signature files over the minimum number of matches.""" if not matches: return print('\nApplying signature files...') for result in matches: if result.matches >= min_matches: sig_path = Path(result.path) print(f'Applying {sig_path.name}') db.signature_files.apply(sig_path, probe_only=False) def generate_signatures(db: ida_domain.Database): """Generate signature files from current database.""" print('\nGenerating signatures...') produced_files = db.signature_files.create() if produced_files: for file_path in produced_files: print(f'Generated: {Path(file_path).name}') def main(): """Main entry point.""" parser = argparse.ArgumentParser(description='FLIRT signature files example') parser.add_argument('-f', '--input-file', required=True, help='Binary file to analyze') parser.add_argument('-d', '--sig-dir', help='Directory where to look for signature files') parser.add_argument('-p', '--min-probe-matches', default=5, type=int) parser.add_argument('-a', '--min-apply-matches', default=10, type=int) args = parser.parse_args() ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) db = ida_domain.Database() if db.open(args.input_file, ida_options): matches = probe_signature_files(db, args.min_probe_matches, args.sig_dir) apply_signature_files(db, matches, args.min_apply_matches) generate_signatures(db) db.close(False) if __name__ == '__main__': main() ``` ## String Analysis ### Finding and Analyzing Strings ``` #!/usr/bin/env python3 """ String analysis example for IDA Domain API. This example demonstrates how to find and analyze strings in an IDA database. """ import argparse import ida_domain def analyze_strings(db_path, min_length=5, max_display=20, show_interesting=True): """Find and analyze strings in the database.""" ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) db = ida_domain.Database() if db.open(db_path, ida_options): strings = db.strings print(f'Analyzing strings (minimum length: {min_length}):') # Collect all strings all_strings = [] interesting_strings = [] for addr, string_value in strings.get_all(): if len(string_value) >= min_length: all_strings.append((addr, string_value)) # Check for interesting keywords if show_interesting: lower_str = string_value.lower() interesting_keywords = [ 'password', 'passwd', 'pwd', 'key', 'secret', 'token', 'api', 'username', 'user', 'login', 'config', 'settings', 'registry', 'file', 'path', 'directory', 'http', 'https', 'ftp', 'url', 'sql', 'database', 'query', ] if any(keyword in lower_str for keyword in interesting_keywords): interesting_strings.append((addr, string_value)) print(f'Total strings found: {strings.get_count()}') print(f'Strings >= {min_length} chars: {len(all_strings)}') # Display regular strings print(f'\nFirst {max_display} strings:') for i, (addr, string_value) in enumerate(all_strings[:max_display]): print(f'{hex(addr)}: {repr(string_value)}') if len(all_strings) > max_display: print(f'... (showing first {max_display} of {len(all_strings)} strings)') # Display interesting strings if show_interesting and interesting_strings: print(f'\nInteresting strings found ({len(interesting_strings)}):') for addr, string_value in interesting_strings[:10]: # Limit to 10 print(f'{hex(addr)}: {repr(string_value)}') if len(interesting_strings) > 10: print(f'... (showing first 10 of {len(interesting_strings)} interesting strings)') db.close(save=False) def main(): """Main entry point with argument parsing.""" parser = argparse.ArgumentParser(description='Database exploration example') parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) parser.add_argument( '-l', '--min-length', type=int, default=5, help='Minimum string length(default: 5)' ) parser.add_argument( '-m', '--max-display', type=int, default=20, help='Maximum displayed strings (default: 20)' ) parser.add_argument( '-s', '--show-interesting', type=bool, default=True, help='Highlight interesting strings (default True)', ) args = parser.parse_args() analyze_strings(args.input_file, args.min_length, args.max_display, args.show_interesting) if __name__ == '__main__': main() ``` ## Bytes Analysis ### Analyzing and Manipulating Bytes ``` #!/usr/bin/env python3 """ Byte analysis example for IDA Domain API. This example demonstrates how to analyze, search, and manipulate bytes in an IDA database. It showcases the comprehensive byte manipulation capabilities including data type operations, patching, flag checking, and search functionality. """ import argparse import ida_domain from ida_domain.bytes import ByteFlags, SearchFlags, StringType def analyze_bytes(db_path, search_pattern=None, patch_demo=False, max_results=20): """Analyze and manipulate bytes in the database.""" ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) db = ida_domain.Database() if db.open(db_path, ida_options): bytes_handler = db.bytes print('=== IDA Domain Bytes Analysis ===\n') # 1. Basic byte reading operations print('1. Basic Byte Reading Operations:') print('-' * 40) # Read different data types from entry point entry_point = db.minimum_ea print(f'Entry point: {hex(entry_point)}') byte_val = bytes_handler.get_byte(entry_point) word_val = bytes_handler.get_word(entry_point) dword_val = bytes_handler.get_dword(entry_point) qword_val = bytes_handler.get_qword(entry_point) print(f' Byte: 0x{byte_val:02x} ({byte_val})') print(f' Word: 0x{word_val:04x} ({word_val})') print(f' DWord: 0x{dword_val:08x} ({dword_val})') print(f' QWord: 0x{qword_val:016x} ({qword_val})') # Get disassembly disasm = bytes_handler.get_disassembly(entry_point) print(f' Disassembly: {disasm}') # 2. Data type analysis using flags print('\n2. Data Type Analysis:') print('-' * 40) # Analyze different addresses test_addresses = [entry_point, entry_point + 0x10, entry_point + 0x20] for addr in test_addresses: if addr <= db.maximum_ea: flags = bytes_handler.get_flags(addr) data_type = bytes_handler.get_data_type(addr) data_size = bytes_handler.get_data_size(addr) # Use new flag checking methods is_code = bytes_handler.check_flags(addr, ByteFlags.CODE) is_data = bytes_handler.check_flags(addr, ByteFlags.DATA) has_any_data_flags = bytes_handler.has_any_flags( addr, ByteFlags.BYTE | ByteFlags.WORD | ByteFlags.DWORD ) print(f' Address {hex(addr)}:') print(f' Type: {data_type}, Size: {data_size}') print(f' Flags: 0x{flags:x}') print(f' Is Code: {is_code}, Is Data: {is_data}') print(f' Has Data Flags: {has_any_data_flags}') # 3. Search operations print('\n3. Search Operations:') print('-' * 40) # Search for common patterns patterns_to_search = [ (b'\x48\x89\xe5', 'Function prologue (mov rbp, rsp)'), (b'\x55', 'Push rbp'), (b'\xc3', 'Return instruction'), ] for pattern, description in patterns_to_search: found_addr = bytes_handler.find_bytes(pattern) if found_addr: print(f' Found {description} at {hex(found_addr)}') else: print(f' {description} not found') # Text search with flags if search_pattern: print(f"\n Searching for text: '{search_pattern}'") # Case-sensitive search addr_case = bytes_handler.find_text( search_pattern, flags=SearchFlags.DOWN | SearchFlags.CASE ) # Case-insensitive search addr_nocase = bytes_handler.find_text(search_pattern, flags=SearchFlags.DOWN) if addr_case: print(f' Case-sensitive found at: {hex(addr_case)}') if addr_nocase and addr_nocase != addr_case: print(f' Case-insensitive found at: {hex(addr_nocase)}') if not addr_case and not addr_nocase: print(f" Text '{search_pattern}' not found") # Search for immediate values immediate_addr = bytes_handler.find_immediate(1) if immediate_addr is not None: print(f' Found immediate value 1 at {hex(immediate_addr)}') # 4. String operations print('\n4. String Operations:') print('-' * 40) # Find and analyze strings string_count = 0 for addr, string_val in db.strings.get_all(): if string_count >= 3: # Limit output break print(f' String at {hex(addr)}: {repr(string_val)}') # Try different string reading methods success, cstring = bytes_handler.get_cstring(addr) if success: print(f' C-string: {repr(cstring)}') success, unicode_str = bytes_handler.get_unicode_string(addr) if success: print(f' Unicode: {repr(unicode_str)}') string_count += 1 # 5. Data type creation print('\n5. Data Type Creation:') print('-' * 40) # Find a suitable data address for demonstration data_addr = None for addr in range(db.minimum_ea, min(db.minimum_ea + 0x100, db.maximum_ea), 4): if bytes_handler.is_data(addr) or bytes_handler.is_unknown(addr): data_addr = addr break if data_addr: print(f' Working with data at {hex(data_addr)}') # Create different data types original_type = bytes_handler.get_data_type(data_addr) print(f' Original type: {original_type}') # Make it a byte if bytes_handler.make_byte(data_addr): print(f' Successfully created byte at {hex(data_addr)}') # Make it a word if bytes_handler.make_word(data_addr): print(f' Successfully created word at {hex(data_addr)}') # Create a string with specific type string_addr = data_addr + 8 if bytes_handler.make_string(string_addr, string_type=StringType.C): print(f' Successfully created C-string at {hex(string_addr)}') # 6. Patching demonstration (if requested) if patch_demo: print('\n6. Patching Demonstration:') print('-' * 40) # Find a safe address to patch (data section) patch_addr = None for addr in range(db.minimum_ea, min(db.minimum_ea + 0x200, db.maximum_ea)): if bytes_handler.is_data(addr): patch_addr = addr break if patch_addr: print(f' Demonstrating patching at {hex(patch_addr)}') # Get original values orig_byte = bytes_handler.get_byte(patch_addr) orig_word = bytes_handler.get_word(patch_addr) print(f' Original byte: 0x{orig_byte:02x}') print(f' Original word: 0x{orig_word:04x}') # Patch byte if bytes_handler.patch_byte(patch_addr, 0xAB): new_byte = bytes_handler.get_byte(patch_addr) print(f' Patched byte: 0x{new_byte:02x}') # Get original value retrieved_orig = bytes_handler.get_original_byte(patch_addr) print(f' Retrieved original: 0x{retrieved_orig:02x}') # Revert patch if bytes_handler.revert_byte(patch_addr): reverted_byte = bytes_handler.get_byte(patch_addr) print(f' Reverted byte: 0x{reverted_byte:02x}') # Patch multiple bytes test_data = b'\x90\x90\x90\x90' # NOP instructions if bytes_handler.patch_bytes(patch_addr, test_data): print(f' Patched {len(test_data)} bytes with NOPs') # Get original bytes success, orig_bytes = bytes_handler.get_original_bytes( patch_addr, len(test_data) ) if success: print(f' Original bytes: {orig_bytes.hex()}') # 7. Navigation helpers print('\n7. Navigation Helpers:') print('-' * 40) test_addr = entry_point + 0x10 if test_addr <= db.maximum_ea: next_head = bytes_handler.next_head(test_addr) prev_head = bytes_handler.prev_head(test_addr) next_addr = bytes_handler.next_addr(test_addr) prev_addr = bytes_handler.prev_addr(test_addr) print(f' From address {hex(test_addr)}:') print( f' Next head: {hex(next_head) if next_head != 0xFFFFFFFFFFFFFFFF else "None"}' ) print( f' Prev head: {hex(prev_head) if prev_head != 0xFFFFFFFFFFFFFFFF else "None"}' ) print(f' Next addr: {hex(next_addr)}') print(f' Prev addr: {hex(prev_addr)}') # 8. Summary statistics print('\n8. Summary Statistics:') print('-' * 40) code_count = data_count = unknown_count = 0 sample_size = db.maximum_ea - db.minimum_ea for addr in range(db.minimum_ea, db.minimum_ea + sample_size): if bytes_handler.is_code(addr): code_count += 1 elif bytes_handler.is_data(addr): data_count += 1 elif bytes_handler.is_unknown(addr): unknown_count += 1 print(f' Sample size: {sample_size} bytes') print(f' Code bytes: {code_count} ({code_count / sample_size * 100:.1f}%)') print(f' Data bytes: {data_count} ({data_count / sample_size * 100:.1f}%)') print(f' Unknown bytes: {unknown_count} ({unknown_count / sample_size * 100:.1f}%)') print('\n=== Analysis Complete ===') db.close(save=False) def main(): """Main entry point with argument parsing.""" parser = argparse.ArgumentParser(description='Byte analysis example for IDA Domain API') parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) parser.add_argument( '-s', '--search-pattern', help='Text pattern to search for in the binary', type=str, default=None, ) parser.add_argument( '-p', '--patch-demo', action='store_true', help='Demonstrate patching operations (modifies database temporarily)', ) parser.add_argument( '-m', '--max-results', type=int, default=20, help='Maximum number of results to display (default: 20)', ) args = parser.parse_args() analyze_bytes(args.input_file, args.search_pattern, args.patch_demo, args.max_results) if __name__ == '__main__': main() ``` ## Type Analysis ### Analyzing and Working with Types ``` #!/usr/bin/env python3 """ Types example for IDA Domain API. This example demonstrates how list all existing types from an IDA database. """ import argparse from pathlib import Path import ida_domain parser = argparse.ArgumentParser( description='IDA Domain usage example, version {ida_domain.VersionInfo.api_version}' ) parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) args = parser.parse_args() example_til_path = (Path(__file__).parent.parent / 'tests' / 'resources' / 'example.til').resolve() db = ida_domain.Database() if db.open(args.input_file): # Iterate names from external til for name in db.types.get_names(str(example_til_path)): print(name) # Iterate names from local til for name in db.types.get_names(): print(name) # Iterate named types from external til for type_info in db.types.get_all(ida_domain.types.TypeKind.NAMED, str(example_til_path)): print(f'{type_info.get_type_name()}') # Iterate named types from local til for type_info in db.types.get_all(): print(f'{type_info.get_type_name()}') # Iterate ordinal types for type_info in db.types.get_all(ida_domain.types.TypeKind.NUMBERED): print(f'{type_info.get_type_name()}') db.close(False) ``` ## Cross-Reference Analysis ### Analyzing Cross-References ``` #!/usr/bin/env python3 """ Cross-reference analysis example for IDA Domain API. This example demonstrates how to analyze cross-references in an IDA database. """ import argparse import ida_domain def analyze_xrefs(db_path, target_addr): """Analyze cross-references to and from a target address.""" ida_options = ida_domain.Database.IdaCommandBuilder().auto_analysis(True).new_database(True) db = ida_domain.Database() if db.open(db_path, ida_options): print(f'Cross-references to {hex(target_addr)}:') # Get references TO the target address xref_to_count = 0 for xref in db.xrefs.get_to(target_addr): xref_type_name = db.xrefs.get_name(xref) print(f' From {hex(xref.frm)} to {hex(xref.to)} (type: {xref_type_name})') xref_to_count += 1 if xref_to_count == 0: print(' No cross-references found') else: print(f' Total: {xref_to_count} references') print(f'\nCross-references from {hex(target_addr)}:') # Get references FROM the target address xref_from_count = 0 for xref in db.xrefs.get_from(target_addr): xref_type_name = db.xrefs.get_name(xref) print(f' From {hex(xref.frm)} to {hex(xref.to)} (type: {xref_type_name})') xref_from_count += 1 if xref_from_count == 0: print(' No outgoing references found') else: print(f' Total: {xref_from_count} outgoing references') # Use convenience methods for specific xref types call_count = sum(1 for _ in db.xrefs.get_calls_to(target_addr)) jump_count = sum(1 for _ in db.xrefs.get_jumps_to(target_addr)) read_count = sum(1 for _ in db.xrefs.get_data_reads_of(target_addr)) write_count = sum(1 for _ in db.xrefs.get_data_writes_to(target_addr)) # Summary print(f'\nSummary for {hex(target_addr)}:') print(f' Calls to address: {call_count}') print(f' Jumps to address: {jump_count}') print(f' Data reads to address: {read_count}') print(f' Data writes to address: {write_count}') print(f' Incoming references: {xref_to_count}') print(f' Outgoing references: {xref_from_count}') db.close(save=False) def parse_address(value): """Parse address as either decimal or hexadecimal""" try: if value.lower().startswith('0x'): return int(value, 16) else: return int(value, 10) except ValueError: raise argparse.ArgumentTypeError(f'Invalid address format: {value}') def main(): """Main entry point with argument parsing.""" parser = argparse.ArgumentParser(description='Database exploration example') parser.add_argument( '-f', '--input-file', help='Binary input file to be loaded', type=str, required=True ) parser.add_argument( '-a', '--address', help='Address (decimal or hex with 0x prefix)', type=parse_address, required=True, ) args = parser.parse_args() analyze_xrefs(args.input_file, args.address) if __name__ == '__main__': main() ``` ## Running the Examples To run these examples, save them to Python files and execute them with your IDA database path: ``` python example_script.py ``` Make sure you have: 1. Set the `IDADIR` environment variable 1. Installed the ida-domain package # Getting Started This guide will take you from nothing to a working first script with the IDA Domain API. ## Prerequisites - **Python 3.9 or higher** - **IDA Pro 9.0 or higher** ## Installation ### Step 1: Set up IDA SDK Access The IDA Domain API needs access to the IDA SDK. Choose one of these options: **Option A: Set IDADIR Environment Variable** Point to your IDA installation directory: ``` export IDADIR="/Applications/IDA Professional 9.2.app/Contents/MacOS/" ``` ``` export IDADIR="/opt/ida-9.2/" ``` ``` set IDADIR="C:\Program Files\IDA Professional 9.2\" ``` To make this permanent, add the export command to your shell profile (`~/.bashrc`, `~/.zshrc`, etc.). **Option B: Use idapro Python Package** If you already have the `idapro` Python package configured, skip setting `IDADIR`. ### Step 2: Install the Package For a clean environment, use a virtual environment: ``` # Create and activate virtual environment python -m venv ida-env source ida-env/bin/activate # On Windows: ida-env\Scripts\activate # Install the package pip install ida-domain ``` ### Step 3: Verify Installation ``` # test_install.py try: from ida_domain import Database print("✓ Installation successful!") except ImportError as e: print(f"✗ Installation failed: {e}") ``` ## Your First Script Create a simple script to explore an IDA database: ``` # my_first_script.py import argparse from ida_domain import Database def explore_database(db_path): # Create and open database db = Database() if not db.open(db_path): print(f'Failed to open: {db_path}') return # Basic database info print(f'✓ Opened: {db_path}') print(f' Architecture: {db.architecture}') print(f' Entry point: {hex(db.entries.get_at_index(0).address)}') print(f' Address range: {hex(db.minimum_ea)} - {hex(db.maximum_ea)}') # Count functions func_count = len(list(db.functions.get_all())) print(f' Functions: {func_count}') # Count strings string_count = len(list(db.strings.get_all())) print(f' Strings: {string_count}') # Clean up db.close(save=False) print('✓ Database closed') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-f', '--input-file', type=str, required=True) args = parser.parse_args() # Run with your IDA input file explore_database(args.input_file) ``` **To run this script:** Run: `python my_first_script.py -f ` **Expected output:** ``` ✓ Opened: /path/to/sample.idb Architecture: x86_64 Entry point: 0x1000 Address range: 0x1000 - 0x2000 Functions: 42 Strings: 15 ✓ Database closed ``` ## Troubleshooting **ImportError: No module named 'ida_domain'** - Run `pip install ida-domain` - Check you're in the correct virtual environment **IDA SDK not found** - Verify `IDADIR` is set: `echo $IDADIR` - Ensure the path points to your actual IDA installation **Database won't open** - Check the file path exists - Ensure the database was created with IDA Pro 9.0+ ## Next Steps 1. **[Examples](../examples/)** - Complete examples for real-world tasks 1. **[API Reference](../usage/)** - Detailed API documentation 1. **Start your project** - Apply these concepts to your reverse engineering work! # API Reference # `Basic Blocks` ## basic_blocks Classes: - **`BasicBlocks`** – Interface for working with basic blocks in functions. ### BasicBlocks ``` BasicBlocks(database: 'Database') ``` Interface for working with basic blocks in functions. Basic blocks are sequences of instructions with a single entry point and single exit point, used for control flow analysis and optimization. Constructs a basic block handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`get_between`** – Retrieves the basic blocks within a given address range. - **`get_from_function`** – Retrieves the basic blocks within a given function. - **`get_instructions`** – Retrieves the instructions within a given basic block. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### get_between ``` get_between(start: 'ea_t', end: 'ea_t', flags=0) ``` Retrieves the basic blocks within a given address range. Args: start: The start address of the range. end: The end address of the range. flags: Optional qflow_chart_t flags for flowchart generation (default: 0). Returns: An iterable flowchart containing the basic blocks within the specified range. #### get_from_function ``` get_from_function(func: 'func_t', flags=0) ``` Retrieves the basic blocks within a given function. Args: func: The function to retrieve basic blocks from. flags: Optional qflow_chart_t flags for flowchart generation (default: 0). Returns: An iterable flowchart containing the basic blocks of the function. #### get_instructions ``` get_instructions(block: 'qbasic_block_t') ``` Retrieves the instructions within a given basic block. Args: block: The basic block to analyze. Returns: An instruction iterator for the block. Returns an empty iterator if the block is invalid. # `Bytes` ## bytes Classes: - **`ByteFlags`** – Byte flag constants for flag checking operations. - **`Bytes`** – Handles operations related to raw data access from the IDA database. - **`DataTypeFlags`** – Data type flags for creating data items. - **`SearchFlags`** – Search flags for text and pattern searching. - **`StringType`** – String type constants for string operations. ### ByteFlags Bases: `IntEnum` Byte flag constants for flag checking operations. Attributes: - **`ALIGN`** – - **`BYTE`** – - **`CODE`** – - **`COMM`** – - **`DATA`** – - **`DOUBLE`** – - **`DWORD`** – - **`FLOAT`** – - **`FLOW`** – - **`LABL`** – - **`LINE`** – - **`NAME`** – - **`QWORD`** – - **`REF`** – - **`STRLIT`** – - **`STRUCT`** – - **`TAIL`** – - **`UNK`** – - **`WORD`** – #### ALIGN ``` ALIGN = FF_ALIGN ``` #### BYTE ``` BYTE = FF_BYTE ``` #### CODE ``` CODE = FF_CODE ``` #### COMM ``` COMM = FF_COMM ``` #### DATA ``` DATA = FF_DATA ``` #### DOUBLE ``` DOUBLE = FF_DOUBLE ``` #### DWORD ``` DWORD = FF_DWORD ``` #### FLOAT ``` FLOAT = FF_FLOAT ``` #### FLOW ``` FLOW = FF_FLOW ``` #### LABL ``` LABL = FF_LABL ``` #### LINE ``` LINE = FF_LINE ``` #### NAME ``` NAME = FF_NAME ``` #### QWORD ``` QWORD = FF_QWORD ``` #### REF ``` REF = FF_REF ``` #### STRLIT ``` STRLIT = FF_STRLIT ``` #### STRUCT ``` STRUCT = FF_STRUCT ``` #### TAIL ``` TAIL = FF_TAIL ``` #### UNK ``` UNK = FF_UNK ``` #### WORD ``` WORD = FF_WORD ``` ### Bytes ``` Bytes(database: 'Database') ``` Handles operations related to raw data access from the IDA database. This class provides methods to read various data types (bytes, words, floats, etc.) from memory addresses in the disassembled binary. Constructs a bytes handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`check_flags`** – Checks if the specified flags are set at the given address. - **`find_bytes`** – Finds a byte pattern in memory. - **`find_immediate`** – Finds an immediate value in instructions. - **`find_text`** – Finds a text string in memory. - **`get_byte`** – Retrieves a single byte (8 bits) at the specified address. - **`get_cstring`** – Gets a C-style null-terminated string. - **`get_data_size`** – Gets the size of the data item at the specified address. - **`get_data_type`** – Gets the data type at the specified address. - **`get_data_type_from_flags`** – Gets the data type string from flags using ByteFlags enum. - **`get_disassembly`** – Retrieves the disassembly text at the specified address. - **`get_double`** – Retrieves a double-precision floating-point value at the specified address. - **`get_dword`** – Retrieves a double word (32 bits/4 bytes) at the specified address. - **`get_flags`** – Gets the flags for the specified address. - **`get_float`** – Retrieves a single-precision floating-point value at the specified address. - **`get_original_byte`** – Get original byte value (that was before patching). - **`get_original_bytes`** – Gets the original bytes before any patches by reading individual bytes. - **`get_original_dword`** – Get original dword value (that was before patching). - **`get_original_qword`** – Get original qword value (that was before patching). - **`get_original_word`** – Get original word value (that was before patching). - **`get_qword`** – Retrieves a quad word (64 bits/8 bytes) at the specified address. - **`get_string`** – Gets a string from the specified address. - **`get_unicode_string`** – Gets a Unicode string from the specified address. - **`get_word`** – Retrieves a word (16 bits/2 bytes) at the specified address. - **`has_any_flags`** – Checks if any of the specified flags are set at the given address. - **`has_user_name`** – Checks if the address has a user-defined name. - **`is_code`** – Checks if the address contains code. - **`is_data`** – Checks if the address contains data. - **`is_head`** – Checks if the address is the start of a data item. - **`is_tail`** – Checks if the address is part of a multi-byte data item. - **`is_unknown`** – Checks if the address contains unknown/undefined data. - **`make_array`** – Converts data at address to array type. - **`make_byte`** – Converts data at address to byte type. - **`make_dword`** – Converts data at address to double word type. - **`make_qword`** – Converts data at address to quad word type. - **`make_string`** – Converts data at address to string type. - **`make_word`** – Converts data at address to word type. - **`next_addr`** – Gets the next valid address after the specified address. - **`next_head`** – Gets the next head (start of data item) after the specified address. - **`patch_byte`** – Patch a byte of the program. - **`patch_bytes`** – Patch the specified number of bytes of the program. - **`patch_dword`** – Patch a dword of the program. - **`patch_qword`** – Patch a qword of the program. - **`patch_word`** – Patch a word of the program. - **`prev_addr`** – Gets the previous valid address before the specified address. - **`prev_head`** – Gets the previous head (start of data item) before the specified address. - **`revert_byte`** – Revert patched byte to its original value. - **`set_byte`** – Sets a byte value at the specified address. - **`set_bytes`** – Sets a sequence of bytes at the specified address. - **`set_dword`** – Sets a double word (4 bytes) value at the specified address. - **`set_flags`** – Sets the flags for the specified address. - **`set_qword`** – Sets a quad word (8 bytes) value at the specified address. - **`set_word`** – Sets a word (2 bytes) value at the specified address. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### check_flags ``` check_flags(ea: ea_t, flag_mask: ByteFlags) -> bool ``` Checks if the specified flags are set at the given address. Args: ea: The effective address. flag_mask: ByteFlags enum value(s) to check. Returns: True if all specified flags are set, False otherwise. #### find_bytes ``` find_bytes( pattern: bytes, start_ea: ea_t = None, end_ea: ea_t = None, ) -> ea_t | None ``` Finds a byte pattern in memory. Args: pattern: Byte pattern to search for. start_ea: Start address for search. end_ea: End address for search. Returns: Address where pattern was found, or None if not found. #### find_immediate ``` find_immediate( value: int, start_ea: ea_t = None, end_ea: ea_t = None ) -> ea_t | None ``` Finds an immediate value in instructions. Args: value: Immediate value to search for. start_ea: Start address for search. end_ea: End address for search. Returns: Address where immediate was found, or None if not found. #### find_text ``` find_text( text: str, start_ea: ea_t = None, end_ea: ea_t = None, flags: SearchFlags = DOWN, ) -> ea_t | None ``` Finds a text string in memory. Args: text: Text to search for. start_ea: Start address for search. end_ea: End address for search. flags: Search flags (default: SearchFlags.DOWN). Returns: Address where text was found, or None if not found. #### get_byte ``` get_byte(ea: ea_t) -> int | None ``` Retrieves a single byte (8 bits) at the specified address. Args: ea: The effective address. Returns: The byte value (0-255), or None if an error occurs. #### get_cstring ``` get_cstring( ea: ea_t, max_length: int = 1024 ) -> Tuple[bool, str] ``` Gets a C-style null-terminated string. Args: ea: The effective address. max_length: Maximum string length to read (default: 1024). Returns: A pair of (success flag, string). #### get_data_size ``` get_data_size(ea: ea_t) -> int ``` Gets the size of the data item at the specified address. Args: ea: The effective address. Returns: Size of the data item in bytes. #### get_data_type ``` get_data_type(ea: ea_t) -> str ``` Gets the data type at the specified address. Args: ea: The effective address. Returns: String representation of the data type. #### get_data_type_from_flags ``` get_data_type_from_flags(flags: int) -> str ``` Gets the data type string from flags using ByteFlags enum. Args: flags: Flags value to analyze. Returns: String representation of the data type. #### get_disassembly ``` get_disassembly(ea: ea_t) -> str | None ``` Retrieves the disassembly text at the specified address. Args: ea: The effective address. Returns: The disassembly string, or None if an error occurs. #### get_double ``` get_double(ea: ea_t) -> float | None ``` Retrieves a double-precision floating-point value at the specified address. Args: ea: The effective address. Returns: The double value, or None if an error occurs. #### get_dword ``` get_dword(ea: ea_t) -> int | None ``` Retrieves a double word (32 bits/4 bytes) at the specified address. Args: ea: The effective address. Returns: The dword value, or None if an error occurs. #### get_flags ``` get_flags(ea: ea_t) -> int ``` Gets the flags for the specified address. Args: ea: The effective address. Returns: Flags value. #### get_float ``` get_float(ea: ea_t) -> float | None ``` Retrieves a single-precision floating-point value at the specified address. Args: ea: The effective address. Returns: The float value, or None if an error occurs. #### get_original_byte ``` get_original_byte(ea: ea_t) -> int | None ``` Get original byte value (that was before patching). Args: ea: The effective address. Returns: The original byte value, or None if an error occurs. #### get_original_bytes ``` get_original_bytes( ea: ea_t, size: int ) -> Tuple[bool, bytes] ``` Gets the original bytes before any patches by reading individual bytes. Args: ea: The effective address. size: Number of bytes to read. Returns: A pair of (success flag, original bytes). #### get_original_dword ``` get_original_dword(ea: ea_t) -> int | None ``` Get original dword value (that was before patching). Args: ea: The effective address. Returns: The original dword value, or None if an error occurs. #### get_original_qword ``` get_original_qword(ea: ea_t) -> int | None ``` Get original qword value (that was before patching). Args: ea: The effective address. Returns: The original qword value, or None if an error occurs. #### get_original_word ``` get_original_word(ea: ea_t) -> int | None ``` Get original word value (that was before patching). Args: ea: The effective address. Returns: The original word value, or None if an error occurs. #### get_qword ``` get_qword(ea: ea_t) -> int | None ``` Retrieves a quad word (64 bits/8 bytes) at the specified address. Args: ea: The effective address. Returns: The qword value, or None if an error occurs. #### get_string ``` get_string( ea: ea_t, max_length: int = None ) -> Tuple[bool, str] ``` Gets a string from the specified address. Args: ea: The effective address. max_length: Maximum string length to read. Returns: A pair of (success flag, string). #### get_unicode_string ``` get_unicode_string( ea: ea_t, max_length: int = None ) -> Tuple[bool, str] ``` Gets a Unicode string from the specified address. Args: ea: The effective address. max_length: Maximum string length to read. Returns: A pair of (success flag, string). #### get_word ``` get_word(ea: ea_t) -> int | None ``` Retrieves a word (16 bits/2 bytes) at the specified address. Args: ea: The effective address. Returns: The word value, or None if an error occurs. #### has_any_flags ``` has_any_flags(ea: ea_t, flag_mask: ByteFlags) -> bool ``` Checks if any of the specified flags are set at the given address. Args: ea: The effective address. flag_mask: ByteFlags enum value(s) to check. Returns: True if any of the specified flags are set, False otherwise. #### has_user_name ``` has_user_name(ea: ea_t) -> bool ``` Checks if the address has a user-defined name. Args: ea: The effective address. Returns: True if has user name, False otherwise. #### is_code ``` is_code(ea: ea_t) -> bool ``` Checks if the address contains code. Args: ea: The effective address. Returns: True if code, False otherwise. #### is_data ``` is_data(ea: ea_t) -> bool ``` Checks if the address contains data. Args: ea: The effective address. Returns: True if data, False otherwise. #### is_head ``` is_head(ea: ea_t) -> bool ``` Checks if the address is the start of a data item. Args: ea: The effective address. Returns: True if head, False otherwise. #### is_tail ``` is_tail(ea: ea_t) -> bool ``` Checks if the address is part of a multi-byte data item. Args: ea: The effective address. Returns: True if tail, False otherwise. #### is_unknown ``` is_unknown(ea: ea_t) -> bool ``` Checks if the address contains unknown/undefined data. Args: ea: The effective address. Returns: True if unknown, False otherwise. #### make_array ``` make_array(ea: ea_t, element_size: int, count: int) -> bool ``` Converts data at address to array type. Args: ea: The effective address. element_size: Size of each array element. count: Number of elements. Returns: True if successful, False otherwise. #### make_byte ``` make_byte(ea: ea_t) -> bool ``` Converts data at address to byte type. Args: ea: The effective address. Returns: True if successful, False otherwise. #### make_dword ``` make_dword(ea: ea_t) -> bool ``` Converts data at address to double word type. Args: ea: The effective address. Returns: True if successful, False otherwise. #### make_qword ``` make_qword(ea: ea_t) -> bool ``` Converts data at address to quad word type. Args: ea: The effective address. Returns: True if successful, False otherwise. #### make_string ``` make_string( ea: ea_t, length: int = None, string_type: StringType = C, ) -> bool ``` Converts data at address to string type. Args: ea: The effective address. length: String length (auto-detect if None). string_type: String type (default: StringType.C). Returns: True if successful, False otherwise. #### make_word ``` make_word(ea: ea_t) -> bool ``` Converts data at address to word type. Args: ea: The effective address. Returns: True if successful, False otherwise. #### next_addr ``` next_addr(ea: ea_t) -> ea_t ``` Gets the next valid address after the specified address. Args: ea: The effective address. Returns: Next valid address. #### next_head ``` next_head(ea: ea_t, max_ea: ea_t = None) -> ea_t ``` Gets the next head (start of data item) after the specified address. Args: ea: The effective address. max_ea: Maximum address to search. Returns: Address of next head, or BADADDR if not found. #### patch_byte ``` patch_byte(ea: ea_t, value: int) -> bool ``` Patch a byte of the program. The original value is saved and can be obtained by get_original_byte(). Args: ea: The effective address. value: Byte value to patch. Returns: True if the database has been modified, False otherwise. #### patch_bytes ``` patch_bytes(ea: ea_t, data: bytes) -> bool ``` Patch the specified number of bytes of the program. Original values are saved and available with get_original_bytes(). Args: ea: The effective address. data: Bytes to patch. Returns: True if successful, False otherwise. #### patch_dword ``` patch_dword(ea: ea_t, value: int) -> bool ``` Patch a dword of the program. The original value is saved and can be obtained by get_original_dword(). Args: ea: The effective address. value: Dword value to patch. Returns: True if the database has been modified, False otherwise. #### patch_qword ``` patch_qword(ea: ea_t, value: int) -> bool ``` Patch a qword of the program. The original value is saved and can be obtained by get_original_qword(). Args: ea: The effective address. value: Qword value to patch. Returns: True if the database has been modified, False otherwise. #### patch_word ``` patch_word(ea: ea_t, value: int) -> bool ``` Patch a word of the program. The original value is saved and can be obtained by get_original_word(). Args: ea: The effective address. value: Word value to patch. Returns: True if the database has been modified, False otherwise. #### prev_addr ``` prev_addr(ea: ea_t) -> ea_t ``` Gets the previous valid address before the specified address. Args: ea: The effective address. Returns: Previous valid address. #### prev_head ``` prev_head(ea: ea_t, min_ea: ea_t = None) -> ea_t ``` Gets the previous head (start of data item) before the specified address. Args: ea: The effective address. min_ea: Minimum address to search. Returns: Address of previous head, or BADADDR if not found. #### revert_byte ``` revert_byte(ea: ea_t) -> bool ``` Revert patched byte to its original value. Args: ea: The effective address. Returns: True if byte was patched before and reverted now, False otherwise. #### set_byte ``` set_byte(ea: ea_t, value: int) -> bool ``` Sets a byte value at the specified address. Args: ea: The effective address. value: Byte value to set. Returns: True if successful, False otherwise. #### set_bytes ``` set_bytes(ea: ea_t, data: bytes) -> bool ``` Sets a sequence of bytes at the specified address. Args: ea: The effective address. data: Bytes to write. Returns: True if successful, False otherwise. #### set_dword ``` set_dword(ea: ea_t, value: int) -> bool ``` Sets a double word (4 bytes) value at the specified address. Args: ea: The effective address. value: Double word value to set. Returns: True if successful, False otherwise. #### set_flags ``` set_flags(ea: ea_t, flags: int) -> bool ``` Sets the flags for the specified address. Args: ea: The effective address. flags: Flags to set. Returns: True if successful, False otherwise. #### set_qword ``` set_qword(ea: ea_t, value: int) -> bool ``` Sets a quad word (8 bytes) value at the specified address. Args: ea: The effective address. value: Quad word value to set. Returns: True if successful, False otherwise. #### set_word ``` set_word(ea: ea_t, value: int) -> bool ``` Sets a word (2 bytes) value at the specified address. Args: ea: The effective address. value: Word value to set. Returns: True if successful, False otherwise. ### DataTypeFlags Bases: `IntEnum` Data type flags for creating data items. Attributes: - **`BYTE`** – - **`DOUBLE`** – - **`DWORD`** – - **`FLOAT`** – - **`QWORD`** – - **`WORD`** – #### BYTE ``` BYTE = byte_flag() ``` #### DOUBLE ``` DOUBLE = double_flag() ``` #### DWORD ``` DWORD = dword_flag() ``` #### FLOAT ``` FLOAT = float_flag() ``` #### QWORD ``` QWORD = qword_flag() ``` #### WORD ``` WORD = word_flag() ``` ### SearchFlags Bases: `IntFlag` Search flags for text and pattern searching. Attributes: - **`BRK`** – - **`CASE`** – - **`DOWN`** – - **`IDENT`** – - **`NOBRK`** – - **`NOSHOW`** – - **`REGEX`** – - **`UP`** – #### BRK ``` BRK = SEARCH_BRK ``` #### CASE ``` CASE = SEARCH_CASE ``` #### DOWN ``` DOWN = SEARCH_DOWN ``` #### IDENT ``` IDENT = SEARCH_IDENT ``` #### NOBRK ``` NOBRK = SEARCH_NOBRK ``` #### NOSHOW ``` NOSHOW = SEARCH_NOSHOW ``` #### REGEX ``` REGEX = SEARCH_REGEX ``` #### UP ``` UP = SEARCH_UP ``` ### StringType Bases: `IntEnum` String type constants for string operations. Attributes: - **`C`** – - **`C16`** – - **`C32`** – - **`LEN2`** – - **`LEN4`** – - **`PASCAL`** – - **`TERMCHR`** – #### C ``` C = STRTYPE_C ``` #### C16 ``` C16 = STRTYPE_C_16 ``` #### C32 ``` C32 = STRTYPE_C_32 ``` #### LEN2 ``` LEN2 = STRTYPE_LEN2 ``` #### LEN4 ``` LEN4 = STRTYPE_LEN4 ``` #### PASCAL ``` PASCAL = STRTYPE_PASCAL ``` #### TERMCHR ``` TERMCHR = STRTYPE_TERMCHR ``` # `Comments` ## comments Classes: - **`CommentKind`** – Enumeration for IDA comment types. - **`Comments`** – Provides access to user-defined comments in the IDA database. ### CommentKind Bases: `Enum` Enumeration for IDA comment types. Attributes: - **`ALL`** – - **`REGULAR`** – - **`REPEATABLE`** – #### ALL ``` ALL = 'all' ``` #### REGULAR ``` REGULAR = 'regular' ``` #### REPEATABLE ``` REPEATABLE = 'repeatable' ``` ### Comments ``` Comments(database: 'Database') ``` Provides access to user-defined comments in the IDA database. IDA supports two types of comments: - Regular comments: Displayed at specific addresses - Repeatable comments: Displayed at all references to the same address Constructs a comment manager for the given database. Args: database: Reference to the active IDA database. Methods: - **`delete`** – Deletes a comment at the specified address. - **`get`** – Retrieves the comment at the specified address. - **`get_all`** – Creates an iterator for comments in the database. - **`get_any`** – Retrieves any comment at the specified address, checking both regular and repeatable. - **`set`** – Sets a comment at the specified address. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### delete ``` delete( ea: int, comment_kind: CommentKind = REGULAR ) -> bool ``` Deletes a comment at the specified address. Args: ea: The effective address. comment_kind: Type of comment to delete (REGULAR or REPEATABLE). Returns: True if the comment was successfully deleted, False otherwise. #### get ``` get( ea: int, comment_kind: CommentKind = REGULAR ) -> str | None ``` Retrieves the comment at the specified address. Args: ea: The effective address. comment_kind: Type of comment to retrieve (REGULAR or REPEATABLE). Returns: The comment string, or None if no comment exists. #### get_all ``` get_all( comment_kind: CommentKind = REGULAR, ) -> Iterator[Tuple[int, str, bool]] ``` Creates an iterator for comments in the database. Args: comment_kind: Type of comments to retrieve: - CommentType.REGULAR: Only regular comments - CommentType.REPEATABLE: Only repeatable comments - CommentType.ALL: Both regular and repeatable comments Yields: Tuples of (address, comment_text, is_repeatable) for each comment found. #### get_any ``` get_any(ea: int) -> Tuple[bool, str] ``` Retrieves any comment at the specified address, checking both regular and repeatable. Args: ea: The effective address. Returns: A tuple (success, comment string). If no comment exists, success is False. #### set ``` set( ea: int, comment: str, comment_kind: CommentKind = REGULAR, ) -> bool ``` Sets a comment at the specified address. Args: ea: The effective address. comment: The comment text to assign. comment_kind: Type of comment to set (REGULAR or REPEATABLE). Returns: True if the comment was successfully set, False otherwise. # `Database` ## database Classes: - **`Database`** – Provides access and control over the loaded IDA database. ### Database ``` Database() ``` Provides access and control over the loaded IDA database. Can be used as a context manager for automatic resource cleanup: Example: ``` # Open and automatically close a database with Database() as db: if db.open("path/to/file.exe", save_on_close=True): # Work with the database print(f"Loaded: {db.path}") # Database is automatically closed here # Or use without context manager db = Database() if db.open("path/to/file.exe", save_on_close=True): # Work with database db.close() # Uses save_on_close=True automatically ``` Constructs a new interface to the IDA database. Note: When running inside IDA, this refers to the currently open database. Use open() to load a new database when using IDA as a library. Classes: - **`IdaCommandBuilder`** – Builder class for constructing IDA command line arguments. Methods: - **`close`** – Closes the currently open database. - **`is_open`** – Checks if the database is loaded. - **`open`** – Opens a database from the specified file path. Attributes: - **`architecture`** (`Optional[str]`) – The processor architecture. - **`base_address`** (`Optional[ea_t]`) – The image base address of this database. - **`basic_blocks`** (`BasicBlocks`) – Handler that provides access to basic block-related operations. - **`bitness`** (`Optional[int]`) – The application bitness (32/64). - **`bytes`** (`Bytes`) – Handler that provides access to byte-level memory operations. - **`comments`** (`Comments`) – Handler that provides access to user comment-related operations. - **`crc32`** (`Optional[int]`) – The CRC32 checksum of the input file. - **`current_ea`** (`ea_t`) – The current effective address (equivalent to the "screen EA" in IDA GUI). - **`entries`** (`Entries`) – Handler that provides access to entries operations. - **`events`** (`Events`) – Handler that provides access to event related operations. - **`filesize`** (`Optional[int]`) – The input file size. - **`format`** (`Optional[str]`) – The file format type. - **`functions`** (`Functions`) – Handler that provides access to function-related operations. - **`heads`** (`Heads`) – Handler that provides access to user heads operations. - **`instructions`** (`Instructions`) – Handler that provides access to instruction-related operations. - **`load_time`** (`Optional[str]`) – The database load time. - **`maximum_ea`** (`ea_t`) – The maximum effective address from this database. - **`md5`** (`Optional[str]`) – The MD5 hash of the input file. - **`metadata`** (`Dict[str, str]`) – Map of key-value metadata about the current database. - **`minimum_ea`** (`ea_t`) – The minimum effective address from this database. - **`module`** (`Optional[str]`) – The module name. - **`names`** (`Names`) – Handler that provides access to name-related operations. - **`path`** (`Optional[str]`) – The input file path. - **`save_on_close`** – - **`segments`** (`Segments`) – Handler that provides access to memory segment-related operations. - **`sha256`** (`Optional[str]`) – The SHA256 hash of the input file. - **`signature_files`** (`SignatureFiles`) – Handler that provides access to signature file operations. - **`strings`** (`Strings`) – Handler that provides access to string-related operations. - **`types`** (`Types`) – Handler that provides access to type-related operations. - **`xrefs`** (`Xrefs`) – Handler that provides access to cross-reference (xref) operations. #### architecture ``` architecture: Optional[str] ``` The processor architecture. #### base_address ``` base_address: Optional[ea_t] ``` The image base address of this database. #### basic_blocks ``` basic_blocks: BasicBlocks ``` Handler that provides access to basic block-related operations. #### bitness ``` bitness: Optional[int] ``` The application bitness (32/64). #### bytes ``` bytes: Bytes ``` Handler that provides access to byte-level memory operations. #### comments ``` comments: Comments ``` Handler that provides access to user comment-related operations. #### crc32 ``` crc32: Optional[int] ``` The CRC32 checksum of the input file. #### current_ea ``` current_ea: ea_t ``` The current effective address (equivalent to the "screen EA" in IDA GUI). #### entries ``` entries: Entries ``` Handler that provides access to entries operations. #### events ``` events: Events ``` Handler that provides access to event related operations. #### filesize ``` filesize: Optional[int] ``` The input file size. #### format ``` format: Optional[str] ``` The file format type. #### functions ``` functions: Functions ``` Handler that provides access to function-related operations. #### heads ``` heads: Heads ``` Handler that provides access to user heads operations. #### instructions ``` instructions: Instructions ``` Handler that provides access to instruction-related operations. #### load_time ``` load_time: Optional[str] ``` The database load time. #### maximum_ea ``` maximum_ea: ea_t ``` The maximum effective address from this database. #### md5 ``` md5: Optional[str] ``` The MD5 hash of the input file. #### metadata ``` metadata: Dict[str, str] ``` Map of key-value metadata about the current database. Dynamically built from all metadata properties. #### minimum_ea ``` minimum_ea: ea_t ``` The minimum effective address from this database. #### module ``` module: Optional[str] ``` The module name. #### names ``` names: Names ``` Handler that provides access to name-related operations. #### path ``` path: Optional[str] ``` The input file path. #### save_on_close ``` save_on_close = False ``` #### segments ``` segments: Segments ``` Handler that provides access to memory segment-related operations. #### sha256 ``` sha256: Optional[str] ``` The SHA256 hash of the input file. #### signature_files ``` signature_files: SignatureFiles ``` Handler that provides access to signature file operations. #### strings ``` strings: Strings ``` Handler that provides access to string-related operations. #### types ``` types: Types ``` Handler that provides access to type-related operations. #### xrefs ``` xrefs: Xrefs ``` Handler that provides access to cross-reference (xref) operations. #### IdaCommandBuilder ``` IdaCommandBuilder() ``` Builder class for constructing IDA command line arguments. This class provides an interface to build IDA command line arguments for passing them in the database open call. Usage: builder = Database.IdaCommandBuilder() builder.auto_analysis(False).autonomous(True).set_loading_address(0x400000) args = builder.build_args() Initialize the command builder with default values. Methods: - **`add_first_pass_directive`** – Add a configuration directive for the first pass (-d switch). - **`add_second_pass_directive`** – Add a configuration directive for the second pass (-D switch). - **`auto_analysis`** – Control automatic analysis (-a switch). - **`build_args`** – Build the complete command line arguments string. - **`compress_database`** – Compress database to create zipped idb (-P+ switch). - **`disable_fpp_instructions`** – Disable FPP (Floating Point Processor) instructions (-f switch). - **`disable_mouse`** – Disable mouse support (-M switch). - **`empty_database`** – Create an empty database (-t switch). - **`load_resources`** – Load MS Windows exe file resources (-R switch). - **`new_database`** – Disassemble a new file by deleting the old database (-c switch). - **`no_pack_database`** – Do not pack database (-P- switch). - **`no_segmentation`** – Do not create segmentation (-x switch). - **`pack_database`** – Pack database to create unzipped idb (-P switch). - **`run_debugger`** – Immediately run the built-in debugger (-r### switch). - **`run_script`** – Execute a script file when the database is opened (-S### switch). - **`set_compiler`** – Set compiler in format name:abi (-C#### switch). - **`set_debug_flags`** – Set debug flags (-z switch). - **`set_entry_point`** – Set the program entry point (-i#### switch). - **`set_file_type`** – Interpret the input file as the specified file type (-T### switch). - **`set_jit_debugger`** – Set IDA as just-in-time debugger (-I# switch). - **`set_loading_address`** – Set the loading address (-b#### switch). - **`set_log_file`** – Set the name of the log file (-L#### switch). - **`set_output_database`** – Specify the output database path (-o#### switch). - **`set_plugin_options`** – Set options to pass to plugins (-O#### switch). - **`set_processor`** – Set the processor type (-p#### switch). - **`set_windows_directory`** – Specify MS Windows directory (-W### switch). Attributes: - **`auto_analysis_enabled`** (`bool`) – Check if auto analysis is enabled. ##### auto_analysis_enabled ``` auto_analysis_enabled: bool ``` Check if auto analysis is enabled. Returns: True if auto analysis is enabled, False otherwise. ##### add_first_pass_directive ``` add_first_pass_directive(directive: str) ``` Add a configuration directive for the first pass (-d switch). Configuration directives are processed at the first pass. Example: "VPAGESIZE=8192" Args: directive: Configuration directive string. Returns: Self for method chaining. ##### add_second_pass_directive ``` add_second_pass_directive(directive: str) ``` Add a configuration directive for the second pass (-D switch). Configuration directives are processed at the second pass. Args: directive: Configuration directive string. Returns: Self for method chaining. ##### auto_analysis ``` auto_analysis(enabled=True) ``` Control automatic analysis (-a switch). Args: enabled: If False, disables auto analysis (-a). If True, enables auto analysis (-a-). Returns: Self for method chaining. ##### build_args ``` build_args() ``` Build the complete command line arguments string. Constructs the command line arguments based on all the configured options. This method processes all the settings and generates the appropriate IDA command line switches. Returns: String containing all command line arguments separated by spaces. ##### compress_database ``` compress_database() ``` Compress database to create zipped idb (-P+ switch). Returns: Self for method chaining. ##### disable_fpp_instructions ``` disable_fpp_instructions(disabled=True) ``` Disable FPP (Floating Point Processor) instructions (-f switch). This option is specific to IBM PC only. Args: disabled: True to disable FPP instructions. Returns: Self for method chaining. ##### disable_mouse ``` disable_mouse(disabled=True) ``` Disable mouse support (-M switch). This option is for text mode only. Args: disabled: True to disable mouse support. Returns: Self for method chaining. ##### empty_database ``` empty_database(enabled=True) ``` Create an empty database (-t switch). Args: enabled: True to create an empty database. Returns: Self for method chaining. ##### load_resources ``` load_resources(enabled=True) ``` Load MS Windows exe file resources (-R switch). Args: enabled: True to load Windows resources. Returns: Self for method chaining. ##### new_database ``` new_database(enabled=True) ``` Disassemble a new file by deleting the old database (-c switch). Args: enabled: True to create a new database, deleting any existing one. Returns: Self for method chaining. ##### no_pack_database ``` no_pack_database() ``` Do not pack database (-P- switch). Note: This is not recommended. See Abort command documentation. Returns: Self for method chaining. ##### no_segmentation ``` no_segmentation(enabled=True) ``` Do not create segmentation (-x switch). Used in pair with Dump database command. This switch affects EXE and COM format files only. Args: enabled: True to disable segmentation. Returns: Self for method chaining. ##### pack_database ``` pack_database() ``` Pack database to create unzipped idb (-P switch). Returns: Self for method chaining. ##### run_debugger ``` run_debugger(options: str = '') ``` Immediately run the built-in debugger (-r### switch). Args: options: Debugger options string. Returns: Self for method chaining. ##### run_script ``` run_script(script_file: str, args: List[str] = []) ``` Execute a script file when the database is opened (-S### switch). The script file extension determines which extlang will run the script. Command line arguments can be passed after the script name. The passed parameters are stored in the "ARGV" global IDC variable: - Use "ARGV.count" to determine the number of arguments - The first argument "ARGV[0]" contains the script name Note: This switch is not available in the IDA Home edition. Args: script_file: Path to the script file. args: List of command line arguments to pass to the script. Returns: Self for method chaining. ##### set_compiler ``` set_compiler(name: str, abi: str = '') ``` Set compiler in format name:abi (-C#### switch). Args: name: Compiler name. abi: Application Binary Interface (optional). Returns: Self for method chaining. ##### set_debug_flags ``` set_debug_flags(flags) ``` Set debug flags (-z switch). Debug flags can be specified as an integer or list of flag names. Available debug flags: - drefs (0x00000001): Data references - offsets (0x00000002): Offsets - flirt (0x00000004): FLIRT signatures - idp (0x00000008): IDP module - ldr (0x00000010): Loader module - plugin (0x00000020): Plugin module - ids (0x00000040): IDS files - config (0x00000080): Config file - heap (0x00000100): Check heap - licensing (0x00000200): Licensing - demangler (0x00000400): Demangler - queue (0x00000800): Queue - rollback (0x00001000): Rollback - already_data_or_code (0x00002000): Already data or code - type_system (0x00004000): Type system - notifications (0x00008000): Show all notifications - debugger (0x00010000): Debugger - debugger_appcall (0x00020000): Debugger appcall - source_debugger (0x00040000): Source-level debugger - accessibility (0x00080000): Accessibility - network (0x00100000): Network - stack_analysis (0x00200000): Full stack analysis (simplex method) - debug_info (0x00400000): Handling of debug info (e.g. pdb, dwarf) - lumina (0x00800000): Lumina Args: flags: Integer value or list of flag names. Returns: Self for method chaining. ##### set_entry_point ``` set_entry_point(address: int) ``` Set the program entry point (-i#### switch). Args: address: Entry point address as hexadecimal number. Returns: Self for method chaining. ##### set_file_type ``` set_file_type(file_type: str, member: str = '') ``` Interpret the input file as the specified file type (-T### switch). The file type is specified as a prefix of a file type visible in the 'load file' dialog box. IDA does not display the 'load file' dialog when this option is used. To specify archive member, put it after the colon character. You can specify nested paths: -T\[:{::}[:]\] Examples: - set_file_type("ZIP", "classes.dex") -> -TZIP:classes.dex Args: file_type: File type prefix. member: Archive member name (optional). Returns: Self for method chaining. ##### set_jit_debugger ``` set_jit_debugger(enabled=True) ``` Set IDA as just-in-time debugger (-I# switch). Args: enabled: True to enable (1), False to disable (0). Returns: Self for method chaining. ##### set_loading_address ``` set_loading_address(address: int) ``` Set the loading address (-b#### switch). Args: address: Loading address as a hexadecimal number, in paragraphs. A paragraph is 16 bytes. Returns: Self for method chaining. ##### set_log_file ``` set_log_file(filename: str) ``` Set the name of the log file (-L#### switch). Args: filename: Path to the log file. Returns: Self for method chaining. ##### set_output_database ``` set_output_database(path: str) ``` Specify the output database path (-o#### switch). This automatically implies creating a new database (-c). Args: path: Path to the output database file. Returns: Self for method chaining. ##### set_plugin_options ``` set_plugin_options(options: str) ``` Set options to pass to plugins (-O#### switch). Note: This switch is not available in the IDA Home edition. Args: options: Options string to pass to plugins. Returns: Self for method chaining. ##### set_processor ``` set_processor(processor_type: str) ``` Set the processor type (-p#### switch). Args: processor_type: Processor type identifier. Returns: Self for method chaining. ##### set_windows_directory ``` set_windows_directory(directory: str) ``` Specify MS Windows directory (-W### switch). Args: directory: Path to Windows directory. Returns: Self for method chaining. #### close ``` close(save: Optional[bool] = None) -> None ``` Closes the currently open database. Args: save: If provided, saves/discards changes accordingly. If None, uses the save_on_close setting from open(). Note: This function is available only when running IDA as a library. When running inside the IDA GUI, we have no control on the database lifecycle. #### is_open ``` is_open() -> bool ``` Checks if the database is loaded. Returns: True if a database is open, false otherwise. #### open ``` open( db_path: str, db_args: Optional['Database.IdaCommandBuilder'] = None, save_on_close=False, ) -> bool ``` Opens a database from the specified file path. Args: db_path: Path to the input file. db_args: Command builder responsible for passing arguments to IDA kernel. save_on_close: Default behavior for saving changes on close. Used automatically when exiting context manager, but can be overridden in explicit close() calls. Returns: True if the database was successfully opened, false otherwise. Note: This function is available only when running IDA as a library. When running inside the IDA GUI, simply construct a Database() instance to refer to the currently open database. Use is_open() to check if a database is loaded. # `Entries` ## entries Classes: - **`Entries`** – Provides access to entries in the IDA database. - **`EntryInfo`** – Represents a program entry point. - **`ForwarderInfo`** – Represents information about an entry point forwarder. ### Entries ``` Entries(database) ``` Provides access to entries in the IDA database. Methods: - **`add`** – Add a new entry point. - **`exists`** – Check if an entry point with the given ordinal exists. - **`get_addresses`** – Get all entry point addresses. - **`get_all`** – Get all entry points. - **`get_at_index`** – Get entry point by its index in the entry table. - **`get_by_address`** – Get entry point by its address. - **`get_by_name`** – Find entry point by name. - **`get_by_ordinal`** – Get entry point by its ordinal number. - **`get_count`** – Get the total number of entry points. - **`get_forwarders`** – Get all entry points that have forwarders. - **`get_names`** – Get all entry point names. - **`get_ordinals`** – Get all ordinal numbers. - **`rename`** – Rename an existing entry point. - **`set_forwarder`** – Set forwarder name for an entry point. #### add ``` add( address: ea_t, name: str, ordinal: Optional[int] = None, make_code: bool = True, ) -> bool ``` Add a new entry point. Args: address: Linear address of the entry point name: Name for the entry point ordinal: Ordinal number (if None, uses address as ordinal) make_code: Whether to convert bytes to instructions Returns: bool: True if successful #### exists ``` exists(ordinal: int) -> bool ``` Check if an entry point with the given ordinal exists. Args: ordinal: Ordinal number to check Returns: bool: True if entry point exists #### get_addresses ``` get_addresses() -> Iterator[ea_t] ``` Get all entry point addresses. Yields: int: Each entry point address #### get_all ``` get_all() -> Iterator[EntryInfo] ``` Get all entry points. Yields: Entry: Each entry point in the program #### get_at_index ``` get_at_index(index: int) -> EntryInfo ``` Get entry point by its index in the entry table. Args: index: Internal index (0 to get_count()-1) Returns: Entry: The entry point at the specified index Raises: IndexError: If index is out of range #### get_by_address ``` get_by_address(address: ea_t) -> EntryInfo | None ``` Get entry point by its address. Args: address: Linear address to search for Returns: Entry: The entry point at the specified address, or None if not found #### get_by_name ``` get_by_name(name: str) -> EntryInfo | None ``` Find entry point by name. Args: name: Name to search for Returns: Entry: The entry point with the specified name, or None if not found #### get_by_ordinal ``` get_by_ordinal(ordinal: int) -> EntryInfo | None ``` Get entry point by its ordinal number. Args: ordinal: Ordinal number of the entry point Returns: Entry: The entry point with the specified ordinal, or None if not found #### get_count ``` get_count() -> int ``` Get the total number of entry points. Returns: int: Number of entry points in the program #### get_forwarders ``` get_forwarders() -> Iterator[ForwarderInfo] ``` Get all entry points that have forwarders. Yields: ForwarderInfo: Information about each entry with a forwarder #### get_names ``` get_names() -> Iterator[str] ``` Get all entry point names. Yields: str: Each entry point name #### get_ordinals ``` get_ordinals() -> Iterator[int] ``` Get all ordinal numbers. Yields: int: Each ordinal number #### rename ``` rename(ordinal: int, new_name: str) -> bool ``` Rename an existing entry point. Args: ordinal: Ordinal number of the entry point new_name: New name for the entry point Returns: bool: True if successful #### set_forwarder ``` set_forwarder(ordinal: int, forwarder_name: str) -> bool ``` Set forwarder name for an entry point. Args: ordinal: Ordinal number of the entry point forwarder_name: Forwarder name to set Returns: bool: True if successful ### EntryInfo ``` EntryInfo( ordinal: int, address: ea_t, name: str, forwarder_name: Optional[str] = None, ) ``` Represents a program entry point. Exported functions are considered entry points as well. Methods: - **`has_forwarder`** – Check if this entry point has a forwarder. Attributes: - **`address`** (`ea_t`) – - **`forwarder_name`** (`Optional[str]`) – - **`name`** (`str`) – - **`ordinal`** (`int`) – #### address ``` address: ea_t ``` #### forwarder_name ``` forwarder_name: Optional[str] = None ``` #### name ``` name: str ``` #### ordinal ``` ordinal: int ``` #### has_forwarder ``` has_forwarder() -> bool ``` Check if this entry point has a forwarder. ### ForwarderInfo ``` ForwarderInfo(ordinal: int, name: str) ``` Represents information about an entry point forwarder. Attributes: - **`name`** (`str`) – - **`ordinal`** (`int`) – #### name ``` name: str ``` #### ordinal ``` ordinal: int ``` # `Events` ## Events ``` Events(database: Optional[Database] = None) ``` Events handler class. Provides decorators and methods for registering event handlers for various IDA Pro events. This class wraps the IDA SDK's IDB_Hooks, IDP_Hooks, and DBG_Hooks to provide a clean Python API. Usage: events = Events(db) # or db.events() ``` @events.on_function_added def handle_func_added(pfn): print(f"Function added at 0x{pfn.start_ea:X}") events.hook() # Start listening for events ``` Initialize the IDA Events handler. Sets up all event handlers for IDB, IDP, and DBG events. Events are initially disabled until hook() is called. Methods: - **`enable_logging`** – Enable or disable event logging for debugging. - **`hook`** – Start listening for IDA events. - **`on_bookmark_changed`** – Decorator for bookmark changed events. - **`on_byte_patched`** – Decorator for byte patched events. - **`on_comment_changed`** – Decorator for comment changed events. - **`on_compiler_changed`** – Decorator for compiler changed events. - **`on_flow_chart_created`** – Decorator for flow chart created events. - **`on_frame_created`** – Decorator for frame created events. - **`on_frame_expanded`** – Decorator for frame expanded events. - **`on_frame_udm_changed`** – Decorator for frame user-defined member changed events. - **`on_frame_udm_created`** – Decorator for frame user-defined member created events. - **`on_frame_udm_deleted`** – Decorator for frame user-defined member deleted events. - **`on_frame_udm_renamed`** – Decorator for frame user-defined member renamed events. - **`on_function_added`** – Decorator for function added events. - **`on_function_deleted`** – Decorator for function deleted events. - **`on_item_color_changed`** – Decorator for item color changed events. - **`on_local_types_changed`** – Decorator for local types changed events. - **`on_local_udm_changed`** – Decorator for local type user-defined member changed events. - **`on_local_udm_created`** – Decorator for local type user-defined member created events. - **`on_local_udm_deleted`** – Decorator for local type user-defined member deleted events. - **`on_local_udm_renamed`** – Decorator for local type user-defined member renamed events. - **`on_make_code`** – Decorator for make code events. - **`on_make_data`** – Decorator for make data events. - **`on_renamed`** – Decorator for rename events. - **`on_segment_added`** – Decorator for segment added events. - **`register_handler`** – Register a callback for a specific event. - **`unhook`** – Stop listening for IDA events. - **`unregister_handler`** – Unregister a callback for a specific event. Attributes: - **`handlers`** (`Dict[str, EventHandler]`) – - **`hooked`** – - **`log_events`** – - **`m_database`** – ### handlers ``` handlers: Dict[str, EventHandler] = {} ``` ### hooked ``` hooked = False ``` ### log_events ``` log_events = False ``` ### m_database ``` m_database = database ``` ### enable_logging ``` enable_logging(enabled: bool = True) ``` Enable or disable event logging for debugging. Args: enabled: True to enable logging, False to disable ### hook ``` hook() ``` Start listening for IDA events. This creates and hooks the IDB, IDP, and DBG event handlers. Events will start being processed and callbacks will be triggered. ### on_bookmark_changed ``` on_bookmark_changed( func: Callable[[int, object, str, int], None], ) ``` Decorator for bookmark changed events. Bookmarked position changed. Args: func: Callback function that takes: - index: Bookmark index - pos: Position (lochist_entry_t) - desc: Description - operation: 0-added, 1-updated, 2-deleted ### on_byte_patched ``` on_byte_patched(func: Callable[[int, int], None]) ``` Decorator for byte patched events. A byte has been patched. Args: func: Callback function that takes: - ea: Address - old_value: Previous byte value ### on_comment_changed ``` on_comment_changed(func: Callable[[int, bool], None]) ``` Decorator for comment changed events. An item comment has been changed. Args: func: Callback function that takes: - ea: Address - repeatable_cmt: True if repeatable comment ### on_compiler_changed ``` on_compiler_changed(func: Callable[[bool], None]) ``` Decorator for compiler changed events. The kernel has changed the compiler information. Args: func: Callback function that takes: - adjust_inf_fields: May change inf fields? ### on_flow_chart_created ``` on_flow_chart_created(func: Callable[[object], None]) ``` Decorator for flow chart created events. GUI has retrieved a function flow chart. Plugins may modify the flow chart in this callback. Args: func: Callback function that takes fc (qflow_chart_t) ### on_frame_created ``` on_frame_created(func: Callable[[int], None]) ``` Decorator for frame created events. A function frame has been created. Args: func: Callback function that takes func_ea (function address) ### on_frame_expanded ``` on_frame_expanded(func: Callable[[int, int, int], None]) ``` Decorator for frame expanded events. Args: func_ea (ea_t), udm_tid (tid_t), delta (adiff_t) ### on_frame_udm_changed ``` on_frame_udm_changed( func: Callable[[int, int, object, object], None], ) ``` Decorator for frame user-defined member changed events. Args: func_ea (ea_t), udm_tid (tid_t), udmold (udm_t), udmnew (udm_t) ### on_frame_udm_created ``` on_frame_udm_created(func: Callable[[int, object], None]) ``` Decorator for frame user-defined member created events. Args: func_ea (ea_t), udm (udm_t object) ### on_frame_udm_deleted ``` on_frame_udm_deleted( func: Callable[[int, int, object], None], ) ``` Decorator for frame user-defined member deleted events. Args: func_ea (ea_t), udm_tid (tid_t), udm (udm_t object) ### on_frame_udm_renamed ``` on_frame_udm_renamed( func: Callable[[int, object, str], None], ) ``` Decorator for frame user-defined member renamed events. Args: func_ea (ea_t), udm (udm_t object), oldname (str) ### on_function_added ``` on_function_added(func: Callable[[int], None]) ``` Decorator for function added events. The kernel has added a function. Args: func: Callback function that takes pfn.start_ea (function start address) ### on_function_deleted ``` on_function_deleted(func: Callable[[int], None]) ``` Decorator for function deleted events. The kernel is about to delete a function. Args: func: Callback function that takes pfn.start_ea (function start address) ### on_item_color_changed ``` on_item_color_changed(func: Callable[[int, int], None]) ``` Decorator for item color changed events. An item color has been changed. Args: func: Callback function that takes: - ea: Address - color: New color (DEFCOLOR means color deleted) ### on_local_types_changed ``` on_local_types_changed( func: Callable[[int, int, str], None], ) ``` Decorator for local types changed events. Local types have been changed. Args: func: Callback function that takes: - ltc: Local type change (local_type_change_t) - ordinal: Ordinal (0 means unknown) - name: Name (None means unknown) ### on_local_udm_changed ``` on_local_udm_changed( func: Callable[[str, int, object, object], None], ) ``` Decorator for local type user-defined member changed events. Args: udtname (str), udm_tid (tid_t), udmold (udm_t), udmnew (udm_t) ### on_local_udm_created ``` on_local_udm_created(func: Callable[[str, object], None]) ``` Decorator for local type user-defined member created events. Args: udtname (str), udm (udm_t object) ### on_local_udm_deleted ``` on_local_udm_deleted( func: Callable[[str, int, object], None], ) ``` Decorator for local type user-defined member deleted events. Args: udtname (str), udm_tid (tid_t), udm (udm_t object) ### on_local_udm_renamed ``` on_local_udm_renamed( func: Callable[[str, object, str], None], ) ``` Decorator for local type user-defined member renamed events. Args: udtname (str), udm (udm_t object), oldname (str) ### on_make_code ``` on_make_code(func: Callable[[int], None]) ``` Decorator for make code events. An instruction is being created. Args: func: Callback function that takes insn.ea (instruction address) ### on_make_data ``` on_make_data(func: Callable[[int, int, int, int], None]) ``` Decorator for make data events. A data item is being created. Args: func: Callback function that takes: - ea: Address - flags: Data flags - tid: Type ID - length: Data length ### on_renamed ``` on_renamed(func: Callable[[int, str, bool, str], None]) ``` Decorator for rename events. The kernel has renamed a byte. See also the rename event. Args: func: Callback function that takes: - ea: Address - new_name: New name (can be None) - local_name: True if local name - old_name: Old name (can be None) ### on_segment_added ``` on_segment_added(func: Callable[[int, int], None]) ``` Decorator for segment added events. A new segment has been created. Args: func: Callback function that takes: - start_ea: Segment start address - end_ea: Segment end address ### register_handler ``` register_handler(event_name: str, callback: Callable) ``` Register a callback for a specific event. Args: event_name: Name of the event to register for callback: Function to call when event occurs Raises: ValueError: If event_name is not a valid event ### unhook ``` unhook() ``` Stop listening for IDA events. This unhooks all event handlers and stops processing events. Callbacks will no longer be triggered. ### unregister_handler ``` unregister_handler(event_name: str, callback: Callable) ``` Unregister a callback for a specific event. Args: event_name: Name of the event to unregister from callback: Function to remove from callbacks # `Functions` ## functions Classes: - **`Functions`** – Provides access to function-related operations within the IDA database. ### Functions ``` Functions(database: 'Database') ``` Provides access to function-related operations within the IDA database. This class handles function discovery, analysis, manipulation, and provides access to function properties like names, signatures, basic blocks, and pseudocode. Constructs a functions handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`create`** – Creates a new function at the specified address. - **`get_all`** – Retrieves all functions in the database. - **`get_at`** – Retrieves the function that contains the given address. - **`get_basic_blocks`** – Retrieves the basic blocks that compose the given function. - **`get_between`** – Retrieves functions within the specified address range. - **`get_callees`** – Gets all functions called by this function. - **`get_callers`** – Gets all functions that call this function. - **`get_disassembly`** – Retrieves the disassembly lines for the given function. - **`get_instructions`** – Retrieves all instructions within the given function. - **`get_microcode`** – Retrieves the microcode of the given function. - **`get_name`** – Retrieves the function's name. - **`get_pseudocode`** – Retrieves the decompiled pseudocode of the given function. - **`get_signature`** – Retrieves the function's type signature. - **`matches_signature`** – Checks if a function matches the given signature. - **`remove`** – Removes the function at the specified address. - **`set_name`** – Renames the given function. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### create ``` create(ea: ea_t) -> bool ``` Creates a new function at the specified address. Args: ea: The effective address where the function should start. Returns: True if the function was successfully created, False otherwise. #### get_all ``` get_all() -> Iterator[func_t] ``` Retrieves all functions in the database. Returns: An iterator over all functions in the database. #### get_at ``` get_at(ea: ea_t) -> Optional[func_t] ``` Retrieves the function that contains the given address. Args: ea: An effective address within the function body. Returns: The function object containing the address, or None if no function exists at that address. #### get_basic_blocks ``` get_basic_blocks(func: func_t) ``` Retrieves the basic blocks that compose the given function. Args: func: The function instance. Returns: An iterator over the function's basic blocks, or empty iterator if function is invalid. #### get_between ``` get_between(start: ea_t, end: ea_t) -> Iterator[func_t] ``` Retrieves functions within the specified address range. Args: start: Start address of the range (inclusive). end: End address of the range (exclusive). Yields: Function objects whose start address falls within the specified range. #### get_callees ``` get_callees(func: func_t) -> List[func_t] ``` Gets all functions called by this function. Args: func: The function instance. Returns: List of called functions. #### get_callers ``` get_callers(func: func_t) -> List[func_t] ``` Gets all functions that call this function. Args: func: The function instance. Returns: List of calling functions. #### get_disassembly ``` get_disassembly(func: func_t) -> List[str] ``` Retrieves the disassembly lines for the given function. Args: func: The function instance. Returns: A list of strings, each representing a line of disassembly. Returns empty list if function is invalid. #### get_instructions ``` get_instructions(func: func_t) ``` Retrieves all instructions within the given function. Args: func: The function instance. Returns: An iterator over all instructions in the function, or empty iterator if function is invalid. #### get_microcode ``` get_microcode( func: func_t, remove_tags: bool = True ) -> List[str] ``` Retrieves the microcode of the given function. Args: func: The function instance. remove_tags: If True, removes IDA color/formatting tags from the output. Returns: A list of strings, each representing a line of microcode. Returns empty list if function is invalid or decompilation fails. #### get_name ``` get_name(func: func_t) -> str ``` Retrieves the function's name. Args: func: The function instance. Returns: The function name as a string, or empty string if no name is set. #### get_pseudocode ``` get_pseudocode( func: func_t, remove_tags: bool = True ) -> List[str] ``` Retrieves the decompiled pseudocode of the given function. Args: func: The function instance. remove_tags: If True, removes IDA color/formatting tags from the output. Returns: A list of strings, each representing a line of pseudocode. Returns empty list if function is invalid or decompilation fails. #### get_signature ``` get_signature(func: func_t) -> str ``` Retrieves the function's type signature. Args: func: The function instance. Returns: The function signature as a string, or empty string if unavailable or function is invalid. #### matches_signature ``` matches_signature(func: func_t, signature: str) -> bool ``` Checks if a function matches the given signature. Args: func: The function instance. signature: The signature string to compare against. Returns: True if the function signature matches, False otherwise. #### remove ``` remove(ea: ea_t) -> bool ``` Removes the function at the specified address. Args: ea: The effective address of the function to remove. Returns: True if the function was successfully removed, False otherwise. #### set_name ``` set_name( func: func_t, name: str, auto_correct: bool = True ) -> bool ``` Renames the given function. Args: func: The function instance. name: The new name to assign to the function. auto_correct: If True, allows IDA to replace invalid characters automatically. Returns: True if the function was successfully renamed, False otherwise. # `Heads` ## heads Classes: - **`Heads`** – Provides access to heads(instructions or data items) in the IDA database. ### Heads ``` Heads(database: 'Database') ``` Provides access to heads(instructions or data items) in the IDA database. Constructs a heads handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`get_all`** – Retrieves an iterator over all heads in the database. - **`get_between`** – Retrieves all basic heads between two addresses. - **`get_next`** – Retrieves the next head. - **`get_prev`** – Retrieves the prev head. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### get_all ``` get_all() ``` Retrieves an iterator over all heads in the database. Returns: An iterator over the heads. #### get_between ``` get_between(start: ea_t, end: ea_t) ``` Retrieves all basic heads between two addresses. Args: start_ea: Start address of the range. end_ea: End address of the range. Returns: An iterator over the heads. #### get_next ``` get_next(ea: ea_t) -> ea_t | None ``` Retrieves the next head. Args: ea: Current head address. Returns: Next head, on error returns None. #### get_prev ``` get_prev(ea: ea_t) -> ea_t | None ``` Retrieves the prev head. Args: ea: Current head address. Returns: Prev head, on error returns None. # `Instructions` ## instructions Classes: - **`Instructions`** – Provides access to instruction-related operations using structured operand hierarchy. ### Instructions ``` Instructions(database: 'Database') ``` Provides access to instruction-related operations using structured operand hierarchy. Constructs an instructions handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`get_at`** – Decodes the instruction at the specified address. - **`get_between`** – Retrieves instructions between the specified addresses. - **`get_disassembly`** – Retrieves the disassembled string representation of the given instruction. - **`get_mnemonic`** – Retrieves the mnemonic of the given instruction. - **`get_operand`** – Get a specific operand from the instruction. - **`get_operands`** – Get all operands from the instruction. - **`get_operands_count`** – Retrieve the operands number of the given instruction. - **`get_prev`** – Decodes prev instruction of the one at specified address. - **`is_call_instruction`** – Check if the instruction is a call instruction. - **`is_jump_instruction`** – Check if the instruction is a jump instruction. - **`is_return_instruction`** – Check if the instruction is a return instruction. - **`is_valid`** – Checks if the given instruction is valid. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### get_at ``` get_at(ea: 'ea_t') -> insn_t | None ``` Decodes the instruction at the specified address. Args: ea: The effective address of the instruction. Returns: An insn_t instance, if fails returns None. #### get_between ``` get_between(start: 'ea_t', end: 'ea_t') -> Iterator[insn_t] ``` Retrieves instructions between the specified addresses. Args: start: Start of the address range. end: End of the address range. Returns: An instruction iterator. #### get_disassembly ``` get_disassembly(insn: insn_t) -> str | None ``` Retrieves the disassembled string representation of the given instruction. Args: insn: The instruction to disassemble. Returns: The disassembly as string, if fails, returns None. #### get_mnemonic ``` get_mnemonic(insn: insn_t) -> str | None ``` Retrieves the mnemonic of the given instruction. Args: insn: The instruction to analyze. Returns: A string representing the mnemonic of the given instruction. If retrieving fails, returns None. #### get_operand ``` get_operand( insn: insn_t, index: int ) -> Optional[Operand] | None ``` Get a specific operand from the instruction. Args: insn: The instruction to analyze. index: The operand index (0, 1, 2, etc.). Returns: An Operand instance of the appropriate type, or None if the index is invalid or operand is void. #### get_operands ``` get_operands(insn: insn_t) -> List[Operand] ``` Get all operands from the instruction. Args: insn: The instruction to analyze. Returns: A list of Operand instances of appropriate types (excludes void operands). #### get_operands_count ``` get_operands_count(insn: insn_t) -> int ``` Retrieve the operands number of the given instruction. Args: insn: The instruction to analyze. Returns: An integer representing the number, if error, the number is negative. #### get_prev ``` get_prev(ea: 'ea_t') -> insn_t | None ``` Decodes prev instruction of the one at specified address. Args: ea: The effective address of the instruction. Returns: An insn_t instance, if fails returns None. #### is_call_instruction ``` is_call_instruction(insn: insn_t) -> bool ``` Check if the instruction is a call instruction. Args: insn: The instruction to analyze. Returns: True if this is a call instruction. #### is_jump_instruction ``` is_jump_instruction(insn: insn_t) -> bool ``` Check if the instruction is a jump instruction. Args: insn: The instruction to analyze. Returns: True if this is a jump instruction. #### is_return_instruction ``` is_return_instruction(insn: insn_t) -> bool ``` Check if the instruction is a return instruction. Args: insn: The instruction to analyze. Returns: True if this is a return instruction. #### is_valid ``` is_valid(insn: object) -> bool ``` Checks if the given instruction is valid. Args: insn: The instruction to validate. Returns: `True` if the instruction is valid, `False` otherwise. # `Names` ## names Classes: - **`DemangleFlags`** – Flags for demangling operations. - **`Names`** – Provides access to symbol and label management in the IDA database. - **`SetNameFlags`** – Flags for set_name() function. ### DemangleFlags Bases: `IntFlag` Flags for demangling operations. Attributes: - **`CALC_VALID`** – - **`COMPILER_MSK`** – - **`DEFFAR`** – - **`DEFHUGE`** – - **`DEFNEAR`** – - **`DEFNEARANY`** – - **`DEFNONE`** – - **`DEFPTR64`** – - **`DROP_IMP`** – - **`IGN_ANYWAY`** – - **`IGN_JMP`** – - **`LONG_FORM`** – - **`MOVE_JMP`** – - **`NOBASEDT`** – - **`NOCALLC`** – - **`NOCLOSUR`** – - **`NOCSVOL`** – - **`NODEFINIT`** – - **`NOECSU`** – - **`NOMANAGE`** – - **`NOMODULE`** – - **`NOPOSTFC`** – - **`NOPTRTYP`** – - **`NOPTRTYP16`** – - **`NORETTYPE`** – - **`NOSCTYP`** – - **`NOSTVIR`** – - **`NOTHROW`** – - **`NOTYPE`** – - **`NOUNALG`** – - **`NOUNDERSCORE`** – - **`PTRMSK`** – - **`SHORT_FORM`** – - **`SHORT_S`** – - **`SHORT_U`** – - **`ZPT_SPACE`** – #### CALC_VALID ``` CALC_VALID = MNG_CALC_VALID ``` #### COMPILER_MSK ``` COMPILER_MSK = MNG_COMPILER_MSK ``` #### DEFFAR ``` DEFFAR = MNG_DEFFAR ``` #### DEFHUGE ``` DEFHUGE = MNG_DEFHUGE ``` #### DEFNEAR ``` DEFNEAR = MNG_DEFNEAR ``` #### DEFNEARANY ``` DEFNEARANY = MNG_DEFNEARANY ``` #### DEFNONE ``` DEFNONE = MNG_DEFNONE ``` #### DEFPTR64 ``` DEFPTR64 = MNG_DEFPTR64 ``` #### DROP_IMP ``` DROP_IMP = MNG_DROP_IMP ``` #### IGN_ANYWAY ``` IGN_ANYWAY = MNG_IGN_ANYWAY ``` #### IGN_JMP ``` IGN_JMP = MNG_IGN_JMP ``` #### LONG_FORM ``` LONG_FORM = MNG_LONG_FORM ``` #### MOVE_JMP ``` MOVE_JMP = MNG_MOVE_JMP ``` #### NOBASEDT ``` NOBASEDT = MNG_NOBASEDT ``` #### NOCALLC ``` NOCALLC = MNG_NOCALLC ``` #### NOCLOSUR ``` NOCLOSUR = MNG_NOCLOSUR ``` #### NOCSVOL ``` NOCSVOL = MNG_NOCSVOL ``` #### NODEFINIT ``` NODEFINIT = MNG_NODEFINIT ``` #### NOECSU ``` NOECSU = MNG_NOECSU ``` #### NOMANAGE ``` NOMANAGE = MNG_NOMANAGE ``` #### NOMODULE ``` NOMODULE = MNG_NOMODULE ``` #### NOPOSTFC ``` NOPOSTFC = MNG_NOPOSTFC ``` #### NOPTRTYP ``` NOPTRTYP = MNG_NOPTRTYP ``` #### NOPTRTYP16 ``` NOPTRTYP16 = MNG_NOPTRTYP16 ``` #### NORETTYPE ``` NORETTYPE = MNG_NORETTYPE ``` #### NOSCTYP ``` NOSCTYP = MNG_NOSCTYP ``` #### NOSTVIR ``` NOSTVIR = MNG_NOSTVIR ``` #### NOTHROW ``` NOTHROW = MNG_NOTHROW ``` #### NOTYPE ``` NOTYPE = MNG_NOTYPE ``` #### NOUNALG ``` NOUNALG = MNG_NOUNALG ``` #### NOUNDERSCORE ``` NOUNDERSCORE = MNG_NOUNDERSCORE ``` #### PTRMSK ``` PTRMSK = MNG_PTRMSK ``` #### SHORT_FORM ``` SHORT_FORM = MNG_SHORT_FORM ``` #### SHORT_S ``` SHORT_S = MNG_SHORT_S ``` #### SHORT_U ``` SHORT_U = MNG_SHORT_U ``` #### ZPT_SPACE ``` ZPT_SPACE = MNG_ZPT_SPACE ``` ### Names ``` Names(database: 'Database') ``` Provides access to symbol and label management in the IDA database. Constructs a names handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`delete`** – Delete name at the specified address. - **`demangle_name`** – Demangle a mangled name. - **`force_name`** – Force set a name, trying variations if the name already exists. - **`get_all`** – Returns an iterator over all named elements in the database. - **`get_at`** – Retrieves the name at the specified address. - **`get_at_index`** – Retrieves the named element at the specified index. - **`get_count`** – Retrieves the total number of named elements in the database. - **`get_demangled_name`** – Get demangled name at address. - **`is_public_name`** – Check if name at address is public. - **`is_valid_name`** – Check if a name is a valid user defined name. - **`is_weak_name`** – Check if name at address is weak. - **`make_name_non_public`** – Make name at address non-public. - **`make_name_non_weak`** – Make name at address non-weak. - **`make_name_public`** – Make name at address public. - **`make_name_weak`** – Make name at address weak. - **`set_name`** – Set or delete name of an item at the specified address. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### delete ``` delete(ea: ea_t) -> bool ``` Delete name at the specified address. Args: ea: Linear address. Returns: True if successful, False otherwise. #### demangle_name ``` demangle_name( name: str, disable_mask: Union[int, DemangleFlags] = 0 ) -> str ``` Demangle a mangled name. Args: name: Mangled name to demangle. disable_mask: Bits to inhibit parts of demangled name (DemangleFlags enum or raw int). Returns: Demangled name or original name if demangling failed. #### force_name ``` force_name( ea: ea_t, name: str, flags: Union[int, SetNameFlags] = NOCHECK, ) -> bool ``` Force set a name, trying variations if the name already exists. Args: ea: Linear address. name: New name. flags: Set name flags (SetNameFlags enum or raw int). Returns: True if successful, False otherwise. #### get_all ``` get_all() -> Iterator[Tuple[ea_t, str]] ``` Returns an iterator over all named elements in the database. Returns: An iterator over (address, name) tuples. #### get_at ``` get_at(ea: ea_t) -> str | None ``` Retrieves the name at the specified address. Args: ea: The effective address. Returns: The name string if it exists, None otherwise. #### get_at_index ``` get_at_index(index: int) -> Tuple[ea_t, str] | None ``` Retrieves the named element at the specified index. Args: index: Index of the named element to retrieve. Returns: A tuple (effective address, name) at the given index. In case of error, returns None. #### get_count ``` get_count() -> int ``` Retrieves the total number of named elements in the database. Returns: The number of named elements. #### get_demangled_name ``` get_demangled_name( ea: ea_t, inhibitor: Union[int, DemangleFlags] = 0, demform: int = 0, ) -> str | None ``` Get demangled name at address. Args: ea: Linear address. inhibitor: Demangling inhibitor flags (DemangleFlags enum or raw int). demform: Demangling form flags. Returns: Demangled name or None if not available. #### is_public_name ``` is_public_name(ea: ea_t) -> bool ``` Check if name at address is public. Args: ea: Linear address. Returns: True if public, False otherwise. #### is_valid_name ``` is_valid_name(name: str) -> bool ``` Check if a name is a valid user defined name. Args: name: Name to validate. Returns: True if valid, False otherwise. #### is_weak_name ``` is_weak_name(ea: ea_t) -> bool ``` Check if name at address is weak. Args: ea: Linear address. Returns: True if weak, False otherwise. #### make_name_non_public ``` make_name_non_public(ea: ea_t) -> None ``` Make name at address non-public. Args: ea: Linear address. #### make_name_non_weak ``` make_name_non_weak(ea: ea_t) -> None ``` Make name at address non-weak. Args: ea: Linear address. #### make_name_public ``` make_name_public(ea: ea_t) -> None ``` Make name at address public. Args: ea: Linear address. #### make_name_weak ``` make_name_weak(ea: ea_t) -> None ``` Make name at address weak. Args: ea: Linear address. #### set_name ``` set_name( ea: ea_t, name: str, flags: Union[int, SetNameFlags] = NOCHECK, ) -> bool ``` Set or delete name of an item at the specified address. Args: ea: Linear address. name: New name. Empty string to delete name. flags: Set name flags (SetNameFlags enum or raw int). Returns: True if successful, False otherwise. ### SetNameFlags Bases: `IntFlag` Flags for set_name() function. Attributes: - **`AUTO`** – - **`CHECK`** – - **`DELTAIL`** – - **`FORCE`** – - **`IDBENC`** – - **`LOCAL`** – - **`NOCHECK`** – - **`NODUMMY`** – - **`NOLIST`** – - **`NON_AUTO`** – - **`NON_PUBLIC`** – - **`NON_WEAK`** – - **`NOWARN`** – - **`PUBLIC`** – - **`WEAK`** – #### AUTO ``` AUTO = SN_AUTO ``` #### CHECK ``` CHECK = SN_CHECK ``` #### DELTAIL ``` DELTAIL = SN_DELTAIL ``` #### FORCE ``` FORCE = SN_FORCE ``` #### IDBENC ``` IDBENC = SN_IDBENC ``` #### LOCAL ``` LOCAL = SN_LOCAL ``` #### NOCHECK ``` NOCHECK = SN_NOCHECK ``` #### NODUMMY ``` NODUMMY = SN_NODUMMY ``` #### NOLIST ``` NOLIST = SN_NOLIST ``` #### NON_AUTO ``` NON_AUTO = SN_NON_AUTO ``` #### NON_PUBLIC ``` NON_PUBLIC = SN_NON_PUBLIC ``` #### NON_WEAK ``` NON_WEAK = SN_NON_WEAK ``` #### NOWARN ``` NOWARN = SN_NOWARN ``` #### PUBLIC ``` PUBLIC = SN_PUBLIC ``` #### WEAK ``` WEAK = SN_WEAK ``` # `Operands` ## operands Classes: - **`AddressingInfo`** – Information about memory operand addressing. - **`ImmediateInfo`** – Information about an immediate operand. - **`ImmediateOperand`** – Operand representing immediate values (o_imm, o_far, o_near). - **`MemoryOperand`** – Operand representing memory access (o_mem, o_phrase, o_displ). - **`Operand`** – Abstract base class for all operand types. - **`OperandDataType`** – Enumeration of operand data types. - **`OperandFactory`** – Factory for creating appropriate operand instances. - **`OperandInfo`** – Basic information about an operand. - **`OperandType`** – Enumeration of operand types for easier identification. - **`ProcessorSpecificOperand`** – Operand representing processor-specific types (o_idpspec0-5). - **`RegisterInfo`** – Information about a register operand. - **`RegisterOperand`** – Operand representing a processor register (o_reg). ### AddressingInfo ``` AddressingInfo( addressing_type: str, formatted_string: Optional[str] = None, address: Optional[ea_t] = None, symbol_name: Optional[str] = None, phrase_number: Optional[int] = None, displacement: Optional[int] = None, outer_displacement: Optional[int] = None, has_outer_displacement: bool = False, ) ``` Information about memory operand addressing. Methods: - **`has_displacement`** – Check if this addressing mode has any displacement. - **`is_direct_memory`** – Check if this is direct memory addressing. - **`is_register_based`** – Check if this uses register-based addressing. Attributes: - **`address`** (`Optional[ea_t]`) – - **`addressing_type`** (`str`) – - **`displacement`** (`Optional[int]`) – - **`formatted_string`** (`Optional[str]`) – - **`has_outer_displacement`** (`bool`) – - **`outer_displacement`** (`Optional[int]`) – - **`phrase_number`** (`Optional[int]`) – - **`symbol_name`** (`Optional[str]`) – #### address ``` address: Optional[ea_t] = None ``` #### addressing_type ``` addressing_type: str ``` #### displacement ``` displacement: Optional[int] = None ``` #### formatted_string ``` formatted_string: Optional[str] = None ``` #### has_outer_displacement ``` has_outer_displacement: bool = False ``` #### outer_displacement ``` outer_displacement: Optional[int] = None ``` #### phrase_number ``` phrase_number: Optional[int] = None ``` #### symbol_name ``` symbol_name: Optional[str] = None ``` #### has_displacement ``` has_displacement() -> bool ``` Check if this addressing mode has any displacement. #### is_direct_memory ``` is_direct_memory() -> bool ``` Check if this is direct memory addressing. #### is_register_based ``` is_register_based() -> bool ``` Check if this uses register-based addressing. ### ImmediateInfo ``` ImmediateInfo( value: int, hex_value: str, is_address: bool, symbol_name: Optional[str] = None, signed_32bit: Optional[int] = None, ) ``` Information about an immediate operand. Attributes: - **`hex_value`** (`str`) – - **`is_address`** (`bool`) – - **`signed_32bit`** (`Optional[int]`) – - **`symbol_name`** (`Optional[str]`) – - **`value`** (`int`) – #### hex_value ``` hex_value: str ``` #### is_address ``` is_address: bool ``` #### signed_32bit ``` signed_32bit: Optional[int] = None ``` #### symbol_name ``` symbol_name: Optional[str] = None ``` #### value ``` value: int ``` ### ImmediateOperand ``` ImmediateOperand( database: 'Database', operand: op_t, instruction_ea: ea_t, ) ``` Bases: `Operand` Operand representing immediate values (o_imm, o_far, o_near). Methods: - **`get_access_type`** – Get a string description of how this operand is accessed. - **`get_data_type_name`** – Get a human-readable name for the operand data type. - **`get_hex_value`** – Get hex representation of the value. - **`get_immediate_info`** – Get detailed immediate information. - **`get_info`** – - **`get_name`** – Get the symbolic name for address operands. - **`get_register_info`** – Get detailed register information. - **`get_signed_32bit`** – Get signed 32-bit interpretation for large values. - **`get_type_name`** – - **`get_value`** – Get the immediate value or address. - **`has_outer_displacement`** – Check if this operand has an outer displacement. - **`is_address`** – Check if this is an address operand (far/near). - **`is_floating_point`** – Check if this is a floating point operand. - **`is_read`** – Check if this operand is read (used) by the instruction. - **`is_write`** – Check if this operand is written (modified) by the instruction. Attributes: - **`data_type`** (`OperandDataType`) – Get the operand data type as an enum. - **`flags`** (`int`) – Get the operand flags. - **`is_shown`** (`bool`) – Check if the operand should be displayed. - **`m_database`** – - **`number`** (`int`) – Get the operand number (0, 1, 2, etc.). - **`raw_operand`** (`op_t`) – Get the underlying op_t object. - **`size_bits`** (`int`) – Get the size of the operand in bits. - **`size_bytes`** (`int`) – Get the size of the operand in bytes. - **`type`** (`OperandType`) – Get the operand type as an enum. #### data_type ``` data_type: OperandDataType ``` Get the operand data type as an enum. #### flags ``` flags: int ``` Get the operand flags. #### is_shown ``` is_shown: bool ``` Check if the operand should be displayed. #### m_database ``` m_database = database ``` #### number ``` number: int ``` Get the operand number (0, 1, 2, etc.). #### raw_operand ``` raw_operand: op_t ``` Get the underlying op_t object. #### size_bits ``` size_bits: int ``` Get the size of the operand in bits. #### size_bytes ``` size_bytes: int ``` Get the size of the operand in bytes. #### type ``` type: OperandType ``` Get the operand type as an enum. #### get_access_type ``` get_access_type() -> str ``` Get a string description of how this operand is accessed. #### get_data_type_name ``` get_data_type_name() -> str ``` Get a human-readable name for the operand data type. #### get_hex_value ``` get_hex_value() -> str ``` Get hex representation of the value. #### get_immediate_info ``` get_immediate_info() -> ImmediateInfo ``` Get detailed immediate information. #### get_info ``` get_info() -> OperandInfo ``` #### get_name ``` get_name() -> Optional[str] ``` Get the symbolic name for address operands. #### get_register_info ``` get_register_info() -> RegisterInfo ``` Get detailed register information. #### get_signed_32bit ``` get_signed_32bit() -> Optional[int] ``` Get signed 32-bit interpretation for large values. #### get_type_name ``` get_type_name() -> str ``` #### get_value ``` get_value() -> int ``` Get the immediate value or address. #### has_outer_displacement ``` has_outer_displacement() -> bool ``` Check if this operand has an outer displacement. Returns True if the OF_OUTER_DISP flag is set. #### is_address ``` is_address() -> bool ``` Check if this is an address operand (far/near). #### is_floating_point ``` is_floating_point() -> bool ``` Check if this is a floating point operand. #### is_read ``` is_read() -> bool ``` Check if this operand is read (used) by the instruction. #### is_write ``` is_write() -> bool ``` Check if this operand is written (modified) by the instruction. ### MemoryOperand ``` MemoryOperand( database: 'Database', operand: op_t, instruction_ea: ea_t, ) ``` Bases: `Operand` Operand representing memory access (o_mem, o_phrase, o_displ). Methods: - **`get_access_type`** – Get a string description of how this operand is accessed. - **`get_address`** – Get the address for direct memory operands. - **`get_addressing_info`** – Get detailed addressing information. - **`get_base_register`** – Get the base register name (e.g., 'rsi', 'rbp'). - **`get_data_type_name`** – Get a human-readable name for the operand data type. - **`get_displacement`** – Get the base displacement value. - **`get_formatted_string`** – Get the formatted operand string from IDA. - **`get_index_register`** – Get the index register name (e.g., 'rdi', 'rcx'). - **`get_info`** – - **`get_name`** – Get the symbolic name for direct memory operands. - **`get_outer_displacement`** – Get the outer displacement value for complex addressing modes. - **`get_phrase_number`** – Get the phrase number for register-based operands. - **`get_register_info`** – Get detailed register information. - **`get_scale`** – Get the scale factor (1, 2, 4, or 8). - **`get_sib_components`** – Get SIB components: (base_register, index_register, scale, displacement). - **`get_sib_displacement`** – Get the displacement value from SIB addressing. - **`get_type_name`** – - **`get_value`** – Get the primary value based on memory type. - **`has_outer_displacement`** – Check if this operand has an outer displacement. - **`is_direct_memory`** – Check if this is direct memory access. - **`is_floating_point`** – Check if this is a floating point operand. - **`is_read`** – Check if this operand is read (used) by the instruction. - **`is_register_based`** – Check if this uses register-based addressing. - **`is_write`** – Check if this operand is written (modified) by the instruction. Attributes: - **`data_type`** (`OperandDataType`) – Get the operand data type as an enum. - **`flags`** (`int`) – Get the operand flags. - **`is_shown`** (`bool`) – Check if the operand should be displayed. - **`m_database`** – - **`number`** (`int`) – Get the operand number (0, 1, 2, etc.). - **`raw_operand`** (`op_t`) – Get the underlying op_t object. - **`size_bits`** (`int`) – Get the size of the operand in bits. - **`size_bytes`** (`int`) – Get the size of the operand in bytes. - **`type`** (`OperandType`) – Get the operand type as an enum. #### data_type ``` data_type: OperandDataType ``` Get the operand data type as an enum. #### flags ``` flags: int ``` Get the operand flags. #### is_shown ``` is_shown: bool ``` Check if the operand should be displayed. #### m_database ``` m_database = database ``` #### number ``` number: int ``` Get the operand number (0, 1, 2, etc.). #### raw_operand ``` raw_operand: op_t ``` Get the underlying op_t object. #### size_bits ``` size_bits: int ``` Get the size of the operand in bits. #### size_bytes ``` size_bytes: int ``` Get the size of the operand in bytes. #### type ``` type: OperandType ``` Get the operand type as an enum. #### get_access_type ``` get_access_type() -> str ``` Get a string description of how this operand is accessed. #### get_address ``` get_address() -> Optional[ea_t] ``` Get the address for direct memory operands. #### get_addressing_info ``` get_addressing_info() -> AddressingInfo ``` Get detailed addressing information. #### get_base_register ``` get_base_register() -> Optional[str] ``` Get the base register name (e.g., 'rsi', 'rbp'). #### get_data_type_name ``` get_data_type_name() -> str ``` Get a human-readable name for the operand data type. #### get_displacement ``` get_displacement() -> Optional[int] ``` Get the base displacement value. This is the primary displacement used in addressing modes like [reg + disp]. Stored in op_t.addr field. #### get_formatted_string ``` get_formatted_string() -> Optional[str] ``` Get the formatted operand string from IDA. #### get_index_register ``` get_index_register() -> Optional[str] ``` Get the index register name (e.g., 'rdi', 'rcx'). #### get_info ``` get_info() -> OperandInfo ``` #### get_name ``` get_name() -> Optional[str] ``` Get the symbolic name for direct memory operands. #### get_outer_displacement ``` get_outer_displacement() -> Optional[int] ``` Get the outer displacement value for complex addressing modes. Used in processors like 68k for nested addressing: ([reg + disp1], disp2) where disp1 is base displacement and disp2 is outer displacement. Only present when OF_OUTER_DISP flag is set. Stored in op_t.value field. #### get_phrase_number ``` get_phrase_number() -> Optional[int] ``` Get the phrase number for register-based operands. #### get_register_info ``` get_register_info() -> RegisterInfo ``` Get detailed register information. #### get_scale ``` get_scale() -> Optional[int] ``` Get the scale factor (1, 2, 4, or 8). #### get_sib_components ``` get_sib_components() -> tuple[ Optional[str], Optional[str], Optional[int], Optional[int], ] ``` Get SIB components: (base_register, index_register, scale, displacement). Returns: tuple: (base_reg, index_reg, scale, displacement) or (None, None, None, None) if fails #### get_sib_displacement ``` get_sib_displacement() -> Optional[int] ``` Get the displacement value from SIB addressing. #### get_type_name ``` get_type_name() -> str ``` #### get_value ``` get_value() -> Any ``` Get the primary value based on memory type. #### has_outer_displacement ``` has_outer_displacement() -> bool ``` Check if this operand has an outer displacement. Returns True if the OF_OUTER_DISP flag is set. #### is_direct_memory ``` is_direct_memory() -> bool ``` Check if this is direct memory access. #### is_floating_point ``` is_floating_point() -> bool ``` Check if this is a floating point operand. #### is_read ``` is_read() -> bool ``` Check if this operand is read (used) by the instruction. #### is_register_based ``` is_register_based() -> bool ``` Check if this uses register-based addressing. #### is_write ``` is_write() -> bool ``` Check if this operand is written (modified) by the instruction. ### Operand ``` Operand( database: 'Database', operand: op_t, instruction_ea: ea_t, ) ``` Bases: `ABC` Abstract base class for all operand types. Methods: - **`get_access_type`** – Get a string description of how this operand is accessed. - **`get_data_type_name`** – Get a human-readable name for the operand data type. - **`get_info`** – Get structured information about the operand. - **`get_register_info`** – Get detailed register information. - **`get_type_name`** – Get a human-readable name for the operand type. - **`get_value`** – Get the primary value of the operand. - **`is_floating_point`** – Check if this is a floating point operand. - **`is_read`** – Check if this operand is read (used) by the instruction. - **`is_write`** – Check if this operand is written (modified) by the instruction. Attributes: - **`data_type`** (`OperandDataType`) – Get the operand data type as an enum. - **`flags`** (`int`) – Get the operand flags. - **`is_shown`** (`bool`) – Check if the operand should be displayed. - **`m_database`** – - **`number`** (`int`) – Get the operand number (0, 1, 2, etc.). - **`raw_operand`** (`op_t`) – Get the underlying op_t object. - **`size_bits`** (`int`) – Get the size of the operand in bits. - **`size_bytes`** (`int`) – Get the size of the operand in bytes. - **`type`** (`OperandType`) – Get the operand type as an enum. #### data_type ``` data_type: OperandDataType ``` Get the operand data type as an enum. #### flags ``` flags: int ``` Get the operand flags. #### is_shown ``` is_shown: bool ``` Check if the operand should be displayed. #### m_database ``` m_database = database ``` #### number ``` number: int ``` Get the operand number (0, 1, 2, etc.). #### raw_operand ``` raw_operand: op_t ``` Get the underlying op_t object. #### size_bits ``` size_bits: int ``` Get the size of the operand in bits. #### size_bytes ``` size_bytes: int ``` Get the size of the operand in bytes. #### type ``` type: OperandType ``` Get the operand type as an enum. #### get_access_type ``` get_access_type() -> str ``` Get a string description of how this operand is accessed. #### get_data_type_name ``` get_data_type_name() -> str ``` Get a human-readable name for the operand data type. #### get_info ``` get_info() -> OperandInfo ``` Get structured information about the operand. #### get_register_info ``` get_register_info() -> RegisterInfo ``` Get detailed register information. #### get_type_name ``` get_type_name() -> str ``` Get a human-readable name for the operand type. #### get_value ``` get_value() -> Any ``` Get the primary value of the operand. #### is_floating_point ``` is_floating_point() -> bool ``` Check if this is a floating point operand. #### is_read ``` is_read() -> bool ``` Check if this operand is read (used) by the instruction. #### is_write ``` is_write() -> bool ``` Check if this operand is written (modified) by the instruction. ### OperandDataType Bases: `IntEnum` Enumeration of operand data types. Attributes: - **`BITFIELD`** – - **`BYTE`** – - **`BYTE16`** – - **`BYTE32`** – - **`BYTE64`** – - **`CODE`** – - **`DOUBLE`** – - **`DWORD`** – - **`FLOAT`** – - **`FWORD`** – - **`HALF`** – - **`LDBL`** – - **`PACKREAL`** – - **`QWORD`** – - **`STRING`** – - **`TBYTE`** – - **`UNICODE`** – - **`VOID`** – - **`WORD`** – #### BITFIELD ``` BITFIELD = dt_bitfild ``` #### BYTE ``` BYTE = dt_byte ``` #### BYTE16 ``` BYTE16 = dt_byte16 ``` #### BYTE32 ``` BYTE32 = dt_byte32 ``` #### BYTE64 ``` BYTE64 = dt_byte64 ``` #### CODE ``` CODE = dt_code ``` #### DOUBLE ``` DOUBLE = dt_double ``` #### DWORD ``` DWORD = dt_dword ``` #### FLOAT ``` FLOAT = dt_float ``` #### FWORD ``` FWORD = dt_fword ``` #### HALF ``` HALF = dt_half ``` #### LDBL ``` LDBL = dt_ldbl ``` #### PACKREAL ``` PACKREAL = dt_packreal ``` #### QWORD ``` QWORD = dt_qword ``` #### STRING ``` STRING = dt_string ``` #### TBYTE ``` TBYTE = dt_tbyte ``` #### UNICODE ``` UNICODE = dt_unicode ``` #### VOID ``` VOID = dt_void ``` #### WORD ``` WORD = dt_word ``` ### OperandFactory Factory for creating appropriate operand instances. Methods: - **`create`** – Create an operand instance based on the operand type. #### create ``` create( database: 'Database', operand: op_t, instruction_ea: int ) -> Optional[Operand] ``` Create an operand instance based on the operand type. ### OperandInfo ``` OperandInfo( number: int, type_name: str, data_type_name: str, size_bytes: int, size_bits: Optional[int] = None, flags: Optional[str] = None, is_hidden: bool = False, special_value: Optional[str] = None, is_floating_point: bool = False, is_read: bool = False, is_write: bool = False, access_type: Optional[str] = None, ) ``` Basic information about an operand. Attributes: - **`access_type`** (`Optional[str]`) – - **`data_type_name`** (`str`) – - **`flags`** (`Optional[str]`) – - **`is_floating_point`** (`bool`) – - **`is_hidden`** (`bool`) – - **`is_read`** (`bool`) – - **`is_write`** (`bool`) – - **`number`** (`int`) – - **`size_bits`** (`Optional[int]`) – - **`size_bytes`** (`int`) – - **`special_value`** (`Optional[str]`) – - **`type_name`** (`str`) – #### access_type ``` access_type: Optional[str] = None ``` #### data_type_name ``` data_type_name: str ``` #### flags ``` flags: Optional[str] = None ``` #### is_floating_point ``` is_floating_point: bool = False ``` #### is_hidden ``` is_hidden: bool = False ``` #### is_read ``` is_read: bool = False ``` #### is_write ``` is_write: bool = False ``` #### number ``` number: int ``` #### size_bits ``` size_bits: Optional[int] = None ``` #### size_bytes ``` size_bytes: int ``` #### special_value ``` special_value: Optional[str] = None ``` #### type_name ``` type_name: str ``` ### OperandType Bases: `IntEnum` Enumeration of operand types for easier identification. Attributes: - **`DISPLACEMENT`** – - **`FAR_ADDRESS`** – - **`IMMEDIATE`** – - **`MEMORY`** – - **`NEAR_ADDRESS`** – - **`PHRASE`** – - **`PROCESSOR_SPECIFIC_0`** – - **`PROCESSOR_SPECIFIC_1`** – - **`PROCESSOR_SPECIFIC_2`** – - **`PROCESSOR_SPECIFIC_3`** – - **`PROCESSOR_SPECIFIC_4`** – - **`PROCESSOR_SPECIFIC_5`** – - **`REGISTER`** – - **`VOID`** – #### DISPLACEMENT ``` DISPLACEMENT = o_displ ``` #### FAR_ADDRESS ``` FAR_ADDRESS = o_far ``` #### IMMEDIATE ``` IMMEDIATE = o_imm ``` #### MEMORY ``` MEMORY = o_mem ``` #### NEAR_ADDRESS ``` NEAR_ADDRESS = o_near ``` #### PHRASE ``` PHRASE = o_phrase ``` #### PROCESSOR_SPECIFIC_0 ``` PROCESSOR_SPECIFIC_0 = o_idpspec0 ``` #### PROCESSOR_SPECIFIC_1 ``` PROCESSOR_SPECIFIC_1 = o_idpspec1 ``` #### PROCESSOR_SPECIFIC_2 ``` PROCESSOR_SPECIFIC_2 = o_idpspec2 ``` #### PROCESSOR_SPECIFIC_3 ``` PROCESSOR_SPECIFIC_3 = o_idpspec3 ``` #### PROCESSOR_SPECIFIC_4 ``` PROCESSOR_SPECIFIC_4 = o_idpspec4 ``` #### PROCESSOR_SPECIFIC_5 ``` PROCESSOR_SPECIFIC_5 = o_idpspec5 ``` #### REGISTER ``` REGISTER = o_reg ``` #### VOID ``` VOID = o_void ``` ### ProcessorSpecificOperand ``` ProcessorSpecificOperand( database: 'Database', operand: op_t, instruction_ea: int ) ``` Bases: `Operand` Operand representing processor-specific types (o_idpspec0-5). Methods: - **`get_access_type`** – Get a string description of how this operand is accessed. - **`get_data_type_name`** – Get a human-readable name for the operand data type. - **`get_info`** – - **`get_register_info`** – Get detailed register information. - **`get_spec_type`** – Get the processor-specific type number (0-5). - **`get_type_name`** – - **`get_value`** – Return raw value for processor-specific operands. - **`is_floating_point`** – Check if this is a floating point operand. - **`is_read`** – Check if this operand is read (used) by the instruction. - **`is_write`** – Check if this operand is written (modified) by the instruction. Attributes: - **`data_type`** (`OperandDataType`) – Get the operand data type as an enum. - **`flags`** (`int`) – Get the operand flags. - **`is_shown`** (`bool`) – Check if the operand should be displayed. - **`m_database`** – - **`number`** (`int`) – Get the operand number (0, 1, 2, etc.). - **`raw_operand`** (`op_t`) – Get the underlying op_t object. - **`size_bits`** (`int`) – Get the size of the operand in bits. - **`size_bytes`** (`int`) – Get the size of the operand in bytes. - **`type`** (`OperandType`) – Get the operand type as an enum. #### data_type ``` data_type: OperandDataType ``` Get the operand data type as an enum. #### flags ``` flags: int ``` Get the operand flags. #### is_shown ``` is_shown: bool ``` Check if the operand should be displayed. #### m_database ``` m_database = database ``` #### number ``` number: int ``` Get the operand number (0, 1, 2, etc.). #### raw_operand ``` raw_operand: op_t ``` Get the underlying op_t object. #### size_bits ``` size_bits: int ``` Get the size of the operand in bits. #### size_bytes ``` size_bytes: int ``` Get the size of the operand in bytes. #### type ``` type: OperandType ``` Get the operand type as an enum. #### get_access_type ``` get_access_type() -> str ``` Get a string description of how this operand is accessed. #### get_data_type_name ``` get_data_type_name() -> str ``` Get a human-readable name for the operand data type. #### get_info ``` get_info() -> OperandInfo ``` #### get_register_info ``` get_register_info() -> RegisterInfo ``` Get detailed register information. #### get_spec_type ``` get_spec_type() -> int ``` Get the processor-specific type number (0-5). #### get_type_name ``` get_type_name() -> str ``` #### get_value ``` get_value() -> Any ``` Return raw value for processor-specific operands. #### is_floating_point ``` is_floating_point() -> bool ``` Check if this is a floating point operand. #### is_read ``` is_read() -> bool ``` Check if this operand is read (used) by the instruction. #### is_write ``` is_write() -> bool ``` Check if this operand is written (modified) by the instruction. ### RegisterInfo ``` RegisterInfo(register_number: int, register_name: str) ``` Information about a register operand. Attributes: - **`register_name`** (`str`) – - **`register_number`** (`int`) – #### register_name ``` register_name: str ``` #### register_number ``` register_number: int ``` ### RegisterOperand ``` RegisterOperand( database: 'Database', operand: op_t, instruction_ea: ea_t, ) ``` Bases: `Operand` Operand representing a processor register (o_reg). Methods: - **`get_access_type`** – Get a string description of how this operand is accessed. - **`get_data_type_name`** – Get a human-readable name for the operand data type. - **`get_info`** – - **`get_register_info`** – Get detailed register information. - **`get_register_name`** – Get the name of this register using the operand's size. - **`get_type_name`** – - **`get_value`** – - **`is_floating_point`** – Check if this is a floating point operand. - **`is_read`** – Check if this operand is read (used) by the instruction. - **`is_write`** – Check if this operand is written (modified) by the instruction. Attributes: - **`data_type`** (`OperandDataType`) – Get the operand data type as an enum. - **`flags`** (`int`) – Get the operand flags. - **`is_shown`** (`bool`) – Check if the operand should be displayed. - **`m_database`** – - **`number`** (`int`) – Get the operand number (0, 1, 2, etc.). - **`raw_operand`** (`op_t`) – Get the underlying op_t object. - **`register_number`** (`int`) – Get the register number. - **`size_bits`** (`int`) – Get the size of the operand in bits. - **`size_bytes`** (`int`) – Get the size of the operand in bytes. - **`type`** (`OperandType`) – Get the operand type as an enum. #### data_type ``` data_type: OperandDataType ``` Get the operand data type as an enum. #### flags ``` flags: int ``` Get the operand flags. #### is_shown ``` is_shown: bool ``` Check if the operand should be displayed. #### m_database ``` m_database = database ``` #### number ``` number: int ``` Get the operand number (0, 1, 2, etc.). #### raw_operand ``` raw_operand: op_t ``` Get the underlying op_t object. #### register_number ``` register_number: int ``` Get the register number. #### size_bits ``` size_bits: int ``` Get the size of the operand in bits. #### size_bytes ``` size_bytes: int ``` Get the size of the operand in bytes. #### type ``` type: OperandType ``` Get the operand type as an enum. #### get_access_type ``` get_access_type() -> str ``` Get a string description of how this operand is accessed. #### get_data_type_name ``` get_data_type_name() -> str ``` Get a human-readable name for the operand data type. #### get_info ``` get_info() -> OperandInfo ``` #### get_register_info ``` get_register_info() -> RegisterInfo ``` Get detailed register information. #### get_register_name ``` get_register_name() -> str ``` Get the name of this register using the operand's size. #### get_type_name ``` get_type_name() -> str ``` #### get_value ``` get_value() -> int ``` #### is_floating_point ``` is_floating_point() -> bool ``` Check if this is a floating point operand. #### is_read ``` is_read() -> bool ``` Check if this operand is read (used) by the instruction. #### is_write ``` is_write() -> bool ``` Check if this operand is written (modified) by the instruction. # `Segments` ## segments Classes: - **`Segments`** – Provides access to segment-related operations in the IDA database. ### Segments ``` Segments(database: 'Database') ``` Provides access to segment-related operations in the IDA database. Constructs a segment handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`get_all`** – Retrieves an iterator over all segments in the database. - **`get_at`** – Retrieves the segment that contains the given address. - **`get_name`** – Retrieves the name of the given segment. - **`set_name`** – Renames a segment. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### get_all ``` get_all() -> Iterator[segment_t] ``` Retrieves an iterator over all segments in the database. Returns: A generator yielding all segments in the database. #### get_at ``` get_at(ea: int) -> Optional[segment_t] ``` Retrieves the segment that contains the given address. Args: ea: The effective address to search. Returns: A pointer to the containing segment, or None if none found. #### get_name ``` get_name(segment: segment_t) -> str ``` Retrieves the name of the given segment. Args: segment: Pointer to the segment. Returns: The segment name as a string, or an empty string if unavailable. #### set_name ``` set_name(segment: segment_t, name: str) -> bool ``` Renames a segment. Args: segment: Pointer to the segment to rename. name: The new name to assign to the segment. Returns: True if the rename operation succeeded, False otherwise. # `Signature Files` ## signature_files Classes: - **`FileInfo`** – Represents information about a FLIRT signature file application. - **`MatchInfo`** – Represents information about a single function matched by a FLIRT signature. - **`SignatureFiles`** – Provides access to FLIRT signature (.sig) files in the IDA database. ### FileInfo ``` FileInfo( path: str = '', matches: int = 0, functions: List[MatchInfo] = list(), ) ``` Represents information about a FLIRT signature file application. Contains the signature file path, number of matches, and details of matched functions. Attributes: - **`functions`** (`List[MatchInfo]`) – - **`matches`** (`int`) – - **`path`** (`str`) – #### functions ``` functions: List[MatchInfo] = field(default_factory=list) ``` #### matches ``` matches: int = 0 ``` #### path ``` path: str = '' ``` ### MatchInfo ``` MatchInfo(addr: ea_t, name: str = '', lib: str = '') ``` Represents information about a single function matched by a FLIRT signature. Attributes: - **`addr`** (`ea_t`) – - **`lib`** (`str`) – - **`name`** (`str`) – #### addr ``` addr: ea_t ``` #### lib ``` lib: str = '' ``` #### name ``` name: str = '' ``` ### SignatureFiles ``` SignatureFiles(database: 'Database') ``` Provides access to FLIRT signature (.sig) files in the IDA database. Constructs a signature file handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`apply`** – Applies signature files to current database. - **`create`** – Create signature files (.pat and .sig) from current database. - **`get_files`** – Retrieves a list of available FLIRT signature (.sig) files. - **`get_index`** – Get index of applied signature file. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### apply ``` apply(path: Path, probe_only: bool = False) ``` Applies signature files to current database. Args: path: Path to the signature file or directory with sig files. probe_only: If true, signature files are only probed (apply operation is undone). Returns: A list of FileInfo objects containing application details. #### create ``` create(pat_only: bool = False) -> List[str] | None ``` Create signature files (.pat and .sig) from current database. Args: pat_only: If true, generate only PAT file. Returns: A list containing paths to the generated files. In case of failure, returns None. #### get_files ``` get_files(directories: List[Path] = None) -> List[Path] ``` Retrieves a list of available FLIRT signature (.sig) files. Args: directories: Optional list of paths to directories containing FLIRT signature files. If the parameter is missing, IDA signature folders will be used. Returns: A list of available signature file paths. #### get_index ``` get_index(path: Path) -> int ``` Get index of applied signature file. Args: path: Path to the signature file. Returns: Index of applied signature file, -1 if not found. # `Strings` ## strings Classes: - **`StringInfo`** – Represents detailed information about a string in the IDA database. - **`StringType`** – String type constants. - **`Strings`** – Provides access to string-related operations in the IDA database. ### StringInfo ``` StringInfo( address: ea_t, content: str, length: int, type: StringType, ) ``` Represents detailed information about a string in the IDA database. Methods: - **`get_encoding_info`** – Get a human-readable description of the string encoding. - **`is_c_string`** – Check if this is a C-style null-terminated string. - **`is_pascal_string`** – Check if this is a Pascal-style string. - **`is_unicode`** – Check if this is a Unicode string. Attributes: - **`address`** (`ea_t`) – - **`content`** (`str`) – - **`length`** (`int`) – - **`type`** (`StringType`) – #### address ``` address: ea_t ``` #### content ``` content: str ``` #### length ``` length: int ``` #### type ``` type: StringType ``` #### get_encoding_info ``` get_encoding_info() -> str ``` Get a human-readable description of the string encoding. #### is_c_string ``` is_c_string() -> bool ``` Check if this is a C-style null-terminated string. #### is_pascal_string ``` is_pascal_string() -> bool ``` Check if this is a Pascal-style string. #### is_unicode ``` is_unicode() -> bool ``` Check if this is a Unicode string. ### StringType Bases: `IntEnum` String type constants. Attributes: - **`C`** – - **`C_16`** – - **`C_32`** – - **`LEN2`** – - **`LEN2_16`** – - **`LEN2_32`** – - **`PASCAL`** – - **`PASCAL_16`** – - **`PASCAL_32`** – #### C ``` C = STRTYPE_C ``` #### C_16 ``` C_16 = STRTYPE_C_16 ``` #### C_32 ``` C_32 = STRTYPE_C_32 ``` #### LEN2 ``` LEN2 = STRTYPE_LEN2 ``` #### LEN2_16 ``` LEN2_16 = STRTYPE_LEN2_16 ``` #### LEN2_32 ``` LEN2_32 = STRTYPE_LEN2_32 ``` #### PASCAL ``` PASCAL = STRTYPE_PASCAL ``` #### PASCAL_16 ``` PASCAL_16 = STRTYPE_PASCAL_16 ``` #### PASCAL_32 ``` PASCAL_32 = STRTYPE_PASCAL_32 ``` ### Strings ``` Strings(database: 'Database') ``` Provides access to string-related operations in the IDA database. Constructs a strings handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`build_string_list`** – Rebuild the string list from scratch. - **`clear_string_list`** – Clear the string list. - **`exists_at`** – Check if the specified address contains a string. - **`find_strings_containing`** – Find all strings containing the specified substring. - **`get_all`** – Retrieves an iterator over all extracted strings in the database. - **`get_at`** – Retrieves detailed string information at the specified address. - **`get_at_index`** – Retrieves the string at the specified index. - **`get_between`** – Retrieves strings within the specified address range. - **`get_count`** – Retrieves the total number of extracted strings. - **`get_length`** – Get the length at the specified address. - **`get_type`** – Get the type at the specified address. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### build_string_list ``` build_string_list() -> None ``` Rebuild the string list from scratch. This should be called to get an up-to-date string list. #### clear_string_list ``` clear_string_list() -> None ``` Clear the string list. #### exists_at ``` exists_at(ea: ea_t) -> bool ``` Check if the specified address contains a string. Args: ea: The effective address. Returns: True if address contains a string, False otherwise. #### find_strings_containing ``` find_strings_containing( substring: str, case_sensitive: bool = False ) -> Iterator[Tuple[ea_t, str]] ``` Find all strings containing the specified substring. Args: substring: Substring to search for. case_sensitive: Whether the search should be case sensitive. Returns: Iterator over matching strings (address, content). #### get_all ``` get_all() -> Iterator[Tuple[ea_t, str]] ``` Retrieves an iterator over all extracted strings in the database. Returns: An iterator over all strings. #### get_at ``` get_at(ea: ea_t) -> StringInfo | None ``` Retrieves detailed string information at the specified address. Args: ea: The effective address. Returns: A StringInfo object if found, None otherwise. #### get_at_index ``` get_at_index(index: int) -> Tuple[ea_t, str] | None ``` Retrieves the string at the specified index. Args: index: Index of the string to retrieve. Returns: A pair (effective address, string content) at the given index. In case of error, returns None. #### get_between ``` get_between( start_ea: ea_t, end_ea: ea_t ) -> Iterator[Tuple[ea_t, str]] ``` Retrieves strings within the specified address range. Args: start_ea: Start address of the range (inclusive). end_ea: End address of the range (exclusive). Returns: An iterator over strings in the range. #### get_count ``` get_count() -> int ``` Retrieves the total number of extracted strings. Returns: The number of stored strings. #### get_length ``` get_length(ea: ea_t) -> int ``` Get the length at the specified address. Args: ea: The effective address. Returns: String length or -1 if not a string. #### get_type ``` get_type(ea: ea_t) -> Union[StringType, int] ``` Get the type at the specified address. Args: ea: The effective address. Returns: String type (StringType enum) or -1 if not a string. # `Types` ## types Classes: - **`TypeKind`** – Type category enumeration. - **`Types`** – Provides access to type information and manipulation in the IDA database. ### TypeKind Bases: `Enum` Type category enumeration. Attributes: - **`NAMED`** – - **`NUMBERED`** – #### NAMED ``` NAMED = 1 ``` #### NUMBERED ``` NUMBERED = 2 ``` ### Types ``` Types(database: 'Database') ``` Provides access to type information and manipulation in the IDA database. Constructs a types handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`apply_named_type`** – Applies a named type to the given address. - **`get_all`** – Retrieves a generator over all types in the specified type library. - **`get_name_at`** – Retrieves the type information of the item at the given address. - **`get_names`** – Retrieves a generator over all names in the specified type library. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### apply_named_type ``` apply_named_type(ea: 'ea_t', type: 'str') ``` Applies a named type to the given address. Args: ea: The effective address. type: The name of the type to apply. Returns: True if the type was applied successfully, false otherwise. #### get_all ``` get_all( type_kind: TypeKind = NAMED, type_library: str = '' ) ``` Retrieves a generator over all types in the specified type library. #### get_name_at ``` get_name_at(ea: 'ea_t') -> str | None ``` Retrieves the type information of the item at the given address. Args: ea: The effective address. Returns: The type name or None if it does not exist. #### get_names ``` get_names(type_library: str = '') ``` Retrieves a generator over all names in the specified type library. # `Xrefs` ## xrefs Classes: - **`CodeRefType`** – Code reference types. - **`DataRefType`** – Data reference types. - **`Xrefs`** – Provides access to cross-reference (xref) analysis in the IDA database. - **`XrefsKind`** – Enumeration for IDA Xrefs types. Functions: - **`get_ref_type_name`** – Get human-readable name for xref type. - **`is_call_ref`** – Check if xref type is a call reference. - **`is_code_ref`** – Check if xref type is a code reference. - **`is_data_ref`** – Check if xref type is a data reference. - **`is_jump_ref`** – Check if xref type is a jump reference. - **`is_offset_ref`** – Check if xref type is an offset reference. - **`is_read_ref`** – Check if xref type is a data read reference. - **`is_write_ref`** – Check if xref type is a data write reference. ### CodeRefType Bases: `IntEnum` Code reference types. Attributes: - **`CALL_FAR`** – - **`CALL_NEAR`** – - **`JUMP_FAR`** – - **`JUMP_NEAR`** – - **`ORDINARY_FLOW`** – - **`UNKNOWN`** – - **`USER_SPECIFIED`** – #### CALL_FAR ``` CALL_FAR = fl_CF ``` #### CALL_NEAR ``` CALL_NEAR = fl_CN ``` #### JUMP_FAR ``` JUMP_FAR = fl_JF ``` #### JUMP_NEAR ``` JUMP_NEAR = fl_JN ``` #### ORDINARY_FLOW ``` ORDINARY_FLOW = fl_F ``` #### UNKNOWN ``` UNKNOWN = fl_U ``` #### USER_SPECIFIED ``` USER_SPECIFIED = fl_USobsolete ``` ### DataRefType Bases: `IntEnum` Data reference types. Attributes: - **`INFORMATIONAL`** – - **`OFFSET`** – - **`READ`** – - **`SYMBOLIC`** – - **`TEXT`** – - **`UNKNOWN`** – - **`WRITE`** – #### INFORMATIONAL ``` INFORMATIONAL = dr_I ``` #### OFFSET ``` OFFSET = dr_O ``` #### READ ``` READ = dr_R ``` #### SYMBOLIC ``` SYMBOLIC = dr_S ``` #### TEXT ``` TEXT = dr_T ``` #### UNKNOWN ``` UNKNOWN = dr_U ``` #### WRITE ``` WRITE = dr_W ``` ### Xrefs ``` Xrefs(database: 'Database') ``` Provides access to cross-reference (xref) analysis in the IDA database. Constructs a xrefs handler for the given database. Args: database: Reference to the active IDA database. Methods: - **`get_calls_from`** – Get all call references from the specified address. - **`get_calls_to`** – Get all call references to the specified address. - **`get_data_reads_of`** – Get all places that read data from the specified address. - **`get_data_writes_to`** – Get all places that write data to the specified address. - **`get_from`** – Creates an iterator over all xrefs originating from a given address. - **`get_jumps_from`** – Get all jump references from the specified address. - **`get_jumps_to`** – Get all jump references to the specified address. - **`get_name`** – Get human-readable xref type name. - **`get_ref_type_name`** – Get human-readable name for xref type. - **`get_to`** – Creates an iterator over all xrefs pointing to a given address. - **`is_call_ref`** – Check if xref type is a call reference. - **`is_code_ref`** – Check if xref type is a code reference. - **`is_data_ref`** – Check if xref type is a data reference. - **`is_jump_ref`** – Check if xref type is a jump reference. - **`is_offset_ref`** – Check if xref type is an offset reference. - **`is_read_ref`** – Check if xref type is a data read reference. - **`is_write_ref`** – Check if xref type is a data write reference. Attributes: - **`m_database`** – #### m_database ``` m_database = database ``` #### get_calls_from ``` get_calls_from(ea: int) ``` Get all call references from the specified address. Args: ea: Source effective address. Returns: An iterator over call references from the address. #### get_calls_to ``` get_calls_to(ea: int) ``` Get all call references to the specified address. Args: ea: Target effective address. Returns: An iterator over call references to the address. #### get_data_reads_of ``` get_data_reads_of(ea: int) ``` Get all places that read data from the specified address. Args: ea: Target effective address (the data being read). Returns: An iterator over references that read data from the address. #### get_data_writes_to ``` get_data_writes_to(ea: int) ``` Get all places that write data to the specified address. Args: ea: Target effective address (the data being written to). Returns: An iterator over references that write data to the address. #### get_from ``` get_from( ea: int, kind: XrefsKind = ALL, flow: bool = False ) ``` Creates an iterator over all xrefs originating from a given address. Args: ea: Source effective address. kind: Xrefs kind (defaults to XrefsKind.ALL). flow: Follow normal code flow or not (defaults to True). Returns: An iterator over outgoing xrefs. #### get_jumps_from ``` get_jumps_from(ea: int) ``` Get all jump references from the specified address. Args: ea: Source effective address. Returns: An iterator over jump references from the address. #### get_jumps_to ``` get_jumps_to(ea: int) ``` Get all jump references to the specified address. Args: ea: Target effective address. Returns: An iterator over jump references to the address. #### get_name ``` get_name(ref: xrefblk_t()) ``` Get human-readable xref type name. Args: ref: A xref block. Returns: A human-readable xref type name. #### get_ref_type_name ``` get_ref_type_name( xref_type: Union[int, CodeRefType, DataRefType], ) -> str ``` Get human-readable name for xref type. #### get_to ``` get_to(ea: int, kind: XrefsKind = ALL, flow: bool = True) ``` Creates an iterator over all xrefs pointing to a given address. Args: ea: Target effective address. kind: Xrefs kind (defaults to XrefsKind.ALL). flow: Follow normal code flow or not (defaults to True). Returns: An iterator over references to input target addresses. #### is_call_ref ``` is_call_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a call reference. #### is_code_ref ``` is_code_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a code reference. #### is_data_ref ``` is_data_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a data reference. #### is_jump_ref ``` is_jump_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a jump reference. #### is_offset_ref ``` is_offset_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is an offset reference. #### is_read_ref ``` is_read_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a data read reference. #### is_write_ref ``` is_write_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a data write reference. ### XrefsKind Bases: `Enum` Enumeration for IDA Xrefs types. Attributes: - **`ALL`** – - **`CODE`** – - **`DATA`** – #### ALL ``` ALL = 'all' ``` #### CODE ``` CODE = 'code' ``` #### DATA ``` DATA = 'data' ``` ### get_ref_type_name ``` get_ref_type_name( xref_type: Union[int, CodeRefType, DataRefType], ) -> str ``` Get human-readable name for xref type. ### is_call_ref ``` is_call_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a call reference. ### is_code_ref ``` is_code_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a code reference. ### is_data_ref ``` is_data_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a data reference. ### is_jump_ref ``` is_jump_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a jump reference. ### is_offset_ref ``` is_offset_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is an offset reference. ### is_read_ref ``` is_read_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a data read reference. ### is_write_ref ``` is_write_ref( xref_type: Union[int, CodeRefType, DataRefType], ) -> bool ``` Check if xref type is a data write reference.