mtk-wifi-fw/tools/ghidra_scripts/LabelHandlers.py

46 lines
1.8 KiB
Python

# Headless post-script: label command handlers from a named-handler map.
# Reads files listed in env MTK_HANDLER_MAPS (colon-separated), lines like:
# 0x02231eb0 id=0x25 fn=0xf0097174 MCU_EXT_CMD_STA_REC_UPDATE
# Creates a function at each fn address (if missing) and renames it
# cmdHdlr_<id02x>_<ENUMNAME>.
#@category Analysis
import os
import re
from ghidra.program.model.symbol import SourceType
from ghidra.app.cmd.function import CreateFunctionCmd
from ghidra.app.cmd.label import RenameLabelCmd
maps = os.environ.get('MTK_HANDLER_MAPS', '')
fm = currentProgram.getFunctionManager()
created = renamed = skipped = 0
pat = re.compile(r'id=(0x[0-9a-f]+) fn=(0x[0-9a-f]+) (MCU_[A-Z0-9_]+|\(MTK-internal id\))')
for path in maps.split(':'):
if not path:
continue
print('map file: %s' % path)
for ln in open(path):
m = pat.search(ln)
if not m:
continue
cid, fns, nm = int(m.group(1), 16), m.group(2), m.group(3)
name = 'cmdHdlr_%02x_%s' % (cid, nm.strip('()').replace('-internal id', 'internal'))
addr = currentProgram.getAddressFactory().getAddress(fns)
f = fm.getFunctionAt(addr)
tx = currentProgram.startTransaction('label')
try:
if f is None:
f = createFunction(addr, name)
if f is not None:
created += 1
else:
skipped += 1
print(' ! could not create %s at %s' % (name, fns))
else:
f.setName(name, SourceType.USER_DEFINED)
renamed += 1
print(' %s -> %s' % (fns, name))
finally:
currentProgram.endTransaction(tx, True)
print('label summary: created=%d renamed=%d skipped=%d' % (created, renamed, skipped))