<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
# Ghidra Reverse Engineering — API Reference

## Headless Analyzer

### Basic Usage

```bash
analyzeHeadless <project_dir> <project_name> \
  -import <binary> \
  -postScript <script.py> [script_args...] \
  -scriptPath <additional_script_dirs>
```

### Key Flags

| Flag | Description |
|------|-------------|
| `-import <file>` | Import binary into project |
| `-process <file>` | Process already-imported binary |
| `-postScript <script>` | Run script after analysis |
| `-preScript <script>` | Run script before analysis |
| `-scriptPath <dir>` | Additional script search paths |
| `-deleteProject` | Delete project after completion |
| `-noanalysis` | Skip auto-analysis |
| `-recursive` | Analyze directory recursively |
| `-overwrite` | Overwrite existing program |

## Ghidra Python Scripting API

### Program Access

```python
currentProgram                    # Active program
currentProgram.getImageBase()     # Base address
currentProgram.getMemory()        # Memory manager
currentProgram.getListing()       # Code listing
currentProgram.getFunctionManager()  # Function manager
currentProgram.getSymbolTable()   # Symbol table
```

### Function Manager

```python
fm = currentProgram.getFunctionManager()
fm.getFunctions(True)             # Iterator: all functions (forward)
fm.getFunctionAt(addr)            # Function at exact address
fm.getFunctionContaining(addr)    # Function containing address
func.getName()                    # Function name
func.getEntryPoint()              # Entry point address
func.getBody()                    # AddressSetView of function body
func.isExternal()                 # Is imported/external
func.getCalledFunctions(monitor)  # Functions called by this function
func.getCallingFunctions(monitor) # Functions that call this function
```

### Decompiler Interface

```python
from ghidra.app.decompiler import DecompileInterface

decomp = DecompileInterface()
decomp.openProgram(currentProgram)
result = decomp.decompileFunction(func, 60, monitor)
if result.decompileCompleted():
    c_code = result.getDecompiledFunction().getC()
decomp.dispose()
```

### Memory Access

```python
memory = currentProgram.getMemory()
memory.getBlocks()                # List memory blocks
block.getStart()                  # Block start address
block.getEnd()                    # Block end address
block.isInitialized()             # Has data
memory.getBytes(addr, buffer)     # Read bytes
memory.getByte(addr)              # Read single byte
```

### Cross-References

```python
ref_mgr = currentProgram.getReferenceManager()
ref_mgr.getReferencesFrom(addr)    # Outgoing references
ref_mgr.getReferencesTo(addr)      # Incoming references
ref.getFromAddress()               # Source address
ref.getToAddress()                 # Target address
ref.getReferenceType()             # Type (CALL, DATA, etc.)
```

### Address Manipulation

```python
af = currentProgram.getAddressFactory()
addr = af.getAddress("0x00401000")  # Parse address string
addr.add(offset)                    # Offset from address
addr.subtract(other_addr)          # Distance between addresses
toAddr("0x00401000")               # Shorthand in scripts
```

## Ghidra Bridge (External Python)

```bash
pip install ghidra-bridge
```

```python
import ghidra_bridge
b = ghidra_bridge.GhidraBridge(namespace=globals())
# Now use Ghidra API from external Python
print(currentProgram.getName())
```

## Common Analysis Patterns

### Find All Calls to API

```python
symbol = currentProgram.getSymbolTable().getExternalSymbol("VirtualAlloc")
refs = currentProgram.getReferenceManager().getReferencesTo(symbol.getAddress())
for ref in refs:
    caller = fm.getFunctionContaining(ref.getFromAddress())
    println(f"{caller.getName()} calls VirtualAlloc at {ref.getFromAddress()}")
```

### Annotate Binary

```python
listing = currentProgram.getListing()
# Set comment types: EOL=0, PRE=1, POST=2, PLATE=3
listing.setComment(addr, 0, "Decryption routine")
```
