Dump some of the most interesting bits of information about the function we are currently looking at.
How to create user actions, that once created can be inserted in menus, toolbars, context menus, ... Those actions, when triggered, will be passed a 'context' that contains some of the most frequently needed bits of information. In addition, custom actions can determine when they want to be available (through their `ida_kernwin.action_handler_t.update` callback)
`ida_kernwin.add_hotkey` is a simpler, but much less flexible alternative to `ida_kernwin.register_action` (though it does use the same mechanism under the hood.) It's particularly useful during prototyping, but note that the actions that are created cannot be inserted in menus, toolbars or cannot provide a custom `ida_kernwin.action_handler_t.update` callback.
This is a somewhat ancient way of registering actions & binding shortcuts. It's still here for reference, but "fresher" alternatives should be preferred.
This is an example demonstrating how one can create widgets from a plugin,
and have them re-created automatically at IDA startup-time or at desktop load-time.
This example should be placed in the 'plugins' directory of the
IDA installation, for it to work.
There are 2 ways to use this example:
1) reloading an IDB, where the widget was opened
- open the widget ('View > Open subview > ...')
- save this IDB, and close IDA
- restart IDA with this IDB
=> the widget will be visible
2) reloading a desktop, where the widget was opened
- open the widget ('View > Open subview > ...')
- save the desktop ('Windows > Save desktop...') under, say, the name 'with_auto'
- start another IDA instance with some IDB, and load that desktop
=> the widget will be visible
This builds upon the `ida_kernwin.UI_Hooks.get_lines_rendering_info` feature, to provide a quick & easy way to colorize disassembly lines. Contrary to @colorize_disassembly, the coloring is not persisted in the database, and will therefore be lost after the session. By triggering the action multiple times, the user can "carousel" across 4 predefined colors (and return to the "no color" state.)
Usage of the API to create & populate a structure with members of different types.
Illustrates how one can add command-line interpreters to IDA This custom interpreter doesn't actually run any code; it's there as a 'getting started'. It provides an example tab completion support.
IDA can be extended to support certain data types that it does not know about out-of-the-box. A 'custom data type' provide information about the type & size of a piece of data, while a 'custom data format' is in charge of formatting that data (there can be more than one format for a specific 'custom data type'.)
Use the `ida_lines.get_extra_cmt` API to retrieve anterior and posterior extra comments. This script registers two actions, that can be used to dump the previous and next extra comments.
Dumps the current function's flowchart, using 2 methods:
* the low-level `ida_gdl.qflow_chart_t` type
* the somewhat higher-level, and slightly more pythonic
`ida_gdl.FlowChart` type.
Shows how to retrieve the selection from a listing
widget ("IDA View-A", "Hex View-1", "Pseudocode-A", ...) as
two "cursors", and from there retrieve (in fact, generate)
the corresponding text.
After running this script:
* select some text in one of the listing widgets (i.e.,
"IDA View-*", "Local Types", "Pseudocode-*")
* press Ctrl+Shift+S to dump the selection
You can add IDC functions to IDA, whose "body" consists of IDAPython statements! We'll register a 'pow' function, available to all IDC code, that when invoked will call back into IDAPython, and execute the provided function body. After running this script, try switching to the IDC interpreter (using the button on the lower-left corner of IDA) and executing `pow(3, 7)`
IDAPython's ida_bytes.find_string can be used to implement a simple replacement for the 'Search > Sequence of bytes...' dialog, that lets users search for sequences of bytes that compose string literals in the binary file (either in the default 1-byte-per-char encoding, or as UTF-16.)
The `idapythonrc.py` file: * %APPDATA%\Hex-Rays\IDA Pro\idapythonrc.py (on Windows) * ~/.idapro/idapythonrc.py (on Linux & Mac) can contain any IDAPython code that will be run as soon as IDAPython is done successfully initializing.
By default, disassembly line prefixes contain segment + address information (e.g., '.text:08047718'), but it is possible to "inject" other bits of information in there, thanks to the `ida_lines.user_defined_prefix_t` helper type.
This sample shows how to programmatically access the list of bookmarks placed in a listing widget (e.g., "IDA View-A", "Pseudocode-", …) using the low-level `ida_moves.bookmarks_t` type.
This demonstrates how to use some of the iterators available on the func_t type.
This example will focus on:
* `func_t[.__iter__]`: the default iterator; iterates on instructions
* `func_t.data_items`: iterate on data items contained within a function
* `func_t.head_items`: iterate on 'heads' (i.e., addresses containing
the start of an instruction, or a data item.
* `func_t.addresses`: iterate on all addresses within function (code
and data, beginning of an item or not)
Type `help(ida_funcs.func_t)` for a full list of iterators.
In addition, one can use:
* `func_tail_iterator_t`: iterate on all the chunks (including
the main one) of the function
* `func_parent_iterator_t`: iterate on all the parent functions,
that include this chunk
Using the API to enumerate file imports.
Using the API to iterate over all the places in the file, that were patched using IDA.
Using the API to list all problem[atic situation]s that IDA encountered during analysis.
List all the functions in the current segment, as well as all the cross-references to them.
List all the functions in the current segment, as well as all the cross-references to them. Contrary to @list_segment_functions, this uses the somewhat higher-level `idautils` module.
Contrary to (in-memory) data & code xrefs, retrieving stack variables xrefs requires a bit more work than just using ida_xref's first_to(), next_to() (or higher level utilities such as idautils.XrefsTo)
This uses `idautils.Strings` to iterate over the string literals that are present in the IDB. Contrary to @show_selected_strings, this will not require that the "Strings" window is opened & available.
Automate IDA to perform auto-analysis on a file and,
once that is done, produce a .c file containing the
decompilation of all the functions in that file.
Run like so:
ida -A "-S...path/to/produce_c_file.py"
where:
* -A instructs IDA to run in non-interactive mode
* -S holds a path to the script to run (note this is a single token;
there is no space between '-S' and its path.)
Automate IDA to perform auto-analysis on a file and,
once that is done, produce a .lst file with the disassembly.
Run like so:
ida -A "-S...path/to/produce_lst_file.py"
where:
* -A instructs IDA to run in non-interactive mode
* -S holds a path to the script to run (note this is a single token;
there is no space between '-S' and its path.)
Register (possibly repeating) timers.
It's possible to invoke any action programmatically, by using either of those two: * ida_kernwin.execute_ui_requests() * ida_kernwin.process_ui_action() Ideally, this script should be run through the "File > Script file..." menu, so as to keep focus on "IDA View-A" and have the 'ProcessUiActions' part work as intended.
For more infortmation see SDK/plugins/cvt64_sample example
Start a debugging session, step through the first five instructions. Each instruction is disassembled after execution.
This script demonstrates using the low-level tracing hook
(ida_dbg.DBG_Hooks.dbg_trace). It can be run like so:
ida[t].exe -B -Sdbg_trace.py -Ltrace.log file.exe
Print the return addresses from the call stack at a breakpoint.
(and print also the module and the debug name from debugger)
To use this example:
* run `ida64` on test program `simple_appcall_linux64`, or
`ida` on test program `simple_appcall_linux32`, and wait for
auto-analysis to finish
* put a breakpoint where you want to see the call stack
* select the 'linux debugger' (either local, or remote)
* start debugging
* Press Shift+C at the breakpoint
Iterate over the list of threads in the program being
debugged, and dump all registers contents
To use this example:
* run `ida64` on test program `simple_appcall_linux64`, or
`ida` on test program `simple_appcall_linux32`, and wait for
auto-analysis to finish
* put a breakpoint somewhere in the code
* select the 'linux debugger' (either local, or remote)
* start debugging
* Press Alt+Shift+C at the breakpoint
Queries the debugger (possibly remotely) for the list of symbols that the process being debugged, provides.
Using the `ida_idd.Appcall` utility to execute code in
the process being debugged.
This example will run the test program and stop wherever
the cursor currently is, and then perform an appcall to
execute the `ref4` and `ref8` functions.
To use this example:
* run `ida64` on test program `simple_appcall_linux64`, or
`ida` on test program `simple_appcall_linux32`, and wait for
auto-analysis to finish
* select the 'linux debugger' (either local, or remote)
* run this script
Note: the real body of code is in `simple_appcall_common.py`.
Using the `ida_idd.Appcall` utility to execute code in
the process being debugged.
This example will run the test program and stop wherever
the cursor currently is, and then perform an appcall to
execute the `ref4` and `ref8` functions.
To use this example:
* run `ida64` on test program `simple_appcall_win64.exe`, or
`ida` on test program `simple_appcall_win32.exe`, and wait for
auto-analysis to finish
* select the 'windows debugger' (either local, or remote)
* run this script
Note: the real body of code is in `simple_appcall_common.py`.
This illustrates the setting/retrieval of background colours using the IDC wrappers In order to do so, we'll be assigning colors to specific ranges (item, function, or segment). Those will be persisted in the database.
Provides an action that can be used to dynamically alter the lines background rendering for pseudocode listings (as opposed to using `ida_hexrays.cfunc_t.pseudocode[N].bgcolor`) After running this script, pressing 'M' on a line in a "Pseudocode-?" widget, will cause that line to be rendered with a special background color.
Shows how user input information can be retrieved during processing of a notification triggered by that input
Attempts to load a decompiler plugin corresponding to the current architecture (and address size) right after auto-analysis is performed, and then tries to decompile the function at the first entrypoint. It is particularly suited for use with the '-S' flag, for example: idat -Ldecompile.log -Sdecompile_entry_points.py -c file
Decompile & print current function.
Installs a custom microcode instruction optimization rule,
to transform:
call !DbgRaiseAssertionFailure .0
into
call !DbgRaiseAssertionFailure .0
To see this plugin in action please use arm64_brk.i64
Installs a custom microcode block optimization rule,
to transform:
goto L1
...
L1:
goto L2
into
goto L2
In other words we fix a goto target if it points to a chain of gotos.
This improves the decompiler output in some cases.
Shows a list of direct references to a register from the current instruction.
Generates microcode for selection and dumps it to the output window.
Registers an action opens the "Select offsets" widget (select_udt_by_offset() call). This effectively repeats the functionality already available through Alt+Y. Place cursor on the union field and press Shift+T
Installs a custom microcode instruction optimization rule,
to transform:
x | ~x
into
-1
To see this plugin in action please use be_ornot_be.idb
This plugin can greatly improve decompilation of indirect calls:
call [eax+4]
For them, the decompiler has to guess the prototype of the called function.
This has to be done at a very early phase of decompilation because
the function prototype influences the data flow analysis. On the other
hand, we do not have global data flow analysis results yet because
we haven't analyzed all calls in the function. It is a chicked-and-egg
problem.
The decompiler uses various techniques to guess the called function
prototype. While it works very well, it may fail in some cases.
To fix, the user can specify the call prototype manually, using
"Edit, Operand types, Set operand type" at the call instruction.
This plugin illustrates another approach to the problem:
if you happen to be able to calculate the call prototypes dynamically,
this is how to inform the decompiler about them.
Registers an action that can be used to invert the `if`
and `else` blocks of a `ida_hexrays.cif_t`.
For example, a statement like
if ( cond )
{
statements1;
}
else
{
statements2;
}
will be displayed as
if ( !cond )
{
statements2;
}
else
{
statements1;
}
The modifications are persistent: the user can quit & restart
IDA, and the changes will be present.
Prints user-defined information to the "Output" window. Namely: * user defined label names * user defined indented comments * user defined number formats * user defined local variable names, types, comments This script loads information from the database without decompiling anything.
Registers an action that can be used to show the graph of the ctree. The current item will be highlighted in the graph. The command shortcut is `Ctrl+Shift+G`, and is also added to the context menu. To display the graph, we produce a .gdl file, and request that ida displays that using `ida_gdl.display_gdl`.
Modifies the decompilation output in a superficial manner, by removing some white spaces Note: this is rather crude, not quite "pythonic" code.
Using a `ida_hexrays.ctree_visitor_t`, search for `ida_hexrays.cit_block` instances and dump them.
Registers an action that uses a `ida_hexrays.udc_filter_t` to decompile `svc 0x900001` and `svc 0x9000F8` as function calls to `svc_exit()` and `svc_exit_group()` respectively. You will need to have an ARM + Linux IDB for this script to be usable In addition to having a shortcut, the action will be present in the context menu.
Handle `ida_hexrays.hxe_create_hint` notification using hooks,
to return our own.
If the object under the cursor is:
* a function call, prefix the original decompiler hint with `==> `
* a local variable declaration, replace the hint with our own in
the form of `!{varname}` (where `{varname}` is replaced with the
variable name)
* an `if` statement, replace the hint with our own, saying "condition"
Shows how to hook to many notifications sent by the decompiler. This plugin doesn't really accomplish anything: it just prints the parameters. The list of notifications handled below should be exhaustive, and is there to hint at what is possible to accomplish by subclassing `ida_hexrays.Hexrays_Hooks`
Use a `ida_hexrays.user_lvar_modifier_t` to modify names, comments and/or types of local variables.
Show decompiler-style Xref when the `Ctrl+X` key is pressed in the Decompiler window. * supports any global name: functions, strings, integers, ... * supports structure member.
These hooks will be notified about IDB events, and dump their information to the "Output" window
Show notifications whenever the user changes an instruction's operand, or a data item.
This is a sample script, that will record (in memory) all changes in functions prototypes, in order to re-apply them later. To use this script: - open an IDB (say, "test.idb") - modify some functions prototypes (e.g., by triggering the 'Y' shortcut when the cursor is placed on the first address of a function) - reload that IDB, *without saving it first* - call rpc.replay(), to re-apply the modifications. Note: 'ti_changed' is also called for changes to the function frames, but we'll only record function prototypes changes.
Implements disassembly of BUG_INSTR used in Linux kernel BUG() macro, which is architecturally undefined and is not disassembled by IDA's ARM module See Linux/arch/arm/include/asm/bug.h for more info
We add support for assembling the following pseudo instructions: * "zero eax" -> xor eax, eax * "nothing" -> nop
This is a primitive plugin which asks user for some info and saves it for
some addresses.
We will add a merge functionality to plugin.
An IDA plugin may have two kinds of data with permanent storage:
1. Data common for entire database (e.g. the options).
To describe them we will use the idbattr_info_t type.
2. Data specific to a particular address.
To describe them we will use the merge_node_info_t type.
Also, see SDK/plugins/mex1 example
IDA Teams uses a chooser to display the merge conflicts.
To fill the chooser columns IDA Teams uses the following methods from diff_source_t type:
* print_diffpos_name()
* print_diffpos_details()
and UI hints from merge_handler_params_t type:
* ui_has_details()
* ui_complex_details()
* ui_complex_name()
In general, chooser columns are filled as following:
columns.clear()
NAME = print_diffpos_name()
if ui_complex_name()
then
columns.add(split NAME by ui_split_char())
else
columns[0] = NAME
if not ui_complex_details()
then
columns.add(print_diffpos_details())
Also, see SDK/plugins/mex3 example
This example illustrates how one can execute commands in the "Output" window, from their own widgets. A few notes: * the original, underlying `cli:Execute` action, that has to be triggered for the code present in the input field to execute and be placed in the history, requires that the input field has focus (otherwise it simply won't do anything.) * this, in turn, forces us to do "delayed" execution of that action, hence the need for a `QTimer` * the IDA/SWiG 'TWidget' type that we retrieve through `ida_kernwin.find_widget`, is not the same type as a `QtWidgets.QWidget`. We therefore need to convert it using `ida_kernwin.PluginForm.TWidgetToPyQtWidget`
This sample registers an action enabling painting of a recognizable string of text over horizontal nodes edge sections beyond a satisfying size threshold. In a disassembly view, open the context menu and select "Paint on edges". This should work for both graph disassembly, and proximity browser. Using an "event filter", we will intercept paint events targeted at the disassembly view, let it paint itself, and then add our own markers along.
Using `ida_kernwin.PluginForm.FormToPyQtWidget`, this script converts IDA's own dockable widget into a type that is recognized by PyQt5, which then enables populating it with regular Qt widgets.
Color the function in the Function window according to its size. The larger the function, the darker the color.
Shows how one can dynamically alter the lines background rendering (as opposed to, say, using ida_nalt.set_item_color()), and also shows how that rendering can be limited to just a few glyphs, not the whole line.
Hooks to be notified about certain UI events, and dump their information to the "Output" window
Using `ida_kernwin.UI_Hooks.preprocess_action`, it is possible to respond to a command instead of the action that would otherwise do it.
How to query for complex user input, using IDA's built-in forms. Note: while this example produces full-fledged forms for complex input, simpler types of inputs might can be retrieved by using `ida_kernwin.ask_str` and similar functions.
Shows how to subclass the ida_kernwin.Choose class to show data organized in a simple table. In addition, registers a couple actions that can be applied to it.
By adding the necessary bits to a ida_kernwin.Choose subclass, IDA can show the otherwise tabular data, in a tree-like fashion. The important bits to enable this are: * ida_dirtree.dirspec_t (and my_dirspec_t) * ida_kernwin.CH_HAS_DIRTREE * ida_kernwin.Choose.OnGetDirTree * ida_kernwin.Choose.OnIndexToInode
Showing custom graphs, using `ida_graph.GraphViewer`. In addition, show how to write actions that can be performed on those.
How to create simple listings, that will share many of the features as the built-in IDA widgets (highlighting, copy & paste, notifications, ...) In addition, creates actions that will be bound to the freshly-created widget (using `ida_kernwin.attach_action_to_popup`.)
Partially re-implements the "Functions" widget present in IDA, with a custom widget.
We want our action not only to find the next line containing a comment, but to also place the cursor at the right horizontal position. To find that position, we will have to inspect the text that IDA generates, looking for the start of a comment. However, we won't be looking for a comment "prefix" (e.g., "; "), as that would be too fragile. Instead, we will look for special "tags" that IDA injects into textual lines, and that bear semantic information. Those tags are primarily used for rendering (i.e., switching colors), but can also be very handy for spotting tokens of interest (registers, addresses, comments, prefixes, instruction mnemonics, ...)
Shows how it is possible re-implement IDA's bookmark capability,
using 2 custom actions: one action saves the current location,
and the other restores it.
Note that, contrary to actual bookmarks, this example:
* remembers only 1 saved position
* doesn't save that position in the IDB (and therefore cannot
be restored if IDA is closed & reopened.)
Using the progress dialog (aka 'wait box') primitives.
In IDA it's possible to write actions that can be applied even to core (i.e., "standard") widgets. The actions in this example use the action "context" to know what the current selection is. This example shows how you can either retrieve string literals data directly from the chooser (`ida_kernwin.get_chooser_data`), or by querying the IDB (`ida_bytes.get_strlit_contents`)
Since it is possible to be notified of movements that happen take place in a widget, it's possible to "replay" those movements in another. In this case, "IDA View-B" (will be opened if necessary) will show the same contents as "IDA View-A", slightly zoomed out.
This is an example illustrating how to manipulate an existing IDA-provided view (and thus possibly its graph), in Python.