#!/usr/bin/env python3
# ghidra_fast.py - import KHONG auto-analysis, tu disassemble + tao function + decompile
# Usage: python ghidra_fast.py <binary> <out.txt> <addr_hex> [addr_hex ...]
import os, sys

os.environ.setdefault("GHIDRA_INSTALL_DIR",
                      r"E:\ios\zsign-windows-x64\ghidra_12.2_PUBLIC_20261016\ghidra_12.2_PUBLIC")
os.environ.setdefault("APPDATA", os.path.expandvars(r"%USERPROFILE%\AppData\Roaming"))

import pyghidra
pyghidra.start(verbose=False)

def main():
    binary = os.path.abspath(sys.argv[1])
    outpath = os.path.abspath(sys.argv[2])
    addrs = [int(a, 16) for a in sys.argv[3:]]
    proj = os.path.abspath("analysis/ghidra_proj_fast")
    os.makedirs(proj, exist_ok=True)
    name = os.path.splitext(os.path.basename(binary))[0]

    with pyghidra.open_program(binary, proj, name + "_fast", analyze=False, program_name=name) as flat:
        program = flat.getCurrentProgram()
        from ghidra.app.cmd.disassemble import DisassembleCommand
        from ghidra.app.cmd.function import CreateFunctionCmd
        from ghidra.app.decompiler import DecompInterface, DecompileOptions
        from ghidra.util.task import ConsoleTaskMonitor

        monitor = ConsoleTaskMonitor()
        fm = program.getFunctionManager()
        listing = program.getListing()
        af = program.getAddressFactory().getDefaultAddressSpace()

        # 1) disassemble + create function cho tung dia chi (window 0x600)
        for a in addrs:
            addr = af.getAddress(a)
            if listing.getInstructionAt(addr) is None:
                cmd = DisassembleCommand(addr, None, True)
                cmd.applyTo(program, monitor)
            f = fm.getFunctionContaining(addr) or fm.getFunctionAt(addr)
            if f is None:
                CreateFunctionCmd(addr).applyTo(program, monitor)

        # 2) name cac stub import (decompiler hien ten symbol neu co)
        di = DecompInterface()
        di.setOptions(DecompileOptions())
        di.openProgram(program)

        fh = open(outpath, "w", encoding="utf-8")
        for a in addrs:
            addr = af.getAddress(a)
            f = fm.getFunctionContaining(addr) or fm.getFunctionAt(addr)
            if f is None:
                fh.write(f"\n=== {a:#x}: khong tao duoc function ===\n")
                continue
            fh.write(f"\n{'='*100}\n=== FUNCTION {f.getName()} @ {f.getEntryPoint().getOffset():#x}"
                     f"  body {f.getBody().getMinAddress()}-{f.getBody().getMaxAddress()}\n")
            try:
                callees = [c.getName() + "@" + hex(c.getEntryPoint().getOffset())
                           for c in f.getCalledFunctions(monitor)]
                fh.write("callees: " + ", ".join(callees[:80]) + "\n")
            except Exception as e:
                fh.write(f"callees err: {e}\n")
            res = di.decompileFunction(f, 180, monitor)
            if res.decompileCompleted():
                fh.write(res.getDecompiledFunction().getC())
            else:
                fh.write("// decompile failed: %s\n" % res.getErrorMessage())
            fh.write("\n")
        fh.close()
        di.dispose()
    print("[ghidra_fast] done ->", outpath, flush=True)

if __name__ == "__main__":
    main()
