### Starting Cygwin Shell on Windows Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Command to start the Cygwin shell from the Windows Command Prompt. ```Batch C:\cygwin\cygwin.bat ``` -------------------------------- ### Example Shell Commands for Building IDAPython Plugins Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/build.md These examples illustrate how to invoke the `build.py` script from the command line on different operating systems (Windows, Linux/OSX) to compile IDAPython plugins. They demonstrate specifying the SWIG installation path, enabling Hex-Rays bindings, and providing the IDA installation directory. ```shell python3 build.py \ --with-hexrays \ --swig-home C:/swigwin-4.0.1 \ --ida-install "c:/Program\\ Files/IDA_8.0" ``` ```shell python3 build.py \ --with-hexrays \ --swig-home /opt/swiglinux-4.0.1 \ --ida-install /opt/my-ida-install ``` -------------------------------- ### Advanced Build Commands with `make` and `idamake.pl` on Linux/macOS Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Examples of `make` commands for optimized and non-optimized builds across different platforms, and using `idamake.pl` with `IDAMAKE_SIMPLIFY` to filter compiler output. ```Shell make __LINUX__=1 make NDEBUG=1 __MAC__=1 __ARM__=1 make NDEBUG=1 __NT__=1 IDAMAKE_SIMPLIFY=1 idamake.pl [...] ``` -------------------------------- ### Setting Visual C++ Installation Directory on Windows Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Defines the VCINSTALLDIR environment variable, pointing to the Visual C++ installation path, which is required for the build system. ```Batch set VCINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\ ``` -------------------------------- ### Execute IDA SDK Build Command Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Shows an example of running the `mo.bat` build command for the IDA SDK with parallel job execution. ```Shell /cygdrive/c/idasdk $ mo.bat -j 12 ``` -------------------------------- ### Parse Command-Line Arguments and Detect OS for IDA Library Setup Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/idalib/python/py-activate-idalib.md This section initializes an argument parser to accept the IDA installation directory. It also detects the operating system to determine the correct IDA library filename (e.g., `idalib.dll` for Windows, `libidalib.so` for Linux). ```python import argparse import platform # Parse input arguments parser = argparse.ArgumentParser(description="IDA Python Library setup utility") parser.add_argument( "-d", "--ida-install-dir", help="IDA installation directory to be used by ida Python library", type=str, required=False, default=None ) args = parser.parse_args() platform_str = platform.system() if platform_str == "Windows": libname = "idalib.dll" elif platform_str == "Linux": libname = "libidalib.so" elif platform_str == "Darwin": libname = "libidalib.dylib" else: raise Exception(f"Unknown platform {platform_str}") ``` -------------------------------- ### Create a Basic 'Hello World' IDA Pro Python Plugin Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/hello/pyhello.md This Python code defines a minimal plugin for IDA Pro. It consists of two main classes: `hello_plugmod_t` which contains the plugin's core logic (printing 'Hello world!'), and `hello_plugin_t` which handles the plugin's initialization and metadata. The `PLUGIN_ENTRY` function serves as the entry point for IDA Pro to load the plugin. ```Python import idaapi class hello_plugmod_t(idaapi.plugmod_t): def run(self, arg): print("Hello world! (py)") return 0 class hello_plugin_t(idaapi.plugin_t): flags = idaapi.PLUGIN_UNL | idaapi.PLUGIN_MULTI comment = "This is a comment" help = "This is help" wanted_name = "Hello Python plugin" wanted_hotkey = "Alt-F8" def init(self): return hello_plugmod_t() def PLUGIN_ENTRY(): return hello_plugin_t() ``` -------------------------------- ### Get Arguments Section Start Offset Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/ida_frame.md Retrieves the starting address of the arguments section within the function frame. ```APIDOC frame_off_args(pfn: 'func_t const *') -> ida_idaapi.ea_t pfn: pointer to function structure ``` -------------------------------- ### Get Start Address of Selected Range Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/idc.md Retrieves the starting linear address of the currently selected range in IDA. Returns BADADDR if no range is selected. ```Python def read_selection_start(): """ Get start address of the selected range returns BADADDR - the user has not selected an range """ selection, startaddr, endaddr = ida_kernwin.read_range_selection(None) if selection == 1: return startaddr else: return BADADDR ``` -------------------------------- ### Creating a Basic Hello World IDC Plugin Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/hello/idchello.md This IDC script defines a simple plugin for IDA Pro that prints 'Hello world!' to the console. It includes a `hello_plugmod_t` class for the plugin's core logic and a `hello_plugin_t` class for plugin metadata and initialization, registering it as a multi-instance plugin with a hotkey. ```IDC #include class hello_plugmod_t { run(arg) { msg("Hello world! (idc)\n"); return 0; } } class hello_plugin_t { hello_plugin_t() { this.flags = PLUGIN_MULTI; this.comment = "This is a comment"; this.help = "This is help"; this.wanted_name = "Hello IDC plugin"; this.wanted_hotkey = "Alt-F6"; } init() { return hello_plugmod_t(); } } static PLUGIN_ENTRY() { return hello_plugin_t(); } ``` -------------------------------- ### Defining an IDA Pro Plugin Entry Point and Metadata Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/cvt64_sample/cvt64_sample.md This C++ code defines the essential components for an IDA Pro plugin, including the `init` function which serves as the plugin's entry point by instantiating a new plugin context. It also illustrates the `plugin_t` structure, specifying crucial flags like `PLUGIN_MULTI` for multi-database compatibility and `PLUGIN_MOD` for database modification, along with descriptive metadata such as comments and names. ```C++ //------------------------------------------------------------------------- // Create a plugin context and return it to the kernel. static plugmod_t *idaapi init() { return new cvt64_ctx_t; } //------------------------------------------------------------------------- static const char comment[] = "An example how to implement CVT64 functionality"; static const char wanted_name[] = "CVT64 sample"; static const char wanted_hotkey[] = ""; //------------------------------------------------------------------------- plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_MULTI // Can work with multiple databases. A must for the plugins // that support IDA Teams. Such plugins must keep all // their data in the plugin context (global data variables // cannot be used because they are not database dependent). |PLUGIN_MOD, // Plugin may modify the database. init, // initialize nullptr, nullptr, comment, // long comment about the plugin nullptr, // multiline help about the plugin wanted_name, // the preferred short name of the plugin wanted_hotkey // the preferred hotkey to run the plugin }; ``` -------------------------------- ### Get Segment Start Address by Selector/Base Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/idc.md Retrieves the starting linear address of a segment given its base paragraph or selector. Returns BADADDR if no such segment exists. ```Python def get_segm_by_sel(base): """ Get segment by segment base @param base: segment base paragraph or selector @return: linear address of the start of the segment or BADADDR if no such segment """ sel = ida_segment.find_selector(base) seg = ida_segment.get_segm_by_sel(sel) if seg: return seg.start_ea else: return BADADDR ``` -------------------------------- ### Creating an IDA Pro Python Plugin Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/api-examples/inf/print_basic_info_plugin.md This snippet illustrates the complete structure required to implement an IDA Pro Python plugin. It defines `pbi_plugmod_t` for the plugin's runtime logic and `pbi_plugin_t` for its lifecycle management (initialization, hotkey, name). The `PLUGIN_ENTRY` function serves as the entry point for IDA Pro to load the plugin. ```Python """ summary: Python plugin that print basic IDB information. description: Demonstrates how to turn an IDA python script into an IDA Python plugin. """ import ida_idaapi import ida_kernwin import print_basic_info class pbi_plugmod_t(ida_idaapi.plugmod_t): def __del__(self): ida_kernwin.msg("PBI >> unloaded pbi_plugmod\n") def run(self, arg): ida_kernwin.msg("PBI >> run() called with %d!\n" % arg) print_basic_info.main() return True class pbi_plugin_t(ida_idaapi.plugin_t): flags = ida_idaapi.PLUGIN_UNL | ida_idaapi.PLUGIN_MULTI comment = "This is a simple plugin printing basic info" help = "" wanted_name = "Print Basic Info (PBI) plugin" wanted_hotkey = "Ctrl-Alt-F12" def init(self): ida_kernwin.msg("PBI >> init() called!\n") return pbi_plugmod_t() def term(self): ida_kernwin.msg("PBI >> ERROR: term() called (should never be called)\n") def PLUGIN_ENTRY(): return pbi_plugin_t() ``` -------------------------------- ### Get Local Variables Section Start Offset Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/ida_frame.md Retrieves the starting address of the local variables section within the function frame. ```APIDOC frame_off_lvars(pfn: 'func_t const *') -> ida_idaapi.ea_t pfn: pointer to function structure ``` -------------------------------- ### Get Saved Registers Section Start Offset Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/ida_frame.md Retrieves the starting address of the saved registers section within the function frame. ```APIDOC frame_off_savregs(pfn: 'func_t const *') -> ida_idaapi.ea_t pfn: pointer to function structure ``` -------------------------------- ### Main Application Entry Point and IDA Database Initialization Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/idalib/examples/idacli.md This `main` function serves as the application's entry point. It parses command-line arguments, initializes the IDA library, and opens the target database. It includes error handling for initialization and database opening. Optionally, it can execute a script or list binary segments based on command-line flags. ```C++ int main(int argc, char *argv[]) { command_line_arguments arguments; if ( !parse_arguments(argc, argv, arguments) ) { display_usage(argv[0]); return -1; } ////////////////////////////////////////// // Initialize library with the sample file, if verbose display to console library provided logs int res = init_library(); if ( res != 0 ) { std::cout << "Library initialization failed with result: " << res < 0); res = open_database(arguments.binary_file_name.c_str(), true); if ( res != 0 ) { std::cout << "Open file failed with result: " << res < ida_idaapi.ea_t pfn: pointer to function structure ``` -------------------------------- ### Define Command-Line Arguments with argparse Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/tools/gen_examples_index.md This snippet sets up command-line argument parsing using Python's `argparse` module. It defines a main parser with 'write' and 'show' subparsers, each having specific arguments like examples directory, template, output, keywords, and search. It also includes a verbose flag. ```Python from argparse import ArgumentParser parser = ArgumentParser() subparsers = parser.add_subparsers(dest="command") subparsers.required = True w_subparser = subparsers.add_parser("write") s_subparser = subparsers.add_parser("show") parser.add_argument("-v", "--verbose", default=False, action="store_true") w_subparser.add_argument("-e", "--examples-dir", required=True) w_subparser.add_argument("-t", "--template", required=True) w_subparser.add_argument("-o", "--output", required=True) s_subparser.add_argument("-k", "--keywords", default=False, action="store_true") s_subparser.add_argument("-s", "--search", type=str) s_subparser.add_argument("-e", "--examples-dir", required=True) args = parser.parse_args() ``` -------------------------------- ### Generating Build Configuration File for IDA SDK Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Commands to generate the build configuration file, essential for the SDK build process, executable from both Windows Command Prompt and Cygwin shell. ```Batch bin\m.bat env ``` ```Shell bin\m.bat env ``` -------------------------------- ### Get Arguments Section Start Address Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/frame.md Obtains the starting address of the arguments section within a function's stack frame by internally calling `get_frame_part` with `FPC_ARGS`. ```C++ inline ea_t frame_off_args(const func_t *pfn) { range_t range; get_frame_part(&range, pfn, FPC_ARGS); return range.start_ea; } ``` -------------------------------- ### Adding IDA SDK Bin Directory to System PATH Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Commands to add the IDA SDK's `bin` directory to the system PATH, enabling direct execution of SDK tools from the command line, applicable to both Windows Command Prompt and Cygwin shell. ```Batch set PATH=C:\idasdk\bin;%PATH% ``` ```Shell export PATH=/cygdrive/c/idasdk/bin:$PATH ``` -------------------------------- ### Get Segment Start Address (IDA Pro Python) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/idc.md Determines the start address of the segment that encompasses the specified linear address. If the provided address does not belong to any segment, `BADADDR` is returned. ```Python def get_segm_start(ea): """ Get start address of a segment @param ea: any address in the segment @return: start of segment BADADDR - the specified address doesn't belong to any segment """ seg = ida_segment.getseg(ea) if not seg: return BADADDR else: return seg.start_ea ``` -------------------------------- ### Navigating to IDA SDK Directory on Windows Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Changes the current directory to the IDA SDK root, a common first step before building. ```Batch cd C:\idasdk ``` -------------------------------- ### Get Local Variables Section Start Address Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/frame.md Obtains the starting address of the local variables section within a function's stack frame by internally calling `get_frame_part` with `FPC_LVARS`. ```C++ inline ea_t frame_off_lvars(const func_t *pfn) { range_t range; get_frame_part(&range, pfn, FPC_LVARS); return range.start_ea; } ``` -------------------------------- ### Get Saved Registers Section Start Address Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/frame.md Obtains the starting address of the saved registers section within a function's stack frame by internally calling `get_frame_part` with `FPC_SAVREGS`. ```C++ inline ea_t frame_off_savregs(const func_t *pfn) { range_t range; get_frame_part(&range, pfn, FPC_SAVREGS); return range.start_ea; } ``` -------------------------------- ### IDA Pro C++ Plugin Initialization and Metadata Definition Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/qwindow/qwindow.md This snippet illustrates the standard initialization function (`init`) for an IDA Pro plugin, which returns a new instance of the plugin context. It also defines the `plugin_t` structure, which provides essential metadata about the plugin, including its version, capabilities, comments, help text, preferred name, and hotkey, making it discoverable and runnable within IDA Pro. ```C++ //-------------------------------------------------------------------------- static plugmod_t *idaapi init() { if ( !is_idaq() ) return nullptr; return new plugin_ctx_t; } //-------------------------------------------------------------------------- static const char comment[] = "This is a sample Qt plugin."; static const char help[] = "A sample plugin module\n" "\n" "This module shows you how to create a Qt window."; //-------------------------------------------------------------------------- // This is the preferred name of the plugin module in the menu system // The preferred name may be overridden in plugins.cfg file static const char wanted_name[] = "Create Qt subwindow"; // This is the preferred hotkey for the plugin module // The preferred hotkey may be overridden in plugins.cfg file static const char wanted_hotkey[] = ""; //-------------------------------------------------------------------------- // // PLUGIN DESCRIPTION BLOCK // //-------------------------------------------------------------------------- plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_MULTI, // The plugin can work with multiple idbs in parallel init, // initialize nullptr, nullptr, comment, // long comment about the plugin help, // multiline help about the plugin wanted_name, wanted_hotkey }; ``` -------------------------------- ### IDA Pro Script Initial Setup and Execution Flow Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/examples/debugger/dbghooks/dbg_trace.md This snippet covers the initial setup of the IDA Pro tracing script, including necessary imports, a conditional block to determine if the script is running in a test environment, and the crucial logic for dynamically loading the correct debugger module based on the executable's file type (PE, ELF, MACHO). It also includes the main entry point call to do_trace() which initiates the debugging process. The script can be run from the command line like: ida.exe -B -Sdbg_trace.py -Ltrace.log file.exe ```Python import time import ida_dbg import ida_ida import ida_pro import ida_ua from ida_allins import NN_callni, NN_call, NN_callfi from ida_lines import generate_disasm_line, GENDSM_FORCE_CODE, GENDSM_REMOVE_TAGS # Note: this try/except block below is just there to # let us (at Hex-Rays) test this script in various # situations. try: import idc print(idc.ARGV[1]) under_test = bool(idc.ARGV[1]) except: under_test = False # load the debugger module depending on the file type if ida_ida.inf_get_filetype() == ida_ida.f_PE: ida_dbg.load_debugger("win32", 0) elif ida_ida.inf_get_filetype() == ida_ida.f_ELF: ida_dbg.load_debugger("linux", 0) elif ida_ida.inf_get_filetype() == ida_ida.f_MACHO: ida_dbg.load_debugger("mac", 0) if not under_test: do_trace() ``` -------------------------------- ### Get Return Address Section Start Address Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/frame.md Obtains the starting address of the return address section within a function's stack frame by internally calling `get_frame_part` with `FPC_RETADDR`. ```C++ inline ea_t frame_off_retaddr(const func_t *pfn) { range_t range; get_frame_part(&range, pfn, FPC_RETADDR); return range.start_ea; } ``` -------------------------------- ### Get Start Address of Item (IDA Pro C++) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/bytes.md Returns the starting address of the item located at the specified address `ea`. If there is no current item, the function returns `ea` itself. ```C++ inline ea_t idaapi get_item_head(ea_t ea); ``` -------------------------------- ### Initialize IDA Pro Plugin and Display Help Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/snapshots/snapshots.md The `init` function is called when the plugin is loaded. It displays a help message to the user, explaining how to use the snapshot manager and its hotkeys. It then instantiates and returns a new `plugin_ctx_t` object, indicating successful initialization and readiness for execution. ```C++ static plugmod_t *idaapi init() { // Display help msg( "Simple snapshot manager loaded!\n" "Press Shift+F8 to toggle the plugin\n" "Inside the snapshots window, press:\n" " - Insert: to take a snapshot\n" " - Delete: to delete\n" " - Edit: to edit the snapshot description\n" "\n" "Click on:\n" " - Ok: to restore the selected snapshot\n" " - Cancel: close without doing anything\n"); // The plugin flags must include PLUGIN_FIX as well return new plugin_ctx_t; } ``` -------------------------------- ### Get Processor Module Instruction Start Index (IDA) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/apidoc/ida_idp.md Retrieves the `ph.instruc_start` field, indicating the starting index of the instruction set, from the currently loaded processor module in IDA Pro. ```Python def ph_get_instruc_start(): """ Returns the 'ph.instruc_start' """ pass ``` -------------------------------- ### Example Python Application Entry Point Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/tools/gen_examples_index.md This block demonstrates a typical entry point for a Python application, including configuration reading, processing, and error handling. It catches `ProcessException` and exits gracefully, while allowing other exceptions to propagate. ```python try: read_config() e = Examples() e.process() except ProcessException as ex: print(ex) sys.exit(1) # other exceptions - let them fail ``` -------------------------------- ### API: Get Start of Next Defined Item Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/bytes.md Searches forward from `ea` up to `maxea` (exclusive) to find the start address of the next defined item. Returns `BADADDR` if no such item exists. ```APIDOC next_head(ea: ea_t, maxea: ea_t) Description: Get start of next defined item. Parameters: ea: begin search at this address maxea: not included in the search range Returns: BADADDR if none exists. ``` -------------------------------- ### IDA Pro C++ Plugin: Hello World Example Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/hello/hello.md This C++ code defines a minimal IDA Pro plugin. It inherits from `plugmod_t`, overrides the `run` method to print a message, and sets up the `PLUGIN` structure for initialization and behavior. The plugin is configured to unload immediately after execution (`PLUGIN_UNL`) and support multiple IDB instances (`PLUGIN_MULTI`). ```cpp #include #include #include #include //-------------------------------------------------------------------------- struct plugin_ctx_t : public plugmod_t { virtual bool idaapi run(size_t) override; }; //-------------------------------------------------------------------------- bool idaapi plugin_ctx_t::run(size_t) { msg("Hello, world! (cpp)\n"); return true; } //-------------------------------------------------------------------------- static plugmod_t *idaapi init() { return new plugin_ctx_t; } //-------------------------------------------------------------------------- plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_UNL // Unload the plugin immediately after calling 'run' | PLUGIN_MULTI, // The plugin can work with multiple idbs in parallel init, // initialize nullptr, nullptr, nullptr, // long comment about the plugin nullptr, // multiline help about the plugin "Hello, world", // the preferred short name of the plugin nullptr, // the preferred hotkey to run the plugin }; ``` -------------------------------- ### API: Get Start of Previous Defined Item Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/bytes.md Searches backward from `ea` to `minea` (inclusive) to find the start address of the previous defined item. Returns `BADADDR` if no such item exists. ```APIDOC prev_head(ea: ea_t, minea: ea_t) Description: Get start of previous defined item. Parameters: ea: begin search at this address minea: included in the search range Returns: BADADDR if none exists. ``` -------------------------------- ### Get Segment Start Address by Name (RPC_GET_SEGM_START) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/dbg/dbg_rpc_handler.md Processes the `RPC_GET_SEGM_START` request to find the starting address of a segment given a base address and segment name. It uses `dbg_get_segm_start` and packs the resulting `ea_t`. ```C++ case RPC_GET_SEGM_START: { ea_t base = mmdsr.unpack_ea64(); const char *segname = mmdsr.unpack_str(); ea_t result = dbg_mod->dbg_get_segm_start(base, segname); verb(("get_segm_start(base=%a, segname=%s) => %a\n", base, segname, result)); req.pack_ea64(result); } ``` -------------------------------- ### Building IDA SDK Components on Windows with Parallelization Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Uses specific batch files (`mo.bat`, `mso.bat`, `mso32.bat`) to build different IDA SDK components on Windows. The `-j` argument enables parallel builds. ```Batch mo.bat -j 12 ``` ```Shell mo.bat -j 12 ``` -------------------------------- ### Python Class for Generating Examples Index Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/tools/gen_examples_index.md The `ExamplesIndex` class in Python is responsible for orchestrating the generation of an examples index. It initializes a `TemplateReplacer` to process a template file and then uses it to expand and write the final output, incorporating provided examples and keywords. This class acts as the main entry point for the documentation generation process. ```python class ExamplesIndex(object): def __init__(self): self.replacer = TemplateReplacer() with open(args.template, "r", encoding="UTF-8", errors="surrogateescape") as f: self.replacer.template(f.read()) def produce(self, examples, all_keywords): with open(args.output, "w", encoding="UTF-8") as f: self.replacer.expand(examples, all_keywords, f) ``` -------------------------------- ### Determine Potential Function Start for HPPA Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/module/hppa/emu.md This function is intended to determine if a given instruction could be the start of a new function. In this specific implementation for HPPA, it always returns 0, indicating that it does not identify function starts based on instruction patterns. The commented-out ALPHA example shows how it might be used in other architectures. ```C++ int may_be_func(const insn_t &/*insn*/) // can a function start here? // returns: probability 0..100 { // ldah $gp, 0x2000($27) // if ( insn.itype == ALPHA_ldah && insn.Op1.reg == GP ) // return 100; return 0; } ``` -------------------------------- ### Get IDA Pro Installation Directory Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/idc.md Retrieves the directory path where the IDA.EXE executable resides. ```Python def idadir(): """ Get IDA directory This function returns the directory where IDA.EXE resides """ return ida_diskio.idadir("") ``` -------------------------------- ### Create Default IDA Pro Configuration File Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/idalib/python/py-activate-idalib.md This function generates a default `ida-config.json` file with an empty `ida-install-dir` path. It ensures the parent directory exists and writes the default JSON structure, providing a starting point for user configuration. ```python import json from pathlib import Path def create_default_config(user_config_path): """Create a default config file in JSON format.""" # Create a default JSON config structure default_config = { "Paths": { "ida-install-dir": "" } } # Create the directory if it doesn't exist user_config_path.parent.mkdir(parents=True, exist_ok=True) # Write the default config to the user-specific config file with user_config_path.open('w') as configfile: json.dump(default_config, configfile, indent=4) print(f"Default config file created at {user_config_path}") return default_config ``` -------------------------------- ### Define Example Categories and Levels Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/tools/gen_examples_index.md These Python lists define metadata for categorizing and leveling examples. `CATEGORY_INFO` includes a short name, display name, and a detailed description for each category (e.g., UI, Disassembler, Decompiler). `LEVEL_INFO` defines different difficulty levels (Beginner, Intermediate, Advanced). ```Python CATEGORY_INFO = [ ( "ui", "User interface", "Creating & manipulating user-interface widgets, prompting the " + "user with forms, enriching existing widgets, or creating your " + "own UI through Python Qt bindings." ), ( "disassembler", "Disassembly", "Various ways to query, or modify the disassembly listing, " + "alter the way analysis is performed, or be notified of changes " + "made to the IDB." ), ( "decompiler", "Decompilation", "Querying the decompiler, manipulating the decompilation trees " + "(either at the microcode level, or the C-tree), and examples " + "showing how to intervene in the decompilation output." ), ( "debugger", "Debuggers", "Driving debugging sessions, be notified of debugging events." ), ( "types", "Working with types", "These samples utilize our Type APIs, which allow you to manage " + "the types and perform various operations on them, like creating " + "the structures or enums and adding their members programmatically." ), ( "misc", "Miscellaneous", "Miscellaneous examples that don't quite fall into another category, " + "but don't really justify one of their own." ) ] LEVEL_INFO = [ ( "beginner", "Beginner" ), ( "intermediate", "Intermediate" ), ( "advanced", "Advanced" ) ] ``` -------------------------------- ### Get Segment Start Address in IDA Pro Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/python/idc.md Determines the starting linear address of the segment that contains the specified address `ea`. This function is crucial for understanding segment boundaries. If `ea` does not belong to any segment, `BADADDR` is returned. ```Python def get_segm_start(ea): """ Get start address of a segment @param ea: any address in the segment @return: start of segment BADADDR - the specified address doesn't belong to any segment """ seg = ida_segment.getseg(ea) if not seg: return BADADDR else: return seg.start_ea ``` -------------------------------- ### Python Function to Read Application Configuration Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/tools/gen_examples_index.md The `read_config` function reads the application's configuration from a `.cfg` file. It uses `ast.literal_eval` for safe parsing, converts the 'exclude' list to a set for efficient lookups, and compiles regular expressions for 'auto-keywords' to be used in matching. It handles file path construction and UTF-8 encoding with surrogate escape error handling. ```Python def read_config(): global config config_path = os.path.join(prog_dir, prog_name + ".cfg") with open(config_path, "r", encoding="UTF-8", errors="surrogateescape") as f: config = ast.literal_eval(f.read()) config["exclude"] = set(config["exclude"]) for _, key_res in config["auto-keywords"]: for i in range(len(key_res)): key_res[i] = re.compile(key_res[i] + "$") # anchored for match() ``` -------------------------------- ### Get Start of Next Contiguous Program Chunk (IDA Pro C++) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/bytes.md Finds the starting address of the next contiguous block of addresses (chunk) in the program. This is useful for navigating through allocated memory regions. ```APIDOC ea_t next_chunk(ea_t ea) ea: The current address. Returns: The first address of the next contiguous chunk, or BADADDR if no next chunk exists. ``` -------------------------------- ### Get IDA Pro Installation Directory Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/python/idc.md Retrieves the full path to the directory where IDA.EXE is located. ```Python def idadir(): """ Get IDA directory This function returns the directory where IDA.EXE resides """ return ida_diskio.idadir("") ``` -------------------------------- ### Building IDA SDK with Explicit Target Platform on Linux/macOS Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/install_make.md Uses `make` to build the SDK, explicitly specifying the target platform and architecture as command-line arguments, overriding environment variables. ```Shell make __LINUX__=1 make __MAC__=1 __ARM__=1 ``` -------------------------------- ### Initialize IDA Pro Highlighter Plugin Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/highlighter/highlighter.md This simple function serves as the entry point for the IDA Pro plugin. It creates and returns a new instance of `plugin_ctx_t`, which encapsulates the entire plugin's logic and state. IDA Pro calls this `init` function to load the plugin. ```C++ static plugmod_t *idaapi init() { return new plugin_ctx_t; } ``` -------------------------------- ### Validate IDA Pro Installation Directory Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/idalib/python/py-activate-idalib.md This function checks if a given directory is a valid IDA Pro installation by verifying the presence of `ida.hlp` and the platform-specific `idalib` file. It ensures the specified path contains essential IDA components. ```python from pathlib import Path def is_valid_ida_dir(dir: str) -> bool: """Check if a directory looks like a valid IDA installation directory.""" ida_install_dir = Path(dir) return (ida_install_dir / "ida.hlp").is_file() and (ida_install_dir / libname).is_file() ``` -------------------------------- ### IDA Pro Debugger Initialization and Script Execution Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/examples/debugger/dbghooks/dbg_trace.md This section handles the initial setup and execution flow of the tracing script. It includes importing necessary IDA Pro modules, a conditional check for testing environments, and dynamic loading of the correct debugger module (win32, linux, or mac) based on the loaded file's format (PE, ELF, or MACHO). Finally, it calls the `do_trace` function to begin the tracing process if not in a test environment. ```Python import time import ida_dbg import ida_ida import ida_pro import ida_ua from ida_allins import NN_callni, NN_call, NN_callfi from ida_lines import generate_disasm_line, GENDSM_FORCE_CODE, GENDSM_REMOVE_TAGS # Note: this try/except block below is just there to # let us (at Hex-Rays) test this script in various # situations. try: import idc print(idc.ARGV[1]) under_test = bool(idc.ARGV[1]) except: under_test = False # load the debugger module depending on the file type if ida_ida.inf_get_filetype() == ida_ida.f_PE: ida_dbg.load_debugger("win32", 0) elif ida_ida.inf_get_filetype() == ida_ida.f_ELF: ida_dbg.load_debugger("linux", 0) elif ida_ida.inf_get_filetype() == ida_ida.f_MACHO: ida_dbg.load_debugger("mac", 0) if not under_test: do_trace() ``` -------------------------------- ### Get Start Address of Containing Program Chunk (IDA Pro C++) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/include/bytes.md Retrieves the starting address of the contiguous block of program addresses that contains the given address. This helps identify the boundaries of allocated regions. ```APIDOC ea_t chunk_start(ea_t ea) ea: An address within a program chunk. Returns: The starting address of the chunk containing 'ea', or BADADDR if 'ea' is not part of the program. ``` -------------------------------- ### Get Previous Function Chunk (IDA Pro Python) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/python/idc.md Retrieves the starting address of the previous function chunk in the database. This function enumerates all chunks of all functions. It returns the starting address of the previous chunk or BADADDR if no previous chunk is found. ```Python func = ida_funcs.get_prev_fchunk(ea) if func: return func.start_ea else: return BADADDR ``` -------------------------------- ### Python: Tags Class for Example Metadata Management Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/tools/gen_examples_index.md The `Tags` class defines a comprehensive set of metadata tags (e.g., NAME, PATH, SUMMARY, KEYWORDS) used to describe and categorize code examples. It distinguishes between tags usable in templates (`ALL_TAGS`) and those allowed within example docstrings (`IN_DOCSTRING`). The constructor initializes tag items with appropriate default types (lists, sets, or strings). ```Python class Tags(object): NAME = "name" PATH = "path" SUMMARY = "summary" DESCRIPTION = "description" CATEGORY = "category" KEYWORDS = "keywords" SHORTCUTS = "shortcuts" USES = "uses" IMPORTS = "imports" SEE_ALSO = "see_also" AUTHOR = "author" LEVEL = "level" ALL_TAGS = set([NAME, PATH, SUMMARY, DESCRIPTION, CATEGORY, \ KEYWORDS, USES, IMPORTS, SEE_ALSO, AUTHOR, \ LEVEL]) IN_DOCSTRING = set([SUMMARY, DESCRIPTION, CATEGORY, \ KEYWORDS, USES, SEE_ALSO, AUTHOR, \ LEVEL]) def __init__(self): self.items = {} for tag in self.ALL_TAGS: if tag in (self.KEYWORDS, self.SEE_ALSO): self.items[tag] = [] elif tag in (self.USES, self.IMPORTS): self.items[tag] = set() else: self.items[tag] = "" ``` -------------------------------- ### Initialize IDA Pro Plugin and Define Plugin Metadata Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/ex_merge_ldrdata/ldrdata.md This snippet contains the `init` function, which serves as the entry point for the IDA Pro plugin, responsible for creating and returning an instance of `plugin_ctx_t`. It also defines the global `PLUGIN` structure, providing essential metadata such as the plugin's version, flags (e.g., `PLUGIN_MOD`, `PLUGIN_HIDE`, `PLUGIN_MULTI`), initialization and termination routines, and descriptive names. ```C++ static plugmod_t *idaapi init() { auto plugmod = new plugin_ctx_t; set_module_data(&data_id, plugmod); return plugmod; } //-------------------------------------------------------------------------- static const char wanted_name[] = "Example: Merge data created by loaders"; plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_MOD | PLUGIN_HIDE | PLUGIN_MULTI, // plugin flags init, // initialize nullptr, // terminate. this pointer may be nullptr. nullptr, // invoke plugin wanted_name, // long comment about the plugin wanted_name, // multiline help about the plugin wanted_name, // the preferred short name of the plugin "" // the preferred hotkey to run the plugin }; ``` -------------------------------- ### Get Next Function Chunk (IDA Pro Python) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/idapython/python/idc.md Retrieves the starting address of the next function chunk in the database. This function enumerates all chunks of all functions. It returns the starting address of the next chunk or BADADDR if no next chunk is found. ```Python func = ida_funcs.get_next_fchunk(ea) if func: return func.start_ea else: return BADADDR ``` -------------------------------- ### IDA Plugin Entry Point and Metadata Definition Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida_sdk_91/plugins/mex1/mex_impl.md This structure defines the entry point and metadata for the IDA plugin. It specifies the plugin's version, capabilities (e.g., `PLUGIN_MULTI` for multi-database support, `PLUGIN_MOD` for database modification), initialization function (`init`), and descriptive strings. `PLUGIN_MULTI` is crucial for plugins supporting IDA Teams, as it mandates keeping all data within the plugin context rather than global variables. ```cpp static plugmod_t *idaapi init() { return new mex_ctx_t; } static const char comment[] = "An example " MEX_NUMBER " how to implement IDA merge functionality"; static const char wanted_name[] = "Merge example " MEX_NUMBER; static const char wanted_hotkey[] = ""; plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_MULTI, // Can work with multiple databases. A must for the plugins // that support IDA Teams. Such plugins must keep all // their data in the plugin context (global data variables // cannot be used because they are not database dependent). |PLUGIN_MOD, // Plugin may modify the database. init, // initialize nullptr, nullptr, comment, // long comment about the plugin nullptr, // multiline help about the plugin wanted_name // the preferred short name of the plugin }; ``` -------------------------------- ### Get Previous Function Chunk (IDA Pro) Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/idc.md Retrieves the starting address of the previous function chunk in the database, relative to a given address. This function enumerates all chunks of all functions. Returns the starting address of the previous chunk or BADADDR if none is found. ```Python def get_prev_fchunk(ea): """ Get previous function chunk @param ea: any address @return: the starting address of the function chunk or BADADDR @note: This function enumerates all chunks of all functions in the database """ func = ida_funcs.get_prev_fchunk(ea) if func: return func.start_ea else: return BADADDR ``` -------------------------------- ### Initialize PyQt5 Package Path and Validate Python Version Source: https://github.com/w00tzenheimer/ida9ctx/blob/main/ida91/python/PyQt5/__init__.md This snippet demonstrates how a Python `__init__.py` file can extend its package's `__path__` to include sub-packages created by setuptools and dynamically add a version-specific directory for `sip` modules. It also includes a crucial check to enforce a minimum Python version (3.8) before allowing the package to load, raising an `ImportError` if the requirement is not met. ```Python # Copyright (c) 2021 Riverbank Computing Limited # # This file is part of PyQt5. # # This software is licensed for use under the terms of the Riverbank Commercial # License. See the file LICENSE for more details. It is supplied WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # Support PyQt5 sub-packages that have been created by setuptools. __path__ = __import__('pkgutil').extend_path(__path__, __name__) # Hex-Rays addition: append version-specific subdir for sip import os, sys REQ = (3, 8) v = sys.version_info[:2] if v < REQ: raise ImportError("Unsupported Python version %d.%d (required >= %d.%d)" % (v, REQ) ) subdir = "python_%d.%d" % v __path__.append(os.path.join(os.path.dirname(__file__), subdir)) ```