Skip to content

Ghidrust provides a hyper fast, AI native reverse engineering platform built in Rust, inspired by Ghidra. Includes experimental GPU kernels to rapidly decompile large files, a decryption suite, and network monitor for packet to binary reverse engineering.

24.2 KB
Raw Blame
//! Ghidrust GUI Script Manager, Text Editor, and MCP REPL panes.
//!
//! - **Script Manager** — catalog of shipped Ghidrust MCP tools (non-network).
//!   `Run` invokes `ghidrust` CLI (when mappable) or `ghidrust mcp` tools/call.
//! - **Text Editor** — multi-tab in-memory editor for scripts on disk.
//! - **MCP REPL** — line-oriented `tool_name` / `tool_name {json}` → MCP/CLI.

use crate::layout_tokens::FieldWidth;
use ghidrust_core::ThemeDensity;
use crate::mcp_host::{
    invoke_tool, invoke_tool_with_session, parse_tool_line, McpStdioSession,
};
use eframe::egui::{self, Color32, Ui};
use serde_json::json;
use std::path::PathBuf;

/// One script entry (Ghidrust MCP tools double as the catalog).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptEntry {
    pub name: String,
    pub category: String,
    pub description: String,
    /// Preferred keyboard shortcut, empty if none.
    pub key_binding: String,
}

/// Built-in catalog — real `ghidrust mcp` tool names (excludes all `net_*`).
pub fn builtin_catalog() -> Vec<ScriptEntry> {
    let s = |name: &str, cat: &str, desc: &str| ScriptEntry {
        name: name.into(),
        category: cat.into(),
        description: desc.into(),
        key_binding: String::new(),
    };
    vec![
        // Core
        s(
            "server_info",
            "MCP · Core",
            "Package version, tool_surface, and feature flags.",
        ),
        s(
            "load",
            "MCP · Core",
            "Load a PE or ELF binary (path or project+file_id).",
        ),
        s(
            "list_analyzers",
            "MCP · Analysis",
            "List Auto Analysis options (labels).",
        ),
        s(
            "analyze",
            "MCP · Analysis",
            "Run selected analyzers on a binary path; optional GPU enrich.",
        ),
        s(
            "list_gpu_strategies",
            "MCP · Analysis",
            "Per-analyzer GPU strategy matrix.",
        ),
        // Disasm / decode
        s(
            "disassemble",
            "MCP · Disasm",
            "Disassemble at addr with decode engine options.",
        ),
        s(
            "decode_support",
            "MCP · Disasm",
            "Report decode engine / arch support matrix.",
        ),
        s(
            "decode_query",
            "MCP · Disasm",
            "Engine introspection (insn/reg/group queries).",
        ),
        s(
            "read_bytes",
            "MCP · Disasm",
            "Read raw bytes at a VA from a loaded path.",
        ),
        // Decompile
        s(
            "decompile",
            "MCP · Decompile",
            "Stage-1 expression-folded typed C; optional follow_stub.",
        ),
        s(
            "gpu_decompile",
            "MCP · Decompile",
            "GPU VRAM multipass decompile to .gdecomp.",
        ),
        // Strings / crypto
        s(
            "list_strings",
            "MCP · Strings",
            "ASCII/UTF-16 strings; match/limit/raw blob.",
        ),
        s(
            "search_strings",
            "MCP · Strings",
            "Filter-oriented alias of list_strings.",
        ),
        s(
            "crypt_constants",
            "MCP · Crypto",
            "Scan cryptographic constant tables (S-boxes, TEA, …).",
        ),
        s(
            "list_crypt_constants",
            "MCP · Crypto",
            "List detected crypto constant hits (catalog form).",
        ),
        s(
            "recover_strings",
            "MCP · Crypto",
            "Recover obfuscated strings, optionally scoped to functions.",
        ),
        s(
            "decode_bake",
            "MCP · Crypto",
            "Bake explicit decode operations over input bytes.",
        ),
        s(
            "decode_magic",
            "MCP · Crypto",
            "Suggest and apply a decode recipe from input bytes.",
        ),
        s(
            "list_crypto_capabilities",
            "MCP · Crypto",
            "List detected cryptographic capabilities.",
        ),
        // Functions / xrefs
        s(
            "function_at",
            "MCP · Functions",
            "Containing function for a body VA.",
        ),
        s(
            "get_function_by_address",
            "MCP · Functions",
            "Fetch function metadata by VA.",
        ),
        s(
            "function_create",
            "MCP · Functions",
            "Create/heal a function at VA (optional end).",
        ),
        s(
            "get_xrefs_to",
            "MCP · Xrefs",
            "Refs to a VA; optional skip_stubs/classify.",
        ),
        s(
            "get_xrefs_from",
            "MCP · Xrefs",
            "References emitted from a VA.",
        ),
        s(
            "get_calls_from",
            "MCP · Xrefs",
            "Call sites from a function VA.",
        ),
        s(
            "list_imports",
            "MCP · Xrefs",
            "Enumerate PE import / IAT slots.",
        ),
        s(
            "get_import_xrefs",
            "MCP · Xrefs",
            "Code sites referencing an import IAT slot.",
        ),
        s(
            "get_string_xrefs",
            "MCP · Xrefs",
            "Resolve strings by filter, then xrefs to each.",
        ),
        // Artifacts / FS
        s(
            "inventory",
            "MCP · FS",
            "Generic PE install inventory (exe/dll + VERSIONINFO).",
        ),
        s(
            "list_tree",
            "MCP · FS",
            "Bounded file tree index (size/mtime).",
        ),
        s(
            "artifact_list",
            "MCP · Artifacts",
            "List recent spilled analysis artifacts.",
        ),
        s(
            "artifact_query",
            "MCP · Artifacts",
            "Page through an artifact with offset/limit.",
        ),
        s(
            "artifact_get",
            "MCP · Artifacts",
            "Fetch a spilled analysis artifact by id or path.",
        ),
        // IL2CPP / Unity
        s(
            "il2cpp_meta",
            "MCP · IL2CPP",
            "Parse global-metadata.dat types/methods.",
        ),
        s(
            "il2cpp_map",
            "MCP · IL2CPP",
            "Metadata ↔ RVA map (null when unproven).",
        ),
        s(
            "il2cpp_touch_map",
            "MCP · IL2CPP",
            "Substring touch-map over metadata heaps.",
        ),
        s(
            "il2cpp_stubs",
            "MCP · IL2CPP",
            "List IL2CPP resolve stubs by icall name.",
        ),
        s(
            "il2cpp_icalls",
            "MCP · IL2CPP",
            "Resolve Unity engine icall name‖fn pointer tables.",
        ),
        s(
            "unity_inventory",
            "MCP · Unity",
            "Player install inventory (assemblies, plugins, metadata).",
        ),
        // RTTI
        s(
            "rtti",
            "MCP · RTTI",
            "Recover C++ RTTI class names and vtable links.",
        ),
        s(
            "rtti_query",
            "MCP · RTTI",
            "RTTI catalog query (filter/exact) with multi-vtable honesty.",
        ),
        s(
            "rtti_gpu_bench",
            "MCP · RTTI",
            "CPU recover_rtti vs GPU rtti_scan with PCIe split.",
        ),
        // Process
        s(
            "process_list",
            "MCP · Process",
            "List OS processes (Live Process Bridge).",
        ),
        s(
            "process_attach",
            "MCP · Process",
            "Attach to pid; mode=observe|debug.",
        ),
        s(
            "process_modules",
            "MCP · Process",
            "List modules for an attached session.",
        ),
        s(
            "process_break_set",
            "MCP · Process",
            "Set software breakpoint (debug mode).",
        ),
        s(
            "process_continue",
            "MCP · Process",
            "Continue a stopped debug session.",
        ),
        s(
            "process_step_into",
            "MCP · Process",
            "Single-step into (TF).",
        ),
        s(
            "process_step_over",
            "MCP · Process",
            "Single-step over (TF MVP).",
        ),
        s(
            "process_step_out",
            "MCP · Process",
            "Step out of current frame (debug mode).",
        ),
        s(
            "process_vtable_probe",
            "MCP · Process",
            "Validate object* vtable; list slot targets as live VAs.",
        ),
    ]
}

/// Script Manager session state.
#[derive(Debug, Clone, Default)]
pub struct ScriptManagerState {
    pub catalog: Vec<ScriptEntry>,
    pub filter: String,
    pub selected: Option<usize>,
    /// User-assigned category filter ("" = all).
    pub category_filter: String,
    /// Last Run stdout / JSON / error text shown in the pane.
    pub last_result: String,
    pub last_run_name: String,
}

impl ScriptManagerState {
    pub fn new_with_builtin() -> Self {
        Self {
            catalog: builtin_catalog(),
            ..Self::default()
        }
    }
}

/// One open Text Editor tab.
#[derive(Debug, Clone, Default)]
pub struct TextEditorTab {
    pub path: Option<PathBuf>,
    pub title: String,
    pub body: String,
    pub dirty: bool,
}

/// Text Editor session state (multi-tab).
#[derive(Debug, Clone, Default)]
pub struct TextEditorState {
    pub tabs: Vec<TextEditorTab>,
    pub active: usize,
}

impl TextEditorState {
    pub fn open_untitled(&mut self) {
        let n = self.tabs.len();
        self.tabs.push(TextEditorTab {
            path: None,
            title: format!("Untitled-{}", n + 1),
            body: String::new(),
            dirty: false,
        });
        self.active = self.tabs.len() - 1;
    }
    pub fn open_file(&mut self, path: PathBuf) -> std::io::Result<()> {
        let body = std::fs::read_to_string(&path)?;
        let title = path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("script")
            .to_string();
        self.tabs.push(TextEditorTab {
            path: Some(path),
            title,
            body,
            dirty: false,
        });
        self.active = self.tabs.len() - 1;
        Ok(())
    }
    pub fn save_active(&mut self) -> std::io::Result<()> {
        let Some(tab) = self.tabs.get_mut(self.active) else {
            return Ok(());
        };
        let Some(path) = tab.path.clone() else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "no path — use Save As…",
            ));
        };
        std::fs::write(&path, &tab.body)?;
        tab.dirty = false;
        Ok(())
    }
    pub fn save_active_as(&mut self, path: PathBuf) -> std::io::Result<()> {
        let Some(tab) = self.tabs.get_mut(self.active) else {
            return Ok(());
        };
        std::fs::write(&path, &tab.body)?;
        tab.title = path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("script")
            .to_string();
        tab.path = Some(path);
        tab.dirty = false;
        Ok(())
    }
    pub fn close_active(&mut self) {
        if self.tabs.is_empty() {
            return;
        }
        let idx = self.active.min(self.tabs.len() - 1);
        self.tabs.remove(idx);
        self.active = self.active.saturating_sub(1);
    }
}

/// MCP REPL session state.
#[derive(Default)]
pub struct MacropadReplState {
    pub input: String,
    pub transcript: Vec<ReplLine>,
    /// Persistent `ghidrust mcp` child when available.
    session: Option<McpStdioSession>,
}

#[derive(Debug, Clone)]
pub struct ReplLine {
    pub prompt: bool,
    pub text: String,
}

impl MacropadReplState {
    pub fn submit(&mut self) -> String {
        let cmd = self.input.trim().to_string();
        if cmd.is_empty() {
            return String::new();
        }
        self.transcript.push(ReplLine {
            prompt: true,
            text: cmd.clone(),
        });
        let out = match parse_tool_line(&cmd) {
            Ok((name, args)) => invoke_tool_with_session(&mut self.session, &name, &args),
            Err(e) => e,
        };
        self.transcript.push(ReplLine {
            prompt: false,
            text: out.clone(),
        });
        self.input.clear();
        out
    }
}

/// Run a catalog tool (empty args) via CLI mapping or MCP tools/call.
pub fn run_catalog_tool(name: &str) -> String {
    invoke_tool(name, &json!({}))
}

// ── Rendering ────────────────────────────────────────────────────────────────

/// Render Script Manager. Returns `Some(name)` if a Run was requested.
pub fn render_script_manager(
    state: &mut ScriptManagerState,
    ui: &mut Ui,
    muted: Color32,
    primary: Color32,
) -> Option<String> {
    ui.heading("Script Manager");
    ui.small(
        egui::RichText::new(
            "Script Manager · Ghidrust MCP tools (non-network) · Run → ghidrust CLI / mcp",
        )
        .color(muted),
    );
    ui.separator();

    let mut categories: Vec<String> = state.catalog.iter().map(|s| s.category.clone()).collect();
    categories.sort();
    categories.dedup();

    ui.horizontal(|ui| {
        ui.label("Filter:");
        ui.add(
            egui::TextEdit::singleline(&mut state.filter)
                .desired_width(FieldWidth::Std.px(&ThemeDensity::FIB_DESKTOP))
                .hint_text("name / description"),
        );
        ui.label("Category:");
        egui::ComboBox::from_id_salt("scriptmgr_cat")
            .selected_text(if state.category_filter.is_empty() {
                "All".to_string()
            } else {
                state.category_filter.clone()
            })
            .show_ui(ui, |ui| {
                ui.selectable_value(&mut state.category_filter, String::new(), "All");
                for c in &categories {
                    ui.selectable_value(&mut state.category_filter, c.clone(), c);
                }
            });
    });
    ui.separator();

    let filt = state.filter.to_ascii_lowercase();
    let cf = state.category_filter.clone();
    let rows: Vec<(usize, ScriptEntry)> = state
        .catalog
        .iter()
        .enumerate()
        .filter(|(_, s)| {
            (cf.is_empty() || s.category == cf)
                && (filt.is_empty()
                    || s.name.to_ascii_lowercase().contains(&filt)
                    || s.description.to_ascii_lowercase().contains(&filt))
        })
        .map(|(i, s)| (i, s.clone()))
        .collect();

    ui.small(format!("{} / {} scripts", rows.len(), state.catalog.len()));
    let mut requested_run: Option<String> = None;
    egui::ScrollArea::vertical()
        .id_salt("scriptmgr_scroll")
        .max_height(ThemeDensity::FIB_DESKTOP.scroll_sm)
        .show(ui, |ui| {
            egui::Grid::new("scriptmgr_grid")
                .num_columns(5)
                .striped(true)
                .show(ui, |ui| {
                    ui.strong("Name");
                    ui.strong("Category");
                    ui.strong("Key");
                    ui.strong("Description");
                    ui.strong("");
                    ui.end_row();
                    for (idx, s) in &rows {
                        let is_sel = state.selected == Some(*idx);
                        let name_text = egui::RichText::new(&s.name).monospace();
                        let name_text = if is_sel {
                            name_text.color(primary)
                        } else {
                            name_text
                        };
                        if ui.selectable_label(is_sel, name_text).clicked() {
                            state.selected = Some(*idx);
                        }
                        ui.label(&s.category);
                        ui.monospace(if s.key_binding.is_empty() {
                            "-".into()
                        } else {
                            s.key_binding.clone()
                        });
                        ui.label(&s.description);
                        if ui.small_button("Run").clicked() {
                            requested_run = Some(s.name.clone());
                        }
                        ui.end_row();
                    }
                });
        });

    if let Some(idx) = state.selected {
        if let Some(entry) = state.catalog.get(idx) {
            ui.separator();
            ui.label(egui::RichText::new("Selected").strong());
            ui.monospace(&entry.name);
            ui.small(&entry.description);
        }
    }

    if let Some(name) = requested_run.clone() {
        let out = run_catalog_tool(&name);
        state.last_run_name = name;
        state.last_result = out;
    }

    if !state.last_result.is_empty() {
        ui.separator();
        ui.label(
            egui::RichText::new(format!("Result · {}", state.last_run_name))
                .strong()
                .color(primary),
        );
        egui::ScrollArea::vertical()
            .id_salt("scriptmgr_result")
            .max_height(ThemeDensity::FIB_DESKTOP.scroll_sm)
            .show(ui, |ui| {
                ui.monospace(egui::RichText::new(&state.last_result).color(muted));
            });
    }

    requested_run
}

/// Render the Text Editor.
///
/// Returns any file-op the caller must dispatch (Open / Save / SaveAs / Close).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextEditorRequest {
    None,
    OpenFile,
    Save,
    SaveAs,
    Close,
    NewUntitled,
}

pub fn render_text_editor(
    state: &mut TextEditorState,
    ui: &mut Ui,
    muted: Color32,
    primary: Color32,
) -> TextEditorRequest {
    ui.heading("Text Editor");
    ui.small(
        egui::RichText::new("Text Editor · in-memory tabs on top of the local filesystem")
            .color(muted),
    );
    ui.separator();

    let mut req = TextEditorRequest::None;
    ui.horizontal(|ui| {
        if ui.button("New").clicked() {
            req = TextEditorRequest::NewUntitled;
        }
        if ui.button("Open…").clicked() {
            req = TextEditorRequest::OpenFile;
        }
        if ui.button("Save").clicked() {
            req = TextEditorRequest::Save;
        }
        if ui.button("Save As…").clicked() {
            req = TextEditorRequest::SaveAs;
        }
        if ui.button("Close Tab").clicked() {
            req = TextEditorRequest::Close;
        }
    });
    ui.separator();

    if state.tabs.is_empty() {
        ui.weak("No files open — click Open… or New to start.");
        return req;
    }

    // Tab bar.
    ui.horizontal_wrapped(|ui| {
        let mut set_active: Option<usize> = None;
        for (i, tab) in state.tabs.iter().enumerate() {
            let mut label = tab.title.clone();
            if tab.dirty {
                label.push('*');
            }
            let is_active = state.active == i;
            let text = if is_active {
                egui::RichText::new(&label).strong().color(primary)
            } else {
                egui::RichText::new(&label)
            };
            if ui.selectable_label(is_active, text).clicked() {
                set_active = Some(i);
            }
        }
        if let Some(i) = set_active {
            state.active = i;
        }
    });

    ui.separator();
    let active = state.active.min(state.tabs.len().saturating_sub(1));
    state.active = active;
    let Some(tab) = state.tabs.get_mut(active) else {
        return req;
    };

    let path_label = tab
        .path
        .as_ref()
        .and_then(|p| p.to_str())
        .unwrap_or("(unsaved)");
    ui.small(egui::RichText::new(path_label).color(muted));
    let before = tab.body.clone();
    egui::ScrollArea::vertical()
        .id_salt("texted_body")
        .max_height(ThemeDensity::FIB_DESKTOP.scroll_md)
        .show(ui, |ui| {
            ui.add(
                egui::TextEdit::multiline(&mut tab.body)
                    .font(egui::FontId::monospace(13.0))
                    .desired_width(f32::INFINITY)
                    .desired_rows(20)
                    .code_editor(),
            );
        });
    if before != tab.body {
        tab.dirty = true;
    }

    req
}

/// Render the MCP REPL.
pub fn render_mcp_repl(
    state: &mut MacropadReplState,
    ui: &mut Ui,
    muted: Color32,
    primary: Color32,
) {
    ui.heading("Python (MCP REPL)");
    ui.small(
        egui::RichText::new("MCP REPL · ghidrust mcp stdio (tool_name or tool_name {json})")
            .color(muted),
    );
    ui.separator();

    egui::ScrollArea::vertical()
        .id_salt("mcp_repl_transcript")
        .stick_to_bottom(true)
        .max_height(ThemeDensity::FIB_DESKTOP.scroll_md)
        .show(ui, |ui| {
            for line in &state.transcript {
                if line.prompt {
                    ui.monospace(egui::RichText::new(format!(">>> {}", line.text)).color(primary));
                } else {
                    ui.monospace(egui::RichText::new(&line.text).color(muted));
                }
            }
        });

    ui.separator();
    ui.horizontal(|ui| {
        ui.label(">>> ");
        let resp = ui.add(
            egui::TextEdit::singleline(&mut state.input)
                .desired_width(ui.available_width() - 80.0)
                .hint_text(r#"server_info  |  list_strings {"path":"…"}"#),
        );
        let submit = ui.button("Run").clicked()
            || (resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
        if submit {
            state.submit();
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builtin_catalog_covers_ghidrust_mcp_surface() {
        let cat = builtin_catalog();
        assert!(cat.len() >= 20);
        assert!(
            !cat.iter().any(|s| s.name.starts_with("net_")),
            "catalog must exclude net_* tools"
        );
        for want in [
            "load",
            "analyze",
            "disassemble",
            "decompile",
            "list_strings",
            "crypt_constants",
            "function_at",
            "function_create",
            "get_xrefs_to",
            "get_xrefs_from",
            "get_calls_from",
            "inventory",
            "list_tree",
            "artifact_list",
            "artifact_query",
            "artifact_get",
            "il2cpp_meta",
            "il2cpp_map",
            "il2cpp_icalls",
            "il2cpp_touch_map",
            "il2cpp_stubs",
            "unity_inventory",
            "decode_support",
            "decode_query",
            "process_list",
            "process_attach",
            "process_modules",
            "process_break_set",
            "process_continue",
            "process_step_into",
            "process_step_over",
            "process_step_out",
            "process_vtable_probe",
            "server_info",
            "list_analyzers",
            "list_gpu_strategies",
            "rtti",
            "rtti_query",
            "rtti_gpu_bench",
        ] {
            assert!(cat.iter().any(|s| s.name == want), "missing {want}");
        }
    }

    #[test]
    fn text_editor_open_and_save_flow() {
        let dir = std::env::temp_dir().join(format!("ghidrust_txted_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("hello.txt");
        std::fs::write(&path, "hello").unwrap();

        let mut st = TextEditorState::default();
        st.open_untitled();
        assert_eq!(st.tabs.len(), 1);
        st.open_file(path.clone()).unwrap();
        assert_eq!(st.tabs.len(), 2);
        assert_eq!(st.tabs[1].body, "hello");
        st.tabs[1].body.push_str(" world");
        st.tabs[1].dirty = true;
        st.save_active().unwrap();
        assert!(!st.tabs[1].dirty);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello world");
        st.close_active();
        assert_eq!(st.tabs.len(), 1);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn repl_submit_appends_prompt_and_response() {
        let mut r = MacropadReplState::default();
        r.input = "server_info".into();
        r.submit();
        assert_eq!(r.transcript.len(), 2);
        assert!(r.transcript[0].prompt);
        assert!(!r.transcript[1].prompt);
        assert!(r.input.is_empty());
        // Response is either real JSON from CLI/MCP or a resolve error — never the old stub.
        assert!(!r.transcript[1].text.contains("Backend pending"));
    }
}