diff --git a/CHANGELOG.md b/CHANGELOG.md index 719bf07..220e73b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to the Simics Target Debug extension will be documented here ## [Unreleased] +### Added + +- The Call Stack view shows the run control context hierarchy: each context + with child contexts, such as a process of the Linux tracker, is a nested + session with its threads. Turn it off with `"callStackHierarchy": false`. + `"callStackCompact": false` gives every context a row of its own. + Containers with a single thread, such as most processes, show the thread in + the session above. + ### Changed - In TCF Launch Configurations, the Start, Duplicate and Delete buttons diff --git a/README.md b/README.md index 29b0ba3..6e860f5 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ and translates DAP requests to TCF commands: | VS Code (DAP) | TCF | |--------------------------|------------------------------------------------------------| | attach | TCP connection + `Locator.Hello` | -| threads | `RunControl` contexts with `HasState` | +| threads | `RunControl` contexts with `HasState`, grouped in a session per container context, see below | | pause / continue | `RunControl.suspend` / `RunControl.resume` | | step over / into / out | `RunControl.resume` with a step mode, see below | | stopped / continued | `contextSuspended`, `containerSuspended`, `contextResumed`, `containerResumed` events | @@ -66,6 +66,81 @@ resume or step. ### Call stack +The Call Stack view shows the parts of the target that can run and be +stopped: processors and, with OS awareness, the processes and threads of the +operating system. They are shown as a tree that follows the structure of the +target. Parts with several threads, such as a board with several CPUs, an OS +awareness tracker or a multi-threaded process, are shown as groups that can +be expanded. Expand a thread to see its call stack. + +To keep the tree short: + +- Only parts with at least two threads get a group. A part with a single + thread, such as most Linux processes, gets no group: its thread is listed + in the group above. +- A thread listed in a group above is named by the parts in between, so + thread `worker` of process `p3` is listed as `p3.worker`. A repeated name, + such as process `init` with thread `init`, is shown once. +- If a group would hold only one thread next to other groups, that thread + gets a row of its own, with its call stack right below it. + +In a group, the threads are listed first, then the single threads with rows +of their own, then the other groups, each in the order of the target. + +For example, take this target with a Linux OS awareness tracker, with +simplified names: + +```text +Linux +├── Kernel +│ ├── Other ── core[0][0] +│ ├── Idle ──┬── core[0][0] +│ │ └── core[1][0] +│ └── Threads ──┬── kthreadd +│ └── kworker/0:0 +└── Userspace ──┬── init ── init + ├── rc ── rc + └── udevd ── udevd +``` + +The Call Stack view shows it like this: + +```text +Linux group, in the row of the debug configuration +├── Kernel group +│ ├── Other.core[0][0] single thread with a row of its own +│ ├── Idle group +│ │ ├── core[0][0] thread +│ │ └── core[1][0] thread +│ └── Threads group +│ ├── kthreadd thread +│ └── kworker/0:0 thread +└── Userspace group + ├── init thread + ├── rc thread + └── udevd thread +``` + +`Other` and the processes in `Userspace` have a single thread each, so they +get no group. The thread of `Other` is next to the groups `Idle` and +`Threads`, so it gets a row of its own. + +Groups come and go as processes and threads start and end. All groups share +the breakpoints and the Debug Console. Stopping or restarting any of them +stops or restarts the whole debug session. + +Two options change the layout. You find them under **Advanced** in the +launch configurations editor: + +- `"callStackHierarchy": false` shows no groups. All threads are listed + directly under the debug configuration, named by all the parts above them, + like `board.cpu0`. In the example, the threads are named + `Linux.Kernel.Idle.core[0][0]`, `Linux.Userspace.init.init` and so on. +- `"callStackCompact": false` gives every group a row of its own. By default, + a group that is alone in its parent shares the parent's row and shows its + own name only, like `Linux` in the example. With `false`, the name of the + debug configuration gets a row of its own above `Linux`. + The call stack of a suspended thread comes from the `StackTrace` service. VS Code first loads the top frame and then the rest in pages ("Load More Stack Frames"), which uses `getChildrenRange`; agents without it fall back to @@ -392,6 +467,8 @@ Configuration attributes: | `traceTcf` | `false` | Log TCF messages to Output › Simics Target Debug | | `traceTcfSilence` | see below | TCF messages left out of the `traceTcf` log | | `disassemblyFunctionHeaders` | `true` | Function header rows in the Disassembly view | +| `callStackHierarchy` | `true` | A nested session per container context in the Call Stack view | +| `callStackCompact` | `true` | Contexts that are the only child share a row with their parent | ### TCF trace @@ -448,8 +525,8 @@ buttons in the editor title switch between the form and the text of - The fields come from `configurationAttributes` in `package.json`, so new attributes appear without changes to the form. Of VS Code's own options only `internalConsoleOptions` (when to open the Debug Console) is shown, - under **Advanced** at the end, with `connectTimeout`, - `disassemblyFunctionHeaders`, `traceTcf` and `traceTcfSilence`. The Simics console options + under **Advanced** at the end, with `connectTimeout`, `callStackHierarchy`, + `callStackCompact`, `disassemblyFunctionHeaders`, `traceTcf` and `traceTcfSilence`. The Simics console options and **Stay in Console** are under **Console**, just before **Advanced**. Others, like `preLaunchTask`, are listed under **Other Attributes** when set, and can be @@ -660,6 +737,11 @@ on the agent (for example with `add-pathmap-entry`). debug type. - `src/tcfDebugSession.ts` – DAP implementation (no `vscode` dependency, so it can also be run as a standalone debug adapter later). +- `src/contextSession.ts` – adapter of the child sessions that show the + threads of a container context; passes requests on to the root session's + adapter. +- `src/contextSessionManager.ts` – starts the child sessions in VS Code and + maps them to their root session for the extension's views and commands. - `src/breakpointManager.ts` – keeps the agent's breakpoint table in sync with VS Code. - `src/variables.ts` – local variables and expressions through the diff --git a/package.json b/package.json index c827584..19a2d93 100644 --- a/package.json +++ b/package.json @@ -917,6 +917,16 @@ "type": "boolean", "description": "Show a header row with source file, line and name above the first instruction of each function in the Disassembly view. Needs the agent's Symbols service and the setting debug.disassemblyView.showSourceCode. Turn off to save the symbol lookups.", "default": true + }, + "callStackHierarchy": { + "type": "boolean", + "description": "Show the run control context hierarchy in the Call Stack view: each context with child contexts and two or more threads (for example a multi-threaded process of an OS awareness tracker) becomes a nested session that holds its threads. Turn off to list all threads directly under the debug session, with their full names.", + "default": true + }, + "callStackCompact": { + "type": "boolean", + "description": "With callStackHierarchy, let VS Code show a context in one row with its parent when it is the parent's only child. The row shows the name of the innermost context only. Turn off to give every context a row of its own, below a row for the debug session.", + "default": true } } } diff --git a/src/contextSession.ts b/src/contextSession.ts new file mode 100644 index 0000000..e8cc09a --- /dev/null +++ b/src/contextSession.ts @@ -0,0 +1,93 @@ +import { DebugSession, InitializedEvent, Response, TerminatedEvent } from "@vscode/debugadapter"; +import { DebugProtocol } from "@vscode/debugprotocol"; +import { ContextSessionLink, ContextSessionSink, TCF_CAPABILITIES } from "./tcfDebugSession"; + +/** Connects a child session to its group in the root adapter, undefined if the group is gone. */ +export type ContextSessionConnector = (sink: ContextSessionSink) => ContextSessionLink | undefined; + +/** + * Debug adapter of a child session that shows the threads of one container + * context (see ContextSessionHost). The root adapter does the work: thread, + * frame and variable IDs are the root's, so requests are passed on as they + * are. Breakpoints are only planted by the root session. + */ +export class TcfContextSession extends DebugSession implements ContextSessionSink { + private link: ContextSessionLink | undefined; + private terminated = false; + + constructor(private readonly connect: ContextSessionConnector) { + super(); + } + + terminate(): void { + this.link = undefined; + if (!this.terminated) { + this.terminated = true; + this.sendEvent(new TerminatedEvent()); + } + } + + override sendEvent(event: DebugProtocol.Event): void { + if (event.event === "stopped") { + // The IDs are the root session's. Without them VS Code finds the + // hit breakpoints by the location of the top frame. + const body = { ...(event as DebugProtocol.StoppedEvent).body }; + delete body.hitBreakpointIds; + event = { ...event, body }; + } + super.sendEvent(event); + } + + protected override dispatchRequest(request: DebugProtocol.Request): void { + const response: DebugProtocol.Response = new Response(request); + switch (request.command) { + case "initialize": + response.body = { ...TCF_CAPABILITIES }; + this.sendResponse(response); + return; + case "attach": + case "launch": + this.link = this.connect(this); + this.sendResponse(response); + if (this.link) { + this.sendEvent(new InitializedEvent()); + } else { + this.terminate(); + } + return; + case "configurationDone": + this.sendResponse(response); + this.link?.configured(); + return; + case "threads": + response.body = { threads: this.link?.threads() ?? [] }; + this.sendResponse(response); + return; + case "setBreakpoints": + case "setFunctionBreakpoints": + case "setInstructionBreakpoints": + case "setDataBreakpoints": + // No entries, so VS Code keeps the root session's state for + // each breakpoint. + response.body = { breakpoints: [] }; + this.sendResponse(response); + return; + case "setExceptionBreakpoints": + this.sendResponse(response); + return; + case "disconnect": + case "terminate": + this.link?.disconnect(); + this.link = undefined; + this.terminated = true; + this.sendResponse(response); + return; + } + const link = this.link; + if (!link) { + this.sendErrorResponse(response, 4, "The debug session has ended"); + return; + } + void link.forward(request).then((r) => this.sendResponse({ ...r, seq: 0, request_seq: request.seq })); + } +} diff --git a/src/contextSessionManager.ts b/src/contextSessionManager.ts new file mode 100644 index 0000000..1505c55 --- /dev/null +++ b/src/contextSessionManager.ts @@ -0,0 +1,190 @@ +import * as vscode from "vscode"; +import { TcfContextSession } from "./contextSession"; +import { + ContextGroup, + ContextSessionHost, + ContextSessionLink, + ContextSessionSink, + TcfDebugSession, +} from "./tcfDebugSession"; + +/** Debug configuration attribute of a context session: its root session and group. */ +const CONTEXT_SESSION = "__simicsContextSession"; + +interface ContextSessionConfig { + root: string; + key: string; +} + +function contextSessionConfig(config: vscode.DebugConfiguration): ContextSessionConfig | undefined { + const value = config[CONTEXT_SESSION] as Partial | undefined; + return typeof value?.root === "string" && typeof value.key === "string" + ? { root: value.root, key: value.key } + : undefined; +} + +/** Whether a configuration is that of a context session, which the extension starts. */ +export function isContextSessionConfig(config: vscode.DebugConfiguration): boolean { + return contextSessionConfig(config) !== undefined; +} + +/** Whether a session only shows the threads of a container context. */ +export function isContextSession(session: vscode.DebugSession): boolean { + return isContextSessionConfig(session.configuration); +} + +/** The session that is connected to the agent: `session`, or the root of a context session. */ +export function rootSession(session: vscode.DebugSession | undefined): vscode.DebugSession | undefined { + while (session && isContextSession(session)) { + session = session.parentSession; + } + return session; +} + +/** The root of the active debug session. */ +export function activeRootSession(): vscode.DebugSession | undefined { + return rootSession(vscode.debug.activeDebugSession); +} + +/** + * Shows the container contexts of the agent (for example the processes of + * an OS awareness tracker) as nested sessions in the Call Stack view, with + * the threads of each context in its session. VS Code has no thread + * hierarchy, but it nests child sessions under their parent. + */ +export class ContextSessionManager implements vscode.Disposable { + private readonly roots = new Map(); + private readonly disposable: vscode.Disposable; + + constructor( + private readonly debugType: string, + private readonly log: vscode.LogOutputChannel, + ) { + this.disposable = vscode.debug.onDidTerminateDebugSession((s) => this.roots.delete(s.id)); + } + + /** The adapter of a context session, undefined for other sessions. */ + createContextAdapter(session: vscode.DebugSession): vscode.DebugAdapter | undefined { + const config = contextSessionConfig(session.configuration); + if (!config) { + return undefined; + } + const root = this.roots.get(config.root); + return new TcfContextSession((sink) => root?.connect(config.key, session, sink)); + } + + /** Lets the adapter of a root session start context sessions. */ + addRoot(session: vscode.DebugSession, adapter: TcfDebugSession): void { + const root = new RootSessions(session, adapter, this.debugType, this.log); + this.roots.set(session.id, root); + adapter.setContextSessionHost(root); + } + + dispose(): void { + this.disposable.dispose(); + } +} + +interface GroupEntry { + name: string; + /** The group's session once its adapter is created, undefined if it was not started. */ + session: Promise; + resolve(session: vscode.DebugSession | undefined): void; +} + +/** The context sessions of one root session. */ +class RootSessions implements ContextSessionHost { + private readonly groups = new Map(); + /** + * The last start of a child session, by parent group key ("" for the + * root). VS Code lists child sessions in the order they start, so + * siblings start one at a time, in the order the adapter added them. + */ + private readonly lastStart = new Map>(); + + constructor( + private readonly session: vscode.DebugSession, + private readonly adapter: TcfDebugSession, + private readonly debugType: string, + private readonly log: vscode.LogOutputChannel, + ) {} + + groupAdded(group: ContextGroup): void { + let resolve!: (session: vscode.DebugSession | undefined) => void; + const entry: GroupEntry = { + name: group.name, + session: new Promise((r) => (resolve = r)), + resolve: (s) => resolve(s), + }; + this.groups.set(group.key, entry); + const parent = + group.parentKey === undefined + ? Promise.resolve(this.session) + : (this.groups.get(group.parentKey)?.session ?? Promise.resolve(undefined)); + const siblings = group.parentKey ?? ""; + const previous = this.lastStart.get(siblings) ?? Promise.resolve(); + const start = Promise.all([parent, previous]).then(async ([parentSession]) => { + if (!parentSession || this.groups.get(group.key) !== entry) { + entry.resolve(undefined); + return; + } + try { + const config: vscode.DebugConfiguration = { + type: this.debugType, + request: "attach", + name: entry.name, + [CONTEXT_SESSION]: { root: this.session.id, key: group.key } satisfies ContextSessionConfig, + }; + const started = await vscode.debug.startDebugging(this.session.workspaceFolder, config, { + parentSession, + lifecycleManagedByParent: true, + consoleMode: vscode.DebugConsoleMode.MergeWithParent, + // VS Code shows a compact session in one row with its parent, if it is the parent's + // only child; the row shows the child's name only. + compact: this.session.configuration.callStackCompact !== false, + suppressSaveBeforeStart: true, + suppressDebugView: true, + }); + if (!started) { + entry.resolve(undefined); + } + } catch (err) { + this.log.error(`Cannot start the debug session of ${entry.name}: ${String(err)}`); + entry.resolve(undefined); + } + }); + this.lastStart.set(siblings, start); + void start.finally(() => { + if (this.lastStart.get(siblings) === start) { + this.lastStart.delete(siblings); + } + }); + } + + groupRenamed(key: string, name: string): void { + const entry = this.groups.get(key); + if (entry) { + entry.name = name; + void entry.session.then((s) => { + if (s) { + s.name = name; + } + }); + } + } + + groupRemoved(key: string): void { + // The root adapter ends the session itself. + this.groups.get(key)?.resolve(undefined); + this.groups.delete(key); + } + + /** Connects the adapter of a group's session, created by VS Code. */ + connect(key: string, session: vscode.DebugSession, sink: ContextSessionSink): ContextSessionLink | undefined { + const link = this.adapter.connectContextSession(key, sink); + if (link) { + this.groups.get(key)?.resolve(session); + } + return link; + } +} diff --git a/src/extension.ts b/src/extension.ts index d6c45ea..20bc524 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -28,6 +28,12 @@ import { suggestSymbolPaths } from "./symbolPath"; import { registerConsolesView } from "./consolesView"; import { CONSOLE_AVAILABLE_EVENT, simicsCliOptions } from "./simicsConsole"; import { SimicsConsoleManager } from "./simicsConsoleManager"; +import { + ContextSessionManager, + activeRootSession, + isContextSession, + isContextSessionConfig, +} from "./contextSessionManager"; import { TcfDebugSession, TcfLog } from "./tcfDebugSession"; import { TargetMemoryManager } from "./targetMemory/targetMemoryManager"; @@ -42,6 +48,7 @@ export function activate(context: vscode.ExtensionContext): void { const sessions = new Map(); const sourceLocator = new SourceLocator(); const adapters = new Map(); + const contextSessions = new ContextSessionManager(DEBUG_TYPE, tcfLog); const consoles = new SimicsConsoleManager( DEBUG_TYPE, (session) => adapters.get(session.id)?.tcfChannel, @@ -49,11 +56,17 @@ export function activate(context: vscode.ExtensionContext): void { ); context.subscriptions.push( tcfLog, + contextSessions, vscode.debug.registerDebugConfigurationProvider(DEBUG_TYPE, new TcfConfigurationProvider()), vscode.debug.registerDebugAdapterDescriptorFactory(DEBUG_TYPE, { createDebugAdapterDescriptor: (session) => { + const contextAdapter = contextSessions.createContextAdapter(session); + if (contextAdapter) { + return new vscode.DebugAdapterInlineImplementation(contextAdapter); + } const adapter = new TcfDebugSession(sessionLog(tcfLog, session.name), hasBreakpoint); adapters.set(session.id, adapter); + contextSessions.addRoot(session, adapter); return new vscode.DebugAdapterInlineImplementation(adapter); }, }), @@ -61,13 +74,17 @@ export function activate(context: vscode.ExtensionContext): void { registerFunctionHeaderFileSystem(), vscode.debug.onDidStartDebugSession((session) => { sessions.set(session.id, session); - symbolFiles.refresh(); + if (!isContextSession(session)) { + symbolFiles.refresh(); + } }), vscode.debug.onDidTerminateDebugSession((session) => { sessions.delete(session.id); adapters.delete(session.id); terminatedSessions.add(session); - symbolFiles.refresh(); + if (!isContextSession(session)) { + symbolFiles.refresh(); + } }), vscode.debug.onDidChangeActiveDebugSession(() => symbolFiles.refresh()), vscode.debug.onDidReceiveDebugSessionCustomEvent((event) => { @@ -90,7 +107,7 @@ export function activate(context: vscode.ExtensionContext): void { consoles, vscode.commands.registerCommand("simics-target-debug.openConsole", () => consoles.open()), vscode.commands.registerCommand("simics-target-debug.locateSourceFile", () => { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); return sourceLocator.locateCommand(session?.type === DEBUG_TYPE ? session : undefined); }), // Invoked from the Call Stack view context menu: the source URI, then @@ -383,7 +400,7 @@ async function editFunctionBreakpointContexts(): Promise { } async function addSymbolFile(symbolFiles: SymbolFilesProvider): Promise { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== DEBUG_TYPE) { void vscode.window.showErrorMessage("Start a Simics Target Debug session before adding a symbol file."); return; @@ -609,7 +626,7 @@ async function updateSymbolFilePath( } async function editSymbolFile(item?: SymbolFileViewItem): Promise { - if (!item || vscode.debug.activeDebugSession !== item.session) { + if (!item || activeRootSession() !== item.session) { void vscode.window.showErrorMessage("Select a symbol file in the active TCF session to edit its mapping."); return; } @@ -674,7 +691,7 @@ async function editSymbolFile(item?: SymbolFileViewItem): Promise { ) { return; } - if (vscode.debug.activeDebugSession !== session) { + if (activeRootSession() !== session) { return; } await replaceSymbolFile(session, index, file, updated); @@ -844,7 +861,7 @@ async function promptSymbolContext(session: vscode.DebugSession, initialContext async function saveSymbolFiles(): Promise { try { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== DEBUG_TYPE) { throw new Error("Select an active Simics Target Debug session."); } @@ -867,7 +884,7 @@ async function saveSymbolFiles(): Promise { if (choice !== "Save") { return; } - if (vscode.debug.activeDebugSession !== session) { + if (activeRootSession() !== session) { throw new Error("The active debug session changed. Please retry."); } const document = await vscode.workspace.openTextDocument( @@ -884,7 +901,7 @@ async function saveSymbolFiles(): Promise { } async function changeSymbolFiles(command: string, item?: SymbolFileViewItem): Promise { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== DEBUG_TYPE || (item && item.session !== session)) { void vscode.window.showErrorMessage("Select an active TCF session and refresh the Symbol Files view."); return; @@ -969,7 +986,7 @@ class SymbolFilesProvider implements vscode.TreeDataProvider, v if (element instanceof ForeignSymbolFilesItem) { return element.children; } - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== DEBUG_TYPE) { return []; } @@ -981,7 +998,7 @@ class SymbolFilesProvider implements vscode.TreeDataProvider, v }>, foreignSymbolFileItems(session), ]); - if (vscode.debug.activeDebugSession !== session) { + if (activeRootSession() !== session) { return []; } if (!result.supported) { @@ -1029,6 +1046,9 @@ class TcfConfigurationProvider implements vscode.DebugConfigurationProvider { folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, ): Promise { + if (isContextSessionConfig(config)) { + return config; + } const problems = pathMapProblems(config.pathMap, (p) => fs.existsSync(p), folder?.uri.fsPath); if (problems.length > 0) { const answer = await vscode.window.showWarningMessage( diff --git a/src/launchSettings/editorProvider.ts b/src/launchSettings/editorProvider.ts index 8e59977..5a95f74 100644 --- a/src/launchSettings/editorProvider.ts +++ b/src/launchSettings/editorProvider.ts @@ -13,6 +13,7 @@ import { removeConfigurations, setValue, } from "./launchJson"; +import { isContextSession } from "@/contextSessionManager"; import { SettingValue, StateMessage, WebviewMessage } from "./protocol"; import { Field, agentAddress, fieldPath, launchFields, launchTemplate, valueAtPath } from "./schema"; @@ -62,7 +63,7 @@ export function registerLaunchSettings(context: vscode.ExtensionContext): void { vscode.commands.registerCommand("simics-target-debug.openLaunchSettings", openLaunchSettings), vscode.commands.registerCommand("simics-target-debug.openLaunchJson", openLaunchJson), vscode.debug.onDidStartDebugSession((session) => { - if (session.type === DEBUG_TYPE) { + if (session.type === DEBUG_TYPE && !isContextSession(session)) { tcfSessions.add(session); debuggingChanged.fire(); } diff --git a/src/launchSettings/schema.ts b/src/launchSettings/schema.ts index 7daa71d..1391d5b 100644 --- a/src/launchSettings/schema.ts +++ b/src/launchSettings/schema.ts @@ -119,7 +119,15 @@ const GROUPS: { group: FieldGroup; keys: string[]; labels?: Record, vscod } async getChildren(): Promise { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== DEBUG_TYPE) { return []; } try { const rules = await getRules(session); - if (session !== vscode.debug.activeDebugSession) { + if (session !== activeRootSession()) { return []; } return rules.length @@ -68,7 +69,7 @@ export function registerPathMapView(context: vscode.ExtensionContext): void { const command = (name: string, action: (session: vscode.DebugSession, item?: PathMapItem) => Promise) => vscode.commands.registerCommand(`simics-target-debug.${name}`, async (item?: PathMapItem) => { try { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== DEBUG_TYPE || (item && item.session !== session)) { throw new Error("Select an active Simics Target Debug session."); } @@ -121,7 +122,7 @@ async function setRules( rules: PathMapRule[], expectedRules: PathMapRule[], ): Promise { - if (vscode.debug.activeDebugSession !== session) { + if (activeRootSession() !== session) { throw new Error("The active debug session changed. Please retry."); } await session.customRequest("setPathMapRules", { rules, expectedRules }); diff --git a/src/simicsConsoleManager.ts b/src/simicsConsoleManager.ts index b783f7a..39be679 100644 --- a/src/simicsConsoleManager.ts +++ b/src/simicsConsoleManager.ts @@ -1,5 +1,6 @@ import * as vscode from "vscode"; import { ConsoleEntry, ConsoleSource } from "./consolesView"; +import { activeRootSession, isContextSession } from "./contextSessionManager"; import { applyAndSave } from "./launchSettings/editorProvider"; import { readConfigurations, setNamedConfigurationValue } from "./launchSettings/launchJson"; import { @@ -107,7 +108,7 @@ export class SimicsConsoleManager implements ConsoleSource, vscode.Disposable { vscode.window.onDidCloseTerminal((t) => this.terminalClosed(t)), vscode.window.onDidChangeActiveTerminal(() => this.updateEditingKeys()), vscode.debug.onDidStartDebugSession((s) => { - if (s.type === debugType) { + if (s.type === debugType && !isContextSession(s)) { this.sessions.add(s.id); } }), @@ -182,7 +183,7 @@ export class SimicsConsoleManager implements ConsoleSource, vscode.Disposable { /** "Open Simics Console": for the active session. */ open(): void { - const session = vscode.debug.activeDebugSession; + const session = activeRootSession(); if (session?.type !== this.debugType) { void vscode.window.showErrorMessage(NO_SESSION); return; diff --git a/src/targetMemory/memoryClient.ts b/src/targetMemory/memoryClient.ts index 904def8..74f88b2 100644 --- a/src/targetMemory/memoryClient.ts +++ b/src/targetMemory/memoryClient.ts @@ -34,10 +34,10 @@ export class TargetMemoryClient { return result.suspended; } + /** The full name of a thread's context, like the physical memory contexts. */ async threadName(threadId: number): Promise { - const result = (await this.session.customRequest("threads")) as - { threads?: { id: number; name: string }[] } | undefined; - return result?.threads?.find((t) => t.id === threadId)?.name; + const args: req.ThreadContextArgs = { threadId }; + return (await this.request(req.TcfRequest.ThreadContext, args)).name; } /** Physical memory contexts with their full names. */ diff --git a/src/targetMemory/targetMemoryManager.ts b/src/targetMemory/targetMemoryManager.ts index 8df800b..c6404e7 100644 --- a/src/targetMemory/targetMemoryManager.ts +++ b/src/targetMemory/targetMemoryManager.ts @@ -1,5 +1,6 @@ import * as vscode from "vscode"; import type { DebugProtocol } from "@vscode/debugprotocol"; +import { activeRootSession, isContextSession, rootSession } from "@/contextSessionManager"; import * as req from "@/tcfRequests"; import { BYTES_PER_ROW_OPTIONS, GROUP_SIZES, addressFromValue, parseAddress } from "@/shared/targetMemory/format"; import { INT_SIZES } from "@/shared/targetMemory/needle"; @@ -79,7 +80,8 @@ export class TargetMemoryManager implements vscode.Disposable { vscode.debug.onDidStartDebugSession((s) => this.addSession(s)), vscode.debug.onDidTerminateDebugSession((s) => this.removeSession(s)), vscode.debug.onDidChangeActiveDebugSession((s) => { - const info = s && this.sessions.get(s.id); + const root = rootSession(s); + const info = root && this.sessions.get(root.id); if (info && info !== this.current) { this.current = info; this.updatePanels(); @@ -101,7 +103,7 @@ export class TargetMemoryManager implements vscode.Disposable { menuCommand("find", "find"), menuCommand("refresh", "refresh"), ); - const active = vscode.debug.activeDebugSession; + const active = activeRootSession(); if (active) { this.addSession(active); this.onActiveStackItem(vscode.debug.activeStackItem); @@ -251,7 +253,9 @@ export class TargetMemoryManager implements vscode.Disposable { private frameId(info: SessionInfo): number | undefined { const item = vscode.debug.activeStackItem; - return item instanceof vscode.DebugStackFrame && item.session.id === info.session.id ? item.frameId : undefined; + return item instanceof vscode.DebugStackFrame && rootSession(item.session) === info.session + ? item.frameId + : undefined; } private async loadPhysicalContexts(info: SessionInfo): Promise { @@ -265,7 +269,7 @@ export class TargetMemoryManager implements vscode.Disposable { } private addSession(session: vscode.DebugSession): void { - if (session.type !== this.debugType || this.sessions.has(session.id)) { + if (session.type !== this.debugType || isContextSession(session) || this.sessions.has(session.id)) { return; } const info: SessionInfo = { @@ -274,7 +278,7 @@ export class TargetMemoryManager implements vscode.Disposable { running: false, }; this.sessions.set(session.id, info); - if (!this.current || vscode.debug.activeDebugSession === session) { + if (!this.current || activeRootSession() === session) { this.current = info; this.updatePanels(); } @@ -287,15 +291,16 @@ export class TargetMemoryManager implements vscode.Disposable { } this.sessions.delete(session.id); if (this.current === info) { - const active = vscode.debug.activeDebugSession; + const active = activeRootSession(); this.current = (active && this.sessions.get(active.id)) ?? [...this.sessions.values()].pop(); this.updatePanels(); } } private onActiveStackItem(item: vscode.DebugThread | vscode.DebugStackFrame | undefined): void { - const info = item && this.sessions.get(item.session.id); - if (!info || info.focusedThread === item.threadId) { + const root = item && rootSession(item.session); + const info = root && this.sessions.get(root.id); + if (!item || !info || info.focusedThread === item.threadId) { return; } info.focusedThread = item.threadId; @@ -305,7 +310,9 @@ export class TargetMemoryManager implements vscode.Disposable { } private onAdapterMessage(session: vscode.DebugSession, m: DebugProtocol.ProtocolMessage): void { - const info = this.sessions.get(session.id); + // Context sessions report the stops of their threads, which belong to the root session. + const root = rootSession(session); + const info = root && this.sessions.get(root.id); if (m.type !== "event" || !info) { return; } @@ -313,6 +320,9 @@ export class TargetMemoryManager implements vscode.Disposable { const isCurrent = info === this.current; switch (e.event) { case "initialized": + if (root !== session) { + break; + } // Attached: the agent's memory contexts can be listed now. info.physical = undefined; if (isCurrent) { diff --git a/src/tcfDebugSession.ts b/src/tcfDebugSession.ts index 7b39777..92cd1c3 100644 --- a/src/tcfDebugSession.ts +++ b/src/tcfDebugSession.ts @@ -72,6 +72,84 @@ export interface TcfAttachArguments extends DebugProtocol.AttachRequestArguments pathMap?: PathMapRule[]; /** Symbol files to add to the agent's memory map. */ symbolFiles?: SymbolFileConfig[]; + /** Show the threads of container contexts in child sessions, see ContextSessionHost. */ + callStackHierarchy?: boolean; + /** Let VS Code merge a child session's row with its parent's, read by the extension. */ + callStackCompact?: boolean; +} + +/** + * A run control context with child contexts, shown as a child debug session + * of the session of its nearest container ancestor. + */ +export interface ContextGroup { + /** Unique, also across adapters, and never reused. */ + key: string; + name: string; + /** The group whose session is the parent, undefined for the root session. */ + parentKey?: string; +} + +/** + * Starts and ends the child debug sessions of container contexts, so that + * the Call Stack view shows the context hierarchy instead of a flat list of + * threads. Groups are added parents first. The child sessions connect to + * the root adapter with connectContextSession. + */ +export interface ContextSessionHost { + groupAdded(group: ContextGroup): void; + groupRenamed(key: string, name: string): void; + groupRemoved(key: string): void; +} + +/** The adapter of a child session, as seen from the root adapter. */ +export interface ContextSessionSink { + sendEvent(event: DebugProtocol.Event): void; + /** The group is gone or the root session ended. */ + terminate(): void; +} + +/** A child session's connection to the root adapter. */ +export interface ContextSessionLink { + threads(): DebugProtocol.Thread[]; + /** VS Code has configured the child session: report its suspended threads. */ + configured(): void; + /** Handles a request in the root adapter, with its IDs for threads, frames and variables. */ + forward(request: DebugProtocol.Request): Promise; + disconnect(): void; +} + +/** The capabilities of the root and child sessions. */ +export const TCF_CAPABILITIES: DebugProtocol.Capabilities = { + supportsConfigurationDoneRequest: true, + supportsDelayedStackTraceLoading: true, + supportsEvaluateForHovers: true, + supportsSteppingGranularity: true, + supportsDisassembleRequest: true, + supportsConditionalBreakpoints: true, + supportsHitConditionalBreakpoints: true, + supportsLogPoints: true, + supportsFunctionBreakpoints: true, + supportsDataBreakpoints: true, + supportsDataBreakpointBytes: true, + supportsInstructionBreakpoints: true, + exceptionBreakpointFilters: [], + supportsTerminateRequest: false, + supportsRestartRequest: false, +}; + +/** The group key of the root session's threads. */ +const ROOT_GROUP = ""; + +let nextGroupKey = 1; + +interface GroupState extends ContextGroup { + contextId: string; + sink?: ContextSessionSink; + /** Events are sent once VS Code has configured the child session. */ + configured: boolean; + /** VS Code shows the session as paused although it has no threads, see updateSessionStates. */ + pausedShown: boolean; } /** Where the TCF trace goes instead of the Debug Console, for example an Output channel. */ @@ -190,6 +268,20 @@ export class TcfDebugSession extends DebugSession { private readonly ctxByThreadId = new Map(); private nextThreadId = 1; private readonly threadStates = new Map(); + private contextSessionHost: ContextSessionHost | undefined; + /** Container contexts shown as child sessions, by key, parents first. */ + private readonly groups = new Map(); + private readonly groupKeyByCtx = new Map(); + /** The group whose session shows a thread, ROOT_GROUP for this session. */ + private readonly threadGroups = new Map(); + private groupsAnnounced = false; + /** Like GroupState.pausedShown, for this session. */ + private rootPausedShown = false; + /** The thread that caused the last stop, which VS Code focuses. */ + private focusThread: string | undefined; + /** Requests forwarded from child sessions, by their (negative) sequence number. */ + private readonly forwardedRequests = new Map void>(); + private nextForwardedSeq = -1; /** Contexts with a step in progress, used to report the stop reason. */ private readonly pendingSteps = new Set(); private readonly frameCache = new Map>(); @@ -235,25 +327,51 @@ export class TcfDebugSession extends DebugSession { return this.channel; } - protected override initializeRequest(response: DebugProtocol.InitializeResponse): void { - response.body = { - ...response.body, - supportsConfigurationDoneRequest: true, - supportsDelayedStackTraceLoading: true, - supportsEvaluateForHovers: true, - supportsSteppingGranularity: true, - supportsDisassembleRequest: true, - supportsConditionalBreakpoints: true, - supportsHitConditionalBreakpoints: true, - supportsLogPoints: true, - supportsFunctionBreakpoints: true, - supportsDataBreakpoints: true, - supportsDataBreakpointBytes: true, - supportsInstructionBreakpoints: true, - exceptionBreakpointFilters: [], - supportsTerminateRequest: false, - supportsRestartRequest: false, + /** + * Shows the threads of container contexts in child sessions started by + * `host`, unless the configuration turns it off. Call before attaching. + */ + setContextSessionHost(host: ContextSessionHost): void { + this.contextSessionHost = host; + } + + /** Connects a child session's adapter, undefined if its group is gone. */ + connectContextSession(key: string, sink: ContextSessionSink): ContextSessionLink | undefined { + const group = this.groups.get(key); + if (!group || group.sink) { + return undefined; + } + group.sink = sink; + return { + threads: () => this.groupThreads(key), + configured: () => { + if (this.groups.get(key)?.sink === sink) { + group.configured = true; + this.reportGroupState(key); + } + }, + forward: (request) => this.forwardRequest(request), + disconnect: () => { + if (group.sink === sink) { + group.sink = undefined; + group.configured = false; + } + }, }; + } + + override sendResponse(response: DebugProtocol.Response): void { + const forwarded = this.forwardedRequests.get(response.request_seq); + if (forwarded) { + this.forwardedRequests.delete(response.request_seq); + forwarded(response); + return; + } + super.sendResponse(response); + } + + protected override initializeRequest(response: DebugProtocol.InitializeResponse): void { + response.body = { ...response.body, ...TCF_CAPABILITIES }; this.sendResponse(response); } @@ -262,6 +380,9 @@ export class TcfDebugSession extends DebugSession { args: TcfAttachArguments, ): Promise { this.disassemblyFunctionHeaders = args.disassemblyFunctionHeaders !== false; + if (args.callStackHierarchy === false) { + this.contextSessionHost = undefined; + } const host = args.host ?? "localhost"; const port = args.port ?? 1534; const tcfLog = this.tcfLog; @@ -317,9 +438,9 @@ export class TcfDebugSession extends DebugSession { contextChanged: () => { this.regContextCache.clear(); this.regChildrenCache.clear(); - this.sendEvent(new InvalidatedEvent(["variables"])); + this.sendInvalidated(["variables"]); }, - registerChanged: () => this.sendEvent(new InvalidatedEvent(["variables"])), + registerChanged: () => this.sendInvalidated(["variables"]), }); } else { this.log( @@ -753,7 +874,7 @@ export class TcfDebugSession extends DebugSession { // Files may have been added or removed by someone else. this.sendEvent(new Event("symbolFilesChanged")); if (this.configured && [...this.threadStates.values()].some((s) => s.suspended)) { - this.sendEvent(new InvalidatedEvent(["stacks", "variables"])); + this.sendInvalidated(["stacks", "variables"]); } }, 100); } @@ -764,6 +885,7 @@ export class TcfDebugSession extends DebugSession { ): Promise { this.sendResponse(response); this.configured = true; + this.announceGroups(); await this.reportInitialState(); } @@ -771,18 +893,14 @@ export class TcfDebugSession extends DebugSession { this.disconnecting = true; clearTimeout(this.symbolsChangedTimer); this.channel?.close(); + for (const key of [...this.groups.keys()]) { + this.removeGroup(key); + } this.sendResponse(response); } protected override threadsRequest(response: DebugProtocol.ThreadsResponse): void { - const threads: Thread[] = []; - for (const id of this.contextOrder) { - const threadId = this.threadIdByCtx.get(id); - if (threadId !== undefined) { - threads.push(new Thread(threadId, this.contextDisplayName(id))); - } - } - response.body = { threads }; + response.body = { threads: this.groupThreads(ROOT_GROUP) }; this.sendResponse(response); } @@ -1094,7 +1212,11 @@ export class TcfDebugSession extends DebugSession { case req.TcfRequest.ThreadContext: await handle(async () => { const { threadId } = args as req.ThreadContextArgs; - response.body = { contextId: this.requireThreadCtx(threadId) } satisfies req.ThreadContextResult; + const contextId = this.requireThreadCtx(threadId); + response.body = { + contextId, + name: this.contextDisplayName(contextId), + } satisfies req.ThreadContextResult; }); return true; case req.TcfRequest.ContextSuspended: @@ -1535,7 +1657,7 @@ export class TcfDebugSession extends DebugSession { this.sendEvent(new Event("pathMapChanged")); const suspended = [...this.threadStates.values()].some((s) => s.suspended); if (this.configured && suspended) { - this.sendEvent(new InvalidatedEvent(["stacks"])); + this.sendInvalidated(["stacks"]); } await this.breakpoints?.updateSourcePaths(); } @@ -1794,11 +1916,13 @@ export class TcfDebugSession extends DebugSession { }; const ordered = await visit(null); for (const id of ordered) { - this.addContext(this.contexts.get(id)!, false); + this.addContext(this.contexts.get(id)!); } + this.updateGroups(); } - private addContext(ctx: RunControlContext, notify: boolean): void { + /** Adds or updates a context. Call updateGroups after a batch, it reports new threads. */ + private addContext(ctx: RunControlContext): void { const isNew = !this.contextOrder.includes(ctx.ID); this.contexts.set(ctx.ID, ctx); if (isNew) { @@ -1808,9 +1932,6 @@ export class TcfDebugSession extends DebugSession { const threadId = this.nextThreadId++; this.threadIdByCtx.set(ctx.ID, threadId); this.ctxByThreadId.set(threadId, ctx.ID); - if (notify) { - this.sendEvent(new ThreadEvent("started", threadId)); - } } } @@ -1857,8 +1978,10 @@ export class TcfDebugSession extends DebugSession { if (threadId !== undefined) { this.threadIdByCtx.delete(id); this.ctxByThreadId.delete(threadId); - if (this.configured) { - this.sendEvent(new ThreadEvent("exited", threadId)); + const group = this.threadGroups.get(id); + this.threadGroups.delete(id); + if (group !== undefined) { + this.sendToGroup(group, new ThreadEvent("exited", threadId)); } } } @@ -1866,16 +1989,19 @@ export class TcfDebugSession extends DebugSession { private addRunControlListener(rc: RunControlService): void { rc.addListener({ contextAdded: (ctxs) => { - ctxs.forEach((c) => this.addContext(c, this.configured)); + ctxs.forEach((c) => this.addContext(c)); + this.updateGroups(); this.pathMapContextsChanged(); void this.breakpoints?.updateInstructionScopes(); }, contextChanged: (ctxs) => { - ctxs.forEach((c) => this.addContext(c, this.configured)); + ctxs.forEach((c) => this.addContext(c)); + this.updateGroups(); this.pathMapContextsChanged(); }, contextRemoved: (ids) => { ids.forEach((id) => this.removeContext(id)); + this.updateGroups(); this.pathMapContextsChanged(); void this.breakpoints?.updateInstructionScopes(); }, @@ -1905,13 +2031,17 @@ export class TcfDebugSession extends DebugSession { if (pc !== undefined) { this.knownInstructionStarts.add(triggerId, pc); } + // The reason is the trigger's. Without a thread as trigger, the first suspended thread is reported as such. + const reasonCtx = this.threadIdByCtx.has(triggerId) ? triggerId : ids.find((id) => this.threadIdByCtx.has(id)); for (const id of ids) { // Only the trigger context's PC is reported, fetch others lazily. - this.threadStates.set(id, { suspended: true, pc: id === triggerId ? pc : undefined, reason }); - } - if (!this.threadStates.has(triggerId)) { - this.threadStates.set(triggerId, { suspended: true, pc, reason }); + this.threadStates.set(id, { + suspended: true, + pc: id === triggerId ? pc : undefined, + reason: id === reasonCtx ? reason : undefined, + }); } + this.threadStates.set(triggerId, { suspended: true, pc, reason }); if (!this.configured) { return; } @@ -1977,45 +2107,76 @@ export class TcfDebugSession extends DebugSession { if (!this.configured) { return; } - const threadIds = ids.map((id) => this.threadIdByCtx.get(id)).filter((t): t is number => t !== undefined); - if (threadIds.length === 0) { - return; - } - if (this.allThreads((s) => !s.suspended)) { - this.sendEvent(new ContinuedEvent(threadIds[0], true)); - } else { - for (const t of threadIds) { - this.sendEvent(new ContinuedEvent(t, false)); + for (const [group, ctxIds] of this.threadsByGroup(ids)) { + if (this.allGroupThreads(group, (s) => !s.suspended)) { + this.sendToGroup(group, new ContinuedEvent(this.threadIdByCtx.get(ctxIds[0])!, true)); + this.setPausedShown(group, false); + } else { + for (const id of ctxIds) { + this.sendToGroup(group, new ContinuedEvent(this.threadIdByCtx.get(id)!, false)); + } } } + this.updateSessionStates(); } - private reportStopped(triggerId: string, ids: string[], stop: StopInfo): void { - const triggerThread = - this.threadIdByCtx.get(triggerId) ?? - ids.map((id) => this.threadIdByCtx.get(id)).find((t) => t !== undefined); - if (triggerThread === undefined) { - return; - } - if (this.allThreads((s) => s.suspended)) { - this.sendEvent(stoppedEvent(stop, triggerThread, true)); + /** + * Reports stopped threads to the sessions that show them. The trigger + * thread gets `stop`, the others the reason in their state, which is + * only set if it is their own (from getState). Only the trigger may take + * the focus, if `focus` is set. + */ + private reportStopped(triggerId: string, ids: string[], stop: StopInfo, focus = true): void { + const triggerCtx = this.threadIdByCtx.has(triggerId) ? triggerId : ids.find((id) => this.threadIdByCtx.has(id)); + if (triggerCtx === undefined) { return; } - this.sendEvent(stoppedEvent(stop, triggerThread, false)); - // Breakpoint hits only apply to the context that hit them. - const others: StopInfo = { reason: stop.reason, stepped: stop.stepped }; - for (const id of ids) { - const t = this.threadIdByCtx.get(id); - if (t !== undefined && t !== triggerThread) { - const e = stoppedEvent(others, t, false); - e.body.preserveFocusHint = true; - this.sendEvent(e); + if (focus) { + this.focusThread = triggerCtx; + } + const triggerGroup = this.groupOfThread(triggerCtx); + for (const [group, ctxIds] of this.threadsByGroup([triggerCtx, ...ids])) { + const event = (id: string, allThreadsStopped: boolean) => { + // Breakpoint hits only apply to the context that hit them. + const info = id === triggerCtx ? stop : { reason: this.threadStates.get(id)?.reason }; + const e = stoppedEvent(info, this.threadIdByCtx.get(id)!, allThreadsStopped); + if (!focus || id !== triggerCtx || group !== triggerGroup) { + e.body.preserveFocusHint = true; + } + return e; + }; + if (this.allGroupThreads(group, (s) => s.suspended)) { + // VS Code shows the other threads as "Paused", only those + // with a reason of their own need an event. + this.sendToGroup(group, event(ctxIds[0], true)); + for (const id of ctxIds.slice(1)) { + if (ownStopReason(this.threadStates.get(id)?.reason)) { + this.sendToGroup(group, event(id, false)); + } + } + } else { + for (const id of ctxIds) { + this.sendToGroup(group, event(id, false)); + } } } + this.updateSessionStates(); + } + + /** The thread to report first among suspended threads: the focused one, else one with a reason of its own. */ + private reportedTrigger(suspended: string[]): string | undefined { + if (this.focusThread !== undefined && suspended.includes(this.focusThread)) { + return this.focusThread; + } + return suspended.find((id) => ownStopReason(this.threadStates.get(id)?.reason)) ?? suspended[0]; } - private allThreads(pred: (s: ThreadState) => boolean): boolean { + /** Whether `pred` holds for all threads shown in a group's session. */ + private allGroupThreads(group: string, pred: (s: ThreadState) => boolean): boolean { for (const id of this.threadIdByCtx.keys()) { + if (this.groupOfThread(id) !== group) { + continue; + } const s = this.threadStates.get(id); if (!s || !pred(s)) { return false; @@ -2046,8 +2207,9 @@ export class TcfDebugSession extends DebugSession { ); } }); - if (suspended.length > 0) { - this.reportStopped(suspended[0], suspended, { reason: this.threadStates.get(suspended[0])?.reason }); + const trigger = this.reportedTrigger(suspended); + if (trigger !== undefined) { + this.reportStopped(trigger, suspended, { reason: this.threadStates.get(trigger)?.reason }); } } @@ -2084,6 +2246,359 @@ export class TcfDebugSession extends DebugSession { return names.length > 0 ? names.join(".") : id; } + // ---- Context sessions -------------------------------------------------- + + private groupOfThread(id: string): string { + return this.threadGroups.get(id) ?? ROOT_GROUP; + } + + /** The threads among `ids` by the group that shows them, in order and without duplicates. */ + private threadsByGroup(ids: string[]): Map { + const result = new Map(); + for (const id of new Set(ids)) { + if (this.threadIdByCtx.has(id)) { + const group = this.groupOfThread(id); + const list = result.get(group); + if (list) { + list.push(id); + } else { + result.set(group, [id]); + } + } + } + return result; + } + + private sendToGroup(group: string, event: DebugProtocol.Event): void { + if (group === ROOT_GROUP) { + if (this.configured) { + this.sendEvent(event); + } + return; + } + const g = this.groups.get(group); + if (g?.configured) { + g.sink?.sendEvent(event); + } + } + + /** Child sessions cache frames and variables too. */ + private sendInvalidated(areas: DebugProtocol.InvalidatedAreas[]): void { + this.sendEvent(new InvalidatedEvent(areas)); + for (const g of this.groups.values()) { + if (g.configured) { + g.sink?.sendEvent(new InvalidatedEvent(areas)); + } + } + } + + private groupThreads(group: string): DebugProtocol.Thread[] { + const threads: DebugProtocol.Thread[] = []; + for (const id of this.contextOrder) { + const threadId = this.threadIdByCtx.get(id); + if (threadId !== undefined && this.groupOfThread(id) === group) { + const name = this.contextSessionHost ? this.groupThreadName(id, group) : this.contextDisplayName(id); + threads.push(new Thread(threadId, name)); + } + } + return threads; + } + + /** + * The name of a thread in its group's session: the names of the + * contexts below the group's context, since the sessions above show the + * rest. A container with a single thread has no session of its own, and + * often has the thread's name, so repeated names are shown once. + */ + private groupThreadName(id: string, group: string): string { + return this.relativeName(id, group === ROOT_GROUP ? undefined : this.groups.get(group)?.contextId); + } + + /** The names of a context and its ancestors below `top`, repeated names once. */ + private relativeName(id: string, top: string | undefined): string { + const names: string[] = []; + for (let c = this.contexts.get(id); c && c.ID !== top && names.length <= this.contexts.size;) { + const name = c.Name ?? c.ID; + if (names[0] !== name) { + names.unshift(name); + } + c = c.ParentID ? this.contexts.get(c.ParentID) : undefined; + } + return names.length > 0 ? names.join(".") : (this.contexts.get(id)?.Name ?? id); + } + + /** + * Brings the groups in line with the context tree and moves threads to + * the session of their nearest container, reporting new threads. A + * session cannot move, so a group whose parent group changes is replaced. + */ + private updateGroups(): void { + const containers = this.contextSessionHost ? this.groupContexts() : []; + const wanted = new Set(containers.map((c) => c.id)); + for (const g of [...this.groups.values()]) { + if (!wanted.has(g.contextId)) { + this.removeGroup(g.key); + } + } + for (const { id, name } of containers) { + const parentKey = this.parentGroupKey(id); + const key = this.groupKeyByCtx.get(id); + let group = key === undefined ? undefined : this.groups.get(key); + if (group && group.parentKey !== parentKey) { + this.removeGroup(group.key); + group = undefined; + } + if (!group) { + group = { + key: String(nextGroupKey++), + name, + parentKey, + contextId: id, + configured: false, + pausedShown: false, + }; + this.groups.set(group.key, group); + this.groupKeyByCtx.set(id, group.key); + if (this.groupsAnnounced) { + this.contextSessionHost!.groupAdded({ key: group.key, name, parentKey }); + } + } else if (group.name !== name) { + group.name = name; + if (this.groupsAnnounced) { + this.contextSessionHost!.groupRenamed(group.key, name); + } + } + } + const moved: string[] = []; + for (const [id, threadId] of this.threadIdByCtx) { + const group = this.groupKeyByCtx.get(id) ?? this.parentGroupKey(id) ?? ROOT_GROUP; + const old = this.threadGroups.get(id); + if (old === group) { + continue; + } + this.threadGroups.set(id, group); + if (old !== undefined) { + this.sendToGroup(old, new ThreadEvent("exited", threadId)); + } + this.sendToGroup(group, new ThreadEvent("started", threadId)); + if (this.threadStates.get(id)?.suspended) { + moved.push(id); + } + } + // A new thread in VS Code is running until reported stopped. + const trigger = this.reportedTrigger(moved); + if (trigger !== undefined) { + const focus = trigger === this.focusThread; + this.reportStopped(trigger, moved, { reason: this.threadStates.get(trigger)?.reason }, focus); + } + this.updateSessionStates(); + } + + /** + * The contexts that get a session, parents first, with the session names. + * + * VS Code shows a session with a single thread without the thread row, + * so only contexts with children and at least two threads among them, + * below them or themselves get a session. The thread of a container with + * a single thread is shown in the session above instead. If that leaves + * a session with a single thread next to child sessions, the thread would + * be hidden, so it gets a session of its own, named like the thread. + */ + private groupContexts(): { id: string; name: string }[] { + const children = new Map(); + for (const id of this.contextOrder) { + const parent = this.contexts.get(id)?.ParentID; + if (parent !== undefined && this.contexts.has(parent)) { + children.set(parent, [...(children.get(parent) ?? []), id]); + } + } + const threadCounts = new Map(); + const threadCount = (id: string): number => { + let result = threadCounts.get(id); + if (result === undefined) { + threadCounts.set(id, 0); + result = + (this.contexts.get(id)?.HasState === true ? 1 : 0) + sum((children.get(id) ?? []).map(threadCount)); + threadCounts.set(id, result); + } + return result; + }; + const containers = this.contextOrder.filter((id) => children.has(id) && threadCount(id) >= 2); + const isContainer = new Set(containers); + // The session of a context: its nearest container, undefined for this session. + const sessionOf = (id: string): string | undefined => { + const seen = new Set(); + for (let p = this.contexts.get(id)?.ParentID; p !== undefined && !seen.has(p);) { + seen.add(p); + if (isContainer.has(p)) { + return p; + } + p = this.contexts.get(p)?.ParentID; + } + return undefined; + }; + const ownThreads = new Map(); + for (const id of this.threadIdByCtx.keys()) { + const session = isContainer.has(id) ? id : sessionOf(id); + ownThreads.set(session, [...(ownThreads.get(session) ?? []), id]); + } + const hasChildSessions = new Set(containers.map(sessionOf)); + const groups = containers.map((id) => ({ id, name: this.contexts.get(id)?.Name ?? id, parent: sessionOf(id) })); + for (const [session, threads] of ownThreads) { + if (threads.length === 1 && threads[0] !== session && hasChildSessions.has(session)) { + groups.push({ id: threads[0], name: this.relativeName(threads[0], session), parent: session }); + } + } + // VS Code lists child sessions in the order they start: parents + // first, then sessions of threads (for example CPUs) before the + // others, else in the order of the context tree. + const sessionDepth = (id: string | undefined): number => { + let d = 0; + for (let p = id; p !== undefined && d < groups.length; d++) { + p = groups.find((g) => g.id === p)?.parent; + } + return d; + }; + const order = new Map(this.contextOrder.map((id, i) => [id, i])); + return groups + .map((g) => ({ + ...g, + depth: sessionDepth(g.parent), + threadsLast: this.contexts.get(g.id)?.HasState === true ? 0 : 1, + })) + .sort((a, b) => a.depth - b.depth || a.threadsLast - b.threadsLast || order.get(a.id)! - order.get(b.id)!) + .map(({ id, name }) => ({ id, name })); + } + + /** The key of the nearest ancestor's group. */ + private parentGroupKey(id: string): string | undefined { + const seen = new Set(); + for (let p = this.contexts.get(id)?.ParentID; p !== undefined && !seen.has(p);) { + seen.add(p); + const key = this.groupKeyByCtx.get(p); + if (key !== undefined) { + return key; + } + p = this.contexts.get(p)?.ParentID; + } + return undefined; + } + + /** Removes a group and ends its session. Its threads move with the next updateGroups. */ + private removeGroup(key: string): void { + const group = this.groups.get(key); + if (!group) { + return; + } + this.groups.delete(key); + if (this.groupKeyByCtx.get(group.contextId) === key) { + this.groupKeyByCtx.delete(group.contextId); + } + for (const [id, g] of this.threadGroups) { + if (g === key) { + // Reported as started in its new session only. + this.threadGroups.delete(id); + } + } + const sink = group.sink; + group.sink = undefined; + group.configured = false; + sink?.terminate(); + if (this.groupsAnnounced) { + this.contextSessionHost?.groupRemoved(key); + } + } + + /** Lets the host start the child sessions, once this session is configured. */ + private announceGroups(): void { + if (!this.contextSessionHost || this.groupsAnnounced) { + return; + } + this.groupsAnnounced = true; + for (const g of this.groups.values()) { + this.contextSessionHost.groupAdded({ key: g.key, name: g.name, parentKey: g.parentKey }); + } + } + + /** Reports the suspended threads of a child session that VS Code has just configured. */ + private reportGroupState(key: string): void { + const suspended = [...this.threadIdByCtx.keys()].filter( + (id) => this.groupOfThread(id) === key && this.threadStates.get(id)?.suspended, + ); + const trigger = this.reportedTrigger(suspended); + if (trigger !== undefined) { + const focus = trigger === this.focusThread; + this.reportStopped(trigger, suspended, { reason: this.threadStates.get(trigger)?.reason }, focus); + } + this.updateSessionStates(); + } + + /** + * VS Code shows a session without threads as running. Such sessions are + * reported stopped, without a thread, while all threads below them are + * suspended, and continued otherwise. + */ + private updateSessionStates(): void { + if (!this.contextSessionHost) { + return; + } + const own = new Set(); + const any = new Set(); + const running = new Set(); + for (const id of this.threadIdByCtx.keys()) { + const isRunning = !this.threadStates.get(id)?.suspended; + let key: string | undefined = this.groupOfThread(id); + own.add(key); + for (const seen = new Set(); key !== undefined && !seen.has(key);) { + seen.add(key); + any.add(key); + if (isRunning) { + running.add(key); + } + key = key === ROOT_GROUP ? undefined : (this.groups.get(key)?.parentKey ?? ROOT_GROUP); + } + } + for (const key of [ROOT_GROUP, ...this.groups.keys()]) { + const ready = key === ROOT_GROUP ? this.configured : this.groups.get(key)!.configured; + if (!ready || own.has(key)) { + continue; + } + const paused = any.has(key) && !running.has(key); + if (paused && !this.isPausedShown(key)) { + const e = new StoppedEvent("pause") as DebugProtocol.StoppedEvent; + e.body = { reason: "pause", description: "Paused", preserveFocusHint: true, allThreadsStopped: false }; + this.sendToGroup(key, e); + this.setPausedShown(key, true); + } else if (!paused && this.isPausedShown(key)) { + this.sendToGroup(key, new ContinuedEvent(0, true)); + this.setPausedShown(key, false); + } + } + } + + private isPausedShown(key: string): boolean { + return key === ROOT_GROUP ? this.rootPausedShown : this.groups.get(key)?.pausedShown === true; + } + + private setPausedShown(key: string, shown: boolean): void { + if (key === ROOT_GROUP) { + this.rootPausedShown = shown; + } else { + const g = this.groups.get(key); + if (g) { + g.pausedShown = shown; + } + } + } + + private forwardRequest(request: DebugProtocol.Request): Promise { + return new Promise((resolve) => { + const seq = this.nextForwardedSeq--; + this.forwardedRequests.set(seq, resolve); + this.dispatchRequest({ ...request, seq }); + }); + } + // ---- Helpers --------------------------------------------------------- private async handle(response: DebugProtocol.Response, fn: () => Promise, showUser = true): Promise { @@ -2120,13 +2635,26 @@ function stoppedEvent(stop: StopInfo, threadId: number, allThreadsStopped: boole if (stop.hits && stop.hits.dapIds.length > 0) { e.body.hitBreakpointIds = stop.hits.dapIds; } + // Only the reason of the context itself is shown, "Paused" otherwise. + e.body.description = ownStopReason(tcfReason) ? tcfReason : reason === "step" ? "Step" : "Paused"; if (tcfReason) { - e.body.description = tcfReason; e.body.text = tcfReason; } return e; } +/** + * Whether a TCF suspend reason says why the context itself stopped, unlike + * "Suspended" and "Container", which contexts get when everything stops. + */ +function ownStopReason(reason: string | undefined): reason is string { + return reason !== undefined && reason !== "Suspended" && reason !== "Container"; +} + +function sum(values: number[]): number { + return values.reduce((a, b) => a + b, 0); +} + /** * Picks the TCF resume mode for a DAP step. Line stepping is used unless * instruction granularity is requested, falling back to instruction stepping diff --git a/src/tcfRequests.ts b/src/tcfRequests.ts index c4bc905..dfa2a19 100644 --- a/src/tcfRequests.ts +++ b/src/tcfRequests.ts @@ -27,6 +27,8 @@ export interface ThreadContextArgs { export interface ThreadContextResult { contextId: string; + /** Full name, made from the names of the context and its ancestors. */ + name?: string; } export interface ContextSuspendedArgs { diff --git a/src/test/contextSession.test.ts b/src/test/contextSession.test.ts new file mode 100644 index 0000000..cbad61f --- /dev/null +++ b/src/test/contextSession.test.ts @@ -0,0 +1,463 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { DebugProtocol } from "@vscode/debugprotocol"; +import type { DebugSession } from "@vscode/debugadapter"; +import { ContextGroup, TcfDebugSession } from "@/tcfDebugSession"; +import { TcfContextSession } from "@/contextSession"; +import type { RunControlContext, RunControlListener, RunControlState } from "@/tcf/services/runControl"; + +/** Sends requests to an adapter and records what it sends back. */ +function client(session: DebugSession) { + const events: DebugProtocol.Event[] = []; + const pending = new Map void>(); + let seq = 0; + session.onDidSendMessage((value) => { + const message = value as DebugProtocol.ProtocolMessage; + // Context changes refresh the Path Map view, which is not tested here. + if (message.type === "event" && (message as DebugProtocol.Event).event !== "pathMapChanged") { + events.push(message as DebugProtocol.Event); + } else if (message.type === "response") { + const r = message as DebugProtocol.Response; + pending.get(r.request_seq)?.(r); + pending.delete(r.request_seq); + } + }); + const request = (command: string, args: object = {}) => + new Promise((resolve) => { + const next = ++seq; + pending.set(next, resolve); + session.handleMessage({ seq: next, type: "request", command, arguments: args } as DebugProtocol.Request); + }); + /** The events received since the last call. */ + const take = () => events.splice(0); + return { request, take }; +} + +function ctx(ID: string, ParentID?: string, HasState = false): RunControlContext { + return { ID, Name: ID, ...(ParentID && { ParentID }), ...(HasState && { HasState }) }; +} + +/** + * A root session with a fake RunControl service: + * board (cpu0, cpu1), linux (p1 (t1, t2)), idle + */ +async function rootSession(withHost = true, states: Record = {}) { + const contexts = [ + ctx("board"), + ctx("cpu0", "board", true), + ctx("cpu1", "board", true), + ctx("linux"), + ctx("p1", "linux"), + ctx("t1", "p1", true), + ctx("t2", "p1", true), + ctx("idle", undefined, true), + ]; + const listeners: RunControlListener[] = []; + const rc = { + getChildren: async (id: string | null) => + contexts.filter((c) => c.ParentID === (id ?? undefined)).map((c) => c.ID), + getContext: async (id: string) => contexts.find((c) => c.ID === id)!, + getState: async (id: string) => states[id] ?? { suspended: false }, + addListener: (l: RunControlListener) => listeners.push(l), + }; + const session = new TcfDebugSession(); + const added: ContextGroup[] = []; + const renamed: [string, string][] = []; + const removed: string[] = []; + const host = { + added, + renamed, + removed, + groupAdded: (g: ContextGroup) => added.push(g), + groupRenamed: (key: string, name: string) => renamed.push([key, name]), + groupRemoved: (key: string) => removed.push(key), + }; + if (withHost) { + session.setContextSessionHost(host); + } + const internal = session as unknown as { + addRunControlListener(rc: unknown): void; + discoverContexts(): Promise; + }; + Object.assign(session, { runControl: rc }); + internal.addRunControlListener(rc); + await internal.discoverContexts(); + const root = client(session); + await root.request("configurationDone"); + // reportInitialState queries the states after the response. + await new Promise((r) => setImmediate(r)); + const keyOf = (name: string) => [...host.added].reverse().find((g) => g.name === name)!.key; + /** Starts the child session of a group, like VS Code does. */ + const child = async (name: string) => { + const adapter = new TcfContextSession((sink) => session.connectContextSession(keyOf(name), sink)); + const c = client(adapter); + const init = await c.request("initialize", { adapterID: "simics-target-debug", pathFormat: "path" }); + assert.equal(init.body.supportsInstructionBreakpoints, true); + await c.request("attach"); + await c.request("configurationDone"); + return { adapter, ...c }; + }; + const threadNames = async (c: { request: typeof root.request }) => + ((await c.request("threads")).body.threads as DebugProtocol.Thread[]).map((t) => t.name); + return { session, root, host, listener: listeners[0], keyOf, child, threadNames }; +} + +// Each container with two threads or more below it gets a group, parents +// first. A session with a single thread next to child sessions would hide +// it, so the top-level thread idle gets a session of its own. Sessions of +// threads come first. +test("container contexts become child sessions with their threads", async () => { + const { root, host, child, keyOf, threadNames } = await rootSession(); + assert.deepEqual( + host.added.map((g) => [g.name, g.parentKey]), + [ + ["idle", undefined], + ["board", undefined], + ["linux", undefined], + ["p1", keyOf("linux")], + ], + ); + assert.deepEqual(await threadNames(root), []); + assert.deepEqual(await threadNames(await child("idle")), ["idle"]); + const board = await child("board"); + assert.deepEqual(await threadNames(board), ["cpu0", "cpu1"]); + assert.deepEqual(await threadNames(await child("linux")), []); + assert.deepEqual(await threadNames(await child("p1")), ["t1", "t2"]); + const initialized = board.take().map((e) => e.event); + assert.deepEqual(initialized, ["initialized"]); +}); + +// Each session gets the stop of its own threads. Only the session of the +// thread that caused it may take the focus. +test("stops and resumes are reported to the session of each thread", async () => { + const { root, listener, child } = await rootSession(); + const board = await child("board"); + const p1 = await child("p1"); + const idle = await child("idle"); + root.take(); + board.take(); + p1.take(); + idle.take(); + listener.containerSuspended!("t2", 0x1000, "Breakpoint", undefined, ["cpu0", "cpu1", "t1", "t2", "idle"]); + const [p1Stop] = p1.take() as DebugProtocol.StoppedEvent[]; + assert.equal(p1Stop.body.allThreadsStopped, true); + assert.equal(p1Stop.body.reason, "breakpoint"); + assert.equal(p1Stop.body.description, "Breakpoint"); + assert.equal(p1Stop.body.preserveFocusHint, undefined); + const [boardStop, ...more] = board.take() as DebugProtocol.StoppedEvent[]; + assert.deepEqual(more, []); + assert.equal(boardStop.body.allThreadsStopped, true); + assert.equal(boardStop.body.preserveFocusHint, true); + // The reason is the trigger's, other threads are just paused. + assert.equal(boardStop.body.reason, "pause"); + assert.equal(boardStop.body.description, "Paused"); + const [idleStop] = idle.take() as DebugProtocol.StoppedEvent[]; + assert.equal(idleStop.event, "stopped"); + assert.equal(idleStop.body.preserveFocusHint, true); + // The root session has no threads of its own. + const [rootStop] = root.take() as DebugProtocol.StoppedEvent[]; + assert.equal(rootStop.body.threadId, undefined); + + listener.contextResumed!("cpu0"); + const [resumed] = board.take() as DebugProtocol.ContinuedEvent[]; + assert.equal(resumed.event, "continued"); + assert.equal(resumed.body.allThreadsContinued, false); + listener.containerResumed!(["t1", "t2"]); + const continued = p1.take() as DebugProtocol.ContinuedEvent[]; + assert.deepEqual( + continued.map((e) => e.body.allThreadsContinued), + [true], + ); + assert.deepEqual( + root.take().map((e) => e.event), + ["continued"], + ); +}); + +// A child session that starts while its threads are suspended reports them. +test("a new child session reports its suspended threads", async () => { + const { listener, child } = await rootSession(); + listener.containerSuspended!("t1", 0x1000, "Suspended", undefined, ["cpu0", "cpu1", "t1", "t2", "idle"]); + const p1 = await child("p1"); + const stops = p1.take().filter((e) => e.event === "stopped") as DebugProtocol.StoppedEvent[]; + assert.equal(stops.length, 1); + assert.equal(stops[0].body.allThreadsStopped, true); +}); + +// Requests other than the session's own are handled by the root adapter, +// which owns the thread, frame and variable IDs. +test("child sessions pass requests on and leave breakpoints to the root", async () => { + const { session, child } = await rootSession(); + const p1 = await child("p1"); + const threads = (await p1.request("threads")).body.threads as DebugProtocol.Thread[]; + const context = await p1.request("tcfThreadContext", { threadId: threads[0].id }); + assert.equal(context.success, true); + assert.equal(context.command, "tcfThreadContext"); + assert.deepEqual(context.body, { contextId: "t1", name: "linux.p1.t1" }); + const failed = await p1.request("tcfThreadContext", { threadId: 999 }); + assert.equal(failed.success, false); + const bps = await p1.request("setBreakpoints", { + source: { path: "/src/a.c" }, + breakpoints: [{ line: 3 }], + }); + assert.deepEqual(bps.body, { breakpoints: [] }); + assert.equal((session as unknown as { forwardedRequests: Map }).forwardedRequests.size, 0); +}); + +// Breakpoint IDs in stopped events are the root session's. +test("child sessions leave out hit breakpoint IDs", async () => { + const { child } = await rootSession(); + const p1 = await child("p1"); + p1.take(); + p1.adapter.sendEvent({ + seq: 0, + type: "event", + event: "stopped", + body: { reason: "breakpoint", threadId: 1, hitBreakpointIds: [4] }, + } as DebugProtocol.StoppedEvent); + const [stop] = p1.take() as DebugProtocol.StoppedEvent[]; + assert.deepEqual(stop.body, { reason: "breakpoint", threadId: 1 }); +}); + +// Processes come and go with OS awareness. +test("groups follow added, changed and removed contexts", async () => { + const { root, host, listener, child, keyOf, threadNames } = await rootSession(); + const p1 = await child("p1"); + // With more top-level threads, idle is back in the root session. + listener.contextAdded!([ctx("spare1", undefined, true), ctx("spare2", undefined, true)]); + assert.deepEqual(host.removed, [keyOf("idle")]); + assert.deepEqual(await threadNames(root), ["idle", "spare1", "spare2"]); + root.take(); + + // Processes with one thread have no session of their own. + const linux = await child("linux"); + linux.take(); + listener.contextAdded!([ + ctx("p2", "linux"), + ctx("t3", "p2", true), + ctx("p3", "linux"), + ctx("t6", "p3", true), + ctx("p4", "linux"), + ctx("t7", "p4", true), + ]); + assert.equal(host.added.length, 4); + assert.deepEqual(await threadNames(linux), ["p2.t3", "p3.t6", "p4.t7"]); + linux.take(); + // With a second thread it gets one, and the thread moves there. + listener.contextAdded!([ctx("t5", "p2", true)]); + const p2 = host.added.at(-1)!; + assert.deepEqual([p2.name, p2.parentKey], ["p2", keyOf("linux")]); + assert.deepEqual( + linux.take().map((e) => (e as DebugProtocol.ThreadEvent).body.reason), + ["exited"], + ); + assert.deepEqual(await threadNames(linux), ["p3.t6", "p4.t7"]); + assert.deepEqual(await threadNames(await child("p2")), ["t3", "t5"]); + + listener.contextChanged!([{ ...ctx("p2", "linux"), Name: "bash" }]); + assert.deepEqual(host.renamed, [[p2.key, "bash"]]); + + p1.take(); + listener.contextRemoved!(["t1", "t2", "p1"]); + assert.deepEqual( + p1.take().map((e) => e.event), + ["thread", "thread", "terminated"], + ); + assert.deepEqual(host.removed.at(-1), keyOf("p1")); + assert.equal((await p1.request("disconnect")).success, true); + assert.deepEqual(root.take(), []); + + // A thread that gets children becomes a container, and moves to its own session. + listener.contextAdded!([ctx("t4", "idle", true)]); + const idle = host.added.at(-1)!; + assert.deepEqual([idle.name, idle.parentKey], ["idle", undefined]); + assert.deepEqual( + (root.take() as DebugProtocol.ThreadEvent[]).map((e) => e.body.reason), + ["exited"], + ); + assert.deepEqual(await threadNames(root), ["spare1", "spare2"]); + assert.deepEqual(await threadNames(await child("idle")), ["idle", "t4"]); + + // Back in the root session, a suspended thread is reported stopped there. + // It caused the last stop, so it gets the focus again. + listener.contextSuspended!("idle", 0x2000, "Suspended", undefined); + root.take(); + listener.contextRemoved!(["t4"]); + assert.deepEqual(host.removed.at(-1), idle.key); + const moved = root.take().filter((e) => e.event === "thread" || e.event === "stopped"); + assert.deepEqual( + moved.map((e) => e.event), + ["thread", "stopped"], + ); + assert.equal((moved[1] as DebugProtocol.StoppedEvent).body.preserveFocusHint, undefined); + assert.deepEqual(await threadNames(root), ["idle", "spare1", "spare2"]); +}); + +// A top-level CPU next to an OS awareness tracker would be hidden in the +// root session, as its only thread, so it gets a session of its own, named +// by the contexts down to it. +test("a lone thread next to child sessions gets a session of its own", async () => { + const { root, host, listener, child, threadNames } = await rootSession(); + listener.contextRemoved!(["idle", "cpu1"]); + // board has a single CPU, so it has no session; cpu0 would be the only + // thread of the root session. + const lone = host.added.at(-1)!; + assert.deepEqual([lone.name, lone.parentKey], ["board.cpu0", undefined]); + assert.deepEqual(await threadNames(root), []); + assert.deepEqual(await threadNames(await child("board.cpu0")), ["cpu0"]); +}); + +// The connection is the root session's: when it ends, so do the children. +test("disconnecting the root session ends the child sessions", async () => { + const { root, host, child } = await rootSession(); + const board = await child("board"); + board.take(); + await root.request("disconnect"); + assert.deepEqual( + board.take().map((e) => e.event), + ["terminated"], + ); + assert.equal(host.removed.length, 4); +}); + +// Without a host all threads are in the root session, with full names. +test("without a host the threads are a flat list", async () => { + const { root, listener, threadNames } = await rootSession(false); + assert.deepEqual(await threadNames(root), ["board.cpu0", "board.cpu1", "linux.p1.t1", "linux.p1.t2", "idle"]); + root.take(); + listener.containerSuspended!("t2", 0x1000, "Breakpoint", undefined, ["cpu0", "cpu1", "t1", "t2", "idle"]); + const stops = root.take() as DebugProtocol.StoppedEvent[]; + assert.equal(stops.length, 1); + assert.equal(stops[0].body.allThreadsStopped, true); + assert.equal(stops[0].body.preserveFocusHint, undefined); + listener.contextAdded!([ctx("t5", "p1", true)]); + assert.deepEqual( + (root.take().filter((e) => e.event === "thread") as DebugProtocol.ThreadEvent[]).map((e) => e.body.reason), + ["started"], + ); +}); + +// A process with a single thread is shown as a thread of the session above, +// named by the contexts below that session. Repeated names are shown once. +test("containers with a single thread are shown as a thread", async () => { + const { root, host, listener, child, threadNames } = await rootSession(); + listener.contextAdded!([ + ctx("init", "linux"), + { ...ctx("init-thread", "init", true), Name: "init" }, + ctx("p3", "linux"), + ctx("worker", "p3", true), + ctx("solo"), + ctx("cpu", "solo", true), + ]); + // idle had a session of its own, as the only thread of the root session. + assert.deepEqual( + host.added.map((g) => g.name), + ["idle", "board", "linux", "p1"], + ); + assert.deepEqual(host.removed, [host.added[0].key]); + assert.deepEqual(await threadNames(await child("linux")), ["init", "p3.worker"]); + assert.deepEqual(await threadNames(root), ["idle", "solo.cpu"]); +}); + +// Only the thread that caused a stop shows its reason. With a step, the +// other threads are paused, not stepped. +test("only the trigger thread shows the stop reason", async () => { + const { listener, child } = await rootSession(); + const board = await child("board"); + const p1 = await child("p1"); + const idle = await child("idle"); + board.take(); + p1.take(); + idle.take(); + listener.containerSuspended!("t1", 0x1000, "Step", undefined, ["t1", "t2", "cpu0", "idle"]); + const [p1Stop, ...p1More] = p1.take() as DebugProtocol.StoppedEvent[]; + assert.deepEqual(p1More, []); + assert.deepEqual( + [p1Stop.body.description, p1Stop.body.allThreadsStopped, p1Stop.body.preserveFocusHint], + ["Step", true, undefined], + ); + // cpu1 runs, so cpu0 gets an event of its own. + const [boardStop, ...boardMore] = board.take() as DebugProtocol.StoppedEvent[]; + assert.deepEqual(boardMore, []); + assert.deepEqual( + [boardStop.body.reason, boardStop.body.description, boardStop.body.allThreadsStopped], + ["pause", "Paused", false], + ); + const [idleStop] = idle.take() as DebugProtocol.StoppedEvent[]; + assert.equal(idleStop.body.description, "Paused"); +}); + +// VS Code shows a session without threads as running: it is reported +// stopped, without a thread, while all threads below it are suspended. +test("sessions without threads follow the threads below them", async () => { + const { listener, child } = await rootSession(); + const linux = await child("linux"); + linux.take(); + listener.containerSuspended!("t1", 0x1000, "Breakpoint", undefined, ["t1"]); + assert.deepEqual(linux.take(), []); + listener.containerSuspended!("cpu0", 0x1000, "Suspended", undefined, ["cpu0", "cpu1", "t2", "idle"]); + const [stop, ...more] = linux.take() as DebugProtocol.StoppedEvent[]; + assert.deepEqual(more, []); + assert.equal(stop.event, "stopped"); + assert.deepEqual(stop.body, { + reason: "pause", + description: "Paused", + preserveFocusHint: true, + allThreadsStopped: false, + }); + listener.contextResumed!("cpu0"); + assert.deepEqual(linux.take(), []); + listener.contextResumed!("t2"); + const [resumed] = linux.take() as DebugProtocol.ContinuedEvent[]; + assert.equal(resumed.event, "continued"); + assert.equal(resumed.body.allThreadsContinued, true); + // A session that starts while all is suspended is stopped at once. + const late = await rootSession(); + late.listener.containerSuspended!("t1", 0x1000, "Suspended", undefined, ["t1", "t2"]); + const lateLinux = await late.child("linux"); + assert.deepEqual( + lateLinux.take().map((e) => e.event), + ["initialized", "stopped"], + ); +}); + +// Child sessions start after the stop is reported. Only the session of the +// thread that caused it takes the focus. +test("child sessions that start later leave the focus to the trigger", async () => { + const { listener, child } = await rootSession(); + listener.containerSuspended!("t2", 0x1000, "Breakpoint", undefined, ["cpu0", "cpu1", "t1", "t2", "idle"]); + const board = await child("board"); + const [boardStop] = board.take().filter((e) => e.event === "stopped") as DebugProtocol.StoppedEvent[]; + assert.equal(boardStop.body.preserveFocusHint, true); + assert.equal(boardStop.body.description, "Paused"); + const p1 = await child("p1"); + const [p1Stop] = p1.take().filter((e) => e.event === "stopped") as DebugProtocol.StoppedEvent[]; + assert.equal(p1Stop.body.preserveFocusHint, undefined); + assert.equal(p1Stop.body.description, "Breakpoint"); +}); + +// When attaching, getState gives each thread's own reason. A thread with a +// reason other than Suspended is reported first and gets the focus; the +// others with a reason of their own are reported too. +test("the initial state shows the reasons of the threads", async () => { + const suspended = (reason: string): RunControlState => ({ suspended: true, reason }); + const { root, child } = await rootSession(true, { + cpu0: suspended("Suspended"), + cpu1: suspended("Suspended"), + t1: suspended("Active"), + t2: suspended("Active"), + idle: suspended("Suspended"), + }); + const [rootStop] = root.take().filter((e) => e.event === "stopped") as DebugProtocol.StoppedEvent[]; + assert.equal(rootStop.body.description, "Paused"); + assert.equal(rootStop.body.preserveFocusHint, true); + const p1 = await child("p1"); + const stops = p1.take().filter((e) => e.event === "stopped") as DebugProtocol.StoppedEvent[]; + assert.deepEqual( + stops.map((e) => [e.body.description, e.body.allThreadsStopped, e.body.preserveFocusHint]), + [ + ["Active", true, undefined], + ["Active", false, true], + ], + ); +}); diff --git a/src/test/schema.test.ts b/src/test/schema.test.ts index be1ab49..21125bd 100644 --- a/src/test/schema.test.ts +++ b/src/test/schema.test.ts @@ -38,6 +38,8 @@ test("launchFields reads the simics-target-debug attributes from package.json", ["consoles.simicsCli.editingKeys", "boolean", "console", "Editing Keys"], ["stayInConsole", "boolean", "console", "Stay in Console"], ["connectTimeout", "number", "advanced", "Connect Timeout"], + ["callStackHierarchy", "boolean", "advanced", "Call Stack Hierarchy"], + ["callStackCompact", "boolean", "advanced", "Call Stack Compact"], ["disassemblyFunctionHeaders", "boolean", "advanced", "Disassembly Function Headers"], ["internalConsoleOptions", "enum", "advanced", "Debug Console"], ["traceTcf", "boolean", "advanced", "Trace TCF"],