-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtouhouReverse.py
More file actions
303 lines (252 loc) · 13.8 KB
/
touhouReverse.py
File metadata and controls
303 lines (252 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
from binaryninja import log
import binaryninja as bn
from importlib import reload as _reload
# Reload all submodules before re-exporting from them.
#
# This ensures that calling reload() on THIS module will also update everything reexported from it.
# (otherwise you'd have to remember which file the thing you changed lives in, import it, and reload that
# before reloading this. Yuck)
import touhouReverseBnutil as _touhouReverseBnutil
import touhouReverseLabels as _touhouReverseLabels
import touhouReverseStructs as _touhouReverseStructs
import touhouReverseSearch as _touhouReverseSearch
import touhouReverseAnalysis as _touhouReverseAnalysis
import touhouReverseConfig as _touhouReverseConfig
for mod in [_touhouReverseBnutil, _touhouReverseLabels, _touhouReverseStructs, _touhouReverseSearch, _touhouReverseAnalysis, _touhouReverseConfig]:
_reload(mod)
# These are re-exports.
# (it'd be nice if we could reexport everything while still being forced to explicitly import the
# things we actually use in this file...)
from touhouReverseBnutil import * # pylint: disable=unused-wildcard-import
from touhouReverseLabels import * # pylint: disable=unused-wildcard-import
from touhouReverseStructs import * # pylint: disable=unused-wildcard-import
from touhouReverseSearch import * # pylint: disable=unused-wildcard-import
from touhouReverseAnalysis import * # pylint: disable=unused-wildcard-import
from touhouReverseConfig import * # pylint: disable=unused-wildcard-import
def name_initialize_method_at(bv, addr): return name_method_at(bv, addr, 'initialize')
def name_destructor_method_at(bv, addr): return name_method_at(bv, addr, 'destructor')
def name_constructor_method_at(bv, addr): return name_method_at(bv, addr, 'constructor')
def name_on_tick_method_at(bv, addr): return name_method_at(bv, addr, 'on_tick')
def name_on_draw_method_at(bv, addr): return name_method_at(bv, addr, 'on_draw')
def name_on_registration_method_at(bv, addr): return name_method_at(bv, addr, 'on_registration')
def name_on_cleanup_method_at(bv, addr): return name_method_at(bv, addr, 'on_cleanup')
def name_method_at(bv: bn.BinaryView, addr, method):
this_func = bv.get_functions_containing(addr)[0]
if '::' not in this_func.name:
raise RuntimeError(f'function name does not contain ::')
class_name = this_func.name.split(':')[0]
desired_name = class_name + '::' + method
return name_func_called_at(bv, addr, desired_name)
def get_stub_target_jump_ins(bv: bn.BinaryView, func: bn.Function):
jumps = []
if len(list(func.instructions)) <= 5:
for toks, ins_addr in func.instructions:
if toks[0].text in ['call', 'jmp']:
# Try to parse last token as an address
if toks[-1].text[:2] != '0x':
continue
try:
addr = int(toks[-1].text[2:], 16)
except ValueError:
continue
funcs = list(bv.get_functions_containing(addr))
if funcs and funcs[0].start == addr:
jumps.append(ins_addr)
if len(jumps) == 1:
return jumps[0]
else:
return None
def name_func_called_at(bv: bn.BinaryView, addr, desired_name):
this_func = bv.get_functions_containing(addr)[0]
for (toks, ins_addr) in this_func.instructions:
if ins_addr == addr:
break
else:
raise RuntimeError(f'no instruction at address {addr:#x}')
if toks[0].text not in ['call', 'jmp', 'push', 'mov']:
raise RuntimeError(f'instruction at {addr:#x} is not a call, jmp, or push')
called_addr = int(toks[-1].text[2:], 16)
called_func = bv.get_functions_containing(called_addr)[0]
jump_ins = get_stub_target_jump_ins(bv, called_func)
if jump_ins:
desired_name += '__stub'
if any(func.name == desired_name for func in bv.functions):
raise RuntimeError(f'function with name {repr(desired_name)} already exists')
bv.define_user_symbol(bn.Symbol(bn.SymbolType.FunctionSymbol, called_addr, desired_name))
if jump_ins:
name_func_called_at(bv, jump_ins, desired_name[:-len('__stub')])
ConvertableToGame = str | int | Game
GamesSpec = str | ConvertableToGame | list[ConvertableToGame] | tuple[ConvertableToGame, ...] | None
def parse_games(game: GamesSpec) -> list[Game]:
if game is None:
return ALL_GAMES
if isinstance(game, (list, tuple)):
return list(map(Game, game))
if isinstance(game, str):
if ',' in game:
return list(map(Game, game.split(',')))
if ':' in game:
lo, hi = map(Game, game.split(':', 1))
return [g for g in ALL_GAMES if lo <= g <= hi]
if isinstance(game, (str, int, Game)):
return [Game(game)]
raise TypeError(f'cannot interpret {type(game)} as game spec')
def iter_all_game_bndb_paths(games: GamesSpec):
config = Config.read_system()
for game in parse_games(games):
version = GAME_VERSIONS[game]
yield config.bndb_dir / f'{game}.{version}.bndb'
def rename_type_in_all_games(old, new, games: GamesSpec = None):
if old.startswith('z') and new.startswith('z'):
old_prefix = old[1:]
new_prefix = new[1:]
else:
old_prefix = old
new_prefix = new
for bndb_path in iter_all_game_bndb_paths(games):
print(bndb_path)
with open_bv(bndb_path) as bv:
rename_type_in_funcs(bv, old_prefix, new_prefix)
if bv.get_type_by_name(old) is not None:
bv.rename_type(old, new)
bv.save_auto_snapshot()
def rename_fields_in_all_games(struct_name, renames: tp.Iterable[tuple[str, str]], games: GamesSpec = None):
for bndb_path in iter_all_game_bndb_paths(games):
print(bndb_path)
with open_bv(bndb_path) as bv:
if bv.get_type_by_name(struct_name) is not None:
change_occurred = False
with recording_undo(bv) as rec:
for (old, new) in renames:
this_change_occurred = struct_rename_member(bv, struct_name, old, new, missing_ok=True)
change_occurred = change_occurred or this_change_occurred
if change_occurred:
bv.save_auto_snapshot()
def rename_type_in_funcs(bv: bn.BinaryView, old, new):
rename_func_prefix(bv, f'{old}::', f'{new}::')
def rename_func_prefix(bv: bn.BinaryView, old_prefix, new_prefix):
with recording_undo(bv) as rec:
for func in bv.functions:
if func.name.startswith(old_prefix):
suffix = func.name[len(old_prefix):]
new_name = new_prefix + suffix
bv.define_user_symbol(bn.Symbol(bn.SymbolType.FunctionSymbol, func.start, new_name))
rec.enable_auto_rollback()
def fix_vtable_method_names(bv: bn.BinaryView, addr, type_name=None):
datavar = bv.get_data_var_at(addr)
start = datavar.address
ty = datavar.type
if isinstance(ty, bn.StructureType):
structure = ty
elif isinstance(ty, bn.NamedTypeReferenceType):
structure = bv.get_type_by_id(ty.type_id)
else:
log.log_error(f'address {addr} is not inside a vtable struct')
def get_type_name():
# gather from first method
symbol = bv.get_symbol_at(read_u32(bv, start))
if not symbol:
log.log_error(f'no symbol defined at {addr}')
return None
if symbol.type != bn.SymbolType.FunctionSymbol:
log.log_error(f'{addr} is not a function')
return None
if '::' not in symbol.name:
log.log_error(f'The first function in the VTable must have an obvious type name, e.g. "SomeStruct::do_a_thing". (got {repr(symbol.name)})')
return None
return symbol.name.split('::')[0]
if type_name is None:
type_name = get_type_name()
if not type_name:
return
for member in structure.members:
method_name = member.name.split('(')[0] # remove parameter list if any
desired_name = f'{type_name}::{method_name}'
function_address = read_u32(bv, start + member.offset)
clashing_symbol = bv.get_symbol_by_raw_name(desired_name)
if clashing_symbol and clashing_symbol.address != function_address:
log.log_error(f'A symbol already exists named {repr(desired_name)}! Skipping...')
continue
bv.define_user_symbol(bn.Symbol(bn.SymbolType.FunctionSymbol, function_address, desired_name))
#bn.PluginCommand.register_for_address('Convert to single-precision float', 'Set the type at this location to a float', convert_to_float)
bn.PluginCommand.register_for_address('Fix VTable method names', 'Given an address anywhere inside a VTable in static memory, rename the referenced functions after the vtable struct fields.', fix_vtable_method_names)
bn.PluginCommand.register_for_address('Name initialize method', 'Name initialize method', name_initialize_method_at)
bn.PluginCommand.register_for_address('Name constructor method', 'Name constructor method', name_constructor_method_at)
bn.PluginCommand.register_for_address('Name destructor method', 'Name destructor method', name_destructor_method_at)
bn.PluginCommand.register_for_address('Name on_tick method', 'Name on_tick method', name_on_tick_method_at)
bn.PluginCommand.register_for_address('Name on_draw method', 'Name on_draw method', name_on_draw_method_at)
bn.PluginCommand.register_for_address('Name on_cleanup method', 'Name on_cleanup method', name_on_cleanup_method_at)
bn.PluginCommand.register_for_address('Name on_registration method', 'Name on_registration method', name_on_registration_method_at)
# ========================================================================
def fill_large_gaps(bv: bn.BinaryView, type_name: str, min_filler_size=0x40, keep=0x20, align=0x10):
struct = bv.get_type_by_name(type_name)
assert isinstance(struct, bn.StructureType)
struct = struct.mutable_copy()
# remove existing fillers
remove_indices = [
index for (index, field) in enumerate(struct.members)
if isinstance(field.type, bn.ArrayType)
and field.type.element_type == bn.Type.char()
and field.name.startswith('__')
]
for index in reversed(remove_indices):
struct.remove(index)
unknown_ranges = [range(struct.width)]
for member in struct.members:
last_range = unknown_ranges.pop()
before = range(last_range.start, member.offset)
after = range(member.offset + member.type.width, last_range.stop)
if before:
unknown_ranges.append(before)
if after:
unknown_ranges.append(after)
for i, r in enumerate(unknown_ranges):
start = r.start + keep
stop = r.stop - keep
if start % align != 0:
start += align - (start % align)
if stop % align != 0:
stop -= stop % align
if stop - start > min_filler_size:
struct.insert(start, bn.Type.array(bn.Type.char(), stop - start), f'__filler_{i:02}')
with recording_undo(bv) as rec:
bv.define_user_type(type_name, struct)
rec.enable_auto_rollback()
repack_name = 'zAnmManager'
def _repack_plugin_callback(bv: bn.BinaryView, addr):
fill_large_gaps(bv, repack_name)
bn.PluginCommand.register_for_address('Repack AnmManagerFields', 'Repack AnmManagerFields', _repack_plugin_callback)
# ========================================================================
_CARD_NAMES = ['Chimata', 'Life', 'Bomb', 'LifeFragment', 'BombFragment', 'Nazrin', 'Ringo', 'Mokou', 'Reimu1', 'Reimu2', 'Marisa1', 'Marisa2', 'Sakuya1', 'Sakuya2', 'Sanae1', 'Sanae2', 'Youmu', 'Alice', 'Cirno', 'Okina', 'Nue', 'Nitori', 'Kanako', 'Eirin', 'Tewi', 'Saki', 'Byakuren', 'Koishi', 'Suwako', 'Aya', 'Keiki', 'Kaguya', 'Mamizou', 'Yuyuko', 'Yachie', 'ShikiEiki', 'Narumi', 'Patchouli', 'Mike', 'Takane', 'Sannyo', 'Yukari', 'Shinmyoumaru', 'Tenshi', 'Clownpiece', 'Miko', 'Remilia', 'Utusho', 'LilyWhite', 'Raiko', 'Sumireko', 'Misumaru', 'Tsukasa', 'Megumu', 'Momoyo', 'Magatama', 'Null']
_CARD_BASE_CLASS_VTABLE = 0x4b6010
def name_card_vtables(bv: bn.BinaryView, jump_addr):
jumptable, _ = read_accessed_jumptable(bv, jump_addr)
with recording_undo(bv) as rec:
for card_id in jumptable:
addr = jumptable[card_id]
card_name = _CARD_NAMES[card_id]
print(card_id, card_name, hex(addr))
class_name = 'Card' + card_name
vtable_name = 'VTABLE_' + _pascal_case_to_snake_case(class_name).upper()
add_label(bv, addr, f'card__case_{card_id}__{card_name}')
for tokens, size in bv.get_basic_blocks_at(addr)[0]:
if size != 6: continue
if not str(tokens[-1]).startswith('0x'): continue
vtable_addr = int(str(tokens[-1]), 16)
if vtable_addr == _CARD_BASE_CLASS_VTABLE: continue
datavar = bv.get_data_var_at(vtable_addr)
if datavar is None: continue
table_type = datavar.type
while isinstance(table_type, bn.NamedTypeReferenceType):
table_type = bv.get_type_by_id(table_type.type_id)
if table_type != bv.get_type_by_name('zVTableCard'): continue
name_symbol(bv, vtable_addr, vtable_name)
rec.enable_auto_rollback()
fix_vtable_method_names(bv, vtable_addr, class_name)
break
else:
print(f'no vtable found for {card_id}')
fix_vtable_method_names(bv, _CARD_BASE_CLASS_VTABLE, 'CardBaseClass')
def _pascal_case_to_snake_case(name):
import re
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()