diff --git a/decompile.sh b/decompile.sh index 9e7c053..0e0a2fa 100755 --- a/decompile.sh +++ b/decompile.sh @@ -1,13 +1,22 @@ #!/bin/bash -# Usage: decompile.sh [--live|--asm] QUERY [MAX] +# Usage: decompile.sh [--live|--asm] QUERY [MAX] | decompile.sh --case CASEADDR... # QUERY = entry/inner address (0x6c0f30 / 006c0f30) or a regex on the qualified name (grep -E). # Default reads the pre-dumped corpus dump/all.c (instant, concurrency-safe). # --asm ADDR [N] prints N (default 20) instructions from ADDR (for functions the decompiler times out on). +# --case decompiles single switch cases of a function the decompiler times out on (Entity_Effect::Update): each +# CASEADDR is a jump-table target; the switch is patched to jump straight there in a throwaway copy (DecompileCase.java). # --live runs the Ghidra decompiler on a copy of the saved project (~25s; env DECOMP_TIMEOUT=secs, default 180). D="$(cd "$(dirname "$0")" && pwd)" LIVE=0; SCRIPT=Decompile.java [ "$1" = --live ] && { LIVE=1; shift; } [ "$1" = --asm ] && { LIVE=1; SCRIPT=Disasm.java; shift; } +if [ "$1" = --case ]; then + shift; TMP=$(mktemp -d); export JAVA_HOME="$D/jdk" + cp -r "$D/project" "$TMP/project"; rm -f "$TMP"/project/*.lock* + "$D/ghidra_12.2_PUBLIC/support/analyzeHeadless" "$TMP/project" isaac -process isaac-ng.exe -noanalysis -readOnly \ + -scriptPath "$D/scripts" -postScript DecompileCase.java "$TMP/out.c" "$@" >/dev/null 2>&1 + cat "$TMP/out.c"; rm -rf "$TMP"; exit +fi Q="$1"; MAX="${2:-20}" [ -z "$Q" ] && { sed -n '2,7p' "$0"; exit 1; } if [[ "$Q" =~ ^(0x)?[0-9a-fA-F]{6,8}$ ]]; then diff --git a/scripts/DecompileCase.java b/scripts/DecompileCase.java new file mode 100644 index 0000000..66bc187 --- /dev/null +++ b/scripts/DecompileCase.java @@ -0,0 +1,68 @@ +// Decompile single switch cases of a function too big for the decompiler (Entity_Effect::Update 0x5d4380 times out). +// Args: outfile [label=]caseAddr... Only ever run on a -readOnly project copy (decompile.sh --case): for each case it finds +// the switch's indirect JMP that lists the case among its flows, patches it into a direct JMP to the case, re-flows the +// function body (prologue + that case + whatever it shares, e.g. the common tail) and decompiles that. +import ghidra.app.script.GhidraScript; +import ghidra.app.decompiler.*; +import ghidra.app.cmd.function.CreateFunctionCmd; +import ghidra.program.model.address.*; +import ghidra.program.model.listing.*; +import java.io.*; +import java.util.*; + +public class DecompileCase extends GhidraScript { + public void run() throws Exception { + String[] a = getScriptArgs(); + DecompInterface di = new DecompInterface(); + DecompileOptions opts = new DecompileOptions(); + opts.setMaxPayloadMBytes(1024); + di.setOptions(opts); + di.openProgram(currentProgram); + int timeout = Integer.parseInt(System.getenv().getOrDefault("DECOMP_TIMEOUT", "600")); + Map switches = new HashMap<>(); + try (PrintStream o = new PrintStream(new FileOutputStream(a[0]))) { + for (int i = 1; i < a.length; i++) { + Address target = toAddr(Long.parseLong(a[i].replaceAll(".*=|0x", ""), 16)); + Function f = getFunctionContaining(target); + if (f == null) f = getFunctionBefore(target); // Ghidra's body for Update stops short of its cases + Instruction sw = switches.get(f); + if (sw == null) + for (Instruction in : currentProgram.getListing().getInstructions(f.getBody(), true)) + if (in.getFlowType().isJump() && in.getFlowType().isComputed() && lists(in, target)) { sw = in; break; } + if (sw == null) { o.println("//@@ case " + target + ": no switch jump in " + f.getName(true) + " lists it"); continue; } + switches.put(f, sw); + Address jmp = sw.getAddress(); + int size = sw.getLength(); + byte[] b = new byte[size]; + Arrays.fill(b, (byte) 0x90); + b[0] = (byte) 0xe9; + int rel = (int) (target.getOffset() - (jmp.getOffset() + 5)); + for (int k = 0; k < 4; k++) b[1 + k] = (byte) (rel >> (8 * k)); + clearListing(jmp, jmp.add(size - 1)); + setBytes(jmp, b); + disassemble(jmp); + CreateFunctionCmd.fixupFunctionBody(currentProgram, f, monitor); + di.flushCache(); + DecompileResults r = di.decompileFunction(f, timeout, monitor); + String label = a[i].contains("=") ? a[i].split("=")[0] : "0x" + target; + o.println("//@@ " + f.getEntryPoint() + " " + f.getName(true) + "/case_" + label + " (case at " + target + ": switch " + jmp + " patched to jump there)"); + o.println(r.decompileCompleted() ? r.getDecompiledFunction().getC() : "/* failed: " + r.getErrorMessage() + " */"); + o.flush(); + } + } + di.dispose(); + } + + // does this `JMP [reg*4 + table]` list target, by its recovered flows or else by reading the table itself + boolean lists(Instruction in, Address target) throws Exception { + if (Arrays.asList(in.getFlows()).contains(target)) return true; + for (Object op : in.getOpObjects(0)) + if (op instanceof ghidra.program.model.scalar.Scalar && currentProgram.getMemory().contains(toAddr(((ghidra.program.model.scalar.Scalar) op).getUnsignedValue()))) + for (int k = 0; k < 1024; k++) { + Address t = toAddr(getInt(toAddr(((ghidra.program.model.scalar.Scalar) op).getUnsignedValue() + 4L * k)) & 0xffffffffL); + if (t.equals(target)) return true; + if (getFunctionBefore(t) != getFunctionBefore(in.getAddress()) && getFunctionContaining(t) != getFunctionContaining(in.getAddress())) break; + } + return false; + } +}