Entry point for ghidrasql sessions: connects to a LibGhidraHost source, verifies access, and routes to the appropriate analysis skill based on user intent.
Ships in ghidrasql. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Entry point for every ghidrasql session. Bootstrap the source, verify the program is bound, then hand off to the right domain skill.
Use this skill when the user wants to:
ghidrasql sessionLibGhidraHostOnce binary and funcs > 0 come back, route by user intent:
| Intent | Skill | First query |
|---|---|---|
| triage / "what does this binary do?" | analysis | SELECT * FROM binary; SELECT name, size FROM funcs ORDER BY size DESC LIMIT 20; |
| disassembly / blocks / CFG | disassembly | SELECT start_addr, end_addr FROM blocks WHERE func_addr = 0xX; |
| callers / callees / call graph / xrefs | xrefs | SELECT * FROM callgraph_edges WHERE src_func_addr = 0xX; |
| find by name pattern | grep | SELECT name, addr FROM funcs WHERE name LIKE '%X%'; |
| strings / bytes / data items / hexdump | data | SELECT * FROM strings WHERE content LIKE '%X%' LIMIT 20; |
| decompile / pseudocode / locals / params | decompiler | SELECT text FROM pseudocode WHERE func_addr = 0xX; |
| ctree / AST patterns | decompiler | SELECT * FROM ctree_v_calls WHERE func_addr = 0xX; |
| low-level P-code / IR / dataflow | decompiler | SELECT seq, op, addr FROM ir_ops WHERE func_addr = 0xX ORDER BY seq; |
| rename / comment / signature / lvars | annotations | READ first, then UPDATE, then re-read; normal shutdown saves |
| struct / enum / typedef / parse C | types | SELECT parse_decls('...'); SELECT * FROM type_members WHERE parent_type_name = 'X'; |
| breakpoints / patch bytes | debugger | SELECT * FROM breakpoints; |
| recursive bottom-up source recovery | re-source | starts with leaf callees and iterates |
| tune Ghidra analyzers / re-run analysis | analysis | SELECT option_key, option_value FROM program_options WHERE option_scope = 'Analyzers' AND settable = 1; |
| runtime knobs / query timeout | connect | SELECT key, value FROM runtime_settings; UPDATE runtime_settings SET value='5000' WHERE key='query_timeout_ms'; |
| SQL helper lookup | functions | reference catalog (no warm-start) |
These five contracts apply across every ghidrasql skill. Skip them at your peril — they prevent the most common failure modes.
Every mutation starts with a SELECT that yields the exact write coordinates. Resolve func_addr, local_id, addr from a query, never from guesswork.
SELECT local_id, name, type FROM decomp_lvars WHERE func_addr = 0x401000;
SELECT func_addr, local_id, name, type FROM decomp_lvars WHERE func_name = 'main';
-- now use the literal local_id from the result, not a guess
Use .tables, .schema <table>, and PRAGMA table_xinfo(<table>) before issuing uncertain queries. ghidrasql exposes 65 public virtual tables, 81 views, and 21 SQL functions — when a query fails, introspect first, then retry.
SELECT type, name, ncol FROM pragma_table_list WHERE schema='main';
PRAGMA table_xinfo('decomp_lvars');
SELECT name, narg FROM pragma_function_list WHERE name LIKE 'search_%';
Read → Write → re-read to verify. Mutations remain in the live Ghidra project;
normal managed shutdown saves once by default. save_database() is an optional
periodic checkpoint, not a per-mutation requirement.
SELECT name, prototype FROM funcs WHERE addr = 0x4011F0; -- read
UPDATE funcs SET name = 'parseConfig' WHERE addr = 0x4011F0; -- write
SELECT name FROM funcs WHERE addr = 0x4011F0; -- verify
For a critical campaign, a shutdown/reopen check is still a useful audit:
-- shut the host down (POST /shutdown for the SQL server, or exit the REPL)
-- reconnect normally in storage mode with --no-analyze
SELECT name FROM funcs WHERE addr = 0xX; -- compare against the post-write value
If changes do not survive a clean save-policy shutdown, or if an explicit
save_database() == 1 checkpoint does not survive reopen, treat that as a
persistence bug: preserve the project and logs, record the
Ghidra/libghidra/GhidraSQL revisions, and stop mutating until the save path is
fixed. Do not normalize silent reversion into a routine re-apply loop.
| Surface | Mandatory predicate | If you skip it |
|---|---|---|
pseudocode, decomp_lvars | WHERE func_addr = X or exact WHERE func_name = 'name' | Decompiles every function. At ~500 ms per function, a binary with thousands of functions takes many minutes per query |
decomp_tokens, decomp_comments | WHERE func_addr = X | Same |
blocks, cfg_edges | WHERE func_addr = X | Per-function CFG built for every function |
instructions | WHERE func_addr = X, exact WHERE addr = X, or a bounded addr range | An unconstrained or mnemonic-only query scans every instruction |
instruction_operands | WHERE func_addr = X or exact WHERE addr = X | A range or unscoped query scans the whole operand table |
xrefs | exact WHERE from_addr = X or to_addr = X | An unscoped read scans every reference; exact points and IN (...) use bounded source lookups |
xref_index | WHERE src_func_addr = X | Reads one function's body references plus the attribution catalog; dst_func_addr alone still scans every reference |
call_edges, callgraph_edges | exact WHERE src_func_addr = X, dst_func_addr = X, dst_addr = X, or call_site = X; call_site IN (...) is a bounded set of exact lookups | Range/non-key predicates or an unscoped read scan the whole call graph |
string_refs | WHERE func_addr = X | Reads that function's body references, the string catalog, and one function record; a string-value pattern alone scans program-wide references |
callers, callees | exact WHERE func_addr = X | Both resolved and raw/unresolved arms are bounded; unscoped reads scan the whole call graph |
data_items | exact addr = X or bounded addr range | Name/type filters or LIMIT alone enumerate all defined data |
leaf_funcs | Native listing, no decompilation | Size/name filters and LIMIT still enumerate functions and their outgoing call references |
bytes | addr = X or range (streamed window) | Streams every mapped byte — bounded memory, but time proportional to the whole image |
comments | exact addr = X | A range or unscoped query scans the whole comment table |
pseudocode/decomp_lvars/blocks/cfg_edges/instructions/instruction_operands push the function filter (func_addr) into the source — without it, you trigger work proportional to the whole program. For pseudocode and decomp_lvars, exact func_name = ... is also pushed down. instructions pushes exact addresses and bounded address ranges; instruction_operands pushes exact addresses. Exact src_func_addr, dst_func_addr, and call_site equality pushes through call_edges and callgraph_edges; SQLite evaluates call_site IN (...) as one exact lookup per value. Exact func_addr equality bounds both arms of callers and callees, including raw/unresolved destinations. Exact dst_addr on callgraph_edges also bounds incoming calls to a raw target. Keep those predicates visible rather than forcing a materialized wrapper. disasm_calls is another call-site view. A mnemonic-only instruction predicate remains a full scan. xrefs pushes exact from_addr and to_addr lookups; xref_index pushes src_func_addr references but still reads the function catalog for attribution. comments pushes an exact address, but a range is a post-filter scan. bytes is a streaming windowed generator: a point (addr =) or range predicate streams only the requested window, while an unconstrained scan streams the whole image (bounded memory, but time proportional to every mapped byte). When the question is function-scoped, prefer the narrow entry-point views (callers, callees, disasm_blocks, function_calls, string_refs, callgraph_edges) over raw tables.
See references/cost-model.md for the full table and materialization details.
| Symptom | Fix |
|---|---|
funcs returns 0 rows | Program isn't bound — pass --program <name> (or --binary to import) and restart the host |
Every query fails with analysis_running | An analysis job owns the program. Poll SELECT state, elapsed_ms FROM analysis_passes ORDER BY pass_id DESC LIMIT 1; until it is done (that table stays readable), or cancel with DELETE FROM analysis_passes WHERE state = 'running'; |
| Import analysis takes far too long on a large binary | Re-import with --analyzers-off '<pattern>,...' for analyzers that do not apply (e.g. Objective-C on a pure-Swift binary), or tune an existing program with UPDATE program_options and INSERT INTO analysis_passes(mode) VALUES ('all') — see the analysis skill |
| Imported PE's external imports show as ordinals, or library symbols unresolved | Imports skip loading external system libraries by default. Re-import with --load-libraries (or POST /project/import {"load_libraries": true}) to load/link kernel32/CRT (slower) |
| Need to see every program in a project | Run ghidrasql ... --list-project-programs, or query SELECT path,name FROM project_programs ORDER BY path; |
--url rejected with "mutually exclusive" | Pass either explicit --url or explicit --ghidra, never both. GHIDRA_INSTALL_DIR is only a fallback when neither connection flag is present, so that environment variable does not conflict with --url |
analyzeHeadless never prints LIBGHIDRA_HEADLESS_READY | Check the log for an exception or unsupported binary format. CLI-spawned hosts now bind an auto (ephemeral) RPC port, so several instances no longer collide there; the SQL HTTP port (default 8081) can still conflict. Pass --rpc-port N only if you need to pin the RPC port |
Stale *.lock / *.lock~ after force-kill | Confirm java.exe is gone, then delete both lock files |
| GUI host stalls under concurrent decompiler reads | Overlapping requests against pseudocode/decomp_lvars/decomp_comments can deadlock the host on a fair ReentrantReadWriteLock. Workaround: serialise decompiler-backed queries against the same host; do not run two ghidrasql clients hitting decompiler tables in parallel |
| Query returns stale rows after a write or external edit | Check SELECT program_revision() and re-read the exact row. SQL materialisation is destroyed at statement close; continued disagreement points to the source/decompiler or an unapplied mutation. Use refresh_database() only to request an explicit source reload. |
A wide comments range query is unexpectedly expensive | Ranges remain SQL post-filters over a full comment-address scan. Use exact WHERE addr = X for bounded reads |
/query runs far longer than expected while /health still answers | First send curl -X POST -d '' http://127.0.0.1:<sql-port>/cancel. This interrupts SQLite and forwards cancellation to the active LibGhidraHost RPC. A read may return accumulated rows with partial:true plus a cancellation warning; a zero-row read or mutation returns an error. Confirm /health/deep returns to zero active RPCs, then reuse the service. If an older or mismatched host cannot accept cancellation, the endpoint returns 502; attach a fresh ghidrasql --url http://127.0.0.1:<rpc-port> process and save pending state before stopping the orphaned tree. |
| Individual RPC wedges (e.g. a pathological signature parse) tie up the worker | Lower the per-RPC timeout via --rpc-timeout-ms <N> (default 0 → libghidra's 120 s). Wedged calls fail with a timeout error and the worker frees up; observable via /health/deep |
| Local rename / type apply over-propagates through reused decompiler temporaries | The decompiler shares storage between source-level variables that happen to use the same register/stack slot, so apply_type_local (or a direct decomp_lvars UPDATE) on one site can change unrelated locals. Mitigation: back the local out to a neutral type (e.g. char *) and keep the recovered struct on prototypes; verify in pseudocode after each edit |
Pointer-return signature update fails with Can't parse name: *fn | Ghidra's CParser tokenises <type> *fn(...) differently from <type>* fn(...). Workaround: use char* fn form (asterisk on the type, not the name). Same applies to void **, int *, etc. |
main, 135 bytes"); show supporting rows only when they help the user verify; don't dump full tables unprompted; never surface data fetched only as an intermediate reasoning step./query response is a JSON envelope ({success, results:[{columns,rows,...}]}). Consume it directly and render in your reply. Do not pipe responses through python/jq to pre-render a table — that discards the success/elapsed_ms/error fields and makes you reason over a lossy view. The CLI (-q/-f) already prints a table. Reserve jq/python for extracting a value to feed a later query. (For direct terminal/pipe use the server can emit ?format=text|csv|tsv; as an agent, consume json.)Addresses are SQLite INTEGERs (signed 64-bit), so one at or above
0x8000000000000000 (kernel images: 0xFFFFF800..., 0xFFFFFFFF8...) is a
negative INTEGER and ORDER BY addr lists the high half first. hex(addr) and
printf('0x%X', addr) print the unsigned form. Write such an address as a hex
literal (0xFFFFF80000100000) or the negative decimal, never as a decimal
= 2^63 (SQLite makes that a REAL, which matches nothing).
addr >= <high hex>also includes every low address; the high half alone isaddr BETWEEN <high hex> AND -1. Details: thedisassemblyanddataskills.
If GHIDRA_INSTALL_DIR is set in the environment, the CLI auto-fills --ghidra from it and rejects --url as conflicting. For any --url-mode invocation either prefix with unset GHIDRA_INSTALL_DIR; or use env -u GHIDRA_INSTALL_DIR ghidrasql --url ....
Prove the source is alive and learn the current program:
ghidrasql --url http://127.0.0.1:18080 -q "SELECT * FROM binary;"
ghidrasql --url http://127.0.0.1:18080 -q "SELECT COUNT(*) AS n FROM funcs;"
Treat funcs > 0 as the real "program is bound" signal. binary.program_name may legitimately read "active-program" (host placeholder) — that alone is not a failure.
Three mutually exclusive modes. Pick one.
--url)ghidrasql --url http://127.0.0.1:18080 # REPL
ghidrasql --url http://127.0.0.1:18080 -q "<sql>" # one-shot
ghidrasql --url http://127.0.0.1:18080 -f script.sql # script
--ghidra)ghidrasql --ghidra <ghidra_dist> \
--project <project_dir> --project-name <name> \
--program <prog>.exe --no-analyze \
-q "SELECT name FROM funcs LIMIT 5;"
Use Ghidra domain paths for multi-program projects:
ghidrasql --ghidra <ghidra_dist> \
--project <project_dir> --project-name <name> \
--program /samples/payload.exe --no-analyze \
-q "SELECT * FROM binary;"
Seed the session (managed vs one-shot). Headless launch requires only
--project+--project-name; a seed (--binaryto import or--programto reopen) is not enforced. A one-shot-qwith no seed does not error — it attaches to the project with no active program and every analysis table (funcs,pseudocode,xrefs, …) returns 0 rows. This is intentional for managed sessions that attach to an already-open program (e.g. a live Ghidra GUI host). For a self-contained one-shot, always pass--binary/--programso the tables are populated.
Library loading.
--binaryimports skip loading external system libraries by default (kernel32, CRT, …) to keep imports fast. Imports referenced by name still resolve; only imports-by-ordinal show as ordinals instead of names. Pass--load-librariesto load and link them (slower, and pulls the libraries into the project). This applies to the CLI flag and thePOST /project/importbody field"load_libraries": true.
Analyzer overrides at import.
--analyzers-off <patterns>/--analyzers-on <patterns>switch Ghidra analyzers off/on for every--binaryimport before analysis runs. Patterns are comma-separated and case-insensitive; one containing*is a whole-name glob, anything else a substring (--analyzers-off 'Objective-C,Shared Return'). The CLI prints each analyzer it switched and warns — without failing — on a pattern that matched nothing (names differ across Ghidra versions and processors). The flags require--binary; for an already-imported program useUPDATE program_optionsinstead.POST /project/importtakes the same lists as"analyzers_off"/"analyzers_on"(a JSON array or a comma-separated string; omitted = the CLI flags).
Re-analyzing on reopen. A
--programreopen does not analyze. An explicit--analyzethere runs a full analysis job before the query/server starts and waits for it (Ctrl-C cancels it).
--binary and --program are repeatable. A host still has one active program; use --program to choose the active project domain path after imports:
ghidrasql --ghidra <ghidra_dist> \
--project <project_dir> --project-name <name> \
--binary loader.dll --binary payload.exe \
--program /payload.exe --http
List project programs without changing the program-scoped SQL model:
ghidrasql --url http://127.0.0.1:18080 --list-project-programs
ghidrasql --url http://127.0.0.1:18080 \
-q "SELECT path,name,folder_path FROM project_programs ORDER BY path;"
All analysis tables (funcs, pseudocode, xrefs, etc.) describe the active program only. To switch in HTTP mode, save if needed, then call POST /project/open with {"program_path":"/path/in/project"}; for one-shot/REPL mode, re-invoke ghidrasql with another --program.
ghidrasql --ghidra <ghidra_dist> \
--project <project_dir> --project-name <name> \
--program <prog>.exe --no-analyze \
--http --port 8081 --max-runtime 0 &
--http serve mode already defaults to no auto-exit timer (--max-runtime 0), so it runs until you stop it (Ctrl-C or POST /shutdown) — the explicit --max-runtime 0 above is redundant but harmless. The SQL endpoint becomes POST http://127.0.0.1:8081/query (default port). For read-only experiments add --readonly, which implies --shutdown discard and prevents accidental mutations being saved.
| URL | What it speaks | Who talks to it |
|---|---|---|
http://127.0.0.1:18080 | LibGhidraHost protobuf RPC | ghidrasql only |
http://127.0.0.1:8081/query | raw SQL (POST body) | any HTTP client |
18080 is the conventional port for a standalone LibGhidraHost you start yourself and connect to with --url. A host spawned by the CLI (--ghidra) binds an auto-assigned (ephemeral) RPC port by default (no fixed-18080 collisions across concurrent instances); pin it with --rpc-port N if you need a known port.
Wrong: curl -X POST http://127.0.0.1:18080/query ... — the upstream port speaks RPC, not SQL.
/query Response Envelope (canonical, single = array of one)All /query responses use the same shape. Single-statement bodies come back as an array of one entry:
{
"success": true,
"statement_count": <N>,
"results": [
{ "statement_index": 0, "success": true,
"columns": [...], "rows": [...], "row_count": <N>,
"elapsed_ms": <ms>, "error": null },
...
],
"row_count_total": <N>,
"elapsed_ms_total": <ms>,
"first_error_index": null
}
results[] stops at the failure; first_error_index points at it. The remaining statements are NOT executed.continue_on_error=1 runs every statement; each gets its own success / error entry in results[].include_sql=1 echoes each statement's SQL back in its results[i].sql field — useful for long scripts./query?continue_on_error=1&include_sql=1, body = raw SQL) or in a JSON request body: {"sql": "...", "continue_on_error": true, "include_sql": true}. With Content-Type: application/json the body must be a JSON object carrying a string sql — a malformed or sql-less body is rejected with 400 (it is not silently run as raw SQL). A body sent without that content type is treated as raw SQL; a valid leading-{ JSON-with-sql body is still accepted as a compatibility fallback, but prefer sending Content-Type: application/json for JSON requests.success:false, statement_count:0, results:[], plus a top-level parse_error string.The SQL HTTP server exposes project-control endpoints in managed mode, in addition to SQL/query lifecycle endpoints:
| Method | Path | Purpose |
|---|---|---|
| GET | / | Welcome + brief help |
| GET | /help | Endpoint documentation |
| POST | /query | Execute SQL (body = raw SQL or JSON {sql,continue_on_error,include_sql}, single or semicolon-separated script, response = canonical envelope) |
| POST | /cancel | Cooperatively cancel the in-flight SQL query and active LibGhidraHost RPC |
| GET | /status | Server status + program info |
| GET | /health | Liveness probe ({"status":"ok"}) — does not probe the query worker |
| GET | /health/deep | Readiness probe — reflects query-worker state, returns 503 when the oldest in-flight query exceeds the configured threshold |
| GET | /shutdown/status | Lifecycle observability — phase (idle / http_stopping / java_exiting / complete / force_killed), listener_running. Useful for polling during managed-mode shutdowns |
| POST | /refresh | Drop ghidrasql caches and reload |
| GET | /project/programs | List project programs when ghidrasql owns a project host |
| GET | /project/active | Show the active project program |
| POST | /project/import | Import a binary into the live project ({"source_path":"...","analyze":true,"load_libraries":false}). load_libraries (default false) loads/links external system libraries |
| POST | /project/open | Switch the active program ({"program_path":"/domain/path"}) |
| POST | /project/close | Close the active program (`{"shutdown_policy":"save |
| POST | /shutdown | Stop the SQL server (see Session End for managed-vs-proxy semantics) |
Host build pairing (no capability negotiation). The
/project/*routes and the writable memory-map surface ride newer libghidra client RPCs (ImportProgram/OpenProgram/CloseProgram/ListProjectFiles/GetRevisionand the memory-block RPCsCreateMemoryBlock/RemoveMemoryBlock/MoveMemory Block, plusLaunchHeadlessProject). There is no version handshake: against an olderLibGhidraHost/libghidrathat predates these RPCs, those calls fail with an RPC error (surfaced assuccess:false, no crash) rather than degrading. Buildghidrasqland theLibGhidraHostextension from the same libghidra revision so the client and host RPC sets match. If/project/*or a memory-map write returns an unexpected RPC error, suspect a stale host build first.
An explicit checkpoint before stopping is optional. Normal GhidraSQL-managed headless shutdown saves once by default. Proxy-mode shutdown leaves the upstream host running and does not select a policy for it; its owner must later choose save/discard/none explicitly. A checkpoint may also be requested at any time before either kind of shutdown:
SELECT save_database();
Stop the HTTP server:
curl -X POST -d '' http://127.0.0.1:8081/shutdown
/shutdown returns {"success":true} once the listener is stopping. What happens next depends on launch mode:
--ghidra ... --http): ghidrasql owns both the SQL server and the upstream headless Java host. After the SQL server stops, the headless host is closed using the launch-time --shutdown save|discard|none policy (default save). For large pending state this can take many seconds. Wait for both java.exe and ghidrasql.exe to actually exit before reusing the project directory.--url ... --http): ghidrasql owns only the SQL proxy. /shutdown stops the proxy. The upstream LibGhidraHost is untouched — it keeps running. Stop it through its own shutdown RPC so its save policy runs.Never taskkill /F Java while relying on save-on-shutdown. A force-kill
bypasses the shutdown policy, can lose changes since the last optional
checkpoint, and leaves orphaned *.lock / *.lock~ files in the project
directory.
These exist in adjacent tooling (idasql) but are explicit non-features here:
idapython() analog. Java-side scripting is not exposed through ghidrasql.ui-context() function. The GUI plugin does not export selection / widget / cursor state.shutdown() SQL function. Exit policy is fixed at launch (--shutdown save|discard|none); trigger the actual stop with POST /shutdown.decompile SQL helper. Use pseudocode for full-function text. Each SQL statement gets fresh query-scoped materialisation, including statements inside a batch.ghidrasql --url http://127.0.0.1:18080 (or --ghidra ...) drops you into an interactive REPL. Nine dot-commands:
| Command | What |
|---|---|
.help / .h | Help text |
.tables | List virtual tables |
.schema <table> | Show columns for one table |
.info | Server + program metadata (same as /status) |
.save | save_database() shortcut |
.discard | discard_changes() shortcut |
.refresh | refresh_database() shortcut |
.http start / .http stop | Start / stop the embedded SQL HTTP server |
.quit / .exit / .q | Leave the REPL |
# CLI one-shot
ghidrasql --url http://127.0.0.1:18080 \
-q "SELECT name, printf('0x%X', addr) AS addr FROM funcs LIMIT 10;"
# HTTP one-shot (requires --http server already running)
curl -X POST http://127.0.0.1:8081/query \
--data "SELECT name, prototype FROM funcs LIMIT 5;"
# Read-only experiment (no save, host discards on exit)
ghidrasql --ghidra "$GHIDRA_INSTALL_DIR" \
--project /path/to/proj --project-name myproj --program sample.exe \
--no-analyze --readonly --http --port 8081 --max-runtime 0 &
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
12 skills in this plugin
/debuggerManage breakpoints and patch bytes through ghidrasql — the breakpoints table and bytes single-byte UPDATE./ghidrasql:connectfrom ghidrasql
npx claudepluginhub 0xeb/ghidrasql-skills --plugin ghidrasqlOther plugins' skills for the same job