Overview
TheGhidraScript class is the foundation for writing custom scripts in Ghidra. It extends FlatProgramAPI and provides access to program analysis, manipulation, and user interaction capabilities.
Creating a Script
All Ghidra scripts must:- Be written in Java
- Extend
ghidra.app.script.GhidraScript - Implement the
run()method - Include a description comment at the top (lines starting with
//)
Basic Template
Script State Variables
Ghidra automatically provides these instance variables when a script runs:| Variable | Type | Description |
|---|---|---|
currentProgram | Program | The active program being analyzed |
currentAddress | Address | The current cursor location in the tool |
currentLocation | ProgramLocation | The current program location (may be null) |
currentSelection | ProgramSelection | The current selection (may be null) |
currentHighlight | ProgramSelection | The current highlight (may be null) |
monitor | TaskMonitor | Task monitor for tracking progress |
Core Methods
Abstract Methods
Output Methods
User Input Methods
GhidraScript provides numerousask* methods for user input:
Running Other Scripts
Analysis Control
AnalysisMode.ENABLED- Script runs normally with auto-analysis responding to changesAnalysisMode.DISABLED- Auto-analysis is disabled during script executionAnalysisMode.SUSPENDED- Analysis is suspended and will run after script completes
Utility Methods
Complete Example
Properties Files
Scripts can use.properties files to pre-populate values for ask* methods:
- Create a file named
MyScript.propertiesin the same directory asMyScript.java - Add key-value pairs for default values
- In GUI mode, these values pre-populate input fields
- In headless mode, these values are used automatically
Script Arguments
Scripts can accept command-line arguments when run in headless mode:Best Practices
- Always check for null - State variables like
currentProgrammay be null - Use monitor.checkCancelled() - Allow users to cancel long-running operations
- Handle exceptions - Wrap risky operations in try-catch blocks
- Clean up resources - Override
cleanup(boolean success)to release resources - Provide meaningful output - Use
println()to keep users informed of progress - Use transactions - When modifying the program, changes are automatically wrapped in transactions
See Also
- FlatProgramAPI - Inherited methods for program manipulation
- PyGhidra - Python scripting with PyGhidra
