// Ghidra headless script: decompile functions of interest in bshield
import ghidra.app.script.GhidraScript;
import ghidra.app.decompiler.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
import ghidra.program.model.address.*;
import java.io.*;
import java.util.*;

public class ExportKeyFunctions extends GhidraScript {

    private static final String[] KW_STRINGS = {
        "executablePath", "infoDictionary", "pathForResource", "dataWithContentsOfFile",
        "bundlePath", "privateFrameworksPath", "processInfo", "environment",
        "bundleIdentifier", "systemVersion", "identifierForVendor",
        "mobileprovision", "embedded", "jailbreak", "frida", "cydia", "substrate",
        "codeSign", "codesign", "CS_",
        "AppStore", "receipt", "sandbox"
    };

    private static final String[] KW_CODE = {
        "sysctl", "getenv", "exit(", "abort(", "signal(", "ptrace",
        "readlink", "fopen", "open(", "stat(", "lstat(", "fork(",
        "task_", "host_", "proc_", "csops", "sandbox", "dladdr", "dyld",
        "kill(", "unlink(", "access(", "fcntl", "mmap"
    };

    @Override
    public void run() throws Exception {
        String[] args = getScriptArgs();
        String outPath = args.length > 0 ? args[0] : "C:\\temp\\bshield_key.txt";
        String listPath = args.length > 1 ? args[1] : "C:\\temp\\bshield_func_list.txt";

        Set<Address> targets = new HashSet<>();
        ReferenceManager rm = currentProgram.getReferenceManager();
        FunctionManager fm = currentProgram.getFunctionManager();

        // 0) explicit hex addresses passed as extra args (e.g. registry 0x452260)
        for (int i = 2; i < args.length; i++) {
            String a = args[i].trim();
            if (a.startsWith("0x") || a.startsWith("0X")) {
                try {
                    Address addr = currentProgram.getAddressFactory().getAddress(a);
                    Function f = fm.getFunctionAt(addr);
                    if (f == null) f = fm.getFunctionContaining(addr);
                    if (f != null) { targets.add(f.getEntryPoint()); println("explicit target: " + f.getName() + " @ " + f.getEntryPoint()); }
                    else { targets.add(addr); println("explicit raw address: " + addr); }
                } catch (Exception e) { println("bad address arg: " + a); }
            }
        }

        // 1) references to external import symbols of interest
        SymbolTable st = currentProgram.getSymbolTable();
        Set<String> extNames = new HashSet<>(Arrays.asList(
            "exit", "abort", "sysctl", "sysctlbyname", "getenv", "signal", "ptrace",
            "readlink", "fopen", "open", "stat", "lstat", "fork", "kill", "task_info",
            "proc_info", "csops", "csops_audittoken", "sandbox_check", "dladdr",
            "unlink", "access", "mmap", "getentropy", "syscall", "task_threads",
            "mach_port", "host_info", "proc_listpids", "cs_blob_get"));
        SymbolIterator all = st.getAllSymbols(true);
        for (Symbol s : all) {
            String n = s.getName();
            String base = n.startsWith("_") ? n.substring(1) : n;
            if (extNames.contains(base)) {
                for (Reference r : rm.getReferencesTo(s.getAddress())) {
                    Function f = fm.getFunctionContaining(r.getFromAddress());
                    if (f != null) targets.add(f.getEntryPoint());
                }
            }
        }
        println("functions referencing imports: " + targets.size());

        // 2) references to interesting strings (selectors / names)
        for (Data d : currentProgram.getListing().getDefinedData(true)) {
            if (!(d.hasStringValue())) continue;
            String v = (String) d.getValue();
            boolean hit = false;
            for (String k : KW_STRINGS) {
                if (v.contains(k)) { hit = true; break; }
            }
            if (!hit) continue;
            for (Reference r : rm.getReferencesTo(d.getAddress())) {
                Function f = fm.getFunctionContaining(r.getFromAddress());
                if (f != null) { targets.add(f.getEntryPoint()); continue; }
                // second hop: string -> selref -> code
                for (Reference r2 : rm.getReferencesTo(r.getFromAddress())) {
                    Function f2 = fm.getFunctionContaining(r2.getFromAddress());
                    if (f2 != null) targets.add(f2.getEntryPoint());
                }
            }
        }
        println("targets after string pass: " + targets.size());

        // 3) add callers (1 level)
        Set<Address> withCallers = new HashSet<>(targets);
        for (Address a : targets) {
            Function f = fm.getFunctionAt(a);
            if (f == null) continue;
            try {
                for (Function c : f.getCallingFunctions(monitor)) {
                    withCallers.add(c.getEntryPoint());
                }
            } catch (Exception e) { }
        }
        println("targets with callers: " + withCallers.size());

        // 4) ShieldLoader / Function* named functions
        for (Function f : fm.getFunctions(true)) {
            String n = f.getName().toLowerCase();
            if (n.contains("shield") || n.contains("loadshield") || n.contains("initshield")) {
                withCallers.add(f.getEntryPoint());
            }
        }
        println("final targets: " + withCallers.size());

        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")));
        PrintWriter pl = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(listPath), "UTF-8")));

        for (Function f : fm.getFunctions(true)) {
            pl.println(f.getEntryPoint() + "  " + f.getName() + "  size=" + f.getBody().getNumAddresses());
        }
        pl.close();

        int done = 0;
        for (Address a : withCallers) {
            Function f = fm.getFunctionAt(a);
            if (f == null) f = fm.getFunctionContaining(a);
            if (f == null) continue;
            if (monitor.isCancelled()) break;
            DecompileResults res = di.decompileFunction(f, 120, monitor);
            if (!res.decompileCompleted()) {
                pw.println("//==== " + f.getName() + " @ " + a + " : DECOMPILE FAILED");
                continue;
            }
            pw.println("//==== " + f.getName() + " @ " + a + " size=" + f.getBody().getNumAddresses());
            pw.println(res.getDecompiledFunction().getC());
            done++;
        }
        pw.close();
        di.dispose();
        println("decompiled " + done + " functions -> " + outPath);
    }
}
