feat(re): headless Ghidra RVA symbol DB exporter + validator

This commit is contained in:
ulw-execute committed 2026-11-28 04:27:11 -05:00
1 parent dd362cb13f
commit a0d649cf57
3 files changed
+1699921

No files matched your search

+1699601
View File
File diff suppressed because it is too large. Load diff
+178
View File
@@ -0,0 +1,178 @@
# Export the analyzed gamekdm program without changing it.
# @category GameKDM
# Run with analyzeHeadless ... -process gamekdm.dll -noanalysis
# -scriptPath tools/ghidra -postScript export_rvadb.py /absolute/re/rvadb.json
# Ghidra 11.3 uses Jython 2.7: no Python 3 syntax or third-party packages.
import json
import math
import os
from ghidra.program.model.address import Address
from ghidra.program.model.scalar import Scalar
from java.lang import Number, String
def rva(address):
"""Use RVAs only for addresses in the program's default memory space."""
if address.getAddressSpace() != image_base.getAddressSpace():
raise ValueError("Not an image address: %s" % address)
offset = address.subtract(image_base)
if offset < 0:
raise ValueError("Address precedes image base: %s" % address)
return "0x%08x" % offset
def decoded_value(data):
"""Preserve typed scalars/strings and recursively decode defined tables."""
value = data.getValue()
if isinstance(value, (basestring, String)):
return unicode(value)
if isinstance(value, Scalar):
return long(value.getValue())
if isinstance(value, Address):
if value.getAddressSpace() == image_base.getAddressSpace():
if value.getOffset() >= image_base.getOffset():
return {"pointer_rva": rva(value)}
return {"address": str(value)}
if isinstance(value, Number):
number = float(value.doubleValue())
return number if not (math.isnan(number) or math.isinf(number)) else str(value)
if data.getNumComponents():
return [decoded_value(data.getComponent(i))
for i in range(data.getNumComponents())]
# Unknown types remain recoverable from the complete bytes_hex field.
return None
def data_record(address, data):
"""Capture each data extent, including all aliases and initialized bytes."""
block = memory.getBlock(address)
length = data.getLength() if data is not None else 1
initialized = (block.isInitialized() and
block.contains(address.add(length - 1)))
raw = None
value = None
if initialized:
raw = "".join("%02x" % (int(byte) & 0xff)
for byte in getBytes(address, length))
value = decoded_value(data) if data is not None else int(raw, 16)
return {
"rva": rva(address),
"names": sorted(set(unicode(s.getName(True))
for s in symbols.getSymbols(address))),
"data_type": unicode(data.getDataType().getPathName()) if data else "undefined",
"size": length,
"section": unicode(block.getName()),
"read_only": not block.isWrite(),
"initialized": initialized,
"bytes_hex": raw,
"value": value,
"extent_known": data is not None,
}
args = getScriptArgs()
if len(args) != 1 or not os.path.isabs(args[0]):
raise ValueError("Usage: export_rvadb.py /absolute/path/to/rvadb.json")
destination = args[0]
prior_statuses = {}
if os.path.exists(destination):
with open(destination, "r") as previous:
prior_statuses = dict((row["rva"], row.get("status", "orig"))
for row in json.load(previous)["functions"])
image_base = currentProgram.getImageBase()
if image_base.getOffset() != 0x10000000:
raise ValueError("Expected gamekdm image base 0x10000000, got %s" % image_base)
fm = currentProgram.getFunctionManager()
listing = currentProgram.getListing()
memory = currentProgram.getMemory()
symbols = currentProgram.getSymbolTable()
references = currentProgram.getReferenceManager()
# Count independently before exporting, using exactly the requested iterator.
ghidra_count = sum(1 for function in fm.getFunctions(True))
print("RVADB_GHIDRA_FUNCTION_COUNT=%d" % ghidra_count)
functions = []
for function in fm.getFunctions(True):
monitor.checkCancelled()
entry = function.getEntryPoint()
namespace = function.getParentNamespace()
module = unicode(namespace.getName(True)) if not namespace.isGlobal() else "unknown"
callees = sorted(set(rva(f.getEntryPoint())
for f in function.getCalledFunctions(monitor)
if not f.isExternal()))
external_callees = sorted(set(unicode(f.getName(True))
for f in function.getCalledFunctions(monitor)
if f.isExternal()))
globals_touched = set()
for source in references.getReferenceSourceIterator(function.getBody(), True):
for ref in references.getReferencesFrom(source):
target = ref.getToAddress()
if (target.isMemoryAddress() and memory.contains(target) and
ref.getReferenceType().isData() and
fm.getFunctionContaining(target) is None):
globals_touched.add(rva(target))
functions.append({
"rva": rva(entry),
"name": unicode(function.getName(True)),
"calling_convention": unicode(function.getCallingConventionName()),
"signature": unicode(function.getSignature()),
"owning_module_guess": module,
"status": prior_statuses.get(rva(entry), "orig"),
"globals_touched": sorted(globals_touched),
"callers": [],
"callees": callees,
"external_callees": external_callees,
})
# Derive the reverse graph from the same resolved edges, without losing self-calls.
by_rva = dict((row["rva"], row) for row in functions)
for row in functions:
for callee in row["callees"]:
by_rva[callee]["callers"].append(row["rva"])
for row in functions:
row["callers"] = sorted(set(row["callers"]))
data_symbols = {}
for data in listing.getDefinedData(True):
monitor.checkCancelled()
address = data.getAddress()
if memory.contains(address):
data_symbols[rva(address)] = data_record(address, data)
for symbol in symbols.getAllSymbols(True):
monitor.checkCancelled()
address = symbol.getAddress()
if (address.isMemoryAddress() and memory.contains(address) and
fm.getFunctionContaining(address) is None and
listing.getDefinedDataContaining(address) is None and
listing.getInstructionContaining(address) is None):
key = rva(address)
if key not in data_symbols:
# A label does not establish table length; export one byte explicitly.
data_symbols[key] = data_record(address, None)
if len(functions) != ghidra_count or len(by_rva) != ghidra_count:
raise ValueError("Function rows differ from Ghidra iterator count")
database = {
"schema_version": 1,
"program": unicode(currentProgram.getName()),
"image_base": "0x10000000",
"function_count": ghidra_count,
"data_symbol_count": len(data_symbols),
"reference_scope": "Ghidra resolved calls and direct memory data references; indirect targets may be unknown",
"module_guess_method": "Ghidra parent namespace, otherwise unknown",
"functions": sorted(functions, key=lambda row: row["rva"]),
"data_symbols": [data_symbols[key] for key in sorted(data_symbols)],
}
parent = os.path.dirname(destination)
if not os.path.isdir(parent):
os.makedirs(parent)
# No timestamps or transient IDs; replace only after the full JSON is written.
with open(destination + ".tmp", "w") as output:
json.dump(database, output, sort_keys=True, indent=2, ensure_ascii=True,
allow_nan=False)
output.write("\n")
os.rename(destination + ".tmp", destination)
print("RVADB_EXPORTED_FUNCTION_COUNT=%d" % len(functions))
print("RVADB_DATA_SYMBOL_COUNT=%d" % len(data_symbols))
print("RVADB_EXPORT_COMPLETE=%s" % destination)
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Validate the RVA database and compare it with an independent Ghidra count.
Usage: python3 tools/ghidra/validate_rvadb.py re/rvadb.json GHIDRA_COUNT
The count is the RVADB_GHIDRA_FUNCTION_COUNT line from the headless transcript.
This companion CLI uses only the standard library, like the Jython exporter.
"""
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True, slots=True)
class InvalidDatabase(ValueError):
"""A failed schema or graph invariant, with its JSON location."""
location: str
requirement: str
def __str__(self) -> str:
return f"{self.location}: {self.requirement}"
def require(condition: bool, location: str, requirement: str) -> None:
"""Reject invalid input even when Python assertions are disabled."""
if not condition:
raise InvalidDatabase(location, requirement)
def valid_rva(value: str) -> bool:
"""Accept canonical 32-bit image-relative hexadecimal addresses."""
return isinstance(value, str) and re.fullmatch(r"0x[0-9a-f]{8}", value) is not None
def validate(path: Path, expected_count: int) -> tuple[int, int]:
"""Check the JSON boundary, unique rows, reference graph and data payloads."""
with path.open(encoding="utf-8") as source:
db = json.load(source)
require(isinstance(db, dict), "$", "must be an object")
require(db.get("schema_version") == 1, "$.schema_version", "must be 1")
require(db.get("image_base") == "0x10000000", "$.image_base", "wrong image base")
require(db.get("program") == "gamekdm.dll", "$.program", "wrong program")
for field in ("reference_scope", "module_guess_method"):
require(isinstance(db.get(field), str) and bool(db[field]), field, "must be text")
require(expected_count > 0, "expected_count", "must be positive")
rows = db.get("functions")
require(isinstance(rows, list), "$.functions", "must be an array")
require(type(db.get("function_count")) is int, "$.function_count", "must be integer")
require(len(rows) == db["function_count"] == expected_count,
"$.functions", f"row/metadata counts must equal Ghidra count {expected_count}")
index = {}
for i, row in enumerate(rows):
location = f"$.functions[{i}]"
require(isinstance(row, dict), location, "must be an object")
require(valid_rva(row.get("rva")), location + ".rva", "must be canonical hex RVA")
require(row["rva"] not in index, location + ".rva", "duplicate function")
index[row["rva"]] = row
for field in ("name", "calling_convention", "signature", "owning_module_guess"):
require(isinstance(row.get(field), str) and bool(row[field]),
location + "." + field, "must be nonempty text")
require(row.get("status") in ("orig", "stub", "reimpl", "verified"),
location + ".status", "must be orig, stub, reimpl, or verified")
for field in ("globals_touched", "callers", "callees"):
values = row.get(field)
require(isinstance(values, list), location + "." + field, "must be an array")
require(all(valid_rva(value) for value in values),
location + "." + field, "entries must be canonical hex RVAs")
require(values == sorted(set(values)),
location + "." + field, "entries must be sorted and unique")
external = row.get("external_callees")
require(isinstance(external, list) and
all(isinstance(name, str) and bool(name) for name in external),
location + ".external_callees", "must be an array of names")
require([row["rva"] for row in rows] == sorted(index), "$.functions", "must be sorted")
for address, row in index.items():
for target in row["callees"]:
require(target in index, address + ".callees", f"unknown function {target}")
require(address in index[target]["callers"], address, "missing reverse call edge")
for source in row["callers"]:
require(source in index, address + ".callers", f"unknown function {source}")
require(address in index[source]["callees"], address, "missing forward call edge")
data_rows = db.get("data_symbols")
require(isinstance(data_rows, list) and bool(data_rows),
"$.data_symbols", "must be a nonempty array")
require(type(db.get("data_symbol_count")) is int and
db["data_symbol_count"] == len(data_rows),
"$.data_symbol_count", "must equal data row count")
data_addresses = []
initialized_count = 0
for i, row in enumerate(data_rows):
location = f"$.data_symbols[{i}]"
require(isinstance(row, dict), location, "must be an object")
require(valid_rva(row.get("rva")), location + ".rva", "must be canonical hex RVA")
data_addresses.append(row["rva"])
require(isinstance(row.get("names"), list) and
all(isinstance(name, str) for name in row["names"]),
location + ".names", "must be an array of names")
for field in ("data_type", "section"):
require(isinstance(row.get(field), str) and bool(row[field]),
location + "." + field, "must be nonempty text")
require(type(row.get("size")) is int and row["size"] > 0,
location + ".size", "must be a positive integer")
for field in ("initialized", "read_only", "extent_known"):
require(type(row.get(field)) is bool, location + "." + field, "must be boolean")
require("value" in row and "bytes_hex" in row, location, "missing initialized payload fields")
if row["initialized"]:
raw = row["bytes_hex"]
require(isinstance(raw, str) and len(raw) == 2 * row["size"] and
re.fullmatch(r"[0-9a-f]+", raw) is not None,
location + ".bytes_hex", "must contain exactly size bytes")
initialized_count += 1
else:
require(row["bytes_hex"] is None and row["value"] is None,
location, "uninitialized data must have null payloads")
require(data_addresses == sorted(set(data_addresses)),
"$.data_symbols", "RVAs must be sorted and unique")
require(initialized_count > 0, "$.data_symbols", "must include initialized values")
return len(rows), len(data_rows)
def main() -> int:
"""Expose a nonzero exit status for malformed input or count mismatch."""
if len(sys.argv) != 3:
print(__doc__, file=sys.stderr)
return 2
try:
functions, data_symbols = validate(Path(sys.argv[1]), int(sys.argv[2]))
except (ValueError, OSError) as error:
print(f"RVADB_INVALID: {error}", file=sys.stderr)
return 1
print(f"RVADB_VALID functions={functions} ghidra_count={sys.argv[2]} data_symbols={data_symbols}")
return 0
if __name__ == "__main__":
sys.exit(main())