forked from ACreTeam/ac-decomp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
426 lines (352 loc) · 10.5 KB
/
common.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"""
Common functions & definitions
"""
from dataclasses import dataclass
from enum import Enum
from hashlib import sha1
import json
import os
from subprocess import PIPE, run
from sys import executable as PYTHON, platform
from typing import List, Tuple, Union
import yaml
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
#############
# Functions #
#############
def get_file_sha1(path: str) -> bytes:
"""Gets the SHA1 hash of a file"""
with open(path, 'rb') as f:
return sha1(f.read()).digest()
def get_cmd_stdout(cmd: str, text=True) -> str:
"""Run a command and get the stdout output as a string"""
ret = run(cmd.split(), stdout=PIPE, text=text)
assert ret.returncode == 0, f"Command '{cmd}' returned {ret.returncode}"
return ret.stdout
class Binary(Enum):
DOL = 1
REL = 2
# ppcdis source output
SourceDesc = Union[str, Tuple[str, int, int]]
def get_containing_slice(addr: int) -> Tuple[Binary, SourceDesc]:
"""Finds the binary containing an address and its source file
Source file is empty string if not decompiled"""
dol_raw = get_cmd_stdout(f"{SLICES} {DOL_YML} {DOL_SLICES} -p {DOL_SRCDIR}/ --containing {addr:x}")
containing = json.loads(dol_raw)
if containing is None:
rel_raw = get_cmd_stdout(
f"{SLICES} {REL_YML} {REL_SLICES} -p {REL_SRCDIR}/ --containing {addr:x}"
)
containing = json.loads(rel_raw)
assert containing is not None, f"Unknown address {addr:x}"
return (Binary.REL, containing)
else:
return (Binary.DOL, containing)
def lookup_sym(sym: str, dol: bool = False, rel: bool = False, source_name: str = None) -> int:
"""Takes a symbol as a name or address and returns the address"""
# Get binary
if dol:
binary_name = DOL_YML
elif rel:
binary_name = REL_YML
else:
binary_name = None
# Determine type
try:
return int(sym, 16)
except ValueError:
return get_address(sym, binary_name, source_name)
def lookup_sym_full(sym: str, dol: bool = False, rel: bool = False, source_name: str = None
) -> int:
"""Takes a symbol as a name or address and returns both the name and address"""
# Get binary
if dol:
binary_name = DOL_YML
elif rel:
binary_name = REL_YML
else:
binary_name = None
# Determine type
try:
return int(sym, 16), get_name(sym)
except ValueError:
return get_address(sym, binary_name, source_name), sym
def get_address(name: str, binary: bool = None, source_name: bool = None) -> int:
"""Finds the address of a symbol"""
args = [name]
if binary is not None:
args.append(f"-b {binary}")
if source_name is not None:
args.append(f"-n {source_name}")
raw = get_cmd_stdout(f"{SYMBOLS} {GAME_SYMBOLS} --get-addr {' '.join(args)}")
return json.loads(raw)
def get_name(addr: int, binary: bool = None, source_name: bool = None) -> int:
"""Finds the name of a symbol"""
args = [addr]
if binary is not None:
args.append(f"-b {binary}")
if source_name is not None:
args.append(f"-n {source_name}")
raw = get_cmd_stdout(f"{SYMBOLS} {GAME_SYMBOLS} --get-name {' '.join(args)}")
return json.loads(raw)
def find_headers(dirname: str, base=None) -> List[str]:
"""Returns a list of all headers in a folder recursively"""
if base is None:
base = dirname
ret = []
for name in os.listdir(dirname):
path = dirname + '/' + name
if os.path.isdir(path):
ret.extend(find_headers(path, base))
elif name.endswith('.h'):
ret.append(path[len(base)+1:])
return ret
def load_from_yaml(path: str, default=None):
"""Loads an object from a yaml file"""
if default is None:
default = {}
with open(path) as f:
ret = yaml.load(f.read(), Loader)
if ret is None:
ret = default
return ret
################
# Project dirs #
################
# Directory for decompiled dol code
DOL_SRCDIR = "src"
# Directory for decompiled rel code
REL_SRCDIR = "rel"
# Include directory
INCDIR = "include"
# Build artifacts directory
BUILDDIR = "build"
# Build include directory
BUILD_INCDIR = f"{BUILDDIR}/include"
# Output binaries directory
OUTDIR = "out"
# Original binaries directory
ORIG = "dump"
# Tools directory
TOOLS = "tools"
# Config directory
CONFIG = "config"
# Extracted assets directory
ASSETS = "assets"
#########
# Tools #
#########
# ppcdis
PPCDIS = "tools/ppcdis"
PPCDIS_INCDIR = f"{PPCDIS}/include"
RELEXTERN = f"{PYTHON} {PPCDIS}/relextern.py"
ANALYSER = f"{PYTHON} {PPCDIS}/analyser.py"
DISASSEMBLER = f"{PYTHON} {PPCDIS}/disassembler.py"
ORDERSTRINGS = f"{PYTHON} {PPCDIS}/orderstrings.py"
ORDERFLOATS = f"{PYTHON} {PPCDIS}/orderfloats.py"
ASSETRIP = f"{PYTHON} {PPCDIS}/assetrip.py"
ASSETINC = f"{PYTHON} {PPCDIS}/assetinc.py"
FORCEACTIVEGEN = f"{PYTHON} {PPCDIS}/forceactivegen.py"
ELF2DOL = f"{PYTHON} {PPCDIS}/elf2dol.py"
ELF2REL = f"{PYTHON} {PPCDIS}/elf2rel.py"
SLICES = f"{PYTHON} {PPCDIS}/slices.py"
PROGRESS = f"{PYTHON} {PPCDIS}/progress.py"
SYMBOLS = f"{PYTHON} {PPCDIS}/symbols.py"
FORCEFILESGEN = f"{PYTHON} {PPCDIS}/forcefilesgen.py"
# Codewarrior
TOOLS = "tools"
CODEWARRIOR = os.path.join(TOOLS, "1.3.2")
SDK_CW = os.path.join(TOOLS, "1.2.5")
HOTFIX_CW = os.path.join(TOOLS, "1.2.5e")
CC = os.path.join(CODEWARRIOR, "mwcceppc.exe")
OCC = os.path.join(SDK_CW, "mwcceppc.exe")
PROFILE = os.path.join(HOTFIX_CW, "mwcceppc.exe")
LD = os.path.join(CODEWARRIOR, "mwldeppc.exe")
if platform != "win32":
CC = f"wibo {CC}"
OCC = f"wibo {OCC}"
PROFILE = f"wibo {PROFILE}"
LD = f"wibo {LD}"
# Frank
FRANKLITE = "tools/franklite.py"
FRANK = "tools/frank.py"
# DevkitPPC
DEVKITPPC = os.environ.get("DEVKITPPC")
AS = os.path.join(DEVKITPPC, "bin", "powerpc-eabi-as")
OBJDUMP = os.path.join(DEVKITPPC, "bin", "powerpc-eabi-objdump")
CPP = os.path.join(DEVKITPPC, "bin", "powerpc-eabi-cpp")
ICONV = f"{PYTHON} tools/sjis.py" # TODO: get actual iconv working(?)
# N64 SDK path for GBI
N64SDK = os.environ.get("N64_SDK")
assert N64SDK != None, "N64_SDK is not defined as a system environment variable"
#########
# Files #
#########
# Slices
DOL_SLICES = f"{CONFIG}/dol_slices.yml"
REL_SLICES = f"{CONFIG}/rel_slices.yml"
# Overrides
ANALYSIS_OVERRIDES = f"{CONFIG}/analysis_overrides.yml"
DOL_DISASM_OVERRIDES = f"{CONFIG}/disasm_overrides.yml"
REL_DISASM_OVERRIDES = f"{CONFIG}/rel_disasm_overrides.yml"
# Binaries
DOL = f"{ORIG}/main.dol" # read in python code
REL = f"{ORIG}/foresta.rel" # read in python code
DOL_YML = f"{CONFIG}/dol.yml"
REL_YML = f"{CONFIG}/rel.yml"
DOL_SHA = f"{ORIG}/main.dol.sha1"
REL_SHA = f"{ORIG}/foresta.rel.sha1"
DOL_OK = f"{BUILDDIR}/main.dol.ok"
REL_OK = f"{BUILDDIR}/foresta.rel.ok"
DOL_ASM_LIST = f"{BUILDDIR}/main.dol.asml"
REL_ASM_LIST = f"{BUILDDIR}/foresta.rel.asml"
# Symbols
GAME_SYMBOLS = f"{CONFIG}/symbols.yml"
# Assets
ASSETS_YML = f"{CONFIG}/assets.yml"
# Analysis outputs
EXTERNS = f"{BUILDDIR}/externs.pickle"
DOL_LABELS = f"{BUILDDIR}/labels.pickle"
DOL_RELOCS = f"{BUILDDIR}/relocs.pickle"
REL_LABELS = f"{BUILDDIR}/rel_labels.pickle"
REL_RELOCS = f"{BUILDDIR}/rel_relocs.pickle"
# Linker
DOL_LCF_TEMPLATE = f"{CONFIG}/dol.lcf"
DOL_LCF_TEMP = f"{BUILDDIR}/dol_temp.lcf"
DOL_LCF = f"{BUILDDIR}/dol.lcf"
REL_LCF = f"{CONFIG}/rel.lcf"
# Outputs
DOL_ELF = f"{BUILDDIR}/main.elf"
REL_PLF = f"{BUILDDIR}/foresta.plf"
DOL_OUT = f"{OUTDIR}/main.dol"
REL_OUT = f"{OUTDIR}/foresta.rel"
DOL_MAP = f"{OUTDIR}/main.map"
REL_MAP = f"{OUTDIR}/foresta.map"
# Optional full disassembly
DOL_FULL = f"{OUTDIR}/dol.s"
REL_FULL = f"{OUTDIR}/rel.s"
##############
# Tool Flags #
##############
ASFLAGS = ' '.join([
"-m gekko",
f"-I {INCDIR}",
f"-I {PPCDIS_INCDIR}",
f"-I orig",
f"-I {N64SDK}/ultra/usr/include"
])
CPPFLAGS = ' '.join([
"-nostdinc",
f"-I {INCDIR}",
f"-I {PPCDIS_INCDIR}",
f"-I {BUILD_INCDIR}",
f"-I {N64SDK}/ultra/usr/include"
])
DOL_SDATA2_SIZE = 8
REL_SDATA2_SIZE = 0
CFLAGS = [
"-O4",
"-char unsigned",
"-fp hard"
]
CPLFLAGS = [
"-lang=c++",
"-O0"
]
COMMON_DEFINES = [
"-d _LANGUAGE_C",
"-d F3DEX_GBI_2"
]
DOL_DEFINES = COMMON_DEFINES + []
REL_DEFINES = COMMON_DEFINES + []
BASE_DOL_CFLAGS = CFLAGS + [
"-inline on",
"-sdata 8",
f"-sdata2 {DOL_SDATA2_SIZE}"
] + DOL_DEFINES
BASE_REL_CFLAGS = CFLAGS + [
"-sdata 0",
f"-sdata2 {REL_SDATA2_SIZE}",
"-pool off"
] + REL_DEFINES
LOCAL_CFLAGS = [
"-nostdinc",
"-proc gekko",
"-maxerrors 1",
"-Cpp_exceptions off",
"-I-",
f"-i {INCDIR}",
f"-i {PPCDIS_INCDIR}",
f"-i {BUILD_INCDIR}",
f"-ir {N64SDK}/ultra/usr/include"
]
PREPROCESSOR_CFLAGS = [
"-E",
"-P"
]
SDK_CFLAG = [
"-O4,p",
"-inline all",
"-sdata 8",
f"-sdata2 {DOL_SDATA2_SIZE}"
]
ALIGN16_CFLAG = [
"-func_align 16",
]
JSYSTEM_BASE = [
"-lang=c++",
"-inline on",
"-fp fmadd",
"-fp_contract on",
#"-pool off", # this is wrong
"-Cpp_exceptions off",
"-RTTI on",
"-char signed",
"-enum int",
"-sym on", # might also be on for base flags?
"-O4,s" # in mkdd some libraries use O4,p, might be the case here too
]
JSYSTEM_CFLAGS = ' '.join(JSYSTEM_BASE + LOCAL_CFLAGS)
DOL_CFLAGS = ' '.join(BASE_DOL_CFLAGS + LOCAL_CFLAGS)
SDK_FLAGS = ' '.join(SDK_CFLAG + LOCAL_CFLAGS)
ALIGN16 = ' '.join(BASE_DOL_CFLAGS + LOCAL_CFLAGS + ALIGN16_CFLAG)
DOL_CPPFLAGS = ' '.join(CPLFLAGS + BASE_DOL_CFLAGS + LOCAL_CFLAGS)
REL_CFLAGS = ' '.join(BASE_REL_CFLAGS + LOCAL_CFLAGS)
EXTERNAL_DOL_CFLAGS = ' '.join(BASE_DOL_CFLAGS)
EXTERNAL_REL_CFLAGS = ' '.join(BASE_REL_CFLAGS)
PREPROCESS_CFLAGS = ' '.join(PREPROCESSOR_CFLAGS)
LDFLAGS = ' '.join([
"-maxerrors 1",
"-mapunused"
])
PPCDIS_ANALYSIS_FLAGS = ' '.join([
f"-o {ANALYSIS_OVERRIDES}",
f"-l {EXTERNS}"
])
############
# Contexts #
############
@dataclass
class SourceContext:
srcdir: str
cflags: str
binary: str
labels: str
relocs: str
slices: str
compiler: str
sdata2_threshold: int
disasm_overrides: int
DOL_CTX = SourceContext(DOL_SRCDIR, DOL_CFLAGS, DOL_YML, DOL_LABELS, DOL_RELOCS, DOL_SLICES,
CC, DOL_SDATA2_SIZE, DOL_DISASM_OVERRIDES)
REL_CTX = SourceContext(REL_SRCDIR, REL_CFLAGS, REL_YML, REL_LABELS, REL_RELOCS, REL_SLICES,
CC, REL_SDATA2_SIZE, REL_DISASM_OVERRIDES)
####################
# diff.py Expected #
####################
EXPECTED = "expected"
DOL_EXPECTED = f"{EXPECTED}/build/main.elf"
REL_EXPECTED = f"{EXPECTED}/build/foresta.plf"