-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathida-re-export.py
340 lines (266 loc) · 13.2 KB
/
ida-re-export.py
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import idautils
import ida_nalt
import idaapi
import idc
import ida_enum
import ida_struct
import ida_funcs
import ida_typeinf
import ida_kernwin
import ida_bytes
import ida_name
import os
import shutil
from datetime import datetime
# Script used with my IDA database to export/generate generate headers, symbols and wrapper ASM files, all ready for some fun ASM hacking ;)
TAB = " "
def is_thumb_mode(func_ea):
func = idaapi.get_func(func_ea)
if not func:
print(f"No function found at address: 0x{func_ea:X}")
return False
start_ea = func.start_ea
flags = idc.get_sreg(start_ea, "T")
if flags == -1:
print(f"Could not retrieve segment register for address: 0x{start_ea:X}")
return False
return flags == 1
def gen_symbols_x(out_file):
with open(out_file, "w") as f:
for func_ea in idautils.Functions():
func_name = ida_funcs.get_func_name(func_ea)
if is_thumb_mode(func_ea):
func_name += "_from_thumb"
f.write(f"{func_name} = 0x{func_ea:08X};\n")
f.write("\n")
for (ea, name) in idautils.Names():
if name.startswith("g_"):
f.write(f"{name} = 0x{ea:08X};\n")
print(f"Done, exported symbols to '{out_file}'")
BASE_TYPES = [
"int",
"char",
"void",
"__int16",
"__int32",
"__int64",
"u8",
"u16",
"u32",
"u64",
"BOOL",
"_BYTE",
"_WORD",
"_DWORD",
"_QWORD"
]
def export_all_to_header(out_types_header_file, out_syms_header_file, out_aliases_asm_file):
with open(out_types_header_file, "w") as f:
now = datetime.now()
f.write("/* MKDS (EU) ARM9 type definitions */\n")
f.write(f"/* Generated by mkds-re: https://github.com/XorTroll/mkds-re, at {now.strftime('%B %d, %Y %I:%M:%S %p')} */\n\n")
f.write("#ifndef MKDS_RE_TYPES_GEN_H\n")
f.write("#define MKDS_RE_TYPES_GEN_H\n\n")
f.write("/* Basic IDA types and definitions */\n\n")
f.write("#define int16_t short\n")
f.write("#define int32_t int\n")
f.write("#define int64_t long long\n")
f.write("#define uint8_t unsigned char\n")
f.write("#define uint16_t unsigned short\n")
f.write("#define uint32_t unsigned int\n")
f.write("#define uint64_t unsigned long long\n")
f.write("#define u8 uint8_t\n")
f.write("#define u16 uint16_t\n")
f.write("#define u32 uint32_t\n")
f.write("#define u64 uint64_t\n")
f.write("#define i16 int16_t\n")
f.write("#define i32 int32_t\n")
f.write("#define fx16 i16\n")
f.write("#define fx32 i32\n")
f.write("#define _BYTE uint8_t\n")
f.write("#define _WORD int16_t\n")
f.write("#define _DWORD int32_t\n")
f.write("#define _QWORD int64_t\n")
f.write("#define BOOL int\n")
f.write("#define __int8 char\n")
f.write("#define __int16 short\n")
f.write("#define __int32 int\n")
f.write("#define __int64 long long\n")
f.write("#define __cdecl\n")
f.write("#define __fastcall\n")
f.write("#define __usercall\n\n")
f.write("#define __noreturn __attribute__((noreturn))\n\n")
f.write("#define __thumb __attribute__((target(\"thumb\")))\n\n")
f.write("_Static_assert(sizeof(u8) == 1, \"u8 definition\");\n")
f.write("_Static_assert(sizeof(u16) == 2, \"u16 definition\");\n")
f.write("_Static_assert(sizeof(u32) == 4, \"u32 definition\");\n")
f.write("_Static_assert(sizeof(u64) == 8, \"u64 definition\");\n\n")
f.write(f"/* Enums ({ida_enum.get_enum_qty()} total) */\n\n")
for enum_idx in range(ida_enum.get_enum_qty()):
enum = ida_enum.getn_enum(enum_idx)
enum_name = ida_enum.get_enum_name(enum)
f.write(f"enum {enum_name} {{\n")
cur_member_value = ida_enum.get_first_enum_member(enum, 0xffffffff)
last_member_value = ida_enum.get_last_enum_member(enum, 0xffffffff)
while True:
cur_member_id = ida_enum.get_enum_member(enum, cur_member_value, -1, 0xffffffff)
member_name = ida_enum.get_enum_member_name(cur_member_id)
member_value = ida_enum.get_enum_member_value(cur_member_id)
f.write(f"{TAB}{member_name} = {member_value},\n")
if cur_member_value == last_member_value:
break
cur_member_value = ida_enum.get_next_enum_member(enum, cur_member_value, 0xffffffff)
f.write("};\n\n")
done_struct_ids = []
struct_count = len(list(idautils.Structs()))
f.write(f"/* Structs ({struct_count} total) */\n\n")
for (struct_id, struct_sid, struct_name) in idautils.Structs():
struct = ida_struct.get_struc(struct_sid)
if struct is not None:
type_keyword = "union" if struct.is_union() else "struct"
f.write(f"typedef {type_keyword} {struct_name} {struct_name};\n\n")
iter_lim = 0
while len(done_struct_ids) < struct_count:
iter_lim += 1
if iter_lim > 20:
break
# print(f"[{iter_lim}] Remaining structs: {struct_count - len(done_struct_ids)}")
for (struct_id, struct_sid, struct_name) in idautils.Structs():
if struct_id in done_struct_ids:
continue
struct = ida_struct.get_struc(struct_sid)
struct_size = ida_struct.get_struc_size(struct)
can_add = True
try:
for (mem_off, mem_name, mem_size) in idautils.StructMembers(struct_sid):
if not can_add:
break
mem = ida_struct.get_member(struct, mem_off)
mem_id = ida_struct.get_member_id(struct, mem_off)
tinfo = idaapi.tinfo_t()
ida_struct.get_member_tinfo(tinfo, mem)
# Ensure proper type order, only add structs whose field struct types have already been added (unless they are just pointers)
mem_type_base = idaapi.print_tinfo("", 0, 0, ida_typeinf.PRTYPE_1LINE, tinfo, "", "")
mem_type = mem_type_base.split(" ")[0].split("[")[0]
if mem_type in BASE_TYPES:
pass
elif mem_type == struct_name:
pass
elif mem_type_base.endswith(" *"):
pass
else:
for (inner_struct_id, inner_struct_sid, inner_struct_name) in idautils.Structs():
if mem_type == inner_struct_name:
if inner_struct_id not in done_struct_ids:
can_add = False
break
except:
print(f"Issue with {struct_name}...")
if can_add:
if struct is not None:
f.write(f"/* size 0x{struct_size:X} */\n")
is_union = struct.is_union()
type_keyword = "union" if is_union else "struct"
f.write(f"{type_keyword} {struct_name} {{\n")
try:
for (mem_off, mem_name, mem_size) in idautils.StructMembers(struct_sid):
mem = ida_struct.get_member(struct, mem_off)
mem_id = ida_struct.get_member_id(struct, mem_off)
tinfo = idaapi.tinfo_t()
ida_struct.get_member_tinfo(tinfo, mem)
mem_fmt = idaapi.print_tinfo("", 0, 0, ida_typeinf.PRTYPE_1LINE, tinfo, mem_name, "")
f.write(f"{TAB}/* off 0x{mem_off:X} size 0x{mem_size:X} */\n")
f.write(f"{TAB}{mem_fmt};\n\n")
except:
print(f"Other issue with {struct_name}...")
f.write(f"}} __attribute__((packed));\n")
if not is_union:
f.write(f"_Static_assert(sizeof({struct_name}) == 0x{struct_size:X}, \"{struct_name} definition\");\n\n")
else:
print(f"Issue with {struct_name}...")
done_struct_ids.append(struct_id)
else:
# print(f"Cannot add {struct_name}...")
pass
if struct_count > len(done_struct_ids):
f.write(f"/* (failed struct types: {struct_count - len(done_struct_ids)}) */\n\n")
f.write("#endif // MKDS_RE_TYPES_GEN_H\n")
print(f"Done, exported types header to '{out_types_header_file}'")
with open(out_syms_header_file, "w") as f:
with open(out_aliases_asm_file, "w") as asm_f:
time_fmt = now.strftime('%B %d, %Y %I:%M:%S %p')
f.write("/* MKDS (EU) ARM9 function/symbol definitions */\n")
f.write(f"/* Generated by mkds-re: https://github.com/XorTroll/mkds-re, at {time_fmt} */\n\n")
asm_f.write("@ MKDS (EU) ARM9 function ARM <-> Thumb wrappers\n")
asm_f.write(f"@ Generated by mkds-re: https://github.com/XorTroll/mkds-re, at {time_fmt} */\n\n")
asm_f.write(".macro BEGIN_ASM_FN name section=text\n")
asm_f.write(f"{TAB}.section .\\section\\().\\name\\(), \"ax\", %progbits\n")
asm_f.write(f"{TAB}.global \\name\n")
asm_f.write(f"{TAB}.type \\name, %function\n")
asm_f.write(f"{TAB}.align 2\n")
asm_f.write(f"\\name:\n")
asm_f.write(f".endm\n\n")
f.write("#ifndef MKDS_RE_SYMS_GEN_H\n")
f.write("#define MKDS_RE_SYMS_GEN_H\n\n")
f.write(f"#include \"{os.path.basename(out_types_header_file)}\"\n\n")
f.write(f"/* Global objects */\n\n")
for (ea, name) in idautils.Names():
if name.startswith("g_"):
type = ida_typeinf.tinfo_t()
ida_nalt.get_tinfo(type, ea)
expr = ida_typeinf.print_tinfo("", 0, 0, ida_typeinf.PRTYPE_1LINE, type, name, "")
if expr is not None:
f.write(f"/* off 0x{ea:08X} */\n")
f.write(f"extern {expr};\n\n")
func_count = len(list(idautils.Functions()))
f.write(f"/* Functions ({func_count} total) */\n\n")
for func_ea in idautils.Functions():
func = ida_funcs.get_func(func_ea)
if func is None:
print(f"Function not found at address 0x{func_ea:08X}")
continue
func_type = ida_typeinf.tinfo_t()
if not ida_nalt.get_tinfo(func_type, func.start_ea):
print(f"Function signature not found for function at address 0x{func_ea:08X}")
continue
function_name = ida_funcs.get_func_name(func_ea)
func_sig = ida_typeinf.print_tinfo("", 0, 0, ida_typeinf.PRTYPE_1LINE, func_type, function_name, "")
thumb_function_name = f"{function_name}_from_thumb"
thumb_func_sig = ida_typeinf.print_tinfo("", 0, 0, ida_typeinf.PRTYPE_1LINE, func_type, thumb_function_name, "")
is_thumb = is_thumb_mode(func_ea)
mode = "[THUMB]" if is_thumb else "[ARM]"
f.write(f"/* off 0x{func_ea:08X} {mode} */\n")
if is_thumb:
f.write(f"{thumb_func_sig} __thumb;\n")
else:
f.write(f"{func_sig};\n")
if is_thumb:
asm_f.write(f"BEGIN_ASM_FN {function_name}\n")
asm_f.write(f"{TAB}ldr r12, ={thumb_function_name}\n")
asm_f.write(f"{TAB}orr r12, r12, #1\n")
asm_f.write(f"{TAB}bx r12\n")
asm_f.write(f"\n")
f.write(f"/* off 0x{func_ea:08X} [THUMB, ARM ASM wrapper] */\n")
f.write(f"{func_sig};\n")
f.write("\n")
f.write("#endif // MKDS_RE_SYMS_GEN_H\n")
print(f"Done, exported symbols header to '{out_syms_header_file}' and ASM wrappers to '{out_aliases_asm_file}'")
script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)
gen_dir = os.path.join(script_dir, "re-export")
if os.path.exists(gen_dir):
shutil.rmtree(gen_dir, ignore_errors=True)
os.mkdir(gen_dir)
print(f"Gen dir: {gen_dir}")
symbols_x_path = os.path.join(gen_dir, "mkds-eu-symbols.x")
gen_symbols_x(symbols_x_path)
include_dir = os.path.join(gen_dir, "include")
if not os.path.exists(include_dir):
os.mkdir(include_dir)
source_dir = os.path.join(gen_dir, "source")
if not os.path.exists(source_dir):
os.mkdir(source_dir)
types_header_path = os.path.join(include_dir, "mkds-eu-types.h")
syms_header_path = os.path.join(include_dir, "mkds-eu.h")
aliases_asm_path = os.path.join(source_dir, "mkds-eu-thumb-wrappers.s")
export_all_to_header(types_header_path, syms_header_path, aliases_asm_path)