Kotlin Interpreter

Ruby Dragon adds interactive Kotlin shells to Ghidra, and also allows scripts to be written in Kotlin with full access to all of Ghidra's functionality.

Environment

The Kotlin interactive interpreter runs as a simple REPL. The same variables that are available in Ghidra's native Java and Python environments are also available in the Kotlin interpreter as global variables, both for interactive sessions and scripts. There are also some extra variables for commonly needed values such as the current function.

    currentAddress
    currentData
    currentFunction
    currentHighlight
    currentInstruction
    currentLocation
    currentProgram
    currentSelection
    

In the interactive interpreter, there is also another variable named currentAPI, which has an instance of FlatProgramAPI for the current program. This can be used to access the convenience functions provided by the flat API.

If you're writing a script, you'll also be able to access the KotlinScript instance (a subclass of GhidraScript) using the script variable binding. This will provide access to all public fields and methods for the instance. There are examples of this in the GhidraBasicsScriptKts script included in the Examples category with this plugin.

An unfortunate pitfall to be aware of is the println method, which exists in Kotlin as a shortend version of System.out.println. If you call this function in the interpreter window or one of your scripts, it will be the same as a call to the System function, which is unlikely to be what you intended. In scripts, you'll need to use script.println explicitly to print output. In the interpreter, make sure that the expression evaluates to a string, and it will be printed automatically.

Headless Analysis

Kotlin scripts may also be run during headless analysis. The following invocation uses one of the Kotlin example scripts to save all strings found in a demo executable to a file named example_file_strings.txt.

    support\analyzeHeadless ^
        my\ghidra\projects DummyProject ^
        -import demo_binary.exe ^
        -postScript SaveStringsScriptKts.kts example_file_strings.txt ^
        -deleteProject
    

Copy/Paste

Copy and paste from within the Kotlin interpreter should work as expected for your given environment:

Import Classes Option

When this option is set to true, a number of Ghidra classes are imported in the Kotlin interactive interpreter automatically. This is particularly useful when using snippets copied from other sources or scripts, so that import statements are not needed to have access to Ghidra classes.

The list of classes (and their containing packages) is in a data file included in this extension's data folder named auto-import.xml. If you wish to add or remove classes from this list, edit this file and reset the interpeter. Note that changes to this file will affect the classes imported by all Ruby Dragon interpreters, not just Kotlin.

Provided by: KotlinDragon