2022-01-07 21:04:07 -05:00
|
|
|
import logging
|
2022-03-13 13:33:19 -04:00
|
|
|
from coreapp import compilers
|
|
|
|
|
|
|
|
|
|
from coreapp.compilers import Compiler
|
|
|
|
|
|
2022-01-07 21:04:07 -05:00
|
|
|
from coreapp.m2c_wrapper import M2CError, M2CWrapper
|
2022-03-13 13:33:19 -04:00
|
|
|
from coreapp.platforms import Platform
|
2022-01-07 21:04:07 -05:00
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2022-10-29 13:41:52 +09:00
|
|
|
MAX_M2C_ASM_LINES = 15000
|
|
|
|
|
|
2024-03-26 06:52:45 +00:00
|
|
|
DECOMP_WITH_CONTEXT_FAILED_PREAMBLE = "/* Decompilation with context failed; here's the decompilation without context: */\n"
|
2024-03-10 22:54:35 +09:00
|
|
|
|
2022-01-07 21:04:07 -05:00
|
|
|
|
|
|
|
|
class DecompilerWrapper:
|
|
|
|
|
@staticmethod
|
2022-02-20 09:21:38 -05:00
|
|
|
def decompile(
|
2022-03-13 13:33:19 -04:00
|
|
|
default_source_code: str,
|
|
|
|
|
platform: Platform,
|
|
|
|
|
asm: str,
|
|
|
|
|
context: str,
|
|
|
|
|
compiler: Compiler,
|
2022-02-20 09:21:38 -05:00
|
|
|
) -> str:
|
2022-03-13 13:33:19 -04:00
|
|
|
if compiler == compilers.DUMMY:
|
2022-01-07 21:04:07 -05:00
|
|
|
return f"decompiled({asm})"
|
|
|
|
|
|
|
|
|
|
ret = default_source_code
|
2024-02-15 14:17:26 +00:00
|
|
|
if platform.arch in ["mips", "mipsee", "mipsel", "mipsel:4000", "ppc"]:
|
2022-10-29 13:41:52 +09:00
|
|
|
if len(asm.splitlines()) > MAX_M2C_ASM_LINES:
|
|
|
|
|
return "/* Too many lines to decompile; please run m2c manually */"
|
2022-01-07 21:04:07 -05:00
|
|
|
try:
|
2023-01-20 18:04:27 +00:00
|
|
|
ret = M2CWrapper.decompile(asm, context, compiler, platform.arch)
|
2022-01-07 21:04:07 -05:00
|
|
|
except M2CError as e:
|
2024-03-10 22:54:35 +09:00
|
|
|
# Attempt to decompile the source without context as a last-ditch effort
|
|
|
|
|
try:
|
|
|
|
|
ret = M2CWrapper.decompile(asm, "", compiler, platform.arch)
|
2024-03-26 06:52:45 +00:00
|
|
|
ret = f"{e}\n{DECOMP_WITH_CONTEXT_FAILED_PREAMBLE}\n{ret}"
|
2024-03-10 22:54:35 +09:00
|
|
|
except M2CError as e:
|
|
|
|
|
ret = f"{e}\n{default_source_code}"
|
2022-01-07 21:04:07 -05:00
|
|
|
except Exception:
|
2022-06-01 23:06:51 -04:00
|
|
|
logger.exception("Error running m2c")
|
|
|
|
|
ret = f"/* Internal error while running m2c */\n{default_source_code}"
|
2022-01-07 21:04:07 -05:00
|
|
|
else:
|
2022-03-13 13:33:19 -04:00
|
|
|
ret = f"/* No decompiler yet implemented for {platform.arch} */\n{default_source_code}"
|
2022-01-07 21:04:07 -05:00
|
|
|
|
|
|
|
|
return ret
|