Initial public release: dockerized reverse-engineering workbench

ChipBench packages Ghidra, radare2, binwalk, chip-programming tools,
simulators, and firmware-unpacking utilities into one reproducible container
for analyzing raw chip dumps entirely from the command line or an AI CLI.
Headless Jython scripts drive import, forced-disassembly sweeps, live
queries, and bulk decompilation exports without any GUI.

Derived from a private engagement environment, generalized for public
release under AGPLv3. No engagement-specific artifacts are included.

💘 Generated with Crush

Assisted-by: Crush:glm-5.2
This commit is contained in:
2026-08-18 11:15:05 -05:00
commit 1b447b77ad
28 changed files with 1860 additions and 0 deletions
+166
View File
@@ -0,0 +1,166 @@
# syntax=docker/dockerfile:1
#
# ChipBench — self-contained reverse-engineering environment for 8-bit
# (and small embedded) chip dumps. Bundles: Ghidra 11.3.2 + GhidraMCP 1.4,
# radare2, binwalk v3, binutils for several targets, sdcc, gputils,
# capstone/unicorn/keystone, plus a firmware-hacker toolset (flashrom,
# avrdude, openocd, srecord, simavr, unpacking tools, serial consoles).
# Optional VNC/noVNC desktop so the Ghidra GUI also runs headlessly.
#
# Nothing runs as root; runtime user is mapped to host uid/gid so
# bind-mounted artifacts keep their owner.
#
# This project is AGPLv3 (see LICENSE). It builds tooling from public
# sources; no binaries are hosted by the project.
# ---- Stage 1: build binwalk v3 (Rust) in an isolated builder ----------------
FROM rust:1-slim-bookworm AS binwalk-builder
RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config libfontconfig1-dev ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN cargo install --root /out --version 3.1.0 binwalk
# ---- Stage 2: main image ----------------------------------------------------
ARG BUILD_UID=1001
ARG BUILD_GID=1001
FROM ubuntu:24.04
# ARGs above do not cross FROM boundaries; re-declare for this stage
# (overridable at build time: --build-arg BUILD_UID=$(id -u) etc.)
ARG BUILD_UID
ARG BUILD_GID
ENV DEBIAN_FRONTEND=noninteractive \
TZ=UTC \
LANG=C.UTF-8 \
LC_ALL=C.UTF-8 \
DISPLAY=:0 \
JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 \
GHIDRA_HOME=/opt/ghidra \
GHIDRAMCP_HOME=/opt/ghidramcp \
VENV_HOME=/opt/venv \
GHIDRA_SCRIPTS=/opt/ghidra-scripts \
PATH="${JAVA_HOME}/bin:/opt/ghidra:/opt/ghidra/support:/opt/venv/bin:/usr/local/bin:${PATH}"
# -----------------------------------------------------------------------------
# 1. System packages
# - GUI/VNC stack (optional desktop for the Ghidra GUI)
# - core RE CLI: radare2, binutils-multiarch, binutils-avr, sdcc, gputils
# - chip-programming & debug: flashrom, avrdude, openocd, stlink-tools
# - EPROM/SREC/HEX wrangling: srecord
# - simulators: simavr (AVR), gpsim (PIC)
# - firmware-unpacking: binwalk deps (7z, cabextract, lzma, cpio, squashfs,
# unar), u-boot-tools (mkimage), device-tree-compiler (dtc)
# - serial: tio, picocom
# - misc: esptool, z80dasm, vbindiff
# NOTE: openjdk-21-jdk is UNPINNED — in-process javac for Ghidra .java
# user scripts has broken before on point-release drift. The supported
# script path here is Jython (.py); the .java helper scripts are not shipped.
# -----------------------------------------------------------------------------
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates wget git unzip xz-utils \
openjdk-21-jdk \
xvfb x11vnc fluxbox supervisor \
novnc websockify \
xterm dbus-x11 \
libfontconfig1 fonts-dejavu-core \
python3 python3-venv python3-pip \
file xxd hexyl binutils \
binutils-avr \
binutils-multiarch \
gputils \
sdcc \
radare2 \
net-tools iproute2 procps less vim-tiny \
flashrom avrdude openocd stlink-tools \
srecord \
simavr gpsim \
z80dasm \
squashfs-tools p7zip-full cabextract lzma cpio unar \
u-boot-tools device-tree-compiler \
tio picocom \
esptool \
vbindiff \
&& rm -rf /var/lib/apt/lists/*
# binwalk v3 binary (Rust) from the builder stage.
COPY --from=binwalk-builder /out/bin/binwalk /usr/local/bin/binwalk
# -----------------------------------------------------------------------------
# 2. Ghidra 11.3.2 (pinned: latest version the GhidraMCP plugin supports)
# -----------------------------------------------------------------------------
ARG GHIDRA_VERSION=11.3.2
ARG GHIDRA_ZIP=ghidra_11.3.2_PUBLIC_20250415.zip
ARG GHIDRA_URL=https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_11.3.2_build/${GHIDRA_ZIP}
ARG GHIDRA_SHA256=99d45035bdcc3d6627e7b1232b7b379905a9fad76c772c920602e2b5d8b2dac2
RUN cd /tmp \
&& wget -q -O ghidra.zip "${GHIDRA_URL}" \
&& echo "${GHIDRA_SHA256} ghidra.zip" | sha256sum -c - \
&& unzip -q ghidra.zip -d /opt \
&& rm -f ghidra.zip \
&& mv /opt/ghidra_* "${GHIDRA_HOME}"
# -----------------------------------------------------------------------------
# 3. GhidraMCP 1.4 plugin (optional REST server inside the Ghidra GUI).
# The GitHub release ships a NESTED zip; unpack both layers.
# (Harmless "Module manifest file error" warnings at headless startup are
# known noise from this plugin's manifest formatting.)
# -----------------------------------------------------------------------------
ARG GHIDRAMCP_VERSION=1.4
ARG GHIDRAMCP_ZIP=GhidraMCP-release-1-4.zip
ARG GHIDRAMCP_URL=https://github.com/LaurieWired/GhidraMCP/releases/download/${GHIDRAMCP_VERSION}/${GHIDRAMCP_ZIP}
ARG GHIDRAMCP_SHA256=b81ca5240fdde57ea4e899170dcd9fdee6ed29246280c74263a509bfcfc7e734
RUN cd /tmp \
&& wget -q -O mcp-outer.zip "${GHIDRAMCP_URL}" \
&& echo "${GHIDRAMCP_SHA256} mcp-outer.zip" | sha256sum -c - \
&& mkdir -p outer && unzip -q mcp-outer.zip -d outer \
&& inner_zip="$(find outer -name 'GhidraMCP-*.zip' | head -n1)" \
&& test -n "$inner_zip" \
&& mkdir -p inner && unzip -q "$inner_zip" -d inner \
&& extdir="$(dirname "$(find inner -name extension.properties | head -n1)")" \
&& test -n "$extdir" \
&& mkdir -p "${GHIDRA_HOME}/Ghidra/Extensions" \
&& cp -r "$extdir" "${GHIDRA_HOME}/Ghidra/Extensions/GhidraMCP" \
&& rm -rf /tmp/*
ARG BRIDGE_URL=https://raw.githubusercontent.com/LaurieWired/GhidraMCP/1.4/bridge_mcp_ghidra.py
# Non-fatal: the MCP bridge is optional (GUI-only convenience). GitHub raw
# occasionally rate-limits (429); retries + a warning keep builds reproducible.
RUN mkdir -p "${GHIDRAMCP_HOME}" \
&& ( wget -q --tries=3 --timeout=30 -O "${GHIDRAMCP_HOME}/bridge_mcp_ghidra.py" "${BRIDGE_URL}" \
|| echo "[warn] GhidraMCP bridge download failed; GUI MCP bridge disabled (headless workflow unaffected)" )
# -----------------------------------------------------------------------------
# 4. Python tooling (isolated venv; respects PEP 668)
# -----------------------------------------------------------------------------
RUN python3 -m venv "${VENV_HOME}" \
&& "${VENV_HOME}/bin/pip" install --no-cache-dir --upgrade pip \
&& "${VENV_HOME}/bin/pip" install --no-cache-dir \
"mcp==1.5.0" "requests==2.32.3" "pyserial>=3.5" \
capstone unicorn \
&& ( "${VENV_HOME}/bin/pip" install --no-cache-dir keystone-engine \
|| echo "[warn] keystone-engine unavailable on this platform; skipping (non-fatal)" )
# -----------------------------------------------------------------------------
# 5. Runtime user matching host uid/gid (no root needed at runtime)
# -----------------------------------------------------------------------------
RUN groupadd -g "${BUILD_GID}" chip \
&& useradd -m -u "${BUILD_UID}" -g "${BUILD_GID}" -s /bin/bash chip
COPY scripts/ghidra-scripts/ "${GHIDRA_SCRIPTS}/"
COPY conf/supervisord.conf /opt/conf/supervisord.conf
COPY conf/profile.d/chipbench.sh /etc/profile.d/chipbench.sh
COPY scripts/entrypoint.sh /opt/entrypoint.sh
RUN chmod +x /opt/entrypoint.sh \
&& chown -R chip:chip "${GHIDRA_SCRIPTS}" /opt/entrypoint.sh /opt/conf
USER chip:chip
WORKDIR /data
EXPOSE 5900 6080 8081
ENTRYPOINT ["/opt/entrypoint.sh"]
CMD ["supervisor"]
+13
View File
@@ -0,0 +1,13 @@
# chipbench shell setup
# Prepend the isolated Python venv so `python3` resolves to the interpreter
# that has capstone / unicorn / mcp installed.
case ":${PATH}:" in
*":/opt/venv/bin:"*) ;;
*) export PATH="/opt/venv/bin:${PATH}" ;;
esac
# Helpful banner once per login shell.
if [ -n "${BASH_VERSION:-}" ] && [ -z "${CHIPREV_BANNER:-}" ]; then
export CHIPREV_BANNER=1
printf '\n chipbench RE shell — try: re-identify, re-analyze, re-binwalk (host) or\n r2 / ghidraRun / binwalk / python3 (here). Artifacts: /data/artifacts (ro)\n Project: /data/work Output: /data/output\n\n'
fi
+74
View File
@@ -0,0 +1,74 @@
[supervisord]
nodaemon=true
user=chip
logfile=/data/work/supervisord.log
pidfile=/tmp/supervisord.pid
childlogdir=/data/work
loglevel=info
; Control socket in a chip-writable location so `supervisorctl status`
; works from inside the container (supervisord runs as non-root uid 1001).
[unix_http_server]
file=/tmp/supervisor.sock
chmod=0700
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///tmp/supervisor.sock
[program:xvfb]
command=/usr/bin/Xvfb :0 -screen 0 1920x1080x24 -ac +extension RANDR
autorestart=true
priority=10
stdout_logfile=/data/work/xvfb.log
stderr_logfile=/data/work/xvfb.err
[program:fluxbox]
command=/usr/bin/fluxbox
environment=DISPLAY=":0",HOME="/home/chip"
autorestart=true
priority=20
stdout_logfile=/data/work/fluxbox.log
stderr_logfile=/data/work/fluxbox.err
[program:x11vnc]
command=/usr/bin/x11vnc -display :0 -forever -shared -noxdamage -rfbauth /home/chip/.vnc/passwd -rfbport 5900
autorestart=true
priority=30
stdout_logfile=/data/work/x11vnc.log
stderr_logfile=/data/work/x11vnc.err
[program:novnc]
command=/usr/bin/websockify --web /usr/share/novnc/ 6080 localhost:5900
autorestart=true
priority=40
stdout_logfile=/data/work/novnc.log
stderr_logfile=/data/work/novnc.err
[program:ghidra]
; GUI project manager. Open the chip dump from here; the GhidraMCP plugin
; starts its REST server on 127.0.0.1:8080 once the CodeBrowser tool loads.
; NOTE: the `ghidraRun` wrapper hardcodes launch.sh "bg" mode, which daemonizes
; the JVM and exits 0 -- supervisor would then respawn it forever. So we call
; launch.sh "fg" directly so the JVM runs in the foreground and is tracked.
; We first wait for the X server to avoid an AWT connect race.
command=bash -c 'for i in {1..60}; do [ -e /tmp/.X11-unix/X0 ] && break; sleep 0.5; done; exec /opt/ghidra/support/launch.sh fg jdk Ghidra "" "" ghidra.GhidraRun'
directory=/data/work
environment=DISPLAY=":0",HOME="/home/chip"
autorestart=true
startsecs=10
startretries=3
priority=50
stdout_logfile=/data/work/ghidra.log
stderr_logfile=/data/work/ghidra.err
[program:mcp-bridge]
; MCP-over-SSE bridge to the GhidraMCP REST API (reachable from host on 8081).
command=/opt/venv/bin/python /opt/ghidramcp/bridge_mcp_ghidra.py --transport sse --mcp-host 0.0.0.0 --mcp-port 8081 --ghidra-server http://127.0.0.1:8080/
autorestart=true
startsecs=3
priority=60
stdout_logfile=/data/work/mcp-bridge.log
stderr_logfile=/data/work/mcp-bridge.err
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Container entrypoint. Two modes:
# - default ("supervisor"): launch the desktop + Ghidra + MCP bridge
# - anything else: exec the given command (used by `docker compose run` for
# headless analysis, interactive shells, etc.)
set -euo pipefail
# Ensure the Ghidra project / output trees exist and are writable by our user.
mkdir -p /data/work /data/output /home/chip/.vnc
# (Re)create the VNC password file from $VNC_PASSWORD (default: chiprev).
VNC_PASSWORD="${VNC_PASSWORD:-chiprev}"
if [ ! -f /home/chip/.vnc/passwd ]; then
x11vnc -storepasswd "${VNC_PASSWORD}" /home/chip/.vnc/passwd >/dev/null 2>&1
fi
if [ "${1:-}" = "supervisor" ] || [ "$#" -eq 0 ]; then
exec /usr/bin/supervisord -c /opt/conf/supervisord.conf
fi
# Pass-through: headless analyze, shell, one-off tools, etc.
exec "$@"
@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*-
#
# Part of ChipBench (AGPLv3). SPDX-FileCopyrightText: 2026 Starting Line Productions LLC
# Analyze8051.py -- force-disassemble a raw 8051 binary and re-run analysis.
# Raw binary imports leave no entry points, so Ghidra finds 0 functions.
# This script disassembles from the reset + interrupt vectors, re-analyzes,
# then sweeps remaining undefined bytes in populated code regions.
from ghidra.app.cmd.disassemble import DisassembleCommand
from ghidra.program.model.address import AddressSet
from ghidra.app.plugin.core.analysis import AutoAnalysisManager
prog = currentProgram
codeSpace = prog.getAddressFactory().getAddressSpace("CODE")
if codeSpace is None:
codeSpace = prog.getAddressFactory().getDefaultAddressSpace()
def A(x):
return codeSpace.getAddress(x)
# 8051 interrupt vectors (standard set; enhanced variants may extend)
vectors = [0x0000, 0x0003, 0x000B, 0x0013, 0x001B, 0x0023, 0x002B, 0x0033, 0x003B]
for v in vectors:
cmd = DisassembleCommand(A(v), None, True)
cmd.applyTo(prog, monitor)
instr = prog.getListing().getNumInstructions()
print("After vector disassembly:", instr, "instructions")
mgr = AutoAnalysisManager.getAnalysisManager(prog)
mgr.reAnalyzeAll(None)
mgr.startAnalysis(monitor)
instr = prog.getListing().getNumInstructions()
funcs = prog.getFunctionManager().getFunctionCount()
print("After analysis:", instr, "instructions,", funcs, "functions")
# Sweep remaining undefined bytes in all populated regions, 1KB at a time.
# String islands (0x9250-0x9F00, 0xEF00-0xF400) stay data; the rest is code.
listing = prog.getListing()
memory = prog.getMemory()
SKIP = set(range(0x9200, 0x9F00, 0x400)) | set(range(0xEE00, 0x10000, 0x400))
for base in range(0x0000, 0xF400, 0x400):
if base in SKIP:
continue
blk = memory.getBlock(A(base))
if blk is None:
continue
# skip fully-erased ranges
erased = True
for i in range(base, base + 0x400, 32):
b = memory.getByte(A(i))
if (b & 0xFF) != 0xFF:
erased = False
break
if erased:
continue
rng = AddressSet(A(base), A(min(base + 0x3FF, 0xF3FF)))
sweep = DisassembleCommand(A(base), rng, True)
sweep.applyTo(prog, monitor)
mgr.reAnalyzeAll(None)
mgr.startAnalysis(monitor)
instr = prog.getListing().getNumInstructions()
funcs = prog.getFunctionManager().getFunctionCount()
print("Final:", instr, "instructions,", funcs, "functions")
@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
#
# Part of ChipBench (AGPLv3). SPDX-FileCopyrightText: 2026 Starting Line Productions LLC
# AutoFuncs.py -- create functions at every LCALL/LJMP target + scheduler
# jumptable entries, iterating until stable. Handles call tables (JMP @A+DPTR)
# where the table entries are LJMPs by treating table bodies as code.
from ghidra.program.model.address import AddressSet
from ghidra.app.cmd.function import CreateFunctionCmd
from ghidra.app.cmd.disassemble import DisassembleCommand
from ghidra.app.plugin.core.analysis import AutoAnalysisManager
prog = currentProgram
af = prog.getAddressFactory()
cs = af.getDefaultAddressSpace()
fm = prog.getFunctionManager()
mem = prog.getMemory()
def A(x): return cs.getAddress(x)
def mk(a):
if a < 0x10000 and fm.getFunctionAt(a) is None:
CreateFunctionCmd(a).applyTo(prog, monitor)
rounds = 0
prev = -1
while rounds < 4:
n = 0
for i in range(0x0000, 0xEE00):
try:
b = mem.getByte(A(i)) & 0xFF
except:
continue
if b == 0x12 or b == 0x02: # LCALL/LJMP
try:
hi = mem.getByte(A(i+1)) & 0xFF
lo = mem.getByte(A(i+2)) & 0xFF
except:
continue
t = (hi << 8) | lo
if 0x0008 <= t < 0xEE00:
if fm.getFunctionAt(A(t)) is None:
if CreateFunctionCmd(A(t)).applyTo(prog, monitor):
n += 1
# reanalyze
mgr = AutoAnalysisManager.getAnalysisManager(prog)
mgr.reAnalyzeAll(None)
mgr.startAnalysis(monitor)
cur = fm.getFunctionCount()
print("round %d: +%d new, total %d" % (rounds, n, cur))
if cur == prev:
break
prev = cur
rounds += 1
print("AutoFuncs done: %d functions, %d instructions" % (
fm.getFunctionCount(), prog.getListing().getNumInstructions()))
@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
#
# Part of ChipBench (AGPLv3). SPDX-FileCopyrightText: 2026 Starting Line Productions LLC
# ExportAll.py -- Jython bulk export (no javac needed).
# Produces <prog>.functions.txt, .strings.txt, .segments.txt, .decompiled.c
import os
from ghidra.app.decompiler import DecompInterface
from ghidra.app.decompiler import DecompileOptions
outdir = os.environ.get("DECOMPILE_OUT", "/data/output")
prog = currentProgram
name = prog.getName()
fm = prog.getFunctionManager()
rm = prog.getReferenceManager()
print("ExportAll.py -> %s" % outdir)
# functions
with open(os.path.join(outdir, name + ".functions.txt"), "w") as fh:
for f in fm.getFunctions(True):
fh.write("%s @ %s\n" % (f.getName(), f.getEntryPoint()))
print("functions: %d" % fm.getFunctionCount())
# segments
with open(os.path.join(outdir, name + ".segments.txt"), "w") as fh:
for b in prog.getMemory().getBlocks():
fh.write("%s %s-%s %d %s%s\n" % (b.getName(), b.getStart(), b.getEnd(),
b.getSize(), "R" if b.isRead() else "-", "W" if b.isWrite() else "-"))
# strings (defined string data)
with open(os.path.join(outdir, name + ".strings.txt"), "w") as fh:
di = prog.getDataTypeManager()
listing = prog.getListing()
it = listing.getDefinedData(True)
n = 0
while it.hasNext():
d = it.next()
dt = d.getDataType()
if dt is not None and ("string" in dt.getName().lower() or "char" in dt.getName().lower()):
try:
v = d.getValue()
except:
v = None
if v is not None and len(str(v)) >= 3:
fh.write("%s: %r\n" % (d.getAddress(), str(v)))
n += 1
print("strings: %d" % n)
# decompile everything
ifc = DecompInterface()
ifc.setOptions(DecompileOptions())
ifc.openProgram(prog)
nf = 0
with open(os.path.join(outdir, name + ".decompiled.c"), "w") as fh:
fh.write("// Decompiled by ExportAll.py (Ghidra %s)\n" % "11.3.2")
for f in fm.getFunctions(True):
res = ifc.decompileFunction(f, 90, monitor)
if res.decompileCompleted():
fh.write("\n/* ==== %s @ %s ==== */\n" % (f.getName(), f.getEntryPoint()))
fh.write(res.getDecompiledFunction().getC())
nf += 1
else:
fh.write("\n/* ==== %s @ %s : DECOMPILE FAILED ==== */\n" % (f.getName(), f.getEntryPoint()))
ifc.dispose()
print("decompiled: %d" % nf)
print("ExportAll.py done")
@@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
#
# Part of ChipBench (AGPLv3). SPDX-FileCopyrightText: 2026 Starting Line Productions LLC
# MakeFuncs.py -- create functions at hex addresses given as script args.
# Usage: -postScript MakeFuncs.py 0x1234 0x0a07 ...
from ghidra.program.model.address import AddressSet
from ghidra.app.cmd.function import CreateFunctionCmd
args = getScriptArgs()
af = currentProgram.getAddressFactory()
fm = currentProgram.getFunctionManager()
for a in args:
addr = af.getAddress(a[2:] if a.startswith("0x") else a)
if addr is None:
print("bad addr: %s" % a); continue
if fm.getFunctionAt(addr) is not None:
print("exists: %s" % addr); continue
cmd = CreateFunctionCmd(addr)
ok = cmd.applyTo(currentProgram, monitor)
print("create %s -> %s" % (addr, ok))
print("MakeFuncs done")
+291
View File
@@ -0,0 +1,291 @@
# -*- coding: utf-8 -*-
#
# Part of ChipBench (AGPLv3). SPDX-FileCopyrightText: 2026 Starting Line Productions LLC
# Query.py -- headless query interface for chat-driven reverse engineering.
# Usage:
# analyzeHeadless <projDir> <proj> -process <prog> -noanalysis -readOnly \
# -scriptPath <dir> -postScript Query.py <command> [args...]
#
# Commands: info, funcs, decompile, disasm, xrefs-to, xrefs-from,
# func-xrefs, strings, segments, data, search, func, mem
from ghidra.app.decompiler import DecompInterface
import jarray
args = getScriptArgs()
if len(args) == 0:
print("Usage: Query.py <command> [args...]")
print("Commands: info, funcs, decompile, disasm, xrefs-to, xrefs-from,")
print(" func-xrefs, strings, segments, data, search, func, mem")
else:
cmd = args[0]
rest = args[1:]
fm = currentProgram.getFunctionManager()
rm = currentProgram.getReferenceManager()
mem = currentProgram.getMemory()
af = currentProgram.getAddressFactory()
def arg(i, default):
if i >= len(rest):
return default
try:
return int(rest[i])
except ValueError:
return default
def parseAddr(s):
try:
return af.getAddress(s)
except:
return None
def resolveFunc(s):
a = parseAddr(s)
if a is not None:
f = fm.getFunctionAt(a)
if f is None:
f = fm.getFunctionContaining(a)
if f is not None:
return f
for f in fm.getFunctions(True):
if f.getName() == s:
return f
return None
if cmd == "info":
print("Name: " + currentProgram.getName())
print("Language: " + str(currentProgram.getLanguageID()))
print("Compiler: " + str(currentProgram.getCompilerSpec().getCompilerSpecID()))
print("Executable: " + str(currentProgram.getExecutablePath()))
print("ImageBase: " + str(currentProgram.getImageBase()))
print("Size: " + str(mem.getSize()) + " bytes")
print("Functions: " + str(fm.getFunctionCount()))
print("Segments:")
for b in mem.getBlocks():
r = "R" if b.isRead() else "-"
w = "W" if b.isWrite() else "-"
x = "X" if b.isExecute() else "-"
print(" " + b.getName() + " " + str(b.getStart()) + "-" + str(b.getEnd()) + " (" + str(b.getSize()) + "B) " + r + w + x)
elif cmd == "funcs":
off = arg(0, 0)
lim = arg(1, 200)
flt = rest[2] if len(rest) > 2 else None
i = 0
shown = 0
for f in fm.getFunctions(True):
if flt is not None and flt.lower() not in f.getName().lower():
continue
if i < off:
i += 1
continue
if shown >= lim:
break
print(f.getName() + " @ " + str(f.getEntryPoint()))
shown += 1
i += 1
print("--- " + str(shown) + " shown (offset " + str(off) + ") ---")
elif cmd == "decompile":
if len(rest) < 1:
print("decompile needs a name or address")
else:
f = resolveFunc(rest[0])
if f is None:
print("No function found for: " + rest[0])
else:
d = DecompInterface()
d.openProgram(currentProgram)
r = d.decompileFunction(f, 60, monitor)
if r is not None and r.decompileCompleted():
for line in r.getDecompiledFunction().getC().split("\n"):
print(line)
else:
print("Decompilation failed")
d.dispose()
elif cmd == "disasm":
if len(rest) < 1:
print("disasm needs an address")
else:
f = resolveFunc(rest[0])
if f is None:
print("No function at/containing: " + rest[0])
else:
end = f.getBody().getMaxAddress()
listing = currentProgram.getListing()
it = listing.getInstructions(f.getEntryPoint(), True)
from ghidra.program.model.listing import CodeUnit
while it.hasNext():
ins = it.next()
if ins.getAddress().compareTo(end) > 0:
break
cmt = listing.getComment(CodeUnit.EOL_COMMENT, ins.getAddress())
line = str(ins.getAddress()) + ": " + ins.toString()
if cmt is not None:
line += " ; " + cmt
print(line)
elif cmd == "xrefs-to":
if len(rest) < 1:
print("xrefs-to needs an address")
else:
lim = arg(1, 200)
a = parseAddr(rest[0])
if a is None:
print("Bad address: " + rest[0])
else:
n = 0
it = rm.getReferencesTo(a)
while it.hasNext():
if n >= lim:
break
ref = it.next()
ff = fm.getFunctionContaining(ref.getFromAddress())
extra = " in " + ff.getName() if ff is not None else ""
print("From " + str(ref.getFromAddress()) + extra + " [" + ref.getReferenceType().getName() + "]")
n += 1
print("--- " + str(n) + " reference(s) to " + str(a) + " ---")
elif cmd == "xrefs-from":
if len(rest) < 1:
print("xrefs-from needs an address")
else:
lim = arg(1, 200)
a = parseAddr(rest[0])
if a is None:
print("Bad address: " + rest[0])
else:
refs = rm.getReferencesFrom(a)
n = 0
for ref in refs:
if n >= lim:
break
tf = fm.getFunctionAt(ref.getToAddress())
extra = " (" + tf.getName() + ")" if tf is not None else ""
print("To " + str(ref.getToAddress()) + extra + " [" + ref.getReferenceType().getName() + "]")
n += 1
print("--- " + str(n) + " reference(s) from " + str(a) + " ---")
elif cmd == "func-xrefs":
if len(rest) < 1:
print("func-xrefs needs a function name")
else:
lim = arg(1, 200)
total = 0
for f in fm.getFunctions(True):
if f.getName() != rest[0]:
continue
it = rm.getReferencesTo(f.getEntryPoint())
while it.hasNext():
if total >= lim:
break
ref = it.next()
ff = fm.getFunctionContaining(ref.getFromAddress())
extra = " in " + ff.getName() if ff is not None else ""
print("From " + str(ref.getFromAddress()) + extra + " [" + ref.getReferenceType().getName() + "]")
total += 1
print("--- " + str(total) + " reference(s) to function '" + rest[0] + "' ---")
elif cmd == "strings":
flt = rest[0] if len(rest) > 0 else None
lim = arg(1, 500)
shown = 0
it = currentProgram.getListing().getDefinedData(True)
while it.hasNext() and shown < lim:
d = it.next()
tn = d.getDataType().getName().lower()
if "string" not in tn and "char" not in tn and tn != "unicode":
continue
v = str(d.getValue()) if d.getValue() is not None else ""
if flt is not None and flt.lower() not in v.lower():
continue
print(str(d.getAddress()) + ": \"" + v[:120] + "\"")
shown += 1
print("--- " + str(shown) + " string(s) ---")
elif cmd == "segments":
for b in mem.getBlocks():
print(b.getName() + ": " + str(b.getStart()) + " - " + str(b.getEnd()) + " (" + str(b.getSize()) + " bytes)")
elif cmd == "data":
off = arg(0, 0)
lim = arg(1, 200)
i = 0
shown = 0
for b in mem.getBlocks():
it = currentProgram.getListing().getDefinedData(b.getStart(), True)
while it.hasNext():
d = it.next()
if not b.contains(d.getAddress()):
break
if i < off:
i += 1
continue
if shown >= lim:
break
lbl = d.getLabel() if d.getLabel() is not None else "(unnamed)"
print(str(d.getAddress()) + ": " + lbl + " = " + d.getDefaultValueRepresentation())
shown += 1
i += 1
print("--- " + str(shown) + " data item(s) ---")
elif cmd == "search":
if len(rest) < 1:
print("search needs a query")
else:
lim = arg(1, 200)
shown = 0
for f in fm.getFunctions(True):
if rest[0].lower() in f.getName().lower():
if shown >= lim:
break
print(f.getName() + " @ " + str(f.getEntryPoint()))
shown += 1
print("--- " + str(shown) + " match(es) ---")
elif cmd == "func":
if len(rest) < 1:
print("func needs an address")
else:
f = resolveFunc(rest[0])
if f is None:
print("No function at/containing: " + rest[0])
else:
print("Name: " + f.getName())
print("Entry: " + str(f.getEntryPoint()))
print("Signature: " + f.getSignature())
print("Body: " + str(f.getBody().getMinAddress()) + " - " + str(f.getBody().getMaxAddress()))
print("Size: " + str(f.getBody().getNumAddresses()) + " bytes")
elif cmd == "mem":
if len(rest) < 2:
print("mem needs <addr> <len>")
else:
a = parseAddr(rest[0])
length = arg(1, 64)
if a is None:
print("Bad address: " + rest[0])
else:
buf = jarray.zeros(length, "b")
got = mem.getBytes(a, buf)
ubuf = [(x & 0xFF) for x in buf[:got]]
hexstr = ""
ascstr = ""
for idx in range(got):
v = ubuf[idx]
hexstr += "%02x " % v
ascstr += chr(v) if (32 <= v < 127) else "."
if (idx + 1) % 16 == 0:
base = a.add(idx - 15)
print("%s %-48s %s" % (base, hexstr, ascstr))
hexstr = ""
ascstr = ""
if hexstr:
print("%s %-48s %s" % (a, hexstr, ascstr))
else:
print("Unknown command: " + cmd)
print("Commands: info, funcs, decompile, disasm, xrefs-to, xrefs-from,")
print(" func-xrefs, strings, segments, data, search, func, mem")