#!/usr/bin/env python3 """Decompile selected native procedures in one local REA stdio session. Uses the public project launcher, no client registration changes or target execution. Keeps complete replies/Evidence on disk and closes owned analysis. """ import argparse import json import os from pathlib import Path import selectors import signal import subprocess import time def main(): cli = argparse.ArgumentParser(description=__doc__) cli.add_argument('target', type=Path) cli.add_argument('output', type=Path) cli.add_argument('procedures', nargs='+') args = cli.parse_args() project = Path(__file__).resolve().parents[2] target = args.target.resolve(strict=True) output = args.output.resolve() originals = (project.parent / 'Original').resolve() if target.is_relative_to(originals) or output.is_relative_to(originals): cli.error('Use a generated target copy and a separate output directory') output.mkdir(parents=True, exist_ok=False) serial = 0 with (output / 'server.stderr').open('w') as stderr: process = subprocess.Popen([str(project / 'scripts/rea.sh'), 'mcp'], cwd=project, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, text=True, bufsize=1, start_new_session=True) selector = selectors.DefaultSelector() selector.register(process.stdout, selectors.EVENT_READ) def rpc(method, params): nonlocal serial serial += 1 process.stdin.write(json.dumps(dict(jsonrpc='2.0', id=serial, method=method, params=params)) + '\n') process.stdin.flush() deadline = time.monotonic() + 180 while time.monotonic() < deadline: if not selector.select(timeout=1): if process.poll() is not None: raise RuntimeError('REA exited; inspect server.stderr') continue line = process.stdout.readline() if not line: raise RuntimeError('REA stdio closed') message = json.loads(line) if message.get('id') == serial: if 'error' in message: raise RuntimeError(message['error']) return message['result'] raise TimeoutError('REA request deadline expired; do not repeat unchanged work') def tool(name, values, filename, required=True): result = rpc('tools/call', dict(name=name, arguments=values)) (output / filename).write_text(json.dumps(result, indent=2) + '\n') if result.get('isError') and required: raise RuntimeError(f'{name} failed; inspect {filename}') return result opened = False failures = 0 try: rpc('initialize', dict(protocolVersion='2024-11-05', capabilities={}, clientInfo=dict(name='Neutron-local-static-batch', version='1'))) process.stdin.write(json.dumps(dict(jsonrpc='2.0', method='notifications/initialized')) + '\n') process.stdin.flush() tool('open_binary', dict(path=str(target), provider_id='ghidra'), 'open.json') opened = True for index, procedure in enumerate(args.procedures): print('Decompiling', procedure, flush=True) result = tool('procedure_pseudo_code', dict(procedure=procedure), f'{index:02d}.json', required=False) if result.get('isError'): failures += 1 print('Unavailable:', procedure, '(see complete reply)', flush=True) tool('export_evidence_bundle', dict(path=str(output / 'evidence.json')), 'export.json') finally: try: if opened: tool('close_binary', dict(snapshot_path=str(output / 'analysis.snapshot.json')), 'close.json') finally: process.stdin.close() try: try: process.wait(timeout=15) except subprocess.TimeoutExpired: # This group contains only the server/helpers started #above. Never terminate an existing MCP client session. os.killpg(process.pid, signal.SIGTERM) try: process.wait(timeout=5) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=5) finally: selector.close() if failures: raise SystemExit(f'{failures} procedure(s) unavailable; successful Evidence retained') if __name__ == '__main__': main()