Repository: LaurieWired/GhidraMCP
Branch: main
Commit: 27f316f80139
Files: 14
Total size: 101.9 KB
Directory structure:
gitextract_813uay9s/
├── .github/
│ └── workflows/
│ └── build.yml
├── .gitignore
├── LICENSE
├── README.md
├── bridge_mcp_ghidra.py
├── lib/
│ └── .gitignore
├── pom.xml
├── requirements.txt
└── src/
├── assembly/
│ └── ghidra-extension.xml
├── main/
│ ├── java/
│ │ └── com/
│ │ └── lauriewired/
│ │ └── GhidraMCPPlugin.java
│ └── resources/
│ ├── META-INF/
│ │ └── MANIFEST.MF
│ ├── Module.manifest
│ └── extension.properties
└── test/
└── java/
└── com/
└── lauriewired/
└── AppTest.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/build.yml
================================================
name: Build with Maven
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
env:
GHIDRA_VERSION: 11.3.2
GHIDRA_DATE: 20250415
GHIDRA_LIBS: >-
Features/Base/lib/Base.jar
Features/Decompiler/lib/Decompiler.jar
Framework/Docking/lib/Docking.jar
Framework/Generic/lib/Generic.jar
Framework/Project/lib/Project.jar
Framework/SoftwareModeling/lib/SoftwareModeling.jar
Framework/Utility/lib/Utility.jar
Framework/Gui/lib/Gui.jar
steps:
- uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
cache: maven
- name: Download Ghidra
run: |
wget --no-verbose -O ghidra.zip https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_${{ env.GHIDRA_VERSION }}_build/ghidra_${{ env.GHIDRA_VERSION }}_PUBLIC_${{ env.GHIDRA_DATE }}.zip
7z x -bd ghidra.zip
- name: Copy Ghidra libs
run: |
mkdir -p ./lib
for libfile in ${{ env.GHIDRA_LIBS }}
do echo "Copying ${libfile} to lib/"
cp ghidra_${{ env.GHIDRA_VERSION }}_PUBLIC/Ghidra/${libfile} ./lib/
done
- name: Build with Maven
run: mvn clean package assembly:single
- name: Assemble release directory
run: |
mkdir release
cp target/GhidraMCP-*-SNAPSHOT.zip release/
cp bridge_mcp_ghidra.py release/
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: GhidraMCP-artifact
path: |
release/*
================================================
FILE: .gitignore
================================================
# Maven target directory
/target/
# Compiled class files
*.class
# Logs
*.log
# IDE files
# IntelliJ
.idea/
*.iml
*.iws
out/
# Eclipse
.project
.classpath
.settings/
bin/
# VS Code
.vscode/
# macOS
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# macOS metadata files
.Spotlight-V100
.Trashes
# Maven Wrapper
.mvn/
!/.mvn/wrapper/maven-wrapper.jar
mvnw
mvnw.cmd
# Environment files
.env
.env.*
# Java crash logs (if any)
hs_err_pid*
replay_pid*
# Third party JAR files from Ghidra
lib/*.jar
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
[](https://www.apache.org/licenses/LICENSE-2.0)
[](https://github.com/LaurieWired/GhidraMCP/releases)
[](https://github.com/LaurieWired/GhidraMCP/stargazers)
[](https://github.com/LaurieWired/GhidraMCP/network/members)
[](https://github.com/LaurieWired/GhidraMCP/graphs/contributors)
[](https://twitter.com/lauriewired)

# ghidraMCP
ghidraMCP is an Model Context Protocol server for allowing LLMs to autonomously reverse engineer applications. It exposes numerous tools from core Ghidra functionality to MCP clients.
https://github.com/user-attachments/assets/36080514-f227-44bd-af84-78e29ee1d7f9
# Features
MCP Server + Ghidra Plugin
- Decompile and analyze binaries in Ghidra
- Automatically rename methods and data
- List methods, classes, imports, and exports
# Installation
## Prerequisites
- Install [Ghidra](https://ghidra-sre.org)
- Python3
- MCP [SDK](https://github.com/modelcontextprotocol/python-sdk)
## Ghidra
First, download the latest [release](https://github.com/LaurieWired/GhidraMCP/releases) from this repository. This contains the Ghidra plugin and Python MCP client. Then, you can directly import the plugin into Ghidra.
1. Run Ghidra
2. Select `File` -> `Install Extensions`
3. Click the `+` button
4. Select the `GhidraMCP-1-2.zip` (or your chosen version) from the downloaded release
5. Restart Ghidra
6. Make sure the GhidraMCPPlugin is enabled in `File` -> `Configure` -> `Developer`
7. *Optional*: Configure the port in Ghidra with `Edit` -> `Tool Options` -> `GhidraMCP HTTP Server`
Video Installation Guide:
https://github.com/user-attachments/assets/75f0c176-6da1-48dc-ad96-c182eb4648c3
## MCP Clients
Theoretically, any MCP client should work with ghidraMCP. Three examples are given below.
## Example 1: Claude Desktop
To set up Claude Desktop as a Ghidra MCP client, go to `Claude` -> `Settings` -> `Developer` -> `Edit Config` -> `claude_desktop_config.json` and add the following:
```json
{
"mcpServers": {
"ghidra": {
"command": "python",
"args": [
"/ABSOLUTE_PATH_TO/bridge_mcp_ghidra.py",
"--ghidra-server",
"http://127.0.0.1:8080/"
]
}
}
}
```
Alternatively, edit this file directly:
```
/Users/YOUR_USER/Library/Application Support/Claude/claude_desktop_config.json
```
The server IP and port are configurable and should be set to point to the target Ghidra instance. If not set, both will default to localhost:8080.
## Example 2: Cline
To use GhidraMCP with [Cline](https://cline.bot), this requires manually running the MCP server as well. First run the following command:
```
python bridge_mcp_ghidra.py --transport sse --mcp-host 127.0.0.1 --mcp-port 8081 --ghidra-server http://127.0.0.1:8080/
```
The only *required* argument is the transport. If all other arguments are unspecified, they will default to the above. Once the MCP server is running, open up Cline and select `MCP Servers` at the top.

Then select `Remote Servers` and add the following, ensuring that the url matches the MCP host and port:
1. Server Name: GhidraMCP
2. Server URL: `http://127.0.0.1:8081/sse`
## Example 3: 5ire
Another MCP client that supports multiple models on the backend is [5ire](https://github.com/nanbingxyz/5ire). To set up GhidraMCP, open 5ire and go to `Tools` -> `New` and set the following configurations:
1. Tool Key: ghidra
2. Name: GhidraMCP
3. Command: `python /ABSOLUTE_PATH_TO/bridge_mcp_ghidra.py`
# Building from Source
1. Copy the following files from your Ghidra directory to this project's `lib/` directory:
- `Ghidra/Features/Base/lib/Base.jar`
- `Ghidra/Features/Decompiler/lib/Decompiler.jar`
- `Ghidra/Framework/Docking/lib/Docking.jar`
- `Ghidra/Framework/Generic/lib/Generic.jar`
- `Ghidra/Framework/Project/lib/Project.jar`
- `Ghidra/Framework/SoftwareModeling/lib/SoftwareModeling.jar`
- `Ghidra/Framework/Utility/lib/Utility.jar`
- `Ghidra/Framework/Gui/lib/Gui.jar`
2. Build with Maven by running:
`mvn clean package assembly:single`
The generated zip file includes the built Ghidra plugin and its resources. These files are required for Ghidra to recognize the new extension.
- lib/GhidraMCP.jar
- extensions.properties
- Module.manifest
================================================
FILE: bridge_mcp_ghidra.py
================================================
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "requests>=2,<3",
# "mcp>=1.2.0,<2",
# ]
# ///
import sys
import requests
import argparse
import logging
from urllib.parse import urljoin
from mcp.server.fastmcp import FastMCP
DEFAULT_GHIDRA_SERVER = "http://127.0.0.1:8080/"
logger = logging.getLogger(__name__)
mcp = FastMCP("ghidra-mcp")
# Initialize ghidra_server_url with default value
ghidra_server_url = DEFAULT_GHIDRA_SERVER
def safe_get(endpoint: str, params: dict = None) -> list:
"""
Perform a GET request with optional query parameters.
"""
if params is None:
params = {}
url = urljoin(ghidra_server_url, endpoint)
try:
response = requests.get(url, params=params, timeout=5)
response.encoding = 'utf-8'
if response.ok:
return response.text.splitlines()
else:
return [f"Error {response.status_code}: {response.text.strip()}"]
except Exception as e:
return [f"Request failed: {str(e)}"]
def safe_post(endpoint: str, data: dict | str) -> str:
try:
url = urljoin(ghidra_server_url, endpoint)
if isinstance(data, dict):
response = requests.post(url, data=data, timeout=5)
else:
response = requests.post(url, data=data.encode("utf-8"), timeout=5)
response.encoding = 'utf-8'
if response.ok:
return response.text.strip()
else:
return f"Error {response.status_code}: {response.text.strip()}"
except Exception as e:
return f"Request failed: {str(e)}"
@mcp.tool()
def list_methods(offset: int = 0, limit: int = 100) -> list:
"""
List all function names in the program with pagination.
"""
return safe_get("methods", {"offset": offset, "limit": limit})
@mcp.tool()
def list_classes(offset: int = 0, limit: int = 100) -> list:
"""
List all namespace/class names in the program with pagination.
"""
return safe_get("classes", {"offset": offset, "limit": limit})
@mcp.tool()
def decompile_function(name: str) -> str:
"""
Decompile a specific function by name and return the decompiled C code.
"""
return safe_post("decompile", name)
@mcp.tool()
def rename_function(old_name: str, new_name: str) -> str:
"""
Rename a function by its current name to a new user-defined name.
"""
return safe_post("renameFunction", {"oldName": old_name, "newName": new_name})
@mcp.tool()
def rename_data(address: str, new_name: str) -> str:
"""
Rename a data label at the specified address.
"""
return safe_post("renameData", {"address": address, "newName": new_name})
@mcp.tool()
def list_segments(offset: int = 0, limit: int = 100) -> list:
"""
List all memory segments in the program with pagination.
"""
return safe_get("segments", {"offset": offset, "limit": limit})
@mcp.tool()
def list_imports(offset: int = 0, limit: int = 100) -> list:
"""
List imported symbols in the program with pagination.
"""
return safe_get("imports", {"offset": offset, "limit": limit})
@mcp.tool()
def list_exports(offset: int = 0, limit: int = 100) -> list:
"""
List exported functions/symbols with pagination.
"""
return safe_get("exports", {"offset": offset, "limit": limit})
@mcp.tool()
def list_namespaces(offset: int = 0, limit: int = 100) -> list:
"""
List all non-global namespaces in the program with pagination.
"""
return safe_get("namespaces", {"offset": offset, "limit": limit})
@mcp.tool()
def list_data_items(offset: int = 0, limit: int = 100) -> list:
"""
List defined data labels and their values with pagination.
"""
return safe_get("data", {"offset": offset, "limit": limit})
@mcp.tool()
def search_functions_by_name(query: str, offset: int = 0, limit: int = 100) -> list:
"""
Search for functions whose name contains the given substring.
"""
if not query:
return ["Error: query string is required"]
return safe_get("searchFunctions", {"query": query, "offset": offset, "limit": limit})
@mcp.tool()
def rename_variable(function_name: str, old_name: str, new_name: str) -> str:
"""
Rename a local variable within a function.
"""
return safe_post("renameVariable", {
"functionName": function_name,
"oldName": old_name,
"newName": new_name
})
@mcp.tool()
def get_function_by_address(address: str) -> str:
"""
Get a function by its address.
"""
return "\n".join(safe_get("get_function_by_address", {"address": address}))
@mcp.tool()
def get_current_address() -> str:
"""
Get the address currently selected by the user.
"""
return "\n".join(safe_get("get_current_address"))
@mcp.tool()
def get_current_function() -> str:
"""
Get the function currently selected by the user.
"""
return "\n".join(safe_get("get_current_function"))
@mcp.tool()
def list_functions() -> list:
"""
List all functions in the database.
"""
return safe_get("list_functions")
@mcp.tool()
def decompile_function_by_address(address: str) -> str:
"""
Decompile a function at the given address.
"""
return "\n".join(safe_get("decompile_function", {"address": address}))
@mcp.tool()
def disassemble_function(address: str) -> list:
"""
Get assembly code (address: instruction; comment) for a function.
"""
return safe_get("disassemble_function", {"address": address})
@mcp.tool()
def set_decompiler_comment(address: str, comment: str) -> str:
"""
Set a comment for a given address in the function pseudocode.
"""
return safe_post("set_decompiler_comment", {"address": address, "comment": comment})
@mcp.tool()
def set_disassembly_comment(address: str, comment: str) -> str:
"""
Set a comment for a given address in the function disassembly.
"""
return safe_post("set_disassembly_comment", {"address": address, "comment": comment})
@mcp.tool()
def rename_function_by_address(function_address: str, new_name: str) -> str:
"""
Rename a function by its address.
"""
return safe_post("rename_function_by_address", {"function_address": function_address, "new_name": new_name})
@mcp.tool()
def set_function_prototype(function_address: str, prototype: str) -> str:
"""
Set a function's prototype.
"""
return safe_post("set_function_prototype", {"function_address": function_address, "prototype": prototype})
@mcp.tool()
def set_local_variable_type(function_address: str, variable_name: str, new_type: str) -> str:
"""
Set a local variable's type.
"""
return safe_post("set_local_variable_type", {"function_address": function_address, "variable_name": variable_name, "new_type": new_type})
@mcp.tool()
def get_xrefs_to(address: str, offset: int = 0, limit: int = 100) -> list:
"""
Get all references to the specified address (xref to).
Args:
address: Target address in hex format (e.g. "0x1400010a0")
offset: Pagination offset (default: 0)
limit: Maximum number of references to return (default: 100)
Returns:
List of references to the specified address
"""
return safe_get("xrefs_to", {"address": address, "offset": offset, "limit": limit})
@mcp.tool()
def get_xrefs_from(address: str, offset: int = 0, limit: int = 100) -> list:
"""
Get all references from the specified address (xref from).
Args:
address: Source address in hex format (e.g. "0x1400010a0")
offset: Pagination offset (default: 0)
limit: Maximum number of references to return (default: 100)
Returns:
List of references from the specified address
"""
return safe_get("xrefs_from", {"address": address, "offset": offset, "limit": limit})
@mcp.tool()
def get_function_xrefs(name: str, offset: int = 0, limit: int = 100) -> list:
"""
Get all references to the specified function by name.
Args:
name: Function name to search for
offset: Pagination offset (default: 0)
limit: Maximum number of references to return (default: 100)
Returns:
List of references to the specified function
"""
return safe_get("function_xrefs", {"name": name, "offset": offset, "limit": limit})
@mcp.tool()
def list_strings(offset: int = 0, limit: int = 2000, filter: str = None) -> list:
"""
List all defined strings in the program with their addresses.
Args:
offset: Pagination offset (default: 0)
limit: Maximum number of strings to return (default: 2000)
filter: Optional filter to match within string content
Returns:
List of strings with their addresses
"""
params = {"offset": offset, "limit": limit}
if filter:
params["filter"] = filter
return safe_get("strings", params)
def main():
parser = argparse.ArgumentParser(description="MCP server for Ghidra")
parser.add_argument("--ghidra-server", type=str, default=DEFAULT_GHIDRA_SERVER,
help=f"Ghidra server URL, default: {DEFAULT_GHIDRA_SERVER}")
parser.add_argument("--mcp-host", type=str, default="127.0.0.1",
help="Host to run MCP server on (only used for sse), default: 127.0.0.1")
parser.add_argument("--mcp-port", type=int,
help="Port to run MCP server on (only used for sse), default: 8081")
parser.add_argument("--transport", type=str, default="stdio", choices=["stdio", "sse"],
help="Transport protocol for MCP, default: stdio")
args = parser.parse_args()
# Use the global variable to ensure it's properly updated
global ghidra_server_url
if args.ghidra_server:
ghidra_server_url = args.ghidra_server
if args.transport == "sse":
try:
# Set up logging
log_level = logging.INFO
logging.basicConfig(level=log_level)
logging.getLogger().setLevel(log_level)
# Configure MCP settings
mcp.settings.log_level = "INFO"
if args.mcp_host:
mcp.settings.host = args.mcp_host
else:
mcp.settings.host = "127.0.0.1"
if args.mcp_port:
mcp.settings.port = args.mcp_port
else:
mcp.settings.port = 8081
logger.info(f"Connecting to Ghidra server at {ghidra_server_url}")
logger.info(f"Starting MCP server on http://{mcp.settings.host}:{mcp.settings.port}/sse")
logger.info(f"Using transport: {args.transport}")
mcp.run(transport="sse")
except KeyboardInterrupt:
logger.info("Server stopped by user")
else:
mcp.run()
if __name__ == "__main__":
main()
================================================
FILE: lib/.gitignore
================================================
*
!.gitignore
================================================
FILE: pom.xml
================================================
4.0.0
com.lauriewired
GhidraMCP
jar
1.0-SNAPSHOT
GhidraMCP
http://maven.apache.org
ghidra
Generic
11.3.2
system
${project.basedir}/lib/Generic.jar
ghidra
SoftwareModeling
11.3.2
system
${project.basedir}/lib/SoftwareModeling.jar
ghidra
Project
11.3.2
system
${project.basedir}/lib/Project.jar
ghidra
Docking
11.3.2
system
${project.basedir}/lib/Docking.jar
ghidra
Decompiler
11.3.2
system
${project.basedir}/lib/Decompiler.jar
ghidra
Utility
11.3.2
system
${project.basedir}/lib/Utility.jar
ghidra
Base
11.3.2
system
${project.basedir}/lib/Base.jar
ghidra
Gui
11.3.2
system
${project.basedir}/lib/Gui.jar
junit
junit
3.8.1
test
maven-jar-plugin
3.2.2
src/main/resources/META-INF/MANIFEST.MF
GhidraMCP
**/App.class
${project.build.directory}
org.apache.maven.plugins
maven-assembly-plugin
3.3.0
src/assembly/ghidra-extension.xml
GhidraMCP-${project.version}
false
make-assembly
package
single
org.apache.maven.plugins
maven-dependency-plugin
3.1.2
copy-dependencies
prepare-package
copy-dependencies
${project.build.directory}/lib
runtime
================================================
FILE: requirements.txt
================================================
mcp==1.5.0
requests==2.32.3
================================================
FILE: src/assembly/ghidra-extension.xml
================================================
ghidra-extension
zip
false
src/main/resources
extension.properties
Module.manifest
GhidraMCP
${project.build.directory}
GhidraMCP.jar
GhidraMCP/lib
================================================
FILE: src/main/java/com/lauriewired/GhidraMCPPlugin.java
================================================
package com.lauriewired;
import ghidra.framework.plugintool.Plugin;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.GlobalNamespace;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.symbol.*;
import ghidra.program.model.symbol.ReferenceManager;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.ReferenceIterator;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.pcode.HighFunction;
import ghidra.program.model.pcode.HighSymbol;
import ghidra.program.model.pcode.LocalSymbolMap;
import ghidra.program.model.pcode.HighFunctionDBUtil;
import ghidra.program.model.pcode.HighFunctionDBUtil.ReturnCommitOption;
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import ghidra.app.plugin.PluginCategoryNames;
import ghidra.app.services.CodeViewerService;
import ghidra.app.services.ProgramManager;
import ghidra.app.util.PseudoDisassembler;
import ghidra.app.cmd.function.SetVariableNameCmd;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.listing.LocalVariableImpl;
import ghidra.program.model.listing.ParameterImpl;
import ghidra.util.exception.DuplicateNameException;
import ghidra.util.exception.InvalidInputException;
import ghidra.framework.plugintool.PluginInfo;
import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.util.ProgramLocation;
import ghidra.util.Msg;
import ghidra.util.task.ConsoleTaskMonitor;
import ghidra.util.task.TaskMonitor;
import ghidra.program.model.pcode.HighVariable;
import ghidra.program.model.pcode.Varnode;
import ghidra.program.model.data.DataType;
import ghidra.program.model.data.DataTypeManager;
import ghidra.program.model.data.PointerDataType;
import ghidra.program.model.data.Undefined1DataType;
import ghidra.program.model.listing.Variable;
import ghidra.app.decompiler.component.DecompilerUtils;
import ghidra.app.decompiler.ClangToken;
import ghidra.framework.options.Options;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import javax.swing.SwingUtilities;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
@PluginInfo(
status = PluginStatus.RELEASED,
packageName = ghidra.app.DeveloperPluginPackage.NAME,
category = PluginCategoryNames.ANALYSIS,
shortDescription = "HTTP server plugin",
description = "Starts an embedded HTTP server to expose program data. Port configurable via Tool Options."
)
public class GhidraMCPPlugin extends Plugin {
private HttpServer server;
private static final String OPTION_CATEGORY_NAME = "GhidraMCP HTTP Server";
private static final String PORT_OPTION_NAME = "Server Port";
private static final int DEFAULT_PORT = 8080;
public GhidraMCPPlugin(PluginTool tool) {
super(tool);
Msg.info(this, "GhidraMCPPlugin loading...");
// Register the configuration option
Options options = tool.getOptions(OPTION_CATEGORY_NAME);
options.registerOption(PORT_OPTION_NAME, DEFAULT_PORT,
null, // No help location for now
"The network port number the embedded HTTP server will listen on. " +
"Requires Ghidra restart or plugin reload to take effect after changing.");
try {
startServer();
}
catch (IOException e) {
Msg.error(this, "Failed to start HTTP server", e);
}
Msg.info(this, "GhidraMCPPlugin loaded!");
}
private void startServer() throws IOException {
// Read the configured port
Options options = tool.getOptions(OPTION_CATEGORY_NAME);
int port = options.getInt(PORT_OPTION_NAME, DEFAULT_PORT);
// Stop existing server if running (e.g., if plugin is reloaded)
if (server != null) {
Msg.info(this, "Stopping existing HTTP server before starting new one.");
server.stop(0);
server = null;
}
server = HttpServer.create(new InetSocketAddress(port), 0);
// Each listing endpoint uses offset & limit from query params:
server.createContext("/methods", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, getAllFunctionNames(offset, limit));
});
server.createContext("/classes", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, getAllClassNames(offset, limit));
});
server.createContext("/decompile", exchange -> {
String name = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
sendResponse(exchange, decompileFunctionByName(name));
});
server.createContext("/renameFunction", exchange -> {
Map params = parsePostParams(exchange);
String response = renameFunction(params.get("oldName"), params.get("newName"))
? "Renamed successfully" : "Rename failed";
sendResponse(exchange, response);
});
server.createContext("/renameData", exchange -> {
Map params = parsePostParams(exchange);
renameDataAtAddress(params.get("address"), params.get("newName"));
sendResponse(exchange, "Rename data attempted");
});
server.createContext("/renameVariable", exchange -> {
Map params = parsePostParams(exchange);
String functionName = params.get("functionName");
String oldName = params.get("oldName");
String newName = params.get("newName");
String result = renameVariableInFunction(functionName, oldName, newName);
sendResponse(exchange, result);
});
server.createContext("/segments", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, listSegments(offset, limit));
});
server.createContext("/imports", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, listImports(offset, limit));
});
server.createContext("/exports", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, listExports(offset, limit));
});
server.createContext("/namespaces", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, listNamespaces(offset, limit));
});
server.createContext("/data", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, listDefinedData(offset, limit));
});
server.createContext("/searchFunctions", exchange -> {
Map qparams = parseQueryParams(exchange);
String searchTerm = qparams.get("query");
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, searchFunctionsByName(searchTerm, offset, limit));
});
// New API endpoints based on requirements
server.createContext("/get_function_by_address", exchange -> {
Map qparams = parseQueryParams(exchange);
String address = qparams.get("address");
sendResponse(exchange, getFunctionByAddress(address));
});
server.createContext("/get_current_address", exchange -> {
sendResponse(exchange, getCurrentAddress());
});
server.createContext("/get_current_function", exchange -> {
sendResponse(exchange, getCurrentFunction());
});
server.createContext("/list_functions", exchange -> {
sendResponse(exchange, listFunctions());
});
server.createContext("/decompile_function", exchange -> {
Map qparams = parseQueryParams(exchange);
String address = qparams.get("address");
sendResponse(exchange, decompileFunctionByAddress(address));
});
server.createContext("/disassemble_function", exchange -> {
Map qparams = parseQueryParams(exchange);
String address = qparams.get("address");
sendResponse(exchange, disassembleFunction(address));
});
server.createContext("/set_decompiler_comment", exchange -> {
Map params = parsePostParams(exchange);
String address = params.get("address");
String comment = params.get("comment");
boolean success = setDecompilerComment(address, comment);
sendResponse(exchange, success ? "Comment set successfully" : "Failed to set comment");
});
server.createContext("/set_disassembly_comment", exchange -> {
Map params = parsePostParams(exchange);
String address = params.get("address");
String comment = params.get("comment");
boolean success = setDisassemblyComment(address, comment);
sendResponse(exchange, success ? "Comment set successfully" : "Failed to set comment");
});
server.createContext("/rename_function_by_address", exchange -> {
Map params = parsePostParams(exchange);
String functionAddress = params.get("function_address");
String newName = params.get("new_name");
boolean success = renameFunctionByAddress(functionAddress, newName);
sendResponse(exchange, success ? "Function renamed successfully" : "Failed to rename function");
});
server.createContext("/set_function_prototype", exchange -> {
Map params = parsePostParams(exchange);
String functionAddress = params.get("function_address");
String prototype = params.get("prototype");
// Call the set prototype function and get detailed result
PrototypeResult result = setFunctionPrototype(functionAddress, prototype);
if (result.isSuccess()) {
// Even with successful operations, include any warning messages for debugging
String successMsg = "Function prototype set successfully";
if (!result.getErrorMessage().isEmpty()) {
successMsg += "\n\nWarnings/Debug Info:\n" + result.getErrorMessage();
}
sendResponse(exchange, successMsg);
} else {
// Return the detailed error message to the client
sendResponse(exchange, "Failed to set function prototype: " + result.getErrorMessage());
}
});
server.createContext("/set_local_variable_type", exchange -> {
Map params = parsePostParams(exchange);
String functionAddress = params.get("function_address");
String variableName = params.get("variable_name");
String newType = params.get("new_type");
// Capture detailed information about setting the type
StringBuilder responseMsg = new StringBuilder();
responseMsg.append("Setting variable type: ").append(variableName)
.append(" to ").append(newType)
.append(" in function at ").append(functionAddress).append("\n\n");
// Attempt to find the data type in various categories
Program program = getCurrentProgram();
if (program != null) {
DataTypeManager dtm = program.getDataTypeManager();
DataType directType = findDataTypeByNameInAllCategories(dtm, newType);
if (directType != null) {
responseMsg.append("Found type: ").append(directType.getPathName()).append("\n");
} else if (newType.startsWith("P") && newType.length() > 1) {
String baseTypeName = newType.substring(1);
DataType baseType = findDataTypeByNameInAllCategories(dtm, baseTypeName);
if (baseType != null) {
responseMsg.append("Found base type for pointer: ").append(baseType.getPathName()).append("\n");
} else {
responseMsg.append("Base type not found for pointer: ").append(baseTypeName).append("\n");
}
} else {
responseMsg.append("Type not found directly: ").append(newType).append("\n");
}
}
// Try to set the type
boolean success = setLocalVariableType(functionAddress, variableName, newType);
String successMsg = success ? "Variable type set successfully" : "Failed to set variable type";
responseMsg.append("\nResult: ").append(successMsg);
sendResponse(exchange, responseMsg.toString());
});
server.createContext("/xrefs_to", exchange -> {
Map qparams = parseQueryParams(exchange);
String address = qparams.get("address");
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, getXrefsTo(address, offset, limit));
});
server.createContext("/xrefs_from", exchange -> {
Map qparams = parseQueryParams(exchange);
String address = qparams.get("address");
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, getXrefsFrom(address, offset, limit));
});
server.createContext("/function_xrefs", exchange -> {
Map qparams = parseQueryParams(exchange);
String name = qparams.get("name");
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
sendResponse(exchange, getFunctionXrefs(name, offset, limit));
});
server.createContext("/strings", exchange -> {
Map qparams = parseQueryParams(exchange);
int offset = parseIntOrDefault(qparams.get("offset"), 0);
int limit = parseIntOrDefault(qparams.get("limit"), 100);
String filter = qparams.get("filter");
sendResponse(exchange, listDefinedStrings(offset, limit, filter));
});
server.setExecutor(null);
new Thread(() -> {
try {
server.start();
Msg.info(this, "GhidraMCP HTTP server started on port " + port);
} catch (Exception e) {
Msg.error(this, "Failed to start HTTP server on port " + port + ". Port might be in use.", e);
server = null; // Ensure server isn't considered running
}
}, "GhidraMCP-HTTP-Server").start();
}
// ----------------------------------------------------------------------------------
// Pagination-aware listing methods
// ----------------------------------------------------------------------------------
private String getAllFunctionNames(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
List names = new ArrayList<>();
for (Function f : program.getFunctionManager().getFunctions(true)) {
names.add(f.getName());
}
return paginateList(names, offset, limit);
}
private String getAllClassNames(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
Set classNames = new HashSet<>();
for (Symbol symbol : program.getSymbolTable().getAllSymbols(true)) {
Namespace ns = symbol.getParentNamespace();
if (ns != null && !ns.isGlobal()) {
classNames.add(ns.getName());
}
}
// Convert set to list for pagination
List sorted = new ArrayList<>(classNames);
Collections.sort(sorted);
return paginateList(sorted, offset, limit);
}
private String listSegments(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
List lines = new ArrayList<>();
for (MemoryBlock block : program.getMemory().getBlocks()) {
lines.add(String.format("%s: %s - %s", block.getName(), block.getStart(), block.getEnd()));
}
return paginateList(lines, offset, limit);
}
private String listImports(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
List lines = new ArrayList<>();
for (Symbol symbol : program.getSymbolTable().getExternalSymbols()) {
lines.add(symbol.getName() + " -> " + symbol.getAddress());
}
return paginateList(lines, offset, limit);
}
private String listExports(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
SymbolTable table = program.getSymbolTable();
SymbolIterator it = table.getAllSymbols(true);
List lines = new ArrayList<>();
while (it.hasNext()) {
Symbol s = it.next();
// On older Ghidra, "export" is recognized via isExternalEntryPoint()
if (s.isExternalEntryPoint()) {
lines.add(s.getName() + " -> " + s.getAddress());
}
}
return paginateList(lines, offset, limit);
}
private String listNamespaces(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
Set namespaces = new HashSet<>();
for (Symbol symbol : program.getSymbolTable().getAllSymbols(true)) {
Namespace ns = symbol.getParentNamespace();
if (ns != null && !(ns instanceof GlobalNamespace)) {
namespaces.add(ns.getName());
}
}
List sorted = new ArrayList<>(namespaces);
Collections.sort(sorted);
return paginateList(sorted, offset, limit);
}
private String listDefinedData(int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
List lines = new ArrayList<>();
for (MemoryBlock block : program.getMemory().getBlocks()) {
DataIterator it = program.getListing().getDefinedData(block.getStart(), true);
while (it.hasNext()) {
Data data = it.next();
if (block.contains(data.getAddress())) {
String label = data.getLabel() != null ? data.getLabel() : "(unnamed)";
String valRepr = data.getDefaultValueRepresentation();
lines.add(String.format("%s: %s = %s",
data.getAddress(),
escapeNonAscii(label),
escapeNonAscii(valRepr)
));
}
}
}
return paginateList(lines, offset, limit);
}
private String searchFunctionsByName(String searchTerm, int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (searchTerm == null || searchTerm.isEmpty()) return "Search term is required";
List matches = new ArrayList<>();
for (Function func : program.getFunctionManager().getFunctions(true)) {
String name = func.getName();
// simple substring match
if (name.toLowerCase().contains(searchTerm.toLowerCase())) {
matches.add(String.format("%s @ %s", name, func.getEntryPoint()));
}
}
Collections.sort(matches);
if (matches.isEmpty()) {
return "No functions matching '" + searchTerm + "'";
}
return paginateList(matches, offset, limit);
}
// ----------------------------------------------------------------------------------
// Logic for rename, decompile, etc.
// ----------------------------------------------------------------------------------
private String decompileFunctionByName(String name) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
DecompInterface decomp = new DecompInterface();
decomp.openProgram(program);
for (Function func : program.getFunctionManager().getFunctions(true)) {
if (func.getName().equals(name)) {
DecompileResults result =
decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());
if (result != null && result.decompileCompleted()) {
return result.getDecompiledFunction().getC();
} else {
return "Decompilation failed";
}
}
}
return "Function not found";
}
private boolean renameFunction(String oldName, String newName) {
Program program = getCurrentProgram();
if (program == null) return false;
AtomicBoolean successFlag = new AtomicBoolean(false);
try {
SwingUtilities.invokeAndWait(() -> {
int tx = program.startTransaction("Rename function via HTTP");
try {
for (Function func : program.getFunctionManager().getFunctions(true)) {
if (func.getName().equals(oldName)) {
func.setName(newName, SourceType.USER_DEFINED);
successFlag.set(true);
break;
}
}
}
catch (Exception e) {
Msg.error(this, "Error renaming function", e);
}
finally {
successFlag.set(program.endTransaction(tx, successFlag.get()));
}
});
}
catch (InterruptedException | InvocationTargetException e) {
Msg.error(this, "Failed to execute rename on Swing thread", e);
}
return successFlag.get();
}
private void renameDataAtAddress(String addressStr, String newName) {
Program program = getCurrentProgram();
if (program == null) return;
try {
SwingUtilities.invokeAndWait(() -> {
int tx = program.startTransaction("Rename data");
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
Listing listing = program.getListing();
Data data = listing.getDefinedDataAt(addr);
if (data != null) {
SymbolTable symTable = program.getSymbolTable();
Symbol symbol = symTable.getPrimarySymbol(addr);
if (symbol != null) {
symbol.setName(newName, SourceType.USER_DEFINED);
} else {
symTable.createLabel(addr, newName, SourceType.USER_DEFINED);
}
}
}
catch (Exception e) {
Msg.error(this, "Rename data error", e);
}
finally {
program.endTransaction(tx, true);
}
});
}
catch (InterruptedException | InvocationTargetException e) {
Msg.error(this, "Failed to execute rename data on Swing thread", e);
}
}
private String renameVariableInFunction(String functionName, String oldVarName, String newVarName) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
DecompInterface decomp = new DecompInterface();
decomp.openProgram(program);
Function func = null;
for (Function f : program.getFunctionManager().getFunctions(true)) {
if (f.getName().equals(functionName)) {
func = f;
break;
}
}
if (func == null) {
return "Function not found";
}
DecompileResults result = decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());
if (result == null || !result.decompileCompleted()) {
return "Decompilation failed";
}
HighFunction highFunction = result.getHighFunction();
if (highFunction == null) {
return "Decompilation failed (no high function)";
}
LocalSymbolMap localSymbolMap = highFunction.getLocalSymbolMap();
if (localSymbolMap == null) {
return "Decompilation failed (no local symbol map)";
}
HighSymbol highSymbol = null;
Iterator symbols = localSymbolMap.getSymbols();
while (symbols.hasNext()) {
HighSymbol symbol = symbols.next();
String symbolName = symbol.getName();
if (symbolName.equals(oldVarName)) {
highSymbol = symbol;
}
if (symbolName.equals(newVarName)) {
return "Error: A variable with name '" + newVarName + "' already exists in this function";
}
}
if (highSymbol == null) {
return "Variable not found";
}
boolean commitRequired = checkFullCommit(highSymbol, highFunction);
final HighSymbol finalHighSymbol = highSymbol;
final Function finalFunction = func;
AtomicBoolean successFlag = new AtomicBoolean(false);
try {
SwingUtilities.invokeAndWait(() -> {
int tx = program.startTransaction("Rename variable");
try {
if (commitRequired) {
HighFunctionDBUtil.commitParamsToDatabase(highFunction, false,
ReturnCommitOption.NO_COMMIT, finalFunction.getSignatureSource());
}
HighFunctionDBUtil.updateDBVariable(
finalHighSymbol,
newVarName,
null,
SourceType.USER_DEFINED
);
successFlag.set(true);
}
catch (Exception e) {
Msg.error(this, "Failed to rename variable", e);
}
finally {
successFlag.set(program.endTransaction(tx, true));
}
});
} catch (InterruptedException | InvocationTargetException e) {
String errorMsg = "Failed to execute rename on Swing thread: " + e.getMessage();
Msg.error(this, errorMsg, e);
return errorMsg;
}
return successFlag.get() ? "Variable renamed" : "Failed to rename variable";
}
/**
* Copied from AbstractDecompilerAction.checkFullCommit, it's protected.
* Compare the given HighFunction's idea of the prototype with the Function's idea.
* Return true if there is a difference. If a specific symbol is being changed,
* it can be passed in to check whether or not the prototype is being affected.
* @param highSymbol (if not null) is the symbol being modified
* @param hfunction is the given HighFunction
* @return true if there is a difference (and a full commit is required)
*/
protected static boolean checkFullCommit(HighSymbol highSymbol, HighFunction hfunction) {
if (highSymbol != null && !highSymbol.isParameter()) {
return false;
}
Function function = hfunction.getFunction();
Parameter[] parameters = function.getParameters();
LocalSymbolMap localSymbolMap = hfunction.getLocalSymbolMap();
int numParams = localSymbolMap.getNumParams();
if (numParams != parameters.length) {
return true;
}
for (int i = 0; i < numParams; i++) {
HighSymbol param = localSymbolMap.getParamSymbol(i);
if (param.getCategoryIndex() != i) {
return true;
}
VariableStorage storage = param.getStorage();
// Don't compare using the equals method so that DynamicVariableStorage can match
if (0 != storage.compareTo(parameters[i].getVariableStorage())) {
return true;
}
}
return false;
}
// ----------------------------------------------------------------------------------
// New methods to implement the new functionalities
// ----------------------------------------------------------------------------------
/**
* Get function by address
*/
private String getFunctionByAddress(String addressStr) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (addressStr == null || addressStr.isEmpty()) return "Address is required";
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
Function func = program.getFunctionManager().getFunctionAt(addr);
if (func == null) return "No function found at address " + addressStr;
return String.format("Function: %s at %s\nSignature: %s\nEntry: %s\nBody: %s - %s",
func.getName(),
func.getEntryPoint(),
func.getSignature(),
func.getEntryPoint(),
func.getBody().getMinAddress(),
func.getBody().getMaxAddress());
} catch (Exception e) {
return "Error getting function: " + e.getMessage();
}
}
/**
* Get current address selected in Ghidra GUI
*/
private String getCurrentAddress() {
CodeViewerService service = tool.getService(CodeViewerService.class);
if (service == null) return "Code viewer service not available";
ProgramLocation location = service.getCurrentLocation();
return (location != null) ? location.getAddress().toString() : "No current location";
}
/**
* Get current function selected in Ghidra GUI
*/
private String getCurrentFunction() {
CodeViewerService service = tool.getService(CodeViewerService.class);
if (service == null) return "Code viewer service not available";
ProgramLocation location = service.getCurrentLocation();
if (location == null) return "No current location";
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
Function func = program.getFunctionManager().getFunctionContaining(location.getAddress());
if (func == null) return "No function at current location: " + location.getAddress();
return String.format("Function: %s at %s\nSignature: %s",
func.getName(),
func.getEntryPoint(),
func.getSignature());
}
/**
* List all functions in the database
*/
private String listFunctions() {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
StringBuilder result = new StringBuilder();
for (Function func : program.getFunctionManager().getFunctions(true)) {
result.append(String.format("%s at %s\n",
func.getName(),
func.getEntryPoint()));
}
return result.toString();
}
/**
* Gets a function at the given address or containing the address
* @return the function or null if not found
*/
private Function getFunctionForAddress(Program program, Address addr) {
Function func = program.getFunctionManager().getFunctionAt(addr);
if (func == null) {
func = program.getFunctionManager().getFunctionContaining(addr);
}
return func;
}
/**
* Decompile a function at the given address
*/
private String decompileFunctionByAddress(String addressStr) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (addressStr == null || addressStr.isEmpty()) return "Address is required";
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
Function func = getFunctionForAddress(program, addr);
if (func == null) return "No function found at or containing address " + addressStr;
DecompInterface decomp = new DecompInterface();
decomp.openProgram(program);
DecompileResults result = decomp.decompileFunction(func, 30, new ConsoleTaskMonitor());
return (result != null && result.decompileCompleted())
? result.getDecompiledFunction().getC()
: "Decompilation failed";
} catch (Exception e) {
return "Error decompiling function: " + e.getMessage();
}
}
/**
* Get assembly code for a function
*/
private String disassembleFunction(String addressStr) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (addressStr == null || addressStr.isEmpty()) return "Address is required";
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
Function func = getFunctionForAddress(program, addr);
if (func == null) return "No function found at or containing address " + addressStr;
StringBuilder result = new StringBuilder();
Listing listing = program.getListing();
Address start = func.getEntryPoint();
Address end = func.getBody().getMaxAddress();
InstructionIterator instructions = listing.getInstructions(start, true);
while (instructions.hasNext()) {
Instruction instr = instructions.next();
if (instr.getAddress().compareTo(end) > 0) {
break; // Stop if we've gone past the end of the function
}
String comment = listing.getComment(CodeUnit.EOL_COMMENT, instr.getAddress());
comment = (comment != null) ? "; " + comment : "";
result.append(String.format("%s: %s %s\n",
instr.getAddress(),
instr.toString(),
comment));
}
return result.toString();
} catch (Exception e) {
return "Error disassembling function: " + e.getMessage();
}
}
/**
* Set a comment using the specified comment type (PRE_COMMENT or EOL_COMMENT)
*/
private boolean setCommentAtAddress(String addressStr, String comment, int commentType, String transactionName) {
Program program = getCurrentProgram();
if (program == null) return false;
if (addressStr == null || addressStr.isEmpty() || comment == null) return false;
AtomicBoolean success = new AtomicBoolean(false);
try {
SwingUtilities.invokeAndWait(() -> {
int tx = program.startTransaction(transactionName);
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
program.getListing().setComment(addr, commentType, comment);
success.set(true);
} catch (Exception e) {
Msg.error(this, "Error setting " + transactionName.toLowerCase(), e);
} finally {
success.set(program.endTransaction(tx, success.get()));
}
});
} catch (InterruptedException | InvocationTargetException e) {
Msg.error(this, "Failed to execute " + transactionName.toLowerCase() + " on Swing thread", e);
}
return success.get();
}
/**
* Set a comment for a given address in the function pseudocode
*/
private boolean setDecompilerComment(String addressStr, String comment) {
return setCommentAtAddress(addressStr, comment, CodeUnit.PRE_COMMENT, "Set decompiler comment");
}
/**
* Set a comment for a given address in the function disassembly
*/
private boolean setDisassemblyComment(String addressStr, String comment) {
return setCommentAtAddress(addressStr, comment, CodeUnit.EOL_COMMENT, "Set disassembly comment");
}
/**
* Class to hold the result of a prototype setting operation
*/
private static class PrototypeResult {
private final boolean success;
private final String errorMessage;
public PrototypeResult(boolean success, String errorMessage) {
this.success = success;
this.errorMessage = errorMessage;
}
public boolean isSuccess() {
return success;
}
public String getErrorMessage() {
return errorMessage;
}
}
/**
* Rename a function by its address
*/
private boolean renameFunctionByAddress(String functionAddrStr, String newName) {
Program program = getCurrentProgram();
if (program == null) return false;
if (functionAddrStr == null || functionAddrStr.isEmpty() ||
newName == null || newName.isEmpty()) {
return false;
}
AtomicBoolean success = new AtomicBoolean(false);
try {
SwingUtilities.invokeAndWait(() -> {
performFunctionRename(program, functionAddrStr, newName, success);
});
} catch (InterruptedException | InvocationTargetException e) {
Msg.error(this, "Failed to execute rename function on Swing thread", e);
}
return success.get();
}
/**
* Helper method to perform the actual function rename within a transaction
*/
private void performFunctionRename(Program program, String functionAddrStr, String newName, AtomicBoolean success) {
int tx = program.startTransaction("Rename function by address");
try {
Address addr = program.getAddressFactory().getAddress(functionAddrStr);
Function func = getFunctionForAddress(program, addr);
if (func == null) {
Msg.error(this, "Could not find function at address: " + functionAddrStr);
return;
}
func.setName(newName, SourceType.USER_DEFINED);
success.set(true);
} catch (Exception e) {
Msg.error(this, "Error renaming function by address", e);
} finally {
program.endTransaction(tx, success.get());
}
}
/**
* Set a function's prototype with proper error handling using ApplyFunctionSignatureCmd
*/
private PrototypeResult setFunctionPrototype(String functionAddrStr, String prototype) {
// Input validation
Program program = getCurrentProgram();
if (program == null) return new PrototypeResult(false, "No program loaded");
if (functionAddrStr == null || functionAddrStr.isEmpty()) {
return new PrototypeResult(false, "Function address is required");
}
if (prototype == null || prototype.isEmpty()) {
return new PrototypeResult(false, "Function prototype is required");
}
final StringBuilder errorMessage = new StringBuilder();
final AtomicBoolean success = new AtomicBoolean(false);
try {
SwingUtilities.invokeAndWait(() ->
applyFunctionPrototype(program, functionAddrStr, prototype, success, errorMessage));
} catch (InterruptedException | InvocationTargetException e) {
String msg = "Failed to set function prototype on Swing thread: " + e.getMessage();
errorMessage.append(msg);
Msg.error(this, msg, e);
}
return new PrototypeResult(success.get(), errorMessage.toString());
}
/**
* Helper method that applies the function prototype within a transaction
*/
private void applyFunctionPrototype(Program program, String functionAddrStr, String prototype,
AtomicBoolean success, StringBuilder errorMessage) {
try {
// Get the address and function
Address addr = program.getAddressFactory().getAddress(functionAddrStr);
Function func = getFunctionForAddress(program, addr);
if (func == null) {
String msg = "Could not find function at address: " + functionAddrStr;
errorMessage.append(msg);
Msg.error(this, msg);
return;
}
Msg.info(this, "Setting prototype for function " + func.getName() + ": " + prototype);
// Store original prototype as a comment for reference
addPrototypeComment(program, func, prototype);
// Use ApplyFunctionSignatureCmd to parse and apply the signature
parseFunctionSignatureAndApply(program, addr, prototype, success, errorMessage);
} catch (Exception e) {
String msg = "Error setting function prototype: " + e.getMessage();
errorMessage.append(msg);
Msg.error(this, msg, e);
}
}
/**
* Add a comment showing the prototype being set
*/
private void addPrototypeComment(Program program, Function func, String prototype) {
int txComment = program.startTransaction("Add prototype comment");
try {
program.getListing().setComment(
func.getEntryPoint(),
CodeUnit.PLATE_COMMENT,
"Setting prototype: " + prototype
);
} finally {
program.endTransaction(txComment, true);
}
}
/**
* Parse and apply the function signature with error handling
*/
private void parseFunctionSignatureAndApply(Program program, Address addr, String prototype,
AtomicBoolean success, StringBuilder errorMessage) {
// Use ApplyFunctionSignatureCmd to parse and apply the signature
int txProto = program.startTransaction("Set function prototype");
try {
// Get data type manager
DataTypeManager dtm = program.getDataTypeManager();
// Get data type manager service
ghidra.app.services.DataTypeManagerService dtms =
tool.getService(ghidra.app.services.DataTypeManagerService.class);
// Create function signature parser
ghidra.app.util.parser.FunctionSignatureParser parser =
new ghidra.app.util.parser.FunctionSignatureParser(dtm, dtms);
// Parse the prototype into a function signature
ghidra.program.model.data.FunctionDefinitionDataType sig = parser.parse(null, prototype);
if (sig == null) {
String msg = "Failed to parse function prototype";
errorMessage.append(msg);
Msg.error(this, msg);
return;
}
// Create and apply the command
ghidra.app.cmd.function.ApplyFunctionSignatureCmd cmd =
new ghidra.app.cmd.function.ApplyFunctionSignatureCmd(
addr, sig, SourceType.USER_DEFINED);
// Apply the command to the program
boolean cmdResult = cmd.applyTo(program, new ConsoleTaskMonitor());
if (cmdResult) {
success.set(true);
Msg.info(this, "Successfully applied function signature");
} else {
String msg = "Command failed: " + cmd.getStatusMsg();
errorMessage.append(msg);
Msg.error(this, msg);
}
} catch (Exception e) {
String msg = "Error applying function signature: " + e.getMessage();
errorMessage.append(msg);
Msg.error(this, msg, e);
} finally {
program.endTransaction(txProto, success.get());
}
}
/**
* Set a local variable's type using HighFunctionDBUtil.updateDBVariable
*/
private boolean setLocalVariableType(String functionAddrStr, String variableName, String newType) {
// Input validation
Program program = getCurrentProgram();
if (program == null) return false;
if (functionAddrStr == null || functionAddrStr.isEmpty() ||
variableName == null || variableName.isEmpty() ||
newType == null || newType.isEmpty()) {
return false;
}
AtomicBoolean success = new AtomicBoolean(false);
try {
SwingUtilities.invokeAndWait(() ->
applyVariableType(program, functionAddrStr, variableName, newType, success));
} catch (InterruptedException | InvocationTargetException e) {
Msg.error(this, "Failed to execute set variable type on Swing thread", e);
}
return success.get();
}
/**
* Helper method that performs the actual variable type change
*/
private void applyVariableType(Program program, String functionAddrStr,
String variableName, String newType, AtomicBoolean success) {
try {
// Find the function
Address addr = program.getAddressFactory().getAddress(functionAddrStr);
Function func = getFunctionForAddress(program, addr);
if (func == null) {
Msg.error(this, "Could not find function at address: " + functionAddrStr);
return;
}
DecompileResults results = decompileFunction(func, program);
if (results == null || !results.decompileCompleted()) {
return;
}
ghidra.program.model.pcode.HighFunction highFunction = results.getHighFunction();
if (highFunction == null) {
Msg.error(this, "No high function available");
return;
}
// Find the symbol by name
HighSymbol symbol = findSymbolByName(highFunction, variableName);
if (symbol == null) {
Msg.error(this, "Could not find variable '" + variableName + "' in decompiled function");
return;
}
// Get high variable
HighVariable highVar = symbol.getHighVariable();
if (highVar == null) {
Msg.error(this, "No HighVariable found for symbol: " + variableName);
return;
}
Msg.info(this, "Found high variable for: " + variableName +
" with current type " + highVar.getDataType().getName());
// Find the data type
DataTypeManager dtm = program.getDataTypeManager();
DataType dataType = resolveDataType(dtm, newType);
if (dataType == null) {
Msg.error(this, "Could not resolve data type: " + newType);
return;
}
Msg.info(this, "Using data type: " + dataType.getName() + " for variable " + variableName);
// Apply the type change in a transaction
updateVariableType(program, symbol, dataType, success);
} catch (Exception e) {
Msg.error(this, "Error setting variable type: " + e.getMessage());
}
}
/**
* Find a high symbol by name in the given high function
*/
private HighSymbol findSymbolByName(ghidra.program.model.pcode.HighFunction highFunction, String variableName) {
Iterator symbols = highFunction.getLocalSymbolMap().getSymbols();
while (symbols.hasNext()) {
HighSymbol s = symbols.next();
if (s.getName().equals(variableName)) {
return s;
}
}
return null;
}
/**
* Decompile a function and return the results
*/
private DecompileResults decompileFunction(Function func, Program program) {
// Set up decompiler for accessing the decompiled function
DecompInterface decomp = new DecompInterface();
decomp.openProgram(program);
decomp.setSimplificationStyle("decompile"); // Full decompilation
// Decompile the function
DecompileResults results = decomp.decompileFunction(func, 60, new ConsoleTaskMonitor());
if (!results.decompileCompleted()) {
Msg.error(this, "Could not decompile function: " + results.getErrorMessage());
return null;
}
return results;
}
/**
* Apply the type update in a transaction
*/
private void updateVariableType(Program program, HighSymbol symbol, DataType dataType, AtomicBoolean success) {
int tx = program.startTransaction("Set variable type");
try {
// Use HighFunctionDBUtil to update the variable with the new type
HighFunctionDBUtil.updateDBVariable(
symbol, // The high symbol to modify
symbol.getName(), // Keep original name
dataType, // The new data type
SourceType.USER_DEFINED // Mark as user-defined
);
success.set(true);
Msg.info(this, "Successfully set variable type using HighFunctionDBUtil");
} catch (Exception e) {
Msg.error(this, "Error setting variable type: " + e.getMessage());
} finally {
program.endTransaction(tx, success.get());
}
}
/**
* Get all references to a specific address (xref to)
*/
private String getXrefsTo(String addressStr, int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (addressStr == null || addressStr.isEmpty()) return "Address is required";
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
ReferenceManager refManager = program.getReferenceManager();
ReferenceIterator refIter = refManager.getReferencesTo(addr);
List refs = new ArrayList<>();
while (refIter.hasNext()) {
Reference ref = refIter.next();
Address fromAddr = ref.getFromAddress();
RefType refType = ref.getReferenceType();
Function fromFunc = program.getFunctionManager().getFunctionContaining(fromAddr);
String funcInfo = (fromFunc != null) ? " in " + fromFunc.getName() : "";
refs.add(String.format("From %s%s [%s]", fromAddr, funcInfo, refType.getName()));
}
return paginateList(refs, offset, limit);
} catch (Exception e) {
return "Error getting references to address: " + e.getMessage();
}
}
/**
* Get all references from a specific address (xref from)
*/
private String getXrefsFrom(String addressStr, int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (addressStr == null || addressStr.isEmpty()) return "Address is required";
try {
Address addr = program.getAddressFactory().getAddress(addressStr);
ReferenceManager refManager = program.getReferenceManager();
Reference[] references = refManager.getReferencesFrom(addr);
List refs = new ArrayList<>();
for (Reference ref : references) {
Address toAddr = ref.getToAddress();
RefType refType = ref.getReferenceType();
String targetInfo = "";
Function toFunc = program.getFunctionManager().getFunctionAt(toAddr);
if (toFunc != null) {
targetInfo = " to function " + toFunc.getName();
} else {
Data data = program.getListing().getDataAt(toAddr);
if (data != null) {
targetInfo = " to data " + (data.getLabel() != null ? data.getLabel() : data.getPathName());
}
}
refs.add(String.format("To %s%s [%s]", toAddr, targetInfo, refType.getName()));
}
return paginateList(refs, offset, limit);
} catch (Exception e) {
return "Error getting references from address: " + e.getMessage();
}
}
/**
* Get all references to a specific function by name
*/
private String getFunctionXrefs(String functionName, int offset, int limit) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
if (functionName == null || functionName.isEmpty()) return "Function name is required";
try {
List refs = new ArrayList<>();
FunctionManager funcManager = program.getFunctionManager();
for (Function function : funcManager.getFunctions(true)) {
if (function.getName().equals(functionName)) {
Address entryPoint = function.getEntryPoint();
ReferenceIterator refIter = program.getReferenceManager().getReferencesTo(entryPoint);
while (refIter.hasNext()) {
Reference ref = refIter.next();
Address fromAddr = ref.getFromAddress();
RefType refType = ref.getReferenceType();
Function fromFunc = funcManager.getFunctionContaining(fromAddr);
String funcInfo = (fromFunc != null) ? " in " + fromFunc.getName() : "";
refs.add(String.format("From %s%s [%s]", fromAddr, funcInfo, refType.getName()));
}
}
}
if (refs.isEmpty()) {
return "No references found to function: " + functionName;
}
return paginateList(refs, offset, limit);
} catch (Exception e) {
return "Error getting function references: " + e.getMessage();
}
}
/**
* List all defined strings in the program with their addresses
*/
private String listDefinedStrings(int offset, int limit, String filter) {
Program program = getCurrentProgram();
if (program == null) return "No program loaded";
List lines = new ArrayList<>();
DataIterator dataIt = program.getListing().getDefinedData(true);
while (dataIt.hasNext()) {
Data data = dataIt.next();
if (data != null && isStringData(data)) {
String value = data.getValue() != null ? data.getValue().toString() : "";
if (filter == null || value.toLowerCase().contains(filter.toLowerCase())) {
String escapedValue = escapeString(value);
lines.add(String.format("%s: \"%s\"", data.getAddress(), escapedValue));
}
}
}
return paginateList(lines, offset, limit);
}
/**
* Check if the given data is a string type
*/
private boolean isStringData(Data data) {
if (data == null) return false;
DataType dt = data.getDataType();
String typeName = dt.getName().toLowerCase();
return typeName.contains("string") || typeName.contains("char") || typeName.equals("unicode");
}
/**
* Escape special characters in a string for display
*/
private String escapeString(String input) {
if (input == null) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 32 && c < 127) {
sb.append(c);
} else if (c == '\n') {
sb.append("\\n");
} else if (c == '\r') {
sb.append("\\r");
} else if (c == '\t') {
sb.append("\\t");
} else {
sb.append(String.format("\\x%02x", (int)c & 0xFF));
}
}
return sb.toString();
}
/**
* Resolves a data type by name, handling common types and pointer types
* @param dtm The data type manager
* @param typeName The type name to resolve
* @return The resolved DataType, or null if not found
*/
private DataType resolveDataType(DataTypeManager dtm, String typeName) {
// First try to find exact match in all categories
DataType dataType = findDataTypeByNameInAllCategories(dtm, typeName);
if (dataType != null) {
Msg.info(this, "Found exact data type match: " + dataType.getPathName());
return dataType;
}
// Check for Windows-style pointer types (PXXX)
if (typeName.startsWith("P") && typeName.length() > 1) {
String baseTypeName = typeName.substring(1);
// Special case for PVOID
if (baseTypeName.equals("VOID")) {
return new PointerDataType(dtm.getDataType("/void"));
}
// Try to find the base type
DataType baseType = findDataTypeByNameInAllCategories(dtm, baseTypeName);
if (baseType != null) {
return new PointerDataType(baseType);
}
Msg.warn(this, "Base type not found for " + typeName + ", defaulting to void*");
return new PointerDataType(dtm.getDataType("/void"));
}
// Handle common built-in types
switch (typeName.toLowerCase()) {
case "int":
case "long":
return dtm.getDataType("/int");
case "uint":
case "unsigned int":
case "unsigned long":
case "dword":
return dtm.getDataType("/uint");
case "short":
return dtm.getDataType("/short");
case "ushort":
case "unsigned short":
case "word":
return dtm.getDataType("/ushort");
case "char":
case "byte":
return dtm.getDataType("/char");
case "uchar":
case "unsigned char":
return dtm.getDataType("/uchar");
case "longlong":
case "__int64":
return dtm.getDataType("/longlong");
case "ulonglong":
case "unsigned __int64":
return dtm.getDataType("/ulonglong");
case "bool":
case "boolean":
return dtm.getDataType("/bool");
case "void":
return dtm.getDataType("/void");
default:
// Try as a direct path
DataType directType = dtm.getDataType("/" + typeName);
if (directType != null) {
return directType;
}
// Fallback to int if we couldn't find it
Msg.warn(this, "Unknown type: " + typeName + ", defaulting to int");
return dtm.getDataType("/int");
}
}
/**
* Find a data type by name in all categories/folders of the data type manager
* This searches through all categories rather than just the root
*/
private DataType findDataTypeByNameInAllCategories(DataTypeManager dtm, String typeName) {
// Try exact match first
DataType result = searchByNameInAllCategories(dtm, typeName);
if (result != null) {
return result;
}
// Try lowercase
return searchByNameInAllCategories(dtm, typeName.toLowerCase());
}
/**
* Helper method to search for a data type by name in all categories
*/
private DataType searchByNameInAllCategories(DataTypeManager dtm, String name) {
// Get all data types from the manager
Iterator allTypes = dtm.getAllDataTypes();
while (allTypes.hasNext()) {
DataType dt = allTypes.next();
// Check if the name matches exactly (case-sensitive)
if (dt.getName().equals(name)) {
return dt;
}
// For case-insensitive, we want an exact match except for case
if (dt.getName().equalsIgnoreCase(name)) {
return dt;
}
}
return null;
}
// ----------------------------------------------------------------------------------
// Utility: parse query params, parse post params, pagination, etc.
// ----------------------------------------------------------------------------------
/**
* Parse query parameters from the URL, e.g. ?offset=10&limit=100
*/
private Map parseQueryParams(HttpExchange exchange) {
Map result = new HashMap<>();
String query = exchange.getRequestURI().getQuery(); // e.g. offset=10&limit=100
if (query != null) {
String[] pairs = query.split("&");
for (String p : pairs) {
String[] kv = p.split("=");
if (kv.length == 2) {
// URL decode parameter values
try {
String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);
String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);
result.put(key, value);
} catch (Exception e) {
Msg.error(this, "Error decoding URL parameter", e);
}
}
}
}
return result;
}
/**
* Parse post body form params, e.g. oldName=foo&newName=bar
*/
private Map parsePostParams(HttpExchange exchange) throws IOException {
byte[] body = exchange.getRequestBody().readAllBytes();
String bodyStr = new String(body, StandardCharsets.UTF_8);
Map params = new HashMap<>();
for (String pair : bodyStr.split("&")) {
String[] kv = pair.split("=");
if (kv.length == 2) {
// URL decode parameter values
try {
String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8);
String value = URLDecoder.decode(kv[1], StandardCharsets.UTF_8);
params.put(key, value);
} catch (Exception e) {
Msg.error(this, "Error decoding URL parameter", e);
}
}
}
return params;
}
/**
* Convert a list of strings into one big newline-delimited string, applying offset & limit.
*/
private String paginateList(List items, int offset, int limit) {
int start = Math.max(0, offset);
int end = Math.min(items.size(), offset + limit);
if (start >= items.size()) {
return ""; // no items in range
}
List sub = items.subList(start, end);
return String.join("\n", sub);
}
/**
* Parse an integer from a string, or return defaultValue if null/invalid.
*/
private int parseIntOrDefault(String val, int defaultValue) {
if (val == null) return defaultValue;
try {
return Integer.parseInt(val);
}
catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Escape non-ASCII chars to avoid potential decode issues.
*/
private String escapeNonAscii(String input) {
if (input == null) return "";
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
if (c >= 32 && c < 127) {
sb.append(c);
}
else {
sb.append("\\x");
sb.append(Integer.toHexString(c & 0xFF));
}
}
return sb.toString();
}
public Program getCurrentProgram() {
ProgramManager pm = tool.getService(ProgramManager.class);
return pm != null ? pm.getCurrentProgram() : null;
}
private void sendResponse(HttpExchange exchange, String response) throws IOException {
byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
@Override
public void dispose() {
if (server != null) {
Msg.info(this, "Stopping GhidraMCP HTTP server...");
server.stop(1); // Stop with a small delay (e.g., 1 second) for connections to finish
server = null; // Nullify the reference
Msg.info(this, "GhidraMCP HTTP server stopped.");
}
super.dispose();
}
}
================================================
FILE: src/main/resources/META-INF/MANIFEST.MF
================================================
Manifest-Version: 1.0
Plugin-Class: com.lauriewired.GhidraMCP
Plugin-Name: GhidraMCP
Plugin-Version: 1.0
Plugin-Author: LaurieWired
Plugin-Description: A custom plugin by LaurieWired
================================================
FILE: src/main/resources/Module.manifest
================================================
GHIDRA_MODULE_NAME=GhidraMCP
GHIDRA_MODULE_DESC=An HTTP server plugin for Ghidra
================================================
FILE: src/main/resources/extension.properties
================================================
name=GhidraMCP
description=A plugin that runs an embedded HTTP server to expose program data.
author=LaurieWired
createdOn=2025-03-22
version=11.3.2
ghidraVersion=11.3.2
================================================
FILE: src/test/java/com/lauriewired/AppTest.java
================================================
package com.lauriewired;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}