From 1326bb15713bc8abec6d05dbf24aa6cc307ac3ed Mon Sep 17 00:00:00 2001 From: shweet Date: Thu, 19 Nov 2026 21:30:14 -0500 Subject: [PATCH] source_tree: generated code coexists with the standard library and simdjson Ghidra's primitive names become the standard types they are (undefined4/uint/ulong -> uint32_t, byte -> uint8_t ...; Ghidra's ulong is 4 bytes, glibc's 8); the prelude includes the C library headers and every Ghidra type, global, import or free function the headers already declare is left to them; the MSVC STL stand-ins move to namespace msvc. A curated file can now include , , simdjson.h and classes.h together. Body rate unchanged: 877/3256. Co-Authored-By: Claude Opus 5.5 --- scripts/source_tree.py | 63 ++++++++++++++++++++++++++++++------------ src/rng.cpp | 16 +++++------ 2 files changed, 54 insertions(+), 25 deletions(-) diff --git a/scripts/source_tree.py b/scripts/source_tree.py index 541b6d9..b9ad9ac 100644 --- a/scripts/source_tree.py +++ b/scripts/source_tree.py @@ -21,7 +21,7 @@ POINTER_LIKE = {'EntityPtr'} # REPENTOGON's smart pointer, a raw Entity * in t 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+)\(') -CLANG = ['clang++', '--target=x86_64-linux-gnu', '-std=c++20', '-fsyntax-only', '-ferror-limit=0', '-nostdinc++', +CLANG = ['clang++', '--target=x86_64-linux-gnu', '-std=c++20', '-fsyntax-only', '-ferror-limit=0', '-Wno-invalid-offsetof', '-Wno-pragma-once-outside-header', '-w'] PRIMITIVE = {'bool': 1, 'char': 1, 'byte': 1, 'undefined': 1, 'undefined1': 1, 'short': 2, 'ushort': 2, 'word': 2, 'undefined2': 2, 'int': 4, 'uint': 4, 'float': 4, 'dword': 4, 'undefined4': 4, 'long': 4, 'ulong': 4, 'double': 8, 'Vector': 8, @@ -29,9 +29,24 @@ PRIMITIVE = {'bool': 1, 'char': 1, 'byte': 1, 'undefined': 1, 'undefined1': 1, ' 'uint16_t': 2, 'int16_t': 2, 'uint64_t': 8, 'int64_t': 8, 'unsigned int': 4, 'unsigned char': 1} PRELUDE = '''// Generated by scripts/source_tree.py. Do not edit: fix names, fields and prototypes in db/ and rebuild. #pragma once -typedef unsigned char uint8_t; typedef signed char int8_t; typedef unsigned short uint16_t; typedef short int16_t; -typedef unsigned int uint32_t; typedef int int32_t; typedef unsigned long long uint64_t; typedef long long int64_t; -typedef __SIZE_TYPE__ size_t; typedef long long __int64; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +typedef long long __int64; // The original 32-bit layout, checked with -m32: offsets and sizes there are the evidence, not the 64-bit target #if __SIZEOF_POINTER__ == 4 #define LAYOUT32(...) static_assert(__VA_ARGS__) @@ -39,8 +54,6 @@ typedef __SIZE_TYPE__ size_t; typedef long long __int64; #define LAYOUT32(...) #endif #define offsetof(type, member) __builtin_offsetof(type, member) -typedef uint8_t undefined, undefined1, byte; typedef uint16_t undefined2, word, ushort; typedef uint32_t undefined4, dword, uint, ulong; -typedef uint64_t undefined8, ulonglong; typedef int64_t longlong; typedef unsigned char uchar; typedef long double float10; typedef void code(...); // Ghidra's p-code intrinsics, as 64-bit bit patterns (CONCATxy: x and y bytes; SUBxy(v, n): y bytes from byte n of x) @@ -60,7 +73,6 @@ template inline T ABS(T v) { return v < 0 ? -v : v; } template 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 inline auto GHIDRA_INT(T v) { if constexpr (__is_pointer(T) || __is_class(T)) return (intptr_t)v; else return (int)v; } template inline auto GHIDRA_UINT(T v) { if constexpr (__is_pointer(T) || __is_class(T)) return (uintptr_t)(intptr_t)v; else return (uint)v; } @@ -82,7 +94,23 @@ 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 ''' -PRELUDE_TYPES = set(re.findall(r'(\w+)(?=[,;])', ' '.join(re.findall(r'typedef [^;]*;', PRELUDE)))) | {'code'} # typedef names +# Ghidra's primitive type names, written as the standard types they are (Ghidra's ulong is 4 bytes, glibc's is 8) +GHIDRA_RENAMES = {'undefined': 'uint8_t', 'undefined1': 'uint8_t', 'byte': 'uint8_t', 'uchar': 'uint8_t', 'undefined2': 'uint16_t', + 'word': 'uint16_t', 'ushort': 'uint16_t', 'undefined4': 'uint32_t', 'dword': 'uint32_t', 'uint': 'uint32_t', + 'ulong': 'uint32_t', 'undefined8': 'uint64_t', 'ulonglong': 'uint64_t', 'qword': 'uint64_t', 'longlong': 'int64_t', + 'float10': 'long double'} +PRELUDE_TYPES = set(GHIDRA_RENAMES) | {'code', '__int64'} + + +def generated_rename(text): # Ghidra's primitive names -> standard types, the MSVC STL stand-ins out of the real std's way + text = re.sub(r'\b(' + '|'.join(GHIDRA_RENAMES) + r')\b', lambda m: GHIDRA_RENAMES[m[1]], text) + return re.sub(r'\bstd::', 'msvc::', re.sub(r'\bnamespace std\b', 'namespace msvc', text)) + + +def std_names_load(): # every name the C library headers declare: the real declaration wins over Ghidra's copy + includes = ''.join(re.findall(r'#include <\w+>\n', PRELUDE)) + text = subprocess.run(['clang++', '-std=c++20', '-E', '-P', '-x', 'c++', '-'], input=includes, capture_output=True, text=True).stdout + return set(re.findall(r'[A-Za-z_]\w*', text)) def snake(name): @@ -293,8 +321,9 @@ while queue: # the closure over by-value and pointer members and typedef targe wanted.add(t) refs = [component_parse(d)[0].rstrip(' *') for _, d, _ in ghidraStructs.get(t, (0, []))[1]] + [component_parse(typedefs.get(t, ''))[0].rstrip(' *')] queue += [r for r in refs if r in ghidraStructs or r in typedefs] +STD_NAMES = std_names_load() for t in sorted(wanted & set(ghidraStructs)): - if t in fields or t in classes or not IDENT.match(t) or t in PRIMITIVE or t in PRELUDE_TYPES: continue + if t in fields or t in classes or not IDENT.match(t) or t in PRIMITIVE or t in PRELUDE_TYPES or t in STD_NAMES: continue taken = set() for off, display, fname in ghidraStructs[t][1]: typ, count = component_parse(display) @@ -410,7 +439,7 @@ def intrinsic_define(name): # CONCAT412: x=4, y=12; ZEXT1632: x=16, y=32 (a le # Everything that is not a method of a class above: free functions (FUN_ too) and namespace functions, as declared free, freeSeen = collections.defaultdict(list), set() for addr, (cls, method, ret, cc, params, thisParam, _) in sorted(funcs.items()): - if cls in done or not IDENT.match(method) or (cls and not QUALIFIED.match(cls)) or (cls, method) in freeSeen: continue + if cls in done or not IDENT.match(method) or (cls and not QUALIFIED.match(cls)) or (cls, method) in freeSeen or (not cls and method in STD_NAMES): continue freeSeen.add((cls, method)) if thisParam: params = [re.sub(r'\bthis$', 'self', thisParam)] + params free[cls].append(f'{ret} {method}({", ".join(params)}); // {addr:08x}') @@ -418,7 +447,7 @@ for addr, (cls, method, ret, cc, params, thisParam, _) in sorted(funcs.items()): # Ghidra enums and typedefs the code names (each enum constant once: they share one scope) aliases, constants = [], set() for t in sorted(wanted & set(enums)): - if t in done or not IDENT.match(t): continue + if t in done or not IDENT.match(t) or t in STD_NAMES: continue size, values = enums[t] values = [(n, v) for n, v in values if IDENT.match(n) and n not in constants] constants.update(n for n, _ in values) @@ -426,7 +455,7 @@ for t in sorted(wanted & set(enums)): aliases.append(f'enum {t} : {underlying} {{ ' + ', '.join(f'{n} = {v}' for n, v in values) + ' };') aliased = set() def typedef_emit(t, depth=0): # a typedef after the typedefs it names - if t in aliased or t in done or t in enums or t in PRIMITIVE or t in PRELUDE_TYPES or not IDENT.match(t) or depth > 16: return + if t in aliased or t in done or t in enums or t in PRIMITIVE or t in PRELUDE_TYPES or t in STD_NAMES or not IDENT.match(t) or depth > 16: return aliased.add(t) target, count = component_parse(typedefs[t]) if '(' in target or t in type_names(target): target, count = 'void *', 1 # function pointers, self references: opaque @@ -437,7 +466,7 @@ def typedef_emit(t, depth=0): # a typedef after the typedefs it names for t in sorted(wanted & set(typedefs)): typedef_emit(t) # Globals (dump/data.tsv), imported functions (dump/externals.tsv) and code addresses used as values (LAB_) -taken = {f[1] for f in funcs.values()} | {c.rpartition('::')[2] for c in done} | constants | set(re.findall(r'(\w+)(?:\[\d*\])?;', PRELUDE)) +taken = {f[1] for f in funcs.values()} | {c.rpartition('::')[2] for c in done} | constants | set(re.findall(r'(\w+)(?:\[\d*\])?;', PRELUDE)) | STD_NAMES globalDecls = [] for line in open(dumpDir + '/data.tsv', errors='replace') if os.path.exists(dumpDir + '/data.tsv') else []: if line.startswith('#'): continue @@ -458,13 +487,13 @@ for line in open(dumpDir + '/externals.tsv', errors='replace') if os.path.exists globalDecls.append(f'{match["ret"]} {match["name"]}({re.sub(r"\bthis\b", "self", match["params"])}); // {cols[0]}') labels = sorted({m for f in funcs.values() for m in re.findall(r'\b(LAB_[0-9a-f]+|register0x[0-9a-f]+|_?DAT_[0-9a-f]+|PTR_\w+_[0-9a-f]{8})\b', f[6])} - taken) # auto labels data.tsv lacks globalDecls += [f'extern {"code" if n.startswith("LAB_") else "undefined4"} {n};' for n in labels] -forward = sorted(t for t in used | {c for c in done if '::' not in c} if '::' not in t and t not in PRELUDE_TYPES and t not in enums and t not in typedefs) +forward = sorted(t for t in used | {c for c in done if '::' not in c} if '::' not in t and t not in PRELUDE_TYPES and t not in enums and t not in typedefs and t not in STD_NAMES) declarations = ''.join(f'namespace {ns} {{\n' + '\n'.join(d) + '\n}\n' if ns else '\n'.join(d) + '\n' for ns, d in sorted(free.items())) os.makedirs(outDir, exist_ok=True) with open(outDir + '/classes.h', 'w') as o: - o.write(PRELUDE + ''.join(intrinsic_define(n) for n in intrinsics) + '\n#if __SIZEOF_POINTER__ == 4\n#pragma pack(push, 1)\n#endif\n' + o.write(generated_rename(PRELUDE + ''.join(intrinsic_define(n) for n in intrinsics) + '\n#if __SIZEOF_POINTER__ == 4\n#pragma pack(push, 1)\n#endif\n' + ''.join(f'struct {t};\n' for t in forward) + '\n' + '\n'.join(aliases) + '\n\n' + '\n'.join(order) + '#if __SIZEOF_POINTER__ == 4\n#pragma pack(pop)\n#endif\n\n' - + declarations + '\n' + '\n'.join(globalDecls) + '\n') + + declarations + '\n' + '\n'.join(globalDecls) + '\n')) # One .cpp per class: each body under the declaration it was declared with; a renamed `this` gets an alias. members = {f'{f[0]}::{f[1]}' for f in funcs.values() if f[3] == '__thiscall' and f[0] in done} @@ -490,7 +519,7 @@ for cls in [c for c in done if not LIBRARY.match(c)]: path = '/'.join(snake(p) for p in cls.split('::')) + '.cpp' files[cls] = path os.makedirs(os.path.dirname(f'{outDir}/{path}') or outDir, exist_ok=True) - open(f'{outDir}/{path}', 'w').write(''.join(parts)) + open(f'{outDir}/{path}', 'w').write(generated_rename(''.join(parts))) print(f'source_tree: {len(curated)} functions taken over by src/, {len(done)} classes, {sum(1 for c in done if size.get(c))} sized, {sum(len(v) for v in methods.values())} methods,' f' {sum(len(s) for s in spans.values())} bodies in {len(files)} .cpp files') diff --git a/src/rng.cpp b/src/rng.cpp index ff1cc49..4218f46 100644 --- a/src/rng.cpp +++ b/src/rng.cpp @@ -23,7 +23,7 @@ constexpr unsigned int SHIFTS[SHIFT_COUNT][3] = { constexpr float FLOAT_SCALE = 2.3283062e-10f; // 007e8fe0 Seeds the generator, clamping the shift index to the last triple. -void RNG::SetSeed(uint seed, uint shiftIndex) +void RNG::SetSeed(uint32_t seed, uint32_t shiftIndex) { unsigned int index = shiftIndex < SHIFT_COUNT ? shiftIndex : SHIFT_COUNT - 1; @@ -34,17 +34,17 @@ void RNG::SetSeed(uint seed, uint shiftIndex) } // 007e8f90 Seeds the generator as its constructor does, asserting on a shift index past the table. -void RNG::game_constructor(uint seed, uint shiftIndex) +void RNG::game_constructor(uint32_t seed, uint32_t shiftIndex) { - if (shiftIndex >= SHIFT_COUNT) KAGE_LogMessage(LOG_ASSERT, (byte*)"RNG: Invalid ShiftIdx\n"); + if (shiftIndex >= SHIFT_COUNT) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"RNG: Invalid ShiftIdx\n"); SetSeed(seed, shiftIndex); } // 007e90f0 Steps the seed through its xorshift and returns it. // The game stops in the debugger on a zero seed, which never moves again. -uint RNG::Next() +uint32_t RNG::Next() { - if (_seed == 0) KAGE_LogMessage(LOG_ASSERT, (byte*)"RNG Seed is zero!\n"); + if (_seed == 0) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"RNG Seed is zero!\n"); _seed ^= _seed >> _shift1; _seed ^= _seed << _shift2; @@ -53,9 +53,9 @@ uint RNG::Next() } // 007e9020 A number below max, or 0 for a max of 0. -uint RNG::RandomInt(uint max) +uint32_t RNG::RandomInt(uint32_t max) { - uint value = Next(); + uint32_t value = Next(); return max == 0 ? 0 : value % max; } @@ -70,7 +70,7 @@ void RNG::Shuffle(RNG* rng, int* begin, int* end) { for (long i = end - begin - 1; i > 0; i--) { - uint other = rng->Next() % (uint)(i + 1); + uint32_t other = rng->Next() % (uint32_t)(i + 1); int value = begin[i]; begin[i] = begin[other];