mseep-mcp-server-windbg 0.1.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mseep_mcp_server_windbg-0.1.1/LICENSE +21 -0
- mseep_mcp_server_windbg-0.1.1/PKG-INFO +22 -0
- mseep_mcp_server_windbg-0.1.1/README.md +210 -0
- mseep_mcp_server_windbg-0.1.1/pyproject.toml +53 -0
- mseep_mcp_server_windbg-0.1.1/setup.cfg +4 -0
- mseep_mcp_server_windbg-0.1.1/src/mcp_server_windbg/__init__.py +26 -0
- mseep_mcp_server_windbg-0.1.1/src/mcp_server_windbg/__main__.py +5 -0
- mseep_mcp_server_windbg-0.1.1/src/mcp_server_windbg/cdb_session.py +253 -0
- mseep_mcp_server_windbg-0.1.1/src/mcp_server_windbg/server.py +470 -0
- mseep_mcp_server_windbg-0.1.1/src/mcp_server_windbg/tests/test_cdb.py +119 -0
- mseep_mcp_server_windbg-0.1.1/src/mcp_server_windbg/tests/test_remote_debugging.py +232 -0
- mseep_mcp_server_windbg-0.1.1/src/mseep_mcp_server_windbg.egg-info/PKG-INFO +22 -0
- mseep_mcp_server_windbg-0.1.1/src/mseep_mcp_server_windbg.egg-info/SOURCES.txt +15 -0
- mseep_mcp_server_windbg-0.1.1/src/mseep_mcp_server_windbg.egg-info/dependency_links.txt +1 -0
- mseep_mcp_server_windbg-0.1.1/src/mseep_mcp_server_windbg.egg-info/entry_points.txt +2 -0
- mseep_mcp_server_windbg-0.1.1/src/mseep_mcp_server_windbg.egg-info/requires.txt +5 -0
- mseep_mcp_server_windbg-0.1.1/src/mseep_mcp_server_windbg.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Sven Scharmentke
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
@@ -0,0 +1,22 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: mseep-mcp-server-windbg
|
3
|
+
Version: 0.1.1
|
4
|
+
Summary: A Model Context Protocol server providing tools to analyze Windows crash dumps using WinDBG/CDB
|
5
|
+
Author-email: mseep <support@skydeck.ai>
|
6
|
+
License: MIT
|
7
|
+
Keywords: windbg,cdb,mcp,llm,crash-analysis
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
9
|
+
Classifier: Intended Audience :: Developers
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
13
|
+
Requires-Python: >=3.10
|
14
|
+
Description-Content-Type: text/plain
|
15
|
+
License-File: LICENSE
|
16
|
+
Requires-Dist: mcp>=1.1.3
|
17
|
+
Requires-Dist: pydantic>=2.0.0
|
18
|
+
Provides-Extra: test
|
19
|
+
Requires-Dist: pytest>=7.0.0; extra == "test"
|
20
|
+
Dynamic: license-file
|
21
|
+
|
22
|
+
Package managed by MseeP.ai
|
@@ -0,0 +1,210 @@
|
|
1
|
+
# MCP Server for WinDBG Crash Analysis
|
2
|
+
|
3
|
+
A Model Context Protocol server providing tools to analyze Windows crash dumps and connect to remote debugging sessions using WinDBG/CDB.
|
4
|
+
|
5
|
+
## Overview
|
6
|
+
|
7
|
+
This MCP server integrates with [CDB](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/opening-a-crash-dump-file-using-cdb) to enable AI models to:
|
8
|
+
- Analyze Windows crash dumps
|
9
|
+
- Connect to remote debugging sessions
|
10
|
+
- Execute WinDBG commands on both dump files and live debugging targets
|
11
|
+
|
12
|
+
## TL;DR
|
13
|
+
|
14
|
+
### What is this?
|
15
|
+
|
16
|
+
- Primarily, a tool that enables AI to interact with WinDBG for both crash dump analysis and live debugging.
|
17
|
+
- The whole "magic" is giving LLMs the ability to execute debugger commands on crash dumps or remote debugging targets. Used creatively, this is quite powerful and a big productivity improvement.
|
18
|
+
|
19
|
+
This means, that this is:
|
20
|
+
|
21
|
+
- A bridge connecting LLMs (AI) with WinDBG (CDB) for assisted crash dump analysis and remote debugging.
|
22
|
+
- A way to get immediate first-level triage analysis, useful for categorizing crash dumps or auto-analyzing simple cases.
|
23
|
+
- A platform for natural language-based "vibe" analysis, allowing you to ask the LLM to inspect specific areas:
|
24
|
+
- Examples for **crash dump analysis**:
|
25
|
+
- "Show me the call stack with `k` and explain what might be causing this access violation"
|
26
|
+
- "Execute `!peb` and tell me if there are any environment variables that might affect this crash"
|
27
|
+
- "Examine frame 3 and analyze the parameters passed to this function"
|
28
|
+
- "Use `dx -r2` on this object and explain its state" (equivalent to `dx -r2 ((MyClass*)0x12345678)`)
|
29
|
+
- "Analyze this heap address with `!heap -p -a 0xABCD1234` and check for buffer overflow"
|
30
|
+
- "Run `.ecxr` followed by `k` and explain the exception's root cause"
|
31
|
+
- Examples for **remote debugging**:
|
32
|
+
- "Connect to tcp:Port=5005,Server=192.168.0.100 and show me the current thread state"
|
33
|
+
- "Set a breakpoint on function XYZ and continue execution"
|
34
|
+
- "Check for timing issues in the thread pool with `!runaway` and `!threads`"
|
35
|
+
- "Examine memory around this address with `db/dw/dd` to identify corruption patterns"
|
36
|
+
- "Show me all threads with `~*k` and identify which one is causing the hang"
|
37
|
+
- ...and many other analytical approaches based on your specific debugging scenario
|
38
|
+
|
39
|
+
### What is this not?
|
40
|
+
|
41
|
+
- A magical solution that automatically fixes all issues.
|
42
|
+
- A full-featured product with custom AI. Instead, it's a **simple Python wrapper around CDB** that **relies** on the **LLM's WinDBG** expertise, best complemented by your own domain knowledge.
|
43
|
+
|
44
|
+
## Blog
|
45
|
+
|
46
|
+
I've written about the whole journey in blog.
|
47
|
+
|
48
|
+
- [The Future of Crash Analysis: AI Meets WinDBG](https://svnscha.de/posts/ai-meets-windbg/)
|
49
|
+
|
50
|
+
## Prerequisites
|
51
|
+
|
52
|
+
- Python 3.10 or higher
|
53
|
+
- Windows operating system with **Debugging Tools for Windows** installed.
|
54
|
+
- This is part of the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/).
|
55
|
+
- A LLM supporting Model Context Protocol.
|
56
|
+
- I have tested with Claude 3.7 Sonnet through GitHub Copilot and I am pretty statisfied with the results.
|
57
|
+
- For GitHub Copilot, requires Model Context Protocol in Chat feature enabled.
|
58
|
+
- See [Extending Copilot Chat with the Model Context Protocol (MCP)](https://docs.github.com/en/copilot/customizing-copilot/extending-copilot-chat-with-mcp).
|
59
|
+
|
60
|
+
|
61
|
+
## Development Setup
|
62
|
+
|
63
|
+
1. Clone the repository:
|
64
|
+
|
65
|
+
```bash
|
66
|
+
git clone https://github.com/svnscha/mcp-windbg.git
|
67
|
+
cd mcp-windbg
|
68
|
+
```
|
69
|
+
|
70
|
+
2. Create and activate a virtual environment:
|
71
|
+
|
72
|
+
```bash
|
73
|
+
python -m venv .venv
|
74
|
+
.\.venv\Scripts\activate
|
75
|
+
```
|
76
|
+
|
77
|
+
3. Install the package in development mode:
|
78
|
+
|
79
|
+
```bash
|
80
|
+
pip install -e .
|
81
|
+
```
|
82
|
+
|
83
|
+
4. Install test dependencies:
|
84
|
+
|
85
|
+
```bash
|
86
|
+
pip install -e ".[test]"
|
87
|
+
```
|
88
|
+
|
89
|
+
## Usage
|
90
|
+
|
91
|
+
### Integrating with VS Code
|
92
|
+
|
93
|
+
To integrate this MCP server with Visual Studio Code:
|
94
|
+
|
95
|
+
1. Create a `.vscode/mcp.json` file in your workspace with the following configuration:
|
96
|
+
|
97
|
+
```json
|
98
|
+
{
|
99
|
+
"servers": {
|
100
|
+
"mcp_server_windbg": {
|
101
|
+
"type": "stdio",
|
102
|
+
"command": "${workspaceFolder}/.venv/Scripts/python",
|
103
|
+
"args": [
|
104
|
+
"-m",
|
105
|
+
"mcp_server_windbg"
|
106
|
+
],
|
107
|
+
"env": {
|
108
|
+
"_NT_SYMBOL_PATH": "SRV*C:\\Symbols*https://msdl.microsoft.com/download/symbols"
|
109
|
+
}
|
110
|
+
},
|
111
|
+
}
|
112
|
+
}
|
113
|
+
```
|
114
|
+
|
115
|
+
Alternatively, edit your user settings to enable it globally (independent of workspace).
|
116
|
+
Once added and with Model Context Protocol in Chat feature enabled, the tools from this model context protocol server are available in Agent mode.
|
117
|
+
|
118
|
+
That's how it should look like:
|
119
|
+
|
120
|
+

|
121
|
+
|
122
|
+
|
123
|
+
### Starting the MCP Server (optional)
|
124
|
+
|
125
|
+
If integrated through Copilot, you don't need this. The IDE will auto-start the MCP.
|
126
|
+
|
127
|
+
Start the server using the module command:
|
128
|
+
|
129
|
+
```bash
|
130
|
+
python -m mcp_server_windbg
|
131
|
+
```
|
132
|
+
|
133
|
+
### Command Line Options
|
134
|
+
|
135
|
+
```bash
|
136
|
+
python -m mcp_server_windbg [options]
|
137
|
+
```
|
138
|
+
|
139
|
+
Available options:
|
140
|
+
|
141
|
+
- `--cdb-path CDB_PATH`: Custom path to cdb.exe
|
142
|
+
- `--symbols-path SYMBOLS_PATH`: Custom symbols path
|
143
|
+
- `--timeout TIMEOUT`: Command timeout in seconds (default: 30)
|
144
|
+
- `--verbose`: Enable verbose output
|
145
|
+
|
146
|
+
|
147
|
+
2. Customize the configuration as needed:
|
148
|
+
- Adjust the Python interpreter path if needed
|
149
|
+
- Set custom paths for CDB by adding `"--cdb-path": "C:\\path\\to\\cdb.exe"` to the `args` array
|
150
|
+
- Set the symbol path environment variable as shown above, or add `"--symbols-path"` to the args
|
151
|
+
|
152
|
+
### Integration with Copilot
|
153
|
+
|
154
|
+
Once the server is configured in VS Code:
|
155
|
+
|
156
|
+
1. Enable MCP in Chat feature in Copilot settings
|
157
|
+
2. The MCP server will appear in Copilot's available tools
|
158
|
+
3. The WinDBG analysis capabilities will be accessible through Copilot's interface
|
159
|
+
4. You can now analyze crash dumps directly through Copilot using natural language queries
|
160
|
+
|
161
|
+
## Tools
|
162
|
+
|
163
|
+
This server provides the following tools:
|
164
|
+
|
165
|
+
### Crash Dump Analysis
|
166
|
+
- `open_windbg_dump`: Analyze a Windows crash dump file using common WinDBG commands
|
167
|
+
- `close_windbg_dump`: Unload a crash dump and release resources
|
168
|
+
|
169
|
+
### Remote Debugging
|
170
|
+
- `open_windbg_remote`: Connect to a remote debugging session using a connection string (e.g., `tcp:Port=5005,Server=192.168.0.100`)
|
171
|
+
- `close_windbg_remote`: Disconnect from a remote debugging session and release resources
|
172
|
+
|
173
|
+
### General Commands
|
174
|
+
- `run_windbg_cmd`: Execute a specific WinDBG command on either a loaded crash dump or active remote session
|
175
|
+
- `list_windbg_dumps`: List Windows crash dump (.dmp) files in the specified directory
|
176
|
+
|
177
|
+
## Running Tests
|
178
|
+
|
179
|
+
To run the tests:
|
180
|
+
|
181
|
+
```bash
|
182
|
+
pytest
|
183
|
+
```
|
184
|
+
|
185
|
+
## Troubleshooting
|
186
|
+
|
187
|
+
### CDB Not Found
|
188
|
+
|
189
|
+
If you get a "CDB executable not found" error, make sure:
|
190
|
+
|
191
|
+
1. WinDBG/CDB is installed on your system
|
192
|
+
2. The CDB executable is in your system PATH, or
|
193
|
+
3. You specify the path using the `--cdb-path` option
|
194
|
+
|
195
|
+
### Symbol Path Issues
|
196
|
+
|
197
|
+
For proper crash analysis, set up your symbol path:
|
198
|
+
|
199
|
+
1. Use the `--symbols-path` parameter, or
|
200
|
+
2. Set the `_NT_SYMBOL_PATH` environment variable
|
201
|
+
|
202
|
+
### Common Symbol Paths
|
203
|
+
|
204
|
+
```
|
205
|
+
SRV*C:\Symbols*https://msdl.microsoft.com/download/symbols
|
206
|
+
```
|
207
|
+
|
208
|
+
## License
|
209
|
+
|
210
|
+
MIT
|
@@ -0,0 +1,53 @@
|
|
1
|
+
[project]
|
2
|
+
name = "mseep-mcp-server-windbg"
|
3
|
+
version = "0.1.1"
|
4
|
+
description = "A Model Context Protocol server providing tools to analyze Windows crash dumps using WinDBG/CDB"
|
5
|
+
requires-python = ">=3.10"
|
6
|
+
authors = [
|
7
|
+
{ name = "mseep", email = "support@skydeck.ai" },
|
8
|
+
]
|
9
|
+
keywords = [
|
10
|
+
"windbg",
|
11
|
+
"cdb",
|
12
|
+
"mcp",
|
13
|
+
"llm",
|
14
|
+
"crash-analysis",
|
15
|
+
]
|
16
|
+
classifiers = [
|
17
|
+
"Development Status :: 4 - Beta",
|
18
|
+
"Intended Audience :: Developers",
|
19
|
+
"License :: OSI Approved :: MIT License",
|
20
|
+
"Programming Language :: Python :: 3",
|
21
|
+
"Programming Language :: Python :: 3.10",
|
22
|
+
]
|
23
|
+
dependencies = [
|
24
|
+
"mcp>=1.1.3",
|
25
|
+
"pydantic>=2.0.0",
|
26
|
+
]
|
27
|
+
|
28
|
+
[project.readme]
|
29
|
+
content-type = "text/plain"
|
30
|
+
text = "Package managed by MseeP.ai"
|
31
|
+
|
32
|
+
[project.license]
|
33
|
+
text = "MIT"
|
34
|
+
|
35
|
+
[project.scripts]
|
36
|
+
mcp-server-windbg = "mcp_server_windbg:main"
|
37
|
+
|
38
|
+
[project.optional-dependencies]
|
39
|
+
test = [
|
40
|
+
"pytest>=7.0.0",
|
41
|
+
]
|
42
|
+
|
43
|
+
[build-system]
|
44
|
+
requires = [
|
45
|
+
"setuptools>=42",
|
46
|
+
"wheel",
|
47
|
+
]
|
48
|
+
build-backend = "setuptools.build_meta"
|
49
|
+
|
50
|
+
[tool.pytest.ini_options]
|
51
|
+
testpaths = [
|
52
|
+
"src/mcp_server_windbg/tests",
|
53
|
+
]
|
@@ -0,0 +1,26 @@
|
|
1
|
+
from .server import serve
|
2
|
+
|
3
|
+
def main():
|
4
|
+
"""MCP WinDBG Server - Windows crash dump analysis functionality for MCP"""
|
5
|
+
import argparse
|
6
|
+
import asyncio
|
7
|
+
|
8
|
+
parser = argparse.ArgumentParser(
|
9
|
+
description="Give a model the ability to analyze Windows crash dumps with WinDBG/CDB"
|
10
|
+
)
|
11
|
+
parser.add_argument("--cdb-path", type=str, help="Custom path to cdb.exe")
|
12
|
+
parser.add_argument("--symbols-path", type=str, help="Custom symbols path")
|
13
|
+
parser.add_argument("--timeout", type=int, default=30, help="Command timeout in seconds")
|
14
|
+
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
|
15
|
+
|
16
|
+
args = parser.parse_args()
|
17
|
+
asyncio.run(serve(
|
18
|
+
cdb_path=args.cdb_path,
|
19
|
+
symbols_path=args.symbols_path,
|
20
|
+
timeout=args.timeout,
|
21
|
+
verbose=args.verbose
|
22
|
+
))
|
23
|
+
|
24
|
+
|
25
|
+
if __name__ == "__main__":
|
26
|
+
main()
|
@@ -0,0 +1,253 @@
|
|
1
|
+
import subprocess
|
2
|
+
import threading
|
3
|
+
import re
|
4
|
+
import os
|
5
|
+
import platform
|
6
|
+
from typing import List, Optional
|
7
|
+
|
8
|
+
# Regular expression to detect CDB prompts
|
9
|
+
PROMPT_REGEX = re.compile(r"^\d+:\d+>\s*$")
|
10
|
+
|
11
|
+
# Command marker to reliably detect command completion
|
12
|
+
COMMAND_MARKER = ".echo COMMAND_COMPLETED_MARKER"
|
13
|
+
COMMAND_MARKER_PATTERN = re.compile(r"COMMAND_COMPLETED_MARKER")
|
14
|
+
|
15
|
+
# Default paths where cdb.exe might be located
|
16
|
+
DEFAULT_CDB_PATHS = [
|
17
|
+
r"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe",
|
18
|
+
r"C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\cdb.exe",
|
19
|
+
r"C:\Program Files\Debugging Tools for Windows (x64)\cdb.exe",
|
20
|
+
r"C:\Program Files\Debugging Tools for Windows (x86)\cdb.exe",
|
21
|
+
]
|
22
|
+
|
23
|
+
class CDBError(Exception):
|
24
|
+
"""Custom exception for CDB-related errors"""
|
25
|
+
pass
|
26
|
+
|
27
|
+
class CDBSession:
|
28
|
+
def __init__(
|
29
|
+
self,
|
30
|
+
dump_path: Optional[str] = None,
|
31
|
+
remote_connection: Optional[str] = None,
|
32
|
+
cdb_path: Optional[str] = None,
|
33
|
+
symbols_path: Optional[str] = None,
|
34
|
+
initial_commands: Optional[List[str]] = None,
|
35
|
+
timeout: int = 10,
|
36
|
+
verbose: bool = False,
|
37
|
+
additional_args: Optional[List[str]] = None
|
38
|
+
):
|
39
|
+
"""
|
40
|
+
Initialize a new CDB debugging session.
|
41
|
+
|
42
|
+
Args:
|
43
|
+
dump_path: Path to the crash dump file (mutually exclusive with remote_connection)
|
44
|
+
remote_connection: Remote debugging connection string (e.g., "tcp:Port=5005,Server=192.168.0.100")
|
45
|
+
cdb_path: Custom path to cdb.exe. If None, will try to find it automatically
|
46
|
+
symbols_path: Custom symbols path. If None, uses default Windows symbols
|
47
|
+
initial_commands: List of commands to run when CDB starts
|
48
|
+
timeout: Timeout in seconds for waiting for CDB responses
|
49
|
+
verbose: Whether to print additional debug information
|
50
|
+
additional_args: Additional arguments to pass to cdb.exe
|
51
|
+
|
52
|
+
Raises:
|
53
|
+
CDBError: If cdb.exe cannot be found or started
|
54
|
+
FileNotFoundError: If the dump file cannot be found
|
55
|
+
ValueError: If invalid parameters are provided
|
56
|
+
"""
|
57
|
+
# Validate that exactly one of dump_path or remote_connection is provided
|
58
|
+
if not dump_path and not remote_connection:
|
59
|
+
raise ValueError("Either dump_path or remote_connection must be provided")
|
60
|
+
if dump_path and remote_connection:
|
61
|
+
raise ValueError("dump_path and remote_connection are mutually exclusive")
|
62
|
+
|
63
|
+
if dump_path and not os.path.isfile(dump_path):
|
64
|
+
raise FileNotFoundError(f"Dump file not found: {dump_path}")
|
65
|
+
|
66
|
+
self.dump_path = dump_path
|
67
|
+
self.remote_connection = remote_connection
|
68
|
+
self.timeout = timeout
|
69
|
+
self.verbose = verbose
|
70
|
+
|
71
|
+
# Find cdb executable
|
72
|
+
self.cdb_path = self._find_cdb_executable(cdb_path)
|
73
|
+
if not self.cdb_path:
|
74
|
+
raise CDBError("Could not find cdb.exe. Please provide a valid path.")
|
75
|
+
|
76
|
+
# Prepare command args
|
77
|
+
cmd_args = [self.cdb_path]
|
78
|
+
|
79
|
+
# Add connection type specific arguments
|
80
|
+
if self.dump_path:
|
81
|
+
cmd_args.extend(["-z", self.dump_path])
|
82
|
+
elif self.remote_connection:
|
83
|
+
cmd_args.extend(["-remote", self.remote_connection])
|
84
|
+
|
85
|
+
# Add symbols path if provided
|
86
|
+
if symbols_path:
|
87
|
+
cmd_args.extend(["-y", symbols_path])
|
88
|
+
|
89
|
+
# Add any additional arguments
|
90
|
+
if additional_args:
|
91
|
+
cmd_args.extend(additional_args)
|
92
|
+
|
93
|
+
try:
|
94
|
+
self.process = subprocess.Popen(
|
95
|
+
cmd_args,
|
96
|
+
stdin=subprocess.PIPE,
|
97
|
+
stdout=subprocess.PIPE,
|
98
|
+
stderr=subprocess.STDOUT,
|
99
|
+
text=True,
|
100
|
+
bufsize=1
|
101
|
+
)
|
102
|
+
except Exception as e:
|
103
|
+
raise CDBError(f"Failed to start CDB process: {str(e)}")
|
104
|
+
|
105
|
+
self.output_lines = []
|
106
|
+
self.lock = threading.Lock()
|
107
|
+
self.ready_event = threading.Event()
|
108
|
+
self.reader_thread = threading.Thread(target=self._read_output)
|
109
|
+
self.reader_thread.daemon = True
|
110
|
+
self.reader_thread.start()
|
111
|
+
|
112
|
+
# Wait for CDB to initialize by sending an echo marker
|
113
|
+
try:
|
114
|
+
self._wait_for_prompt(timeout=self.timeout)
|
115
|
+
except CDBError:
|
116
|
+
self.shutdown()
|
117
|
+
raise CDBError("CDB initialization timed out")
|
118
|
+
|
119
|
+
# Run initial commands if provided
|
120
|
+
if initial_commands:
|
121
|
+
for cmd in initial_commands:
|
122
|
+
self.send_command(cmd)
|
123
|
+
|
124
|
+
def _find_cdb_executable(self, custom_path: Optional[str] = None) -> Optional[str]:
|
125
|
+
"""Find the cdb.exe executable"""
|
126
|
+
if custom_path and os.path.isfile(custom_path):
|
127
|
+
return custom_path
|
128
|
+
|
129
|
+
# If we're on Windows, try the default paths
|
130
|
+
if platform.system() == "Windows":
|
131
|
+
for path in DEFAULT_CDB_PATHS:
|
132
|
+
if os.path.isfile(path):
|
133
|
+
return path
|
134
|
+
|
135
|
+
return None
|
136
|
+
|
137
|
+
def _read_output(self):
|
138
|
+
"""Thread function to continuously read CDB output"""
|
139
|
+
if not self.process or not self.process.stdout:
|
140
|
+
return
|
141
|
+
|
142
|
+
buffer = []
|
143
|
+
try:
|
144
|
+
for line in self.process.stdout:
|
145
|
+
line = line.rstrip()
|
146
|
+
if self.verbose:
|
147
|
+
print(f"CDB > {line}")
|
148
|
+
|
149
|
+
with self.lock:
|
150
|
+
buffer.append(line)
|
151
|
+
# Check if the marker is in this line
|
152
|
+
if COMMAND_MARKER_PATTERN.search(line):
|
153
|
+
# Remove the marker line itself
|
154
|
+
if buffer and COMMAND_MARKER_PATTERN.search(buffer[-1]):
|
155
|
+
buffer.pop()
|
156
|
+
self.output_lines = buffer
|
157
|
+
buffer = []
|
158
|
+
self.ready_event.set()
|
159
|
+
except (IOError, ValueError) as e:
|
160
|
+
if self.verbose:
|
161
|
+
print(f"CDB output reader error: {e}")
|
162
|
+
|
163
|
+
def _wait_for_prompt(self, timeout=None):
|
164
|
+
"""Wait for CDB to be ready for commands by sending a marker"""
|
165
|
+
try:
|
166
|
+
self.ready_event.clear()
|
167
|
+
self.process.stdin.write(f"{COMMAND_MARKER}\n")
|
168
|
+
self.process.stdin.flush()
|
169
|
+
|
170
|
+
if not self.ready_event.wait(timeout=timeout or self.timeout):
|
171
|
+
raise CDBError(f"Timed out waiting for CDB prompt")
|
172
|
+
except IOError as e:
|
173
|
+
raise CDBError(f"Failed to communicate with CDB: {str(e)}")
|
174
|
+
|
175
|
+
def send_command(self, command: str, timeout: Optional[int] = None) -> List[str]:
|
176
|
+
"""
|
177
|
+
Send a command to CDB and return the output
|
178
|
+
|
179
|
+
Args:
|
180
|
+
command: The command to send
|
181
|
+
timeout: Custom timeout for this command (overrides instance timeout)
|
182
|
+
|
183
|
+
Returns:
|
184
|
+
List of output lines from CDB
|
185
|
+
|
186
|
+
Raises:
|
187
|
+
CDBError: If the command times out or CDB is not responsive
|
188
|
+
"""
|
189
|
+
if not self.process:
|
190
|
+
raise CDBError("CDB process is not running")
|
191
|
+
|
192
|
+
self.ready_event.clear()
|
193
|
+
with self.lock:
|
194
|
+
self.output_lines = []
|
195
|
+
|
196
|
+
try:
|
197
|
+
# Send the command followed by our marker to detect completion
|
198
|
+
self.process.stdin.write(f"{command}\n{COMMAND_MARKER}\n")
|
199
|
+
self.process.stdin.flush()
|
200
|
+
except IOError as e:
|
201
|
+
raise CDBError(f"Failed to send command: {str(e)}")
|
202
|
+
|
203
|
+
cmd_timeout = timeout or self.timeout
|
204
|
+
if not self.ready_event.wait(timeout=cmd_timeout):
|
205
|
+
raise CDBError(f"Command timed out after {cmd_timeout} seconds: {command}")
|
206
|
+
|
207
|
+
with self.lock:
|
208
|
+
result = self.output_lines.copy()
|
209
|
+
self.output_lines = []
|
210
|
+
return result
|
211
|
+
|
212
|
+
def shutdown(self):
|
213
|
+
"""Clean up and terminate the CDB process"""
|
214
|
+
try:
|
215
|
+
if self.process and self.process.poll() is None:
|
216
|
+
try:
|
217
|
+
if self.remote_connection:
|
218
|
+
# For remote connections, send CTRL+B to detach
|
219
|
+
self.process.stdin.write("\x02") # CTRL+B
|
220
|
+
self.process.stdin.flush()
|
221
|
+
else:
|
222
|
+
# For dump files, send 'q' to quit
|
223
|
+
self.process.stdin.write("q\n")
|
224
|
+
self.process.stdin.flush()
|
225
|
+
self.process.wait(timeout=1)
|
226
|
+
except Exception:
|
227
|
+
pass
|
228
|
+
|
229
|
+
if self.process.poll() is None:
|
230
|
+
self.process.terminate()
|
231
|
+
self.process.wait(timeout=3)
|
232
|
+
except Exception as e:
|
233
|
+
if self.verbose:
|
234
|
+
print(f"Error during shutdown: {e}")
|
235
|
+
finally:
|
236
|
+
self.process = None
|
237
|
+
|
238
|
+
def get_session_id(self) -> str:
|
239
|
+
"""Get a unique identifier for this CDB session."""
|
240
|
+
if self.dump_path:
|
241
|
+
return os.path.abspath(self.dump_path)
|
242
|
+
elif self.remote_connection:
|
243
|
+
return f"remote:{self.remote_connection}"
|
244
|
+
else:
|
245
|
+
raise CDBError("Session has no valid identifier")
|
246
|
+
|
247
|
+
def __enter__(self):
|
248
|
+
"""Support for context manager protocol"""
|
249
|
+
return self
|
250
|
+
|
251
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
252
|
+
"""Clean up when exiting context manager"""
|
253
|
+
self.shutdown()
|