Add live debugger frontend and mutex stall recovery (#383)

This commit is contained in:
Spooks
2026-07-17 22:41:07 -06:00
committed by GitHub
parent 1c8cdd6537
commit 13269797bf
57 changed files with 6534 additions and 22 deletions
+2
View File
@@ -32,6 +32,8 @@ packages/
.nuget/
.dotnet-home/
.cache/
__pycache__/
*.py[cod]
.DS_Store
Thumbs.db
+2
View File
@@ -7,6 +7,8 @@ SPDX-License-Identifier: GPL-2.0-or-later
<Folder Name="/src/">
<Project Path="src/SharpEmu.CLI/SharpEmu.CLI.csproj" />
<Project Path="src/SharpEmu.Core/SharpEmu.Core.csproj" />
<Project Path="src/SharpEmu.DebugClient/SharpEmu.DebugClient.csproj" />
<Project Path="src/SharpEmu.Debugger/SharpEmu.Debugger.csproj" />
<Project Path="src/SharpEmu.GUI/SharpEmu.GUI.csproj" />
<Project Path="src/SharpEmu.HLE/SharpEmu.HLE.csproj" />
<Project Path="src/SharpEmu.Libs/SharpEmu.Libs.csproj" />
+177
View File
@@ -0,0 +1,177 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# Live debug server
SharpEmu can expose a **live debug server** so an external process can inspect
and control a running guest over TCP. The server lives in the emulator; the
companion `SharpEmu.DebugClient` executable is one client, and the wire protocol
is simple enough to script against directly.
This document describes the moving parts and the wire protocol. For day-to-day
client usage, see
[`src/SharpEmu.DebugClient/DEVELOPER_READ.md`](../src/SharpEmu.DebugClient/DEVELOPER_READ.md).
## Layering
| Assembly | Role |
| -------- | ---- |
| `SharpEmu.Core` | Defines the dispatcher seam `ICpuDebugHook` / `ICpuDebugFrame` (namespace `SharpEmu.Core.Cpu.Debug`) and the `CpuExecutionOptions.DebugHook` slot. Core has **no** reference to the debugger. |
| `SharpEmu.Debugger` | The debugger: `DebuggerSession` (implements the hook), `BreakpointStore`, the TCP `DebuggerServer`, the pluggable `IDebugProtocol` with a JSON-lines implementation, and the `DebuggerServerHost` one-call wiring. |
| `SharpEmu.CLI` | Parses `--debug-server`, builds a `DebuggerServerHost`, hands its `Hook` to `SharpEmuRuntimeOptions.DebugHook`, and manages its lifetime. |
| `SharpEmu.DebugClient` | A standalone client executable. Depends only on the BCL. |
The dependency direction is important: Core stays debugger-agnostic and only
publishes the seam. Anything that observes execution implements
`ICpuDebugHook` and is injected through the options, so the debugger can evolve
without touching the CPU core.
## Execution model
`CpuDispatcher` enters a fresh frame for the process entry point and for each
module initializer. When a `DebugHook` is attached it is notified at those
boundaries:
- `OnFrameEnter(frame)` — before the native backend runs the frame. The
`DebuggerSession` decides whether to stop (pause request, breakpoint on the
entry address, single-step, or stop-at-entry). To stop, it **parks the
emulation thread** inside this call on a gate; the frame stays live, so a
client can read and write registers and memory while parked. `continue` /
`step` release the gate.
- `OnFrameExit(frame, result)` — after the frame completes.
Because pausing parks the one thread that owns the guest context, register and
memory accessors are only served while the session reports `Paused`; otherwise
they return "not paused" so a client never observes torn state.
### What is and isn't live yet
- **Live:** attach/handshake, run-state tracking, register read/write, memory
read/write, breakpoint management, execution breakpoints at frame entry,
pause, frame-level step, continue, and stop/resume/terminate events.
- **Surface only (armed as the backend grows hooks):** per-instruction
stepping and data watchpoints (`readwatch` / `writewatch` / `accesswatch`).
The verbs and types exist so clients and tooling can be written now.
## Enabling the server
```bash
SharpEmu --debug-server "/path/to/eboot.bin" # 127.0.0.1:5714
SharpEmu --debug-server=0.0.0.0:5714 "/path/to/eboot.bin"
```
The bind address defaults to loopback; a routable address must be given
explicitly. With stop-at-entry (the default `DebuggerSessionOptions.StopAtEntry`),
the guest parks at its first frame until a client connects and issues
`continue`, giving you a window to set breakpoints before any guest code runs.
## Browser frontend
The dependency-free Python frontend can choose and launch an `eboot.bin`, attach
to its debugger automatically, and provides execution controls, registers,
memory inspection, breakpoint management, process output, and a live protocol
activity stream:
```bash
./tools/SharpEmu.DebuggerFrontend/run.sh
```
It connects to `127.0.0.1:5714` and opens `http://127.0.0.1:8765/` by default.
See [`tools/SharpEmu.DebuggerFrontend/README.md`](../tools/SharpEmu.DebuggerFrontend/README.md)
for configuration and testing options.
## Wire protocol (json-lines/1)
One JSON object per line, UTF-8, `\n`-terminated, in both directions.
### Requests
A `command` string plus command-specific fields. Numeric fields accept a JSON
number or a `0x`-prefixed hex string.
| `command` | Fields | Reply `data` |
| --------- | ------ | ------------ |
| `ping` | — | — |
| `status` (`info`) | — | `state`, `breakpoints`, `lastStop?` |
| `state` | — | `state` |
| `registers` (`regs`) | — | `registers` (rax..r15, rip, rflags, fs_base, gs_base) |
| `set-register` | `register`, `value` | — |
| `read-memory` | `address`, `length` (≤ 65536) | `address`, `length`, `bytes` (hex) |
| `write-memory` | `address`, `bytes` (hex) | `written` |
| `list-breakpoints` (`breakpoints`) | — | `breakpoints[]` |
| `add-breakpoint` (`break`) | `address`, `kind?`, `length?` | `breakpoint` |
| `remove-breakpoint` (`delete-breakpoint`) | `id` | — |
| `enable-breakpoint` | `id`, `enabled?` (default true) | — |
| `continue` (`cont`, `c`) | — | — |
| `step` (`s`) | — | — |
| `pause` | — | — |
### Replies
```json
{"ok":true,"command":"registers","data":{ "registers": { "rax":"0x…", } }}
{"ok":false,"command":"read-memory","error":"Target is not paused."}
```
### Events (unsolicited)
```json
{"event":"hello","protocol":"json-lines/1","state":"Paused"}
{"event":"stopped","reason":"Breakpoint","address":"0x…","frameKind":"ProcessEntry","frameLabel":"eboot.bin","registers":{},"breakpoint":{}}
{"event":"resumed"}
{"event":"terminated"}
```
`reason` is one of `EntryPoint`, `Breakpoint`, `Watchpoint`, `Step`, `Pause`,
`Fault`, or `Stall`.
Stall stops include structured evidence in addition to the human-readable
detail. Import-loop evidence identifies the NID, resolved HLE export, repeating
guest return site, dispatch count, and first two ABI arguments:
```json
{
"event": "stopped",
"reason": "Stall",
"stall": {
"kind": "ImportLoop",
"nid": "9UK1vLZQft4",
"instructionPointer": "0x0000000801CE2418",
"dispatchIndex": 40667904,
"argument0": "0x0000000812345000",
"argument1": "0x0000000000000000",
"resolved": true,
"library": "libKernel",
"function": "scePthreadMutexLock"
}
}
```
The Python frontend uses this evidence to explain the likely failure class and
rank concrete checks/fixes. Its diagnosis is intentionally labelled heuristic:
it helps locate the responsible HLE/scheduler path but does not replace tracing.
## Swapping the protocol
`DebuggerServer` takes an `IDebugProtocol` factory. The default is
`JsonLineDebugProtocol`; a GDB remote serial stub (or any other framing) can be
dropped in without changing the session or command semantics, which live in
`DebugCommandDispatcher`.
## Embedding the server
```csharp
using SharpEmu.Debugger;
using SharpEmu.Core.Runtime;
await using var host = new DebuggerServerHost();
host.Start();
var options = new SharpEmuRuntimeOptions { DebugHook = host.Hook };
using var runtime = SharpEmuRuntime.CreateDefault(options);
var result = runtime.Run(ebootPath);
host.NotifyRunCompleted();
```
+79 -1
View File
@@ -262,6 +262,32 @@ internal static partial class Program
return 2;
}
if (!TryGetDebugServerOptions(args, out var debugServerEnabled, out var debugServerOptions, out var debugServerError))
{
Log.Error($"Invalid --debug-server endpoint: {debugServerError}");
return 1;
}
SharpEmu.Debugger.DebuggerServerHost? debugHost = null;
if (debugServerEnabled)
{
debugHost = new SharpEmu.Debugger.DebuggerServerHost(debugServerOptions);
try
{
debugHost.Start();
Log.Info($"Live debug server listening on {debugHost.Endpoint}. Attach with SharpEmu.DebugClient.");
// With StopAtEntry, the guest parks at its first frame until a
// client connects and continues.
runtimeOptions = runtimeOptions with { DebugHook = debugHost.Hook };
}
catch (Exception ex)
{
Log.Error("Failed to start the debug server.", ex);
debugHost.DisposeAsync().AsTask().GetAwaiter().GetResult();
return 6;
}
}
Console.Error.WriteLine("[DEBUG] Creating runtime...");
try
@@ -335,6 +361,12 @@ internal static partial class Program
}
finally
{
if (debugHost is not null)
{
debugHost.NotifyRunCompleted();
debugHost.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
HostSessionControl.SetEmbeddedHostSurface(0);
if (hostSurface is not null)
{
@@ -998,8 +1030,45 @@ internal static partial class Program
private static void PrintUsage()
{
Log.Info("Usage: SharpEmu.CLI [--strict] [--trace-imports[=N]] [--cpu-engine=<native>] [--log-level=<level>] [--log-file[=<path>]] <path-to-eboot.bin>");
Log.Info("Usage: SharpEmu.CLI [--strict] [--trace-imports[=N]] [--cpu-engine=<native>] [--log-level=<level>] [--log-file[=<path>]] [--debug-server[=host:port]] <path-to-eboot.bin>");
Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin""");
Log.Info("Debug server: --debug-server starts a live debug listener (default 127.0.0.1:5714); connect with SharpEmu.DebugClient.");
}
/// <summary>
/// Detects the <c>--debug-server</c> flag and parses its optional
/// <c>host:port</c> endpoint. Returns false only when the flag is present but
/// its endpoint is malformed, so the caller can abort with a clear error.
/// </summary>
private static bool TryGetDebugServerOptions(
string[] args,
out bool enabled,
out SharpEmu.Debugger.Server.DebuggerServerOptions options,
out string error)
{
enabled = false;
options = new SharpEmu.Debugger.Server.DebuggerServerOptions();
error = string.Empty;
foreach (var argument in args)
{
if (string.Equals(argument, "--debug-server", StringComparison.OrdinalIgnoreCase))
{
enabled = true;
continue;
}
const string prefix = "--debug-server=";
if (argument.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
enabled = true;
if (!SharpEmu.Debugger.Server.DebuggerServerOptions.TryParseEndpoint(argument[prefix.Length..], out options, out error))
{
return false;
}
}
}
return true;
}
private static bool TryParseArguments(
@@ -1033,6 +1102,15 @@ internal static partial class Program
continue;
}
// The debug-server endpoint is parsed separately (see
// TryGetDebugServerOptions); accept the flag here so it is not
// rejected as an unknown option or mistaken for the eboot path.
if (string.Equals(argument, "--debug-server", StringComparison.OrdinalIgnoreCase) ||
argument.StartsWith("--debug-server=", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (string.Equals(argument, "--trace-imports", StringComparison.OrdinalIgnoreCase))
{
importTraceLimit = DefaultImportTraceLimit;
+1
View File
@@ -7,6 +7,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ItemGroup>
<ProjectReference Include="..\SharpEmu.Core\SharpEmu.Core.csproj" />
<ProjectReference Include="..\SharpEmu.Debugger\SharpEmu.Debugger.csproj" />
<ProjectReference Include="..\SharpEmu.GUI\SharpEmu.GUI.csproj" />
<ProjectReference Include="..\SharpEmu.Logging\SharpEmu.Logging.csproj" />
</ItemGroup>
+20 -12
View File
@@ -216,9 +216,17 @@
"type": "Project",
"dependencies": {
"Iced": "[1.21.0, )",
"SharpEmu.HLE": "[0.0.2-beta.2, )",
"SharpEmu.Libs": "[0.0.2-beta.2, )",
"SharpEmu.Logging": "[0.0.2-beta.2, )"
"SharpEmu.HLE": "[0.0.2-beta.3, )",
"SharpEmu.Libs": "[0.0.2-beta.3, )",
"SharpEmu.Logging": "[0.0.2-beta.3, )"
}
},
"sharpemu.debugger": {
"type": "Project",
"dependencies": {
"SharpEmu.Core": "[0.0.2-beta.3, )",
"SharpEmu.HLE": "[0.0.2-beta.3, )",
"SharpEmu.Logging": "[0.0.2-beta.3, )"
}
},
"sharpemu.gui": {
@@ -228,24 +236,24 @@
"Avalonia.Desktop": "[11.3.18, )",
"Avalonia.Fonts.Inter": "[11.3.18, )",
"Avalonia.Themes.Fluent": "[11.3.18, )",
"SharpEmu.Core": "[0.0.2-beta.2, )",
"SharpEmu.Libs": "[0.0.2-beta.2, )",
"SharpEmu.Logging": "[0.0.2-beta.2, )",
"SharpEmu.Core": "[0.0.2-beta.3, )",
"SharpEmu.Libs": "[0.0.2-beta.3, )",
"SharpEmu.Logging": "[0.0.2-beta.3, )",
"Tmds.DBus.Protocol": "[0.21.3, )"
}
},
"sharpemu.hle": {
"type": "Project",
"dependencies": {
"SharpEmu.Logging": "[0.0.2-beta.2, )"
"SharpEmu.Logging": "[0.0.2-beta.3, )"
}
},
"sharpemu.libs": {
"type": "Project",
"dependencies": {
"SharpEmu.HLE": "[0.0.2-beta.2, )",
"SharpEmu.ShaderCompiler": "[0.0.2-beta.2, )",
"SharpEmu.ShaderCompiler.Vulkan": "[0.0.2-beta.2, )",
"SharpEmu.HLE": "[0.0.2-beta.3, )",
"SharpEmu.ShaderCompiler": "[0.0.2-beta.3, )",
"SharpEmu.ShaderCompiler.Vulkan": "[0.0.2-beta.3, )",
"Silk.NET.Input": "[2.23.0, )",
"Silk.NET.Vulkan": "[2.23.0, )",
"Silk.NET.Vulkan.Extensions.EXT": "[2.23.0, )",
@@ -259,13 +267,13 @@
"sharpemu.shadercompiler": {
"type": "Project",
"dependencies": {
"SharpEmu.HLE": "[0.0.2-beta.2, )"
"SharpEmu.HLE": "[0.0.2-beta.3, )"
}
},
"sharpemu.shadercompiler.vulkan": {
"type": "Project",
"dependencies": {
"SharpEmu.ShaderCompiler": "[0.0.2-beta.2, )"
"SharpEmu.ShaderCompiler": "[0.0.2-beta.3, )"
}
},
"Avalonia": {
+20
View File
@@ -3,6 +3,7 @@
using System.Buffers.Binary;
using System.Text;
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Core.Cpu.Native;
using SharpEmu.Core.Loader;
using SharpEmu.Core.Memory;
@@ -272,7 +273,23 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
entryFrameDiagnostic,
Environment.NewLine,
"CpuEngine: native-only");
// Frame boundaries an attached debugger observes; null hook = a branch.
var debugHook = executionOptions.DebugHook;
var debugFrame = debugHook is null
? null
: new CpuContextDebugFrame(
frameKind == EntryFrameKind.ProcessEntry
? CpuDebugFrameKind.ProcessEntry
: CpuDebugFrameKind.ModuleInitializer,
entryPoint,
processImageName,
context,
effectiveImportStubs);
debugHook?.OnFrameEnter(debugFrame!);
_nativeCpuBackend ??= new DirectExecutionBackend(_moduleManager);
// Let backend stall reports reference the same frame as entry.
(_nativeCpuBackend as DirectExecutionBackend)?.SetActiveDebugFrame(debugFrame);
if (_nativeCpuBackend.TryExecute(
context,
entryPoint,
@@ -282,6 +299,7 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
executionOptions,
out var nativeResult))
{
debugHook?.OnFrameExit(debugFrame!, nativeResult);
LastSessionSummary = new CpuSessionSummary(
nativeResult,
nativeResult == OrbisGen2Result.ORBIS_GEN2_OK
@@ -296,6 +314,8 @@ public sealed class CpuDispatcher : ICpuDispatcher, IDisposable
return nativeResult;
}
debugHook?.OnFrameExit(debugFrame!, OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_IMPLEMENTED);
var backendName = string.IsNullOrWhiteSpace(_nativeCpuBackend.BackendName)
? "native-backend"
: _nativeCpuBackend.BackendName;
+12 -1
View File
@@ -1,15 +1,26 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Cpu.Debugging;
namespace SharpEmu.Core.Cpu;
public readonly struct CpuExecutionOptions
{
public bool EnableDisasmDiagnostics { get; init; }
public CpuExecutionEngine CpuEngine { get; init; }
public bool StrictDynlibResolution { get; init; }
public int ImportTraceLimit { get; init; }
/// <summary>
/// An optional debugger attached to this execution session. When set, the
/// dispatcher notifies it at each frame boundary via
/// <see cref="ICpuDebugHook.OnFrameEnter"/> / <see cref="ICpuDebugHook.OnFrameExit"/>.
/// Null when no debugger is attached, which is the default and imposes no
/// runtime cost.
/// </summary>
public ICpuDebugHook? DebugHook { get; init; }
}
@@ -0,0 +1,66 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
namespace SharpEmu.Core.Cpu.Debugging;
/// <summary>
/// Adapts a live <see cref="CpuContext"/> to <see cref="ICpuDebugFrame"/>. The
/// dispatcher creates one of these around the guest context it is about to run
/// and passes it to the attached <see cref="ICpuDebugHook"/>; every accessor
/// forwards directly to the underlying context.
/// </summary>
internal sealed class CpuContextDebugFrame : ICpuDebugFrame
{
private readonly CpuContext _context;
internal CpuContextDebugFrame(
CpuDebugFrameKind kind,
ulong entryPoint,
string label,
CpuContext context,
IReadOnlyDictionary<ulong, string> importStubs)
{
Kind = kind;
EntryPoint = entryPoint;
Label = label ?? string.Empty;
_context = context ?? throw new ArgumentNullException(nameof(context));
ImportStubs = importStubs ?? new Dictionary<ulong, string>();
}
public CpuDebugFrameKind Kind { get; }
public Generation Generation => _context.TargetGeneration;
public ulong EntryPoint { get; }
public string Label { get; }
public ICpuMemory Memory => _context.Memory;
public ulong GetRegister(CpuRegister register) => _context[register];
public void SetRegister(CpuRegister register, ulong value) => _context[register] = value;
public ulong Rip
{
get => _context.Rip;
set => _context.Rip = value;
}
public ulong Rflags
{
get => _context.Rflags;
set => _context.Rflags = value;
}
public ulong FsBase => _context.FsBase;
public ulong GsBase => _context.GsBase;
public void GetXmm(int registerIndex, out ulong low, out ulong high)
=> _context.GetXmmRegister(registerIndex, out low, out high);
public IReadOnlyDictionary<ulong, string> ImportStubs { get; }
}
@@ -0,0 +1,18 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Core.Cpu.Debugging;
/// <summary>
/// Identifies the kind of guest entry frame a debugger is observing. The
/// dispatcher enters a fresh frame for the process entry point and for every
/// module initializer, so the debug layer can label stops accordingly.
/// </summary>
public enum CpuDebugFrameKind
{
/// <summary>The guest process entry point (<c>eboot.bin</c> start).</summary>
ProcessEntry,
/// <summary>A module DT_INIT / initializer routine.</summary>
ModuleInitializer,
}
@@ -0,0 +1,70 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Core.Cpu.Debugging;
/// <summary>The kind of execution stall the backend detected.</summary>
public enum CpuStallKind
{
/// <summary>
/// The guest is repeatedly re-dispatching the same import with no forward
/// progress — most commonly a spin on a mutex lock/unlock pair.
/// </summary>
ImportLoop,
}
/// <summary>
/// Details of a detected stall handed to <see cref="ICpuDebugHook.OnStall"/>.
/// Reported from the emulation thread at the point the backend recognises the
/// livelock, before it forces the guest out of the loop.
/// </summary>
public readonly struct CpuStallInfo
{
public CpuStallInfo(
CpuStallKind kind,
string? nid,
ulong instructionPointer,
long dispatchIndex,
ulong argument0,
ulong argument1,
string detail,
string? libraryName = null,
string? functionName = null)
{
Kind = kind;
Nid = nid;
InstructionPointer = instructionPointer;
DispatchIndex = dispatchIndex;
Argument0 = argument0;
Argument1 = argument1;
Detail = detail ?? string.Empty;
LibraryName = libraryName;
FunctionName = functionName;
}
public CpuStallKind Kind { get; }
/// <summary>The NID of the import being spun on, when known.</summary>
public string? Nid { get; }
/// <summary>The guest return address of the looping import dispatch.</summary>
public ulong InstructionPointer { get; }
/// <summary>The import dispatch counter at detection time.</summary>
public long DispatchIndex { get; }
/// <summary>The first two guest ABI arguments at stall detection.</summary>
public ulong Argument0 { get; }
public ulong Argument1 { get; }
/// <summary>The resolved HLE export, when the NID is registered.</summary>
public string? LibraryName { get; }
public string? FunctionName { get; }
public bool IsResolved => !string.IsNullOrWhiteSpace(FunctionName);
/// <summary>A human-readable one-line summary of the stall.</summary>
public string Detail { get; }
}
@@ -0,0 +1,66 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
namespace SharpEmu.Core.Cpu.Debugging;
/// <summary>
/// A live view of the guest CPU state at a dispatch boundary, handed to an
/// <see cref="ICpuDebugHook"/> so a debugger can read and mutate registers and
/// guest memory without taking a dependency on the concrete
/// <c>CpuContext</c>/<c>CpuDispatcher</c> types.
/// </summary>
/// <remarks>
/// The frame instance is only valid for the duration of the hook call that
/// receives it (between <see cref="ICpuDebugHook.OnFrameEnter"/> and the
/// matching <see cref="ICpuDebugHook.OnFrameExit"/>). Reads and writes are
/// forwarded straight to the underlying guest context, so mutations made from
/// a hook are observed by the CPU backend when it resumes the frame.
/// </remarks>
public interface ICpuDebugFrame
{
/// <summary>The kind of frame being executed.</summary>
CpuDebugFrameKind Kind { get; }
/// <summary>The guest ABI generation this frame targets.</summary>
Generation Generation { get; }
/// <summary>The guest virtual address the frame begins executing at.</summary>
ulong EntryPoint { get; }
/// <summary>
/// A human-readable label for the frame (process image name or module name).
/// </summary>
string Label { get; }
/// <summary>Guest-addressable memory for this frame.</summary>
ICpuMemory Memory { get; }
/// <summary>Reads a general-purpose register.</summary>
ulong GetRegister(CpuRegister register);
/// <summary>Overwrites a general-purpose register.</summary>
void SetRegister(CpuRegister register, ulong value);
/// <summary>The instruction pointer.</summary>
ulong Rip { get; set; }
/// <summary>The flags register.</summary>
ulong Rflags { get; set; }
/// <summary>The FS segment base (guest TLS pointer).</summary>
ulong FsBase { get; }
/// <summary>The GS segment base.</summary>
ulong GsBase { get; }
/// <summary>Reads the 128-bit value of an XMM register.</summary>
void GetXmm(int registerIndex, out ulong low, out ulong high);
/// <summary>
/// The import stubs (guest address to NID) resolved for this frame, so a
/// debugger can annotate calls into HLE exports.
/// </summary>
IReadOnlyDictionary<ulong, string> ImportStubs { get; }
}
@@ -0,0 +1,49 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
namespace SharpEmu.Core.Cpu.Debugging;
/// <summary>
/// The seam the CPU dispatcher uses to notify an attached debugger when guest
/// execution crosses a frame boundary. Implemented outside of Core (for
/// example by <c>SharpEmu.Debugger</c>) and supplied through
/// <see cref="CpuExecutionOptions.DebugHook"/>.
/// </summary>
/// <remarks>
/// This is intentionally coarse-grained: it exposes the entry and exit of each
/// dispatched frame rather than per-instruction stepping. Per-instruction
/// control requires cooperation from the native execution backend and is layered
/// on top of this seam as the backend gains support; keeping the dispatcher-level
/// contract stable lets the debugger infrastructure exist independently of that
/// work. Implementations must be thread-safe: frames may be dispatched from the
/// dedicated emulation thread while a debug server services clients on its own
/// threads.
/// </remarks>
public interface ICpuDebugHook
{
/// <summary>
/// Invoked immediately before the native backend begins executing a frame.
/// The debugger may inspect or mutate <paramref name="frame"/> and may block
/// the calling thread (for example, to honour a pause request) before
/// returning to allow execution to proceed.
/// </summary>
void OnFrameEnter(ICpuDebugFrame frame);
/// <summary>
/// Invoked after a frame completes, whether it returned to the host or
/// terminated with an error. <paramref name="frame"/> reflects the final
/// guest state.
/// </summary>
void OnFrameExit(ICpuDebugFrame frame, OrbisGen2Result result);
/// <summary>
/// Invoked from the emulation thread when the backend detects an execution
/// stall (for example a mutex spin loop) in the running frame, before it
/// forces the guest out of the loop. As with <see cref="OnFrameEnter"/>, the
/// implementation may inspect <paramref name="frame"/> and block to honour a
/// break before returning to let the backend proceed.
/// </summary>
void OnStall(ICpuDebugFrame frame, CpuStallInfo info);
}
@@ -10,6 +10,7 @@ using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Core.Cpu;
using SharpEmu.HLE;
using SharpEmu.Libs.Kernel;
@@ -316,11 +317,15 @@ public sealed partial class DirectExecutionBackend
}
if (!isGuestWorker &&
!ActiveForcedGuestExit &&
ShouldForceGuestExitOnImportLoop(in importStubEntry, num7, num, value, value2) &&
TryForceGuestExitToHostStub(argPackPtr, num, num7, importStubEntry.Nid))
ShouldForceGuestExitOnImportLoop(in importStubEntry, num7, num, value, value2))
{
cpuContext[CpuRegister.Rax] = 1uL;
return 1uL;
// Break before the forced exit so the loop state is still live.
NotifyDebuggerStall(CpuStallKind.ImportLoop, in importStubEntry, num7, num, value, value2);
if (TryForceGuestExitToHostStub(argPackPtr, num, num7, importStubEntry.Nid))
{
cpuContext[CpuRegister.Rax] = 1uL;
return 1uL;
}
}
bool flag0 = importStubEntry.SuppressStrlenTrace;
bool flag = num7 >= 2156221920u && num7 <= 2156225024u;
@@ -9,6 +9,7 @@ using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using SharpEmu.Core.Cpu;
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Core.Loader;
using SharpEmu.Core.Memory;
using SharpEmu.HLE;
@@ -235,6 +236,11 @@ public sealed unsafe partial class DirectExecutionBackend : INativeCpuBackend, I
private CpuContext? _cpuContext;
// Debugger seam; both null when no debugger is attached.
private ICpuDebugHook? _debugHook;
private ICpuDebugFrame? _activeDebugFrame;
[ThreadStatic]
private static DirectExecutionBackend? _activeExecutionBackend;
@@ -890,6 +896,49 @@ public sealed unsafe partial class DirectExecutionBackend : INativeCpuBackend, I
private bool HasActiveExecutionThread => ReferenceEquals(_activeExecutionBackend, this);
/// <summary>
/// Binds the debug frame view the dispatcher created for the frame about to
/// run, so stall notifications reference the same frame the debugger saw at
/// entry. Set to null when no debugger is attached.
/// </summary>
internal void SetActiveDebugFrame(ICpuDebugFrame? frame) => _activeDebugFrame = frame;
/// <summary>
/// Notifies an attached debugger of a detected execution stall. No-op when no
/// debugger is attached or no frame is bound. The debugger may block here to
/// present a break before the backend forces the guest out of the loop.
/// </summary>
private void NotifyDebuggerStall(
CpuStallKind kind,
in ImportStubEntry import,
ulong instructionPointer,
long dispatchIndex,
ulong argument0,
ulong argument1)
{
var hook = _debugHook;
var frame = _activeDebugFrame;
if (hook is null || frame is null)
{
return;
}
var export = import.Export;
var exportDescription = export is null ? "unresolved" : $"{export.LibraryName}:{export.Name}";
var detail = $"kind={kind}, nid={import.Nid}, export={exportDescription}, dispatch#{dispatchIndex}, " +
$"rip=0x{instructionPointer:X16}, arg0=0x{argument0:X16}, arg1=0x{argument1:X16}";
hook.OnStall(frame, new CpuStallInfo(
kind,
import.Nid,
instructionPointer,
dispatchIndex,
argument0,
argument1,
detail,
export?.LibraryName,
export?.Name));
}
private CpuContext? ActiveCpuContext => HasActiveExecutionThread ? _activeCpuContext : _cpuContext;
private ulong ActiveEntryReturnSentinelRip
@@ -1051,6 +1100,7 @@ public sealed unsafe partial class DirectExecutionBackend : INativeCpuBackend, I
Console.Error.WriteLine(_moduleManager.TryGetExport("L-Q3LEjIbgA", out ExportedFunction export2) ? ("[LOADER][INFO] ExportCheck map_direct: " + export2.LibraryName + ":" + export2.Name) : "[LOADER][INFO] ExportCheck map_direct: MISSING");
_entryPoint = entryPoint;
_cpuContext = context;
_debugHook = executionOptions.DebugHook;
_returnFallbackTarget = context[CpuRegister.Rsi];
Volatile.Write(ref _globalFallbackTarget, _returnFallbackTarget);
Volatile.Write(ref _globalUnresolvedReturnStub, (ulong)_unresolvedReturnStub);
@@ -68,6 +68,7 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
CpuEngine = cpuExecutionOptions.CpuEngine,
StrictDynlibResolution = cpuExecutionOptions.StrictDynlibResolution,
ImportTraceLimit = Math.Max(0, cpuExecutionOptions.ImportTraceLimit),
DebugHook = cpuExecutionOptions.DebugHook,
};
_fileSystem = fileSystem ?? new PhysicalFileSystem();
}
@@ -79,6 +80,7 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
CpuEngine = options.CpuEngine,
StrictDynlibResolution = options.StrictDynlibResolution,
ImportTraceLimit = Math.Max(0, options.ImportTraceLimit),
DebugHook = options.DebugHook,
};
var moduleManager = new ModuleManager();
// The compile-time generated registry (SharpEmu.SourceGenerators) is the sole
@@ -4,6 +4,7 @@
namespace SharpEmu.Core.Runtime;
using SharpEmu.Core.Cpu;
using SharpEmu.Core.Cpu.Debugging;
public readonly struct SharpEmuRuntimeOptions
{
@@ -12,4 +13,11 @@ public readonly struct SharpEmuRuntimeOptions
public bool StrictDynlibResolution { get; init; }
public int ImportTraceLimit { get; init; }
/// <summary>
/// An optional debugger to attach to guest execution. Flows through to
/// <see cref="CpuExecutionOptions.DebugHook"/>. Null (the default) runs with
/// no debugger attached.
/// </summary>
public ICpuDebugHook? DebugHook { get; init; }
}
@@ -0,0 +1,54 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net;
namespace SharpEmu.DebugClient;
/// <summary>
/// Parses the <c>host:port</c> the client connects to. Mirrors the server's
/// defaults (loopback, port 5714) so a bare invocation attaches to a local
/// emulator with no arguments.
/// </summary>
internal static class ClientEndpoint
{
public const int DefaultPort = 5714;
public static bool TryParse(string? text, out string host, out int port, out string error)
{
host = "127.0.0.1";
port = DefaultPort;
error = string.Empty;
if (string.IsNullOrWhiteSpace(text))
{
return true;
}
var value = text.Trim();
var separator = value.LastIndexOf(':');
if (separator >= 0)
{
var portText = value[(separator + 1)..];
if (portText.Length > 0 && (!int.TryParse(portText, out port) || port is <= 0 or > 65535))
{
error = $"Invalid port '{portText}'.";
return false;
}
value = value[..separator];
}
if (!string.IsNullOrWhiteSpace(value))
{
host = string.Equals(value, "localhost", StringComparison.OrdinalIgnoreCase) ? "127.0.0.1" : value;
}
if (!IPAddress.TryParse(host, out _) && !Uri.CheckHostName(host).Equals(UriHostNameType.Dns))
{
error = $"Invalid host '{host}'.";
return false;
}
return true;
}
}
@@ -0,0 +1,160 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Text.Json;
namespace SharpEmu.DebugClient;
/// <summary>
/// Turns a friendly REPL line (<c>mem 0x1000 64</c>) into the JSON request the
/// server understands. Local-only verbs (help, quit) are reported back to the
/// caller instead of producing a request.
/// </summary>
internal static class CommandTranslator
{
public enum ActionKind
{
SendRequest,
ShowHelp,
Quit,
Ignore,
Error,
}
public readonly record struct Result(ActionKind Kind, string? Payload = null, string? Error = null);
public static Result Translate(string line)
{
var trimmed = line.Trim();
if (trimmed.Length == 0)
{
return new Result(ActionKind.Ignore);
}
var parts = trimmed.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
var verb = parts[0].ToLowerInvariant();
switch (verb)
{
case "help" or "?":
return new Result(ActionKind.ShowHelp);
case "quit" or "exit" or "q":
return new Result(ActionKind.Quit);
case "raw":
var json = trimmed[verb.Length..].Trim();
return json.Length == 0
? Error("raw requires a JSON object argument.")
: Send(json);
case "ping":
return Request("ping");
case "status" or "info":
return Request("status");
case "state":
return Request("state");
case "regs" or "registers":
return Request("registers");
case "continue" or "cont" or "c":
return Request("continue");
case "step" or "s":
return Request("step");
case "pause" or "p":
return Request("pause");
case "bp" or "breakpoints" or "bl":
return Request("list-breakpoints");
case "setreg":
return parts.Length >= 3
? Request("set-register", ("register", parts[1]), ("value", parts[2]))
: Error("Usage: setreg <register> <value>");
case "mem" or "read":
return parts.Length >= 3
? Request("read-memory", ("address", parts[1]), ("length", parts[2]))
: Error("Usage: mem <address> <length>");
case "write":
return parts.Length >= 3
? Request("write-memory", ("address", parts[1]), ("bytes", parts[2]))
: Error("Usage: write <address> <hex-bytes>");
case "break" or "b":
if (parts.Length < 2)
{
return Error("Usage: break <address> [kind] [length]");
}
var breakArgs = new List<(string, string)> { ("address", parts[1]) };
if (parts.Length >= 3)
{
breakArgs.Add(("kind", parts[2]));
}
if (parts.Length >= 4)
{
breakArgs.Add(("length", parts[3]));
}
return Request("add-breakpoint", breakArgs.ToArray());
case "del" or "rm" or "delete":
return parts.Length >= 2
? Request("remove-breakpoint", ("id", parts[1]))
: Error("Usage: del <id>");
case "enable":
return parts.Length >= 2
? Request("enable-breakpoint", ("id", parts[1]), ("enabled", "true"))
: Error("Usage: enable <id>");
case "disable":
return parts.Length >= 2
? RequestWithBool("enable-breakpoint", ("id", parts[1]), enabledName: "enabled", enabled: false)
: Error("Usage: disable <id>");
default:
return Error($"Unknown command '{verb}'. Type 'help' for the command list.");
}
}
private static Result Request(string command, params (string Name, string Value)[] args)
{
var payload = new Dictionary<string, object?> { ["command"] = command };
foreach (var (name, value) in args)
{
payload[name] = value;
}
return Send(JsonSerializer.Serialize(payload));
}
private static Result RequestWithBool(string command, (string Name, string Value) idArg, string enabledName, bool enabled)
{
var payload = new Dictionary<string, object?>
{
["command"] = command,
[idArg.Name] = idArg.Value,
[enabledName] = enabled,
};
return Send(JsonSerializer.Serialize(payload));
}
private static Result Send(string json) => new(ActionKind.SendRequest, json);
private static Result Error(string message) => new(ActionKind.Error, Error: message);
public const string HelpText = """
SharpEmu debug client commands:
status | info Show target state and last stop
state Show run state only
regs | registers Dump integer registers (paused only)
setreg <reg> <value> Set a register (rip/rflags/gp, paused only)
mem <addr> <len> Read guest memory as hex (paused only)
write <addr> <hex> Write guest memory from hex (paused only)
break <addr> [kind] [len] Add a breakpoint (kind: execute/readwatch/writewatch/accesswatch)
bp | breakpoints List breakpoints
del <id> Remove a breakpoint
enable <id> / disable <id> Toggle a breakpoint
continue | c Resume the target
step | s Resume and stop at the next frame
pause Ask a running target to stop
ping Round-trip check
raw <json> Send a literal JSON request
help | ? Show this help
quit | exit Disconnect and exit
Addresses and values accept decimal or 0x-prefixed hex.
""";
}
+153
View File
@@ -0,0 +1,153 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# SharpEmu.DebugClient
A small, standalone command-line client that connects to the SharpEmu
emulator's **live debug server** and drives it interactively. It ships as its
own executable (`SharpEmu.DebugClient`) and takes no dependency on the emulator
assemblies — it speaks the server's line-delimited JSON protocol directly over
TCP, so you can also drive the server from `nc`, a script, or your own tool.
> **Status:** infrastructure. The transport, protocol, session model, and
> breakpoint store are in place. Stops are delivered at **frame boundaries**
> (process entry and each module initializer); per-instruction stepping and data
> watchpoints are part of the surface and become live as the CPU backend grows
> the corresponding hooks. See [`docs/debugger-server.md`](../../docs/debugger-server.md)
> for the architecture and protocol reference.
## How it fits together
```
+-------------------------+ TCP (JSON lines) +----------------------+
| SharpEmu (emulator) | <------------------------------> | SharpEmu.DebugClient |
| --debug-server | | (this executable) |
| | | |
| DebuggerServerHost | | REPL / --exec |
| +- DebuggerServer | frame boundaries via ICpuDebugHook| |
| +- DebuggerSession <-+------ CPU dispatcher ------------ | |
+-------------------------+ +----------------------+
```
The emulator is the **server**; this client is a separate process that connects
to it and issues commands. The two never share memory — everything crosses the
socket as JSON.
## Building
```bash
dotnet build src/SharpEmu.DebugClient/SharpEmu.DebugClient.csproj
```
## Quick start
1. Launch the emulator with the debug server enabled. It listens on
`127.0.0.1:5714` by default and, with stop-at-entry on, parks the guest at
its first frame until you continue:
```bash
SharpEmu --debug-server "/path/to/game/eboot.bin"
# or choose an endpoint:
SharpEmu --debug-server=127.0.0.1:5714 "/path/to/game/eboot.bin"
```
2. In another terminal, attach the client:
```bash
SharpEmu.DebugClient # defaults to 127.0.0.1:5714
SharpEmu.DebugClient 127.0.0.1:5714 # explicit endpoint
```
3. Drive the target:
```
status
regs
break 0x00000008801234a0
continue
mem 0x00000008802000000 64
```
## Invocation
```
SharpEmu.DebugClient [host:port] [--exec "<command>"]... [--quiet]
```
| Option | Meaning |
| ------------- | ------------------------------------------------------------- |
| `host:port` | Server endpoint. Default `127.0.0.1:5714`. `localhost` is fine. |
| `--exec, -e` | Run one command non-interactively, then exit. Repeatable. |
| `--quiet` | Suppress the connection banner. |
| `--help, -h` | Show usage and the command list. |
Non-interactive example (scriptable):
```bash
SharpEmu.DebugClient --exec "break 0x8801234a0" --exec "continue"
```
## Commands
Addresses and values accept decimal or `0x`-prefixed hex. Register and memory
commands only succeed while the target is **paused**.
| Command | Server verb | Description |
| ------- | ----------- | ----------- |
| `status` \| `info` | `status` | Target state plus the last stop. |
| `state` | `state` | Run state only (`Running`/`Paused`/…). |
| `regs` \| `registers` | `registers` | Dump the integer registers. |
| `setreg <reg> <value>` | `set-register` | Set `rip`, `rflags`, or a GP register. |
| `mem <addr> <len>` \| `read <addr> <len>` | `read-memory` | Read guest memory as hex. |
| `write <addr> <hex>` | `write-memory` | Write guest memory from a hex string. |
| `break <addr> [kind] [len]` \| `b …` | `add-breakpoint` | Add a breakpoint. `kind`: `execute` (default), `readwatch`, `writewatch`, `accesswatch`. |
| `bp` \| `breakpoints` | `list-breakpoints` | List breakpoints. |
| `del <id>` \| `rm <id>` | `remove-breakpoint` | Remove a breakpoint. |
| `enable <id>` / `disable <id>` | `enable-breakpoint` | Toggle a breakpoint. |
| `continue` \| `c` | `continue` | Resume a paused target. |
| `step` \| `s` | `step` | Resume and stop at the next frame boundary. |
| `pause` | `pause` | Ask a running target to stop at the next boundary. |
| `ping` | `ping` | Round-trip liveness check. |
| `raw <json>` | *(passthrough)* | Send a literal JSON request. |
| `help` \| `?` | — | Show the command list (local). |
| `quit` \| `exit` | — | Disconnect and exit (local). |
## Output
The client prints two kinds of lines as they arrive:
- `reply>` — the response to a command you sent (`ok`, plus `data` or `error`).
- `event>` — an unsolicited notification: `hello` on connect, `stopped` when the
target hits a breakpoint / entry / step / pause, `resumed` on continue, and
`terminated` when the run ends.
Because replies and events share one stream, the client prints everything it
receives rather than pairing replies to requests — a `stopped` event may arrive
between your command and its reply.
## Protocol (for building your own client)
One JSON object per line, UTF-8, `\n`-terminated, in both directions.
Request:
```json
{"command":"read-memory","address":"0x8802000000","length":64}
```
Reply:
```json
{"ok":true,"command":"read-memory","data":{"address":"0x0000000880200000","length":64,"bytes":"48894C24.."}}
```
Event:
```json
{"event":"stopped","reason":"Breakpoint","address":"0x00000008801234A0","frameKind":"ProcessEntry","frameLabel":"eboot.bin","registers":{ ... }}
```
The full verb list and payload fields live in
[`docs/debugger-server.md`](../../docs/debugger-server.md).
@@ -0,0 +1,120 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
namespace SharpEmu.DebugClient;
/// <summary>
/// A thin TCP wrapper around the server's line-delimited JSON protocol: it
/// writes request lines and runs a background loop that prints incoming
/// responses and events as they arrive. Because the stream interleaves replies
/// with asynchronous stop/resume events, a single reader printing everything is
/// simpler and more robust than correlating request/response pairs.
/// </summary>
internal sealed class DebugClientConnection : IAsyncDisposable
{
private static readonly UTF8Encoding Utf8NoBom = new(encoderShouldEmitUTF8Identifier: false);
private static readonly JsonSerializerOptions PrettyOptions = new() { WriteIndented = true };
private readonly TcpClient _client;
private readonly StreamReader _reader;
private readonly StreamWriter _writer;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private DebugClientConnection(TcpClient client, NetworkStream stream)
{
_client = client;
_reader = new StreamReader(stream, Utf8NoBom);
_writer = new StreamWriter(stream, Utf8NoBom) { AutoFlush = false };
}
public static async Task<DebugClientConnection> ConnectAsync(string host, int port, CancellationToken cancellationToken)
{
var client = new TcpClient();
await client.ConnectAsync(host, port, cancellationToken).ConfigureAwait(false);
return new DebugClientConnection(client, client.GetStream());
}
/// <summary>Continuously prints incoming lines until the stream closes.</summary>
public async Task ReceiveLoopAsync(CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
var line = await _reader.ReadLineAsync(cancellationToken).ConfigureAwait(false);
if (line is null)
{
Console.WriteLine();
Console.WriteLine("[connection closed by server]");
return;
}
Print(line);
}
}
catch (OperationCanceledException)
{
}
catch (IOException)
{
Console.WriteLine();
Console.WriteLine("[connection lost]");
}
}
public async Task SendAsync(string json, CancellationToken cancellationToken)
{
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await _writer.WriteLineAsync(json.AsMemory(), cancellationToken).ConfigureAwait(false);
await _writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_writeLock.Release();
}
}
private static void Print(string line)
{
try
{
using var document = JsonDocument.Parse(line);
var root = document.RootElement;
var isEvent = root.TryGetProperty("event", out _);
var prefix = isEvent ? "event>" : "reply>";
var pretty = JsonSerializer.Serialize(root, PrettyOptions);
Console.WriteLine();
Console.WriteLine($"{prefix}\n{pretty}");
}
catch (JsonException)
{
Console.WriteLine();
Console.WriteLine(line);
}
}
public async ValueTask DisposeAsync()
{
try
{
await _writer.FlushAsync().ConfigureAwait(false);
}
catch (IOException)
{
}
catch (ObjectDisposedException)
{
}
_writeLock.Dispose();
_reader.Dispose();
await _writer.DisposeAsync().ConfigureAwait(false);
_client.Dispose();
}
}
+193
View File
@@ -0,0 +1,193 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net.Sockets;
using SharpEmu.DebugClient;
return await ClientProgram.RunAsync(args).ConfigureAwait(false);
internal static class ClientProgram
{
public static async Task<int> RunAsync(string[] args)
{
if (args.Any(a => a is "--help" or "-h"))
{
PrintUsage();
return 0;
}
string? endpointArg = null;
var execCommands = new List<string>();
var quiet = false;
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (string.Equals(arg, "--exec", StringComparison.OrdinalIgnoreCase) || string.Equals(arg, "-e", StringComparison.OrdinalIgnoreCase))
{
if (i + 1 >= args.Length)
{
Console.Error.WriteLine("--exec requires a command argument.");
return 2;
}
execCommands.Add(args[++i]);
continue;
}
if (string.Equals(arg, "--quiet", StringComparison.OrdinalIgnoreCase))
{
quiet = true;
continue;
}
if (arg.StartsWith('-'))
{
Console.Error.WriteLine($"Unknown option '{arg}'.");
PrintUsage();
return 2;
}
endpointArg ??= arg;
}
if (!ClientEndpoint.TryParse(endpointArg, out var host, out var port, out var endpointError))
{
Console.Error.WriteLine(endpointError);
return 2;
}
using var shutdown = new CancellationTokenSource();
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
shutdown.Cancel();
};
DebugClientConnection connection;
try
{
connection = await DebugClientConnection.ConnectAsync(host, port, shutdown.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is SocketException or OperationCanceledException)
{
Console.Error.WriteLine($"Could not connect to {host}:{port}: {ex.Message}");
Console.Error.WriteLine("Start the emulator with --debug-server first.");
return 3;
}
await using (connection)
{
var receiveTask = connection.ReceiveLoopAsync(shutdown.Token);
if (execCommands.Count > 0)
{
await RunOneShotAsync(connection, execCommands, shutdown.Token).ConfigureAwait(false);
}
else
{
if (!quiet)
{
Console.WriteLine($"Connected to SharpEmu debug server at {host}:{port}.");
Console.WriteLine("Type 'help' for commands, 'quit' to exit.");
}
await RunReplAsync(connection, shutdown).ConfigureAwait(false);
}
shutdown.Cancel();
try
{
await receiveTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
return 0;
}
private static async Task RunOneShotAsync(
DebugClientConnection connection,
IReadOnlyList<string> commands,
CancellationToken cancellationToken)
{
foreach (var command in commands)
{
var result = CommandTranslator.Translate(command);
switch (result.Kind)
{
case CommandTranslator.ActionKind.SendRequest:
await connection.SendAsync(result.Payload!, cancellationToken).ConfigureAwait(false);
break;
case CommandTranslator.ActionKind.Error:
Console.Error.WriteLine(result.Error);
break;
case CommandTranslator.ActionKind.ShowHelp:
Console.WriteLine(CommandTranslator.HelpText);
break;
}
}
// Give the server a moment to answer before the client exits.
try
{
await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
private static async Task RunReplAsync(DebugClientConnection connection, CancellationTokenSource shutdown)
{
while (!shutdown.IsCancellationRequested)
{
var line = await Console.In.ReadLineAsync(shutdown.Token).ConfigureAwait(false);
if (line is null)
{
break;
}
var result = CommandTranslator.Translate(line);
switch (result.Kind)
{
case CommandTranslator.ActionKind.Quit:
return;
case CommandTranslator.ActionKind.ShowHelp:
Console.WriteLine(CommandTranslator.HelpText);
break;
case CommandTranslator.ActionKind.Error:
Console.Error.WriteLine(result.Error);
break;
case CommandTranslator.ActionKind.Ignore:
break;
case CommandTranslator.ActionKind.SendRequest:
try
{
await connection.SendAsync(result.Payload!, shutdown.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
Console.Error.WriteLine("Send failed; the connection is closed.");
return;
}
break;
}
}
}
private static void PrintUsage()
{
Console.WriteLine("SharpEmu.DebugClient — live debugger client for the SharpEmu debug server.");
Console.WriteLine();
Console.WriteLine("Usage: SharpEmu.DebugClient [host:port] [--exec \"<command>\"]... [--quiet]");
Console.WriteLine(" host:port Server endpoint (default 127.0.0.1:5714).");
Console.WriteLine(" --exec, -e Run a command non-interactively (repeatable), then exit.");
Console.WriteLine(" --quiet Suppress the connection banner.");
Console.WriteLine(" --help, -h Show this help.");
Console.WriteLine();
Console.WriteLine(CommandTranslator.HelpText);
}
}
@@ -0,0 +1,16 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- A small, standalone console tool: it speaks the debug server's
line-delimited JSON protocol directly over TCP and takes no dependency
on the emulator assemblies, so it builds and ships independently. -->
<OutputType>Exe</OutputType>
<AssemblyName>SharpEmu.DebugClient</AssemblyName>
<RootNamespace>SharpEmu.DebugClient</RootNamespace>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
</Project>
@@ -0,0 +1,48 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Breakpoints;
/// <summary>
/// A single breakpoint or watchpoint. Instances are immutable; the owning
/// <see cref="BreakpointStore"/> replaces an entry to change its enabled state.
/// </summary>
public sealed class Breakpoint
{
public Breakpoint(int id, BreakpointKind kind, ulong address, ulong length = 1, bool enabled = true)
{
if (length == 0)
{
throw new ArgumentOutOfRangeException(nameof(length), "Breakpoint length must be at least one byte.");
}
Id = id;
Kind = kind;
Address = address;
Length = length;
Enabled = enabled;
}
/// <summary>The store-assigned identifier used by clients to reference it.</summary>
public int Id { get; }
public BreakpointKind Kind { get; }
/// <summary>The first guest address the breakpoint covers.</summary>
public ulong Address { get; }
/// <summary>
/// The number of bytes the breakpoint covers. Always one for
/// <see cref="BreakpointKind.Execute"/>; the watch kinds may span a range.
/// </summary>
public ulong Length { get; }
public bool Enabled { get; }
/// <summary>True when <paramref name="address"/> falls within this breakpoint.</summary>
public bool Covers(ulong address) => address >= Address && address < Address + Length;
/// <summary>Returns a copy with a different enabled state.</summary>
public Breakpoint WithEnabled(bool enabled)
=> enabled == Enabled ? this : new Breakpoint(Id, Kind, Address, Length, enabled);
}
@@ -0,0 +1,26 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Breakpoints;
/// <summary>
/// The kind of stop a breakpoint requests. Execution breakpoints are honoured
/// at the frame-boundary seam that exists today; the data-watch kinds are part
/// of the surface so client protocols and tooling can be built against them,
/// and are armed once the execution backend can report the corresponding
/// accesses.
/// </summary>
public enum BreakpointKind
{
/// <summary>Stop when the instruction pointer reaches the address.</summary>
Execute,
/// <summary>Stop when the guest reads from the address range.</summary>
ReadWatch,
/// <summary>Stop when the guest writes to the address range.</summary>
WriteWatch,
/// <summary>Stop when the guest reads from or writes to the address range.</summary>
AccessWatch,
}
@@ -0,0 +1,90 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Breakpoints;
/// <summary>
/// A thread-safe registry of breakpoints. The debug server mutates it from
/// client-servicing threads while the emulation thread queries it at frame
/// boundaries, so every operation takes the same lock.
/// </summary>
public sealed class BreakpointStore
{
private readonly object _sync = new();
private readonly Dictionary<int, Breakpoint> _breakpoints = new();
private int _nextId = 1;
/// <summary>Adds a breakpoint and returns the created entry with its id.</summary>
public Breakpoint Add(BreakpointKind kind, ulong address, ulong length = 1)
{
lock (_sync)
{
var effectiveLength = kind == BreakpointKind.Execute ? 1UL : Math.Max(1UL, length);
var breakpoint = new Breakpoint(_nextId++, kind, address, effectiveLength);
_breakpoints[breakpoint.Id] = breakpoint;
return breakpoint;
}
}
/// <summary>Removes a breakpoint by id. Returns false when it did not exist.</summary>
public bool Remove(int id)
{
lock (_sync)
{
return _breakpoints.Remove(id);
}
}
/// <summary>Enables or disables a breakpoint by id.</summary>
public bool SetEnabled(int id, bool enabled)
{
lock (_sync)
{
if (!_breakpoints.TryGetValue(id, out var breakpoint))
{
return false;
}
_breakpoints[id] = breakpoint.WithEnabled(enabled);
return true;
}
}
/// <summary>Removes every breakpoint.</summary>
public void Clear()
{
lock (_sync)
{
_breakpoints.Clear();
}
}
/// <summary>Returns a point-in-time copy of all breakpoints.</summary>
public IReadOnlyList<Breakpoint> Snapshot()
{
lock (_sync)
{
return _breakpoints.Values.ToArray();
}
}
/// <summary>
/// Finds the first enabled execution breakpoint covering <paramref name="address"/>,
/// or null when none applies.
/// </summary>
public Breakpoint? FindExecuteHit(ulong address)
{
lock (_sync)
{
foreach (var breakpoint in _breakpoints.Values)
{
if (breakpoint.Enabled && breakpoint.Kind == BreakpointKind.Execute && breakpoint.Covers(address))
{
return breakpoint;
}
}
return null;
}
}
}
@@ -0,0 +1,73 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.HLE;
namespace SharpEmu.Debugger;
/// <summary>
/// An immutable snapshot of the guest integer register state at a stop. XMM/YMM
/// state is intentionally omitted here and read on demand through the target to
/// keep the common register-dump path cheap.
/// </summary>
public readonly struct DebugRegisterFile
{
private readonly ulong[] _generalPurpose;
public DebugRegisterFile(
ulong[] generalPurpose,
ulong rip,
ulong rflags,
ulong fsBase,
ulong gsBase)
{
ArgumentNullException.ThrowIfNull(generalPurpose);
if (generalPurpose.Length != 16)
{
throw new ArgumentException("Expected 16 general-purpose registers.", nameof(generalPurpose));
}
_generalPurpose = generalPurpose;
Rip = rip;
Rflags = rflags;
FsBase = fsBase;
GsBase = gsBase;
}
public ulong Rip { get; }
public ulong Rflags { get; }
public ulong FsBase { get; }
public ulong GsBase { get; }
/// <summary>Reads a register by identifier.</summary>
public ulong this[DebugRegisterId id] => id switch
{
DebugRegisterId.Rip => Rip,
DebugRegisterId.Rflags => Rflags,
DebugRegisterId.FsBase => FsBase,
DebugRegisterId.GsBase => GsBase,
_ when id.IsGeneralPurpose() => _generalPurpose[(int)id],
_ => throw new ArgumentOutOfRangeException(nameof(id), id, null),
};
/// <summary>Reads a general-purpose register.</summary>
public ulong this[CpuRegister register] => _generalPurpose[(int)register];
/// <summary>Captures the integer register state of a live debug frame.</summary>
public static DebugRegisterFile Capture(ICpuDebugFrame frame)
{
ArgumentNullException.ThrowIfNull(frame);
var gpr = new ulong[16];
for (var i = 0; i < gpr.Length; i++)
{
gpr[i] = frame.GetRegister((CpuRegister)i);
}
return new DebugRegisterFile(gpr, frame.Rip, frame.Rflags, frame.FsBase, frame.GsBase);
}
}
+62
View File
@@ -0,0 +1,62 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
namespace SharpEmu.Debugger;
/// <summary>
/// The registers a debugger can name. The first sixteen values line up with
/// <see cref="CpuRegister"/> so a general-purpose register can be converted
/// between the two enums by casting; the remaining values cover the special
/// registers a debug frame exposes.
/// </summary>
public enum DebugRegisterId
{
Rax = 0,
Rcx = 1,
Rdx = 2,
Rbx = 3,
Rsp = 4,
Rbp = 5,
Rsi = 6,
Rdi = 7,
R8 = 8,
R9 = 9,
R10 = 10,
R11 = 11,
R12 = 12,
R13 = 13,
R14 = 14,
R15 = 15,
Rip = 16,
Rflags = 17,
FsBase = 18,
GsBase = 19,
}
/// <summary>Helpers for mapping between debug and CPU register identifiers.</summary>
public static class DebugRegisterIdExtensions
{
/// <summary>
/// True when the identifier names one of the sixteen general-purpose
/// registers and can be cast to <see cref="CpuRegister"/>.
/// </summary>
public static bool IsGeneralPurpose(this DebugRegisterId id)
=> id is >= DebugRegisterId.Rax and <= DebugRegisterId.R15;
/// <summary>
/// Converts a general-purpose identifier to its <see cref="CpuRegister"/>.
/// Throws when <paramref name="id"/> is a special register.
/// </summary>
public static CpuRegister ToCpuRegister(this DebugRegisterId id)
{
if (!id.IsGeneralPurpose())
{
throw new ArgumentOutOfRangeException(nameof(id), id, "Not a general-purpose register.");
}
return (CpuRegister)(int)id;
}
}
@@ -0,0 +1,59 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net;
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Debugger.Server;
using SharpEmu.Debugger.Session;
namespace SharpEmu.Debugger;
/// <summary>
/// One-call wiring of the live debugger: it owns a <see cref="DebuggerSession"/>
/// and a <see cref="DebuggerServer"/>, exposes the <see cref="Hook"/> to attach
/// to <c>SharpEmuRuntimeOptions.DebugHook</c>, and starts/stops the network
/// front-end. A host constructs one, hands <see cref="Hook"/> to the runtime,
/// calls <see cref="Start"/>, and calls <see cref="NotifyRunCompleted"/> once the
/// runtime returns.
/// </summary>
public sealed class DebuggerServerHost : IAsyncDisposable
{
private readonly DebuggerSession _session;
private readonly DebuggerServer _server;
public DebuggerServerHost(
DebuggerServerOptions? serverOptions = null,
DebuggerSessionOptions? sessionOptions = null)
{
_session = new DebuggerSession(sessionOptions);
_server = new DebuggerServer(_session, serverOptions);
}
/// <summary>The session driving the target.</summary>
public IDebuggerSession Session => _session;
/// <summary>
/// The dispatcher hook to hand to the runtime so guest frames route through
/// the debugger.
/// </summary>
public ICpuDebugHook Hook => _session.Hook;
/// <summary>The endpoint the server bound to, or null before <see cref="Start"/>.</summary>
public IPEndPoint? Endpoint => _server.Endpoint;
/// <summary>Begins accepting debugger clients.</summary>
public void Start() => _server.Start();
/// <summary>
/// Releases a parked emulation thread and marks the target terminated. Call
/// after the runtime's run returns so any attached client is notified and the
/// guest thread is never left blocked in the debugger.
/// </summary>
public void NotifyRunCompleted() => _session.NotifyTerminated();
public async ValueTask DisposeAsync()
{
_session.NotifyTerminated();
await _server.DisposeAsync().ConfigureAwait(false);
}
}
@@ -0,0 +1,340 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Debugger.Breakpoints;
using SharpEmu.Debugger.Session;
using SharpEmu.HLE;
namespace SharpEmu.Debugger.Protocol;
/// <summary>
/// Translates parsed <see cref="DebugRequest"/> verbs into operations on an
/// <see cref="IDebuggerSession"/> and packages the outcome as a
/// <see cref="DebugResponse"/>. This is the single place command semantics live,
/// so it is shared by every connection and independent of the wire format.
/// </summary>
public sealed class DebugCommandDispatcher
{
private readonly IDebuggerSession _session;
public DebugCommandDispatcher(IDebuggerSession session)
{
_session = session ?? throw new ArgumentNullException(nameof(session));
}
public DebugResponse Dispatch(DebugRequest request)
{
return request.Command switch
{
JsonLineDebugProtocol.ParseErrorCommand => ParseError(request),
"ping" => DebugResponse.Success(request.Command),
"status" or "info" => Status(request),
"state" => DebugResponse.Success(request.Command, new Dictionary<string, object?>
{
["state"] = _session.State.ToString(),
}),
"registers" or "regs" => Registers(request),
"set-register" or "set-reg" => SetRegister(request),
"read-memory" or "read-mem" => ReadMemory(request),
"write-memory" or "write-mem" => WriteMemory(request),
"list-breakpoints" or "breakpoints" => ListBreakpoints(request),
"add-breakpoint" or "break" => AddBreakpoint(request),
"remove-breakpoint" or "delete-breakpoint" => RemoveBreakpoint(request),
"enable-breakpoint" => EnableBreakpoint(request),
"continue" or "cont" or "c" => Simple(request, _session.Continue(), "Target is not paused."),
"step" or "s" => Simple(request, _session.StepFrame(), "Target is not paused."),
"pause" => Pause(request),
_ => DebugResponse.Failure(request.Command, $"Unknown command '{request.Command}'."),
};
}
private static DebugResponse ParseError(DebugRequest request)
{
var message = request.TryGetString("message", out var text) ? text : "Malformed request.";
return DebugResponse.Failure(request.Command, message);
}
private DebugResponse Status(DebugRequest request)
{
var data = new Dictionary<string, object?>
{
["state"] = _session.State.ToString(),
["breakpoints"] = _session.Breakpoints.Snapshot().Count,
};
if (_session.LastStop is { } stop)
{
data["lastStop"] = DescribeStop(stop);
}
return DebugResponse.Success(request.Command, data);
}
private DebugResponse Registers(DebugRequest request)
{
if (!_session.TryGetRegisters(out var registers))
{
return NotPaused(request);
}
return DebugResponse.Success(request.Command, new Dictionary<string, object?>
{
["registers"] = DescribeRegisters(registers),
});
}
private DebugResponse SetRegister(DebugRequest request)
{
if (!request.TryGetString("register", out var name) || !TryParseRegister(name, out var id))
{
return DebugResponse.Failure(request.Command, "Expected a valid 'register' name.");
}
if (!request.TryGetUInt64("value", out var value))
{
return DebugResponse.Failure(request.Command, "Expected a 'value'.");
}
return _session.TrySetRegister(id, value)
? DebugResponse.Success(request.Command)
: DebugResponse.Failure(request.Command, "Register is not writable or target is not paused.");
}
private DebugResponse ReadMemory(DebugRequest request)
{
if (!request.TryGetUInt64("address", out var address))
{
return DebugResponse.Failure(request.Command, "Expected an 'address'.");
}
if (!request.TryGetInt32("length", out var length) || length <= 0 || length > MaxMemoryChunk)
{
return DebugResponse.Failure(request.Command, $"Expected a 'length' between 1 and {MaxMemoryChunk}.");
}
var buffer = new byte[length];
if (!_session.TryReadMemory(address, buffer))
{
return DebugResponse.Failure(request.Command, "Memory is unreadable or target is not paused.");
}
return DebugResponse.Success(request.Command, new Dictionary<string, object?>
{
["address"] = FormatAddress(address),
["length"] = length,
["bytes"] = Convert.ToHexString(buffer),
});
}
private DebugResponse WriteMemory(DebugRequest request)
{
if (!request.TryGetUInt64("address", out var address))
{
return DebugResponse.Failure(request.Command, "Expected an 'address'.");
}
if (!request.TryGetString("bytes", out var hex) || hex.Length == 0 || (hex.Length & 1) != 0)
{
return DebugResponse.Failure(request.Command, "Expected 'bytes' as an even-length hex string.");
}
byte[] data;
try
{
data = Convert.FromHexString(hex);
}
catch (FormatException)
{
return DebugResponse.Failure(request.Command, "'bytes' is not valid hex.");
}
if (data.Length > MaxMemoryChunk)
{
return DebugResponse.Failure(request.Command, $"Cannot write more than {MaxMemoryChunk} bytes at once.");
}
return _session.TryWriteMemory(address, data)
? DebugResponse.Success(request.Command, new Dictionary<string, object?> { ["written"] = data.Length })
: DebugResponse.Failure(request.Command, "Memory is unwritable or target is not paused.");
}
private DebugResponse ListBreakpoints(DebugRequest request)
{
var breakpoints = _session.Breakpoints.Snapshot()
.OrderBy(breakpoint => breakpoint.Id)
.Select(DescribeBreakpoint)
.ToArray();
return DebugResponse.Success(request.Command, new Dictionary<string, object?>
{
["breakpoints"] = breakpoints,
});
}
private DebugResponse AddBreakpoint(DebugRequest request)
{
if (!request.TryGetUInt64("address", out var address))
{
return DebugResponse.Failure(request.Command, "Expected an 'address'.");
}
var kind = BreakpointKind.Execute;
if (request.TryGetString("kind", out var kindText) && !TryParseBreakpointKind(kindText, out kind))
{
return DebugResponse.Failure(request.Command, $"Unknown breakpoint kind '{kindText}'.");
}
var length = 1UL;
if (request.TryGetUInt64("length", out var requestedLength) && requestedLength > 0)
{
length = requestedLength;
}
var breakpoint = _session.Breakpoints.Add(kind, address, length);
return DebugResponse.Success(request.Command, new Dictionary<string, object?>
{
["breakpoint"] = DescribeBreakpoint(breakpoint),
});
}
private DebugResponse RemoveBreakpoint(DebugRequest request)
{
if (!request.TryGetInt32("id", out var id))
{
return DebugResponse.Failure(request.Command, "Expected an 'id'.");
}
return _session.Breakpoints.Remove(id)
? DebugResponse.Success(request.Command)
: DebugResponse.Failure(request.Command, $"No breakpoint with id {id}.");
}
private DebugResponse EnableBreakpoint(DebugRequest request)
{
if (!request.TryGetInt32("id", out var id))
{
return DebugResponse.Failure(request.Command, "Expected an 'id'.");
}
var enabled = !request.TryGetBool("enabled", out var requested) || requested;
return _session.Breakpoints.SetEnabled(id, enabled)
? DebugResponse.Success(request.Command)
: DebugResponse.Failure(request.Command, $"No breakpoint with id {id}.");
}
private DebugResponse Pause(DebugRequest request)
{
_session.RequestPause();
return DebugResponse.Success(request.Command);
}
private static DebugResponse Simple(DebugRequest request, bool succeeded, string failureMessage)
=> succeeded ? DebugResponse.Success(request.Command) : DebugResponse.Failure(request.Command, failureMessage);
private static DebugResponse NotPaused(DebugRequest request)
=> DebugResponse.Failure(request.Command, "Target is not paused.");
internal static IReadOnlyDictionary<string, object?> DescribeStop(DebugStopEvent stop)
{
var data = new Dictionary<string, object?>
{
["reason"] = stop.Reason.ToString(),
["address"] = FormatAddress(stop.Address),
["frameKind"] = stop.FrameKind.ToString(),
["frameLabel"] = stop.FrameLabel,
["registers"] = DescribeRegisters(stop.Registers),
};
if (stop.Breakpoint is { } breakpoint)
{
data["breakpoint"] = DescribeBreakpoint(breakpoint);
}
if (stop.Result is { } result)
{
data["result"] = result.ToString();
}
if (stop.Detail is { } detail)
{
data["detail"] = detail;
}
if (stop.OpcodeBytes is { } opcodeBytes)
{
data["opcodeBytes"] = opcodeBytes;
}
if (stop.StallInfo is { } stall)
{
data["stall"] = new Dictionary<string, object?>
{
["kind"] = stall.Kind.ToString(),
["nid"] = stall.Nid,
["instructionPointer"] = FormatAddress(stall.InstructionPointer),
["dispatchIndex"] = stall.DispatchIndex,
["argument0"] = FormatAddress(stall.Argument0),
["argument1"] = FormatAddress(stall.Argument1),
["resolved"] = stall.IsResolved,
["library"] = stall.LibraryName,
["function"] = stall.FunctionName,
};
}
return data;
}
private static IReadOnlyDictionary<string, object?> DescribeRegisters(DebugRegisterFile registers)
{
var result = new Dictionary<string, object?>(20);
for (var i = 0; i < 16; i++)
{
result[((CpuRegister)i).ToString().ToLowerInvariant()] = FormatAddress(registers[(CpuRegister)i]);
}
result["rip"] = FormatAddress(registers.Rip);
result["rflags"] = FormatAddress(registers.Rflags);
result["fs_base"] = FormatAddress(registers.FsBase);
result["gs_base"] = FormatAddress(registers.GsBase);
return result;
}
private static IReadOnlyDictionary<string, object?> DescribeBreakpoint(Breakpoint breakpoint)
=> new Dictionary<string, object?>
{
["id"] = breakpoint.Id,
["kind"] = breakpoint.Kind.ToString(),
["address"] = FormatAddress(breakpoint.Address),
["length"] = breakpoint.Length,
["enabled"] = breakpoint.Enabled,
};
private static string FormatAddress(ulong value) => $"0x{value:X16}";
private static bool TryParseRegister(string name, out DebugRegisterId id)
{
var normalized = name.Trim().ToLowerInvariant();
switch (normalized)
{
case "rip":
id = DebugRegisterId.Rip;
return true;
case "rflags":
id = DebugRegisterId.Rflags;
return true;
case "fs_base" or "fsbase":
id = DebugRegisterId.FsBase;
return true;
case "gs_base" or "gsbase":
id = DebugRegisterId.GsBase;
return true;
}
return Enum.TryParse(normalized, ignoreCase: true, out id) && Enum.IsDefined(id);
}
private static bool TryParseBreakpointKind(string text, out BreakpointKind kind)
=> Enum.TryParse(text.Trim(), ignoreCase: true, out kind) && Enum.IsDefined(kind);
private const int MaxMemoryChunk = 64 * 1024;
}
@@ -0,0 +1,152 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Globalization;
using System.Text.Json;
namespace SharpEmu.Debugger.Protocol;
/// <summary>
/// A parsed client request: a <see cref="Command"/> verb plus a bag of named
/// arguments backed by the original JSON. Numeric arguments accept either JSON
/// numbers or <c>"0x"</c>-prefixed hex strings so addresses read naturally on
/// the wire.
/// </summary>
public sealed class DebugRequest
{
private readonly JsonElement _root;
private DebugRequest(string command, JsonElement root)
{
Command = command;
_root = root;
}
/// <summary>The lower-cased command verb.</summary>
public string Command { get; }
/// <summary>
/// Parses a single JSON object into a request. Returns false when the text is
/// not a JSON object or is missing a string <c>command</c> field.
/// </summary>
public static bool TryParse(string json, out DebugRequest request, out string error)
{
request = null!;
error = string.Empty;
try
{
using var document = JsonDocument.Parse(json);
var root = document.RootElement.Clone();
if (root.ValueKind != JsonValueKind.Object)
{
error = "Request must be a JSON object.";
return false;
}
if (!root.TryGetProperty("command", out var commandElement) ||
commandElement.ValueKind != JsonValueKind.String)
{
error = "Request is missing a string 'command'.";
return false;
}
var command = commandElement.GetString() ?? string.Empty;
request = new DebugRequest(command.Trim().ToLowerInvariant(), root);
return true;
}
catch (JsonException ex)
{
error = $"Malformed JSON: {ex.Message}";
return false;
}
}
public bool TryGetString(string name, out string value)
{
if (_root.TryGetProperty(name, out var element) && element.ValueKind == JsonValueKind.String)
{
value = element.GetString() ?? string.Empty;
return true;
}
value = string.Empty;
return false;
}
public bool TryGetUInt64(string name, out ulong value)
{
value = 0;
if (!_root.TryGetProperty(name, out var element))
{
return false;
}
switch (element.ValueKind)
{
case JsonValueKind.Number:
return element.TryGetUInt64(out value);
case JsonValueKind.String:
return TryParseNumber(element.GetString(), out value);
default:
return false;
}
}
public bool TryGetInt32(string name, out int value)
{
value = 0;
if (!_root.TryGetProperty(name, out var element))
{
return false;
}
switch (element.ValueKind)
{
case JsonValueKind.Number:
return element.TryGetInt32(out value);
case JsonValueKind.String when TryParseNumber(element.GetString(), out var parsed) && parsed <= int.MaxValue:
value = (int)parsed;
return true;
default:
return false;
}
}
public bool TryGetBool(string name, out bool value)
{
value = false;
if (!_root.TryGetProperty(name, out var element))
{
return false;
}
switch (element.ValueKind)
{
case JsonValueKind.True:
value = true;
return true;
case JsonValueKind.False:
value = false;
return true;
default:
return false;
}
}
private static bool TryParseNumber(string? text, out ulong value)
{
value = 0;
if (string.IsNullOrWhiteSpace(text))
{
return false;
}
text = text.Trim();
if (text.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
return ulong.TryParse(text.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value);
}
return ulong.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
}
}
@@ -0,0 +1,34 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Protocol;
/// <summary>
/// The reply to a <see cref="DebugRequest"/>: either success with an optional
/// data payload, or a failure with a human-readable message.
/// </summary>
public sealed class DebugResponse
{
private DebugResponse(bool ok, string? command, IReadOnlyDictionary<string, object?>? data, string? error)
{
Ok = ok;
Command = command;
Data = data;
Error = error;
}
public bool Ok { get; }
/// <summary>Echoes the command the reply answers, when known.</summary>
public string? Command { get; }
public IReadOnlyDictionary<string, object?>? Data { get; }
public string? Error { get; }
public static DebugResponse Success(string command, IReadOnlyDictionary<string, object?>? data = null)
=> new(ok: true, command, data, error: null);
public static DebugResponse Failure(string command, string error)
=> new(ok: false, command, data: null, error);
}
@@ -0,0 +1,33 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Protocol;
/// <summary>
/// Frames debugger traffic on a connection. A protocol turns bytes into
/// <see cref="DebugRequest"/> objects and serialises <see cref="DebugResponse"/>
/// replies plus asynchronous events (stops, resumes, termination) back to the
/// client. Swapping the implementation (line-delimited JSON today, a GDB remote
/// serial stub later) leaves the session and server untouched.
/// </summary>
public interface IDebugProtocol
{
/// <summary>A short protocol name reported in the handshake.</summary>
string Name { get; }
/// <summary>
/// Reads the next request, or null at end of stream. Parse failures are
/// surfaced as a request with a reserved error command rather than throwing.
/// </summary>
Task<DebugRequest?> ReadRequestAsync(TextReader reader, CancellationToken cancellationToken);
/// <summary>Writes a reply to a request.</summary>
Task WriteResponseAsync(TextWriter writer, DebugResponse response, CancellationToken cancellationToken);
/// <summary>Writes an unsolicited event (for example a stop notification).</summary>
Task WriteEventAsync(
TextWriter writer,
string eventName,
IReadOnlyDictionary<string, object?> data,
CancellationToken cancellationToken);
}
@@ -0,0 +1,112 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Text.Json;
namespace SharpEmu.Debugger.Protocol;
/// <summary>
/// A newline-delimited JSON protocol: one JSON object per line in each
/// direction. Requests carry a <c>command</c>; replies carry <c>ok</c> plus
/// <c>data</c>/<c>error</c>; events carry an <c>event</c> name. It is trivial to
/// drive from a socket, <c>nc</c>, or a small script, which suits bring-up and
/// tooling while a richer protocol is layered on later.
/// </summary>
public sealed class JsonLineDebugProtocol : IDebugProtocol
{
/// <summary>The command assigned to a request that failed to parse.</summary>
public const string ParseErrorCommand = "$parse-error";
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = false,
};
public string Name => "json-lines/1";
public async Task<DebugRequest?> ReadRequestAsync(TextReader reader, CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false);
if (line is null)
{
return null;
}
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
if (DebugRequest.TryParse(line, out var request, out var error))
{
return request;
}
// Surface the parse failure as a synthetic request so the connection
// loop can reply with an error rather than dropping the client.
var envelope = $"{{\"command\":\"{ParseErrorCommand}\",\"message\":{JsonSerializer.Serialize(error)}}}";
if (DebugRequest.TryParse(envelope, out var errorRequest, out _))
{
return errorRequest;
}
}
}
public async Task WriteResponseAsync(TextWriter writer, DebugResponse response, CancellationToken cancellationToken)
{
var payload = new Dictionary<string, object?>
{
["ok"] = response.Ok,
};
if (response.Command is not null)
{
payload["command"] = response.Command;
}
if (response.Data is not null)
{
payload["data"] = response.Data;
}
if (response.Error is not null)
{
payload["error"] = response.Error;
}
await WriteLineAsync(writer, payload, cancellationToken).ConfigureAwait(false);
}
public async Task WriteEventAsync(
TextWriter writer,
string eventName,
IReadOnlyDictionary<string, object?> data,
CancellationToken cancellationToken)
{
var payload = new Dictionary<string, object?>(data.Count + 1)
{
["event"] = eventName,
};
foreach (var (key, value) in data)
{
payload[key] = value;
}
await WriteLineAsync(writer, payload, cancellationToken).ConfigureAwait(false);
}
private static async Task WriteLineAsync(
TextWriter writer,
IReadOnlyDictionary<string, object?> payload,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var json = JsonSerializer.Serialize(payload, SerializerOptions);
await writer.WriteLineAsync(json.AsMemory(), cancellationToken).ConfigureAwait(false);
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,158 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net.Sockets;
using System.Text;
using SharpEmu.Debugger.Protocol;
using SharpEmu.Debugger.Session;
using SharpEmu.Logging;
namespace SharpEmu.Debugger.Server;
/// <summary>
/// Services a single connected client: reads requests, dispatches them against
/// the shared session, and pushes session lifecycle events. Writes from the
/// request loop and from event callbacks are serialised through one lock so the
/// two never interleave a half-written line.
/// </summary>
internal sealed class DebuggerClientConnection : IAsyncDisposable
{
private static readonly SharpEmuLogger Log = SharpEmuLog.For("SharpEmu.Debugger");
private static readonly UTF8Encoding Utf8NoBom = new(encoderShouldEmitUTF8Identifier: false);
private readonly TcpClient _client;
private readonly IDebuggerSession _session;
private readonly IDebugProtocol _protocol;
private readonly DebugCommandDispatcher _dispatcher;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private TextWriter? _writer;
private CancellationToken _cancellationToken;
public DebuggerClientConnection(TcpClient client, IDebuggerSession session, IDebugProtocol protocol)
{
_client = client;
_session = session;
_protocol = protocol;
_dispatcher = new DebugCommandDispatcher(session);
}
public async Task RunAsync(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
var endpoint = _client.Client.RemoteEndPoint?.ToString() ?? "unknown";
Log.Info($"Debugger client connected: {endpoint}");
using var stream = _client.GetStream();
using var reader = new StreamReader(stream, Utf8NoBom);
await using var writer = new StreamWriter(stream, Utf8NoBom) { AutoFlush = false };
_writer = writer;
_session.Stopped += OnStopped;
_session.Resumed += OnResumed;
_session.Terminated += OnTerminated;
try
{
await SendEventAsync("hello", new Dictionary<string, object?>
{
["protocol"] = _protocol.Name,
["state"] = _session.State.ToString(),
}).ConfigureAwait(false);
while (!cancellationToken.IsCancellationRequested)
{
var request = await _protocol.ReadRequestAsync(reader, cancellationToken).ConfigureAwait(false);
if (request is null)
{
break;
}
var response = _dispatcher.Dispatch(request);
await WriteResponseAsync(response).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
// Server shutting down.
}
catch (IOException)
{
// Client dropped the connection.
}
catch (Exception ex)
{
Log.Warn($"Debugger client error ({endpoint}): {ex.Message}");
}
finally
{
_session.Stopped -= OnStopped;
_session.Resumed -= OnResumed;
_session.Terminated -= OnTerminated;
_writer = null;
Log.Info($"Debugger client disconnected: {endpoint}");
}
}
private void OnStopped(object? sender, DebugStopEvent stop)
=> _ = SendEventAsync("stopped", DebugCommandDispatcher.DescribeStop(stop));
private void OnResumed(object? sender, EventArgs e)
=> _ = SendEventAsync("resumed", EmptyData);
private void OnTerminated(object? sender, EventArgs e)
=> _ = SendEventAsync("terminated", EmptyData);
private async Task WriteResponseAsync(DebugResponse response)
{
var writer = _writer;
if (writer is null)
{
return;
}
await _writeLock.WaitAsync(_cancellationToken).ConfigureAwait(false);
try
{
await _protocol.WriteResponseAsync(writer, response, _cancellationToken).ConfigureAwait(false);
}
finally
{
_writeLock.Release();
}
}
private async Task SendEventAsync(string name, IReadOnlyDictionary<string, object?> data)
{
var writer = _writer;
if (writer is null)
{
return;
}
try
{
await _writeLock.WaitAsync(_cancellationToken).ConfigureAwait(false);
try
{
await _protocol.WriteEventAsync(writer, name, data, _cancellationToken).ConfigureAwait(false);
}
finally
{
_writeLock.Release();
}
}
catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException)
{
// The client went away between the event firing and the write.
}
}
public ValueTask DisposeAsync()
{
_writeLock.Dispose();
_client.Dispose();
return ValueTask.CompletedTask;
}
private static readonly IReadOnlyDictionary<string, object?> EmptyData = new Dictionary<string, object?>();
}
@@ -0,0 +1,136 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using SharpEmu.Debugger.Protocol;
using SharpEmu.Debugger.Session;
using SharpEmu.Logging;
namespace SharpEmu.Debugger.Server;
/// <summary>
/// A TCP server that exposes an <see cref="IDebuggerSession"/> to remote
/// clients over a pluggable <see cref="IDebugProtocol"/>. Every connection sees
/// the same session, so multiple clients (for example a UI and a scripted
/// probe) observe a consistent view of the target.
/// </summary>
public sealed class DebuggerServer : IDebuggerServer
{
private static readonly SharpEmuLogger Log = SharpEmuLog.For("SharpEmu.Debugger");
private readonly IDebuggerSession _session;
private readonly DebuggerServerOptions _options;
private readonly Func<IDebugProtocol> _protocolFactory;
private readonly ConcurrentDictionary<DebuggerClientConnection, Task> _connections = new();
private readonly CancellationTokenSource _shutdown = new();
private TcpListener? _listener;
private Task? _acceptLoop;
public DebuggerServer(
IDebuggerSession session,
DebuggerServerOptions? options = null,
Func<IDebugProtocol>? protocolFactory = null)
{
_session = session ?? throw new ArgumentNullException(nameof(session));
_options = options ?? new DebuggerServerOptions();
_protocolFactory = protocolFactory ?? (static () => new JsonLineDebugProtocol());
}
public bool IsListening => _listener is not null;
public IPEndPoint? Endpoint { get; private set; }
public void Start()
{
if (_listener is not null)
{
return;
}
var listener = new TcpListener(_options.BindAddress, _options.Port);
listener.Start(_options.MaxClients);
_listener = listener;
Endpoint = (IPEndPoint?)listener.LocalEndpoint;
Log.Info($"Debug server listening on {Endpoint} (protocol {_protocolFactory().Name})");
_acceptLoop = Task.Run(() => AcceptLoopAsync(listener, _shutdown.Token));
}
private async Task AcceptLoopAsync(TcpListener listener, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
TcpClient client;
try
{
client = await listener.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
catch (SocketException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (ObjectDisposedException)
{
break;
}
var connection = new DebuggerClientConnection(client, _session, _protocolFactory());
var task = Task.Run(() => ServeAsync(connection, cancellationToken), cancellationToken);
_connections[connection] = task;
}
}
private async Task ServeAsync(DebuggerClientConnection connection, CancellationToken cancellationToken)
{
try
{
await connection.RunAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_connections.TryRemove(connection, out _);
await connection.DisposeAsync().ConfigureAwait(false);
}
}
public async Task StopAsync()
{
if (_listener is null)
{
return;
}
await _shutdown.CancelAsync().ConfigureAwait(false);
_listener.Stop();
_listener = null;
try
{
if (_acceptLoop is not null)
{
await _acceptLoop.ConfigureAwait(false);
}
await Task.WhenAll(_connections.Values).ConfigureAwait(false);
}
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
{
// Expected while tearing connections down.
}
_connections.Clear();
Log.Info("Debug server stopped.");
}
public async ValueTask DisposeAsync()
{
await StopAsync().ConfigureAwait(false);
_shutdown.Dispose();
}
}
@@ -0,0 +1,78 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net;
namespace SharpEmu.Debugger.Server;
/// <summary>Network configuration for a <see cref="DebuggerServer"/>.</summary>
public sealed class DebuggerServerOptions
{
/// <summary>The default TCP port the debug server listens on.</summary>
public const int DefaultPort = 5714;
/// <summary>
/// The address to bind. Defaults to loopback so the debug surface is not
/// exposed off-box; a caller must opt in to a routable address explicitly.
/// </summary>
public IPAddress BindAddress { get; init; } = IPAddress.Loopback;
/// <summary>The TCP port to listen on.</summary>
public int Port { get; init; } = DefaultPort;
/// <summary>
/// The maximum number of simultaneous client connections. Additional
/// connections wait in the accept backlog.
/// </summary>
public int MaxClients { get; init; } = 4;
/// <summary>
/// Parses a <c>host:port</c>, bare <c>port</c>, or bare host into options.
/// Returns false when the text cannot be interpreted.
/// </summary>
public static bool TryParseEndpoint(string? text, out DebuggerServerOptions options, out string error)
{
options = new DebuggerServerOptions();
error = string.Empty;
if (string.IsNullOrWhiteSpace(text))
{
return true;
}
var value = text.Trim();
var host = value;
var port = DefaultPort;
var separator = value.LastIndexOf(':');
if (separator >= 0)
{
var portText = value[(separator + 1)..];
if (portText.Length > 0)
{
if (!int.TryParse(portText, out port) || port is <= 0 or > 65535)
{
error = $"Invalid port '{portText}'.";
return false;
}
}
host = value[..separator];
}
var address = IPAddress.Loopback;
if (!string.IsNullOrWhiteSpace(host) &&
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
!IPAddress.TryParse(host, out address!))
{
error = $"Invalid bind address '{host}'.";
return false;
}
options = new DebuggerServerOptions
{
BindAddress = address ?? IPAddress.Loopback,
Port = port,
};
return true;
}
}
@@ -0,0 +1,24 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Net;
namespace SharpEmu.Debugger.Server;
/// <summary>
/// A network front-end that exposes a debugger session to remote clients.
/// </summary>
public interface IDebuggerServer : IAsyncDisposable
{
/// <summary>True once the listener is accepting connections.</summary>
bool IsListening { get; }
/// <summary>The endpoint the server is bound to, or null before start.</summary>
IPEndPoint? Endpoint { get; }
/// <summary>Binds and begins accepting client connections.</summary>
void Start();
/// <summary>Stops accepting connections and closes active clients.</summary>
Task StopAsync();
}
@@ -0,0 +1,69 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Debugger.Breakpoints;
using SharpEmu.HLE;
namespace SharpEmu.Debugger.Session;
/// <summary>
/// Describes a stop delivered to debugger clients: why the target stopped,
/// where, and the register snapshot at that point.
/// </summary>
public sealed class DebugStopEvent
{
public DebugStopEvent(
DebugStopReason reason,
DebugRegisterFile registers,
CpuDebugFrameKind frameKind,
string frameLabel,
Breakpoint? breakpoint = null,
OrbisGen2Result? result = null,
string? detail = null,
string? opcodeBytes = null,
CpuStallInfo? stallInfo = null)
{
Reason = reason;
Registers = registers;
FrameKind = frameKind;
FrameLabel = frameLabel ?? string.Empty;
Breakpoint = breakpoint;
Result = result;
Detail = detail;
OpcodeBytes = opcodeBytes;
StallInfo = stallInfo;
}
public DebugStopReason Reason { get; }
/// <summary>The instruction pointer where the target stopped.</summary>
public ulong Address => Registers.Rip;
public DebugRegisterFile Registers { get; }
public CpuDebugFrameKind FrameKind { get; }
public string FrameLabel { get; }
/// <summary>The breakpoint responsible for the stop, when applicable.</summary>
public Breakpoint? Breakpoint { get; }
/// <summary>
/// The frame result for a <see cref="DebugStopReason.Fault"/> stop; null for
/// non-fault stops.
/// </summary>
public OrbisGen2Result? Result { get; }
/// <summary>A human-readable summary of a fault, when applicable.</summary>
public string? Detail { get; }
/// <summary>
/// A hex preview of the bytes at <see cref="Address"/> (the faulting
/// instruction), when the stop is a fault and the bytes were readable.
/// </summary>
public string? OpcodeBytes { get; }
/// <summary>Structured backend evidence for a stall stop.</summary>
public CpuStallInfo? StallInfo { get; }
}
@@ -0,0 +1,32 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Session;
/// <summary>Why the target stopped and handed control to the debugger.</summary>
public enum DebugStopReason
{
/// <summary>Stopped at the configured entry point before running any frame.</summary>
EntryPoint,
/// <summary>An execution breakpoint was hit.</summary>
Breakpoint,
/// <summary>A data watchpoint was hit.</summary>
Watchpoint,
/// <summary>A single-step (frame step) request completed.</summary>
Step,
/// <summary>A client-requested pause took effect.</summary>
Pause,
/// <summary>The guest raised a fault or trap.</summary>
Fault,
/// <summary>
/// The backend detected an execution stall (for example a mutex spin loop /
/// livelock) with no forward progress.
/// </summary>
Stall,
}
@@ -0,0 +1,23 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Session;
/// <summary>The execution state of a debugged target as seen by the debugger.</summary>
public enum DebuggerRunState
{
/// <summary>No guest frame has entered the debugger yet.</summary>
Detached,
/// <summary>The guest is executing and cannot be inspected safely.</summary>
Running,
/// <summary>
/// The guest is parked at a frame boundary. Registers and memory can be
/// read and written, and breakpoints can be edited.
/// </summary>
Paused,
/// <summary>The guest has finished; no further frames will run.</summary>
Terminated,
}
@@ -0,0 +1,425 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Debugger.Breakpoints;
using SharpEmu.HLE;
using SharpEmu.Logging;
namespace SharpEmu.Debugger.Session;
/// <summary>
/// The default <see cref="IDebuggerSession"/>. It plugs into the CPU dispatcher
/// as an <see cref="ICpuDebugHook"/>: when a frame boundary warrants a stop it
/// parks the emulation thread inside <see cref="ICpuDebugHook.OnFrameEnter"/>
/// while a debug client inspects and edits state, then releases it on
/// continue/step.
/// </summary>
/// <remarks>
/// Pausing works by blocking the emulation thread on <see cref="_resumeGate"/>
/// from within the hook call. Because that thread is the one that owns the guest
/// context, register and memory accessors are safe to serve from other threads
/// only while it is parked — which is exactly the <see cref="DebuggerRunState.Paused"/>
/// window the accessors gate on.
/// </remarks>
public sealed class DebuggerSession : IDebuggerSession, ICpuDebugHook
{
private static readonly SharpEmuLogger Log = SharpEmuLog.For("SharpEmu.Debugger");
private readonly object _sync = new();
private readonly ManualResetEventSlim _resumeGate = new(initialState: false);
private readonly DebuggerSessionOptions _options;
private ICpuDebugFrame? _currentFrame;
private DebuggerRunState _state = DebuggerRunState.Detached;
private DebugStopEvent? _lastStop;
private bool _seenFirstFrame;
private bool _pausePending;
private bool _stepPending;
public DebuggerSession(DebuggerSessionOptions? options = null)
{
_options = options ?? new DebuggerSessionOptions();
Breakpoints = new BreakpointStore();
}
public BreakpointStore Breakpoints { get; }
public ICpuDebugHook Hook => this;
public event EventHandler<DebugStopEvent>? Stopped;
public event EventHandler? Resumed;
public event EventHandler? Terminated;
public DebuggerRunState State
{
get
{
lock (_sync)
{
return _state;
}
}
}
public DebugStopEvent? LastStop
{
get
{
lock (_sync)
{
return _lastStop;
}
}
}
void ICpuDebugHook.OnFrameEnter(ICpuDebugFrame frame)
{
DebugStopEvent? stop;
lock (_sync)
{
_currentFrame = frame;
var firstFrame = !_seenFirstFrame;
_seenFirstFrame = true;
var reason = ResolveStopReason(frame, firstFrame, out var breakpoint);
if (reason is null)
{
_state = DebuggerRunState.Running;
return;
}
_state = DebuggerRunState.Paused;
_lastStop = new DebugStopEvent(
reason.Value,
DebugRegisterFile.Capture(frame),
frame.Kind,
frame.Label,
breakpoint);
stop = _lastStop;
_resumeGate.Reset();
}
Log.Debug($"Debugger stop: {stop!.Reason} at 0x{stop.Address:X16} ({stop.FrameLabel})");
Stopped?.Invoke(this, stop);
// Park the emulation thread until a client resumes the target. The frame
// stays live and inspectable for the whole wait.
_resumeGate.Wait();
lock (_sync)
{
if (_state != DebuggerRunState.Terminated)
{
_state = DebuggerRunState.Running;
}
}
Resumed?.Invoke(this, EventArgs.Empty);
}
void ICpuDebugHook.OnFrameExit(ICpuDebugFrame frame, OrbisGen2Result result)
{
DebugStopEvent? stop = null;
lock (_sync)
{
if (_options.BreakOnFault &&
result != OrbisGen2Result.ORBIS_GEN2_OK &&
_state != DebuggerRunState.Terminated)
{
// Parking here keeps the post-fault frame inspectable.
_currentFrame = frame;
_state = DebuggerRunState.Paused;
_lastStop = BuildFaultStop(frame, result);
stop = _lastStop;
_resumeGate.Reset();
}
}
if (stop is not null)
{
Log.Debug($"Debugger fault stop: {stop.Result} at 0x{stop.Address:X16} ({stop.FrameLabel})");
Stopped?.Invoke(this, stop);
_resumeGate.Wait();
Resumed?.Invoke(this, EventArgs.Empty);
}
lock (_sync)
{
if (ReferenceEquals(_currentFrame, frame))
{
_currentFrame = null;
}
if (_state != DebuggerRunState.Terminated)
{
_state = DebuggerRunState.Running;
}
}
}
void ICpuDebugHook.OnStall(ICpuDebugFrame frame, CpuStallInfo info)
{
if (!_options.BreakOnStall)
{
return;
}
DebugStopEvent? stop = null;
lock (_sync)
{
if (_state == DebuggerRunState.Terminated)
{
return;
}
_currentFrame = frame;
_state = DebuggerRunState.Paused;
_lastStop = new DebugStopEvent(
DebugStopReason.Stall,
DebugRegisterFile.Capture(frame),
frame.Kind,
frame.Label,
breakpoint: null,
result: null,
detail: info.Detail,
opcodeBytes: ReadOpcodePreview(frame, info.InstructionPointer, 16),
stallInfo: info);
stop = _lastStop;
_resumeGate.Reset();
}
Log.Debug($"Debugger stall stop: {info.Kind} nid={info.Nid} at 0x{info.InstructionPointer:X16}");
Stopped?.Invoke(this, stop);
_resumeGate.Wait();
lock (_sync)
{
if (ReferenceEquals(_currentFrame, frame))
{
_currentFrame = null;
}
if (_state != DebuggerRunState.Terminated)
{
_state = DebuggerRunState.Running;
}
}
Resumed?.Invoke(this, EventArgs.Empty);
}
private static DebugStopEvent BuildFaultStop(ICpuDebugFrame frame, OrbisGen2Result result)
{
var opcodeBytes = ReadOpcodePreview(frame, frame.Rip, 16);
var detail = $"result={result}";
if (opcodeBytes is not null)
{
detail += $", bytes={opcodeBytes}";
}
return new DebugStopEvent(
DebugStopReason.Fault,
DebugRegisterFile.Capture(frame),
frame.Kind,
frame.Label,
breakpoint: null,
result: result,
detail: detail,
opcodeBytes: opcodeBytes);
}
private static string? ReadOpcodePreview(ICpuDebugFrame frame, ulong address, int maxBytes)
{
Span<byte> buffer = stackalloc byte[maxBytes];
var count = 0;
for (; count < maxBytes; count++)
{
if (!frame.Memory.TryRead(address + (ulong)count, buffer.Slice(count, 1)))
{
break;
}
}
return count == 0 ? null : Convert.ToHexString(buffer[..count]);
}
/// <summary>
/// Signals that the whole guest run has finished. Releases any parked
/// emulation thread and moves the session to
/// <see cref="DebuggerRunState.Terminated"/>.
/// </summary>
public void NotifyTerminated()
{
lock (_sync)
{
_state = DebuggerRunState.Terminated;
_currentFrame = null;
}
_resumeGate.Set();
Terminated?.Invoke(this, EventArgs.Empty);
}
private DebugStopReason? ResolveStopReason(ICpuDebugFrame frame, bool firstFrame, out Breakpoint? breakpoint)
{
breakpoint = null;
if (_pausePending)
{
_pausePending = false;
return DebugStopReason.Pause;
}
if (_stepPending)
{
_stepPending = false;
return DebugStopReason.Step;
}
var hit = Breakpoints.FindExecuteHit(frame.EntryPoint);
if (hit is not null)
{
breakpoint = hit;
return DebugStopReason.Breakpoint;
}
if (_options.StopAtEntry && firstFrame)
{
return DebugStopReason.EntryPoint;
}
return null;
}
public bool TryGetRegisters(out DebugRegisterFile registers)
{
lock (_sync)
{
if (!IsPausedWithFrame(out var frame))
{
registers = default;
return false;
}
registers = DebugRegisterFile.Capture(frame);
return true;
}
}
public bool TrySetRegister(DebugRegisterId id, ulong value)
{
lock (_sync)
{
if (!IsPausedWithFrame(out var frame))
{
return false;
}
if (id.IsGeneralPurpose())
{
frame.SetRegister(id.ToCpuRegister(), value);
return true;
}
switch (id)
{
case DebugRegisterId.Rip:
frame.Rip = value;
return true;
case DebugRegisterId.Rflags:
frame.Rflags = value;
return true;
default:
// FS/GS bases are owned by the TLS setup and are read-only here.
return false;
}
}
}
public bool TryReadMemory(ulong address, Span<byte> destination)
{
lock (_sync)
{
return IsPausedWithFrame(out var frame) && frame.Memory.TryRead(address, destination);
}
}
public bool TryWriteMemory(ulong address, ReadOnlySpan<byte> source)
{
lock (_sync)
{
return IsPausedWithFrame(out var frame) && frame.Memory.TryWrite(address, source);
}
}
public bool TryReadXmm(int registerIndex, out ulong low, out ulong high)
{
lock (_sync)
{
if (!IsPausedWithFrame(out var frame) || (uint)registerIndex >= 16)
{
low = 0;
high = 0;
return false;
}
frame.GetXmm(registerIndex, out low, out high);
return true;
}
}
public bool Continue()
{
lock (_sync)
{
if (_state != DebuggerRunState.Paused)
{
return false;
}
_resumeGate.Set();
return true;
}
}
public bool StepFrame()
{
lock (_sync)
{
if (_state != DebuggerRunState.Paused)
{
return false;
}
_stepPending = true;
_resumeGate.Set();
return true;
}
}
public void RequestPause()
{
lock (_sync)
{
if (_state == DebuggerRunState.Running)
{
_pausePending = true;
}
}
}
private bool IsPausedWithFrame(out ICpuDebugFrame frame)
{
// Callers must hold _sync.
if (_state == DebuggerRunState.Paused && _currentFrame is not null)
{
frame = _currentFrame;
return true;
}
frame = null!;
return false;
}
}
@@ -0,0 +1,31 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Session;
/// <summary>Configuration for a <see cref="DebuggerSession"/>.</summary>
public sealed class DebuggerSessionOptions
{
/// <summary>
/// When true, the session pauses at the first frame it observes so a client
/// can attach breakpoints before the guest runs. Defaults to true, matching
/// the "stop at entry" behaviour most debuggers expose.
/// </summary>
public bool StopAtEntry { get; init; } = true;
/// <summary>
/// When true, the session pauses when a frame ends with a non-OK result (a
/// CPU trap, memory fault, or unimplemented path) so a client can inspect the
/// post-fault register/memory state before the frame is torn down. Defaults
/// to true. The stop reports <see cref="DebugStopReason.Fault"/>.
/// </summary>
public bool BreakOnFault { get; init; } = true;
/// <summary>
/// When true, the session pauses when the backend detects an execution stall
/// (a mutex spin loop / livelock) before the guest is forced out of the loop,
/// so a client can inspect the stalled state. Defaults to true. The stop
/// reports <see cref="DebugStopReason.Stall"/>.
/// </summary>
public bool BreakOnStall { get; init; } = true;
}
@@ -0,0 +1,51 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
namespace SharpEmu.Debugger.Session;
/// <summary>
/// The inspection and control surface a debugger front-end (for example a
/// network server) drives. Register and memory accessors succeed only while the
/// target is <see cref="DebuggerRunState.Paused"/>; they return <c>false</c>
/// otherwise so callers never read torn state from a running guest.
/// </summary>
public interface IDebugTarget
{
/// <summary>The current execution state.</summary>
DebuggerRunState State { get; }
/// <summary>The most recent stop, or null if the target has not stopped yet.</summary>
DebugStopEvent? LastStop { get; }
/// <summary>Reads the integer register file. Fails unless paused.</summary>
bool TryGetRegisters(out DebugRegisterFile registers);
/// <summary>Writes a single register. Fails unless paused.</summary>
bool TrySetRegister(DebugRegisterId id, ulong value);
/// <summary>Reads guest memory into <paramref name="destination"/>. Fails unless paused.</summary>
bool TryReadMemory(ulong address, Span<byte> destination);
/// <summary>Writes guest memory from <paramref name="source"/>. Fails unless paused.</summary>
bool TryWriteMemory(ulong address, ReadOnlySpan<byte> source);
/// <summary>Reads a 128-bit XMM register. Fails unless paused.</summary>
bool TryReadXmm(int registerIndex, out ulong low, out ulong high);
/// <summary>
/// Resumes a paused target. Returns false when the target was not paused.
/// </summary>
bool Continue();
/// <summary>
/// Resumes a paused target and stops again at the next frame boundary.
/// Returns false when the target was not paused.
/// </summary>
bool StepFrame();
/// <summary>
/// Requests that a running target stop at the next frame boundary. Has no
/// effect if the target is already paused or terminated.
/// </summary>
void RequestPause();
}
@@ -0,0 +1,43 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Cpu.Debugging;
using SharpEmu.Debugger.Breakpoints;
namespace SharpEmu.Debugger.Session;
/// <summary>
/// The debugger's coordination point. It bridges the CPU dispatcher seam
/// (<see cref="Hook"/>) to the inspection surface (<see cref="IDebugTarget"/>),
/// owns breakpoint state, and raises lifecycle events that a server relays to
/// connected clients.
/// </summary>
public interface IDebuggerSession : IDebugTarget
{
/// <summary>The breakpoints armed for this session.</summary>
BreakpointStore Breakpoints { get; }
/// <summary>
/// The dispatcher-facing hook. Assign this to
/// <c>SharpEmuRuntimeOptions.DebugHook</c> so guest frames are routed through
/// the session.
/// </summary>
ICpuDebugHook Hook { get; }
/// <summary>Raised on the emulation thread each time the target stops.</summary>
event EventHandler<DebugStopEvent>? Stopped;
/// <summary>Raised when a paused target resumes.</summary>
event EventHandler? Resumed;
/// <summary>Raised once the target has terminated.</summary>
event EventHandler? Terminated;
/// <summary>
/// Signals that the guest run has finished. Releases any parked emulation
/// thread and transitions the session to
/// <see cref="DebuggerRunState.Terminated"/>. Hosts call this after the
/// runtime returns.
/// </summary>
void NotifyTerminated();
}
@@ -0,0 +1,16 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\SharpEmu.Core\SharpEmu.Core.csproj" />
<ProjectReference Include="..\SharpEmu.HLE\SharpEmu.HLE.csproj" />
<ProjectReference Include="..\SharpEmu.Logging\SharpEmu.Logging.csproj" />
</ItemGroup>
<PropertyGroup>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
</Project>
@@ -676,10 +676,15 @@ public static class KernelPthreadCompatExports
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
}
// FreeBSD maps NORMAL to checked non-recursive behavior:
// self-lock is an error, never implicit recursion.
TracePthreadMutex(ctx, "lock", mutexAddress, resolvedAddress, state, currentThreadId, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_DEADLOCK);
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_DEADLOCK;
// Several Gen5 runtimes layer their own owner/count bookkeeping
// over a NORMAL or ADAPTIVE kernel mutex. Returning EDEADLK here
// leaves that guest bookkeeping out of sync with the HLE owner and
// turns the wrapper into a permanent lock/unlock retry loop. Keep
// the compatibility recursion used by the original implementation;
// ERRORCHECK mutexes still take the strict EDEADLK path below.
state.RecursionCount++;
TracePthreadMutex(ctx, "lock", mutexAddress, resolvedAddress, state, currentThreadId, (int)OrbisGen2Result.ORBIS_GEN2_OK);
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
else
{
@@ -0,0 +1,99 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
using SharpEmu.Libs.Kernel;
using Xunit;
namespace SharpEmu.Libs.Tests.Pthread;
public sealed class PthreadMutexSemanticsTests
{
[Fact]
public void AdaptiveMutex_SelfLockUsesCompatibilityRecursion()
{
const ulong memoryBase = 0x1_0000_0000;
const ulong mutexAddress = memoryBase + 0x100;
var memory = new AllocatingCpuMemory(memoryBase, 0x4000);
var context = new CpuContext(memory, Generation.Gen5);
Assert.True(context.TryWriteUInt64(mutexAddress, 1)); // Static adaptive initializer.
context[CpuRegister.Rdi] = mutexAddress;
Assert.Equal(0, KernelPthreadCompatExports.PthreadMutexLock(context));
Assert.Equal(0, KernelPthreadCompatExports.PthreadMutexLock(context));
Assert.Equal(0, KernelPthreadCompatExports.PthreadMutexUnlock(context));
Assert.Equal(0, KernelPthreadCompatExports.PthreadMutexUnlock(context));
}
private sealed class AllocatingCpuMemory : ICpuMemory, IGuestMemoryAllocator
{
private readonly ulong _baseAddress;
private readonly byte[] _storage;
private ulong _nextAllocation;
public AllocatingCpuMemory(ulong baseAddress, int size)
{
_baseAddress = baseAddress;
_storage = new byte[size];
_nextAllocation = baseAddress + 0x1000;
}
public bool TryRead(ulong virtualAddress, Span<byte> destination)
{
if (!TryResolve(virtualAddress, destination.Length, out var offset))
{
return false;
}
_storage.AsSpan(offset, destination.Length).CopyTo(destination);
return true;
}
public bool TryWrite(ulong virtualAddress, ReadOnlySpan<byte> source)
{
if (!TryResolve(virtualAddress, source.Length, out var offset))
{
return false;
}
source.CopyTo(_storage.AsSpan(offset, source.Length));
return true;
}
public bool TryAllocateGuestMemory(ulong size, ulong alignment, out ulong address)
{
var mask = alignment - 1;
var aligned = (_nextAllocation + mask) & ~mask;
if (!TryResolve(aligned, checked((int)size), out _))
{
address = 0;
return false;
}
address = aligned;
_nextAllocation = aligned + size;
return true;
}
public bool TryFreeGuestMemory(ulong address) =>
address >= _baseAddress && address < _baseAddress + (ulong)_storage.Length;
private bool TryResolve(ulong virtualAddress, int length, out int offset)
{
offset = 0;
if (virtualAddress < _baseAddress)
{
return false;
}
var relative = virtualAddress - _baseAddress;
if (relative + (ulong)length > (ulong)_storage.Length)
{
return false;
}
offset = (int)relative;
return true;
}
}
}
+89
View File
@@ -0,0 +1,89 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
# SharpEmu Debugger Frontend
A polished browser UI for SharpEmu's live debugger. A small Python bridge talks
to the emulator over its JSON-lines TCP protocol and serves the frontend on
loopback. It uses only the Python standard library; no package installation or
JavaScript build step is required.
The favicon and header mark use the official SharpEmu logo served by
`sharpemu.app`.
## Start
Start the frontend from the repository root:
```bash
./tools/SharpEmu.DebuggerFrontend/run.sh
```
Use **Browse…** to choose the game's `eboot.bin`, then select **Launch &
attach**. The frontend starts the local Release build with its debug server,
waits for it to become ready, and connects automatically. Emulator output is
shown in the Activity panel. The Stop button only controls the process launched
by this frontend.
You can still start SharpEmu manually and use the connection bar to attach:
```bash
./artifacts/bin/Release/net10.0/linux-x64/SharpEmu \
--debug-server=127.0.0.1:5714 "/path/to/game/eboot.bin"
```
The frontend opens `http://127.0.0.1:8765/`. If SharpEmu is already running, it
connects to the default debug endpoint automatically. If it is not running yet,
the UI remains available for launching or attaching later.
Running the launcher again on the same UI port gracefully closes and replaces
the previous verified SharpEmu frontend instance. It will not stop an unrelated
application that happens to own the requested port; in that case, select a
different port with `--ui-port`.
Useful options:
```text
--debug-host HOST Debug server host (default 127.0.0.1)
--debug-port PORT Debug server port (default 5714)
--listen ADDRESS Web UI bind address (default 127.0.0.1)
--ui-port PORT Web UI port; 0 chooses a free port (default 8765)
--no-connect Do not connect to SharpEmu automatically
--no-browser Do not open a browser automatically
--verbose Print HTTP request logs
```
## Features
- Live connection and target-state display
- Native file picker, local emulator launch, automatic debugger attach, and process stop
- Live output from the frontend-launched SharpEmu process
- Continue, pause, and frame-step controls with keyboard shortcuts
- Register inspection and editing
- Hex/ASCII memory reads and validated memory writes
- Breakpoint and watchpoint creation, toggling, and deletion
- Stop reason, frame, result, opcode, and fault details
- Evidence-based stall diagnosis with likely causes, ranked fixes, and targeted checks
- Raw JSON command console for new protocol operations
- Searchable activity stream containing requests, replies, and async events
The debugger currently stops and steps at guest frame boundaries. Data
watchpoints and per-instruction stepping are exposed in the protocol but depend
on future CPU backend hooks, as documented in `docs/debugger-server.md`.
## Test
```bash
python3 -m unittest discover -s tools/SharpEmu.DebuggerFrontend/tests -v
node --check tools/SharpEmu.DebuggerFrontend/web/app.js
```
The HTTP service binds to loopback by default and has no authentication. Only
use a non-loopback `--listen` address on a trusted network.
On Linux, the Browse button uses `zenity` or `kdialog`. A full path can always
be entered manually. Closing the frontend also stops the emulator process it
launched so its captured output pipe cannot be orphaned; manually launched
emulators are never stopped by the frontend.
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env sh
# Copyright (C) 2026 SharpEmu Emulator Project
# SPDX-License-Identifier: GPL-2.0-or-later
set -eu
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
exec python3 "$script_dir/debugger_frontend.py" "$@"
@@ -0,0 +1,309 @@
# Copyright (C) 2026 SharpEmu Emulator Project
# SPDX-License-Identifier: GPL-2.0-or-later
from __future__ import annotations
import json
from pathlib import Path
import socket
import sys
import tempfile
import textwrap
import threading
import unittest
from urllib.request import Request, urlopen
FRONTEND_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(FRONTEND_ROOT))
from debugger_frontend import ( # noqa: E402
BridgeError,
DebuggerBridge,
EmulatorProcessManager,
FrontendHttpServer,
FrontendRequestHandler,
analyze_debug_stop,
create_frontend_server,
)
REGISTERS = {
"rax": "0x0000000000000001",
"rip": "0x00000008801234A0",
"rflags": "0x0000000000000202",
}
class FakeDebuggerServer:
def __init__(self) -> None:
self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listener.bind(("127.0.0.1", 0))
self.listener.listen(1)
self.port = self.listener.getsockname()[1]
self.client: socket.socket | None = None
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
def _run(self) -> None:
try:
client, _ = self.listener.accept()
self.client = client
reader = client.makefile("r", encoding="utf-8", newline="\n")
writer = client.makefile("w", encoding="utf-8", newline="\n")
self._write(writer, {"event": "hello", "protocol": "json-lines/1", "state": "Paused"})
for line in reader:
request = json.loads(line)
command = request["command"]
if command == "status":
self._write(writer, {
"ok": True,
"command": command,
"data": {"state": "Paused", "breakpoints": 1},
})
elif command == "registers":
self._write(writer, {
"event": "stopped",
"reason": "Breakpoint",
"address": REGISTERS["rip"],
"frameKind": "ProcessEntry",
"frameLabel": "eboot.bin",
"registers": REGISTERS,
})
self._write(writer, {
"ok": True,
"command": command,
"data": {"registers": REGISTERS},
})
elif command == "list-breakpoints":
self._write(writer, {
"ok": True,
"command": command,
"data": {
"breakpoints": [{
"id": 1,
"kind": "Execute",
"address": REGISTERS["rip"],
"length": 1,
"enabled": True,
}],
},
})
else:
self._write(writer, {"ok": True, "command": command})
except OSError:
pass
@staticmethod
def _write(writer: object, payload: dict[str, object]) -> None:
writer.write(json.dumps(payload, separators=(",", ":")) + "\n")
writer.flush()
def close(self) -> None:
if self.client is not None:
try:
self.client.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.client.close()
self.listener.close()
self.thread.join(timeout=1)
class DebuggerBridgeTests(unittest.TestCase):
def setUp(self) -> None:
self.server = FakeDebuggerServer()
self.bridge = DebuggerBridge()
self.bridge.connect("127.0.0.1", self.server.port)
def tearDown(self) -> None:
self.bridge.disconnect(log=False)
self.server.close()
def test_connect_receives_hello(self) -> None:
snapshot = self.bridge.snapshot()
self.assertTrue(snapshot["connected"])
self.assertEqual("json-lines/1", snapshot["protocol"])
self.assertEqual("Paused", snapshot["state"])
def test_request_pairs_reply_while_processing_event(self) -> None:
reply = self.bridge.request({"command": "registers"})
self.assertTrue(reply["ok"])
snapshot = self.bridge.snapshot()
self.assertEqual(REGISTERS["rip"], snapshot["registers"]["rip"])
self.assertEqual("Breakpoint", snapshot["lastStop"]["reason"])
self.assertTrue(any(item["summary"] == "stopped" for item in snapshot["messages"]))
def test_breakpoint_snapshot_is_updated(self) -> None:
self.bridge.request({"command": "list-breakpoints"})
snapshot = self.bridge.snapshot()
self.assertEqual(1, len(snapshot["breakpoints"]))
self.assertEqual("Execute", snapshot["breakpoints"][0]["kind"])
def test_invalid_request_is_rejected_locally(self) -> None:
with self.assertRaises(BridgeError):
self.bridge.request({})
def test_journal_cursor_returns_only_new_messages(self) -> None:
cursor = self.bridge.snapshot()["cursor"]
self.bridge.request({"command": "status"})
snapshot = self.bridge.snapshot(cursor)
self.assertGreaterEqual(len(snapshot["messages"]), 2)
self.assertTrue(all(message["id"] > cursor for message in snapshot["messages"]))
class StallAnalysisTests(unittest.TestCase):
def test_legacy_mutex_stall_identifies_likely_scheduler_fix(self) -> None:
analysis = analyze_debug_stop({
"reason": "Stall",
"detail": "kind=ImportLoop, nid=9UK1vLZQft4, dispatch#40667904, rip=0x0000000801CE2418",
})
self.assertIsNotNone(analysis)
self.assertEqual("Mutex lock is livelocking", analysis["title"])
self.assertEqual("High", analysis["confidence"])
self.assertIn("PthreadMutexLockCore", analysis["fix"])
self.assertTrue(any("9UK1vLZQft4" in item for item in analysis["evidence"]))
def test_unresolved_import_stall_recommends_export_implementation(self) -> None:
analysis = analyze_debug_stop({
"reason": "Stall",
"stall": {
"kind": "ImportLoop",
"nid": "missing-nid",
"resolved": False,
"dispatchIndex": 8192,
"instructionPointer": "0x0000000000001234",
},
})
self.assertIsNotNone(analysis)
self.assertEqual("Unresolved import is being retried", analysis["title"])
self.assertIn("Implement or correctly register", analysis["fix"])
class FrontendHttpTests(unittest.TestCase):
def setUp(self) -> None:
self.debugger = FakeDebuggerServer()
self.bridge = DebuggerBridge()
self.process_manager = EmulatorProcessManager(self.bridge.journal)
handler = type(
"TestFrontendRequestHandler",
(FrontendRequestHandler,),
{"bridge": self.bridge, "process_manager": self.process_manager},
)
self.http_server = FrontendHttpServer(("127.0.0.1", 0), handler)
self.http_port = self.http_server.server_address[1]
self.http_thread = threading.Thread(target=self.http_server.serve_forever, daemon=True)
self.http_thread.start()
def tearDown(self) -> None:
self.bridge.disconnect(log=False)
self.process_manager.stop(log=False)
self.http_server.shutdown()
self.http_server.server_close()
self.http_thread.join(timeout=1)
self.debugger.close()
def post(self, path: str, payload: dict[str, object]) -> dict[str, object]:
request = Request(
f"http://127.0.0.1:{self.http_port}{path}",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urlopen(request, timeout=2) as response:
return json.load(response)
def test_api_connect_and_command_round_trip(self) -> None:
connected = self.post("/api/connect", {"host": "127.0.0.1", "port": self.debugger.port})
self.assertTrue(connected["connected"])
self.assertEqual("json-lines/1", connected["protocol"])
result = self.post("/api/command", {"request": {"command": "registers"}})
self.assertTrue(result["response"]["ok"])
def test_static_frontend_is_served(self) -> None:
with urlopen(f"http://127.0.0.1:{self.http_port}/", timeout=2) as response:
body = response.read().decode("utf-8")
self.assertEqual("text/html; charset=utf-8", response.headers["Content-Type"])
self.assertIn("SharpEmu <span>Debugger</span>", body)
self.assertIn('rel="icon" type="image/webp"', body)
with urlopen(f"http://127.0.0.1:{self.http_port}/sharpemu-logo.webp", timeout=2) as response:
logo = response.read()
self.assertEqual("image/webp", response.headers["Content-Type"])
self.assertTrue(logo.startswith(b"RIFF"))
def test_api_launches_and_stops_emulator_with_auto_attach(self) -> None:
with tempfile.TemporaryDirectory() as temporary_directory:
root = Path(temporary_directory)
eboot = root / "eboot.bin"
eboot.write_bytes(b"test")
emulator = root / "fake-sharpemu"
emulator.write_text(textwrap.dedent("""\
#!/usr/bin/env python3
import json
import socket
import sys
endpoint = next(arg.split("=", 1)[1] for arg in sys.argv if arg.startswith("--debug-server="))
port = int(endpoint.rsplit(":", 1)[1])
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", port))
listener.listen(4)
print("Fake SharpEmu debug server ready", flush=True)
while True:
client, _ = listener.accept()
with client:
reader = client.makefile("r", encoding="utf-8")
writer = client.makefile("w", encoding="utf-8")
writer.write(json.dumps({"event": "hello", "protocol": "json-lines/1", "state": "Paused"}) + "\\n")
writer.flush()
for line in reader:
request = json.loads(line)
command = request["command"]
data = {"state": "Paused", "breakpoints": 0} if command == "status" else {"breakpoints": []}
writer.write(json.dumps({"ok": True, "command": command, "data": data}) + "\\n")
writer.flush()
"""), encoding="utf-8")
emulator.chmod(0o755)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as reservation:
reservation.bind(("127.0.0.1", 0))
debug_port = reservation.getsockname()[1]
launched = self.post("/api/launch", {
"ebootPath": str(eboot),
"debugPort": debug_port,
"emulatorPath": str(emulator),
})
self.assertTrue(launched["connected"])
self.assertTrue(launched["emulator"]["running"])
self.assertEqual(str(eboot), launched["emulator"]["eboot"])
stopped = self.post("/api/stop-emulator", {})
self.assertFalse(stopped["connected"])
self.assertFalse(stopped["emulator"]["running"])
def test_rerun_replaces_existing_frontend_on_same_port(self) -> None:
replacement_handler = type(
"ReplacementFrontendRequestHandler",
(FrontendRequestHandler,),
{"bridge": self.bridge, "process_manager": self.process_manager},
)
old_thread = self.http_thread
replacement = create_frontend_server("127.0.0.1", self.http_port, replacement_handler)
old_thread.join(timeout=2)
self.assertFalse(old_thread.is_alive())
self.http_server = replacement
self.http_thread = threading.Thread(target=replacement.serve_forever, daemon=True)
self.http_thread.start()
with urlopen(f"http://127.0.0.1:{self.http_port}/api/health", timeout=2) as response:
health = json.load(response)
self.assertEqual("sharpemu-debugger-frontend", health["application"])
if __name__ == "__main__":
unittest.main()
+626
View File
@@ -0,0 +1,626 @@
/*
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
*/
"use strict";
const REGISTER_ORDER = [
"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"rip", "rflags", "fs_base", "gs_base",
];
const ui = {
cursor: 0,
snapshot: null,
activity: [],
polling: false,
refreshing: false,
};
const byId = (id) => document.getElementById(id);
async function api(path, options = {}) {
const response = await fetch(path, {
headers: { "Content-Type": "application/json" },
cache: "no-store",
...options,
});
let payload;
try {
payload = await response.json();
} catch {
throw new Error(`Frontend returned HTTP ${response.status}.`);
}
if (!response.ok) {
throw new Error(payload.error || `Request failed with HTTP ${response.status}.`);
}
return payload;
}
async function pollSnapshot() {
if (ui.polling) return;
ui.polling = true;
try {
const snapshot = await api(`/api/snapshot?since=${ui.cursor}`);
applySnapshot(snapshot);
} catch (error) {
showToast("Frontend unavailable", error.message, "error");
} finally {
ui.polling = false;
}
}
function applySnapshot(snapshot) {
const previous = ui.snapshot;
const previousCursor = ui.cursor;
const newMessages = (snapshot.messages || []).filter((message) => message.id > previousCursor);
ui.snapshot = snapshot;
ui.cursor = snapshot.cursor;
if (newMessages.length) {
ui.activity.push(...newMessages);
ui.activity = ui.activity.slice(-350);
renderActivity();
for (const message of newMessages) {
handleActivityNotification(message);
}
}
if (!previous && snapshot.defaultEndpoint) {
byId("debug-host").value = snapshot.defaultEndpoint.host;
byId("debug-port").value = snapshot.defaultEndpoint.port;
}
renderConnection(snapshot);
renderEmulator(snapshot.emulator || {});
renderTarget(snapshot);
renderRegisters(snapshot.registers || {});
renderBreakpoints(snapshot.breakpoints || []);
updateControls(snapshot);
}
function renderConnection(snapshot) {
const status = byId("connection-status");
status.classList.toggle("connected", snapshot.connected);
status.classList.toggle("disconnected", !snapshot.connected);
byId("connection-state").textContent = snapshot.connected ? "Connected" : "Offline";
byId("connection-endpoint").textContent = snapshot.endpoint || "Not connected";
byId("connection-button-label").textContent = snapshot.connected ? "Disconnect" : "Connect";
byId("connection-button").classList.toggle("button-danger", snapshot.connected);
byId("connection-button").classList.toggle("button-primary", !snapshot.connected);
byId("protocol-version").textContent = snapshot.protocol || "—";
}
function renderEmulator(emulator) {
const statusWrap = byId("emulator-status").closest(".launch-status");
statusWrap.classList.toggle("running", Boolean(emulator.running));
statusWrap.classList.toggle("exited", !emulator.running && emulator.exitCode !== null && emulator.exitCode !== undefined);
if (emulator.running) {
byId("emulator-status").textContent = `SharpEmu running · PID ${emulator.pid}`;
byId("emulator-detail").textContent = emulator.eboot || "Launching game executable";
} else if (emulator.exitCode !== null && emulator.exitCode !== undefined) {
byId("emulator-status").textContent = `SharpEmu exited · code ${emulator.exitCode}`;
byId("emulator-detail").textContent = emulator.eboot || "The launched process has ended.";
} else {
byId("emulator-status").textContent = "No frontend-launched session";
byId("emulator-detail").textContent = "You can still attach to an emulator that is already running.";
}
if (emulator.eboot && document.activeElement !== byId("eboot-path")) {
byId("eboot-path").value = emulator.eboot;
}
byId("eboot-path").disabled = Boolean(emulator.running);
byId("browse-eboot-button").disabled = Boolean(emulator.running);
byId("launch-button").disabled = Boolean(emulator.running);
byId("stop-emulator-button").disabled = !emulator.running;
}
function renderTarget(snapshot) {
const state = snapshot.state || "Disconnected";
const stop = snapshot.lastStop || {};
const registers = snapshot.registers || {};
byId("toolbar-target-state").textContent = state;
const badge = byId("target-state-badge");
badge.textContent = state;
badge.className = `state-badge ${state.toLowerCase()}`;
byId("target-address").textContent = stop.address || registers.rip || "—";
byId("stop-reason").textContent = stop.reason || "—";
byId("frame-kind").textContent = stop.frameKind || "—";
byId("frame-label").textContent = stop.frameLabel || "—";
byId("stop-result").textContent = stop.result || "—";
byId("opcode-bytes").textContent = stop.opcodeBytes || "—";
const detailWrap = byId("stop-detail-wrap");
detailWrap.classList.toggle("hidden", !stop.detail);
byId("stop-detail").textContent = stop.detail || "";
renderStallAnalysis(stop.analysis);
}
function renderStallAnalysis(analysis) {
const panel = byId("stall-analysis");
if (!analysis) {
panel.classList.add("hidden");
return;
}
panel.classList.remove("hidden");
byId("stall-analysis-title").textContent = analysis.title || "Execution stall detected";
byId("stall-confidence").textContent = `${analysis.confidence || "Medium"} confidence`;
byId("stall-summary").textContent = analysis.summary || "The guest is not making forward progress.";
byId("stall-cause").textContent = analysis.cause || "The repeated path is not changing the state checked by the guest.";
byId("stall-fix").textContent = analysis.fix || "Trace the repeated import and implement its missing state transition.";
const actions = (analysis.actions || []).map((text) => createTextElement("li", text));
byId("stall-actions").replaceChildren(...actions);
const evidence = (analysis.evidence || []).map((text) => createTextElement("li", text));
byId("stall-evidence").replaceChildren(...evidence);
}
function renderRegisters(registers) {
const grid = byId("register-grid");
if (!Object.keys(registers).length) {
grid.className = "register-grid empty-state";
grid.replaceChildren(createTextElement("p", "Pause the target to inspect registers."));
return;
}
grid.className = "register-grid";
const fragment = document.createDocumentFragment();
for (const name of REGISTER_ORDER) {
const value = registers[name] ?? "—";
const item = document.createElement("div");
item.className = `register-item ${["rip", "rflags", "fs_base", "gs_base"].includes(name) ? "special" : ""}`;
const label = createTextElement("span", name);
label.className = "register-name";
const button = createTextElement("button", value);
button.type = "button";
button.className = "register-value";
button.dataset.register = name;
button.title = `Edit ${name}`;
button.addEventListener("click", () => openRegisterDialog(name, value));
item.append(label, button);
fragment.append(item);
}
grid.replaceChildren(fragment);
}
function renderBreakpoints(breakpoints) {
byId("breakpoint-count").textContent = breakpoints.length;
const body = byId("breakpoint-table");
if (!breakpoints.length) {
const row = document.createElement("tr");
row.className = "empty-row";
const cell = createTextElement("td", "No breakpoints configured.");
cell.colSpan = 6;
row.append(cell);
body.replaceChildren(row);
return;
}
const fragment = document.createDocumentFragment();
for (const breakpoint of breakpoints) {
const row = document.createElement("tr");
const enabledCell = document.createElement("td");
const toggle = document.createElement("input");
toggle.type = "checkbox";
toggle.className = "switch";
toggle.checked = Boolean(breakpoint.enabled);
toggle.title = toggle.checked ? "Disable breakpoint" : "Enable breakpoint";
toggle.addEventListener("change", async () => {
toggle.disabled = true;
try {
await sendCommand({ command: "enable-breakpoint", id: breakpoint.id, enabled: toggle.checked });
await refreshBreakpoints();
} catch (error) {
toggle.checked = !toggle.checked;
showToast("Breakpoint update failed", error.message, "error");
} finally {
toggle.disabled = false;
}
});
enabledCell.append(toggle);
const idCell = createTextElement("td", String(breakpoint.id));
const kindCell = document.createElement("td");
const kind = createTextElement("span", breakpoint.kind);
kind.className = "kind-pill";
kindCell.append(kind);
const addressCell = createTextElement("td", breakpoint.address);
const lengthCell = createTextElement("td", String(breakpoint.length));
const actionCell = document.createElement("td");
const remove = createTextElement("button", "Remove");
remove.type = "button";
remove.className = "row-action";
remove.addEventListener("click", async () => {
remove.disabled = true;
try {
await sendCommand({ command: "remove-breakpoint", id: breakpoint.id });
await refreshBreakpoints();
showToast("Breakpoint removed", `Breakpoint ${breakpoint.id} was removed.`, "success");
} catch (error) {
showToast("Remove failed", error.message, "error");
} finally {
remove.disabled = false;
}
});
actionCell.append(remove);
row.append(enabledCell, idCell, kindCell, addressCell, lengthCell, actionCell);
fragment.append(row);
}
body.replaceChildren(fragment);
}
function updateControls(snapshot) {
const connected = Boolean(snapshot.connected);
const state = String(snapshot.state || "").toLowerCase();
const paused = connected && state === "paused";
const running = connected && state === "running";
byId("continue-button").disabled = !paused;
byId("step-button").disabled = !paused;
byId("pause-button").disabled = !running;
byId("refresh-button").disabled = !connected;
for (const id of [
"breakpoint-address", "breakpoint-kind", "breakpoint-length",
"memory-address", "memory-length", "memory-write-address", "memory-write-bytes",
"raw-command-input",
]) {
byId(id).disabled = !connected || (["memory-address", "memory-length", "memory-write-address", "memory-write-bytes"].includes(id) && !paused);
}
byId("breakpoint-form").querySelector("button").disabled = !connected;
byId("memory-read-form").querySelector("button").disabled = !paused;
byId("memory-write-form").querySelector("button").disabled = !paused;
byId("raw-command-form").querySelector("button").disabled = !connected;
}
async function sendCommand(request) {
const payload = await api("/api/command", {
method: "POST",
body: JSON.stringify({ request }),
});
const response = payload.response;
if (!response?.ok) {
throw new Error(response?.error || `${request.command} failed.`);
}
await pollSnapshot();
return response;
}
async function refreshTarget() {
if (!ui.snapshot?.connected || ui.refreshing) return;
ui.refreshing = true;
byId("refresh-button").disabled = true;
try {
const status = await sendCommand({ command: "status" });
if (String(status.data?.state).toLowerCase() === "paused") {
await sendCommand({ command: "registers" });
}
await sendCommand({ command: "list-breakpoints" });
} catch (error) {
showToast("Refresh failed", error.message, "error");
} finally {
ui.refreshing = false;
await pollSnapshot();
}
}
async function refreshBreakpoints() {
await sendCommand({ command: "list-breakpoints" });
}
async function connectOrDisconnect(event) {
event.preventDefault();
const button = byId("connection-button");
button.disabled = true;
try {
if (ui.snapshot?.connected) {
const snapshot = await api("/api/disconnect", { method: "POST", body: "{}" });
applySnapshot(snapshot);
showToast("Disconnected", "The debugger connection was closed.");
return;
}
const host = byId("debug-host").value.trim();
const port = Number.parseInt(byId("debug-port").value, 10);
const snapshot = await api("/api/connect", {
method: "POST",
body: JSON.stringify({ host, port }),
});
applySnapshot(snapshot);
showToast("Debugger connected", `Attached to ${host}:${port}.`, "success");
await refreshTarget();
} catch (error) {
showToast("Connection failed", error.message, "error");
await pollSnapshot();
} finally {
button.disabled = false;
}
}
async function browseForEboot() {
const button = byId("browse-eboot-button");
button.disabled = true;
const previousLabel = button.textContent;
button.textContent = "Choosing…";
try {
const result = await api("/api/select-eboot", {
method: "POST",
body: JSON.stringify({ initialPath: byId("eboot-path").value.trim() || null }),
});
if (result.path) {
byId("eboot-path").value = result.path;
byId("eboot-path").focus();
byId("eboot-path").setSelectionRange(result.path.length, result.path.length);
}
} catch (error) {
showToast("File picker unavailable", error.message, "error");
} finally {
button.textContent = previousLabel;
button.disabled = Boolean(ui.snapshot?.emulator?.running);
}
}
async function launchEboot(event) {
event.preventDefault();
const ebootPath = byId("eboot-path").value.trim();
const debugPort = Number.parseInt(byId("debug-port").value, 10);
const button = byId("launch-button");
const previousHtml = button.innerHTML;
button.disabled = true;
button.textContent = "Starting SharpEmu…";
showToast("Launching SharpEmu", "Waiting for the local debug server to become ready.");
try {
const snapshot = await api("/api/launch", {
method: "POST",
body: JSON.stringify({ ebootPath, debugPort }),
});
byId("debug-host").value = "127.0.0.1";
applySnapshot(snapshot);
showToast("Launch complete", "SharpEmu is running and the debugger attached automatically.", "success");
await refreshTarget();
} catch (error) {
showToast("Launch failed", error.message, "error");
await pollSnapshot();
} finally {
button.innerHTML = previousHtml;
button.disabled = Boolean(ui.snapshot?.emulator?.running);
}
}
async function stopEmulator() {
if (!window.confirm("Stop the SharpEmu process launched by this frontend?")) return;
const button = byId("stop-emulator-button");
button.disabled = true;
button.textContent = "Stopping…";
try {
const snapshot = await api("/api/stop-emulator", { method: "POST", body: "{}" });
applySnapshot(snapshot);
showToast("SharpEmu stopped", "The frontend-launched emulator process was stopped.");
} catch (error) {
showToast("Stop failed", error.message, "error");
} finally {
button.textContent = "Stop";
button.disabled = !ui.snapshot?.emulator?.running;
}
}
async function executionCommand(command, label) {
try {
await sendCommand({ command });
showToast(label, command === "pause" ? "Pause requested at the next frame boundary." : `${label} command accepted.`, "success");
} catch (error) {
showToast(`${label} failed`, error.message, "error");
}
}
function openRegisterDialog(name, value) {
if (String(ui.snapshot?.state).toLowerCase() !== "paused") return;
byId("register-name").value = name;
byId("register-value").value = value;
byId("register-dialog").showModal();
byId("register-value").focus();
byId("register-value").select();
}
async function applyRegister(event) {
event.preventDefault();
const name = byId("register-name").value;
const value = byId("register-value").value.trim();
try {
await sendCommand({ command: "set-register", register: name, value });
await sendCommand({ command: "registers" });
byId("register-dialog").close();
showToast("Register updated", `${name.toUpperCase()} is now ${value}.`, "success");
} catch (error) {
showToast("Register update failed", error.message, "error");
}
}
async function addBreakpoint(event) {
event.preventDefault();
const address = byId("breakpoint-address").value.trim();
const kind = byId("breakpoint-kind").value;
const length = Number.parseInt(byId("breakpoint-length").value, 10);
try {
await sendCommand({ command: "add-breakpoint", address, kind, length });
await refreshBreakpoints();
byId("breakpoint-address").value = "";
showToast("Breakpoint added", `${kind} breakpoint created at ${address}.`, "success");
} catch (error) {
showToast("Breakpoint failed", error.message, "error");
}
}
async function readMemory(event) {
event.preventDefault();
const address = byId("memory-address").value.trim();
const length = Number.parseInt(byId("memory-length").value, 10);
try {
const response = await sendCommand({ command: "read-memory", address, length });
const data = response.data || {};
byId("memory-view").textContent = formatHexDump(data.address || address, data.bytes || "");
byId("memory-meta").textContent = `${data.length || 0} bytes from ${data.address || address}`;
if (!byId("memory-write-address").value) byId("memory-write-address").value = data.address || address;
} catch (error) {
showToast("Memory read failed", error.message, "error");
}
}
async function writeMemory(event) {
event.preventDefault();
const address = byId("memory-write-address").value.trim();
const bytes = byId("memory-write-bytes").value.replace(/\s+/g, "");
if (!bytes || bytes.length % 2 || !/^[0-9a-f]+$/i.test(bytes)) {
showToast("Invalid bytes", "Enter an even number of hexadecimal digits.", "error");
return;
}
try {
const response = await sendCommand({ command: "write-memory", address, bytes });
showToast("Memory written", `${response.data?.written || bytes.length / 2} bytes written at ${address}.`, "success");
if (byId("memory-address").value.trim() === address) {
byId("memory-read-form").requestSubmit();
}
} catch (error) {
showToast("Memory write failed", error.message, "error");
}
}
function formatHexDump(startAddress, hex) {
const clean = String(hex).replace(/\s+/g, "");
if (!clean) return "No bytes returned.";
const bytes = clean.match(/.{1,2}/g) || [];
let base = 0n;
try { base = BigInt(startAddress); } catch { /* display from zero */ }
const lines = [];
for (let offset = 0; offset < bytes.length; offset += 16) {
const chunk = bytes.slice(offset, offset + 16);
const address = `0x${(base + BigInt(offset)).toString(16).toUpperCase().padStart(16, "0")}`;
const left = chunk.slice(0, 8).join(" ").padEnd(23, " ");
const right = chunk.slice(8).join(" ").padEnd(23, " ");
const ascii = chunk.map((value) => {
const code = Number.parseInt(value, 16);
return code >= 32 && code <= 126 ? String.fromCharCode(code) : ".";
}).join("");
lines.push(`${address} ${left} ${right} |${ascii.padEnd(16, " ")}|`);
}
return lines.join("\n");
}
async function sendRawCommand(event) {
event.preventDefault();
try {
const request = JSON.parse(byId("raw-command-input").value);
if (!request || Array.isArray(request) || typeof request !== "object") throw new Error("Request must be a JSON object.");
await sendCommand(request);
showToast("Raw request sent", request.command || "Request completed.", "success");
} catch (error) {
showToast("Raw request failed", error.message, "error");
}
}
function renderActivity() {
const stream = byId("activity-stream");
const query = byId("activity-search").value.trim().toLowerCase();
const messages = query
? ui.activity.filter((item) => `${item.kind} ${item.summary} ${JSON.stringify(item.payload || "")}`.toLowerCase().includes(query))
: ui.activity;
if (!messages.length) {
const empty = createTextElement("div", query ? "No activity matches this filter." : "Protocol events and commands will appear here.");
empty.className = "activity-empty";
stream.replaceChildren(empty);
return;
}
const nearBottom = stream.scrollHeight - stream.scrollTop - stream.clientHeight < 70;
const fragment = document.createDocumentFragment();
for (const item of messages.slice(-250)) {
const row = document.createElement("div");
row.className = `activity-row ${item.kind}`;
const timestamp = createTextElement("span", item.time);
timestamp.className = "activity-time";
const kind = createTextElement("span", item.kind);
kind.className = "activity-kind";
const summary = document.createElement("div");
summary.className = "activity-summary";
summary.append(createTextElement("span", item.summary));
if (item.payload !== undefined) {
const details = document.createElement("details");
details.append(createTextElement("summary", "View payload"));
const pre = createTextElement("pre", JSON.stringify(item.payload, null, 2));
details.append(pre);
summary.append(details);
}
row.append(timestamp, kind, summary);
fragment.append(row);
}
stream.replaceChildren(fragment);
if (nearBottom || !query) stream.scrollTop = stream.scrollHeight;
}
function handleActivityNotification(message) {
if (message.kind === "event" && message.summary === "stopped") {
const reason = message.payload?.reason || "Target stopped";
showToast("Target paused", `${reason} at ${message.payload?.address || "unknown address"}.`);
} else if (message.kind === "event" && message.summary === "terminated") {
showToast("Target terminated", "The emulation run has completed.");
} else if (message.kind === "emulator" && message.summary.startsWith("Emulator exited")) {
showToast("Emulator exited", message.summary);
}
}
function showToast(title, message, tone = "") {
const toast = document.createElement("div");
toast.className = `toast ${tone}`;
toast.append(createTextElement("strong", title), createTextElement("span", message));
byId("toast-stack").append(toast);
window.setTimeout(() => toast.remove(), 4300);
}
function createTextElement(tag, text) {
const element = document.createElement(tag);
element.textContent = text == null ? "" : String(text);
return element;
}
function bindEvents() {
byId("connection-form").addEventListener("submit", connectOrDisconnect);
byId("launch-form").addEventListener("submit", launchEboot);
byId("browse-eboot-button").addEventListener("click", browseForEboot);
byId("stop-emulator-button").addEventListener("click", stopEmulator);
byId("continue-button").addEventListener("click", () => executionCommand("continue", "Continue"));
byId("pause-button").addEventListener("click", () => executionCommand("pause", "Pause"));
byId("step-button").addEventListener("click", () => executionCommand("step", "Step"));
byId("refresh-button").addEventListener("click", refreshTarget);
byId("breakpoint-form").addEventListener("submit", addBreakpoint);
byId("memory-read-form").addEventListener("submit", readMemory);
byId("memory-write-form").addEventListener("submit", writeMemory);
byId("raw-command-form").addEventListener("submit", sendRawCommand);
byId("register-form").addEventListener("submit", applyRegister);
byId("register-dialog-close").addEventListener("click", () => byId("register-dialog").close());
byId("register-cancel").addEventListener("click", () => byId("register-dialog").close());
byId("activity-search").addEventListener("input", renderActivity);
byId("clear-activity").addEventListener("click", () => {
ui.activity = [];
renderActivity();
});
document.addEventListener("keydown", (event) => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement?.tagName)) return;
if (event.key === "F5") {
event.preventDefault();
if (!byId("continue-button").disabled) executionCommand("continue", "Continue");
} else if (event.key === "F6") {
event.preventDefault();
if (!byId("pause-button").disabled) executionCommand("pause", "Pause");
} else if (event.key === "F10") {
event.preventDefault();
if (!byId("step-button").disabled) executionCommand("step", "Step");
}
});
}
async function initialize() {
bindEvents();
await pollSnapshot();
window.setInterval(pollSnapshot, 700);
window.setInterval(() => {
if (ui.snapshot?.connected) refreshTarget();
}, 7000);
}
initialize();
@@ -0,0 +1,302 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>SharpEmu Debugger</title>
<link rel="icon" type="image/webp" href="/sharpemu-logo.webp">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div class="ambient ambient-one"></div>
<div class="ambient ambient-two"></div>
<header class="app-header">
<div class="brand">
<div class="brand-mark" aria-hidden="true"><img src="/sharpemu-logo.webp" alt=""></div>
<div>
<div class="eyebrow">LIVE DEVELOPMENT TOOLS</div>
<h1>SharpEmu <span>Debugger</span></h1>
</div>
</div>
<form id="connection-form" class="connection-bar">
<label class="connection-field">
<span>Host</span>
<input id="debug-host" name="host" autocomplete="off" value="127.0.0.1" aria-label="Debugger host">
</label>
<div class="connection-divider" aria-hidden="true">:</div>
<label class="connection-field port-field">
<span>Port</span>
<input id="debug-port" name="port" type="number" min="1" max="65535" value="5714" aria-label="Debugger port">
</label>
<button id="connection-button" class="button button-primary" type="submit">
<span class="button-icon" aria-hidden="true"></span>
<span id="connection-button-label">Connect</span>
</button>
</form>
<div id="connection-status" class="connection-status disconnected" aria-live="polite">
<span class="status-dot"></span>
<div>
<strong id="connection-state">Offline</strong>
<small id="connection-endpoint">Not connected</small>
</div>
</div>
</header>
<nav class="execution-toolbar" aria-label="Execution controls">
<div class="toolbar-group">
<button id="continue-button" class="tool-button accent" type="button" title="Continue (F5)">
<span class="tool-icon"></span><span>Continue</span><kbd>F5</kbd>
</button>
<button id="pause-button" class="tool-button" type="button" title="Pause (F6)">
<span class="tool-icon"></span><span>Pause</span><kbd>F6</kbd>
</button>
<button id="step-button" class="tool-button" type="button" title="Step frame (F10)">
<span class="tool-icon"></span><span>Step frame</span><kbd>F10</kbd>
</button>
<div class="toolbar-separator"></div>
<button id="refresh-button" class="tool-button compact" type="button" title="Refresh target state">
<span class="tool-icon"></span><span>Refresh</span>
</button>
</div>
<div class="target-pill">
<span>Target</span>
<strong id="toolbar-target-state">Disconnected</strong>
</div>
</nav>
<main class="workspace">
<section class="launch-panel" aria-labelledby="launch-title">
<div class="launch-heading">
<div class="launch-icon" aria-hidden="true"></div>
<div>
<div class="eyebrow">LOCAL SESSION</div>
<h2 id="launch-title">Launch and attach</h2>
<p>Choose a game executable and the frontend will start SharpEmu with its debugger enabled.</p>
</div>
</div>
<form id="launch-form" class="launch-form">
<label class="launch-path-field">
<span>Game executable</span>
<input id="eboot-path" placeholder="/path/to/game/eboot.bin" autocomplete="off" required>
</label>
<button id="browse-eboot-button" class="button button-secondary align-end" type="button">Browse…</button>
<button id="launch-button" class="button button-primary align-end" type="submit">
<span class="button-icon" aria-hidden="true"></span>Launch &amp; attach
</button>
<button id="stop-emulator-button" class="button button-danger align-end" type="button" disabled>Stop</button>
</form>
<div class="launch-status">
<span id="emulator-status-dot" class="status-dot"></span>
<div>
<strong id="emulator-status">No frontend-launched session</strong>
<small id="emulator-detail">You can still attach to an emulator that is already running.</small>
</div>
</div>
</section>
<section class="dashboard-grid">
<article class="panel target-panel">
<div class="panel-header">
<div>
<div class="eyebrow">SESSION</div>
<h2>Target overview</h2>
</div>
<span id="target-state-badge" class="state-badge disconnected">Disconnected</span>
</div>
<div class="target-address">
<span>Instruction pointer</span>
<strong id="target-address"></strong>
</div>
<dl class="fact-grid">
<div><dt>Stop reason</dt><dd id="stop-reason"></dd></div>
<div><dt>Frame</dt><dd id="frame-kind"></dd></div>
<div class="wide"><dt>Image / module</dt><dd id="frame-label"></dd></div>
<div><dt>Result</dt><dd id="stop-result"></dd></div>
<div><dt>Opcode bytes</dt><dd id="opcode-bytes"></dd></div>
</dl>
<div id="stop-detail-wrap" class="stop-detail hidden">
<span>Detail</span>
<p id="stop-detail"></p>
</div>
<div id="stall-analysis" class="stall-analysis hidden">
<div class="stall-analysis-header">
<div>
<div class="eyebrow">STALL DIAGNOSIS</div>
<h3 id="stall-analysis-title">Execution is not making progress</h3>
</div>
<span id="stall-confidence" class="confidence-badge">Medium confidence</span>
</div>
<p id="stall-summary" class="stall-summary"></p>
<div class="diagnosis-block cause-block">
<span class="diagnosis-label">Why this happens</span>
<p id="stall-cause"></p>
</div>
<div class="diagnosis-block fix-block">
<span class="diagnosis-label">Most likely fix</span>
<p id="stall-fix"></p>
</div>
<div class="diagnosis-columns">
<div>
<span class="diagnosis-label">Recommended checks</span>
<ol id="stall-actions"></ol>
</div>
<div>
<span class="diagnosis-label">Evidence</span>
<ul id="stall-evidence"></ul>
</div>
</div>
<p class="diagnosis-disclaimer">Heuristic diagnosis based on the detected loop and resolved HLE import. Confirm with tracing before changing synchronization behavior.</p>
</div>
</article>
<article class="panel registers-panel">
<div class="panel-header">
<div>
<div class="eyebrow">CPU STATE</div>
<h2>Registers</h2>
</div>
<span class="panel-hint">Select a value to edit</span>
</div>
<div id="register-grid" class="register-grid empty-state">
<p>Pause the target to inspect registers.</p>
</div>
</article>
<article class="panel breakpoints-panel">
<div class="panel-header">
<div>
<div class="eyebrow">EXECUTION</div>
<h2>Breakpoints</h2>
</div>
<span id="breakpoint-count" class="count-badge">0</span>
</div>
<form id="breakpoint-form" class="inline-form breakpoint-form">
<label class="grow">
<span>Address</span>
<input id="breakpoint-address" placeholder="0x00000008801234A0" autocomplete="off" required>
</label>
<label>
<span>Kind</span>
<select id="breakpoint-kind">
<option value="execute">Execute</option>
<option value="readwatch">Read watch</option>
<option value="writewatch">Write watch</option>
<option value="accesswatch">Access watch</option>
</select>
</label>
<label class="length-field">
<span>Length</span>
<input id="breakpoint-length" type="number" min="1" value="1">
</label>
<button class="button button-secondary align-end" type="submit">Add</button>
</form>
<div class="table-wrap">
<table class="data-table">
<thead><tr><th>On</th><th>ID</th><th>Kind</th><th>Address</th><th>Length</th><th></th></tr></thead>
<tbody id="breakpoint-table">
<tr class="empty-row"><td colspan="6">No breakpoints configured.</td></tr>
</tbody>
</table>
</div>
<p class="panel-note">Execute breakpoints are active at frame boundaries. Data watchpoints are protocol-ready and await CPU backend hooks.</p>
</article>
<article class="panel memory-panel">
<div class="panel-header">
<div>
<div class="eyebrow">GUEST MEMORY</div>
<h2>Memory inspector</h2>
</div>
<span id="memory-meta" class="panel-hint">Up to 64 KiB</span>
</div>
<form id="memory-read-form" class="inline-form memory-controls">
<label class="grow">
<span>Address</span>
<input id="memory-address" placeholder="0x0000000880200000" autocomplete="off" required>
</label>
<label class="memory-length">
<span>Bytes</span>
<input id="memory-length" type="number" min="1" max="65536" value="256" required>
</label>
<button class="button button-secondary align-end" type="submit">Read memory</button>
</form>
<pre id="memory-view" class="memory-view" tabindex="0">No memory loaded.</pre>
<form id="memory-write-form" class="write-form">
<label>
<span>Write address</span>
<input id="memory-write-address" placeholder="0x0000000880200000" autocomplete="off" required>
</label>
<label class="grow">
<span>Hex bytes</span>
<input id="memory-write-bytes" placeholder="90 90 CC" autocomplete="off" required>
</label>
<button class="button button-danger align-end" type="submit">Write</button>
</form>
</article>
<article class="panel activity-panel">
<div class="panel-header activity-header">
<div>
<div class="eyebrow">PROTOCOL</div>
<h2>Activity</h2>
</div>
<div class="activity-actions">
<label class="search-box">
<span aria-hidden="true"></span>
<input id="activity-search" placeholder="Filter activity" aria-label="Filter activity">
</label>
<button id="clear-activity" class="icon-button" type="button" title="Clear activity">Clear</button>
</div>
</div>
<div id="activity-stream" class="activity-stream" role="log" aria-live="polite">
<div class="activity-empty">Protocol events and commands will appear here.</div>
</div>
<details class="raw-command">
<summary>Advanced: send raw JSON request</summary>
<form id="raw-command-form">
<textarea id="raw-command-input" spellcheck="false">{"command":"status"}</textarea>
<button class="button button-secondary" type="submit">Send request</button>
</form>
</details>
</article>
</section>
</main>
<footer class="app-footer">
<span>SharpEmu JSON-lines protocol <strong id="protocol-version"></strong></span>
<span class="footer-shortcuts"><kbd>F5</kbd> Continue <kbd>F6</kbd> Pause <kbd>F10</kbd> Step</span>
</footer>
<dialog id="register-dialog" class="modal">
<form id="register-form" method="dialog">
<div class="modal-header">
<div><div class="eyebrow">CPU STATE</div><h2>Edit register</h2></div>
<button id="register-dialog-close" class="icon-button close-button" type="button" aria-label="Close">×</button>
</div>
<label>
<span>Register</span>
<input id="register-name" readonly>
</label>
<label>
<span>Value</span>
<input id="register-value" autocomplete="off" required>
</label>
<div class="modal-actions">
<button id="register-cancel" class="button button-ghost" type="button">Cancel</button>
<button class="button button-primary" type="submit">Apply value</button>
</div>
</form>
</dialog>
<div id="toast-stack" class="toast-stack" aria-live="assertive"></div>
<script src="/app.js"></script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
@@ -0,0 +1,463 @@
/*
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
*/
:root {
--bg: #090c12;
--surface: rgba(18, 23, 34, 0.88);
--surface-solid: #121722;
--surface-raised: #181e2b;
--surface-input: #0d111a;
--border: rgba(157, 172, 205, 0.14);
--border-strong: rgba(157, 172, 205, 0.25);
--text: #f1f4fb;
--text-soft: #aab3c6;
--text-dim: #737d92;
--accent: #8a7dff;
--accent-bright: #a89fff;
--accent-muted: rgba(138, 125, 255, 0.14);
--cyan: #48d9d0;
--cyan-muted: rgba(72, 217, 208, 0.12);
--success: #48d597;
--warning: #ffbd62;
--danger: #ff6f83;
--radius: 16px;
--radius-small: 9px;
--shadow: 0 22px 60px rgba(0, 0, 0, 0.32);
--mono: "JetBrains Mono", "Cascadia Code", "SFMono-Regular", Consolas, monospace;
--sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
html { min-width: 360px; background: var(--bg); }
body {
min-height: 100vh;
margin: 0;
color: var(--text);
background:
radial-gradient(circle at 8% 2%, rgba(113, 92, 246, 0.13), transparent 27rem),
radial-gradient(circle at 94% 22%, rgba(41, 190, 196, 0.08), transparent 32rem),
linear-gradient(145deg, #080b10, #0b0e16 48%, #090c12);
font: 14px/1.45 var(--sans);
}
button, input, select, textarea { font: inherit; }
button { color: inherit; }
.ambient {
position: fixed;
z-index: -1;
width: 28rem;
height: 28rem;
border-radius: 50%;
filter: blur(110px);
opacity: 0.13;
pointer-events: none;
}
.ambient-one { top: -15rem; left: 18%; background: var(--accent); }
.ambient-two { right: -18rem; top: 32%; background: var(--cyan); }
.app-header {
display: grid;
grid-template-columns: minmax(260px, 1fr) auto minmax(220px, 1fr);
align-items: center;
gap: 26px;
padding: 21px clamp(20px, 3vw, 52px);
border-bottom: 1px solid var(--border);
background: rgba(9, 12, 18, 0.76);
backdrop-filter: blur(22px);
position: sticky;
top: 0;
z-index: 30;
}
.brand { display: flex; align-items: center; gap: 14px; }
.brand-mark {
display: grid;
place-items: center;
width: 46px;
height: 46px;
border-radius: 13px;
box-shadow: 0 10px 30px rgba(89, 83, 255, 0.24);
overflow: hidden;
}
.brand-mark img { display: block; width: 100%; height: 100%; object-fit: cover; }
.eyebrow {
color: var(--text-dim);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.16em;
}
h1, h2, p { margin: 0; }
h1 { font-size: 20px; line-height: 1.15; letter-spacing: -0.025em; }
h1 span { color: var(--accent-bright); font-weight: 500; }
h2 { margin-top: 3px; font-size: 17px; letter-spacing: -0.02em; }
.connection-bar {
display: flex;
align-items: stretch;
padding: 4px;
border: 1px solid var(--border-strong);
border-radius: 12px;
background: var(--surface-input);
box-shadow: inset 0 1px rgba(255, 255, 255, 0.025);
}
.connection-field { display: grid; align-content: center; padding: 1px 10px; }
.connection-field span, label > span {
display: block;
margin-bottom: 3px;
color: var(--text-dim);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.connection-field input {
width: 148px;
padding: 0;
border: 0;
outline: 0;
color: var(--text);
background: transparent;
font: 13px var(--mono);
}
.connection-field.port-field input { width: 62px; }
.connection-divider { align-self: center; color: var(--text-dim); font: 15px var(--mono); }
input, select, textarea {
width: 100%;
border: 1px solid var(--border-strong);
border-radius: var(--radius-small);
outline: none;
color: var(--text);
background: var(--surface-input);
transition: border-color 140ms, box-shadow 140ms, background 140ms;
}
input, select { min-height: 38px; padding: 8px 11px; }
textarea { padding: 12px; resize: vertical; }
input:focus, select:focus, textarea:focus {
border-color: rgba(138, 125, 255, 0.7);
box-shadow: 0 0 0 3px rgba(138, 125, 255, 0.11);
background: #0f1420;
}
input:disabled, select:disabled, textarea:disabled { opacity: 0.52; cursor: not-allowed; }
.button, .tool-button, .icon-button {
border: 0;
cursor: pointer;
transition: transform 130ms, border-color 130ms, background 130ms, opacity 130ms;
}
.button:hover:not(:disabled), .tool-button:hover:not(:disabled), .icon-button:hover:not(:disabled) { transform: translateY(-1px); }
.button:active:not(:disabled), .tool-button:active:not(:disabled) { transform: translateY(0); }
.button:disabled, .tool-button:disabled, .icon-button:disabled { opacity: 0.38; cursor: not-allowed; }
.button {
min-height: 38px;
padding: 8px 15px;
border-radius: 8px;
font-weight: 680;
white-space: nowrap;
}
.button-primary { color: #fff; background: linear-gradient(135deg, #7568e8, #9184ff); box-shadow: 0 8px 24px rgba(103, 86, 226, 0.22); }
.button-secondary { border: 1px solid var(--border-strong); background: var(--surface-raised); }
.button-danger { border: 1px solid rgba(255, 111, 131, 0.3); color: #ffadba; background: rgba(255, 111, 131, 0.1); }
.button-ghost { border: 1px solid var(--border); background: transparent; }
.button-icon { margin-right: 5px; }
.connection-status { justify-self: end; display: flex; align-items: center; gap: 10px; min-width: 190px; }
.connection-status strong { display: block; font-size: 13px; }
.connection-status small { display: block; margin-top: 1px; color: var(--text-dim); font: 11px var(--mono); }
.status-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--text-dim); box-shadow: 0 0 0 5px rgba(115, 125, 146, 0.09); }
.connection-status.connected .status-dot { background: var(--success); box-shadow: 0 0 0 5px rgba(72, 213, 151, 0.1), 0 0 14px rgba(72, 213, 151, 0.55); }
.execution-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 20px;
min-height: 58px;
padding: 9px clamp(20px, 3vw, 52px);
border-bottom: 1px solid var(--border);
background: rgba(13, 17, 25, 0.84);
}
.toolbar-group { display: flex; align-items: center; gap: 7px; }
.tool-button {
display: flex;
align-items: center;
gap: 8px;
min-height: 37px;
padding: 7px 11px;
border: 1px solid transparent;
border-radius: 8px;
color: var(--text-soft);
background: transparent;
font-weight: 640;
}
.tool-button:hover:not(:disabled) { border-color: var(--border); color: var(--text); background: var(--surface-raised); }
.tool-button.accent:not(:disabled) { color: #c9c3ff; background: var(--accent-muted); }
.tool-button.compact { padding-inline: 10px; }
.tool-icon { width: 18px; color: var(--accent-bright); font-size: 16px; text-align: center; }
.toolbar-separator { width: 1px; height: 24px; margin: 0 5px; background: var(--border); }
kbd { padding: 2px 5px; border: 1px solid var(--border-strong); border-bottom-width: 2px; border-radius: 4px; color: var(--text-dim); background: #0a0e15; font: 9px var(--mono); }
.target-pill { display: flex; align-items: center; gap: 9px; color: var(--text-dim); font-size: 12px; }
.target-pill strong { color: var(--text-soft); font-family: var(--mono); }
.workspace { width: min(1800px, 100%); margin: 0 auto; padding: 22px clamp(16px, 2.5vw, 42px) 34px; }
.dashboard-grid { display: grid; grid-template-columns: minmax(330px, 0.8fr) minmax(540px, 1.5fr); gap: 16px; }
.launch-panel {
display: grid;
grid-template-columns: minmax(240px, 0.75fr) minmax(520px, 1.5fr) auto;
align-items: end;
gap: 22px;
margin-bottom: 16px;
padding: 17px 19px;
border: 1px solid rgba(138, 125, 255, 0.25);
border-radius: var(--radius);
background:
linear-gradient(105deg, rgba(138, 125, 255, 0.1), transparent 38%),
linear-gradient(145deg, rgba(20, 25, 37, 0.94), rgba(14, 18, 27, 0.94));
box-shadow: var(--shadow), inset 0 1px rgba(255, 255, 255, 0.035);
}
.launch-heading { display: flex; align-items: center; gap: 13px; min-width: 0; }
.launch-heading p { margin-top: 4px; color: var(--text-dim); font-size: 11px; }
.launch-icon {
display: grid;
flex: 0 0 auto;
place-items: center;
width: 39px;
height: 39px;
border: 1px solid rgba(138, 125, 255, 0.35);
border-radius: 10px;
color: var(--accent-bright);
background: var(--accent-muted);
font-size: 18px;
}
.launch-form { display: flex; align-items: flex-end; gap: 8px; min-width: 0; }
.launch-path-field { flex: 1; min-width: 180px; }
.launch-status { display: flex; align-items: center; gap: 10px; min-width: 210px; padding-bottom: 3px; }
.launch-status strong { display: block; font-size: 12px; }
.launch-status small { display: block; overflow: hidden; max-width: 260px; margin-top: 2px; color: var(--text-dim); font: 10px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
.launch-status.running .status-dot { background: var(--success); box-shadow: 0 0 0 5px rgba(72, 213, 151, 0.1), 0 0 14px rgba(72, 213, 151, 0.5); }
.launch-status.exited .status-dot { background: var(--danger); box-shadow: 0 0 0 5px rgba(255, 111, 131, 0.09); }
.panel {
min-width: 0;
border: 1px solid var(--border);
border-radius: var(--radius);
background: linear-gradient(145deg, rgba(20, 25, 37, 0.92), rgba(14, 18, 27, 0.92));
box-shadow: var(--shadow), inset 0 1px rgba(255, 255, 255, 0.025);
backdrop-filter: blur(18px);
overflow: hidden;
}
.panel-header { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 18px 20px 15px; border-bottom: 1px solid var(--border); }
.panel-hint { color: var(--text-dim); font-size: 11px; }
.panel-note { padding: 11px 18px 15px; color: var(--text-dim); font-size: 11px; }
.target-panel { grid-column: 1; }
.registers-panel { grid-column: 2; grid-row: span 2; }
.breakpoints-panel { grid-column: 1; }
.memory-panel, .activity-panel { grid-column: 1 / -1; }
.state-badge, .count-badge {
padding: 5px 9px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text-soft);
background: rgba(255,255,255,0.025);
font: 600 10px var(--mono);
text-transform: uppercase;
}
.state-badge.paused { border-color: rgba(255, 189, 98, 0.25); color: var(--warning); background: rgba(255, 189, 98, 0.08); }
.state-badge.running { border-color: rgba(72, 213, 151, 0.25); color: var(--success); background: rgba(72, 213, 151, 0.08); }
.state-badge.terminated { border-color: rgba(255, 111, 131, 0.25); color: var(--danger); background: rgba(255, 111, 131, 0.08); }
.target-address { padding: 21px 20px 19px; border-bottom: 1px solid var(--border); background: linear-gradient(90deg, rgba(138, 125, 255, 0.075), transparent); }
.target-address span { display: block; margin-bottom: 5px; color: var(--text-dim); font-size: 11px; }
.target-address strong { color: #d9d5ff; font: 650 clamp(17px, 1.5vw, 22px) var(--mono); letter-spacing: -0.035em; }
.fact-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0; margin: 0; }
.fact-grid div { min-width: 0; padding: 13px 20px; border-bottom: 1px solid var(--border); }
.fact-grid div:nth-child(odd):not(.wide) { border-right: 1px solid var(--border); }
.fact-grid .wide { grid-column: 1 / -1; }
.fact-grid dt { color: var(--text-dim); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; }
.fact-grid dd { overflow: hidden; margin: 4px 0 0; color: var(--text-soft); font: 12px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
.stop-detail { padding: 13px 20px 17px; color: var(--text-soft); background: rgba(255, 111, 131, 0.045); }
.stop-detail span { color: var(--danger); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; }
.stop-detail p { margin-top: 5px; font-size: 12px; }
.stall-analysis { border-top: 1px solid rgba(255, 189, 98, 0.2); background: linear-gradient(145deg, rgba(255, 189, 98, 0.07), rgba(138, 125, 255, 0.035)); }
.stall-analysis-header { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 16px 20px 12px; }
.stall-analysis h3 { margin: 3px 0 0; color: #fff1da; font-size: 15px; letter-spacing: -0.015em; }
.confidence-badge { flex: 0 0 auto; padding: 4px 8px; border: 1px solid rgba(255, 189, 98, 0.25); border-radius: 999px; color: var(--warning); background: rgba(255, 189, 98, 0.075); font: 600 9px var(--mono); text-transform: uppercase; }
.stall-summary { padding: 0 20px 14px; color: var(--text-soft); font-size: 12px; }
.diagnosis-block { margin: 0 20px 10px; padding: 11px 12px; border: 1px solid var(--border); border-radius: 9px; background: rgba(7, 10, 16, 0.34); }
.diagnosis-block.fix-block { border-color: rgba(72, 213, 151, 0.2); background: rgba(72, 213, 151, 0.045); }
.diagnosis-label { display: block; margin-bottom: 5px; color: var(--text-dim); font-size: 9px; font-weight: 750; letter-spacing: 0.09em; text-transform: uppercase; }
.cause-block .diagnosis-label { color: var(--warning); }
.fix-block .diagnosis-label { color: var(--success); }
.diagnosis-block p { color: var(--text-soft); font-size: 11px; line-height: 1.55; }
.diagnosis-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; padding: 4px 20px 12px; }
.diagnosis-columns ol, .diagnosis-columns ul { margin: 0; padding-left: 18px; color: var(--text-soft); font-size: 10px; line-height: 1.55; }
.diagnosis-columns li + li { margin-top: 5px; }
.diagnosis-columns li::marker { color: var(--accent-bright); font-family: var(--mono); }
.diagnosis-disclaimer { padding: 10px 20px 14px; border-top: 1px solid var(--border); color: var(--text-dim); font-size: 9px; }
.hidden { display: none !important; }
.register-grid { display: grid; grid-template-columns: repeat(4, minmax(120px, 1fr)); gap: 1px; background: var(--border); }
.register-grid.empty-state { grid-template-columns: 1fr; }
.register-item { min-width: 0; padding: 12px 14px; background: rgba(14, 18, 27, 0.97); }
.register-item.special { background: linear-gradient(135deg, rgba(138, 125, 255, 0.09), rgba(14, 18, 27, 0.97)); }
.register-name { display: block; margin-bottom: 4px; color: var(--text-dim); font: 700 10px var(--mono); text-transform: uppercase; }
.register-value {
display: block;
overflow: hidden;
width: 100%;
padding: 0;
border: 0;
color: #d5d9e5;
background: transparent;
font: 11px var(--mono);
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
}
.register-value:hover { color: var(--accent-bright); }
.empty-state { display: grid; place-items: center; min-height: 210px; color: var(--text-dim); background: transparent; }
.inline-form, .write-form { display: flex; align-items: flex-start; gap: 9px; padding: 14px 16px; border-bottom: 1px solid var(--border); }
.inline-form label, .write-form label, .modal label { min-width: 0; }
.grow { flex: 1; }
.length-field { width: 82px; }
.memory-length { width: 90px; }
.align-end { align-self: flex-end; }
.table-wrap { overflow-x: auto; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th { padding: 9px 11px; border-bottom: 1px solid var(--border); color: var(--text-dim); font-size: 9px; letter-spacing: 0.08em; text-align: left; text-transform: uppercase; }
.data-table td { padding: 10px 11px; border-bottom: 1px solid rgba(157, 172, 205, 0.08); color: var(--text-soft); font: 11px var(--mono); }
.data-table tr:last-child td { border-bottom: 0; }
.data-table tbody tr:hover:not(.empty-row) { background: rgba(138, 125, 255, 0.045); }
.empty-row td { padding: 25px; color: var(--text-dim); font-family: var(--sans); text-align: center; }
.kind-pill { padding: 3px 6px; border-radius: 5px; color: #bbb5ff; background: var(--accent-muted); font: 9px var(--mono); text-transform: uppercase; }
.row-action { padding: 3px 7px; border: 1px solid transparent; border-radius: 5px; color: var(--text-dim); background: transparent; cursor: pointer; }
.row-action:hover { border-color: rgba(255, 111, 131, 0.25); color: var(--danger); background: rgba(255, 111, 131, 0.07); }
.switch { width: 15px; height: 15px; accent-color: var(--accent); cursor: pointer; }
.memory-controls { padding-bottom: 12px; }
.memory-view {
min-height: 240px;
max-height: 430px;
margin: 0;
padding: 17px 20px;
overflow: auto;
border-bottom: 1px solid var(--border);
outline: none;
color: #bcc6da;
background: #090d14;
font: 12px/1.65 var(--mono);
tab-size: 4;
}
.memory-view:focus { box-shadow: inset 0 0 0 1px rgba(138, 125, 255, 0.38); }
.write-form { border-bottom: 0; }
.activity-header { align-items: flex-end; }
.activity-actions { display: flex; align-items: center; gap: 8px; }
.search-box { position: relative; display: flex; align-items: center; }
.search-box > span { position: absolute; left: 10px; color: var(--text-dim); }
.search-box input { min-height: 34px; padding-left: 29px; }
.icon-button { min-height: 32px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 7px; color: var(--text-soft); background: transparent; font-size: 12px; }
.activity-stream { min-height: 180px; max-height: 360px; overflow: auto; background: #0a0e15; }
.activity-empty { display: grid; place-items: center; min-height: 180px; color: var(--text-dim); }
.activity-row { display: grid; grid-template-columns: 66px 76px 1fr; align-items: start; gap: 10px; padding: 9px 16px; border-bottom: 1px solid rgba(157, 172, 205, 0.07); }
.activity-row:hover { background: rgba(255, 255, 255, 0.018); }
.activity-time { padding-top: 2px; color: var(--text-dim); font: 10px var(--mono); }
.activity-kind { width: max-content; padding: 2px 6px; border-radius: 5px; color: var(--text-soft); background: rgba(170, 179, 198, 0.09); font: 700 9px var(--mono); text-transform: uppercase; }
.activity-row.event .activity-kind { color: var(--cyan); background: var(--cyan-muted); }
.activity-row.request .activity-kind { color: var(--accent-bright); background: var(--accent-muted); }
.activity-row.error .activity-kind { color: var(--danger); background: rgba(255, 111, 131, 0.1); }
.activity-row.response .activity-kind { color: var(--success); background: rgba(72, 213, 151, 0.09); }
.activity-row.emulator .activity-kind { color: var(--warning); background: rgba(255, 189, 98, 0.09); }
.activity-summary { min-width: 0; color: var(--text-soft); font: 11px var(--mono); }
.activity-summary details { margin-top: 3px; }
.activity-summary summary { color: var(--text-dim); cursor: pointer; font: 10px var(--sans); }
.activity-summary pre { overflow: auto; margin: 7px 0 1px; padding: 9px; border: 1px solid var(--border); border-radius: 7px; color: #aeb8cd; background: #080b11; font: 10px/1.5 var(--mono); }
.raw-command { border-top: 1px solid var(--border); color: var(--text-dim); }
.raw-command > summary { padding: 11px 16px; cursor: pointer; font-size: 11px; }
.raw-command form { display: flex; gap: 9px; padding: 0 16px 15px; }
.raw-command textarea { min-height: 62px; font: 11px/1.5 var(--mono); }
.raw-command .button { align-self: flex-end; }
.app-footer { display: flex; justify-content: space-between; gap: 20px; padding: 14px clamp(20px, 3vw, 52px) 22px; color: var(--text-dim); font-size: 11px; }
.app-footer strong { color: var(--text-soft); font-family: var(--mono); }
.footer-shortcuts { display: flex; gap: 7px; align-items: center; }
.modal {
width: min(430px, calc(100vw - 32px));
padding: 0;
border: 1px solid var(--border-strong);
border-radius: 15px;
color: var(--text);
background: var(--surface-solid);
box-shadow: 0 30px 90px rgba(0,0,0,0.62);
}
.modal::backdrop { background: rgba(3, 5, 9, 0.74); backdrop-filter: blur(5px); }
.modal form { display: grid; gap: 15px; padding: 20px; }
.modal-header { display: flex; justify-content: space-between; align-items: start; }
.close-button { border: 0; font-size: 20px; }
.modal-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
.toast-stack { position: fixed; right: 18px; bottom: 18px; z-index: 60; display: grid; gap: 8px; width: min(380px, calc(100vw - 36px)); pointer-events: none; }
.toast { padding: 12px 14px; border: 1px solid var(--border-strong); border-left: 3px solid var(--accent); border-radius: 9px; color: var(--text-soft); background: rgba(20, 25, 37, 0.96); box-shadow: 0 14px 45px rgba(0,0,0,0.4); animation: toast-in 180ms ease-out; }
.toast.error { border-left-color: var(--danger); }
.toast.success { border-left-color: var(--success); }
.toast strong { display: block; margin-bottom: 2px; color: var(--text); font-size: 12px; }
@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } }
@media (max-width: 1100px) {
.app-header { grid-template-columns: 1fr auto; }
.connection-bar { grid-column: 1 / -1; grid-row: 2; justify-self: stretch; }
.connection-field:first-child { flex: 1; }
.connection-field input { width: 100%; }
.connection-status { grid-column: 2; grid-row: 1; }
.dashboard-grid { grid-template-columns: 1fr; }
.launch-panel { grid-template-columns: 1fr; align-items: stretch; }
.launch-form { flex-wrap: wrap; }
.launch-status { min-width: 0; }
.target-panel, .registers-panel, .breakpoints-panel, .memory-panel, .activity-panel { grid-column: 1; grid-row: auto; }
}
@media (max-width: 680px) {
.app-header { position: static; padding: 16px; gap: 16px; }
.brand-mark { width: 40px; height: 40px; }
.connection-status { min-width: 0; }
.connection-status small { display: none; }
.connection-bar { flex-wrap: wrap; }
.connection-field:first-child { min-width: 150px; }
.connection-bar .button { flex: 1; }
.execution-toolbar { align-items: stretch; padding: 8px 12px; overflow-x: auto; }
.target-pill { display: none; }
.tool-button kbd { display: none; }
.workspace { padding: 12px; }
.launch-panel { padding: 15px; gap: 15px; }
.launch-form { align-items: stretch; }
.launch-path-field { flex-basis: 100%; }
.launch-form .button { flex: 1 1 auto; }
.register-grid { grid-template-columns: repeat(2, minmax(130px, 1fr)); }
.inline-form, .write-form { flex-wrap: wrap; }
.inline-form label, .write-form label { flex: 1 1 140px; }
.align-end { flex: 1 1 auto; }
.activity-header { align-items: stretch; flex-direction: column; }
.activity-actions, .search-box { width: 100%; }
.search-box { flex: 1; }
.activity-row { grid-template-columns: 58px 64px 1fr; padding-inline: 10px; gap: 7px; }
.diagnosis-columns { grid-template-columns: 1fr; }
.raw-command form { flex-direction: column; }
.app-footer { padding-inline: 16px; }
.footer-shortcuts { display: none; }
}