sotn-decomp/tools/m2ctx.py

80 lines
2.0 KiB
Python
Raw Normal View History

2022-10-15 10:18:32 +00:00
#!/usr/bin/env python3
import argparse
import os
import sys
import subprocess
import tempfile
2023-09-19 22:24:03 +00:00
script_dir = os.path.dirname(os.path.realpath(__file__))
root_dir = os.path.abspath(os.path.join(script_dir, ".."))
2022-10-15 10:18:32 +00:00
src_dir = root_dir + "src/"
# Project-specific
CPP_FLAGS = [
"-Iinclude",
"-Isrc",
"-Iver/current/build/include",
"-D_LANGUAGE_C",
"-DF3DEX_GBI_2",
"-D_MIPS_SZLONG=32",
"-DSCRIPT(...)={}",
2023-09-19 22:24:03 +00:00
"-D__attribute__(...)=",
2022-10-15 10:18:32 +00:00
"-D__asm__(...)=",
"-ffreestanding",
"-DM2CTX",
]
2023-09-19 22:25:08 +00:00
2023-09-19 22:24:03 +00:00
def import_c_file(in_file) -> str:
in_file = os.path.relpath(in_file, root_dir)
2022-10-15 10:18:32 +00:00
cpp_command = ["gcc", "-E", "-P", "-dM", *CPP_FLAGS, in_file]
cpp_command2 = ["gcc", "-E", "-P", *CPP_FLAGS, in_file]
with tempfile.NamedTemporaryFile(suffix=".c") as tmp:
2023-09-19 22:25:08 +00:00
stock_macros = subprocess.check_output(
["gcc", "-E", "-P", "-dM", tmp.name], cwd=root_dir, encoding="utf-8"
)
2022-10-15 10:18:32 +00:00
out_text = ""
try:
2023-07-25 17:38:30 +00:00
out_text += subprocess.check_output(cpp_command, cwd=root_dir, encoding="utf-8")
2023-09-19 22:25:08 +00:00
out_text += subprocess.check_output(
cpp_command2, cwd=root_dir, encoding="utf-8"
)
2022-10-15 10:18:32 +00:00
except subprocess.CalledProcessError:
print(
"Failed to preprocess input file, when running command:\n"
2023-09-19 22:25:08 +00:00
+ " ".join(cpp_command),
2022-10-15 10:18:32 +00:00
file=sys.stderr,
2023-09-19 22:25:08 +00:00
)
2022-10-15 10:18:32 +00:00
sys.exit(1)
if not out_text:
print("Output is empty - aborting")
sys.exit(1)
for line in stock_macros.strip().splitlines():
out_text = out_text.replace(line + "\n", "")
return out_text
2023-09-19 22:25:08 +00:00
2022-10-15 10:18:32 +00:00
def main():
parser = argparse.ArgumentParser(
2023-09-19 22:24:03 +00:00
description="""Create a context file which can be used for m2c / decomp.me"""
2022-10-15 10:18:32 +00:00
)
parser.add_argument(
"c_file",
help="""File from which to create context""",
)
args = parser.parse_args()
output = import_c_file(args.c_file)
with open(os.path.join(root_dir, "ctx.c"), "w", encoding="UTF-8") as f:
f.write(output)
if __name__ == "__main__":
main()