дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
feat(debugger): Disassembly view and instruction stepping for native debugging (#6694)
Native debug sessions whose adapter supports disassemble get a Disassembly tab showing the selected frame's instructions with the program counter highlighted, following stepping and frame selection, including frames without source. Show Disassembly is on the Frames list; Step Over Instruction and Step Into Instruction send steps with instruction granularity and are disabled with a reason when the adapter lacks it. Frames keep instructionPointerReference; when the PC is not where the requested window expects it, the view reads again from the PC. lldb-dap sends instruction bytes already spaced and pads mnemonics unevenly; the view strips the spacing before grouping the bytes and pads mnemonics to one width. Part of #5922 Co-authored-by: bertyhell <[email protected]>
Цей коміт міститься в:
1 джерело
5fb8f21c60
коміт
ad685ea19e
21 files changed
+1407
-16
No files matched your search
+58
-4
@@ -471,6 +471,11 @@ export const commands = {
|
||||
/** Completions for an expression typed in Evaluate (`line` / `column` 0-based, UTF-16). */
|
||||
debugCompletions: (session: DebugSessionId, frameId: number | null, text: string, line: number, column: number) => typedError<DebugCompletion[], IdeError>(__TAURI_INVOKE("debug_completions", { session, frameId, text, line, column })),
|
||||
debugDataBreakpointInfo: (session: DebugSessionId, container: number, name: string, frameId: number | null) => typedError<DataBreakpointInfo, IdeError>(__TAURI_INVOKE("debug_data_breakpoint_info", { session, container, name, frameId })),
|
||||
/**
|
||||
* Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference`
|
||||
* (a frame's instruction pointer or an instruction's address).
|
||||
*/
|
||||
debugDisassemble: (session: DebugSessionId, memoryReference: string, before: number, count: number) => typedError<Instruction_Serialize[], IdeError>(__TAURI_INVOKE("debug_disassemble", { session, memoryReference, before, count })),
|
||||
debugEvaluate: (session: DebugSessionId, frameId: number | null, expression: string) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_evaluate", { session, frameId, expression })),
|
||||
/** Evaluate with an explicit DAP context: `repl`, `watch`, `hover` or `clipboard`. */
|
||||
debugEvaluateIn: (session: DebugSessionId, frameId: number | null, expression: string, context: string | null) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_evaluate_in", { session, frameId, expression, context })),
|
||||
@@ -560,21 +565,23 @@ export const commands = {
|
||||
/** Method breakpoints (all files); states aligned with `breakpoints`. */
|
||||
debugSetFunctionBreakpoints: (breakpoints: FunctionBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_function_breakpoints", { breakpoints })),
|
||||
debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })),
|
||||
debugStackTrace: (session: DebugSessionId, threadId: number) => typedError<StackFrame[], IdeError>(__TAURI_INVOKE("debug_stack_trace", { session, threadId })),
|
||||
debugStackTrace: (session: DebugSessionId, threadId: number) => typedError<StackFrame_Serialize[], IdeError>(__TAURI_INVOKE("debug_stack_trace", { session, threadId })),
|
||||
/** Starts a session owned by this window: its events (and those of child sessions) go here only. */
|
||||
debugStart: (config: LaunchConfig) => typedError<DebugSessionId, IdeError>(__TAURI_INVOKE("debug_start", { config })),
|
||||
debugStep: (session: DebugSessionId, threadId: number, kind: StepKind) => typedError<null, IdeError>(__TAURI_INVOKE("debug_step", { session, threadId, kind })),
|
||||
debugStepInTarget: (session: DebugSessionId, threadId: number, targetId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_step_in_target", { session, threadId, targetId })),
|
||||
/** Smart Step Into: the calls on the current line of `frame_id`. */
|
||||
debugStepInTargets: (session: DebugSessionId, frameId: number) => typedError<StepInTarget[], IdeError>(__TAURI_INVOKE("debug_step_in_targets", { session, frameId })),
|
||||
/** Step Over / Into Instruction: a step by one machine instruction. */
|
||||
debugStepInstruction: (session: DebugSessionId, threadId: number, kind: StepKind) => typedError<null, IdeError>(__TAURI_INVOKE("debug_step_instruction", { session, threadId, kind })),
|
||||
debugStop: (session: DebugSessionId) => typedError<null, IdeError>(__TAURI_INVOKE("debug_stop", { session })),
|
||||
/** The stream chains around `frame`'s line; `top`: it is the thread's top frame. */
|
||||
debugStreamChains: (session: DebugSessionId, frame: StackFrame, top: boolean) => typedError<StreamChainInfo_Serialize[], IdeError>(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })),
|
||||
debugStreamChains: (session: DebugSessionId, frame: StackFrame_Deserialize, top: boolean) => typedError<StreamChainInfo_Serialize[], IdeError>(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })),
|
||||
/**
|
||||
* Traces chain `chain_index` of [`debug_stream_chains`], whose `range` the UI showed, while the
|
||||
* program runs it; cancelling `request` stops recording.
|
||||
*/
|
||||
debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame, chainIndex: number, range: Range, onProgress: Channel<TraceProgress>) => typedError<StreamTraceResult_Serialize, IdeError>(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })),
|
||||
debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame_Deserialize, chainIndex: number, range: Range, onProgress: Channel<TraceProgress>) => typedError<StreamTraceResult_Serialize, IdeError>(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })),
|
||||
/** Ends the running trace's terminal operation; `None` when no trace runs. */
|
||||
debugStreamTraceAbort: (session: DebugSessionId) => typedError<{ kind: "interrupted" } | { kind: "stopped" } |
|
||||
/** Suspended threads that own a monitor the terminal may be waiting for: `(thread id, name)`. */
|
||||
@@ -6307,6 +6314,10 @@ export type DebugCapabilities = {
|
||||
streamTrace: boolean,
|
||||
/** The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View. */
|
||||
readMemory: boolean,
|
||||
/** The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view. */
|
||||
disassemble: boolean,
|
||||
/** Steps can move by one instruction ([`DebugManager::step_instruction`]). */
|
||||
instructionStepping: boolean,
|
||||
};
|
||||
|
||||
/** A completion the adapter offers for an expression (DAP `completions`). */
|
||||
@@ -9453,6 +9464,33 @@ export type InstalledIntellijTheme = {
|
||||
active: boolean,
|
||||
};
|
||||
|
||||
/** One disassembled instruction. */
|
||||
export type Instruction = Instruction_Serialize | Instruction_Deserialize;
|
||||
|
||||
/** One disassembled instruction. */
|
||||
export type Instruction_Deserialize = {
|
||||
/** Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. */
|
||||
address: string,
|
||||
/** The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). */
|
||||
instruction: string,
|
||||
/** Its machine code as hex (`488b45d8`), when the adapter sends it. */
|
||||
bytes?: string | null,
|
||||
/** The function it belongs to, when the adapter names it (often on the first instruction only). */
|
||||
symbol?: string | null,
|
||||
};
|
||||
|
||||
/** One disassembled instruction. */
|
||||
export type Instruction_Serialize = {
|
||||
/** Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. */
|
||||
address: string,
|
||||
/** The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). */
|
||||
instruction: string,
|
||||
/** Its machine code as hex (`488b45d8`), when the adapter sends it. */
|
||||
bytes?: string | null,
|
||||
/** The function it belongs to, when the adapter names it (often on the first instruction only). */
|
||||
symbol?: string | null,
|
||||
};
|
||||
|
||||
export type IntellijThemeFile = {
|
||||
/** The `themeProvider` id (what `laf.xml` names), or the file name without `.theme.json`. */
|
||||
id: string,
|
||||
@@ -14475,7 +14513,9 @@ export type SshSigningKey = {
|
||||
inAgent: boolean,
|
||||
};
|
||||
|
||||
export type StackFrame = {
|
||||
export type StackFrame = StackFrame_Serialize | StackFrame_Deserialize;
|
||||
|
||||
export type StackFrame_Deserialize = {
|
||||
id: number,
|
||||
name: string,
|
||||
path: IpcPath | null,
|
||||
@@ -14483,6 +14523,20 @@ export type StackFrame = {
|
||||
column: number,
|
||||
/** `subtle` frames (library/generated) are collapsed in the UI. */
|
||||
presentationHint: string | null,
|
||||
/** The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). */
|
||||
instructionPointerReference?: string | null,
|
||||
};
|
||||
|
||||
export type StackFrame_Serialize = {
|
||||
id: number,
|
||||
name: string,
|
||||
path: IpcPath | null,
|
||||
line: number,
|
||||
column: number,
|
||||
/** `subtle` frames (library/generated) are collapsed in the UI. */
|
||||
presentationHint: string | null,
|
||||
/** The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). */
|
||||
instructionPointerReference?: string | null,
|
||||
};
|
||||
|
||||
export type StagedText = {
|
||||
|
||||
@@ -9,6 +9,7 @@ const ipc = vi.hoisted(() => {
|
||||
ok,
|
||||
runStop: vi.fn(() => ok(null)),
|
||||
debugStep: vi.fn(() => ok(null)),
|
||||
debugStepInstruction: vi.fn(() => ok(null)),
|
||||
debugResume: vi.fn(() => ok(null)),
|
||||
debugForceStepOver: vi.fn(() => ok(null)),
|
||||
debugRunTo: vi.fn(() => ok(null)),
|
||||
@@ -107,6 +108,7 @@ import { forgetMemory, selectMemoryClass } from "../memory/memoryState";
|
||||
import { forgetInstances, setInstancesLead, showInstances, useInstances } from "../memory/instancesState";
|
||||
import { InstancesPane } from "../memory/InstancesPane";
|
||||
import { forgetMemoryView, useMemoryView } from "../memoryView/memoryViewState";
|
||||
import { useDisassembly } from "../disassembly/disassemblyState";
|
||||
|
||||
const caps = (p: Partial<DebugCapabilities> = {}): DebugCapabilities => ({
|
||||
restartFrame: false,
|
||||
@@ -125,6 +127,8 @@ const caps = (p: Partial<DebugCapabilities> = {}): DebugCapabilities => ({
|
||||
liveEvaluate: false,
|
||||
streamTrace: false,
|
||||
readMemory: false,
|
||||
disassemble: false,
|
||||
instructionStepping: false,
|
||||
...p,
|
||||
});
|
||||
|
||||
@@ -207,6 +211,9 @@ describe("debugger actions (IDEA parity)", () => {
|
||||
"debug.memory.showReferrers": undefined,
|
||||
"debug.memory.closeInstances": undefined,
|
||||
"debug.viewMemory": undefined,
|
||||
"debug.showDisassembly": undefined,
|
||||
"debug.stepOverInstruction": undefined,
|
||||
"debug.stepIntoInstruction": undefined,
|
||||
"debug.toggleMethodBreakpoint": undefined,
|
||||
"debug.toggleFieldWatchpoint": undefined,
|
||||
"debug.traceStreamChain": undefined,
|
||||
@@ -657,6 +664,50 @@ describe("View Memory", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Disassembly and instruction steps", () => {
|
||||
const notify = vi.fn();
|
||||
const show = vi.fn();
|
||||
beforeEach(() => {
|
||||
provideNotificationService({ notify });
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
useDisassembly.setState({ bySession: {}, revealPending: false });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["debug.stepOverInstruction", "Step Over Instruction"],
|
||||
["debug.stepIntoInstruction", "Step Into Instruction"],
|
||||
["debug.showDisassembly", "Disassembly"],
|
||||
])("%s says when the session's debugger cannot do it", async (id, what) => {
|
||||
paused({ adapter: "debugpy" });
|
||||
await executeAction(id);
|
||||
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: `${what} is not supported by debugpy` }));
|
||||
expect(ipc.debugStepInstruction).not.toHaveBeenCalled();
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
expect(useDebug.getState().sessions[3]?.status).toBe("paused");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["debug.stepOverInstruction", "over"],
|
||||
["debug.stepIntoInstruction", "into"],
|
||||
] as const)("%s steps the paused thread by one instruction", async (id, kind) => {
|
||||
paused({ adapter: "gdb", caps: caps({ instructionStepping: true }) });
|
||||
await executeAction(id);
|
||||
await settle();
|
||||
expect(ipc.debugStepInstruction).toHaveBeenCalledWith(3, 1, kind);
|
||||
expect(ipc.debugStep).not.toHaveBeenCalled();
|
||||
expect(useDebug.getState().sessions[3]).toMatchObject({ status: "running", frames: [] });
|
||||
});
|
||||
|
||||
it("opens the Disassembly view at a frame of the Frames list", async () => {
|
||||
paused({ adapter: "lldb-dap", caps: caps({ disassemble: true }) });
|
||||
await executeAction("debug.showDisassembly", 70);
|
||||
expect(show).toHaveBeenCalledWith("debug", true);
|
||||
expect(useDisassembly.getState().revealPending).toBe(true);
|
||||
expect(useDebug.getState().sessions[3]?.selectedFrame).toBe(70);
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PHP debugging without Xdebug", () => {
|
||||
const php: RunConfig = {
|
||||
id: "php:index",
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
debugDisassemble: vi.fn(),
|
||||
debugScopes: vi.fn(),
|
||||
debugVariables: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
|
||||
import type { DebugCapabilities, Instruction, StackFrame } from "@/platform/ipc";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { setLocale } from "@/platform/i18n";
|
||||
import { hideContextMenu, useContextMenuStore } from "@/ui/Menu";
|
||||
import { useDebug, type DebugSession } from "../state";
|
||||
import { DebugToolWindow } from "../ui/DebugToolWindow";
|
||||
import { revealDisassembly, useDisassembly } from "../disassembly/disassemblyState";
|
||||
import { instructionText, spacedBytes } from "../disassembly/DisassemblyPane";
|
||||
|
||||
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
|
||||
const fail = (message: string) =>
|
||||
Promise.resolve({ status: "error" as const, error: { kind: "invalidInput", message } });
|
||||
|
||||
/** A program of 4-byte instructions from 0x401000 (`sum`) to 0x402000; `before` works like lldb-dap's. */
|
||||
function program(reference: string, before: number, count: number): Instruction[] {
|
||||
const start = Number(BigInt(reference)) - 4 * before;
|
||||
return Array.from({ length: count }, (_, i) => start + 4 * i)
|
||||
.filter((a) => a >= 0x401000 && a < 0x402000)
|
||||
.map((a) => ({
|
||||
address: `0x${a.toString(16)}`,
|
||||
instruction: `insn ${(a - 0x401000) / 4}`,
|
||||
bytes: "488b45d8",
|
||||
symbol: a === 0x401000 ? "sum" : null,
|
||||
}));
|
||||
}
|
||||
|
||||
const caps = (p: Partial<DebugCapabilities>) =>
|
||||
({ disassemble: true, instructionStepping: true, ...p }) as DebugCapabilities;
|
||||
|
||||
const frame = (id: number, name: string, pc: string | null, path: string | null = "/p/main.c"): StackFrame => ({
|
||||
id,
|
||||
name,
|
||||
path,
|
||||
line: 13,
|
||||
column: 0,
|
||||
presentationHint: null,
|
||||
instructionPointerReference: pc,
|
||||
});
|
||||
|
||||
const session: DebugSession = {
|
||||
id: 1,
|
||||
name: "app-c",
|
||||
adapter: "gdb",
|
||||
parent: null,
|
||||
launch: null,
|
||||
process: null,
|
||||
status: "paused",
|
||||
stoppedThread: 1,
|
||||
stopReason: "breakpoint",
|
||||
stopDescription: null,
|
||||
threads: [{ id: 1, name: "main" }],
|
||||
selectedThread: 1,
|
||||
frames: [frame(0, "sum", "0x401100"), frame(1, "run", "0x401f00")],
|
||||
selectedFrame: 0,
|
||||
hits: 1,
|
||||
stops: 1,
|
||||
exitCode: null,
|
||||
caps: caps({}),
|
||||
};
|
||||
|
||||
const reads = () => ipc.debugDisassemble.mock.calls.map((c) => c.slice(1));
|
||||
const currentRow = () => screen.getAllByRole("row").find((r) => r.getAttribute("aria-current") === "location");
|
||||
const currentAddress = () => (currentRow() ? within(currentRow()!).getByRole("rowheader").textContent : null);
|
||||
const patchSession = (p: Partial<DebugSession>) =>
|
||||
act(() => useDebug.setState((s) => ({ sessions: { 1: { ...s.sessions[1]!, ...p } } })));
|
||||
|
||||
function openTab() {
|
||||
render(<DebugToolWindow />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Disassembly" }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setLocale("en");
|
||||
useDisassembly.setState({ bySession: {}, revealPending: false });
|
||||
useDebug.setState({ sessions: { 1: session }, active: 1 });
|
||||
ipc.debugDisassemble.mockImplementation((_s: number, reference: string, before: number, count: number) =>
|
||||
Number(BigInt(reference)) < 0x1000
|
||||
? fail(`disassemble failed: Cannot access memory at address ${reference}`)
|
||||
: ok(program(reference, before, count)),
|
||||
);
|
||||
ipc.debugScopes.mockImplementation(() => ok([]));
|
||||
ipc.debugVariables.mockImplementation(() => ok([]));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
hideContextMenu();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("Disassembly view", () => {
|
||||
it("is a tab of sessions whose adapter disassembles, and only those", () => {
|
||||
useDebug.setState({ sessions: { 1: { ...session, caps: caps({ disassemble: false }) } } });
|
||||
const { unmount } = render(<DebugToolWindow />);
|
||||
expect(screen.queryByRole("tab", { name: "Disassembly" })).toBeNull();
|
||||
unmount();
|
||||
useDebug.setState({ sessions: { 1: session } });
|
||||
render(<DebugToolWindow />);
|
||||
expect(screen.getByRole("tab", { name: "Disassembly" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows the selected frame's instructions with the current one highlighted", async () => {
|
||||
openTab();
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401100"));
|
||||
expect(reads()).toEqual([["0x401100", 32, 128]]);
|
||||
const row = currentRow()!;
|
||||
const [bytes, instruction] = within(row).getAllByRole("gridcell");
|
||||
expect(bytes!.textContent).toBe("48 8B 45 D8");
|
||||
expect(instruction!.textContent).toBe("insn 64");
|
||||
expect(screen.getByRole("grid", { name: "Disassembly" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("moves the highlight through the instructions shown while stepping, and reads again past them", async () => {
|
||||
openTab();
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401100"));
|
||||
// A step to an instruction already shown reads nothing.
|
||||
patchSession({ status: "running", frames: [], selectedFrame: null });
|
||||
expect(screen.getByText("Instructions are shown while the program is paused.")).toBeTruthy();
|
||||
patchSession({
|
||||
status: "paused",
|
||||
stops: 2,
|
||||
stopReason: "step",
|
||||
frames: [frame(0, "sum", "0x401104")],
|
||||
selectedFrame: 0,
|
||||
});
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401104"));
|
||||
expect(reads()).toHaveLength(1);
|
||||
// One outside them (a call into another function) reads around it.
|
||||
patchSession({ stops: 3, frames: [frame(0, "parse", "0x401e00")], selectedFrame: 0 });
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401E00"));
|
||||
expect(reads().at(-1)).toEqual(["0x401e00", 32, 128]);
|
||||
});
|
||||
|
||||
it("follows frame selection, also to frames without source", async () => {
|
||||
useDebug.setState({
|
||||
sessions: {
|
||||
1: { ...session, frames: [frame(9, "atoi@plt", "0x401040", null), ...session.frames], selectedFrame: 9 },
|
||||
},
|
||||
});
|
||||
openTab();
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401040"));
|
||||
expect(screen.getByText("atoi@plt")).toBeTruthy();
|
||||
// `sum` was shown at its start: its symbol labels the instructions that follow.
|
||||
expect(screen.getByText("sum:")).toBeTruthy();
|
||||
patchSession({ selectedFrame: 0 });
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401100"));
|
||||
patchSession({ selectedFrame: 1 });
|
||||
await waitFor(() => expect(currentAddress()).toBe("0x00401F00"));
|
||||
});
|
||||
|
||||
it("says why there is nothing to show, and does not ask again for the same address", async () => {
|
||||
useDebug.setState({ sessions: { 1: { ...session, frames: [frame(0, "??", "0x10")] } } });
|
||||
openTab();
|
||||
expect((await screen.findByRole("alert")).textContent).toBe(
|
||||
"disassemble failed: Cannot access memory at address 0x10",
|
||||
);
|
||||
patchSession({ stops: 2 });
|
||||
expect(reads()).toHaveLength(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
|
||||
await waitFor(() => expect(reads()).toHaveLength(2));
|
||||
patchSession({ frames: [frame(0, "jit", null)] });
|
||||
expect(screen.getByText("The debugger gives no instruction address for this frame.")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("offers instruction steps, disabled with the reason where the adapter has none", async () => {
|
||||
const stepOver = vi.fn();
|
||||
const unregister = registerActions([
|
||||
{ id: "debug.stepOverInstruction", title: "Step Over Instruction", run: stepOver },
|
||||
{ id: "debug.stepIntoInstruction", title: "Step Into Instruction", run: vi.fn() },
|
||||
]);
|
||||
openTab();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Step Over Instruction" }));
|
||||
expect(stepOver).toHaveBeenCalled();
|
||||
patchSession({ caps: caps({ instructionStepping: false }) });
|
||||
const button = screen.getByRole("button", { name: "Step Over Instruction" });
|
||||
expect(button.hasAttribute("disabled")).toBe(true);
|
||||
expect(button.getAttribute("data-tooltip") ?? button.getAttribute("title") ?? "").toContain(
|
||||
"Instruction stepping is not supported by gdb",
|
||||
);
|
||||
unregister();
|
||||
});
|
||||
|
||||
it("is offered on frames with an instruction address", async () => {
|
||||
const show = vi.fn();
|
||||
const unregister = registerActions([
|
||||
{ id: "debug.showDisassembly", title: "Show Disassembly", run: ({ arg }) => show(arg) },
|
||||
]);
|
||||
render(<DebugToolWindow />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Threads & Variables" }));
|
||||
fireEvent.contextMenu(await screen.findByText("run"));
|
||||
const item = useContextMenuStore
|
||||
.getState()
|
||||
.menu!.items.find((i) => "label" in i && i.label === "Show Disassembly") as {
|
||||
run: () => void;
|
||||
disabled?: boolean;
|
||||
};
|
||||
expect(item.disabled).toBe(false);
|
||||
act(() => item.run());
|
||||
await waitFor(() => expect(show).toHaveBeenCalledWith(1));
|
||||
hideContextMenu();
|
||||
patchSession({ caps: caps({ disassemble: false }) });
|
||||
fireEvent.contextMenu(await screen.findByText("run"));
|
||||
const labels = useContextMenuStore.getState().menu!.items.map((i) => ("label" in i ? i.label : "-"));
|
||||
expect(labels).not.toContain("Show Disassembly");
|
||||
unregister();
|
||||
});
|
||||
|
||||
it("comes to the front when Show Disassembly asks for it", () => {
|
||||
render(<DebugToolWindow />);
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Console" }));
|
||||
act(() => revealDisassembly());
|
||||
expect(screen.getByRole("tab", { name: "Disassembly" }).getAttribute("aria-selected")).toBe("true");
|
||||
expect(useDisassembly.getState().revealPending).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("instruction text", () => {
|
||||
it("spaces the bytes whether or not the adapter already did", () => {
|
||||
expect(spacedBytes("488b45d8")).toBe("48 8B 45 D8");
|
||||
expect(spacedBytes("a1 03 5f f8")).toBe("A1 03 5F F8");
|
||||
expect(spacedBytes(null)).toBe("");
|
||||
});
|
||||
|
||||
it("pads lldb-dap's mnemonics to one width", () => {
|
||||
expect(instructionText(" ldur x1, [x29, #-0x10]")).toBe("ldur x1, [x29, #-0x10]");
|
||||
expect(instructionText(" mov x9, sp")).toBe("mov x9, sp");
|
||||
expect(instructionText(" bl 0x10000062c ; hash at main.c:13")).toBe("bl 0x10000062c ; hash at main.c:13");
|
||||
expect(instructionText("mov -0x2c(%rbp),%eax")).toBe("mov -0x2c(%rbp),%eax");
|
||||
expect(instructionText(" ret")).toBe("ret");
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
adoptSession,
|
||||
handleDebugEvent,
|
||||
isThreadSuspended,
|
||||
markInstructionStep,
|
||||
selectThread,
|
||||
resumeExecution,
|
||||
useDebug,
|
||||
@@ -82,6 +83,30 @@ describe("execution point state", () => {
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 9 });
|
||||
});
|
||||
|
||||
it("selects the frame without source an instruction step stopped in, and the first with source otherwise", async () => {
|
||||
// GDB, one instruction into `atoi@plt` from `parse` (#5922): the innermost frame has no source.
|
||||
const plt: StackFrame = {
|
||||
id: 0,
|
||||
name: "atoi@plt",
|
||||
path: null,
|
||||
line: 0,
|
||||
column: 0,
|
||||
presentationHint: null,
|
||||
instructionPointerReference: "0x555555555090",
|
||||
};
|
||||
ipc.debugStackTrace.mockResolvedValue(ipc.ok([plt, frame(5, 1)]));
|
||||
markInstructionStep(1, true);
|
||||
stopped();
|
||||
await settle();
|
||||
expect(useDebug.getState().sessions[1]?.selectedFrame).toBe(0);
|
||||
expect(useExecutionPoint.getState().path).toBeNull();
|
||||
// Only that stop: the next (a line step, a breakpoint) selects the first frame with source again.
|
||||
stopped();
|
||||
await settle();
|
||||
expect(useDebug.getState().sessions[1]?.selectedFrame).toBe(1);
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 5 });
|
||||
});
|
||||
|
||||
it("keeps a failed stack trace's reason for the frames list, and a retry loads the frames", async () => {
|
||||
const error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
ipc.debugStackTrace.mockResolvedValueOnce({
|
||||
|
||||
@@ -56,6 +56,7 @@ import { refreshMemory, useMemory } from "./memory/memoryState";
|
||||
import { closeInstances, instancesOutdated, showInstances, showReferrers, useInstances } from "./memory/instancesState";
|
||||
import { jumpToClass } from "./memory/jumpToClass";
|
||||
import { revealMemoryView, showMemoryAt } from "./memoryView/memoryViewState";
|
||||
import { revealDisassembly } from "./disassembly/disassemblyState";
|
||||
import { captureHeap } from "./heap/heapState";
|
||||
import { stopRecording, traceStreamChain } from "./streams/streamState";
|
||||
import { isTracing, useStreamTrace } from "./streams/streamStore";
|
||||
@@ -80,11 +81,13 @@ import {
|
||||
evaluate,
|
||||
isLive,
|
||||
justDetached,
|
||||
markInstructionStep,
|
||||
pausedThread,
|
||||
rerunSession,
|
||||
revealFrame,
|
||||
rootOf,
|
||||
selectedFrame,
|
||||
selectFrame,
|
||||
sessionSupports,
|
||||
showExecutionPoint,
|
||||
startBrowserSession,
|
||||
@@ -200,6 +203,20 @@ function viewMemory(reference: unknown) {
|
||||
toolWindowService().show("debug", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show Disassembly: the Disassembly view, at the frame `frameId` (from the Frames list) when given,
|
||||
* otherwise at the selected frame. Adapters without `disassemble` say so instead.
|
||||
*/
|
||||
function showDisassembly(frameId: unknown) {
|
||||
const s = activeSession();
|
||||
if (!s || !isLive(s)) return;
|
||||
if (!sessionSupports("disassemble", s)) return notSupported("Disassembly", s);
|
||||
if (typeof frameId === "number" && s.status === "paused" && s.frames.some((f) => f.id === frameId))
|
||||
selectFrame(s.id, frameId, false);
|
||||
revealDisassembly();
|
||||
toolWindowService().show("debug", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Smart Step Into: the calls on the current line, picked in the editor (the
|
||||
* dialog when they cannot be placed); one call (or none) steps straight in, like IDEA.
|
||||
@@ -524,6 +541,30 @@ export function registerDebugActions(): () => void {
|
||||
},
|
||||
});
|
||||
|
||||
// Its stop selects the frame that holds the program counter, also one without source.
|
||||
const stepInstruction = (id: string, title: string, kind: "over" | "into", icon: string): Action => ({
|
||||
id,
|
||||
title,
|
||||
category: "Debug",
|
||||
icon,
|
||||
keywords: ["instruction", "assembly", "disassembly", "machine code"],
|
||||
when: paused,
|
||||
run: () => {
|
||||
const t = pausedTarget();
|
||||
if (!t) return;
|
||||
if (!sessionSupports("instructionStepping", t.s)) return notSupported(title, t.s);
|
||||
markInstructionStep(t.s.id, true);
|
||||
const sent = resumeExecution(t.s.id, () => call(commands.debugStepInstruction(t.s.id, t.thread, kind)));
|
||||
void report(
|
||||
title,
|
||||
sent.catch((e: unknown) => {
|
||||
markInstructionStep(t.s.id, false);
|
||||
throw e;
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return registerActions([
|
||||
{
|
||||
id: "debug.pluginStart",
|
||||
@@ -920,6 +961,17 @@ export function registerDebugActions(): () => void {
|
||||
step("debug.stepOver", "Step Over", "over", "step-over"),
|
||||
step("debug.stepInto", "Step Into", "into", "step-into"),
|
||||
step("debug.stepOut", "Step Out", "out", "step-out"),
|
||||
stepInstruction("debug.stepOverInstruction", "Step Over Instruction", "over", "step-over"),
|
||||
stepInstruction("debug.stepIntoInstruction", "Step Into Instruction", "into", "step-into"),
|
||||
{
|
||||
// The Frames list passes the frame; without one, the selected frame.
|
||||
id: "debug.showDisassembly",
|
||||
title: "Show Disassembly",
|
||||
category: "Debug",
|
||||
keywords: ["assembly", "instructions", "machine code", "asm", "program counter"],
|
||||
when: "debugSessionActive",
|
||||
run: ({ arg }) => showDisassembly(arg),
|
||||
},
|
||||
{
|
||||
id: "debug.forceStepOver",
|
||||
title: "Force Step Over",
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.frame {
|
||||
margin-left: var(--space-2);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-subtle);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
}
|
||||
|
||||
.note,
|
||||
.error {
|
||||
flex: none;
|
||||
padding: 4px 12px;
|
||||
font-size: var(--fs-ui);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.note {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.error {
|
||||
color: var(--fg);
|
||||
background: var(--bg-feedback-error);
|
||||
border-bottom-color: var(--border-feedback-error);
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* Every column is in the code font, so addresses, bytes and instructions line up from row to row. */
|
||||
.grid {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 4px 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
line-height: var(--lh-code);
|
||||
white-space: pre;
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.dimmed {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2ch;
|
||||
padding: 0 12px 0 4px;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
}
|
||||
.head {
|
||||
position: sticky;
|
||||
top: -4px;
|
||||
color: var(--fg-subtle);
|
||||
background: var(--bg-app);
|
||||
}
|
||||
.row:not(.head, .symbol):hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.marker {
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
width: 12px;
|
||||
flex: none;
|
||||
color: var(--accent);
|
||||
}
|
||||
.address {
|
||||
color: var(--fg-subtle);
|
||||
min-width: 18ch;
|
||||
}
|
||||
.bytes {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
/* Disassemblers align operands with runs of spaces. */
|
||||
.instruction {
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.symbol {
|
||||
padding-top: 4px;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.symbolName {
|
||||
padding-left: calc(12px + 2ch);
|
||||
}
|
||||
|
||||
.current {
|
||||
color: var(--fg-strong);
|
||||
background: var(--bg-selected);
|
||||
}
|
||||
.current:hover {
|
||||
background: var(--bg-selected);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/** Disassembly tab of the Debug tool window: the selected frame's machine code around its program counter. */
|
||||
import { Fragment, useEffect, useMemo, useRef } from "react";
|
||||
import clsx from "clsx";
|
||||
import { EmptyState, Icon, IconButton, T } from "@/ui";
|
||||
import { formatMessage, useTx } from "@/platform/i18n";
|
||||
import type { Instruction } from "@/platform/ipc";
|
||||
import { formatAddress, parseAddress } from "../memoryView/bytes";
|
||||
import { selectedFrame, sessionSupports, type DebugSession } from "../state";
|
||||
import { readInstructions, sameAddress, showInstructionsAt, useDisassembly } from "./disassemblyState";
|
||||
import styles from "./DisassemblyPane.module.css";
|
||||
|
||||
const NONE: Instruction[] = [];
|
||||
|
||||
/** `488b45d8` (GDB) or `48 8b 45 d8` (lldb-dap) as `48 8B 45 D8`. */
|
||||
export function spacedBytes(hex: string | null | undefined): string {
|
||||
return (hex ?? "").replace(/\s+/g, "").toUpperCase().match(/../g)?.join(" ") ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The instruction with its mnemonic padded to one width: lldb-dap pads the mnemonic and operands
|
||||
* of each instruction differently (` ldur x1, …`, ` mov x9, sp`).
|
||||
*/
|
||||
export function instructionText(text: string): string {
|
||||
return text.trim().replace(/^(\S+)\s+/, (_, mnemonic: string) => `${mnemonic.padEnd(7)} `);
|
||||
}
|
||||
|
||||
/** The instruction's address in the address column (the adapter's text when it is not a number). */
|
||||
function addressText(i: Instruction, width: number): string {
|
||||
const a = parseAddress(i.address);
|
||||
return a === null ? i.address : formatAddress(a, width);
|
||||
}
|
||||
|
||||
export function DisassemblyPane({ session }: { session: DebugSession }) {
|
||||
const tx = useTx();
|
||||
const id = session.id;
|
||||
const entry = useDisassembly((s) => s.bySession[id]);
|
||||
const paused = session.status === "paused";
|
||||
const frame = paused ? selectedFrame(session) : null;
|
||||
const pc = frame?.instructionPointerReference ?? null;
|
||||
|
||||
// Stepping and frame selection move the program counter: the view follows it.
|
||||
useEffect(() => {
|
||||
if (paused && pc) void showInstructionsAt(id, pc);
|
||||
}, [id, paused, pc]);
|
||||
|
||||
const instructions = entry?.instructions ?? NONE;
|
||||
const width = useMemo(
|
||||
() => (instructions.some((i) => (parseAddress(i.address) ?? 0n) > 0xffffffffn) ? 16 : 8),
|
||||
[instructions],
|
||||
);
|
||||
// As wide as the longest machine code shown, so every row's instruction starts in the same column.
|
||||
const bytesWidth = useMemo(
|
||||
() => ({ minWidth: `${Math.max(5, ...instructions.map((i) => spacedBytes(i.bytes).length))}ch` }),
|
||||
[instructions],
|
||||
);
|
||||
const current = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
current.current?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [pc, instructions]);
|
||||
|
||||
const stepping = sessionSupports("instructionStepping", session);
|
||||
const noStepping = stepping
|
||||
? undefined
|
||||
: formatMessage(tx("Instruction stepping is not supported by {adapter}"), {
|
||||
adapter: session.adapter || tx("this debugger"),
|
||||
});
|
||||
const busy = !!entry?.loading;
|
||||
|
||||
return (
|
||||
<div className={styles.root} aria-busy={busy || undefined}>
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Disassembly")}>
|
||||
<IconButton
|
||||
icon="step-over"
|
||||
action="debug.stepOverInstruction"
|
||||
title={noStepping}
|
||||
aria-label="Step Over Instruction"
|
||||
size="small"
|
||||
disabled={!paused || !stepping}
|
||||
/>
|
||||
<IconButton
|
||||
icon="step-into"
|
||||
action="debug.stepIntoInstruction"
|
||||
title={noStepping}
|
||||
aria-label="Step Into Instruction"
|
||||
size="small"
|
||||
disabled={!paused || !stepping}
|
||||
/>
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Refresh"
|
||||
size="small"
|
||||
disabled={!paused || !pc || busy}
|
||||
onClick={() => pc && void readInstructions(id, pc)}
|
||||
/>
|
||||
{frame && <span className={styles.frame}>{frame.name}</span>}
|
||||
</div>
|
||||
{!paused && (
|
||||
<div className={styles.note} role="status">
|
||||
<T>Instructions are shown while the program is paused.</T>
|
||||
</div>
|
||||
)}
|
||||
{paused && frame && !pc && (
|
||||
<div className={styles.note} role="status">
|
||||
<T>The debugger gives no instruction address for this frame.</T>
|
||||
</div>
|
||||
)}
|
||||
{entry?.error && (
|
||||
<div className={styles.error} role="alert">
|
||||
{entry.error}
|
||||
</div>
|
||||
)}
|
||||
{instructions.length > 0 ? (
|
||||
<div className={clsx(styles.grid, !paused && styles.dimmed)} role="grid" aria-label={tx("Disassembly")}>
|
||||
<div className={clsx(styles.row, styles.head)} role="row">
|
||||
<span className={styles.marker} />
|
||||
<span role="columnheader" className={styles.address}>
|
||||
{tx("Address")}
|
||||
</span>
|
||||
<span role="columnheader" className={styles.bytes} style={bytesWidth}>
|
||||
{tx("Bytes")}
|
||||
</span>
|
||||
<span role="columnheader" className={styles.instruction}>
|
||||
{tx("Instruction")}
|
||||
</span>
|
||||
</div>
|
||||
{instructions.map((i, n) => {
|
||||
const isPc = !!pc && paused && sameAddress(i.address, pc);
|
||||
const symbol = i.symbol && i.symbol !== instructions[n - 1]?.symbol ? i.symbol : null;
|
||||
return (
|
||||
<Fragment key={i.address}>
|
||||
{symbol && (
|
||||
<div className={clsx(styles.row, styles.symbol)} role="row">
|
||||
<span role="gridcell" className={styles.symbolName}>
|
||||
{symbol}:
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={isPc ? current : undefined}
|
||||
className={clsx(styles.row, isPc && styles.current)}
|
||||
role="row"
|
||||
aria-current={isPc ? "location" : undefined}
|
||||
>
|
||||
<span className={styles.marker} aria-hidden>
|
||||
{isPc && <Icon name="arrow-right" size={12} />}
|
||||
</span>
|
||||
<span role="rowheader" className={styles.address}>
|
||||
{addressText(i, width)}
|
||||
</span>
|
||||
<span role="gridcell" className={styles.bytes} style={bytesWidth}>
|
||||
{spacedBytes(i.bytes)}
|
||||
</span>
|
||||
<span role="gridcell" className={styles.instruction}>
|
||||
{instructionText(i.instruction)}
|
||||
</span>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
!entry?.error &&
|
||||
!busy &&
|
||||
paused &&
|
||||
!!pc && (
|
||||
<div className={styles.empty}>
|
||||
<EmptyState title="Disassembly">
|
||||
<T>No instructions at this address.</T>
|
||||
</EmptyState>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/** Disassembly view (DAP `disassemble`): the instructions each session's view shows, and reading them. */
|
||||
import { create } from "zustand";
|
||||
import { call, commands, type DebugSessionId, type Instruction } from "@/platform/ipc";
|
||||
import { parseAddress } from "../memoryView/bytes";
|
||||
import { useDebug } from "../state";
|
||||
|
||||
/** Instructions read ahead of the program counter (adapters that cannot go back start at it), and in all. */
|
||||
export const BEFORE = 32;
|
||||
export const COUNT = 128;
|
||||
|
||||
export interface DisassemblyEntry {
|
||||
instructions: Instruction[];
|
||||
/** The instruction pointer the last read was for. */
|
||||
reference: string | null;
|
||||
error: string | null;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
interface DisassemblyState {
|
||||
bySession: Record<DebugSessionId, DisassemblyEntry>;
|
||||
/** Set by Show Disassembly until the Debug tool window has brought the Disassembly view to the front. */
|
||||
revealPending: boolean;
|
||||
}
|
||||
|
||||
export const useDisassembly = create<DisassemblyState>(() => ({ bySession: {}, revealPending: false }));
|
||||
|
||||
const emptyEntry = (): DisassemblyEntry => ({ instructions: [], reference: null, error: null, loading: false });
|
||||
|
||||
/** The read each session waits for; a newer one (or `forgetDisassembly`) makes an older reply stale. */
|
||||
const inflight = new Map<DebugSessionId, symbol>();
|
||||
|
||||
function patchEntry(id: DebugSessionId, patch: Partial<DisassemblyEntry>) {
|
||||
useDisassembly.setState((s) => ({
|
||||
bySession: { ...s.bySession, [id]: { ...(s.bySession[id] ?? emptyEntry()), ...patch } },
|
||||
}));
|
||||
}
|
||||
|
||||
/** Whether `a` and `b` are the same address (`0x00401000` and `0x401000`). */
|
||||
export function sameAddress(a: string, b: string): boolean {
|
||||
const x = parseAddress(a);
|
||||
return x === null ? a === b : x === parseAddress(b);
|
||||
}
|
||||
|
||||
/** Reads the instructions around `pc`, whatever is shown. */
|
||||
export async function readInstructions(id: DebugSessionId, pc: string): Promise<void> {
|
||||
const session = useDebug.getState().sessions[id];
|
||||
if (!session || session.status !== "paused") return;
|
||||
const token = Symbol("disassembly");
|
||||
inflight.set(id, token);
|
||||
patchEntry(id, { reference: pc, loading: true });
|
||||
try {
|
||||
const instructions = await call(commands.debugDisassemble(id, pc, BEFORE, COUNT));
|
||||
if (inflight.get(id) !== token) return;
|
||||
patchEntry(id, { instructions, error: null });
|
||||
} catch (e) {
|
||||
if (inflight.get(id) !== token) return;
|
||||
patchEntry(id, { instructions: [], error: e instanceof Error ? e.message : String(e) });
|
||||
} finally {
|
||||
if (inflight.get(id) === token) {
|
||||
inflight.delete(id);
|
||||
patchEntry(id, { loading: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the instructions around `pc`, the selected frame's instruction pointer. Instructions already
|
||||
* shown stay when they hold it, so the highlight moves through them while stepping; a failed read is
|
||||
* not repeated for the same `pc` (Refresh does that).
|
||||
*/
|
||||
export function showInstructionsAt(id: DebugSessionId, pc: string): Promise<void> {
|
||||
const entry = useDisassembly.getState().bySession[id];
|
||||
if (entry?.instructions.some((i) => sameAddress(i.address, pc))) return Promise.resolve();
|
||||
if (entry?.reference === pc && (entry.loading || entry.error)) return Promise.resolve();
|
||||
return readInstructions(id, pc);
|
||||
}
|
||||
|
||||
export function revealDisassembly(): void {
|
||||
useDisassembly.setState({ revealPending: true });
|
||||
}
|
||||
|
||||
/** The Debug tool window shows the Disassembly view: the request is done. */
|
||||
export function disassemblyRevealed(): void {
|
||||
useDisassembly.setState({ revealPending: false });
|
||||
}
|
||||
|
||||
export function forgetDisassembly(id: DebugSessionId): void {
|
||||
inflight.delete(id);
|
||||
useDisassembly.setState((s) => {
|
||||
if (!(id in s.bySession)) return s;
|
||||
const { [id]: _gone, ...rest } = s.bySession;
|
||||
return { bySession: rest };
|
||||
});
|
||||
}
|
||||
@@ -56,6 +56,7 @@ import { streamTraceKind } from "./streams/streamTraceKind";
|
||||
import { installHeapContext } from "./heap/heapDumpFiles";
|
||||
import { forgetMemory } from "./memory/memoryState";
|
||||
import { forgetMemoryView } from "./memoryView/memoryViewState";
|
||||
import { forgetDisassembly } from "./disassembly/disassemblyState";
|
||||
import { closeStaleStreamChooser, forgetStreamTrace } from "./streams/streamState";
|
||||
|
||||
/** Whether a breakpoint popover, debugger dialog or chooser is open. */
|
||||
@@ -177,6 +178,7 @@ export function activate(): () => void {
|
||||
if (id in s.sessions) continue;
|
||||
forgetMemory(Number(id));
|
||||
forgetMemoryView(Number(id));
|
||||
forgetDisassembly(Number(id));
|
||||
forgetInstances(Number(id));
|
||||
forgetHeapCapture(Number(id));
|
||||
forgetStreamTrace(Number(id));
|
||||
|
||||
@@ -1278,8 +1278,18 @@ export function topFrame(frames: StackFrame[]): StackFrame | null {
|
||||
return frames.find((f) => f.path && f.presentationHint !== "label") ?? frames[0] ?? null;
|
||||
}
|
||||
|
||||
/** Sessions whose next stop ends an instruction step: it selects the frame that holds the program counter. */
|
||||
const instructionSteps = new Set<DebugSessionId>();
|
||||
|
||||
/** The step about to be sent moves by one instruction (`false`: it was not sent after all). */
|
||||
export function markInstructionStep(id: DebugSessionId, on: boolean) {
|
||||
if (on) instructionSteps.add(id);
|
||||
else instructionSteps.delete(id);
|
||||
}
|
||||
|
||||
function markTerminated(id: DebugSessionId) {
|
||||
stopTaskbarFlash();
|
||||
instructionSteps.delete(id);
|
||||
forgetImports(id);
|
||||
const page = serverPages.get(id)?.page;
|
||||
if (serverPages.delete(id) && page != null) void stopSession(page);
|
||||
@@ -1333,8 +1343,11 @@ export function selectFrame(id: DebugSessionId, frameId: number, reveal = true)
|
||||
void loadLocals(id, frameId);
|
||||
}
|
||||
|
||||
/** `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened. */
|
||||
async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true) {
|
||||
/**
|
||||
* `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened.
|
||||
* `exact`: select the innermost frame even without source (after an instruction step into a library).
|
||||
*/
|
||||
async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true, exact = false) {
|
||||
if (useDebug.getState().sessions[id]?.framesError) patch(id, { framesError: null });
|
||||
const before = useDebug.getState().sessions[id];
|
||||
let frames: StackFrame[] = [];
|
||||
@@ -1348,7 +1361,7 @@ async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean,
|
||||
const s = useDebug.getState().sessions[id];
|
||||
if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return;
|
||||
patch(id, { frames, framesError });
|
||||
const top = topFrame(frames);
|
||||
const top = exact ? (frames[0] ?? null) : topFrame(frames);
|
||||
if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) {
|
||||
void logSuspendingHit(id, top);
|
||||
consumeTemporary(top.path, top.line);
|
||||
@@ -1646,7 +1659,13 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
|
||||
updateExecutionPoint();
|
||||
void loadThreads(id);
|
||||
// The stop a stream trace ends in would bring the source tab over the trace tab that shows its result.
|
||||
void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1));
|
||||
void loadFrames(
|
||||
id,
|
||||
event.threadId,
|
||||
!markTraceStop(id, event.threadId, s.stops + 1),
|
||||
true,
|
||||
instructionSteps.delete(id),
|
||||
);
|
||||
const dbg = workflowSettings().debugger;
|
||||
try {
|
||||
// A session debugged in place from Services shows its debugger there (#4773).
|
||||
|
||||
@@ -61,6 +61,8 @@ import { pageProfileItems, useJsProfile } from "../js/profile";
|
||||
import { MemoryView } from "../memory/MemoryView";
|
||||
import { MemoryViewPane } from "../memoryView/MemoryViewPane";
|
||||
import { memoryViewRevealed, useMemoryView } from "../memoryView/memoryViewState";
|
||||
import { DisassemblyPane } from "../disassembly/DisassemblyPane";
|
||||
import { disassemblyRevealed, useDisassembly } from "../disassembly/disassemblyState";
|
||||
import { DebugConsole } from "./DebugConsole";
|
||||
import { VariablesView, type VarRoot } from "./VariablesView";
|
||||
import { useExpressionCompletion } from "./ExpressionCompletion";
|
||||
@@ -131,7 +133,7 @@ function MoreActions() {
|
||||
);
|
||||
}
|
||||
|
||||
type Tab = "variables" | "console" | "memory" | "memoryView" | "network";
|
||||
type Tab = "variables" | "console" | "memory" | "memoryView" | "disassembly" | "network";
|
||||
|
||||
/** The view the user last picked; the tool window opens on it again (Console until one is picked). */
|
||||
let chosenTab: Tab = "console";
|
||||
@@ -230,7 +232,11 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
|
||||
}>(() => ({
|
||||
session: undefined,
|
||||
status: undefined,
|
||||
tab: useMemoryView.getState().revealPending ? "memoryView" : chosenTab,
|
||||
tab: useDisassembly.getState().revealPending
|
||||
? "disassembly"
|
||||
: useMemoryView.getState().revealPending
|
||||
? "memoryView"
|
||||
: chosenTab,
|
||||
}));
|
||||
// View Memory brings the Memory View to the front, also in the tool window it opens (above).
|
||||
useEffect(() => {
|
||||
@@ -243,19 +249,31 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
|
||||
reveal(useMemoryView.getState().revealPending, true);
|
||||
return useMemoryView.subscribe((s) => reveal(s.revealPending, false));
|
||||
}, []);
|
||||
// Show Disassembly does the same for the Disassembly view.
|
||||
useEffect(() => {
|
||||
const reveal = (pending: boolean, shown: boolean) => {
|
||||
if (!pending) return;
|
||||
disassemblyRevealed();
|
||||
chosenTab = "disassembly";
|
||||
if (!shown) setView((v) => (v.tab === "disassembly" ? v : { ...v, tab: "disassembly" }));
|
||||
};
|
||||
reveal(useDisassembly.getState().revealPending, true);
|
||||
return useDisassembly.subscribe((s) => reveal(s.revealPending, false));
|
||||
}, []);
|
||||
if (active && (view.session !== active.startedAt || view.status !== active.status))
|
||||
setView({
|
||||
session: active.startedAt,
|
||||
status: active.status,
|
||||
// A breakpoint or exception brings Threads & Variables to the front unless its Focus On Breakpoint
|
||||
// is off; finishing a step keeps the tab the user is on (e.g. Console, to watch the output while
|
||||
// stepping), and so do Memory and the Memory View.
|
||||
// stepping), and so do Memory, the Memory View and the Disassembly view.
|
||||
tab:
|
||||
active.status === "starting"
|
||||
? "console"
|
||||
: active.status === "paused" &&
|
||||
view.tab !== "memory" &&
|
||||
view.tab !== "memoryView" &&
|
||||
view.tab !== "disassembly" &&
|
||||
active.stopReason !== "step" &&
|
||||
workflowSettings().debugger.variablesOnBreakpoint
|
||||
? "variables"
|
||||
@@ -267,10 +285,13 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
|
||||
const hasNetwork = !!active && sessionSupports("jsPage", active);
|
||||
// The native Memory View follows the adapter's `readMemory` support.
|
||||
const hasMemoryView = !!active && sessionSupports("readMemory", active);
|
||||
// The selected session may be one without the Memory, Memory View or Network tab.
|
||||
// So does the Disassembly view, its `disassemble` support.
|
||||
const hasDisassembly = !!active && sessionSupports("disassemble", active);
|
||||
// The selected session may be one without the Memory, Memory View, Disassembly or Network tab.
|
||||
const tab: Tab =
|
||||
(view.tab === "memory" && !hasMemory) ||
|
||||
(view.tab === "memoryView" && !hasMemoryView) ||
|
||||
(view.tab === "disassembly" && !hasDisassembly) ||
|
||||
(view.tab === "network" && !hasNetwork)
|
||||
? "variables"
|
||||
: view.tab;
|
||||
@@ -332,6 +353,7 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
|
||||
["console", "Console"],
|
||||
...(hasMemory ? [["memory", "Memory"] as const] : []),
|
||||
...(hasMemoryView ? [["memoryView", "Memory View"] as const] : []),
|
||||
...(hasDisassembly ? [["disassembly", "Disassembly"] as const] : []),
|
||||
...(hasNetwork ? [["network", "Network"] as const] : []),
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
@@ -382,6 +404,8 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
|
||||
)
|
||||
) : tab === "memoryView" ? (
|
||||
<MemoryViewPane key={active.id} session={active} />
|
||||
) : tab === "disassembly" ? (
|
||||
<DisassemblyPane key={active.id} session={active} />
|
||||
) : tab === "network" ? (
|
||||
<NetworkView key={active.id} session={active.id} />
|
||||
) : (
|
||||
@@ -561,6 +585,15 @@ function FramesPane({ session }: { session: DebugSession }) {
|
||||
disabled: !paused || !sessionSupports("restartFrame", session),
|
||||
run: () => void executeAction("debug.resetFrame"),
|
||||
},
|
||||
...(sessionSupports("disassemble", session)
|
||||
? [
|
||||
{
|
||||
label: "Show Disassembly",
|
||||
disabled: !paused || !item.frame.instructionPointerReference,
|
||||
run: () => void executeAction("debug.showDisassembly", item.frame.id),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: showAll ? "Hide Library Frames" : "Show All Frames",
|
||||
|
||||
@@ -4670,5 +4670,15 @@
|
||||
"Memory is read while the program is paused.": "Memory is read while the program is paused.",
|
||||
"The memory at {address} cannot be read.": "The memory at {address} cannot be read.",
|
||||
"Enter an address or an expression, or choose View Memory on a variable.": "Enter an address or an expression, or choose View Memory on a variable.",
|
||||
"“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0]."
|
||||
"“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].",
|
||||
"Disassembly": "Disassembly",
|
||||
"Show Disassembly": "Show Disassembly",
|
||||
"Step Over Instruction": "Step Over Instruction",
|
||||
"Step Into Instruction": "Step Into Instruction",
|
||||
"Instruction stepping is not supported by {adapter}": "Instruction stepping is not supported by {adapter}",
|
||||
"this debugger": "this debugger",
|
||||
"Instructions are shown while the program is paused.": "Instructions are shown while the program is paused.",
|
||||
"The debugger gives no instruction address for this frame.": "The debugger gives no instruction address for this frame.",
|
||||
"Bytes": "Bytes",
|
||||
"No instructions at this address.": "No instructions at this address."
|
||||
}
|
||||
@@ -11260,5 +11260,15 @@
|
||||
"Memory is read while the program is paused.": "程序暂停时才会读取内存。",
|
||||
"The memory at {address} cannot be read.": "无法读取 {address} 处的内存。",
|
||||
"Enter an address or an expression, or choose View Memory on a variable.": "输入地址或表达式,或在变量上选择“查看内存”。",
|
||||
"“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}”不是地址。请输入指针或地址,例如 &buffer[0]。"
|
||||
"“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}”不是地址。请输入指针或地址,例如 &buffer[0]。",
|
||||
"Disassembly": "反汇编",
|
||||
"Show Disassembly": "显示反汇编",
|
||||
"Step Over Instruction": "单步跳过指令",
|
||||
"Step Into Instruction": "单步进入指令",
|
||||
"Instruction stepping is not supported by {adapter}": "{adapter} 不支持按指令单步执行",
|
||||
"this debugger": "此调试器",
|
||||
"Instructions are shown while the program is paused.": "程序暂停时才会显示指令。",
|
||||
"The debugger gives no instruction address for this frame.": "调试器没有提供此帧的指令地址。",
|
||||
"Bytes": "字节",
|
||||
"No instructions at this address.": "此地址没有指令。"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача