// Ghidra headless: decompile CHÍNH XÁC các offset chỉ định trong build-info (không cần full analysis).
// Args: <out_file> <offset_hex> ...
// VD: DecompileTargets.java out.txt 0x4680 0x6364 ...
import ghidra.app.script.GhidraScript;
import ghidra.app.decompiler.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.address.*;
import ghidra.program.model.mem.*;
import ghidra.app.cmd.function.CreateFunctionCmd;
import java.io.*;
import java.util.*;

public class DecompileTargets extends GhidraScript {

    @Override
    public void run() throws Exception {
        String[] args = getScriptArgs();
        if (args.length < 2) { println("usage: <out> <offset_hex> ..."); return; }
        int timeoutSec = 600;
        String outPath = args[0];

        Address textBase = null;
        for (MemoryBlock b : currentProgram.getMemory().getBlocks()) {
            if ("__TEXT".equals(b.getName())) { textBase = b.getStart(); break; }
        }
        if (textBase == null) textBase = currentProgram.getImageBase();
        println("textBase = " + textBase);

        FunctionManager fm = currentProgram.getFunctionManager();
        DecompInterface di = new DecompInterface();
        DecompileOptions opts = new DecompileOptions();
        di.setOptions(opts);
        di.openProgram(currentProgram);

        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(outPath), "UTF-8")));

        LinkedHashMap<Long, Function> work = new LinkedHashMap<>();
        for (int i = 1; i < args.length; i++) {
            long off = Long.parseLong(args[i].trim().replace("0x", "").replace("0X", ""), 16);
            Address a = textBase.add(off);
            Function f = fm.getFunctionAt(a);
            if (f == null) {
                CreateFunctionCmd cmd = new CreateFunctionCmd(a);
                boolean ok = cmd.applyTo(currentProgram, monitor);
                f = fm.getFunctionAt(a);
                println("target 0x" + Long.toHexString(off) + ": createFunction ok=" + ok +
                    (f != null ? (" name=" + f.getName() + " size=" + f.getBody().getNumAddresses()) : " NO-FUNC"));
            } else {
                println("target 0x" + Long.toHexString(off) + ": existing " + f.getName() +
                    " size=" + f.getBody().getNumAddresses());
            }
            if (f != null) work.put(off, f);
        }

        for (Map.Entry<Long, Function> e : work.entrySet()) {
            long off = e.getKey();
            Function f = e.getValue();
            if (monitor.isCancelled()) break;
            try {
                DecompileResults res = di.decompileFunction(f, timeoutSec, monitor);
                pw.println("//==== offset 0x" + Long.toHexString(off) + "  " + f.getName() +
                    "  size=" + f.getBody().getNumAddresses());
                if (res != null && res.decompileCompleted()) {
                    pw.println(res.getDecompiledFunction().getC());
                } else {
                    pw.println("// DECOMPILE FAILED: " + (res == null ? "null" : res.getErrorMessage()));
                }
                pw.flush();
            } catch (Exception ex) {
                pw.println("// EXCEPTION on 0x" + Long.toHexString(off) + ": " + ex);
                pw.flush();
            }
        }
        pw.close();
        di.dispose();
        println("DONE -> " + outPath);
    }
}
