Files
isaac-port/scripts/apply_db.py
T

25 lines
1.6 KiB
Python

# Applies db/names.tsv to the dump in place (no Ghidra): headers, call sites, functions.tsv, strings.tsv, npc_ai.tsv.
# Only names change; types/fields need build.sh --db. Safe to re-run. Usage: apply_db.py names.tsv dumpdir
import re, sys
from collections import Counter
db, d = sys.argv[1:3]
fns = dict(l.rstrip('\n').split('\t')[:2] for l in open(f'{d}/functions.tsv'))
count = Counter(fns.values())
ren = {}
for l in open(db):
if l.strip() and not l.startswith('#'):
a, new = l.rstrip('\n').split('\t')[:2]
a = '%08x' % int(a, 16) # accept 0x59e730 / 0059e730 / 0x0059e730
if a in fns: ren[a] = new
# By address everywhere: "//@@ addr name" headers, functions.tsv, and addr:name user lists in strings.tsv/npc_ai.tsv.
# Call sites only show the old name, so they are rewritten only where that old name belonged to one function.
old2new = {fns[a]: n for a, n in ren.items() if fns[a] != n and count[fns[a]] == 1}
calls = re.compile(r'(?<!\w)(?<!::)(' + '|'.join(sorted(map(re.escape, old2new), key=len, reverse=True)) + r')(?![\w:])')
users = re.compile(r'(?:(?<=^//@@ )|\b)(' + '|'.join(ren) + r')([: ])[^\s]+', re.M)
def fix(s): return users.sub(lambda m: m.group(1) + m.group(2) + ren[m.group(1)], calls.sub(lambda m: old2new[m.group(1)], s) if old2new else s)
for f in ('all.c', 'strings.tsv', 'npc_ai.tsv'):
p = f'{d}/{f}'; s = open(p).read(); open(p, 'w').write(fix(s))
rows = [l.split('\t', 2) for l in open(f'{d}/functions.tsv')]
open(f'{d}/functions.tsv', 'w').writelines(f'{a}\t{ren.get(a, n)}\t{r}' for a, n, r in rows)
print(f'apply_db: {sum(fns[a] != n for a, n in ren.items())} renamed, {len(ren)} in db')