In reverse engineering and dynamic analysis, tools like x64dbg provide an excellent foundation for inspecting, modifying, and understanding binary behavior at runtime. But what if you want automated control over memory patching, module inspection, or call stack introspection — all in a structured, programmable service?
That’s exactly what I’m building: an MCP (Memory Control & Patch) Service, powered by a custom x64dbg plugin written in C#, using the x64dbgBridge API.
The goal of the MCP service is to:
- Programmatically inspect and manipulate process memory
- Automatically patch instructions and bypass protections
- Resolve modules, stack frames, and thread states
- Provide reusable building blocks for automated reversing workflows
In short: to turn x64dbg into an automation-capable backend for dynamic analysis and patching.
Here’s a high-level look at some of the powerful functionality already implemented:
🔍 GetAllModulesFromMemMap()
This function scans all loaded memory regions using the DbgMemMap()
API and filters them to extract loaded module ranges:
1 2 |
csharpCopyEdit<code>List<(string Name, nuint Base, nuint End)> modules = GetAllModulesFromMemMap(); |
You can use this to:
- Dump modules to disk
- Locate specific symbols
- Validate memory protections
🛠️ WriteBytesToAddress(string address, byte[] data)
This powerful utility lets you patch live memory, injecting NOPs or custom shellcode into any address:
1 2 |
csharpCopyEdit<code>WriteBytesToAddress("0x14000140B", new byte[] { 0x90, 0x90 }); // Patch 2 NOPs |
It also has an overload that accepts a string like "90-90-CC"
and converts it to a byte array for convenience.
🧵 GetAllActiveThreads()
Leverages the DbgGetThreadList
API to retrieve all active threads, including their TIDs and TEB base addresses:
1 2 |
csharpCopyEdit<code>List<(uint ThreadId, nuint EntryPoint, nuint Teb)> threads = GetAllActiveThreads(); |
This is vital for thread enumeration, debugging concurrency, or even suspending specific threads for injection.
🧠 GetCallStack()
A custom stack walker that reads memory from the RBP
chain and extracts return addresses:
1 2 |
csharpCopyEdit<code>List<nuint> stackFrames = GetCallStack(); |
Perfect for:
- Stack analysis
- Call tracing
- Resolving return paths
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 |
//https://github.com/x64dbg/x64dbg/blob/development/src/bridge/bridgemain.h <-- Ref if additional commands need to be added /// <summary> /// Executes a debugger command synchronously using x64dbg's command engine. /// /// This function wraps the native `DbgCmdExecDirect` API to simplify command execution. /// It blocks until the command has finished executing. /// /// Examples: /// ExecuteDebuggerCommand("load C:\\Path\\To\\Program.exe"); // Loads an executable /// ExecuteDebuggerCommand("restart"); // Restarts the current debugging session /// ExecuteDebuggerCommand("run"); // Starts execution /// </summary> /// <param name="command">The debugger command string to execute.</param> /// <returns>True if the command executed successfully, false otherwise.</returns> public static bool ExecuteDebuggerCommand(string command) { return DbgCmdExecDirect(command); } public static byte[] ReadMemory(nuint address, uint size) { byte[] buffer = new byte[size]; if (!Bridge.DbgMemRead(address, buffer, size)) // assume NativeBridge is a P/Invoke wrapper return null; return buffer; } public static bool WriteMemory(nuint address, byte[] data) { return Bridge.DbgMemWrite(address, data, (uint)data.Length); } public static bool WriteBytesToAddress(string addressStr, byte[] data) { if (data == null || data.Length == 0) { Console.WriteLine("Data is null or empty."); return false; } if (!ulong.TryParse(addressStr.Replace("0x", ""), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong parsed)) { Console.WriteLine($"Invalid address: {addressStr}"); return false; } IntPtr ptr = new IntPtr((long)parsed); nuint address = (nuint)ptr.ToInt64(); bool success = WriteMemory(address, data); if (success) { Console.WriteLine($"Successfully wrote {data.Length} bytes at 0x{address:X}"); } else { Console.WriteLine($"Failed to write memory at 0x{address:X}"); } return success; } public static bool PatchWithNops(string addressStr, int nopCount = 7) { if (!ulong.TryParse(addressStr.Replace("0x", ""), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong parsed)) { Console.WriteLine($"Invalid address: {addressStr}"); return false; } IntPtr ptr = new IntPtr((long)parsed); nuint address = (nuint)ptr.ToInt64(); byte[] nops = Enumerable.Repeat((byte)0x90, nopCount).ToArray(); bool success = WriteMemory(address, nops); if (success) { Console.WriteLine($"Successfully patched {nopCount} NOPs at 0x{address:X}"); } else { Console.WriteLine($"Failed to write memory at 0x{address:X}"); } return success; } /// <summary> /// Parses a string of hexadecimal byte values separated by hyphens into a byte array. /// </summary> /// <param name="pattern"> /// A string containing hexadecimal byte values, e.g., "75-38" or "90-90-CC". /// Each byte must be two hex digits and separated by hyphens. /// </param> /// <returns> /// A byte array representing the parsed hex values. /// </returns> /// <example> /// byte[] bytes = ParseBytePattern("75-38"); // returns new byte[] { 0x75, 0x38 } /// </example> public static byte[] ParseBytePattern(string pattern) { return pattern.Split('-').Select(b => Convert.ToByte(b, 16)).ToArray(); } public static string GetLabel(nuint address) { return Bridge.DbgGetLabelAt(address, SEGMENTREG.SEG_DEFAULT, out var label) ? label : null; } string TryGetDereferencedString(nuint address) { var data = ReadMemory(address, 64); // read 64 bytes (arbitrary) int end = Array.IndexOf(data, (byte)0); if (end <= 0) return null; return Encoding.ASCII.GetString(data, 0, end); } public static void LabelIfCallTargetMatches(nuint address, ref Bridge.BASIC_INSTRUCTION_INFO disasm, nuint targetAddress, string value = "test", string mode = "Label") { if (disasm.addr == targetAddress) { if (string.Equals(mode, "Label", StringComparison.OrdinalIgnoreCase)) { Bridge.DbgSetLabelAt(address, value); Console.WriteLine($"Label '{value}' added at {address:X}"); } else if (string.Equals(mode, "Comment", StringComparison.OrdinalIgnoreCase)) { Bridge.DbgSetCommentAt(address, value); Console.WriteLine($"Comment '{value}' added at {address:X}"); } } } public static void LabelMatchingInstruction(nuint address, ref Bridge.BASIC_INSTRUCTION_INFO disasm, string targetInstruction = "jnz 0x0000000140001501", string value = "test", string mode = "Label") { if (string.Equals(disasm.instruction, targetInstruction, StringComparison.OrdinalIgnoreCase)) { if (string.Equals(mode, "Label", StringComparison.OrdinalIgnoreCase)) { Bridge.DbgSetLabelAt(address, value); Console.WriteLine($"Label 'test' added at {address:X}"); } else if (string.Equals(mode, "Comment", StringComparison.OrdinalIgnoreCase)) { Bridge.DbgSetCommentAt(address, value); Console.WriteLine($"Comment 'test' added at {address:X}"); } } } public static void LabelMatchingBytes(nuint address, byte[] pattern, string value = "test", string mode = "Label") { try { byte[] actualBytes = ReadMemory(address, (uint)pattern.Length); if (actualBytes.Length != pattern.Length) return; for (int i = 0; i < pattern.Length; i++) { if (actualBytes[i] != pattern[i]) return; } if (string.Equals(mode, "Label", StringComparison.OrdinalIgnoreCase)) { Bridge.DbgSetLabelAt(address, value); Console.WriteLine($"Label '{value}' added at {address:X} (byte pattern match)"); } else if (string.Equals(mode, "Comment", StringComparison.OrdinalIgnoreCase)) { Bridge.DbgSetCommentAt(address, value); Console.WriteLine($"Comment '{value}' added at {address:X} (byte pattern match)"); } } catch { // Fail quietly on bad memory read } } public static List<(string Name, nuint Base, nuint End)> GetAllModulesFromMemMap() { var result = new List<(string Name, nuint Base, nuint End)>(); MEMMAP memMap = new MEMMAP { page = new MEMMAPENTRY[128] // ensure array is allocated }; if (!Bridge.DbgMemMap(ref memMap)) { Console.WriteLine("Failed to retrieve memory map."); return result; } Console.WriteLine("Memory map count: " + memMap.count); int max = Math.Min(memMap.page.Length, (int)memMap.count); for (int i = 0; i < max; i++) { var entry = memMap.page[i]; if (!string.IsNullOrEmpty(entry.info) && entry.info.Contains("Image")) { nuint start = entry.addr; nuint end = start + entry.size; result.Add((entry.name, start, end)); } } return result; } public static List<nuint> GetCallStack(int maxFrames = 32) { List<nuint> callstack = new List<nuint>(); nuint rbp = Bridge.DbgValFromString("rbp"); nuint rsp = Bridge.DbgValFromString("rsp"); for (int i = 0; i < maxFrames; i++) { // Read return address (next value after saved RBP) byte[] addrBuffer = new byte[8]; // 64-bit address if (!Bridge.DbgMemRead(rbp + 8, addrBuffer, 8)) break; nuint returnAddress = (nuint)BitConverter.ToUInt64(addrBuffer, 0); if (returnAddress == 0) break; callstack.Add(returnAddress); // Read the previous RBP if (!Bridge.DbgMemRead(rbp, addrBuffer, 8)) break; rbp = (nuint)BitConverter.ToUInt64(addrBuffer, 0); if (rbp == 0 || rbp < rsp) break; // Invalid frame or stack unwound } return callstack; } public static List<(uint ThreadId, nuint EntryPoint, nuint TEB)> GetAllActiveThreads() { var result = new List<(uint, nuint, nuint)>(); THREADLIST threadList = new THREADLIST { Entries = new THREADENTRY[256] }; DbgGetThreadList(ref threadList); for (int i = 0; i < threadList.Count; i++) { var t = threadList.Entries[i]; result.Add((t.ThreadId, t.ThreadEntry, t.TebBase)); } return result; } public static string[] GetAllRegistersAsStrings() { string[] regNames = new[] { "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "rip" }; List<string> result = new List<string>(); foreach (string reg in regNames) { try { nuint val = Bridge.DbgValFromString(reg); result.Add($"{reg.ToUpper(),-4}: {val.ToPtrString()}"); } catch { result.Add($"{reg.ToUpper(),-4}: <unavailable>"); } } return result.ToArray(); } [Command("DumpModuleToFile", DebugOnly = true)] public static void DumpModuleToFile(string[] args) { const string filePath = @"C:\dump.txt"; // Hardcoded file path as requested Console.WriteLine($"Attempting to dump module info to: {filePath}"); try { // 1. Get current instruction pointer and module info var cip = Bridge.DbgValFromString("cip"); // Gets EIP or RIP depending on architecture var modInfo = new Module.ModuleInfo(); if (!Module.InfoFromAddr(cip, ref modInfo)) { Console.Error.WriteLine($"Error: Could not find module information for address {cip.ToPtrString()}. Is the debugger attached and running?"); return; } var LoadedModules = GetAllModulesFromMemMap(); Console.WriteLine("Modules loaded Count: " + LoadedModules.Count); foreach (var (name, start, end) in LoadedModules) { Console.WriteLine($"{name,-20} 0x{start:X} - 0x{end:X}"); } IntPtr ptr = new IntPtr(0x14000140B); nuint address = (nuint)ptr.ToInt64(); byte[] nops = Enumerable.Repeat((byte)0x90, 7).ToArray(); bool success = WriteMemory(address, nops); if (success) { Console.WriteLine($"Successfully patched {nops.Length} NOPs at 0x{address:X}"); } else { Console.WriteLine($"Failed to write memory at 0x{address:X}"); } Console.WriteLine($"Found module '{modInfo.name}' at base {modInfo.@base.ToPtrString()}, size {modInfo.size:X}"); // Use StreamWriter to write to the file using (var writer = new StreamWriter(filePath, false, Encoding.UTF8)) // Overwrite if exists { // 2. Dump Registers writer.WriteLine("--- Current Register State ---"); writer.WriteLine($"Module: {modInfo.name}"); writer.WriteLine($"Timestamp: {DateTime.Now}"); writer.WriteLine("-----------------------------"); // Add common registers (adjust for x86/x64 as needed, DbgValFromString handles it) writer.WriteLine($"RAX: {Bridge.DbgValFromString("rax").ToPtrString()}"); writer.WriteLine($"RBX: {Bridge.DbgValFromString("rbx").ToPtrString()}"); writer.WriteLine($"RCX: {Bridge.DbgValFromString("rcx").ToPtrString()}"); writer.WriteLine($"RDX: {Bridge.DbgValFromString("rdx").ToPtrString()}"); writer.WriteLine($"RSI: {Bridge.DbgValFromString("rsi").ToPtrString()}"); writer.WriteLine($"RDI: {Bridge.DbgValFromString("rdi").ToPtrString()}"); writer.WriteLine($"RBP: {Bridge.DbgValFromString("rbp").ToPtrString()}"); writer.WriteLine($"RSP: {Bridge.DbgValFromString("rsp").ToPtrString()}"); writer.WriteLine($"RIP: {cip.ToPtrString()}"); // Use the 'cip' we already fetched writer.WriteLine($"R8: {Bridge.DbgValFromString("r8").ToPtrString()}"); writer.WriteLine($"R9: {Bridge.DbgValFromString("r9").ToPtrString()}"); writer.WriteLine($"R10: {Bridge.DbgValFromString("r10").ToPtrString()}"); writer.WriteLine($"R11: {Bridge.DbgValFromString("r11").ToPtrString()}"); writer.WriteLine($"R12: {Bridge.DbgValFromString("r12").ToPtrString()}"); writer.WriteLine($"R13: {Bridge.DbgValFromString("r13").ToPtrString()}"); writer.WriteLine($"R14: {Bridge.DbgValFromString("r14").ToPtrString()}"); writer.WriteLine($"R15: {Bridge.DbgValFromString("r15").ToPtrString()}"); writer.WriteLine($"EFlags: {Bridge.DbgValFromString("eflags").ToPtrString()}"); // Or rflags writer.WriteLine("-----------------------------"); writer.WriteLine(); // Add a blank line // 3. Dump Disassembly and Labels writer.WriteLine($"--- Disassembly for {modInfo.name} ({modInfo.@base.ToPtrString()} - {(modInfo.@base + modInfo.size).ToPtrString()}) ---"); writer.WriteLine("-----------------------------"); nuint currentAddr = modInfo.@base; var endAddr = modInfo.@base + modInfo.size; const int MAX_INSTRUCTIONS = 10000; // Limit number of instructions to prevent too large dumps int instructionCount = 0; // Write disassembly with labels while (currentAddr < endAddr && instructionCount < MAX_INSTRUCTIONS) { // Get label at current address if exists string label = GetLabel(currentAddr); if (!string.IsNullOrEmpty(label)) { writer.WriteLine(); writer.WriteLine($"{label}:"); } // Disassemble instruction at current address Bridge.BASIC_INSTRUCTION_INFO disasm = new Bridge.BASIC_INSTRUCTION_INFO(); Bridge.DbgDisasmFastAt(currentAddr, ref disasm); if (disasm.size == 0) { // Failed to disassemble, move to next byte currentAddr++; continue; } //LabelMatchingInstruction(currentAddr, ref disasm); //LabelMatchingBytes(currentAddr, new byte[] { 0x48, 0x85, 0xc0}, "Found Bytes"); // Attempt to dereference value or address for a potential string string inlineString = null; nuint possiblePtr = 0; if (disasm.type == 1) // value (immediate) { possiblePtr = disasm.value.value; } else if (disasm.type == 2) // address { possiblePtr = disasm.addr; } if (possiblePtr != 0) { try { var strData = ReadMemory(possiblePtr, 64); int len = Array.IndexOf(strData, (byte)0); if (len > 0) { inlineString = Encoding.ASCII.GetString(strData, 0, len); // Optional: filter printable ASCII if (inlineString.All(c => c >= 0x20 && c < 0x7F)) { writer.WriteLine($" ; \"{inlineString}\""); } else { inlineString = null; } } } catch { // Ignore invalid memory } } // Format and write instruction string bytes = BitConverter.ToString(ReadMemory(currentAddr, (uint)disasm.size)); //.Replace("-", " ") writer.WriteLine($"{currentAddr.ToPtrString()} {bytes,-20} {disasm.instruction}"); // Move to next instruction currentAddr += (nuint)disasm.size; instructionCount++; // If we've hit a lot of instructions for one section, add a progress note if (instructionCount % 1000 == 0) { //Console.WriteLine($"Dumped {instructionCount} instructions..."); } } if (instructionCount >= MAX_INSTRUCTIONS) { writer.WriteLine(); writer.WriteLine($"--- Instruction limit ({MAX_INSTRUCTIONS}) reached. Dump truncated. ---"); } writer.WriteLine("-----------------------------"); writer.WriteLine("--- Dump Complete ---"); } // StreamWriter is automatically flushed and closed here Console.WriteLine($"Successfully dumped module '{modInfo.name}' and registers to {filePath}"); } catch (UnauthorizedAccessException ex) { Console.Error.WriteLine($"Error: Access denied writing to '{filePath}'. Try running x64dbg as administrator or choose a different path. Details: {ex.Message}"); } catch (IOException ex) { Console.Error.WriteLine($"Error: An I/O error occurred while writing to '{filePath}'. Details: {ex.Message}"); } catch (Exception ex) // Catch-all for other unexpected errors { Console.Error.WriteLine($"An unexpected error occurred: {ex.GetType().Name} - {ex.Message}"); Console.Error.WriteLine(ex.StackTrace); // Log stack trace for debugging } } |
These are net new commands to pass to x96. They ultimately may be exposed by another class such as “Module” but I added direct calls to this class for testing purposes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
[DllImport(dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] private static extern bool DbgMemWrite(nuint va, IntPtr src, nuint size); public static unsafe bool DbgMemWrite<T>(nuint va, T[] buffer, nuint size) where T : unmanaged { if (buffer is null || size > (nuint)buffer.Length * (nuint)sizeof(T)) return false; fixed (T* ptr = buffer) { return DbgMemWrite(va, (IntPtr)ptr, size); } } public static unsafe bool DbgMemWrite<T>(nuint va, ref T src, nuint size) where T : struct { if (size > (nuint)Marshal.SizeOf<T>()) return false; var handle = GCHandle.Alloc(src, GCHandleType.Pinned); try { return DbgMemWrite(va, handle.AddrOfPinnedObject(), size); } finally { handle.Free(); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct MEMMAPENTRY { public nuint addr; // Start address of the memory region public nuint size; // Size of the region public uint protection; // Memory protection flags [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string info; // Type info (e.g., "Image", "Heap", etc.) [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string name; // Module or section name } [StructLayout(LayoutKind.Sequential)] public struct MEMMAP { public uint count; // Number of entries [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] public MEMMAPENTRY[] page; // The memory pages } [DllImport(dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern bool DbgMemMap(ref MEMMAP memmap); [StructLayout(LayoutKind.Sequential)] public struct THREADENTRY { public uint ThreadId; public nuint ThreadEntry; // Entry point address public nuint StartAddress; public nuint TebBase; } [StructLayout(LayoutKind.Sequential)] public struct THREADLIST { public int Count; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public THREADENTRY[] Entries; } [DllImport(dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void DbgGetThreadList(ref THREADLIST list); |