File size: 138,002 Bytes
d8161fe
1
2
{"repo_name": "GhidraMCP", "file_name": "/GhidraMCP/src/main/java/com/lauriewired/GhidraMCPPlugin.java", "inference_info": {"prefix_code": "package com.lauriewired;\n\nimport ghidra.framework.plugintool.Plugin;\nimport ghidra.framework.plugintool.PluginTool;\nimport ghidra.program.model.address.Address;\nimport ghidra.program.model.address.GlobalNamespace;\nimport ghidra.program.model.listing.*;\nimport ghidra.program.model.mem.MemoryBlock;\nimport ghidra.program.model.symbol.*;\nimport ghidra.program.model.symbol.ReferenceManager;\nimport ghidra.program.model.symbol.Reference;\nimport ghidra.program.model.symbol.ReferenceIterator;\nimport ghidra.program.model.symbol.RefType;\nimport ghidra.program.model.pcode.HighFunction;\nimport ghidra.program.model.pcode.HighSymbol;\nimport ghidra.program.model.pcode.LocalSymbolMap;\nimport ghidra.program.model.pcode.HighFunctionDBUtil;\nimport ghidra.program.model.pcode.HighFunctionDBUtil.ReturnCommitOption;\nimport ghidra.app.decompiler.DecompInterface;\nimport ghidra.app.decompiler.DecompileResults;\nimport ghidra.app.plugin.PluginCategoryNames;\nimport ghidra.app.services.CodeViewerService;\nimport ghidra.app.services.ProgramManager;\nimport ghidra.app.util.PseudoDisassembler;\nimport ghidra.app.cmd.function.SetVariableNameCmd;\nimport ghidra.program.model.symbol.SourceType;\nimport ghidra.program.model.listing.LocalVariableImpl;\nimport ghidra.program.model.listing.ParameterImpl;\nimport ghidra.util.exception.DuplicateNameException;\nimport ghidra.util.exception.InvalidInputException;\nimport ghidra.framework.plugintool.PluginInfo;\nimport ghidra.framework.plugintool.util.PluginStatus;\nimport ghidra.program.util.ProgramLocation;\nimport ghidra.util.Msg;\nimport ghidra.util.task.ConsoleTaskMonitor;\nimport ghidra.util.task.TaskMonitor;\nimport ghidra.program.model.pcode.HighVariable;\nimport ghidra.program.model.pcode.Varnode;\nimport ghidra.program.model.data.DataType;\nimport ghidra.program.model.data.DataTypeManager;\nimport ghidra.program.model.data.PointerDataType;\nimport ghidra.program.model.data.Undefined1DataType;\nimport ghidra.program.model.listing.Variable;\nimport ghidra.app.decompiler.component.DecompilerUtils;\nimport ghidra.app.decompiler.ClangToken;\nimport ghidra.framework.options.Options;\n\nimport com.sun.net.httpserver.HttpExchange;\nimport com.sun.net.httpserver.HttpServer;\n\nimport javax.swing.SwingUtilities;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.InetSocketAddress;\nimport java.net.URLDecoder;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\n", "suffix_code": "\n", "middle_code": "@PluginInfo(\n    status = PluginStatus.RELEASED,\n    packageName = ghidra.app.DeveloperPluginPackage.NAME,\n    category = PluginCategoryNames.ANALYSIS,\n    shortDescription = \"HTTP server plugin\",\n    description = \"Starts an embedded HTTP server to expose program data. Port configurable via Tool Options.\"\n)\npublic class GhidraMCPPlugin extends Plugin {\n    private HttpServer server;\n    private static final String OPTION_CATEGORY_NAME = \"GhidraMCP HTTP Server\";\n    private static final String PORT_OPTION_NAME = \"Server Port\";\n    private static final int DEFAULT_PORT = 8080;\n    public GhidraMCPPlugin(PluginTool tool) {\n        super(tool);\n        Msg.info(this, \"GhidraMCPPlugin loading...\");\n        Options options = tool.getOptions(OPTION_CATEGORY_NAME);\n        options.registerOption(PORT_OPTION_NAME, DEFAULT_PORT,\n            null, \n            \"The network port number the embedded HTTP server will listen on. \" +\n            \"Requires Ghidra restart or plugin reload to take effect after changing.\");\n        try {\n            startServer();\n        }\n        catch (IOException e) {\n            Msg.error(this, \"Failed to start HTTP server\", e);\n        }\n        Msg.info(this, \"GhidraMCPPlugin loaded!\");\n    }\n    private void startServer() throws IOException {\n        Options options = tool.getOptions(OPTION_CATEGORY_NAME);\n        int port = options.getInt(PORT_OPTION_NAME, DEFAULT_PORT);\n        if (server != null) {\n            Msg.info(this, \"Stopping existing HTTP server before starting new one.\");\n            server.stop(0);\n            server = null;\n        }\n        server = HttpServer.create(new InetSocketAddress(port), 0);\n        server.createContext(\"/methods\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, getAllFunctionNames(offset, limit));\n        });\n        server.createContext(\"/classes\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, getAllClassNames(offset, limit));\n        });\n        server.createContext(\"/decompile\", exchange -> {\n            String name = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);\n            sendResponse(exchange, decompileFunctionByName(name));\n        });\n        server.createContext(\"/renameFunction\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String response = renameFunction(params.get(\"oldName\"), params.get(\"newName\"))\n                    ? \"Renamed successfully\" : \"Rename failed\";\n            sendResponse(exchange, response);\n        });\n        server.createContext(\"/renameData\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            renameDataAtAddress(params.get(\"address\"), params.get(\"newName\"));\n            sendResponse(exchange, \"Rename data attempted\");\n        });\n        server.createContext(\"/renameVariable\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionName = params.get(\"functionName\");\n            String oldName = params.get(\"oldName\");\n            String newName = params.get(\"newName\");\n            String result = renameVariableInFunction(functionName, oldName, newName);\n            sendResponse(exchange, result);\n        });\n        server.createContext(\"/segments\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listSegments(offset, limit));\n        });\n        server.createContext(\"/imports\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listImports(offset, limit));\n        });\n        server.createContext(\"/exports\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listExports(offset, limit));\n        });\n        server.createContext(\"/namespaces\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listNamespaces(offset, limit));\n        });\n        server.createContext(\"/data\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listDefinedData(offset, limit));\n        });\n        server.createContext(\"/searchFunctions\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String searchTerm = qparams.get(\"query\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, searchFunctionsByName(searchTerm, offset, limit));\n        });\n        server.createContext(\"/get_function_by_address\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            sendResponse(exchange, getFunctionByAddress(address));\n        });\n        server.createContext(\"/get_current_address\", exchange -> {\n            sendResponse(exchange, getCurrentAddress());\n        });\n        server.createContext(\"/get_current_function\", exchange -> {\n            sendResponse(exchange, getCurrentFunction());\n        });\n        server.createContext(\"/list_functions\", exchange -> {\n            sendResponse(exchange, listFunctions());\n        });\n        server.createContext(\"/decompile_function\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            sendResponse(exchange, decompileFunctionByAddress(address));\n        });\n        server.createContext(\"/disassemble_function\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            sendResponse(exchange, disassembleFunction(address));\n        });\n        server.createContext(\"/set_decompiler_comment\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String address = params.get(\"address\");\n            String comment = params.get(\"comment\");\n            boolean success = setDecompilerComment(address, comment);\n            sendResponse(exchange, success ? \"Comment set successfully\" : \"Failed to set comment\");\n        });\n        server.createContext(\"/set_disassembly_comment\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String address = params.get(\"address\");\n            String comment = params.get(\"comment\");\n            boolean success = setDisassemblyComment(address, comment);\n            sendResponse(exchange, success ? \"Comment set successfully\" : \"Failed to set comment\");\n        });\n        server.createContext(\"/rename_function_by_address\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionAddress = params.get(\"function_address\");\n            String newName = params.get(\"new_name\");\n            boolean success = renameFunctionByAddress(functionAddress, newName);\n            sendResponse(exchange, success ? \"Function renamed successfully\" : \"Failed to rename function\");\n        });\n        server.createContext(\"/set_function_prototype\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionAddress = params.get(\"function_address\");\n            String prototype = params.get(\"prototype\");\n            PrototypeResult result = setFunctionPrototype(functionAddress, prototype);\n            if (result.isSuccess()) {\n                String successMsg = \"Function prototype set successfully\";\n                if (!result.getErrorMessage().isEmpty()) {\n                    successMsg += \"\\n\\nWarnings/Debug Info:\\n\" + result.getErrorMessage();\n                }\n                sendResponse(exchange, successMsg);\n            } else {\n                sendResponse(exchange, \"Failed to set function prototype: \" + result.getErrorMessage());\n            }\n        });\n        server.createContext(\"/set_local_variable_type\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionAddress = params.get(\"function_address\");\n            String variableName = params.get(\"variable_name\");\n            String newType = params.get(\"new_type\");\n            StringBuilder responseMsg = new StringBuilder();\n            responseMsg.append(\"Setting variable type: \").append(variableName)\n                      .append(\" to \").append(newType)\n                      .append(\" in function at \").append(functionAddress).append(\"\\n\\n\");\n            Program program = getCurrentProgram();\n            if (program != null) {\n                DataTypeManager dtm = program.getDataTypeManager();\n                DataType directType = findDataTypeByNameInAllCategories(dtm, newType);\n                if (directType != null) {\n                    responseMsg.append(\"Found type: \").append(directType.getPathName()).append(\"\\n\");\n                } else if (newType.startsWith(\"P\") && newType.length() > 1) {\n                    String baseTypeName = newType.substring(1);\n                    DataType baseType = findDataTypeByNameInAllCategories(dtm, baseTypeName);\n                    if (baseType != null) {\n                        responseMsg.append(\"Found base type for pointer: \").append(baseType.getPathName()).append(\"\\n\");\n                    } else {\n                        responseMsg.append(\"Base type not found for pointer: \").append(baseTypeName).append(\"\\n\");\n                    }\n                } else {\n                    responseMsg.append(\"Type not found directly: \").append(newType).append(\"\\n\");\n                }\n            }\n            boolean success = setLocalVariableType(functionAddress, variableName, newType);\n            String successMsg = success ? \"Variable type set successfully\" : \"Failed to set variable type\";\n            responseMsg.append(\"\\nResult: \").append(successMsg);\n            sendResponse(exchange, responseMsg.toString());\n        });\n        server.createContext(\"/xrefs_to\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, getXrefsTo(address, offset, limit));\n        });\n        server.createContext(\"/xrefs_from\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, getXrefsFrom(address, offset, limit));\n        });\n        server.createContext(\"/function_xrefs\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String name = qparams.get(\"name\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, getFunctionXrefs(name, offset, limit));\n        });\n        server.createContext(\"/strings\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            String filter = qparams.get(\"filter\");\n            sendResponse(exchange, listDefinedStrings(offset, limit, filter));\n        });\n        server.setExecutor(null);\n        new Thread(() -> {\n            try {\n                server.start();\n                Msg.info(this, \"GhidraMCP HTTP server started on port \" + port);\n            } catch (Exception e) {\n                Msg.error(this, \"Failed to start HTTP server on port \" + port + \". Port might be in use.\", e);\n                server = null; \n            }\n        }, \"GhidraMCP-HTTP-Server\").start();\n    }\n    private String getAllFunctionNames(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> names = new ArrayList<>();\n        for (Function f : program.getFunctionManager().getFunctions(true)) {\n            names.add(f.getName());\n        }\n        return paginateList(names, offset, limit);\n    }\n    private String getAllClassNames(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        Set<String> classNames = new HashSet<>();\n        for (Symbol symbol : program.getSymbolTable().getAllSymbols(true)) {\n            Namespace ns = symbol.getParentNamespace();\n            if (ns != null && !ns.isGlobal()) {\n                classNames.add(ns.getName());\n            }\n        }\n        List<String> sorted = new ArrayList<>(classNames);\n        Collections.sort(sorted);\n        return paginateList(sorted, offset, limit);\n    }\n    private String listSegments(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        for (MemoryBlock block : program.getMemory().getBlocks()) {\n            lines.add(String.format(\"%s: %s - %s\", block.getName(), block.getStart(), block.getEnd()));\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String listImports(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        for (Symbol symbol : program.getSymbolTable().getExternalSymbols()) {\n            lines.add(symbol.getName() + \" -> \" + symbol.getAddress());\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String listExports(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        SymbolTable table = program.getSymbolTable();\n        SymbolIterator it = table.getAllSymbols(true);\n        List<String> lines = new ArrayList<>();\n        while (it.hasNext()) {\n            Symbol s = it.next();\n            if (s.isExternalEntryPoint()) {\n                lines.add(s.getName() + \" -> \" + s.getAddress());\n            }\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String listNamespaces(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        Set<String> namespaces = new HashSet<>();\n        for (Symbol symbol : program.getSymbolTable().getAllSymbols(true)) {\n            Namespace ns = symbol.getParentNamespace();\n            if (ns != null && !(ns instanceof GlobalNamespace)) {\n                namespaces.add(ns.getName());\n            }\n        }\n        List<String> sorted = new ArrayList<>(namespaces);\n        Collections.sort(sorted);\n        return paginateList(sorted, offset, limit);\n    }\n    private String listDefinedData(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        for (MemoryBlock block : program.getMemory().getBlocks()) {\n            DataIterator it = program.getListing().getDefinedData(block.getStart(), true);\n            while (it.hasNext()) {\n                Data data = it.next();\n                if (block.contains(data.getAddress())) {\n                    String label   = data.getLabel() != null ? data.getLabel() : \"(unnamed)\";\n                    String valRepr = data.getDefaultValueRepresentation();\n                    lines.add(String.format(\"%s: %s = %s\",\n                        data.getAddress(),\n                        escapeNonAscii(label),\n                        escapeNonAscii(valRepr)\n                    ));\n                }\n            }\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String searchFunctionsByName(String searchTerm, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (searchTerm == null || searchTerm.isEmpty()) return \"Search term is required\";\n        List<String> matches = new ArrayList<>();\n        for (Function func : program.getFunctionManager().getFunctions(true)) {\n            String name = func.getName();\n            if (name.toLowerCase().contains(searchTerm.toLowerCase())) {\n                matches.add(String.format(\"%s @ %s\", name, func.getEntryPoint()));\n            }\n        }\n        Collections.sort(matches);\n        if (matches.isEmpty()) {\n            return \"No functions matching '\" + searchTerm + \"'\";\n        }\n        return paginateList(matches, offset, limit);\n    }    \n    private String decompileFunctionByName(String name) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        DecompInterface decomp = new DecompInterface();\n        decomp.openProgram(program);\n        for (Function func : program.getFunctionManager().getFunctions(true)) {\n            if (func.getName().equals(name)) {\n                DecompileResults result =\n                    decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());\n                if (result != null && result.decompileCompleted()) {\n                    return result.getDecompiledFunction().getC();\n                } else {\n                    return \"Decompilation failed\";\n                }\n            }\n        }\n        return \"Function not found\";\n    }\n    private boolean renameFunction(String oldName, String newName) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        AtomicBoolean successFlag = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                int tx = program.startTransaction(\"Rename function via HTTP\");\n                try {\n                    for (Function func : program.getFunctionManager().getFunctions(true)) {\n                        if (func.getName().equals(oldName)) {\n                            func.setName(newName, SourceType.USER_DEFINED);\n                            successFlag.set(true);\n                            break;\n                        }\n                    }\n                }\n                catch (Exception e) {\n                    Msg.error(this, \"Error renaming function\", e);\n                }\n                finally {\n                    successFlag.set(program.endTransaction(tx, successFlag.get()));\n                }\n            });\n        }\n        catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute rename on Swing thread\", e);\n        }\n        return successFlag.get();\n    }\n    private void renameDataAtAddress(String addressStr, String newName) {\n        Program program = getCurrentProgram();\n        if (program == null) return;\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                int tx = program.startTransaction(\"Rename data\");\n                try {\n                    Address addr = program.getAddressFactory().getAddress(addressStr);\n                    Listing listing = program.getListing();\n                    Data data = listing.getDefinedDataAt(addr);\n                    if (data != null) {\n                        SymbolTable symTable = program.getSymbolTable();\n                        Symbol symbol = symTable.getPrimarySymbol(addr);\n                        if (symbol != null) {\n                            symbol.setName(newName, SourceType.USER_DEFINED);\n                        } else {\n                            symTable.createLabel(addr, newName, SourceType.USER_DEFINED);\n                        }\n                    }\n                }\n                catch (Exception e) {\n                    Msg.error(this, \"Rename data error\", e);\n                }\n                finally {\n                    program.endTransaction(tx, true);\n                }\n            });\n        }\n        catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute rename data on Swing thread\", e);\n        }\n    }\n    private String renameVariableInFunction(String functionName, String oldVarName, String newVarName) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        DecompInterface decomp = new DecompInterface();\n        decomp.openProgram(program);\n        Function func = null;\n        for (Function f : program.getFunctionManager().getFunctions(true)) {\n            if (f.getName().equals(functionName)) {\n                func = f;\n                break;\n            }\n        }\n        if (func == null) {\n            return \"Function not found\";\n        }\n        DecompileResults result = decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());\n        if (result == null || !result.decompileCompleted()) {\n            return \"Decompilation failed\";\n        }\n        HighFunction highFunction = result.getHighFunction();\n        if (highFunction == null) {\n            return \"Decompilation failed (no high function)\";\n        }\n        LocalSymbolMap localSymbolMap = highFunction.getLocalSymbolMap();\n        if (localSymbolMap == null) {\n            return \"Decompilation failed (no local symbol map)\";\n        }\n        HighSymbol highSymbol = null;\n        Iterator<HighSymbol> symbols = localSymbolMap.getSymbols();\n        while (symbols.hasNext()) {\n            HighSymbol symbol = symbols.next();\n            String symbolName = symbol.getName();\n            if (symbolName.equals(oldVarName)) {\n                highSymbol = symbol;\n            }\n            if (symbolName.equals(newVarName)) {\n                return \"Error: A variable with name '\" + newVarName + \"' already exists in this function\";\n            }\n        }\n        if (highSymbol == null) {\n            return \"Variable not found\";\n        }\n        boolean commitRequired = checkFullCommit(highSymbol, highFunction);\n        final HighSymbol finalHighSymbol = highSymbol;\n        final Function finalFunction = func;\n        AtomicBoolean successFlag = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {           \n                int tx = program.startTransaction(\"Rename variable\");\n                try {\n                    if (commitRequired) {\n                        HighFunctionDBUtil.commitParamsToDatabase(highFunction, false,\n                            ReturnCommitOption.NO_COMMIT, finalFunction.getSignatureSource());\n                    }\n                    HighFunctionDBUtil.updateDBVariable(\n                        finalHighSymbol,\n                        newVarName,\n                        null,\n                        SourceType.USER_DEFINED\n                    );\n                    successFlag.set(true);\n                }\n                catch (Exception e) {\n                    Msg.error(this, \"Failed to rename variable\", e);\n                }\n                finally {\n                    successFlag.set(program.endTransaction(tx, true));\n                }\n            });\n        } catch (InterruptedException | InvocationTargetException e) {\n            String errorMsg = \"Failed to execute rename on Swing thread: \" + e.getMessage();\n            Msg.error(this, errorMsg, e);\n            return errorMsg;\n        }\n        return successFlag.get() ? \"Variable renamed\" : \"Failed to rename variable\";\n    }\n\tprotected static boolean checkFullCommit(HighSymbol highSymbol, HighFunction hfunction) {\n\t\tif (highSymbol != null && !highSymbol.isParameter()) {\n\t\t\treturn false;\n\t\t}\n\t\tFunction function = hfunction.getFunction();\n\t\tParameter[] parameters = function.getParameters();\n\t\tLocalSymbolMap localSymbolMap = hfunction.getLocalSymbolMap();\n\t\tint numParams = localSymbolMap.getNumParams();\n\t\tif (numParams != parameters.length) {\n\t\t\treturn true;\n\t\t}\n\t\tfor (int i = 0; i < numParams; i++) {\n\t\t\tHighSymbol param = localSymbolMap.getParamSymbol(i);\n\t\t\tif (param.getCategoryIndex() != i) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tVariableStorage storage = param.getStorage();\n\t\t\tif (0 != storage.compareTo(parameters[i].getVariableStorage())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n    private String getFunctionByAddress(String addressStr) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            Function func = program.getFunctionManager().getFunctionAt(addr);\n            if (func == null) return \"No function found at address \" + addressStr;\n            return String.format(\"Function: %s at %s\\nSignature: %s\\nEntry: %s\\nBody: %s - %s\",\n                func.getName(),\n                func.getEntryPoint(),\n                func.getSignature(),\n                func.getEntryPoint(),\n                func.getBody().getMinAddress(),\n                func.getBody().getMaxAddress());\n        } catch (Exception e) {\n            return \"Error getting function: \" + e.getMessage();\n        }\n    }\n    private String getCurrentAddress() {\n        CodeViewerService service = tool.getService(CodeViewerService.class);\n        if (service == null) return \"Code viewer service not available\";\n        ProgramLocation location = service.getCurrentLocation();\n        return (location != null) ? location.getAddress().toString() : \"No current location\";\n    }\n    private String getCurrentFunction() {\n        CodeViewerService service = tool.getService(CodeViewerService.class);\n        if (service == null) return \"Code viewer service not available\";\n        ProgramLocation location = service.getCurrentLocation();\n        if (location == null) return \"No current location\";\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        Function func = program.getFunctionManager().getFunctionContaining(location.getAddress());\n        if (func == null) return \"No function at current location: \" + location.getAddress();\n        return String.format(\"Function: %s at %s\\nSignature: %s\",\n            func.getName(),\n            func.getEntryPoint(),\n            func.getSignature());\n    }\n    private String listFunctions() {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        StringBuilder result = new StringBuilder();\n        for (Function func : program.getFunctionManager().getFunctions(true)) {\n            result.append(String.format(\"%s at %s\\n\", \n                func.getName(), \n                func.getEntryPoint()));\n        }\n        return result.toString();\n    }\n    private Function getFunctionForAddress(Program program, Address addr) {\n        Function func = program.getFunctionManager().getFunctionAt(addr);\n        if (func == null) {\n            func = program.getFunctionManager().getFunctionContaining(addr);\n        }\n        return func;\n    }\n    private String decompileFunctionByAddress(String addressStr) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) return \"No function found at or containing address \" + addressStr;\n            DecompInterface decomp = new DecompInterface();\n            decomp.openProgram(program);\n            DecompileResults result = decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());\n            return (result != null && result.decompileCompleted()) \n                ? result.getDecompiledFunction().getC() \n                : \"Decompilation failed\";\n        } catch (Exception e) {\n            return \"Error decompiling function: \" + e.getMessage();\n        }\n    }\n    private String disassembleFunction(String addressStr) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) return \"No function found at or containing address \" + addressStr;\n            StringBuilder result = new StringBuilder();\n            Listing listing = program.getListing();\n            Address start = func.getEntryPoint();\n            Address end = func.getBody().getMaxAddress();\n            InstructionIterator instructions = listing.getInstructions(start, true);\n            while (instructions.hasNext()) {\n                Instruction instr = instructions.next();\n                if (instr.getAddress().compareTo(end) > 0) {\n                    break; \n                }\n                String comment = listing.getComment(CodeUnit.EOL_COMMENT, instr.getAddress());\n                comment = (comment != null) ? \"; \" + comment : \"\";\n                result.append(String.format(\"%s: %s %s\\n\", \n                    instr.getAddress(), \n                    instr.toString(),\n                    comment));\n            }\n            return result.toString();\n        } catch (Exception e) {\n            return \"Error disassembling function: \" + e.getMessage();\n        }\n    }    \n    private boolean setCommentAtAddress(String addressStr, String comment, int commentType, String transactionName) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        if (addressStr == null || addressStr.isEmpty() || comment == null) return false;\n        AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                int tx = program.startTransaction(transactionName);\n                try {\n                    Address addr = program.getAddressFactory().getAddress(addressStr);\n                    program.getListing().setComment(addr, commentType, comment);\n                    success.set(true);\n                } catch (Exception e) {\n                    Msg.error(this, \"Error setting \" + transactionName.toLowerCase(), e);\n                } finally {\n                    success.set(program.endTransaction(tx, success.get()));\n                }\n            });\n        } catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute \" + transactionName.toLowerCase() + \" on Swing thread\", e);\n        }\n        return success.get();\n    }\n    private boolean setDecompilerComment(String addressStr, String comment) {\n        return setCommentAtAddress(addressStr, comment, CodeUnit.PRE_COMMENT, \"Set decompiler comment\");\n    }\n    private boolean setDisassemblyComment(String addressStr, String comment) {\n        return setCommentAtAddress(addressStr, comment, CodeUnit.EOL_COMMENT, \"Set disassembly comment\");\n    }\n    private static class PrototypeResult {\n        private final boolean success;\n        private final String errorMessage;\n        public PrototypeResult(boolean success, String errorMessage) {\n            this.success = success;\n            this.errorMessage = errorMessage;\n        }\n        public boolean isSuccess() {\n            return success;\n        }\n        public String getErrorMessage() {\n            return errorMessage;\n        }\n    }\n    private boolean renameFunctionByAddress(String functionAddrStr, String newName) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        if (functionAddrStr == null || functionAddrStr.isEmpty() || \n            newName == null || newName.isEmpty()) {\n            return false;\n        }\n        AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                performFunctionRename(program, functionAddrStr, newName, success);\n            });\n        } catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute rename function on Swing thread\", e);\n        }\n        return success.get();\n    }\n    private void performFunctionRename(Program program, String functionAddrStr, String newName, AtomicBoolean success) {\n        int tx = program.startTransaction(\"Rename function by address\");\n        try {\n            Address addr = program.getAddressFactory().getAddress(functionAddrStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) {\n                Msg.error(this, \"Could not find function at address: \" + functionAddrStr);\n                return;\n            }\n            func.setName(newName, SourceType.USER_DEFINED);\n            success.set(true);\n        } catch (Exception e) {\n            Msg.error(this, \"Error renaming function by address\", e);\n        } finally {\n            program.endTransaction(tx, success.get());\n        }\n    }\n    private PrototypeResult setFunctionPrototype(String functionAddrStr, String prototype) {\n        Program program = getCurrentProgram();\n        if (program == null) return new PrototypeResult(false, \"No program loaded\");\n        if (functionAddrStr == null || functionAddrStr.isEmpty()) {\n            return new PrototypeResult(false, \"Function address is required\");\n        }\n        if (prototype == null || prototype.isEmpty()) {\n            return new PrototypeResult(false, \"Function prototype is required\");\n        }\n        final StringBuilder errorMessage = new StringBuilder();\n        final AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> \n                applyFunctionPrototype(program, functionAddrStr, prototype, success, errorMessage));\n        } catch (InterruptedException | InvocationTargetException e) {\n            String msg = \"Failed to set function prototype on Swing thread: \" + e.getMessage();\n            errorMessage.append(msg);\n            Msg.error(this, msg, e);\n        }\n        return new PrototypeResult(success.get(), errorMessage.toString());\n    }\n    private void applyFunctionPrototype(Program program, String functionAddrStr, String prototype, \n                                       AtomicBoolean success, StringBuilder errorMessage) {\n        try {\n            Address addr = program.getAddressFactory().getAddress(functionAddrStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) {\n                String msg = \"Could not find function at address: \" + functionAddrStr;\n                errorMessage.append(msg);\n                Msg.error(this, msg);\n                return;\n            }\n            Msg.info(this, \"Setting prototype for function \" + func.getName() + \": \" + prototype);\n            addPrototypeComment(program, func, prototype);\n            parseFunctionSignatureAndApply(program, addr, prototype, success, errorMessage);\n        } catch (Exception e) {\n            String msg = \"Error setting function prototype: \" + e.getMessage();\n            errorMessage.append(msg);\n            Msg.error(this, msg, e);\n        }\n    }\n    private void addPrototypeComment(Program program, Function func, String prototype) {\n        int txComment = program.startTransaction(\"Add prototype comment\");\n        try {\n            program.getListing().setComment(\n                func.getEntryPoint(), \n                CodeUnit.PLATE_COMMENT, \n                \"Setting prototype: \" + prototype\n            );\n        } finally {\n            program.endTransaction(txComment, true);\n        }\n    }\n    private void parseFunctionSignatureAndApply(Program program, Address addr, String prototype,\n                                              AtomicBoolean success, StringBuilder errorMessage) {\n        int txProto = program.startTransaction(\"Set function prototype\");\n        try {\n            DataTypeManager dtm = program.getDataTypeManager();\n            ghidra.app.services.DataTypeManagerService dtms = \n                tool.getService(ghidra.app.services.DataTypeManagerService.class);\n            ghidra.app.util.parser.FunctionSignatureParser parser = \n                new ghidra.app.util.parser.FunctionSignatureParser(dtm, dtms);\n            ghidra.program.model.data.FunctionDefinitionDataType sig = parser.parse(null, prototype);\n            if (sig == null) {\n                String msg = \"Failed to parse function prototype\";\n                errorMessage.append(msg);\n                Msg.error(this, msg);\n                return;\n            }\n            ghidra.app.cmd.function.ApplyFunctionSignatureCmd cmd = \n                new ghidra.app.cmd.function.ApplyFunctionSignatureCmd(\n                    addr, sig, SourceType.USER_DEFINED);\n            boolean cmdResult = cmd.applyTo(program, new ConsoleTaskMonitor());\n            if (cmdResult) {\n                success.set(true);\n                Msg.info(this, \"Successfully applied function signature\");\n            } else {\n                String msg = \"Command failed: \" + cmd.getStatusMsg();\n                errorMessage.append(msg);\n                Msg.error(this, msg);\n            }\n        } catch (Exception e) {\n            String msg = \"Error applying function signature: \" + e.getMessage();\n            errorMessage.append(msg);\n            Msg.error(this, msg, e);\n        } finally {\n            program.endTransaction(txProto, success.get());\n        }\n    }\n    private boolean setLocalVariableType(String functionAddrStr, String variableName, String newType) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        if (functionAddrStr == null || functionAddrStr.isEmpty() || \n            variableName == null || variableName.isEmpty() ||\n            newType == null || newType.isEmpty()) {\n            return false;\n        }\n        AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> \n                applyVariableType(program, functionAddrStr, variableName, newType, success));\n        } catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute set variable type on Swing thread\", e);\n        }\n        return success.get();\n    }\n    private void applyVariableType(Program program, String functionAddrStr, \n                                  String variableName, String newType, AtomicBoolean success) {\n        try {\n            Address addr = program.getAddressFactory().getAddress(functionAddrStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) {\n                Msg.error(this, \"Could not find function at address: \" + functionAddrStr);\n                return;\n            }\n            DecompileResults results = decompileFunction(func, program);\n            if (results == null || !results.decompileCompleted()) {\n                return;\n            }\n            ghidra.program.model.pcode.HighFunction highFunction = results.getHighFunction();\n            if (highFunction == null) {\n                Msg.error(this, \"No high function available\");\n                return;\n            }\n            HighSymbol symbol = findSymbolByName(highFunction, variableName);\n            if (symbol == null) {\n                Msg.error(this, \"Could not find variable '\" + variableName + \"' in decompiled function\");\n                return;\n            }\n            HighVariable highVar = symbol.getHighVariable();\n            if (highVar == null) {\n                Msg.error(this, \"No HighVariable found for symbol: \" + variableName);\n                return;\n            }\n            Msg.info(this, \"Found high variable for: \" + variableName + \n                     \" with current type \" + highVar.getDataType().getName());\n            DataTypeManager dtm = program.getDataTypeManager();\n            DataType dataType = resolveDataType(dtm, newType);\n            if (dataType == null) {\n                Msg.error(this, \"Could not resolve data type: \" + newType);\n                return;\n            }\n            Msg.info(this, \"Using data type: \" + dataType.getName() + \" for variable \" + variableName);\n            updateVariableType(program, symbol, dataType, success);\n        } catch (Exception e) {\n            Msg.error(this, \"Error setting variable type: \" + e.getMessage());\n        }\n    }\n    private HighSymbol findSymbolByName(ghidra.program.model.pcode.HighFunction highFunction, String variableName) {\n        Iterator<HighSymbol> symbols = highFunction.getLocalSymbolMap().getSymbols();\n        while (symbols.hasNext()) {\n            HighSymbol s = symbols.next();\n            if (s.getName().equals(variableName)) {\n                return s;\n            }\n        }\n        return null;\n    }\n    private DecompileResults decompileFunction(Function func, Program program) {\n        DecompInterface decomp = new DecompInterface();\n        decomp.openProgram(program);\n        decomp.setSimplificationStyle(\"decompile\"); \n        DecompileResults results = decomp.decompileFunction(func, 60, new ConsoleTaskMonitor());\n        if (!results.decompileCompleted()) {\n            Msg.error(this, \"Could not decompile function: \" + results.getErrorMessage());\n            return null;\n        }\n        return results;\n    }\n    private void updateVariableType(Program program, HighSymbol symbol, DataType dataType, AtomicBoolean success) {\n        int tx = program.startTransaction(\"Set variable type\");\n        try {\n            HighFunctionDBUtil.updateDBVariable(\n                symbol,                \n                symbol.getName(),      \n                dataType,              \n                SourceType.USER_DEFINED \n            );\n            success.set(true);\n            Msg.info(this, \"Successfully set variable type using HighFunctionDBUtil\");\n        } catch (Exception e) {\n            Msg.error(this, \"Error setting variable type: \" + e.getMessage());\n        } finally {\n            program.endTransaction(tx, success.get());\n        }\n    }\n    private String getXrefsTo(String addressStr, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            ReferenceManager refManager = program.getReferenceManager();\n            ReferenceIterator refIter = refManager.getReferencesTo(addr);\n            List<String> refs = new ArrayList<>();\n            while (refIter.hasNext()) {\n                Reference ref = refIter.next();\n                Address fromAddr = ref.getFromAddress();\n                RefType refType = ref.getReferenceType();\n                Function fromFunc = program.getFunctionManager().getFunctionContaining(fromAddr);\n                String funcInfo = (fromFunc != null) ? \" in \" + fromFunc.getName() : \"\";\n                refs.add(String.format(\"From %s%s [%s]\", fromAddr, funcInfo, refType.getName()));\n            }\n            return paginateList(refs, offset, limit);\n        } catch (Exception e) {\n            return \"Error getting references to address: \" + e.getMessage();\n        }\n    }\n    private String getXrefsFrom(String addressStr, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            ReferenceManager refManager = program.getReferenceManager();\n            Reference[] references = refManager.getReferencesFrom(addr);\n            List<String> refs = new ArrayList<>();\n            for (Reference ref : references) {\n                Address toAddr = ref.getToAddress();\n                RefType refType = ref.getReferenceType();\n                String targetInfo = \"\";\n                Function toFunc = program.getFunctionManager().getFunctionAt(toAddr);\n                if (toFunc != null) {\n                    targetInfo = \" to function \" + toFunc.getName();\n                } else {\n                    Data data = program.getListing().getDataAt(toAddr);\n                    if (data != null) {\n                        targetInfo = \" to data \" + (data.getLabel() != null ? data.getLabel() : data.getPathName());\n                    }\n                }\n                refs.add(String.format(\"To %s%s [%s]\", toAddr, targetInfo, refType.getName()));\n            }\n            return paginateList(refs, offset, limit);\n        } catch (Exception e) {\n            return \"Error getting references from address: \" + e.getMessage();\n        }\n    }\n    private String getFunctionXrefs(String functionName, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (functionName == null || functionName.isEmpty()) return \"Function name is required\";\n        try {\n            List<String> refs = new ArrayList<>();\n            FunctionManager funcManager = program.getFunctionManager();\n            for (Function function : funcManager.getFunctions(true)) {\n                if (function.getName().equals(functionName)) {\n                    Address entryPoint = function.getEntryPoint();\n                    ReferenceIterator refIter = program.getReferenceManager().getReferencesTo(entryPoint);\n                    while (refIter.hasNext()) {\n                        Reference ref = refIter.next();\n                        Address fromAddr = ref.getFromAddress();\n                        RefType refType = ref.getReferenceType();\n                        Function fromFunc = funcManager.getFunctionContaining(fromAddr);\n                        String funcInfo = (fromFunc != null) ? \" in \" + fromFunc.getName() : \"\";\n                        refs.add(String.format(\"From %s%s [%s]\", fromAddr, funcInfo, refType.getName()));\n                    }\n                }\n            }\n            if (refs.isEmpty()) {\n                return \"No references found to function: \" + functionName;\n            }\n            return paginateList(refs, offset, limit);\n        } catch (Exception e) {\n            return \"Error getting function references: \" + e.getMessage();\n        }\n    }\n    private String listDefinedStrings(int offset, int limit, String filter) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        DataIterator dataIt = program.getListing().getDefinedData(true);\n        while (dataIt.hasNext()) {\n            Data data = dataIt.next();\n            if (data != null && isStringData(data)) {\n                String value = data.getValue() != null ? data.getValue().toString() : \"\";\n                if (filter == null || value.toLowerCase().contains(filter.toLowerCase())) {\n                    String escapedValue = escapeString(value);\n                    lines.add(String.format(\"%s: \\\"%s\\\"\", data.getAddress(), escapedValue));\n                }\n            }\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private boolean isStringData(Data data) {\n        if (data == null) return false;\n        DataType dt = data.getDataType();\n        String typeName = dt.getName().toLowerCase();\n        return typeName.contains(\"string\") || typeName.contains(\"char\") || typeName.equals(\"unicode\");\n    }\n    private String escapeString(String input) {\n        if (input == null) return \"\";\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < input.length(); i++) {\n            char c = input.charAt(i);\n            if (c >= 32 && c < 127) {\n                sb.append(c);\n            } else if (c == '\\n') {\n                sb.append(\"\\\\n\");\n            } else if (c == '\\r') {\n                sb.append(\"\\\\r\");\n            } else if (c == '\\t') {\n                sb.append(\"\\\\t\");\n            } else {\n                sb.append(String.format(\"\\\\x%02x\", (int)c & 0xFF));\n            }\n        }\n        return sb.toString();\n    }\n    private DataType resolveDataType(DataTypeManager dtm, String typeName) {\n        DataType dataType = findDataTypeByNameInAllCategories(dtm, typeName);\n        if (dataType != null) {\n            Msg.info(this, \"Found exact data type match: \" + dataType.getPathName());\n            return dataType;\n        }\n        if (typeName.startsWith(\"P\") && typeName.length() > 1) {\n            String baseTypeName = typeName.substring(1);\n            if (baseTypeName.equals(\"VOID\")) {\n                return new PointerDataType(dtm.getDataType(\"/void\"));\n            }\n            DataType baseType = findDataTypeByNameInAllCategories(dtm, baseTypeName);\n            if (baseType != null) {\n                return new PointerDataType(baseType);\n            }\n            Msg.warn(this, \"Base type not found for \" + typeName + \", defaulting to void*\");\n            return new PointerDataType(dtm.getDataType(\"/void\"));\n        }\n        switch (typeName.toLowerCase()) {\n            case \"int\":\n            case \"long\":\n                return dtm.getDataType(\"/int\");\n            case \"uint\":\n            case \"unsigned int\":\n            case \"unsigned long\":\n            case \"dword\":\n                return dtm.getDataType(\"/uint\");\n            case \"short\":\n                return dtm.getDataType(\"/short\");\n            case \"ushort\":\n            case \"unsigned short\":\n            case \"word\":\n                return dtm.getDataType(\"/ushort\");\n            case \"char\":\n            case \"byte\":\n                return dtm.getDataType(\"/char\");\n            case \"uchar\":\n            case \"unsigned char\":\n                return dtm.getDataType(\"/uchar\");\n            case \"longlong\":\n            case \"__int64\":\n                return dtm.getDataType(\"/longlong\");\n            case \"ulonglong\":\n            case \"unsigned __int64\":\n                return dtm.getDataType(\"/ulonglong\");\n            case \"bool\":\n            case \"boolean\":\n                return dtm.getDataType(\"/bool\");\n            case \"void\":\n                return dtm.getDataType(\"/void\");\n            default:\n                DataType directType = dtm.getDataType(\"/\" + typeName);\n                if (directType != null) {\n                    return directType;\n                }\n                Msg.warn(this, \"Unknown type: \" + typeName + \", defaulting to int\");\n                return dtm.getDataType(\"/int\");\n        }\n    }\n    private DataType findDataTypeByNameInAllCategories(DataTypeManager dtm, String typeName) {\n        DataType result = searchByNameInAllCategories(dtm, typeName);\n        if (result != null) {\n            return result;\n        }\n        return searchByNameInAllCategories(dtm, typeName.toLowerCase());\n    }\n    private DataType searchByNameInAllCategories(DataTypeManager dtm, String name) {\n        Iterator<DataType> allTypes = dtm.getAllDataTypes();\n        while (allTypes.hasNext()) {\n            DataType dt = allTypes.next();\n            if (dt.getName().equals(name)) {\n                return dt;\n            }\n            if (dt.getName().equalsIgnoreCase(name)) {\n                return dt;\n            }\n        }\n        return null;\n    }\n    private Map<String, String> parseQueryParams(HttpExchange exchange) {\n        Map<String, String> result = new HashMap<>();\n        String query = exchange.getRequestURI().getQuery(); \n        if (query != null) {\n            String[] pairs = query.split(\"&\");\n            for (String p : pairs) {\n                String[] kv = p.split(\"=\");\n                if (kv.length == 2) {\n                    try {\n                        String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);\n                        String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);\n                        result.put(key, value);\n                    } catch (Exception e) {\n                        Msg.error(this, \"Error decoding URL parameter\", e);\n                    }\n                }\n            }\n        }\n        return result;\n    }\n    private Map<String, String> parsePostParams(HttpExchange exchange) throws IOException {\n        byte[] body = exchange.getRequestBody().readAllBytes();\n        String bodyStr = new String(body, StandardCharsets.UTF_8);\n        Map<String, String> params = new HashMap<>();\n        for (String pair : bodyStr.split(\"&\")) {\n            String[] kv = pair.split(\"=\");\n            if (kv.length == 2) {\n                try {\n                    String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);\n                    String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);\n                    params.put(key, value);\n                } catch (Exception e) {\n                    Msg.error(this, \"Error decoding URL parameter\", e);\n                }\n            }\n        }\n        return params;\n    }\n    private String paginateList(List<String> items, int offset, int limit) {\n        int start = Math.max(0, offset);\n        int end   = Math.min(items.size(), offset + limit);\n        if (start >= items.size()) {\n            return \"\"; \n        }\n        List<String> sub = items.subList(start, end);\n        return String.join(\"\\n\", sub);\n    }\n    private int parseIntOrDefault(String val, int defaultValue) {\n        if (val == null) return defaultValue;\n        try {\n            return Integer.parseInt(val);\n        }\n        catch (NumberFormatException e) {\n            return defaultValue;\n        }\n    }\n    private String escapeNonAscii(String input) {\n        if (input == null) return \"\";\n        StringBuilder sb = new StringBuilder();\n        for (char c : input.toCharArray()) {\n            if (c >= 32 && c < 127) {\n                sb.append(c);\n            }\n            else {\n                sb.append(\"\\\\x\");\n                sb.append(Integer.toHexString(c & 0xFF));\n            }\n        }\n        return sb.toString();\n    }\n    public Program getCurrentProgram() {\n        ProgramManager pm = tool.getService(ProgramManager.class);\n        return pm != null ? pm.getCurrentProgram() : null;\n    }\n    private void sendResponse(HttpExchange exchange, String response) throws IOException {\n        byte[] bytes = response.getBytes(StandardCharsets.UTF_8);\n        exchange.getResponseHeaders().set(\"Content-Type\", \"text/plain; charset=utf-8\");\n        exchange.sendResponseHeaders(200, bytes.length);\n        try (OutputStream os = exchange.getResponseBody()) {\n            os.write(bytes);\n        }\n    }\n    @Override\n    public void dispose() {\n        if (server != null) {\n            Msg.info(this, \"Stopping GhidraMCP HTTP server...\");\n            server.stop(1); \n            server = null; \n            Msg.info(this, \"GhidraMCP HTTP server stopped.\");\n        }\n        super.dispose();\n    }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "java", "sub_task_type": null}, "context_code": [], "task_instance_info": {"created_time": "2025-08-20 20:21:22", "created_task_model": "DeepSeek-R1", "class_skeleton": "@PluginInfo(\n    status = PluginStatus.RELEASED,\n    packageName = ghidra.app.DeveloperPluginPackage.NAME,\n    category = PluginCategoryNames.ANALYSIS,\n    shortDescription = \"HTTP server plugin\",\n    description = \"Starts an embedded HTTP server to expose program data. Port configurable via Tool Options.\"\n)\npublic\nclass\nGhidraMCPPlugin\nextends Plugin\n{\nprivate HttpServer server;\nprivate static final String OPTION_CATEGORY_NAME = \"GhidraMCP HTTP Server\";\nprivate static final String PORT_OPTION_NAME = \"Server Port\";\nprivate static final int DEFAULT_PORT = 8080;\nprivate void startServer () throws IOException{}\nprivate String getAllFunctionNames (int offset, int limit){}\nprivate String getAllClassNames (int offset, int limit){}\nprivate String listSegments (int offset, int limit){}\nprivate String listImports (int offset, int limit){}\nprivate String listExports (int offset, int limit){}\nprivate String listNamespaces (int offset, int limit){}\nprivate String listDefinedData (int offset, int limit){}\nprivate String searchFunctionsByName (String searchTerm, int offset, int limit){}\nprivate String decompileFunctionByName (String name){}\nprivate boolean renameFunction (String oldName, String newName){}\nprivate void renameDataAtAddress (String addressStr, String newName){}\nprivate String renameVariableInFunction (String functionName, String oldVarName, String newVarName){}\nprotected static boolean checkFullCommit (HighSymbol highSymbol, HighFunction hfunction){}\nprivate String getFunctionByAddress (String addressStr){}\nprivate String getCurrentAddress (){}\nprivate String getCurrentFunction (){}\nprivate String listFunctions (){}\nprivate Function getFunctionForAddress (Program program, Address addr){}\nprivate String decompileFunctionByAddress (String addressStr){}\nprivate String disassembleFunction (String addressStr){}\nprivate boolean setCommentAtAddress (String addressStr, String comment, int commentType, String transactionName){}\nprivate boolean setDecompilerComment (String addressStr, String comment){}\nprivate boolean setDisassemblyComment (String addressStr, String comment){}\nprivate boolean renameFunctionByAddress (String functionAddrStr, String newName){}\nprivate void performFunctionRename (Program program, String functionAddrStr, String newName, AtomicBoolean success){}\nprivate PrototypeResult setFunctionPrototype (String functionAddrStr, String prototype){}\nprivate void applyFunctionPrototype (Program program, String functionAddrStr, String prototype, \n                                       AtomicBoolean success, StringBuilder errorMessage){}\nprivate void addPrototypeComment (Program program, Function func, String prototype){}\nprivate void parseFunctionSignatureAndApply (Program program, Address addr, String prototype,\n                                              AtomicBoolean success, StringBuilder errorMessage){}\nprivate boolean setLocalVariableType (String functionAddrStr, String variableName, String newType){}\nprivate void applyVariableType (Program program, String functionAddrStr, \n                                  String variableName, String newType, AtomicBoolean success){}\nprivate HighSymbol findSymbolByName (ghidra.program.model.pcode.HighFunction highFunction, String variableName){}\nprivate DecompileResults decompileFunction (Function func, Program program){}\nprivate void updateVariableType (Program program, HighSymbol symbol, DataType dataType, AtomicBoolean success){}\nprivate String getXrefsTo (String addressStr, int offset, int limit){}\nprivate String getXrefsFrom (String addressStr, int offset, int limit){}\nprivate String getFunctionXrefs (String functionName, int offset, int limit){}\nprivate String listDefinedStrings (int offset, int limit, String filter){}\nprivate boolean isStringData (Data data){}\nprivate String escapeString (String input){}\nprivate DataType resolveDataType (DataTypeManager dtm, String typeName){}\nprivate DataType findDataTypeByNameInAllCategories (DataTypeManager dtm, String typeName){}\nprivate DataType searchByNameInAllCategories (DataTypeManager dtm, String name){}\nprivate Map<String, String> parseQueryParams (HttpExchange exchange){}\nprivate Map<String, String> parsePostParams (HttpExchange exchange) throws IOException{}\nprivate String paginateList (List<String> items, int offset, int limit){}\nprivate int parseIntOrDefault (String val, int defaultValue){}\nprivate String escapeNonAscii (String input){}\npublic Program getCurrentProgram (){}\nprivate void sendResponse (HttpExchange exchange, String response) throws IOException{}\n@Override\n    public void dispose (){}\n}", "code_description": "This code segment functions to: Establish an embedded HTTP server that exposes program analysis capabilities through RESTful endpoints, enabling remote interaction with binary analysis data including function listings, decompilation results, cross-references, and symbolic renaming operations while providing configurable network parameters through tool options."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```java\n[TASK_BEGIN]\n@PluginInfo(\n    status = PluginStatus.RELEASED,\n    packageName = ghidra.app.DeveloperPluginPackage.NAME,\n    category = PluginCategoryNames.ANALYSIS,\n    shortDescription = \"HTTP server plugin\",\n    description = \"Starts an embedded HTTP server to expose program data. Port configurable via Tool Options.\"\n)\npublic class GhidraMCPPlugin extends Plugin {\n    private HttpServer server;\n    private static final String OPTION_CATEGORY_NAME = \"GhidraMCP HTTP Server\";\n    private static final String PORT_OPTION_NAME = \"Server Port\";\n    private static final int DEFAULT_PORT = 8080;\n\n    private void startServer() throws IOException {\n        // Server initialization logic here\n    }\n\n    private String getAllFunctionNames(int offset, int limit) {\n        return \"\";\n    }\n\n    private String getAllClassNames(int offset, int limit) {\n        return \"\";\n    }\n\n    private String listSegments(int offset, int limit) {\n        return \"\";\n    }\n\n    private String listImports(int offset, int limit) {\n        return \"\";\n    }\n\n    private String listExports(int offset, int limit) {\n        return \"\";\n    }\n\n    private String listNamespaces(int offset, int limit) {\n        return \"\";\n    }\n\n    private String listDefinedData(int offset, int limit) {\n        return \"\";\n    }\n\n    private String searchFunctionsByName(String searchTerm, int offset, int limit) {\n        return \"\";\n    }\n\n    private String decompileFunctionByName(String name) {\n        return \"\";\n    }\n\n    private boolean renameFunction(String oldName, String newName) {\n        return false;\n    }\n\n    private void renameDataAtAddress(String addressStr, String newName) {}\n\n    private String renameVariableInFunction(String functionName, String oldVarName, String newVarName) {\n        return \"\";\n    }\n\n    protected static boolean checkFullCommit(HighSymbol highSymbol, HighFunction hfunction) {\n        return false;\n    }\n\n    private String getFunctionByAddress(String addressStr) {\n        return \"\";\n    }\n\n    private String getCurrentAddress() {\n        return \"\";\n    }\n\n    private String getCurrentFunction() {\n        return \"\";\n    }\n\n    private String listFunctions() {\n        return \"\";\n    }\n\n    private Function getFunctionForAddress(Program program, Address addr) {\n        return null;\n    }\n\n    private String decompileFunctionByAddress(String addressStr) {\n        return \"\";\n    }\n\n    private String disassembleFunction(String addressStr) {\n        return \"\";\n    }\n\n    private boolean setCommentAtAddress(String addressStr, String comment, int commentType, String transactionName) {\n        return false;\n    }\n\n    private boolean setDecompilerComment(String addressStr, String comment) {\n        return false;\n    }\n\n    private boolean setDisassemblyComment(String addressStr, String comment) {\n        return false;\n    }\n\n    private boolean renameFunctionByAddress(String functionAddrStr, String newName) {\n        return false;\n    }\n\n    private void performFunctionRename(Program program, String functionAddrStr, String newName, AtomicBoolean success) {}\n\n    private PrototypeResult setFunctionPrototype(String functionAddrStr, String prototype) {\n        return null;\n    }\n\n    private void applyFunctionPrototype(Program program, String functionAddrStr, String prototype, \n                                       AtomicBoolean success, StringBuilder errorMessage) {}\n\n    private void addPrototypeComment(Program program, Function func, String prototype) {}\n\n    private void parseFunctionSignatureAndApply(Program program, Address addr, String prototype,\n                                              AtomicBoolean success, StringBuilder errorMessage) {}\n\n    private boolean setLocalVariableType(String functionAddrStr, String variableName, String newType) {\n        return false;\n    }\n\n    private void applyVariableType(Program program, String functionAddrStr, \n                                  String variableName, String newType, AtomicBoolean success) {}\n\n    private HighSymbol findSymbolByName(HighFunction highFunction, String variableName) {\n        return null;\n    }\n\n    private DecompileResults decompileFunction(Function func, Program program) {\n        return null;\n    }\n\n    private void updateVariableType(Program program, HighSymbol symbol, DataType dataType, AtomicBoolean success) {}\n\n    private String getXrefsTo(String addressStr, int offset, int limit) {\n        return \"\";\n    }\n\n    private String getXrefsFrom(String addressStr, int offset, int limit) {\n        return \"\";\n    }\n\n    private String getFunctionXrefs(String functionName, int offset, int limit) {\n        return \"\";\n    }\n\n    private String listDefinedStrings(int offset, int limit, String filter) {\n        return \"\";\n    }\n\n    private boolean isStringData(Data data) {\n        return false;\n    }\n\n    private String escapeString(String input) {\n        return \"\";\n    }\n\n    private DataType resolveDataType(DataTypeManager dtm, String typeName) {\n        return null;\n    }\n\n    private DataType findDataTypeByNameInAllCategories(DataTypeManager dtm, String typeName) {\n        return null;\n    }\n\n    private DataType searchByNameInAllCategories(DataTypeManager dtm, String name) {\n        return null;\n    }\n\n    private Map<String, String> parseQueryParams(HttpExchange exchange) {\n        return null;\n    }\n\n    private Map<String, String> parsePostParams(HttpExchange exchange) throws IOException {\n        return null;\n    }\n\n    private String paginateList(List<String> items, int offset, int limit) {\n        return \"\";\n    }\n\n    private int parseIntOrDefault(String val, int defaultValue) {\n        return 0;\n    }\n\n    private String escapeNonAscii(String input) {\n        return \"\";\n    }\n\n    public Program getCurrentProgram() {\n        return null;\n    }\n\n    private void sendResponse(HttpExchange exchange, String response) throws IOException {}\n\n    @Override\n    public void dispose() {\n        // Cleanup logic here\n    }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-22-44"}, "editdistance_info": {"edit_distance": 10.1718, "calculate_time": "2025-08-20 20:22:44", "true_code_clean": "@PluginInfo(\n    status = PluginStatus.RELEASED,\n    packageName = ghidra.app.DeveloperPluginPackage.NAME,\n    category = PluginCategoryNames.ANALYSIS,\n    shortDescription = \"HTTP server plugin\",\n    description = \"Starts an embedded HTTP server to expose program data. Port configurable via Tool Options.\"\n)\npublic class GhidraMCPPlugin extends Plugin {\n    private HttpServer server;\n    private static final String OPTION_CATEGORY_NAME = \"GhidraMCP HTTP Server\";\n    private static final String PORT_OPTION_NAME = \"Server Port\";\n    private static final int DEFAULT_PORT = 8080;\n    public GhidraMCPPlugin(PluginTool tool) {\n        super(tool);\n        Msg.info(this, \"GhidraMCPPlugin loading...\");\n        Options options = tool.getOptions(OPTION_CATEGORY_NAME);\n        options.registerOption(PORT_OPTION_NAME, DEFAULT_PORT,\n            null, \n            \"The network port number the embedded HTTP server will listen on. \" +\n            \"Requires Ghidra restart or plugin reload to take effect after changing.\");\n        try {\n            startServer();\n        }\n        catch (IOException e) {\n            Msg.error(this, \"Failed to start HTTP server\", e);\n        }\n        Msg.info(this, \"GhidraMCPPlugin loaded!\");\n    }\n    private void startServer() throws IOException {\n        Options options = tool.getOptions(OPTION_CATEGORY_NAME);\n        int port = options.getInt(PORT_OPTION_NAME, DEFAULT_PORT);\n        if (server != null) {\n            Msg.info(this, \"Stopping existing HTTP server before starting new one.\");\n            server.stop(0);\n            server = null;\n        }\n        server = HttpServer.create(new InetSocketAddress(port), 0);\n        server.createContext(\"/methods\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, getAllFunctionNames(offset, limit));\n        });\n        server.createContext(\"/classes\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, getAllClassNames(offset, limit));\n        });\n        server.createContext(\"/decompile\", exchange -> {\n            String name = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);\n            sendResponse(exchange, decompileFunctionByName(name));\n        });\n        server.createContext(\"/renameFunction\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String response = renameFunction(params.get(\"oldName\"), params.get(\"newName\"))\n                    ? \"Renamed successfully\" : \"Rename failed\";\n            sendResponse(exchange, response);\n        });\n        server.createContext(\"/renameData\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            renameDataAtAddress(params.get(\"address\"), params.get(\"newName\"));\n            sendResponse(exchange, \"Rename data attempted\");\n        });\n        server.createContext(\"/renameVariable\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionName = params.get(\"functionName\");\n            String oldName = params.get(\"oldName\");\n            String newName = params.get(\"newName\");\n            String result = renameVariableInFunction(functionName, oldName, newName);\n            sendResponse(exchange, result);\n        });\n        server.createContext(\"/segments\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listSegments(offset, limit));\n        });\n        server.createContext(\"/imports\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listImports(offset, limit));\n        });\n        server.createContext(\"/exports\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listExports(offset, limit));\n        });\n        server.createContext(\"/namespaces\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listNamespaces(offset, limit));\n        });\n        server.createContext(\"/data\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit  = parseIntOrDefault(qparams.get(\"limit\"),  100);\n            sendResponse(exchange, listDefinedData(offset, limit));\n        });\n        server.createContext(\"/searchFunctions\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String searchTerm = qparams.get(\"query\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, searchFunctionsByName(searchTerm, offset, limit));\n        });\n        server.createContext(\"/get_function_by_address\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            sendResponse(exchange, getFunctionByAddress(address));\n        });\n        server.createContext(\"/get_current_address\", exchange -> {\n            sendResponse(exchange, getCurrentAddress());\n        });\n        server.createContext(\"/get_current_function\", exchange -> {\n            sendResponse(exchange, getCurrentFunction());\n        });\n        server.createContext(\"/list_functions\", exchange -> {\n            sendResponse(exchange, listFunctions());\n        });\n        server.createContext(\"/decompile_function\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            sendResponse(exchange, decompileFunctionByAddress(address));\n        });\n        server.createContext(\"/disassemble_function\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            sendResponse(exchange, disassembleFunction(address));\n        });\n        server.createContext(\"/set_decompiler_comment\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String address = params.get(\"address\");\n            String comment = params.get(\"comment\");\n            boolean success = setDecompilerComment(address, comment);\n            sendResponse(exchange, success ? \"Comment set successfully\" : \"Failed to set comment\");\n        });\n        server.createContext(\"/set_disassembly_comment\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String address = params.get(\"address\");\n            String comment = params.get(\"comment\");\n            boolean success = setDisassemblyComment(address, comment);\n            sendResponse(exchange, success ? \"Comment set successfully\" : \"Failed to set comment\");\n        });\n        server.createContext(\"/rename_function_by_address\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionAddress = params.get(\"function_address\");\n            String newName = params.get(\"new_name\");\n            boolean success = renameFunctionByAddress(functionAddress, newName);\n            sendResponse(exchange, success ? \"Function renamed successfully\" : \"Failed to rename function\");\n        });\n        server.createContext(\"/set_function_prototype\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionAddress = params.get(\"function_address\");\n            String prototype = params.get(\"prototype\");\n            PrototypeResult result = setFunctionPrototype(functionAddress, prototype);\n            if (result.isSuccess()) {\n                String successMsg = \"Function prototype set successfully\";\n                if (!result.getErrorMessage().isEmpty()) {\n                    successMsg += \"\\n\\nWarnings/Debug Info:\\n\" + result.getErrorMessage();\n                }\n                sendResponse(exchange, successMsg);\n            } else {\n                sendResponse(exchange, \"Failed to set function prototype: \" + result.getErrorMessage());\n            }\n        });\n        server.createContext(\"/set_local_variable_type\", exchange -> {\n            Map<String, String> params = parsePostParams(exchange);\n            String functionAddress = params.get(\"function_address\");\n            String variableName = params.get(\"variable_name\");\n            String newType = params.get(\"new_type\");\n            StringBuilder responseMsg = new StringBuilder();\n            responseMsg.append(\"Setting variable type: \").append(variableName)\n                      .append(\" to \").append(newType)\n                      .append(\" in function at \").append(functionAddress).append(\"\\n\\n\");\n            Program program = getCurrentProgram();\n            if (program != null) {\n                DataTypeManager dtm = program.getDataTypeManager();\n                DataType directType = findDataTypeByNameInAllCategories(dtm, newType);\n                if (directType != null) {\n                    responseMsg.append(\"Found type: \").append(directType.getPathName()).append(\"\\n\");\n                } else if (newType.startsWith(\"P\") && newType.length() > 1) {\n                    String baseTypeName = newType.substring(1);\n                    DataType baseType = findDataTypeByNameInAllCategories(dtm, baseTypeName);\n                    if (baseType != null) {\n                        responseMsg.append(\"Found base type for pointer: \").append(baseType.getPathName()).append(\"\\n\");\n                    } else {\n                        responseMsg.append(\"Base type not found for pointer: \").append(baseTypeName).append(\"\\n\");\n                    }\n                } else {\n                    responseMsg.append(\"Type not found directly: \").append(newType).append(\"\\n\");\n                }\n            }\n            boolean success = setLocalVariableType(functionAddress, variableName, newType);\n            String successMsg = success ? \"Variable type set successfully\" : \"Failed to set variable type\";\n            responseMsg.append(\"\\nResult: \").append(successMsg);\n            sendResponse(exchange, responseMsg.toString());\n        });\n        server.createContext(\"/xrefs_to\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, getXrefsTo(address, offset, limit));\n        });\n        server.createContext(\"/xrefs_from\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String address = qparams.get(\"address\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, getXrefsFrom(address, offset, limit));\n        });\n        server.createContext(\"/function_xrefs\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            String name = qparams.get(\"name\");\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            sendResponse(exchange, getFunctionXrefs(name, offset, limit));\n        });\n        server.createContext(\"/strings\", exchange -> {\n            Map<String, String> qparams = parseQueryParams(exchange);\n            int offset = parseIntOrDefault(qparams.get(\"offset\"), 0);\n            int limit = parseIntOrDefault(qparams.get(\"limit\"), 100);\n            String filter = qparams.get(\"filter\");\n            sendResponse(exchange, listDefinedStrings(offset, limit, filter));\n        });\n        server.setExecutor(null);\n        new Thread(() -> {\n            try {\n                server.start();\n                Msg.info(this, \"GhidraMCP HTTP server started on port \" + port);\n            } catch (Exception e) {\n                Msg.error(this, \"Failed to start HTTP server on port \" + port + \". Port might be in use.\", e);\n                server = null; \n            }\n        }, \"GhidraMCP-HTTP-Server\").start();\n    }\n    private String getAllFunctionNames(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> names = new ArrayList<>();\n        for (Function f : program.getFunctionManager().getFunctions(true)) {\n            names.add(f.getName());\n        }\n        return paginateList(names, offset, limit);\n    }\n    private String getAllClassNames(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        Set<String> classNames = new HashSet<>();\n        for (Symbol symbol : program.getSymbolTable().getAllSymbols(true)) {\n            Namespace ns = symbol.getParentNamespace();\n            if (ns != null && !ns.isGlobal()) {\n                classNames.add(ns.getName());\n            }\n        }\n        List<String> sorted = new ArrayList<>(classNames);\n        Collections.sort(sorted);\n        return paginateList(sorted, offset, limit);\n    }\n    private String listSegments(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        for (MemoryBlock block : program.getMemory().getBlocks()) {\n            lines.add(String.format(\"%s: %s - %s\", block.getName(), block.getStart(), block.getEnd()));\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String listImports(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        for (Symbol symbol : program.getSymbolTable().getExternalSymbols()) {\n            lines.add(symbol.getName() + \" -> \" + symbol.getAddress());\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String listExports(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        SymbolTable table = program.getSymbolTable();\n        SymbolIterator it = table.getAllSymbols(true);\n        List<String> lines = new ArrayList<>();\n        while (it.hasNext()) {\n            Symbol s = it.next();\n            if (s.isExternalEntryPoint()) {\n                lines.add(s.getName() + \" -> \" + s.getAddress());\n            }\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String listNamespaces(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        Set<String> namespaces = new HashSet<>();\n        for (Symbol symbol : program.getSymbolTable().getAllSymbols(true)) {\n            Namespace ns = symbol.getParentNamespace();\n            if (ns != null && !(ns instanceof GlobalNamespace)) {\n                namespaces.add(ns.getName());\n            }\n        }\n        List<String> sorted = new ArrayList<>(namespaces);\n        Collections.sort(sorted);\n        return paginateList(sorted, offset, limit);\n    }\n    private String listDefinedData(int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        for (MemoryBlock block : program.getMemory().getBlocks()) {\n            DataIterator it = program.getListing().getDefinedData(block.getStart(), true);\n            while (it.hasNext()) {\n                Data data = it.next();\n                if (block.contains(data.getAddress())) {\n                    String label   = data.getLabel() != null ? data.getLabel() : \"(unnamed)\";\n                    String valRepr = data.getDefaultValueRepresentation();\n                    lines.add(String.format(\"%s: %s = %s\",\n                        data.getAddress(),\n                        escapeNonAscii(label),\n                        escapeNonAscii(valRepr)\n                    ));\n                }\n            }\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private String searchFunctionsByName(String searchTerm, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (searchTerm == null || searchTerm.isEmpty()) return \"Search term is required\";\n        List<String> matches = new ArrayList<>();\n        for (Function func : program.getFunctionManager().getFunctions(true)) {\n            String name = func.getName();\n            if (name.toLowerCase().contains(searchTerm.toLowerCase())) {\n                matches.add(String.format(\"%s @ %s\", name, func.getEntryPoint()));\n            }\n        }\n        Collections.sort(matches);\n        if (matches.isEmpty()) {\n            return \"No functions matching '\" + searchTerm + \"'\";\n        }\n        return paginateList(matches, offset, limit);\n    }    \n    private String decompileFunctionByName(String name) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        DecompInterface decomp = new DecompInterface();\n        decomp.openProgram(program);\n        for (Function func : program.getFunctionManager().getFunctions(true)) {\n            if (func.getName().equals(name)) {\n                DecompileResults result =\n                    decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());\n                if (result != null && result.decompileCompleted()) {\n                    return result.getDecompiledFunction().getC();\n                } else {\n                    return \"Decompilation failed\";\n                }\n            }\n        }\n        return \"Function not found\";\n    }\n    private boolean renameFunction(String oldName, String newName) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        AtomicBoolean successFlag = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                int tx = program.startTransaction(\"Rename function via HTTP\");\n                try {\n                    for (Function func : program.getFunctionManager().getFunctions(true)) {\n                        if (func.getName().equals(oldName)) {\n                            func.setName(newName, SourceType.USER_DEFINED);\n                            successFlag.set(true);\n                            break;\n                        }\n                    }\n                }\n                catch (Exception e) {\n                    Msg.error(this, \"Error renaming function\", e);\n                }\n                finally {\n                    successFlag.set(program.endTransaction(tx, successFlag.get()));\n                }\n            });\n        }\n        catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute rename on Swing thread\", e);\n        }\n        return successFlag.get();\n    }\n    private void renameDataAtAddress(String addressStr, String newName) {\n        Program program = getCurrentProgram();\n        if (program == null) return;\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                int tx = program.startTransaction(\"Rename data\");\n                try {\n                    Address addr = program.getAddressFactory().getAddress(addressStr);\n                    Listing listing = program.getListing();\n                    Data data = listing.getDefinedDataAt(addr);\n                    if (data != null) {\n                        SymbolTable symTable = program.getSymbolTable();\n                        Symbol symbol = symTable.getPrimarySymbol(addr);\n                        if (symbol != null) {\n                            symbol.setName(newName, SourceType.USER_DEFINED);\n                        } else {\n                            symTable.createLabel(addr, newName, SourceType.USER_DEFINED);\n                        }\n                    }\n                }\n                catch (Exception e) {\n                    Msg.error(this, \"Rename data error\", e);\n                }\n                finally {\n                    program.endTransaction(tx, true);\n                }\n            });\n        }\n        catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute rename data on Swing thread\", e);\n        }\n    }\n    private String renameVariableInFunction(String functionName, String oldVarName, String newVarName) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        DecompInterface decomp = new DecompInterface();\n        decomp.openProgram(program);\n        Function func = null;\n        for (Function f : program.getFunctionManager().getFunctions(true)) {\n            if (f.getName().equals(functionName)) {\n                func = f;\n                break;\n            }\n        }\n        if (func == null) {\n            return \"Function not found\";\n        }\n        DecompileResults result = decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());\n        if (result == null || !result.decompileCompleted()) {\n            return \"Decompilation failed\";\n        }\n        HighFunction highFunction = result.getHighFunction();\n        if (highFunction == null) {\n            return \"Decompilation failed (no high function)\";\n        }\n        LocalSymbolMap localSymbolMap = highFunction.getLocalSymbolMap();\n        if (localSymbolMap == null) {\n            return \"Decompilation failed (no local symbol map)\";\n        }\n        HighSymbol highSymbol = null;\n        Iterator<HighSymbol> symbols = localSymbolMap.getSymbols();\n        while (symbols.hasNext()) {\n            HighSymbol symbol = symbols.next();\n            String symbolName = symbol.getName();\n            if (symbolName.equals(oldVarName)) {\n                highSymbol = symbol;\n            }\n            if (symbolName.equals(newVarName)) {\n                return \"Error: A variable with name '\" + newVarName + \"' already exists in this function\";\n            }\n        }\n        if (highSymbol == null) {\n            return \"Variable not found\";\n        }\n        boolean commitRequired = checkFullCommit(highSymbol, highFunction);\n        final HighSymbol finalHighSymbol = highSymbol;\n        final Function finalFunction = func;\n        AtomicBoolean successFlag = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {           \n                int tx = program.startTransaction(\"Rename variable\");\n                try {\n                    if (commitRequired) {\n                        HighFunctionDBUtil.commitParamsToDatabase(highFunction, false,\n                            ReturnCommitOption.NO_COMMIT, finalFunction.getSignatureSource());\n                    }\n                    HighFunctionDBUtil.updateDBVariable(\n                        finalHighSymbol,\n                        newVarName,\n                        null,\n                        SourceType.USER_DEFINED\n                    );\n                    successFlag.set(true);\n                }\n                catch (Exception e) {\n                    Msg.error(this, \"Failed to rename variable\", e);\n                }\n                finally {\n                    successFlag.set(program.endTransaction(tx, true));\n                }\n            });\n        } catch (InterruptedException | InvocationTargetException e) {\n            String errorMsg = \"Failed to execute rename on Swing thread: \" + e.getMessage();\n            Msg.error(this, errorMsg, e);\n            return errorMsg;\n        }\n        return successFlag.get() ? \"Variable renamed\" : \"Failed to rename variable\";\n    }\n\tprotected static boolean checkFullCommit(HighSymbol highSymbol, HighFunction hfunction) {\n\t\tif (highSymbol != null && !highSymbol.isParameter()) {\n\t\t\treturn false;\n\t\t}\n\t\tFunction function = hfunction.getFunction();\n\t\tParameter[] parameters = function.getParameters();\n\t\tLocalSymbolMap localSymbolMap = hfunction.getLocalSymbolMap();\n\t\tint numParams = localSymbolMap.getNumParams();\n\t\tif (numParams != parameters.length) {\n\t\t\treturn true;\n\t\t}\n\t\tfor (int i = 0; i < numParams; i++) {\n\t\t\tHighSymbol param = localSymbolMap.getParamSymbol(i);\n\t\t\tif (param.getCategoryIndex() != i) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tVariableStorage storage = param.getStorage();\n\t\t\tif (0 != storage.compareTo(parameters[i].getVariableStorage())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n    private String getFunctionByAddress(String addressStr) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            Function func = program.getFunctionManager().getFunctionAt(addr);\n            if (func == null) return \"No function found at address \" + addressStr;\n            return String.format(\"Function: %s at %s\\nSignature: %s\\nEntry: %s\\nBody: %s - %s\",\n                func.getName(),\n                func.getEntryPoint(),\n                func.getSignature(),\n                func.getEntryPoint(),\n                func.getBody().getMinAddress(),\n                func.getBody().getMaxAddress());\n        } catch (Exception e) {\n            return \"Error getting function: \" + e.getMessage();\n        }\n    }\n    private String getCurrentAddress() {\n        CodeViewerService service = tool.getService(CodeViewerService.class);\n        if (service == null) return \"Code viewer service not available\";\n        ProgramLocation location = service.getCurrentLocation();\n        return (location != null) ? location.getAddress().toString() : \"No current location\";\n    }\n    private String getCurrentFunction() {\n        CodeViewerService service = tool.getService(CodeViewerService.class);\n        if (service == null) return \"Code viewer service not available\";\n        ProgramLocation location = service.getCurrentLocation();\n        if (location == null) return \"No current location\";\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        Function func = program.getFunctionManager().getFunctionContaining(location.getAddress());\n        if (func == null) return \"No function at current location: \" + location.getAddress();\n        return String.format(\"Function: %s at %s\\nSignature: %s\",\n            func.getName(),\n            func.getEntryPoint(),\n            func.getSignature());\n    }\n    private String listFunctions() {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        StringBuilder result = new StringBuilder();\n        for (Function func : program.getFunctionManager().getFunctions(true)) {\n            result.append(String.format(\"%s at %s\\n\", \n                func.getName(), \n                func.getEntryPoint()));\n        }\n        return result.toString();\n    }\n    private Function getFunctionForAddress(Program program, Address addr) {\n        Function func = program.getFunctionManager().getFunctionAt(addr);\n        if (func == null) {\n            func = program.getFunctionManager().getFunctionContaining(addr);\n        }\n        return func;\n    }\n    private String decompileFunctionByAddress(String addressStr) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) return \"No function found at or containing address \" + addressStr;\n            DecompInterface decomp = new DecompInterface();\n            decomp.openProgram(program);\n            DecompileResults result = decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());\n            return (result != null && result.decompileCompleted()) \n                ? result.getDecompiledFunction().getC() \n                : \"Decompilation failed\";\n        } catch (Exception e) {\n            return \"Error decompiling function: \" + e.getMessage();\n        }\n    }\n    private String disassembleFunction(String addressStr) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) return \"No function found at or containing address \" + addressStr;\n            StringBuilder result = new StringBuilder();\n            Listing listing = program.getListing();\n            Address start = func.getEntryPoint();\n            Address end = func.getBody().getMaxAddress();\n            InstructionIterator instructions = listing.getInstructions(start, true);\n            while (instructions.hasNext()) {\n                Instruction instr = instructions.next();\n                if (instr.getAddress().compareTo(end) > 0) {\n                    break; \n                }\n                String comment = listing.getComment(CodeUnit.EOL_COMMENT, instr.getAddress());\n                comment = (comment != null) ? \"; \" + comment : \"\";\n                result.append(String.format(\"%s: %s %s\\n\", \n                    instr.getAddress(), \n                    instr.toString(),\n                    comment));\n            }\n            return result.toString();\n        } catch (Exception e) {\n            return \"Error disassembling function: \" + e.getMessage();\n        }\n    }    \n    private boolean setCommentAtAddress(String addressStr, String comment, int commentType, String transactionName) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        if (addressStr == null || addressStr.isEmpty() || comment == null) return false;\n        AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                int tx = program.startTransaction(transactionName);\n                try {\n                    Address addr = program.getAddressFactory().getAddress(addressStr);\n                    program.getListing().setComment(addr, commentType, comment);\n                    success.set(true);\n                } catch (Exception e) {\n                    Msg.error(this, \"Error setting \" + transactionName.toLowerCase(), e);\n                } finally {\n                    success.set(program.endTransaction(tx, success.get()));\n                }\n            });\n        } catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute \" + transactionName.toLowerCase() + \" on Swing thread\", e);\n        }\n        return success.get();\n    }\n    private boolean setDecompilerComment(String addressStr, String comment) {\n        return setCommentAtAddress(addressStr, comment, CodeUnit.PRE_COMMENT, \"Set decompiler comment\");\n    }\n    private boolean setDisassemblyComment(String addressStr, String comment) {\n        return setCommentAtAddress(addressStr, comment, CodeUnit.EOL_COMMENT, \"Set disassembly comment\");\n    }\n    private static class PrototypeResult {\n        private final boolean success;\n        private final String errorMessage;\n        public PrototypeResult(boolean success, String errorMessage) {\n            this.success = success;\n            this.errorMessage = errorMessage;\n        }\n        public boolean isSuccess() {\n            return success;\n        }\n        public String getErrorMessage() {\n            return errorMessage;\n        }\n    }\n    private boolean renameFunctionByAddress(String functionAddrStr, String newName) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        if (functionAddrStr == null || functionAddrStr.isEmpty() || \n            newName == null || newName.isEmpty()) {\n            return false;\n        }\n        AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> {\n                performFunctionRename(program, functionAddrStr, newName, success);\n            });\n        } catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute rename function on Swing thread\", e);\n        }\n        return success.get();\n    }\n    private void performFunctionRename(Program program, String functionAddrStr, String newName, AtomicBoolean success) {\n        int tx = program.startTransaction(\"Rename function by address\");\n        try {\n            Address addr = program.getAddressFactory().getAddress(functionAddrStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) {\n                Msg.error(this, \"Could not find function at address: \" + functionAddrStr);\n                return;\n            }\n            func.setName(newName, SourceType.USER_DEFINED);\n            success.set(true);\n        } catch (Exception e) {\n            Msg.error(this, \"Error renaming function by address\", e);\n        } finally {\n            program.endTransaction(tx, success.get());\n        }\n    }\n    private PrototypeResult setFunctionPrototype(String functionAddrStr, String prototype) {\n        Program program = getCurrentProgram();\n        if (program == null) return new PrototypeResult(false, \"No program loaded\");\n        if (functionAddrStr == null || functionAddrStr.isEmpty()) {\n            return new PrototypeResult(false, \"Function address is required\");\n        }\n        if (prototype == null || prototype.isEmpty()) {\n            return new PrototypeResult(false, \"Function prototype is required\");\n        }\n        final StringBuilder errorMessage = new StringBuilder();\n        final AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> \n                applyFunctionPrototype(program, functionAddrStr, prototype, success, errorMessage));\n        } catch (InterruptedException | InvocationTargetException e) {\n            String msg = \"Failed to set function prototype on Swing thread: \" + e.getMessage();\n            errorMessage.append(msg);\n            Msg.error(this, msg, e);\n        }\n        return new PrototypeResult(success.get(), errorMessage.toString());\n    }\n    private void applyFunctionPrototype(Program program, String functionAddrStr, String prototype, \n                                       AtomicBoolean success, StringBuilder errorMessage) {\n        try {\n            Address addr = program.getAddressFactory().getAddress(functionAddrStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) {\n                String msg = \"Could not find function at address: \" + functionAddrStr;\n                errorMessage.append(msg);\n                Msg.error(this, msg);\n                return;\n            }\n            Msg.info(this, \"Setting prototype for function \" + func.getName() + \": \" + prototype);\n            addPrototypeComment(program, func, prototype);\n            parseFunctionSignatureAndApply(program, addr, prototype, success, errorMessage);\n        } catch (Exception e) {\n            String msg = \"Error setting function prototype: \" + e.getMessage();\n            errorMessage.append(msg);\n            Msg.error(this, msg, e);\n        }\n    }\n    private void addPrototypeComment(Program program, Function func, String prototype) {\n        int txComment = program.startTransaction(\"Add prototype comment\");\n        try {\n            program.getListing().setComment(\n                func.getEntryPoint(), \n                CodeUnit.PLATE_COMMENT, \n                \"Setting prototype: \" + prototype\n            );\n        } finally {\n            program.endTransaction(txComment, true);\n        }\n    }\n    private void parseFunctionSignatureAndApply(Program program, Address addr, String prototype,\n                                              AtomicBoolean success, StringBuilder errorMessage) {\n        int txProto = program.startTransaction(\"Set function prototype\");\n        try {\n            DataTypeManager dtm = program.getDataTypeManager();\n            ghidra.app.services.DataTypeManagerService dtms = \n                tool.getService(ghidra.app.services.DataTypeManagerService.class);\n            ghidra.app.util.parser.FunctionSignatureParser parser = \n                new ghidra.app.util.parser.FunctionSignatureParser(dtm, dtms);\n            ghidra.program.model.data.FunctionDefinitionDataType sig = parser.parse(null, prototype);\n            if (sig == null) {\n                String msg = \"Failed to parse function prototype\";\n                errorMessage.append(msg);\n                Msg.error(this, msg);\n                return;\n            }\n            ghidra.app.cmd.function.ApplyFunctionSignatureCmd cmd = \n                new ghidra.app.cmd.function.ApplyFunctionSignatureCmd(\n                    addr, sig, SourceType.USER_DEFINED);\n            boolean cmdResult = cmd.applyTo(program, new ConsoleTaskMonitor());\n            if (cmdResult) {\n                success.set(true);\n                Msg.info(this, \"Successfully applied function signature\");\n            } else {\n                String msg = \"Command failed: \" + cmd.getStatusMsg();\n                errorMessage.append(msg);\n                Msg.error(this, msg);\n            }\n        } catch (Exception e) {\n            String msg = \"Error applying function signature: \" + e.getMessage();\n            errorMessage.append(msg);\n            Msg.error(this, msg, e);\n        } finally {\n            program.endTransaction(txProto, success.get());\n        }\n    }\n    private boolean setLocalVariableType(String functionAddrStr, String variableName, String newType) {\n        Program program = getCurrentProgram();\n        if (program == null) return false;\n        if (functionAddrStr == null || functionAddrStr.isEmpty() || \n            variableName == null || variableName.isEmpty() ||\n            newType == null || newType.isEmpty()) {\n            return false;\n        }\n        AtomicBoolean success = new AtomicBoolean(false);\n        try {\n            SwingUtilities.invokeAndWait(() -> \n                applyVariableType(program, functionAddrStr, variableName, newType, success));\n        } catch (InterruptedException | InvocationTargetException e) {\n            Msg.error(this, \"Failed to execute set variable type on Swing thread\", e);\n        }\n        return success.get();\n    }\n    private void applyVariableType(Program program, String functionAddrStr, \n                                  String variableName, String newType, AtomicBoolean success) {\n        try {\n            Address addr = program.getAddressFactory().getAddress(functionAddrStr);\n            Function func = getFunctionForAddress(program, addr);\n            if (func == null) {\n                Msg.error(this, \"Could not find function at address: \" + functionAddrStr);\n                return;\n            }\n            DecompileResults results = decompileFunction(func, program);\n            if (results == null || !results.decompileCompleted()) {\n                return;\n            }\n            ghidra.program.model.pcode.HighFunction highFunction = results.getHighFunction();\n            if (highFunction == null) {\n                Msg.error(this, \"No high function available\");\n                return;\n            }\n            HighSymbol symbol = findSymbolByName(highFunction, variableName);\n            if (symbol == null) {\n                Msg.error(this, \"Could not find variable '\" + variableName + \"' in decompiled function\");\n                return;\n            }\n            HighVariable highVar = symbol.getHighVariable();\n            if (highVar == null) {\n                Msg.error(this, \"No HighVariable found for symbol: \" + variableName);\n                return;\n            }\n            Msg.info(this, \"Found high variable for: \" + variableName + \n                     \" with current type \" + highVar.getDataType().getName());\n            DataTypeManager dtm = program.getDataTypeManager();\n            DataType dataType = resolveDataType(dtm, newType);\n            if (dataType == null) {\n                Msg.error(this, \"Could not resolve data type: \" + newType);\n                return;\n            }\n            Msg.info(this, \"Using data type: \" + dataType.getName() + \" for variable \" + variableName);\n            updateVariableType(program, symbol, dataType, success);\n        } catch (Exception e) {\n            Msg.error(this, \"Error setting variable type: \" + e.getMessage());\n        }\n    }\n    private HighSymbol findSymbolByName(ghidra.program.model.pcode.HighFunction highFunction, String variableName) {\n        Iterator<HighSymbol> symbols = highFunction.getLocalSymbolMap().getSymbols();\n        while (symbols.hasNext()) {\n            HighSymbol s = symbols.next();\n            if (s.getName().equals(variableName)) {\n                return s;\n            }\n        }\n        return null;\n    }\n    private DecompileResults decompileFunction(Function func, Program program) {\n        DecompInterface decomp = new DecompInterface();\n        decomp.openProgram(program);\n        decomp.setSimplificationStyle(\"decompile\"); \n        DecompileResults results = decomp.decompileFunction(func, 60, new ConsoleTaskMonitor());\n        if (!results.decompileCompleted()) {\n            Msg.error(this, \"Could not decompile function: \" + results.getErrorMessage());\n            return null;\n        }\n        return results;\n    }\n    private void updateVariableType(Program program, HighSymbol symbol, DataType dataType, AtomicBoolean success) {\n        int tx = program.startTransaction(\"Set variable type\");\n        try {\n            HighFunctionDBUtil.updateDBVariable(\n                symbol,                \n                symbol.getName(),      \n                dataType,              \n                SourceType.USER_DEFINED \n            );\n            success.set(true);\n            Msg.info(this, \"Successfully set variable type using HighFunctionDBUtil\");\n        } catch (Exception e) {\n            Msg.error(this, \"Error setting variable type: \" + e.getMessage());\n        } finally {\n            program.endTransaction(tx, success.get());\n        }\n    }\n    private String getXrefsTo(String addressStr, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            ReferenceManager refManager = program.getReferenceManager();\n            ReferenceIterator refIter = refManager.getReferencesTo(addr);\n            List<String> refs = new ArrayList<>();\n            while (refIter.hasNext()) {\n                Reference ref = refIter.next();\n                Address fromAddr = ref.getFromAddress();\n                RefType refType = ref.getReferenceType();\n                Function fromFunc = program.getFunctionManager().getFunctionContaining(fromAddr);\n                String funcInfo = (fromFunc != null) ? \" in \" + fromFunc.getName() : \"\";\n                refs.add(String.format(\"From %s%s [%s]\", fromAddr, funcInfo, refType.getName()));\n            }\n            return paginateList(refs, offset, limit);\n        } catch (Exception e) {\n            return \"Error getting references to address: \" + e.getMessage();\n        }\n    }\n    private String getXrefsFrom(String addressStr, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (addressStr == null || addressStr.isEmpty()) return \"Address is required\";\n        try {\n            Address addr = program.getAddressFactory().getAddress(addressStr);\n            ReferenceManager refManager = program.getReferenceManager();\n            Reference[] references = refManager.getReferencesFrom(addr);\n            List<String> refs = new ArrayList<>();\n            for (Reference ref : references) {\n                Address toAddr = ref.getToAddress();\n                RefType refType = ref.getReferenceType();\n                String targetInfo = \"\";\n                Function toFunc = program.getFunctionManager().getFunctionAt(toAddr);\n                if (toFunc != null) {\n                    targetInfo = \" to function \" + toFunc.getName();\n                } else {\n                    Data data = program.getListing().getDataAt(toAddr);\n                    if (data != null) {\n                        targetInfo = \" to data \" + (data.getLabel() != null ? data.getLabel() : data.getPathName());\n                    }\n                }\n                refs.add(String.format(\"To %s%s [%s]\", toAddr, targetInfo, refType.getName()));\n            }\n            return paginateList(refs, offset, limit);\n        } catch (Exception e) {\n            return \"Error getting references from address: \" + e.getMessage();\n        }\n    }\n    private String getFunctionXrefs(String functionName, int offset, int limit) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        if (functionName == null || functionName.isEmpty()) return \"Function name is required\";\n        try {\n            List<String> refs = new ArrayList<>();\n            FunctionManager funcManager = program.getFunctionManager();\n            for (Function function : funcManager.getFunctions(true)) {\n                if (function.getName().equals(functionName)) {\n                    Address entryPoint = function.getEntryPoint();\n                    ReferenceIterator refIter = program.getReferenceManager().getReferencesTo(entryPoint);\n                    while (refIter.hasNext()) {\n                        Reference ref = refIter.next();\n                        Address fromAddr = ref.getFromAddress();\n                        RefType refType = ref.getReferenceType();\n                        Function fromFunc = funcManager.getFunctionContaining(fromAddr);\n                        String funcInfo = (fromFunc != null) ? \" in \" + fromFunc.getName() : \"\";\n                        refs.add(String.format(\"From %s%s [%s]\", fromAddr, funcInfo, refType.getName()));\n                    }\n                }\n            }\n            if (refs.isEmpty()) {\n                return \"No references found to function: \" + functionName;\n            }\n            return paginateList(refs, offset, limit);\n        } catch (Exception e) {\n            return \"Error getting function references: \" + e.getMessage();\n        }\n    }\n    private String listDefinedStrings(int offset, int limit, String filter) {\n        Program program = getCurrentProgram();\n        if (program == null) return \"No program loaded\";\n        List<String> lines = new ArrayList<>();\n        DataIterator dataIt = program.getListing().getDefinedData(true);\n        while (dataIt.hasNext()) {\n            Data data = dataIt.next();\n            if (data != null && isStringData(data)) {\n                String value = data.getValue() != null ? data.getValue().toString() : \"\";\n                if (filter == null || value.toLowerCase().contains(filter.toLowerCase())) {\n                    String escapedValue = escapeString(value);\n                    lines.add(String.format(\"%s: \\\"%s\\\"\", data.getAddress(), escapedValue));\n                }\n            }\n        }\n        return paginateList(lines, offset, limit);\n    }\n    private boolean isStringData(Data data) {\n        if (data == null) return false;\n        DataType dt = data.getDataType();\n        String typeName = dt.getName().toLowerCase();\n        return typeName.contains(\"string\") || typeName.contains(\"char\") || typeName.equals(\"unicode\");\n    }\n    private String escapeString(String input) {\n        if (input == null) return \"\";\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < input.length(); i++) {\n            char c = input.charAt(i);\n            if (c >= 32 && c < 127) {\n                sb.append(c);\n            } else if (c == '\\n') {\n                sb.append(\"\\\\n\");\n            } else if (c == '\\r') {\n                sb.append(\"\\\\r\");\n            } else if (c == '\\t') {\n                sb.append(\"\\\\t\");\n            } else {\n                sb.append(String.format(\"\\\\x%02x\", (int)c & 0xFF));\n            }\n        }\n        return sb.toString();\n    }\n    private DataType resolveDataType(DataTypeManager dtm, String typeName) {\n        DataType dataType = findDataTypeByNameInAllCategories(dtm, typeName);\n        if (dataType != null) {\n            Msg.info(this, \"Found exact data type match: \" + dataType.getPathName());\n            return dataType;\n        }\n        if (typeName.startsWith(\"P\") && typeName.length() > 1) {\n            String baseTypeName = typeName.substring(1);\n            if (baseTypeName.equals(\"VOID\")) {\n                return new PointerDataType(dtm.getDataType(\"/void\"));\n            }\n            DataType baseType = findDataTypeByNameInAllCategories(dtm, baseTypeName);\n            if (baseType != null) {\n                return new PointerDataType(baseType);\n            }\n            Msg.warn(this, \"Base type not found for \" + typeName + \", defaulting to void*\");\n            return new PointerDataType(dtm.getDataType(\"/void\"));\n        }\n        switch (typeName.toLowerCase()) {\n            case \"int\":\n            case \"long\":\n                return dtm.getDataType(\"/int\");\n            case \"uint\":\n            case \"unsigned int\":\n            case \"unsigned long\":\n            case \"dword\":\n                return dtm.getDataType(\"/uint\");\n            case \"short\":\n                return dtm.getDataType(\"/short\");\n            case \"ushort\":\n            case \"unsigned short\":\n            case \"word\":\n                return dtm.getDataType(\"/ushort\");\n            case \"char\":\n            case \"byte\":\n                return dtm.getDataType(\"/char\");\n            case \"uchar\":\n            case \"unsigned char\":\n                return dtm.getDataType(\"/uchar\");\n            case \"longlong\":\n            case \"__int64\":\n                return dtm.getDataType(\"/longlong\");\n            case \"ulonglong\":\n            case \"unsigned __int64\":\n                return dtm.getDataType(\"/ulonglong\");\n            case \"bool\":\n            case \"boolean\":\n                return dtm.getDataType(\"/bool\");\n            case \"void\":\n                return dtm.getDataType(\"/void\");\n            default:\n                DataType directType = dtm.getDataType(\"/\" + typeName);\n                if (directType != null) {\n                    return directType;\n                }\n                Msg.warn(this, \"Unknown type: \" + typeName + \", defaulting to int\");\n                return dtm.getDataType(\"/int\");\n        }\n    }\n    private DataType findDataTypeByNameInAllCategories(DataTypeManager dtm, String typeName) {\n        DataType result = searchByNameInAllCategories(dtm, typeName);\n        if (result != null) {\n            return result;\n        }\n        return searchByNameInAllCategories(dtm, typeName.toLowerCase());\n    }\n    private DataType searchByNameInAllCategories(DataTypeManager dtm, String name) {\n        Iterator<DataType> allTypes = dtm.getAllDataTypes();\n        while (allTypes.hasNext()) {\n            DataType dt = allTypes.next();\n            if (dt.getName().equals(name)) {\n                return dt;\n            }\n            if (dt.getName().equalsIgnoreCase(name)) {\n                return dt;\n            }\n        }\n        return null;\n    }\n    private Map<String, String> parseQueryParams(HttpExchange exchange) {\n        Map<String, String> result = new HashMap<>();\n        String query = exchange.getRequestURI().getQuery(); \n        if (query != null) {\n            String[] pairs = query.split(\"&\");\n            for (String p : pairs) {\n                String[] kv = p.split(\"=\");\n                if (kv.length == 2) {\n                    try {\n                        String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);\n                        String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);\n                        result.put(key, value);\n                    } catch (Exception e) {\n                        Msg.error(this, \"Error decoding URL parameter\", e);\n                    }\n                }\n            }\n        }\n        return result;\n    }\n    private Map<String, String> parsePostParams(HttpExchange exchange) throws IOException {\n        byte[] body = exchange.getRequestBody().readAllBytes();\n        String bodyStr = new String(body, StandardCharsets.UTF_8);\n        Map<String, String> params = new HashMap<>();\n        for (String pair : bodyStr.split(\"&\")) {\n            String[] kv = pair.split(\"=\");\n            if (kv.length == 2) {\n                try {\n                    String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);\n                    String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);\n                    params.put(key, value);\n                } catch (Exception e) {\n                    Msg.error(this, \"Error decoding URL parameter\", e);\n                }\n            }\n        }\n        return params;\n    }\n    private String paginateList(List<String> items, int offset, int limit) {\n        int start = Math.max(0, offset);\n        int end   = Math.min(items.size(), offset + limit);\n        if (start >= items.size()) {\n            return \"\"; \n        }\n        List<String> sub = items.subList(start, end);\n        return String.join(\"\\n\", sub);\n    }\n    private int parseIntOrDefault(String val, int defaultValue) {\n        if (val == null) return defaultValue;\n        try {\n            return Integer.parseInt(val);\n        }\n        catch (NumberFormatException e) {\n            return defaultValue;\n        }\n    }\n    private String escapeNonAscii(String input) {\n        if (input == null) return \"\";\n        StringBuilder sb = new StringBuilder();\n        for (char c : input.toCharArray()) {\n            if (c >= 32 && c < 127) {\n                sb.append(c);\n            }\n            else {\n                sb.append(\"\\\\x\");\n                sb.append(Integer.toHexString(c & 0xFF));\n            }\n        }\n        return sb.toString();\n    }\n    public Program getCurrentProgram() {\n        ProgramManager pm = tool.getService(ProgramManager.class);\n        return pm != null ? pm.getCurrentProgram() : null;\n    }\n    private void sendResponse(HttpExchange exchange, String response) throws IOException {\n        byte[] bytes = response.getBytes(StandardCharsets.UTF_8);\n        exchange.getResponseHeaders().set(\"Content-Type\", \"text/plain; charset=utf-8\");\n        exchange.sendResponseHeaders(200, bytes.length);\n        try (OutputStream os = exchange.getResponseBody()) {\n            os.write(bytes);\n        }\n    }\n    @Override\n    public void dispose() {\n        if (server != null) {\n            Msg.info(this, \"Stopping GhidraMCP HTTP server...\");\n            server.stop(1); \n            server = null; \n            Msg.info(this, \"GhidraMCP HTTP server stopped.\");\n        }\n        super.dispose();\n    }\n}", "predict_code_clean": "@PluginInfo(\n    status = PluginStatus.RELEASED,\n    packageName = ghidra.app.DeveloperPluginPackage.NAME,\n    category = PluginCategoryNames.ANALYSIS,\n    shortDescription = \"HTTP server plugin\",\n    description = \"Starts an embedded HTTP server to expose program data. Port configurable via Tool Options.\"\n)\npublic class GhidraMCPPlugin extends Plugin {\n    private HttpServer server;\n    private static final String OPTION_CATEGORY_NAME = \"GhidraMCP HTTP Server\";\n    private static final String PORT_OPTION_NAME = \"Server Port\";\n    private static final int DEFAULT_PORT = 8080;\n    private void startServer() throws IOException {\n    }\n    private String getAllFunctionNames(int offset, int limit) {\n        return \"\";\n    }\n    private String getAllClassNames(int offset, int limit) {\n        return \"\";\n    }\n    private String listSegments(int offset, int limit) {\n        return \"\";\n    }\n    private String listImports(int offset, int limit) {\n        return \"\";\n    }\n    private String listExports(int offset, int limit) {\n        return \"\";\n    }\n    private String listNamespaces(int offset, int limit) {\n        return \"\";\n    }\n    private String listDefinedData(int offset, int limit) {\n        return \"\";\n    }\n    private String searchFunctionsByName(String searchTerm, int offset, int limit) {\n        return \"\";\n    }\n    private String decompileFunctionByName(String name) {\n        return \"\";\n    }\n    private boolean renameFunction(String oldName, String newName) {\n        return false;\n    }\n    private void renameDataAtAddress(String addressStr, String newName) {}\n    private String renameVariableInFunction(String functionName, String oldVarName, String newVarName) {\n        return \"\";\n    }\n    protected static boolean checkFullCommit(HighSymbol highSymbol, HighFunction hfunction) {\n        return false;\n    }\n    private String getFunctionByAddress(String addressStr) {\n        return \"\";\n    }\n    private String getCurrentAddress() {\n        return \"\";\n    }\n    private String getCurrentFunction() {\n        return \"\";\n    }\n    private String listFunctions() {\n        return \"\";\n    }\n    private Function getFunctionForAddress(Program program, Address addr) {\n        return null;\n    }\n    private String decompileFunctionByAddress(String addressStr) {\n        return \"\";\n    }\n    private String disassembleFunction(String addressStr) {\n        return \"\";\n    }\n    private boolean setCommentAtAddress(String addressStr, String comment, int commentType, String transactionName) {\n        return false;\n    }\n    private boolean setDecompilerComment(String addressStr, String comment) {\n        return false;\n    }\n    private boolean setDisassemblyComment(String addressStr, String comment) {\n        return false;\n    }\n    private boolean renameFunctionByAddress(String functionAddrStr, String newName) {\n        return false;\n    }\n    private void performFunctionRename(Program program, String functionAddrStr, String newName, AtomicBoolean success) {}\n    private PrototypeResult setFunctionPrototype(String functionAddrStr, String prototype) {\n        return null;\n    }\n    private void applyFunctionPrototype(Program program, String functionAddrStr, String prototype, \n                                       AtomicBoolean success, StringBuilder errorMessage) {}\n    private void addPrototypeComment(Program program, Function func, String prototype) {}\n    private void parseFunctionSignatureAndApply(Program program, Address addr, String prototype,\n                                              AtomicBoolean success, StringBuilder errorMessage) {}\n    private boolean setLocalVariableType(String functionAddrStr, String variableName, String newType) {\n        return false;\n    }\n    private void applyVariableType(Program program, String functionAddrStr, \n                                  String variableName, String newType, AtomicBoolean success) {}\n    private HighSymbol findSymbolByName(HighFunction highFunction, String variableName) {\n        return null;\n    }\n    private DecompileResults decompileFunction(Function func, Program program) {\n        return null;\n    }\n    private void updateVariableType(Program program, HighSymbol symbol, DataType dataType, AtomicBoolean success) {}\n    private String getXrefsTo(String addressStr, int offset, int limit) {\n        return \"\";\n    }\n    private String getXrefsFrom(String addressStr, int offset, int limit) {\n        return \"\";\n    }\n    private String getFunctionXrefs(String functionName, int offset, int limit) {\n        return \"\";\n    }\n    private String listDefinedStrings(int offset, int limit, String filter) {\n        return \"\";\n    }\n    private boolean isStringData(Data data) {\n        return false;\n    }\n    private String escapeString(String input) {\n        return \"\";\n    }\n    private DataType resolveDataType(DataTypeManager dtm, String typeName) {\n        return null;\n    }\n    private DataType findDataTypeByNameInAllCategories(DataTypeManager dtm, String typeName) {\n        return null;\n    }\n    private DataType searchByNameInAllCategories(DataTypeManager dtm, String name) {\n        return null;\n    }\n    private Map<String, String> parseQueryParams(HttpExchange exchange) {\n        return null;\n    }\n    private Map<String, String> parsePostParams(HttpExchange exchange) throws IOException {\n        return null;\n    }\n    private String paginateList(List<String> items, int offset, int limit) {\n        return \"\";\n    }\n    private int parseIntOrDefault(String val, int defaultValue) {\n        return 0;\n    }\n    private String escapeNonAscii(String input) {\n        return \"\";\n    }\n    public Program getCurrentProgram() {\n        return null;\n    }\n    private void sendResponse(HttpExchange exchange, String response) throws IOException {}\n    @Override\n    public void dispose() {\n    }\n}"}}