source_tree: STL member layouts, (int) casts that keep pointer width, EntityPtr as a pointer, Ghidra partial fields
Container fields use the MSVC layouts ApplyTypes gives Ghidra (vector_X -> std_vector ...); (int)/(uint) casts become GHIDRA_INT/GHIDRA_UINT (32-bit numbers, full-width pointers); EntityPtr behaves as the raw pointer the code treats it as; EXPR._0_4_ partial accesses become explicit offsets; field-less Ghidra placeholders no longer claim 4 bytes. --check: 878/3262 method bodies compile for x86_64 (26.9%). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fdfdb10137
commit
bafef76746
285 files changed
+37175
-37199
No files matched your search
+64
-7
@@ -13,6 +13,7 @@ import collections, concurrent.futures, os, re, subprocess, sys
|
||||
outDir, classesPath, dumpDir, zhlVtablesPath = sys.argv[1:5]
|
||||
isCheck = '--check' in sys.argv
|
||||
CALLING = re.compile(r'^(?P<ret>.+?)\s*\b(?:(?P<cc>__thiscall|__fastcall|__cdecl|__stdcall)\s+)?(?P<name>[\w:~]+)\((?P<params>.*)\)\s*$')
|
||||
POINTER_LIKE = {'EntityPtr'} # REPENTOGON's smart pointer, a raw Entity * in the decompiled code
|
||||
LIBRARY = re.compile(r'^(std|rapidxml|theoraplayer|luabridge|stb_vorbis|Concurrency)(::|$)') # third party: declared, not reconstructed
|
||||
IDENT = re.compile(r'^~?[A-Za-z_]\w*$')
|
||||
INTRINSIC = re.compile(r'\b(CONCAT|SUB|ZEXT|SEXT|CARRY|SCARRY|SBORROW)(\d+)\(')
|
||||
@@ -55,6 +56,19 @@ template <class T> inline T ABS(T v) { return v < 0 ? -v : v; }
|
||||
template <class T> inline T SQRT(T v) { return __builtin_sqrt(v); }
|
||||
inline code *swi(int) { return 0; } // int3 / int 0x29: a breakpoint or fast-fail
|
||||
inline void halt_baddata() {}
|
||||
typedef __INTPTR_TYPE__ intptr_t; typedef __UINTPTR_TYPE__ uintptr_t;
|
||||
// (int)x / (uint)x as decompiled: a number stays 32-bit, a pointer keeps its full width (pointer math on 64-bit)
|
||||
template <class T> inline auto GHIDRA_INT(T v) { if constexpr (__is_pointer(T) || __is_class(T)) return (intptr_t)v; else return (int)v; }
|
||||
template <class T> inline auto GHIDRA_UINT(T v) { if constexpr (__is_pointer(T) || __is_class(T)) return (uintptr_t)(intptr_t)v; else return (uint)v; }
|
||||
// A smart pointer the decompiled code handles as a raw pointer: built from 0 or a pointer, converts back, compares
|
||||
#define GHIDRA_POINTER_LIKE(Self) \
|
||||
void *_ptr; \
|
||||
Self(intptr_t value = 0) : _ptr((void *)value) {} \
|
||||
Self(const void *value) : _ptr((void *)value) {} \
|
||||
template <class T> operator T *() const { return (T *)_ptr; } \
|
||||
explicit operator intptr_t() const { return (intptr_t)_ptr; } \
|
||||
friend bool operator==(Self a, Self b) { return a._ptr == b._ptr; } \
|
||||
friend bool operator!=(Self a, Self b) { return a._ptr != b._ptr; }
|
||||
extern void *ExceptionList; // FS:[0], the SEH chain head
|
||||
extern double __uint_to_double_fixup[2]; // MSVC CRT: +2^32 for a uint whose top bit was set
|
||||
'''
|
||||
@@ -77,6 +91,13 @@ def classes_load():
|
||||
return rows
|
||||
|
||||
|
||||
def container_name(typ): # vector_DamageEvent -> std_vector: the MSVC layouts ApplyTypes gives Ghidra (one per kind)
|
||||
if typ.startswith('std_string'): return 'std_string'
|
||||
if re.fullmatch(r'(std_)?vector_bool', typ): return 'std_vector_bool'
|
||||
match = re.fullmatch(r'(?:std_)?(vector|deque|map|set|multiset|multimap|list)_\w+', typ)
|
||||
return f'std_{match[1]}' if match else typ
|
||||
|
||||
|
||||
def fields_load():
|
||||
fields, bases, sizes = collections.defaultdict(dict), {}, {}
|
||||
for line in open(dumpDir + '/zhl_fields.tsv'):
|
||||
@@ -88,7 +109,7 @@ def fields_load():
|
||||
count = re.search(r'\[(\w+)\]\s*$', decl)
|
||||
if count: decl = decl[:count.start()]
|
||||
typ, name = decl.rsplit(None, 1) if ' ' in decl else (decl, '_unnamed')
|
||||
fields[cols[0]][int(cols[1], 16)] = (typ.strip(), re.sub(r'\W', '', name), int(count.group(1), 0) if count else 1)
|
||||
fields[cols[0]][int(cols[1], 16)] = (container_name(typ.strip()), re.sub(r'\W', '', name), int(count.group(1), 0) if count else 1)
|
||||
return fields, bases, sizes
|
||||
|
||||
|
||||
@@ -148,9 +169,9 @@ def method_declare(cls, method, ret, cc, params, isVirtual):
|
||||
return f' {prefix}{ret} {method}({args});'
|
||||
|
||||
|
||||
def fields_rewrite(text): # EXPR->field_0x1c / EXPR.field_0x1c (a byte Ghidra had no field for) -> the byte at that offset
|
||||
def fields_rewrite(text): # bytes Ghidra has no field for, as explicit offsets: EXPR->field_0x1c, EXPR.field_0x1c, EXPR._0_4_
|
||||
out, pos = [], 0
|
||||
for match in re.finditer(r'(->|\.)field_0x([0-9a-f]+)\b', text):
|
||||
for match in re.finditer(r'(->|\.)(?:field_0x([0-9a-f]+)|_(\d+)_(\d+)_)\b', text):
|
||||
start = match.start()
|
||||
while start > pos: # walk back over the postfix expression: names, (...), [...], -> and .
|
||||
ch = text[start - 1]
|
||||
@@ -164,7 +185,9 @@ def fields_rewrite(text): # EXPR->field_0x1c / EXPR.field_0x1c (a byte Ghidra
|
||||
else: break
|
||||
expr = text[start:match.start()]
|
||||
address = f'(char *)({expr})' if match[1] == '->' else f'(char *)&({expr})'
|
||||
out.append(text[pos:start] + f'(*(undefined1 *)({address} + 0x{match[2]}))'); pos = match.end()
|
||||
offset, width = (int(match[2], 16), 1) if match[2] else (int(match[3]), int(match[4]))
|
||||
typ = {1: 'undefined1', 2: 'undefined2', 4: 'undefined4', 8: 'undefined8'}.get(width, 'undefined1')
|
||||
out.append(text[pos:start] + f'(*({typ} *)({address} + 0x{offset:x}))'); pos = match.end()
|
||||
return ''.join(out) + text[pos:]
|
||||
|
||||
|
||||
@@ -172,6 +195,39 @@ def offsets_rewrite(text): # *(T *)((int)p + 0x10) -> *(T *)((char *)p + 0x10)
|
||||
return re.sub(r'(\*\([\w ]+\*+\)\()\((?:int|uint)\)((?:\w+(?:->|\.))*\w+|\([^()]*\)) \+ ', r'\1(char *)\2 + ', text)
|
||||
|
||||
|
||||
def operand_end(text, i): # end of the unary expression starting at i: prefix ops, casts, a primary, then postfix
|
||||
n = len(text)
|
||||
def group(j): # j at an opening bracket: index after its match
|
||||
depth = 0
|
||||
while j < n:
|
||||
depth += {'(': 1, '[': 1, ')': -1, ']': -1}.get(text[j], 0); j += 1
|
||||
if depth == 0: return j
|
||||
return n
|
||||
while i < n and text[i] in ' *&-!~': i += 1
|
||||
cast = re.match(r'\([\w ]+\*?\s*\)', text[i:]) # a nested cast applies to the operand after it
|
||||
if cast and not re.fullmatch(r'\(\s*\w+\s*\)', cast[0]) or cast and cast[0][1:-1].strip() in PRIMITIVE: return operand_end(text, i + len(cast[0]))
|
||||
if i < n and text[i] == '(': i = group(i)
|
||||
else:
|
||||
m = re.match(r"[\w.]+|'[^']*'|\"[^\"]*\"", text[i:])
|
||||
i += len(m[0]) if m else 0
|
||||
while i < n:
|
||||
if text[i] in '([': i = group(i)
|
||||
elif text.startswith('->', i): i += 2; i += len(re.match(r'\w*', text[i:])[0])
|
||||
elif text[i] == '.' and i + 1 < n and (text[i + 1].isalpha() or text[i + 1] == '_'): i += 1; i += len(re.match(r'\w*', text[i:])[0])
|
||||
else: break
|
||||
return i
|
||||
|
||||
|
||||
def int_casts_rewrite(text): # (int)expr -> GHIDRA_INT(expr), (uint)expr -> GHIDRA_UINT(expr)
|
||||
out, pos = [], 0
|
||||
for match in re.finditer(r'\((int|uint)\)', text):
|
||||
if match.start() < pos: continue
|
||||
end = operand_end(text, match.end())
|
||||
inner = int_casts_rewrite(text[match.end():end])
|
||||
out.append(text[pos:match.start()] + f'GHIDRA_{match[1].upper()}({inner})'); pos = end
|
||||
return ''.join(out) + text[pos:]
|
||||
|
||||
|
||||
def virtuals_rewrite(text, varTypes): # (**(code **)(*(int *)X + 0x24))(args) -> X->Method(args), X's class from its declaration
|
||||
def slot_call(match):
|
||||
var, offset = match[1], int(match[2], 0)
|
||||
@@ -224,8 +280,8 @@ for t in sorted(wanted & set(ghidraStructs)):
|
||||
name = re.sub(r'\W', '_', fname) or f'field_0x{off:x}'
|
||||
if name in taken: name += f'_0x{off:x}'
|
||||
taken.add(name); fields[t][off] = (typ, name, count)
|
||||
sizes[t] = ghidraStructs[t][0]
|
||||
if not ghidraStructs[t][1]: fields[t] # an empty struct still gets its size
|
||||
if ghidraStructs[t][1]: sizes[t] = ghidraStructs[t][0] # a field-less one is Ghidra's 4-byte placeholder, not a size
|
||||
else: fields[t]
|
||||
zhlSlots = {(c, int(i)): n for c, i, n in (l.rstrip('\n').split('\t') for l in open(zhlVtablesPath))}
|
||||
QUALIFIED = re.compile(r'^\w+(::\w+)*$')
|
||||
names = set(classes) | set(fields) | set(fieldBases) | {f[0] for f in funcs.values() if f[3] == '__thiscall' and QUALIFIED.match(f[0])}
|
||||
@@ -313,6 +369,7 @@ def class_emit(cls, stack=()):
|
||||
if not decl: continue
|
||||
seen.add(key); used.update(sig_types(ret, params)); defined[addr] = decl.strip()
|
||||
decls.append(decl + f' // {addr:08x}')
|
||||
if cls in POINTER_LIKE: lines = [f' GHIDRA_POINTER_LIKE({shortName})']
|
||||
nested = [c.rpartition('::')[2] for c in names if c.rpartition('::')[0] == cls]
|
||||
body = '\n'.join([f' struct {n};' for n in sorted(nested)] + decls + ([''] if decls and lines else []) + lines)
|
||||
head = f'struct {cls if isNested else shortName}' + (f' : {parent}' if parent else '')
|
||||
@@ -401,7 +458,7 @@ for cls in [c for c in done if not LIBRARY.match(c)]:
|
||||
varTypes = {m[2]: m[1] for m in re.finditer(r'^\s+((?:\w+::)*\w+)\s*\*\s*(\w+);', funcs[addr][6], re.M)}
|
||||
varTypes.update({p.rsplit('*', 1)[1].strip(): p.rsplit('*', 1)[0].strip() for p in params if '*' in p})
|
||||
varTypes['this'] = cls
|
||||
body = calls_rewrite(virtuals_rewrite(offsets_rewrite(fields_rewrite(funcs[addr][6])), varTypes), members)
|
||||
body = int_casts_rewrite(calls_rewrite(virtuals_rewrite(offsets_rewrite(fields_rewrite(funcs[addr][6])), varTypes), members))
|
||||
text = f'\n// {addr:08x}\n{decl.replace(name + "(", cls + "::" + name + "(", 1)}\n{{\n{alias}{body}\n}}\n'
|
||||
spans[cls].append((line + 1, line + text.count('\n'), addr)); line += text.count('\n'); parts.append(text)
|
||||
if len(parts) > 1:
|
||||
|
||||
Reference in new issue
Block a user