From 600cd889343c34a1754cfbdfc6232067bb2207fb Mon Sep 17 00:00:00 2001 From: Andreas Ragnerstam Date: Tue, 24 Nov 2026 17:07:17 +0100 Subject: [PATCH 1/4] List agent path map rules in Path Maps view The agent can have path map rules that this session did not add, for example from add-pathmap-entry in Simics or from another client. The session already uses them to map paths, but the view did not show them. This made it hard to see why a path was mapped. Show them read-only under "Added Elsewhere", like the Symbol Files view does. Rules for another host are listed too, but marked as not used, since this client ignores them. Signed-off-by: Andreas Ragnerstam --- CHANGELOG.md | 3 ++ README.md | 7 +++-- src/pathMapView.ts | 58 ++++++++++++++++++++++++++++++++++--- src/pathMapper.ts | 54 +++++++++++++++++++++++++++------- src/tcfDebugSession.ts | 12 ++++++++ src/test/pathMapper.test.ts | 19 ++++++++++++ 6 files changed, 136 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d5001f..827cd97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ All notable changes to the Simics Target Debug extension will be documented here name of your own, or one picked like `take-snapshot` does. It uses the Simics `SimUtils` service, and is disabled when the agent does not have its snapshot commands. +- The Path Maps view lists the agent's rules from elsewhere, for example + added with `add-pathmap-entry` in Simics, read-only under + **Added Elsewhere**, like the Symbol Files view does. ### Changed diff --git a/README.md b/README.md index 529d8e7..f655144 100644 --- a/README.md +++ b/README.md @@ -758,8 +758,11 @@ in the current session's named configuration in `.vscode/launch.json` after confirmation, including scopes, removals and ordering. Workspace destinations are saved using `${workspaceFolder}`. Saving requires a workspace launch configuration with a unique name; session-only changes do not modify it. -The view manages this debug client's rules, not rules installed separately -on the agent (for example with `add-pathmap-entry`). +The view manages this debug client's rules. Rules the agent has from +elsewhere, for example added with `add-pathmap-entry` in Simics or by another +client, are listed read-only under **Added Elsewhere**, read with +`PathMap.get`. Rules for another host are listed too, but are not used. The +view is refreshed when the agent reports that its path map changed. ## Source layout diff --git a/src/pathMapView.ts b/src/pathMapView.ts index 27a4d30..bc8d2d6 100644 --- a/src/pathMapView.ts +++ b/src/pathMapView.ts @@ -2,7 +2,7 @@ import * as path from "path"; import * as vscode from "vscode"; import { activeRootSession } from "./contextSessionManager"; import { savePathMapRules, withWorkspaceFolder } from "./locateSource"; -import { PathMapRule, pathMapContextQuery } from "./pathMapper"; +import { ForeignPathMapRule, PathMapRule, pathMapContextQuery } from "./pathMapper"; import { promptPathMapScope } from "./pathMapScope"; const VIEW = "simics-target-debug.pathMap"; @@ -29,6 +29,49 @@ class PathMapItem extends vscode.TreeItem { } } +class ForeignPathMapItem extends vscode.TreeItem { + override readonly contextValue = "foreignPathMapRule"; + + constructor(rule: ForeignPathMapRule) { + super(rule.source); + const scope = rule.contextQuery ?? "all contexts"; + this.description = `${rule.destination} (${scope}${rule.used ? "" : `, host ${rule.host}`})`; + this.tooltip = [ + rule.source, + `To: ${rule.destination}`, + `Scope: ${scope}`, + rule.host && `Host: ${rule.host}`, + rule.id && `ID: ${rule.id}`, + !rule.used && "Not used, the rule is for another host", + ] + .filter(Boolean) + .join("\n"); + this.iconPath = new vscode.ThemeIcon("replace-all"); + } +} + +/** Read-only rules the agent has that the session did not add. */ +class ForeignPathMapRulesItem extends vscode.TreeItem { + constructor(readonly children: vscode.TreeItem[]) { + super("Added Elsewhere", vscode.TreeItemCollapsibleState.Expanded); + this.id = "foreignPathMapRules"; + this.contextValue = "foreignPathMapRules"; + this.tooltip = + "Path map rules the agent has that this session did not add, for example with " + + "add-pathmap-entry in Simics or by another client"; + this.iconPath = new vscode.ThemeIcon("references"); + } +} + +async function foreignRuleItems(session: vscode.DebugSession): Promise { + try { + const { rules } = (await session.customRequest("getForeignPathMapRules")) as { rules: ForeignPathMapRule[] }; + return rules.map((rule) => new ForeignPathMapItem(rule)); + } catch (err) { + return [new vscode.TreeItem(`Could not read the agent's path map: ${errorMessage(err)}`)]; + } +} + class PathMapProvider implements vscode.TreeDataProvider, vscode.Disposable { private readonly changes = new vscode.EventEmitter(); readonly onDidChangeTreeData = this.changes.event; @@ -41,19 +84,26 @@ class PathMapProvider implements vscode.TreeDataProvider, vscod return item; } - async getChildren(): Promise { + async getChildren(element?: vscode.TreeItem): Promise { + if (element instanceof ForeignPathMapRulesItem) { + return element.children; + } const session = activeRootSession(); if (session?.type !== DEBUG_TYPE) { return []; } try { - const rules = await getRules(session); + const [rules, foreignRules] = await Promise.all([getRules(session), foreignRuleItems(session)]); if (session !== activeRootSession()) { return []; } - return rules.length + const items: vscode.TreeItem[] = rules.length ? rules.map((rule, i) => new PathMapItem(rule, i, session)) : [new vscode.TreeItem("No session path map rules")]; + if (foreignRules.length > 0) { + items.push(new ForeignPathMapRulesItem(foreignRules)); + } + return items; } catch (err) { return [new vscode.TreeItem(`Could not load path map: ${errorMessage(err)}`)]; } diff --git a/src/pathMapper.ts b/src/pathMapper.ts index 06a1769..7a49b6d 100644 --- a/src/pathMapper.ts +++ b/src/pathMapper.ts @@ -16,6 +16,17 @@ export interface PathMapRule { contextQuery?: string; } +/** A rule the agent has that this client did not set. */ +export interface ForeignPathMapRule { + source: string; + destination: string; + contextQuery?: string; + id?: string; + host?: string; + /** False if the rule is for another host, so this client does not use it. */ + used: boolean; +} + export interface TargetPath { path: string; /** Only set when local reverse mapping must be limited to this context. */ @@ -264,6 +275,27 @@ export class PathMapper { } } + /** + * Rules the agent has that this client did not set, for example ones + * added with the Simics command add-pathmap-entry or by other clients. + * Read from the agent on each call, and errors are not hidden. + */ + async foreignRules(): Promise { + if (!this.service) { + return []; + } + return (await this.service.get()) + .filter((r) => this.isForeignRule(r)) + .map((r) => ({ + source: r.Source!, + destination: r.Destination!, + ...(typeof r.ContextQuery === "string" && r.ContextQuery && { contextQuery: r.ContextQuery }), + ...(typeof r.ID === "string" && { id: r.ID }), + ...(typeof r.Host === "string" && r.Host && { host: r.Host }), + used: !r.Host || isLocalHost(r.Host), + })); + } + /** Rules the agent knows from elsewhere that apply to this host. */ private otherAgentRules(): Promise { if (!this.service) { @@ -271,20 +303,20 @@ export class PathMapper { } this.agentRules ??= this.service .get() - .then((rules) => - rules.filter( - (r) => - typeof r.Source === "string" && - r.Source.length > 0 && - typeof r.Destination === "string" && - r.Destination.length > 0 && - !(typeof r.ID === "string" && r.ID.startsWith(this.idPrefix)) && - (!r.Host || isLocalHost(r.Host)), - ), - ) + .then((rules) => rules.filter((r) => this.isForeignRule(r) && (!r.Host || isLocalHost(r.Host)))) .catch(() => []); return this.agentRules; } + + private isForeignRule(r: PathMapRuleProperties): boolean { + return ( + typeof r.Source === "string" && + r.Source.length > 0 && + typeof r.Destination === "string" && + r.Destination.length > 0 && + !(typeof r.ID === "string" && r.ID.startsWith(this.idPrefix)) + ); + } } /** diff --git a/src/tcfDebugSession.ts b/src/tcfDebugSession.ts index 6862f12..e79f05a 100644 --- a/src/tcfDebugSession.ts +++ b/src/tcfDebugSession.ts @@ -665,6 +665,18 @@ export class TcfDebugSession extends DebugSession { this.sendResponse(response); return; } + if (command === "getForeignPathMapRules") { + await this.handle( + response, + async () => { + response.body = { + rules: this.pathMapper && !this.disconnecting ? await this.pathMapper.foreignRules() : [], + }; + }, + false, + ); + return; + } if (command === "setPathMapRules") { await this.handle(response, async () => { const input = args as diff --git a/src/test/pathMapper.test.ts b/src/test/pathMapper.test.ts index e0e5bb3..bed2419 100644 --- a/src/test/pathMapper.test.ts +++ b/src/test/pathMapper.test.ts @@ -300,6 +300,25 @@ test("toTarget skips the rules this client sent itself", async () => { assert.equal(await mapper.toTarget("/elsewhere/a.c"), "/elsewhere/a.c"); }); +// The Path Maps view lists the agent's other rules, also ones for other +// hosts, but not this client's own or incomplete ones. +test("foreignRules lists the rules this client did not set", async () => { + const agentRules: PathMapRuleProperties[] = [ + { ID: "simics-1", Source: "/agent", Destination: "/host", ContextQuery: "ID=cpu0" }, + { Source: "/remote", Destination: "/r", Host: "some-other-host.invalid" }, + { Source: "/nodest", Destination: "" }, + ]; + const fake = fakePathMapService(agentRules); + const mapper = new PathMapper([{ source: "/build", destination: "/ws" }], fake.service); + await mapper.apply(); + agentRules.push(...fake.sets[0]); + assert.deepEqual(await mapper.foreignRules(), [ + { id: "simics-1", source: "/agent", destination: "/host", contextQuery: "ID=cpu0", used: true }, + { source: "/remote", destination: "/r", host: "some-other-host.invalid", used: false }, + ]); + await assert.rejects(new PathMapper([], fakePathMapService(new Error("failed")).service).foreignRules()); +}); + // The common tail of the two paths is dropped, so the rule also maps the // other files of the source tree. test("deriveRule maps the differing directory prefixes", () => { From 182064fc535de8943962240996024d4ce7e692cc Mon Sep 17 00:00:00 2001 From: Andreas Ragnerstam Date: Wed, 25 Nov 2026 09:03:02 +0100 Subject: [PATCH 2/4] Share the context picker for symbol files Symbol files had their own picker that took one context, while function breakpoints had a checklist for several. Both now use the same checklist, so they look and work the same. For symbol files it can switch to a context query and accept IDs or names the agent does not list. A symbol file can apply to several contexts with a "contexts" list. MemoryMap.set takes one context, so the region is set in the map of each context. The old "context" string still works but is deprecated. "contexts" and "contextQuery" can no longer be set together. One choice is easier to understand and to edit. Old configurations with both are ignored with an error. The launch configurations form gets a Contexts column for symbol files: all contexts, a list of contexts, or a query. It can pick the contexts from a running session to the same agent. Signed-off-by: Andreas Ragnerstam --- CHANGELOG.md | 10 + README.md | 58 +++--- package.json | 19 +- src/contextChoices.ts | 99 ++++++++++ src/contextPicker.ts | 177 +++++++++++++++++ src/extension.ts | 178 +++++++----------- src/functionBreakpoint.ts | 49 ----- src/launchSettings/editorProvider.ts | 78 +++++++- src/launchSettings/protocol.ts | 2 + src/launchSettings/schema.ts | 97 +++++++++- src/symbolFiles.ts | 111 +++++++---- src/tcfDebugSession.ts | 32 ++-- src/test/contextChoices.test.ts | 46 +++++ src/test/schema.test.ts | 35 +++- src/test/symbolFiles.test.ts | 105 +++++++++-- src/test/tcfDebugSession.test.ts | 53 ++++++ src/webview/launchSettings/App.tsx | 2 + .../launchSettings/components/controls.tsx | 111 ++++++++++- src/webview/launchSettings/styles.css | 11 ++ 19 files changed, 1003 insertions(+), 270 deletions(-) create mode 100644 src/contextChoices.ts create mode 100644 src/contextPicker.ts create mode 100644 src/test/contextChoices.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 827cd97..3cef71b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ All notable changes to the Simics Target Debug extension will be documented here - The Path Maps view lists the agent's rules from elsewhere, for example added with `add-pathmap-entry` in Simics, read-only under **Added Elsewhere**, like the Symbol Files view does. +- A symbol file can apply to several contexts: `symbolFiles` entries take + a `contexts` list of IDs or names. The file is added to the memory map of + each context. ### Changed @@ -40,6 +43,13 @@ All notable changes to the Simics Target Debug extension will be documented here services and message types. Stay in Console is gone from TCF Launch Configurations, turn off `debug.focusEditorOnBreak` instead. +- Symbol files and function breakpoints pick their contexts with the same + checklist. For symbol files, a button in its title bar switches to a + context query. In TCF Launch Configurations, the Contexts column of Symbol + Files chooses all contexts, a list of contexts, or a query, and can pick + contexts from a running session to the agent. +- The `context` of a symbol file is deprecated, use `contexts`. A symbol file + can no longer have both contexts and a `contextQuery`. - In TCF Launch Configurations, the Start, Duplicate and Delete buttons above the form, and the Add and Delete All buttons above the list, stay visible when you scroll. diff --git a/README.md b/README.md index f655144..c36d876 100644 --- a/README.md +++ b/README.md @@ -292,12 +292,12 @@ session stay listed so they are not dropped by accident. The breakpoint is replaced by one with the new name and the same enabled state, condition, hit count, and log message, so it moves to the end of the Breakpoints panel. -In **Symbol Files**, right-click a configured symbol file with a context and +In **Symbol Files**, right-click a configured symbol file with contexts and select **Add Function Breakpoint...** to enter a symbol directly. The breakpoint -uses the file's context rather than the selected call-stack core. Context names +uses the file's contexts rather than the selected call-stack core. Context names are resolved to exact TCF IDs; unavailable or ambiguous contexts produce an error -instead of creating a global breakpoint. Files without a context do not offer -this action. +instead of creating a global breakpoint. Files for all contexts or for a context +query do not offer this action. An address only has a meaning in one address space, so an instruction breakpoint is limited to the process of the context shown in the Disassembly @@ -559,6 +559,12 @@ buttons in the editor title switch between the form and the text of under **Advanced** at the end, with `connectTimeout`. Others, like `preLaunchTask`, are listed under **Other Attributes** when set, and can be edited in the text. +- The **Contexts** column of Symbol Files chooses all contexts, a list of + context IDs or names separated by commas, or a context query. Its checklist + button picks them with the checklist of the Symbol Files view, from the + contexts of a running debug session to the configuration's agent; without + one, type them. Changing the contexts writes `contexts` or `contextQuery` + and removes the old single `context`. - The options that apply to all configurations are [settings](#settings), see the link at the end of the form. @@ -577,7 +583,7 @@ addition to) `add-symbol-file` in Simics: "port": 1534, "symbolFiles": [ { "path": "${workspaceFolder}/build/firmware.elf" }, - { "path": "build/app.elf", "context": "board.mb.cpu0.core[0][0]" }, + { "path": "build/app.elf", "contexts": ["board.mb.cpu0.core[0][0]", "board.mb.cpu0.core[0][1]"] }, { "path": "build/driver.elf", "contextQuery": "**/HasState=true", "address": "0x40000000" }, { "path": "build/module.elf", "address": "0xff000", "absolute": true } ] @@ -587,13 +593,15 @@ addition to) `add-symbol-file` in Simics: | Property | Description | |----------------|-------------| | `path` | The symbol file (ELF with debug information), as seen by the agent. Relative paths are relative to the workspace folder. | -| `context` | ID or name of the context the symbols apply to. | +| `contexts` | IDs or names of the contexts the symbols apply to. | | `contextQuery` | A TCF context query selecting the contexts the symbols apply to, for example `**/HasState=true` for all processors. | +| `context` | Deprecated: one context ID or name, the same as `contexts` with one entry. | | `address` | Relocation offset added to all addresses in the file, like the Simics command `add-symbol-file -relative`. It may be negative, for example `"-0x1000"`. If not set, the addresses in the file are used. With `absolute`, a load address instead, see below. | | `absolute` | If `true`, `address` is a load address: the symbols are relocated so that the loadable segment with the lowest file offset (normally the first one, see `readelf -lW`) is at this address. | -Without `context` and `contextQuery` the symbols apply to all contexts. Both -can be combined. +Without `contexts` and `contextQuery` the symbols apply to all contexts. Set +only one of them; an entry with both is ignored with an error in the Debug +Console. The two ways of relocating differ in what the address refers to. For a file whose first loadable segment is linked at 0x3ff000, with `.text` at 0x400000: @@ -606,8 +614,9 @@ whose first loadable segment is linked at 0x3ff000, with `.text` at 0x400000: This works like "Load symbols" in the Eclipse TCF client: each file becomes a memory map region that is sent to the agent with `MemoryMap.set` when -attaching, for the given context or for all contexts (`""`) with a -`ContextQuery`. The region has the `FileName`, plus the standard `BaseAddress` +attaching, for each of the given contexts or for all contexts (`""`) with a +`ContextQuery`. `MemoryMap.set` takes a single context, so a file with several +contexts is set in the memory map of each one. The region has the `FileName`, plus the standard `BaseAddress` property for an offset (which is what Simics `add-symbol-file -relative` uses too) or `Addr` for an absolute load address. The agent removes the regions when the debug session ends. File names in the memory map are translated with @@ -615,19 +624,22 @@ the path map rules, so `pathMap` also applies to symbol files. To add a symbol file after attaching, open **Symbol Files** in Run and Debug and use its **+** button (or **Simics Target Debug: Add Symbol File...** in the -Command Palette). Enter the path as seen by the agent, an optional context -ID/name and context query, and how the symbols are placed: the file addresses, -a relocation offset (like `-relative`), or an absolute load address. Relative -paths are resolved against the debug session's workspace folder. As you type -the path, local files and folders are suggested; select a folder to browse it, -or enter a path directly if the file is only available to the agent. The -context picker suggests cores returned by the agent's -`ContextQuery.query("HasState=true")` (or stateful RunControl contexts if that -service is unavailable). Selecting one uses its ID; you can also enter a name -directly or select **All contexts**. New entries are added to those from +Command Palette). Enter the path as seen by the agent, the contexts, and how +the symbols are placed: the file addresses, a relocation offset (like +`-relative`), or an absolute load address. Relative paths are resolved against +the debug session's workspace folder. As you type the path, local files and +folders are suggested; select a folder to browse it, or enter a path directly +if the file is only available to the agent. The contexts are picked with the +same checklist as for function breakpoints: it lists the cores returned by the +agent's `ContextQuery.query("HasState=true")` (or stateful RunControl contexts +if that service is unavailable), with the selected call-stack context first. +Check one or more of them, or none for all contexts. Checking a listed context +uses its ID; type an ID or name that is not listed to check it too. The filter +button in its title bar switches to entering a TCF context query instead, and +the checklist button there switches back. New entries are added to those from `symbolFiles` for the running session only unless explicitly saved. Use the -pencil action on a file in the Symbol Files view to edit its path, context, -context query, or load address. The same view lets you reload or remove a +pencil action on a file in the Symbol Files view to edit its path, contexts +(or context query), or load address. The same view lets you reload or remove a mapping. If a configured file is missing on the VS Code host at startup, a warning offers to update its path using the file picker. The file may still exist on a remote TCF agent, so the warning can be dismissed. Mapping edits @@ -640,7 +652,7 @@ Use **Save Symbol Files to Debug Configuration** (the save button in the Symbol Files view, also available in the Command Palette) to persist the session's current list. After confirmation, it replaces `symbolFiles` in the active session's uniquely named workspace configuration in -`.vscode/launch.json`, including removals, context IDs, context queries, +`.vscode/launch.json`, including removals, contexts, context queries, relocation offsets, and absolute load addresses. Saving an empty list clears the configured symbol files. Paths are saved as reported by the session, since symbol files are opened on the agent and may not exist on this host. diff --git a/package.json b/package.json index f89e2fe..6b0b7d1 100644 --- a/package.json +++ b/package.json @@ -883,13 +883,24 @@ "format": "file-path", "description": "Path of the symbol file, as seen by the agent. Relative paths are relative to the workspace folder." }, - "context": { - "type": "string", - "description": "ID or name of the context the symbols apply to. If neither context nor contextQuery is set, the symbols apply to all contexts." + "contexts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true, + "description": "IDs or names of the contexts the symbols apply to. If neither contexts nor contextQuery is set, the symbols apply to all contexts." }, "contextQuery": { "type": "string", - "description": "TCF context query selecting the contexts the symbols apply to, for example \"**/HasState=true\"." + "minLength": 1, + "description": "TCF context query selecting the contexts the symbols apply to, for example \"**/HasState=true\". Use either contexts or contextQuery, not both." + }, + "context": { + "type": "string", + "description": "ID or name of the context the symbols apply to.", + "deprecationMessage": "Use \"contexts\" instead, a list of context IDs or names." }, "address": { "type": [ diff --git a/src/contextChoices.ts b/src/contextChoices.ts new file mode 100644 index 0000000..7fa2c2a --- /dev/null +++ b/src/contextChoices.ts @@ -0,0 +1,99 @@ +/* + * The items of the context picker shared by function breakpoints, symbol + * files and the launch configurations form. No vscode imports, so that it + * can be tested and used by the webview. + */ + +/** A context the agent offers to pick, from the getSymbolContexts or getFunctionBreakpointContexts request. */ +export interface TargetContext { + id: string; + name: string; + /** The DAP thread of the context, if it has one. */ + threadId?: number; +} + +/** The contexts something applies to: listed IDs or names (empty for all), or a TCF context query. */ +export type ContextScope = { contexts: string[] } | { contextQuery: string }; + +export interface ContextChoice { + label: string; + description?: string; + detail?: string; + /** What picking the item gives: the checked ID or name it matched, else the context ID. */ + value: string; + picked: boolean; +} + +/** + * The items of the context checklist: the selected call-stack context first, + * then the session's contexts, then checked entries the session does not + * have, so that editing never drops part of a scope silently. A checked entry + * matches a context by ID, or else by name, and is kept as it was written. + */ +export function contextChoices( + contexts: readonly TargetContext[], + checked: readonly string[], + selectedId?: string, +): ContextChoice[] { + const ids = new Set(contexts.map((context) => context.id)); + const matched = new Set(); + const entryFor = (context: TargetContext): string | undefined => { + const entry = checked.find((e) => e === context.id) ?? checked.find((e) => !ids.has(e) && e === context.name); + if (entry !== undefined) { + matched.add(entry); + } + return entry; + }; + const selected = contexts.find((context) => context.id === selectedId); + const ordered = selected ? [selected, ...contexts.filter((context) => context !== selected)] : contexts; + const choices: ContextChoice[] = ordered.map((context) => { + const entry = entryFor(context); + const choice: ContextChoice = { + label: context.name, + description: context.id, + value: entry ?? context.id, + picked: entry !== undefined, + }; + if (context === selected) { + choice.description = "Selected call-stack context"; + choice.detail = context.id; + } + return choice; + }); + return [ + ...choices, + ...checked + .filter((entry) => !matched.has(entry)) + .map((entry) => ({ + label: entry, + description: "Not available in this session", + value: entry, + picked: true, + })), + ]; +} + +/** The distinct values of picked items, in order. */ +export function pickedValues(choices: readonly Pick[]): string[] { + return [...new Set(choices.map((choice) => choice.value))]; +} + +/** Parses a comma-separated list of context IDs or names. */ +export function parseContextList(text: string): string[] { + return [ + ...new Set( + text + .split(",") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0), + ), + ]; +} + +/** "all contexts", the listed contexts, or "contexts matching ". */ +export function describeContextScope(scope: { contexts?: readonly string[]; contextQuery?: string }): string { + if (scope.contextQuery !== undefined) { + return `contexts matching ${scope.contextQuery}`; + } + return scope.contexts && scope.contexts.length > 0 ? scope.contexts.join(", ") : "all contexts"; +} diff --git a/src/contextPicker.ts b/src/contextPicker.ts new file mode 100644 index 0000000..42dfd7c --- /dev/null +++ b/src/contextPicker.ts @@ -0,0 +1,177 @@ +import * as vscode from "vscode"; +import { ContextChoice, ContextScope, TargetContext, contextChoices, pickedValues } from "./contextChoices"; + +/** + * The contexts of a session to pick from: the cores (contexts with state), + * and with `includeContainers` all run control contexts. + */ +export function listContexts(session: vscode.DebugSession, includeContainers = false): Promise { + return session.customRequest( + "getFunctionBreakpointContexts", + includeContainers ? { includeContainers: true } : undefined, + ) as Promise; +} + +export interface PickContextsOptions { + title: string; + /** The contexts to offer. Checked entries that are not among them are kept as extra items. */ + contexts: readonly TargetContext[]; + /** The scope to start with. */ + scope: ContextScope; + /** A context to list first, such as the one selected in the Call Stack view. */ + selectedId?: string; + placeholder?: string; + /** Offer a button to enter a TCF context query instead of checking contexts. */ + allowQuery?: boolean; + /** Offer typed text as a context ID or name to check, for contexts that are not listed. */ + allowTyped?: boolean; +} + +/** The scope picked, or what was entered when the user switched to the other way of picking. */ +type Step = { scope: ContextScope } | { switched: T } | undefined; + +const QUERY_BUTTON: vscode.QuickInputButton = { + iconPath: new vscode.ThemeIcon("filter"), + tooltip: "Use a Context Query Instead", +}; +const CONTEXTS_BUTTON: vscode.QuickInputButton = { + iconPath: new vscode.ThemeIcon("checklist"), + tooltip: "Check Contexts Instead", +}; + +/** + * Lets the user check the contexts something applies to, or enter a context + * query when `allowQuery` is set. No checked context means all contexts. + * Returns undefined if cancelled. + */ +export async function pickContexts(options: PickContextsOptions): Promise { + let byQuery = "contextQuery" in options.scope; + let contexts = "contexts" in options.scope ? options.scope.contexts : []; + let query = "contextQuery" in options.scope ? options.scope.contextQuery : ""; + for (;;) { + if (byQuery) { + const step = await enterQuery(options, query); + if (step === undefined || "scope" in step) { + return step?.scope; + } + query = step.switched; + } else { + const step = await check(options, contexts); + if (step === undefined || "scope" in step) { + return step?.scope; + } + contexts = step.switched; + } + byQuery = !byQuery; + } +} + +type Item = ContextChoice & vscode.QuickPickItem; + +function check(options: PickContextsOptions, initial: readonly string[]): Promise> { + return new Promise((resolve) => { + const picker = vscode.window.createQuickPick(); + picker.title = options.title; + picker.placeholder = options.placeholder ?? "Check the contexts, or check none for all contexts"; + picker.canSelectMany = true; + picker.matchOnDescription = true; + picker.matchOnDetail = true; + picker.buttons = options.allowQuery ? [QUERY_BUTTON] : []; + let finished = false; + + function finish(step: Step): void { + if (finished) { + return; + } + finished = true; + picker.hide(); + picker.dispose(); + resolve(step); + } + + /** The typed text, if it is offered as an item because it matches no listed item. */ + let typedItem: Item | undefined; + /** True if Enter takes the typed text too, as it filters out all listed items. */ + let typedOnly = false; + + function update(checked: readonly string[]): void { + const items: Item[] = contextChoices(options.contexts, checked, options.selectedId); + const typed = picker.value.trim(); + typedItem = undefined; + if ( + options.allowTyped && + typed && + !items.some((item) => item.value === typed || item.label === typed || item.detail === typed) + ) { + const lower = typed.toLowerCase(); + typedOnly = !items.some((item) => + [item.label, item.description, item.detail].some((text) => text?.toLowerCase().includes(lower)), + ); + typedItem = { + label: typed, + description: typedOnly + ? "Press Enter or check to use this context ID or name" + : "Check to use this context ID or name", + value: typed, + picked: false, + alwaysShow: true, + }; + items.unshift(typedItem); + } + picker.items = items; + picker.selectedItems = items.filter((item) => item.picked); + } + + if (options.allowTyped) { + picker.onDidChangeValue(() => update(pickedValues(picker.selectedItems))); + } + picker.onDidTriggerButton(() => finish({ switched: pickedValues(picker.selectedItems) })); + picker.onDidAccept(() => { + const picked = pickedValues(picker.selectedItems); + if (typedItem && typedOnly && !picked.includes(typedItem.value)) { + picked.push(typedItem.value); + } + finish({ scope: { contexts: picked } }); + }); + picker.onDidHide(() => finish(undefined)); + update(initial); + picker.show(); + }); +} + +function enterQuery(options: PickContextsOptions, initial: string): Promise> { + return new Promise((resolve) => { + const input = vscode.window.createInputBox(); + input.title = options.title; + input.prompt = "TCF context query, for example **/HasState=true"; + input.placeholder = "Context query"; + input.value = initial; + input.buttons = [CONTEXTS_BUTTON]; + let finished = false; + + function finish(step: Step): void { + if (finished) { + return; + } + finished = true; + input.hide(); + input.dispose(); + resolve(step); + } + + input.onDidChangeValue(() => { + input.validationMessage = undefined; + }); + input.onDidTriggerButton(() => finish({ switched: input.value.trim() })); + input.onDidAccept(() => { + const query = input.value.trim(); + if (!query) { + input.validationMessage = "Enter a context query, or use the button to check contexts"; + return; + } + finish({ scope: { contextQuery: query } }); + }); + input.onDidHide(() => finish(undefined)); + input.show(); + }); +} diff --git a/src/extension.ts b/src/extension.ts index a0a7cfb..e3155f5 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -8,13 +8,9 @@ import { parseInstructionReference } from "./disassembly"; import { registerFunctionHeaderFileSystem } from "./functionHeaderFileSystem"; import { applyAndSave, registerLaunchSettings } from "./launchSettings/editorProvider"; import { setNamedConfigurationValue } from "./launchSettings/launchJson"; -import { - FunctionBreakpointContext, - FunctionBreakpointContextChoice, - formatFunctionBreakpointName, - functionBreakpointContextChoices, - parseFunctionBreakpointName, -} from "./functionBreakpoint"; +import { formatFunctionBreakpointName, parseFunctionBreakpointName } from "./functionBreakpoint"; +import { ContextScope, TargetContext, describeContextScope } from "./contextChoices"; +import { listContexts, pickContexts } from "./contextPicker"; import { MissingSource, SourceLocator } from "./locateSource"; import { pathMapProblems } from "./pathMapper"; import { registerPathMapView } from "./pathMapView"; @@ -23,7 +19,7 @@ import { ForeignSymbolFile, SymbolFileConfig, describeForeignSymbolFile, - symbolFileBreakpointContext, + symbolFileBreakpointContexts, } from "./symbolFiles"; import { suggestSymbolPaths } from "./symbolPath"; import { registerConsolesView } from "./consolesView"; @@ -263,13 +259,15 @@ async function addFunctionBreakpointInContext( } const threadId = frame?.threadId ?? (active?.session.id === session.id ? active.threadId : undefined); try { - const contexts = await functionBreakpointContexts(session, symbolFile !== undefined); + const contexts = await listContexts(session, symbolFile !== undefined); const selected = contexts.find((context) => threadId !== undefined && context.threadId === threadId); const contextIds = symbolFile - ? [symbolFileBreakpointContext(symbolFile.file, contexts)] - : await pickFunctionBreakpointContexts( + ? symbolFileBreakpointContexts(symbolFile.file, contexts) + : await pickBreakpointContexts( "Function Breakpoint Contexts", - functionBreakpointContextChoices(contexts, selected ? [selected.id] : [], selected?.id), + contexts, + selected ? [selected.id] : [], + selected, ); if (!contextIds) { return; @@ -295,29 +293,21 @@ async function addFunctionBreakpointInContext( } } -function functionBreakpointContexts( - session: vscode.DebugSession, - includeContainers: boolean, -): Promise<(FunctionBreakpointContext & { threadId?: number })[]> { - return session.customRequest( - "getFunctionBreakpointContexts", - includeContainers ? { includeContainers: true } : undefined, - ) as Promise<(FunctionBreakpointContext & { threadId?: number })[]>; -} - /** Returns the checked context IDs, empty for all contexts, or undefined if cancelled. */ -async function pickFunctionBreakpointContexts( +async function pickBreakpointContexts( title: string, - choices: FunctionBreakpointContextChoice[], + contexts: TargetContext[], + checked: string[], + selected: TargetContext | undefined, ): Promise { - const picked = await vscode.window.showQuickPick(choices, { + const scope = await pickContexts({ title, - placeHolder: "Check the cores to stop in, or check none for all contexts", - canPickMany: true, - matchOnDescription: true, - matchOnDetail: true, + contexts, + scope: { contexts: checked }, + selectedId: selected?.id, + placeholder: "Check the cores to stop in, or check none for all contexts", }); - return picked?.map((choice) => choice.id); + return scope && "contexts" in scope ? scope.contexts : undefined; } /** @@ -369,13 +359,10 @@ async function editFunctionBreakpointContexts(): Promise { return; } try { - const contexts = await functionBreakpointContexts(session, false); + const contexts = await listContexts(session); const threadId = active?.session.id === session.id ? active.threadId : undefined; const selected = contexts.find((context) => threadId !== undefined && context.threadId === threadId); - const ids = await pickFunctionBreakpointContexts( - `Contexts for ${location}`, - functionBreakpointContextChoices(contexts, contextIds, selected?.id), - ); + const ids = await pickBreakpointContexts(`Contexts for ${location}`, contexts, contextIds, selected); if (!ids) { return; } @@ -417,15 +404,8 @@ async function addSymbolFile(symbolFiles: SymbolFilesProvider): Promise { if (filePath === undefined) { return; } - const contextId = await promptSymbolContext(session); - if (contextId === undefined) { - return; - } - const contextQuery = await vscode.window.showInputBox({ - title: "Context Query", - prompt: "Optional TCF context query, for example **/HasState=true", - }); - if (contextQuery === undefined) { + const scope = await promptSymbolScope(session, { contexts: [] }); + if (scope === undefined) { return; } const load = await promptLoadAddress(); @@ -439,8 +419,7 @@ async function addSymbolFile(symbolFiles: SymbolFilesProvider): Promise { session.workspaceFolder && !path.isAbsolute(resolvedPath) ? path.join(session.workspaceFolder.uri.fsPath, resolvedPath) : resolvedPath, - ...(contextId.trim() && { context: contextId.trim() }), - ...(contextQuery.trim() && { contextQuery: contextQuery.trim() }), + ...scopeConfig(scope), ...load, }; try { @@ -641,8 +620,7 @@ async function editSymbolFile(item?: SymbolFileViewItem): Promise { const selected = await vscode.window.showQuickPick( [ { label: "Path", description: file.path, field: "path" }, - { label: "Context", description: file.context || "All contexts", field: "context" }, - { label: "Context Query", description: file.contextQuery || "None", field: "contextQuery" }, + { label: "Contexts", description: capitalize(describeContextScope(file)), field: "contexts" }, { label: "Load Address", description: describeLoadAddress(file), field: "address" }, ], { title: "Edit Symbol Mapping", placeHolder: "Select a field to update" }, @@ -661,22 +639,17 @@ async function editSymbolFile(item?: SymbolFileViewItem): Promise { session.workspaceFolder && !path.isAbsolute(trimmed) ? path.join(session.workspaceFolder.uri.fsPath, trimmed) : trimmed; - } else if (selected.field === "context") { - const contextId = await promptSymbolContext(session, file.context ?? ""); - if (contextId === undefined) { - return; - } - updated.context = contextId.trim(); - } else if (selected.field === "contextQuery") { - const contextQuery = await vscode.window.showInputBox({ - title: "Context Query", - prompt: "Leave blank to remove the context query", - value: file.contextQuery ?? "", - }); - if (contextQuery === undefined) { + } else if (selected.field === "contexts") { + const scope = await promptSymbolScope( + session, + file.contextQuery !== undefined ? { contextQuery: file.contextQuery } : { contexts: file.contexts ?? [] }, + ); + if (scope === undefined) { return; } - updated.contextQuery = contextQuery.trim() || undefined; + delete updated.contexts; + delete updated.contextQuery; + Object.assign(updated, scopeConfig(scope)); } else { const load = await promptLoadAddress(file); if (load === undefined) { @@ -691,7 +664,7 @@ async function editSymbolFile(item?: SymbolFileViewItem): Promise { } if ( updated.path === file.path && - updated.context === file.context && + (updated.contexts ?? []).join("\n") === (file.contexts ?? []).join("\n") && updated.contextQuery === file.contextQuery && updated.address === file.address && (updated.absolute === true) === (file.absolute === true) @@ -812,58 +785,39 @@ async function replaceSymbolFile( } } -interface SymbolContextChoice extends vscode.QuickPickItem { - id: string; -} - -async function promptSymbolContext(session: vscode.DebugSession, initialContext = ""): Promise { - let contexts: { id: string; name: string }[]; +/** Asks which contexts a symbol file applies to. Returns undefined when cancelled. */ +async function promptSymbolScope(session: vscode.DebugSession, scope: ContextScope): Promise { + let contexts: TargetContext[] = []; try { - contexts = (await session.customRequest("getSymbolContexts")) as { id: string; name: string }[]; + contexts = await listContexts(session); } catch (err) { void vscode.window.showWarningMessage( - `Could not list TCF contexts: ${err instanceof Error ? err.message : String(err)}`, + `Could not list TCF contexts, type their IDs or names: ${err instanceof Error ? err.message : String(err)}`, ); - return vscode.window.showInputBox({ - title: "Context ID or Name", - prompt: "Leave blank to apply to all contexts", - value: initialContext, - }); } - return new Promise((resolve) => { - const picker = vscode.window.createQuickPick(); - picker.title = "Context ID or Name"; - picker.placeholder = "Choose a context, type an ID or name, or select All contexts"; - picker.matchOnDescription = true; - let finished = false; - - function finish(value?: string): void { - if (finished) { - return; - } - finished = true; - picker.hide(); - picker.dispose(); - resolve(value); - } + const active = vscode.debug.activeStackItem; + const threadId = active?.session.id === session.id ? active.threadId : undefined; + return pickContexts({ + title: "Symbol File Contexts", + contexts, + scope, + selectedId: contexts.find((context) => threadId !== undefined && context.threadId === threadId)?.id, + placeholder: "Check the contexts the symbols apply to, or check none for all contexts", + allowQuery: true, + allowTyped: true, + }); +} - function update(value: string): void { - const typed = value.trim(); - picker.items = [ - typed - ? { label: typed, description: "Use ID or name as entered", id: typed } - : { label: "All contexts", description: "No context filter", id: "" }, - ...contexts.map((context) => ({ label: context.name, description: context.id, id: context.id })), - ]; - } +/** The "contexts" or "contextQuery" attribute of a symbol file for the scope. */ +function scopeConfig(scope: ContextScope): Pick { + if ("contextQuery" in scope) { + return { contextQuery: scope.contextQuery }; + } + return scope.contexts.length > 0 ? { contexts: scope.contexts } : {}; +} - picker.onDidChangeValue(update); - picker.onDidAccept(() => finish(picker.activeItems[0]?.id ?? picker.value.trim())); - picker.onDidHide(() => finish()); - picker.value = initialContext; - picker.show(); - update(initialContext); - }); +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); } async function saveSymbolFiles(): Promise { @@ -931,12 +885,8 @@ class SymbolFileViewItem extends vscode.TreeItem { readonly session: vscode.DebugSession, ) { super(path.basename(file.path)); - this.contextValue = file.context ? "symbolFile scoped" : "symbolFile"; - const scope = - [file.context && `context ${file.context}`, file.contextQuery && `query ${file.contextQuery}`] - .filter(Boolean) - .join(", ") || "all contexts"; - this.description = `${scope}${loadAddressSuffix(file)}`; + this.contextValue = file.contexts?.length ? "symbolFile scoped" : "symbolFile"; + this.description = `${describeContextScope(file)}${loadAddressSuffix(file)}`; this.tooltip = `${file.path}\n${this.description}`; this.iconPath = new vscode.ThemeIcon("file-code"); } diff --git a/src/functionBreakpoint.ts b/src/functionBreakpoint.ts index 0c74757..83e4a06 100644 --- a/src/functionBreakpoint.ts +++ b/src/functionBreakpoint.ts @@ -33,52 +33,3 @@ export function parseFunctionBreakpointName(name: string): ParsedFunctionBreakpo hasEmptyContext: entries.some((id) => !id), }; } - -export interface FunctionBreakpointContext { - id: string; - name: string; -} - -export interface FunctionBreakpointContextChoice { - label: string; - description?: string; - detail?: string; - id: string; - picked: boolean; -} - -/** - * The items of the context checklist: the selected call-stack context first, - * then the session's contexts, then checked IDs the session does not have, so - * that editing a breakpoint never drops part of its scope silently. - */ -export function functionBreakpointContextChoices( - contexts: readonly FunctionBreakpointContext[], - checkedIds: readonly string[], - selectedId?: string, -): FunctionBreakpointContextChoice[] { - const selected = contexts.find((context) => context.id === selectedId); - const ordered = selected ? [selected, ...contexts.filter((context) => context !== selected)] : contexts; - const known = new Set(contexts.map((context) => context.id)); - return [ - ...ordered.map((context) => - context === selected - ? { - label: context.name, - description: "Selected call-stack context", - detail: context.id, - id: context.id, - picked: checkedIds.includes(context.id), - } - : { - label: context.name, - description: context.id, - id: context.id, - picked: checkedIds.includes(context.id), - }, - ), - ...checkedIds - .filter((id) => !known.has(id)) - .map((id) => ({ label: id, description: "Not available in this session", id, picked: true })), - ]; -} diff --git a/src/launchSettings/editorProvider.ts b/src/launchSettings/editorProvider.ts index c4a95e9..586be05 100644 --- a/src/launchSettings/editorProvider.ts +++ b/src/launchSettings/editorProvider.ts @@ -14,8 +14,19 @@ import { setValue, } from "./launchJson"; import { isContextSession } from "@/contextSessionManager"; +import { TargetContext } from "@/contextChoices"; +import { listContexts, pickContexts } from "@/contextPicker"; import { StateMessage, WebviewMessage } from "./protocol"; -import { Field, agentAddress, fieldPath, launchFields, launchTemplate, valueAtPath } from "./schema"; +import { + Field, + agentAddress, + fieldPath, + launchFields, + launchTemplate, + readContextScope, + valueAtPath, + withContextScope, +} from "./schema"; /** Must match "customEditors" in package.json. */ export const LAUNCH_SETTINGS_VIEW_TYPE = "simics-target-debug.launchSettings"; @@ -219,6 +230,9 @@ class LaunchSettingsEditorProvider implements vscode.CustomTextEditorProvider { } return; } + case "pickContexts": + await pickItemContexts(document, message.index, message.name, message.path); + return; case "start": { const text = checkedText(document, message.index, message.name); const config = readConfigurations(text).configurations?.find((c) => c.index === message.index); @@ -294,6 +308,68 @@ class LaunchSettingsEditorProvider implements vscode.CustomTextEditorProvider { } } +/** + * Lets the user pick the contexts of the list item at `path`, such as a + * symbol file, from those of a running session to the configuration's agent. + */ +async function pickItemContexts( + document: vscode.TextDocument, + index: number, + name: string, + itemPath: (string | number)[], +): Promise { + const read = (text: string) => { + const config = readConfigurations(text).configurations?.find((c) => c.index === index); + const value = valueAtPath(config?.values, itemPath); + const item = + typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : undefined; + return { config, item }; + }; + const { config, item } = read(checkedText(document, index, name)); + if (!config || !item) { + return; + } + const agent = agentAddress(config.values); + const session = [...tcfSessions].find((s) => agentAddress(s.configuration) === agent); + if (!session) { + void vscode.window.showInformationMessage( + `Start a Simics Target Debug session to ${agent} to pick from its contexts.`, + ); + return; + } + let contexts: TargetContext[] = []; + try { + contexts = await listContexts(session); + } catch (err) { + void vscode.window.showWarningMessage( + `Could not list TCF contexts, type their IDs or names: ${err instanceof Error ? err.message : String(err)}`, + ); + } + const file = item.path; + const scope = await pickContexts({ + title: typeof file === "string" && file ? `Contexts for ${file}` : "Contexts", + contexts, + scope: readContextScope(item), + placeholder: "Check the contexts, or check none for all contexts", + allowQuery: true, + allowTyped: true, + }); + if (scope === undefined) { + return; + } + const text = checkedText(document, index, name); + const current = read(text).item; + if (!current) { + throw new Error("launch.json changed while you edited it, please try again."); + } + await applyAndSave( + document, + setValue(text, index, itemPath, withContextScope(current, scope), detectFormatting(text)), + ); +} + /** Loads `script`, a bundle in out/webview, with the form's stylesheet. */ function setWebviewHtml(webview: vscode.Webview, extensionUri: vscode.Uri, script: string, title: string): void { const webviewDir = vscode.Uri.joinPath(extensionUri, "out", "webview"); diff --git a/src/launchSettings/protocol.ts b/src/launchSettings/protocol.ts index 1ba94e4..47613e0 100644 --- a/src/launchSettings/protocol.ts +++ b/src/launchSettings/protocol.ts @@ -28,6 +28,8 @@ export type WebviewMessage = | { type: "remove"; index: number; name: string; path: JsonPath } /** Pick a file or folder for the path attribute at `path`. */ | { type: "browse"; index: number; name: string; path: JsonPath; pick: "file" | "folder" } + /** Pick the contexts of the list item at `path` from a session to the configuration's agent. */ + | { type: "pickContexts"; index: number; name: string; path: JsonPath } | { type: "add" } | { type: "duplicate"; index: number; name: string } | { type: "delete"; index: number; name: string } diff --git a/src/launchSettings/schema.ts b/src/launchSettings/schema.ts index 16a43ce..9ab66ea 100644 --- a/src/launchSettings/schema.ts +++ b/src/launchSettings/schema.ts @@ -5,8 +5,18 @@ * this file too. */ +import type { ContextScope } from "@/contextChoices"; + export type FieldKind = - "string" | "enum" | "number" | "integer" | "boolean" | "stringOrInteger" | "objectList" | "unsupported"; + | "string" + | "enum" + | "number" + | "integer" + | "boolean" + | "stringOrInteger" + | "objectList" + | "contextScope" + | "unsupported"; export interface Field { key: string; @@ -21,7 +31,11 @@ export interface Field { values?: string[]; /** Text to show for each of `values`, if not the values themselves. */ valueLabels?: string[]; - /** The properties of the objects in an 'objectList' field. */ + /** + * The properties of the objects in an 'objectList' field. Objects with + * "contexts" (a list of strings) and "contextQuery" have one + * 'contextScope' column for both, see readContextScope. + */ columns?: Field[]; /** * What a path field may be set to with Browse buttons, from "format" in @@ -195,6 +209,7 @@ interface Schema { items?: unknown; properties?: unknown; required?: unknown; + deprecationMessage?: unknown; } function field(key: string, schema: Schema, required: boolean): Field { @@ -219,7 +234,7 @@ function field(key: string, schema: Schema, required: boolean): Field { } if (f.kind === "objectList") { const items = schema.items as Schema; - f.columns = fieldsFromSchema(items.properties as Record, items.required); + f.columns = objectColumns(items.properties as Record, items.required); // A list default in package.json is only a completion template. delete f.default; } @@ -241,7 +256,7 @@ function kindOf(schema: Schema): FieldKind { if ( items?.type === "object" && isObject(items.properties) && - fieldsFromSchema(items.properties).every((c) => SIMPLE_KINDS.has(c.kind)) + objectColumns(items.properties).every((c) => COLUMN_KINDS.has(c.kind)) ) { return "objectList"; } @@ -255,7 +270,79 @@ function kindOf(schema: Schema): FieldKind { return "unsupported"; } -const SIMPLE_KINDS = new Set(["string", "enum", "number", "integer", "boolean", "stringOrInteger"]); +const COLUMN_KINDS = new Set([ + "string", + "enum", + "number", + "integer", + "boolean", + "stringOrInteger", + "contextScope", +]); + +/** The keys of the attributes a 'contextScope' column edits. "context" is the deprecated single context. */ +const CONTEXT_SCOPE_KEYS = ["contexts", "contextQuery", "context"]; + +/** + * The columns of an object list: one per property, except deprecated ones, + * and with one 'contextScope' column for "contexts" and "contextQuery". + */ +function objectColumns(properties: Record, required: unknown = []): Field[] { + const contexts = properties.contexts as Schema | undefined; + const hasScope = + contexts?.type === "array" && + (contexts.items as Schema | undefined)?.type === "string" && + (properties.contextQuery as Schema | undefined)?.type === "string"; + return fieldsFromSchema(properties, required).flatMap((f) => { + if ((properties[f.key] as Schema | undefined)?.deprecationMessage !== undefined) { + return []; + } + if (hasScope && f.key === "contextQuery") { + return []; + } + if (hasScope && f.key === "contexts") { + return [{ ...f, kind: "contextScope" as const }]; + } + return [f]; + }); +} + +/** The contexts or context query of a list item with a 'contextScope' column. */ +export function readContextScope(item: unknown): ContextScope { + const v = isObject(item) ? item : {}; + if (typeof v.contextQuery === "string" && v.contextQuery.length > 0) { + return { contextQuery: v.contextQuery }; + } + if (Array.isArray(v.contexts)) { + return { contexts: v.contexts.filter((c): c is string => typeof c === "string" && c.length > 0) }; + } + return { contexts: typeof v.context === "string" && v.context.length > 0 ? [v.context] : [] }; +} + +/** + * The list item with its scope attributes replaced by `scope`, where the + * first of them was, else after "path". All contexts leaves them out. + */ +export function withContextScope(item: Record, scope: ContextScope): Record { + const attributes: Record = + "contextQuery" in scope + ? { contextQuery: scope.contextQuery } + : scope.contexts.length > 0 + ? { contexts: scope.contexts } + : {}; + const keys = Object.keys(item); + const after = keys.find((k) => CONTEXT_SCOPE_KEYS.includes(k)) ?? (keys.includes("path") ? "path" : undefined); + const result: Record = after === undefined ? { ...attributes } : {}; + for (const [key, value] of Object.entries(item)) { + if (!CONTEXT_SCOPE_KEYS.includes(key)) { + result[key] = value; + } + if (key === after) { + Object.assign(result, attributes); + } + } + return result; +} interface DebuggerContribution { type?: unknown; diff --git a/src/symbolFiles.ts b/src/symbolFiles.ts index efa93d6..918f622 100644 --- a/src/symbolFiles.ts +++ b/src/symbolFiles.ts @@ -9,9 +9,11 @@ export const SYMBOL_FILE_ID_PREFIX = "vscode-symbol-file-"; export interface SymbolFileConfig { /** Path of the symbol file (ELF with debug information) as seen by the agent. */ path: string; - /** Context ID or name the symbol file applies to. All contexts if not set. */ + /** IDs or names of the contexts the symbol file applies to. All contexts if not set. */ + contexts?: string[]; + /** One context ID or name, read as `contexts` with one entry. */ context?: string; - /** TCF context query selecting the contexts the symbol file applies to. */ + /** TCF context query selecting the contexts the symbol file applies to. Not with `contexts`. */ contextQuery?: string; /** * Relocation offset added to all addresses in the file, like the Simics @@ -27,7 +29,8 @@ export interface SymbolFileConfig { export interface SymbolFile { path: string; - context: string; + /** Context IDs or names, empty for all contexts or those matching `contextQuery`. */ + contexts: string[]; contextQuery?: string; /** Relocation offset (may be negative), or the load address when `absolute` is set. */ address?: bigint; @@ -35,27 +38,45 @@ export interface SymbolFile { absolute?: true; } -export function symbolFileBreakpointContext( - file: Pick, +/** The context IDs to set a function breakpoint in for the symbol file's contexts. */ +export function symbolFileBreakpointContexts( + file: Pick, contexts: readonly { id: string; name: string }[], -): string { - const scope = file.context; - if (!scope) { - throw new Error("The symbol file has no context"); - } - const exact = contexts.find((context) => context.id === scope); - if (exact) { - return exact.id; +): string[] { + const scope = file.contexts ?? []; + if (scope.length === 0) { + throw new Error("The symbol file has no contexts"); } - const matches = contexts.filter((context) => context.name === scope); - if (matches.length !== 1) { - throw new Error( - matches.length === 0 - ? `Symbol file context '${scope}' is not available in this session` - : `Symbol file context '${scope}' is ambiguous; use its exact TCF context ID`, - ); - } - return matches[0].id; + return [ + ...new Set( + scope.map((entry) => { + const exact = contexts.find((context) => context.id === entry); + if (exact) { + return exact.id; + } + const matches = contexts.filter((context) => context.name === entry); + if (matches.length !== 1) { + throw new Error( + matches.length === 0 + ? `Symbol file context '${entry}' is not available in this session` + : `Symbol file context '${entry}' is ambiguous; use its exact TCF context ID`, + ); + } + return matches[0].id; + }), + ), + ]; +} + +/** The symbol file as a "symbolFiles" entry of a debug configuration, with the address as a string. */ +export function symbolFileConfig(file: SymbolFile): SymbolFileConfig { + return { + path: file.path, + ...(file.contexts.length > 0 && { contexts: [...file.contexts] }), + ...(file.contextQuery !== undefined && { contextQuery: file.contextQuery }), + ...(file.address !== undefined && { address: file.address.toString() }), + ...(file.absolute && { absolute: true }), + }; } /** @@ -81,10 +102,26 @@ export function parseSymbolFilesConfig(value: unknown): { files: SymbolFile[]; e errors.push(`symbolFiles[${i}] is ignored, "context" must be a string`); return; } + if ( + e.contexts !== undefined && + (!Array.isArray(e.contexts) || !e.contexts.every((c) => typeof c === "string" && c.length > 0)) + ) { + errors.push(`symbolFiles[${i}] is ignored, "contexts" must be a list of non-empty strings`); + return; + } + if (e.context !== undefined && e.contexts !== undefined) { + errors.push(`symbolFiles[${i}] is ignored, it has both "context" and "contexts"; use "contexts"`); + return; + } if (e.contextQuery !== undefined && (typeof e.contextQuery !== "string" || e.contextQuery.length === 0)) { errors.push(`symbolFiles[${i}] is ignored, "contextQuery" must be a non-empty string`); return; } + const contexts = [...new Set(e.contexts ?? (e.context ? [e.context] : []))]; + if (contexts.length > 0 && e.contextQuery !== undefined) { + errors.push(`symbolFiles[${i}] is ignored, use either "contexts" or "contextQuery", not both`); + return; + } if (e.absolute !== undefined && typeof e.absolute !== "boolean") { errors.push(`symbolFiles[${i}] is ignored, "absolute" must be true or false`); return; @@ -108,7 +145,7 @@ export function parseSymbolFilesConfig(value: unknown): { files: SymbolFile[]; e } files.push({ path: e.path, - context: e.context ?? "", + contexts, contextQuery: e.contextQuery, address, ...(absolute && { absolute: true as const }), @@ -120,13 +157,16 @@ export function parseSymbolFilesConfig(value: unknown): { files: SymbolFile[]; e /** * Adds symbol files to the agent's memory map, like "Load symbols" in the * Eclipse TCF client: each file becomes a memory region with FileName, set - * with MemoryMap.set for its context, or for all contexts ("") with a - * ContextQuery filter. A relocation offset is sent as BaseAddress (added to + * with MemoryMap.set for each of its contexts, or for all contexts ("") + * with an optional ContextQuery filter. A MemoryMap.set call takes a single + * context, so a file with several contexts is in the map of each one, with + * the same region ID. A relocation offset is sent as BaseAddress (added to * all file addresses, which is what Simics add-symbol-file -relative uses); * an absolute load address as Addr (the address of the file's first * loadable segment). The agent removes the regions when the debug session * ends. The region IDs start with `idPrefix`, so that the regions can be - * recognized in MemoryMap.get results. + * recognized in MemoryMap.get results. The maps of contexts that only + * `previousFiles` used are cleared. */ export async function applySymbolFiles( service: MemoryMapService, @@ -152,18 +192,25 @@ export async function applySymbolFiles( if (f.contextQuery !== undefined) { region.ContextQuery = f.contextQuery; } - const regions = maps.get(f.context) ?? []; - regions.push(region); - maps.set(f.context, regions); + for (const context of symbolFileMapContexts(f)) { + const regions = maps.get(context) ?? []; + regions.push(region); + maps.set(context, regions); + } }); - for (const file of previousFiles) { - if (!maps.has(file.context)) { - maps.set(file.context, []); + for (const context of previousFiles.flatMap(symbolFileMapContexts)) { + if (!maps.has(context)) { + maps.set(context, []); } } await Promise.all([...maps].map(([ctx, regions]) => service.set(ctx, regions))); } +/** The contexts whose memory maps have the file's region: its contexts, or "" for all. */ +export function symbolFileMapContexts(file: Pick): string[] { + return file.contexts.length > 0 ? file.contexts : [""]; +} + /** * A memory map region of a file that is mapped by someone else. Numbers are * hex strings. diff --git a/src/tcfDebugSession.ts b/src/tcfDebugSession.ts index e79f05a..2a8f222 100644 --- a/src/tcfDebugSession.ts +++ b/src/tcfDebugSession.ts @@ -50,7 +50,10 @@ import { collectForeignSymbolFiles, formatSymbolFileAddress, parseSymbolFilesConfig, + symbolFileConfig, + symbolFileMapContexts, } from "./symbolFiles"; +import { describeContextScope } from "./contextChoices"; import { toBigInt } from "./tcf/json"; import { scanMemory } from "./shared/targetMemory/search"; import * as req from "./tcfRequests"; @@ -586,10 +589,7 @@ export class TcfDebugSession extends DebugSession { try { await this.applySymbolFiles(service, files); for (const f of files) { - const scope = - [f.context && `context ${f.context}`, f.contextQuery && `contexts matching ${f.contextQuery}`] - .filter(Boolean) - .join(", ") || "all contexts"; + const scope = describeContextScope(f); const at = f.address === undefined ? "" @@ -644,8 +644,7 @@ export class TcfDebugSession extends DebugSession { ids = this.contextOrder.filter((id) => this.contexts.get(id)?.HasState === true); } response.body = ids.map((id) => { - const threadId = - command === "getFunctionBreakpointContexts" ? this.threadIdByCtx.get(id) : undefined; + const threadId = this.threadIdByCtx.get(id); return { id, name: this.contextDisplayName(id), @@ -716,13 +715,7 @@ export class TcfDebugSession extends DebugSession { if (command === "getSymbolFiles") { response.body = { supported: this.memoryMap !== undefined, - files: this.symbolFiles.map((file) => ({ - path: file.path, - context: file.context, - ...(file.contextQuery !== undefined && { contextQuery: file.contextQuery }), - ...(file.address !== undefined && { address: file.address.toString() }), - ...(file.absolute && { absolute: true }), - })), + files: this.symbolFiles.map(symbolFileConfig), }; this.sendResponse(response); return; @@ -790,10 +783,11 @@ export class TcfDebugSession extends DebugSession { this.log(`Symbol file ${this.symbolFiles[index].path} removed\n`); this.symbolFiles = nextFiles; } else { - const contexts = + const files = command === "reloadSymbolFile" - ? [this.symbolFiles[this.symbolFileIndex(args)].context] - : [...new Set(this.symbolFiles.map((file) => file.context))]; + ? [this.symbolFiles[this.symbolFileIndex(args)]] + : this.symbolFiles; + const contexts = [...new Set(files.flatMap(symbolFileMapContexts))]; for (const context of contexts) { await service.set(context, []); } @@ -811,19 +805,21 @@ export class TcfDebugSession extends DebugSession { | { index?: unknown; path?: unknown; - context?: unknown; + contexts?: unknown; contextQuery?: unknown; address?: unknown; absolute?: unknown; } | undefined; const index = selection?.index; + const contexts = Array.isArray(selection?.contexts) ? selection.contexts : []; if ( typeof index !== "number" || !Number.isInteger(index) || index < 0 || this.symbolFiles[index]?.path !== selection?.path || - this.symbolFiles[index].context !== selection?.context || + this.symbolFiles[index].contexts.length !== contexts.length || + this.symbolFiles[index].contexts.some((context, i) => context !== contexts[i]) || this.symbolFiles[index].contextQuery !== selection?.contextQuery || this.symbolFiles[index].address?.toString() !== selection?.address || (this.symbolFiles[index].absolute === true) !== (selection?.absolute === true) diff --git a/src/test/contextChoices.test.ts b/src/test/contextChoices.test.ts new file mode 100644 index 0000000..40fd911 --- /dev/null +++ b/src/test/contextChoices.test.ts @@ -0,0 +1,46 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { contextChoices, describeContextScope, parseContextList, pickedValues } from "@/contextChoices"; + +const CONTEXTS = [ + { id: "core-0", name: "board.cpu0" }, + { id: "core-1", name: "board.cpu1" }, +]; + +// The selected call-stack context comes first. Checked entries keep how they +// were written (ID or name), and those the session does not have stay listed. +test("contextChoices checks entries by ID or name and keeps unknown ones", () => { + const choices = contextChoices(CONTEXTS, ["board.cpu1", "gone"], "core-1"); + assert.deepEqual(choices, [ + { + label: "board.cpu1", + description: "Selected call-stack context", + detail: "core-1", + value: "board.cpu1", + picked: true, + }, + { label: "board.cpu0", description: "core-0", value: "core-0", picked: false }, + { label: "gone", description: "Not available in this session", value: "gone", picked: true }, + ]); + assert.deepEqual(pickedValues(choices.filter((c) => c.picked)), ["board.cpu1", "gone"]); +}); + +// An ID wins over a context whose name is the same text. +test("contextChoices matches IDs before names", () => { + const contexts = [...CONTEXTS, { id: "other", name: "core-0" }]; + assert.deepEqual( + contextChoices(contexts, ["core-0"]).map((c) => [c.label, c.picked]), + [ + ["board.cpu0", true], + ["board.cpu1", false], + ["core-0", false], + ], + ); +}); + +test("parseContextList and describeContextScope", () => { + assert.deepEqual(parseContextList(" cpu0, ,cpu1,cpu0 "), ["cpu0", "cpu1"]); + assert.equal(describeContextScope({}), "all contexts"); + assert.equal(describeContextScope({ contexts: ["cpu0", "cpu1"] }), "cpu0, cpu1"); + assert.equal(describeContextScope({ contextQuery: "**/HasState=true" }), "contexts matching **/HasState=true"); +}); diff --git a/src/test/schema.test.ts b/src/test/schema.test.ts index 9c1adec..9403ac3 100644 --- a/src/test/schema.test.ts +++ b/src/test/schema.test.ts @@ -10,7 +10,9 @@ import { launchFields, launchTemplate, parseInput, + readContextScope, valueAtPath, + withContextScope, } from "@/launchSettings/schema"; import { DEFAULT_TRACE_SILENCE } from "@/tcf/traceSilence"; @@ -52,8 +54,7 @@ test("launchFields reads the simics-target-debug attributes from package.json", symbolFiles?.columns?.map((c) => [c.key, c.kind, c.browse]), [ ["path", "string", "file"], - ["context", "string", undefined], - ["contextQuery", "string", undefined], + ["contexts", "contextScope", undefined], ["address", "stringOrInteger", undefined], ["absolute", "boolean", undefined], ], @@ -254,3 +255,33 @@ test("agentAddress defaults to the debug session's host and port", () => { assert.equal(agentAddress({ host: "simhost", port: 1600 }), "simhost:1600"); assert.notEqual(agentAddress({ port: 1534 }), agentAddress({ port: 1535 })); }); + +// The Contexts cell of a symbol file reads the old single "context" too, and +// writes one scope attribute in place of the old ones. +test("readContextScope and withContextScope edit the scope of a list item", () => { + assert.deepEqual(readContextScope({ path: "a" }), { contexts: [] }); + assert.deepEqual(readContextScope({ context: "cpu0" }), { contexts: ["cpu0"] }); + assert.deepEqual(readContextScope({ contexts: ["cpu0", 1, ""] }), { contexts: ["cpu0"] }); + assert.deepEqual(readContextScope({ contexts: ["cpu0"], contextQuery: "HasState=true" }), { + contextQuery: "HasState=true", + }); + + const item = { path: "a.elf", context: "cpu0", address: "0x1000" }; + const contexts = withContextScope(item, { contexts: ["cpu0", "cpu1"] }); + assert.deepEqual(Object.entries(contexts), [ + ["path", "a.elf"], + ["contexts", ["cpu0", "cpu1"]], + ["address", "0x1000"], + ]); + assert.deepEqual(Object.entries(withContextScope(contexts, { contextQuery: "HasState=true" })), [ + ["path", "a.elf"], + ["contextQuery", "HasState=true"], + ["address", "0x1000"], + ]); + assert.deepEqual(withContextScope(contexts, { contexts: [] }), { path: "a.elf", address: "0x1000" }); + assert.deepEqual(Object.keys(withContextScope({ address: 1, path: "a" }, { contexts: ["c"] })), [ + "address", + "path", + "contexts", + ]); +}); diff --git a/src/test/symbolFiles.test.ts b/src/test/symbolFiles.test.ts index 3ed69dd..8a7a1b1 100644 --- a/src/test/symbolFiles.test.ts +++ b/src/test/symbolFiles.test.ts @@ -9,6 +9,8 @@ import { describeForeignSymbolFile, formatSymbolFileAddress, parseSymbolFilesConfig, + symbolFileBreakpointContexts, + symbolFileConfig, } from "@/symbolFiles"; import { MemoryMapService, MemoryRegionProperties } from "@/tcf/services/memoryMap"; @@ -38,25 +40,25 @@ test("parseSymbolFilesConfig reads valid entries", () => { assert.deepEqual(files, [ { path: "/a.elf", - context: "", + contexts: [], contextQuery: undefined, address: undefined, }, { path: "/b.elf", - context: "cpu0", + contexts: ["cpu0"], contextQuery: undefined, address: 4096n, }, { path: "/c.elf", - context: "", + contexts: [], contextQuery: "Name=cpu*", address: 0xffff0000n, }, { path: "/d.elf", - context: "", + contexts: [], contextQuery: undefined, address: 0x123456789abcdef0n, }, @@ -95,6 +97,79 @@ test("parseSymbolFilesConfig reports invalid entries", () => { ]); }); +// "contexts" lists IDs or names, the old "context" is read as a list of one. +// A file has either contexts or a context query. +test("parseSymbolFilesConfig reads context lists and rejects mixed scopes", () => { + const { files, errors } = parseSymbolFilesConfig([ + { path: "/a.elf", contexts: ["cpu0", "board.cpu1", "cpu0"] }, + { path: "/b.elf", context: "cpu0" }, + { path: "/c.elf", contexts: [] }, + { path: "/d.elf", contexts: ["cpu0"], contextQuery: "HasState=true" }, + { path: "/e.elf", context: "cpu0", contextQuery: "HasState=true" }, + { path: "/f.elf", context: "cpu0", contexts: ["cpu1"] }, + { path: "/g.elf", contexts: "cpu0" }, + { path: "/h.elf", contexts: ["cpu0", ""] }, + ]); + assert.deepEqual( + files.map((f) => [f.path, f.contexts]), + [ + ["/a.elf", ["cpu0", "board.cpu1"]], + ["/b.elf", ["cpu0"]], + ["/c.elf", []], + ], + ); + assert.deepEqual(errors, [ + 'symbolFiles[3] is ignored, use either "contexts" or "contextQuery", not both', + 'symbolFiles[4] is ignored, use either "contexts" or "contextQuery", not both', + 'symbolFiles[5] is ignored, it has both "context" and "contexts"; use "contexts"', + 'symbolFiles[6] is ignored, "contexts" must be a list of non-empty strings', + 'symbolFiles[7] is ignored, "contexts" must be a list of non-empty strings', + ]); + assert.deepEqual(symbolFileConfig(files[0]), { path: "/a.elf", contexts: ["cpu0", "board.cpu1"] }); + assert.deepEqual(symbolFileConfig(files[2]), { path: "/c.elf" }); +}); + +// MemoryMap.set takes one context, so a file with several contexts is in +// each of their maps. Maps that only the previous files used are cleared. +test("applySymbolFiles sets the region in the map of each context", async () => { + const calls: [string, MemoryRegionProperties[]][] = []; + const service = { + set: async (contextId: string, regions: MemoryRegionProperties[]) => { + calls.push([contextId, regions]); + }, + } as unknown as MemoryMapService; + + await applySymbolFiles( + service, + [ + { path: "/a.elf", contexts: ["cpu0", "cpu1"], address: 0x1000n }, + { path: "/b.elf", contexts: ["cpu1"] }, + ], + () => {}, + [{ path: "/old.elf", contexts: ["cpu1", "cpu2"] }], + ); + + const a = { ID: "vscode-symbol-file-1", FileName: "/a.elf", BaseAddress: 0x1000n }; + assert.deepEqual(calls, [ + ["cpu0", [a]], + ["cpu1", [a, { ID: "vscode-symbol-file-2", FileName: "/b.elf" }]], + ["cpu2", []], + ]); +}); + +test("symbolFileBreakpointContexts resolves each context of the file", () => { + const contexts = [ + { id: "core-0", name: "board.cpu0" }, + { id: "core-1", name: "board.cpu1" }, + ]; + assert.deepEqual(symbolFileBreakpointContexts({ contexts: ["board.cpu1", "core-0", "core-1"] }, contexts), [ + "core-1", + "core-0", + ]); + assert.throws(() => symbolFileBreakpointContexts({ contexts: [] }, contexts), /no contexts/); + assert.throws(() => symbolFileBreakpointContexts({ contexts: ["core-0", "gone"] }, contexts), /'gone' is not/); +}); + // Files for the same context share one MemoryMap.set. A missing file only // gives a warning, since the agent may run on another host. test("applySymbolFiles sets one memory map per context", async () => { @@ -112,9 +187,9 @@ test("applySymbolFiles sets one memory map per context", async () => { await applySymbolFiles( service, [ - { path: present, context: "" }, - { path: "/missing/kernel.elf", context: "cpu0", address: 0x1000n }, - { path: present, context: "", contextQuery: "Name=cpu1" }, + { path: present, contexts: [] }, + { path: "/missing/kernel.elf", contexts: ["cpu0"], address: 0x1000n }, + { path: present, contexts: [], contextQuery: "Name=cpu1" }, ], (message) => warnings.push(message), ); @@ -159,11 +234,11 @@ test("parseSymbolFilesConfig reads offsets and absolute addresses", () => { { path: "/h.elf", address: "-" }, ]); assert.deepEqual(files, [ - { path: "/a.elf", context: "", contextQuery: undefined, address: 0x1000n }, - { path: "/b.elf", context: "", contextQuery: undefined, address: -0x300000n }, - { path: "/c.elf", context: "", contextQuery: undefined, address: -16n }, - { path: "/d.elf", context: "", contextQuery: undefined, address: 0xff000n, absolute: true }, - { path: "/e.elf", context: "", contextQuery: undefined, address: 0x1000n }, + { path: "/a.elf", contexts: [], contextQuery: undefined, address: 0x1000n }, + { path: "/b.elf", contexts: [], contextQuery: undefined, address: -0x300000n }, + { path: "/c.elf", contexts: [], contextQuery: undefined, address: -16n }, + { path: "/d.elf", contexts: [], contextQuery: undefined, address: 0xff000n, absolute: true }, + { path: "/e.elf", contexts: [], contextQuery: undefined, address: 0x1000n }, ]); assert.deepEqual(errors, [ 'symbolFiles[5] is ignored, "absolute" requires an "address" to load the file at', @@ -185,8 +260,8 @@ test("applySymbolFiles sends offsets as BaseAddress and absolute addresses as Ad await applySymbolFiles( service, [ - { path: "/a.elf", context: "", address: -0x300000n }, - { path: "/b.elf", context: "", address: 0xff000n, absolute: true }, + { path: "/a.elf", contexts: [], address: -0x300000n }, + { path: "/b.elf", contexts: [], address: 0xff000n, absolute: true }, ], () => {}, ); @@ -219,7 +294,7 @@ test("applySymbolFiles uses the ID prefix", async () => { }, } as unknown as MemoryMapService; - await applySymbolFiles(service, [{ path: "/a.elf", context: "" }], () => {}, [], "vscode-symbol-file-abc-"); + await applySymbolFiles(service, [{ path: "/a.elf", contexts: [] }], () => {}, [], "vscode-symbol-file-abc-"); assert.deepEqual(calls, [["", [{ ID: "vscode-symbol-file-abc-1", FileName: "/a.elf" }]]]); }); diff --git a/src/test/tcfDebugSession.test.ts b/src/test/tcfDebugSession.test.ts index b96cd54..85ac5a9 100644 --- a/src/test/tcfDebugSession.test.ts +++ b/src/test/tcfDebugSession.test.ts @@ -378,3 +378,56 @@ test("getForeignSymbolFiles lists files that the session did not add", async () ], }); }); + +// A symbol file moved from one context to two is set in both maps, and the +// map of the old context is cleared. getSymbolFiles reports "contexts", as +// saved to launch.json. +test("replaceSymbolFile moves a symbol file to several contexts", async () => { + const session = new TcfDebugSession(); + const prefix = (session as unknown as { symbolFileIdPrefix: string }).symbolFileIdPrefix; + const calls: [string, unknown[]][] = []; + Object.assign(session, { + channel: {}, + memoryMap: { + set: async (id: string, regions: unknown[]) => { + calls.push([id, regions]); + }, + }, + symbolFiles: [{ path: "/a.elf", contexts: ["cpu0"] }], + }); + let seq = 0; + const request = (command: string, args: unknown) => + new Promise((resolve) => { + const requestSeq = ++seq; + session.onDidSendMessage((value) => { + const message = value as DebugProtocol.Response; + if (message.type === "response" && message.request_seq === requestSeq) { + resolve(message); + } + }); + session.handleMessage({ + seq: requestSeq, + type: "request", + command, + arguments: args, + } as DebugProtocol.Request); + }); + + const replaced = await request("replaceSymbolFile", { + index: 0, + path: "/a.elf", + contexts: ["cpu0"], + file: { path: "/a.elf", contexts: ["cpu1", "cpu2"] }, + }); + assert.equal(replaced.success, true); + const region = { ID: `${prefix}1`, FileName: "/a.elf" }; + assert.deepEqual(calls, [ + ["cpu1", [region]], + ["cpu2", [region]], + ["cpu0", []], + ]); + const stale = await request("removeSymbolFile", { index: 0, path: "/a.elf", contexts: ["cpu0"] }); + assert.equal(stale.success, false); + const listed = await request("getSymbolFiles", undefined); + assert.deepEqual(listed.body, { supported: true, files: [{ path: "/a.elf", contexts: ["cpu1", "cpu2"] }] }); +}); diff --git a/src/webview/launchSettings/App.tsx b/src/webview/launchSettings/App.tsx index fceea71..9ef8a03 100644 --- a/src/webview/launchSettings/App.tsx +++ b/src/webview/launchSettings/App.tsx @@ -292,6 +292,8 @@ function Details(props: { browse: (path, pick) => post({ type: "browse", ...target, path, pick }), isMissing: (path) => missing.has(`${config.index}:${path.join("/")}`), openText: () => post({ type: "openText" }), + pickContexts: (path) => post({ type: "pickContexts", ...target, path }), + canPickContexts: state.busyAgents.includes(agentAddress(config.values)), }; const sameName = (nameCounts(props.configs).get(config.name) ?? 0) > 1; const known = new Set(state.fields.map((f) => fieldPath(f)[0])); diff --git a/src/webview/launchSettings/components/controls.tsx b/src/webview/launchSettings/components/controls.tsx index daaaa50..a2182c4 100644 --- a/src/webview/launchSettings/components/controls.tsx +++ b/src/webview/launchSettings/components/controls.tsx @@ -1,6 +1,14 @@ import * as React from "react"; import type { JsonPath } from "@/launchSettings/protocol"; -import { type Field, type FieldKind, fieldPath, parseInput } from "@/launchSettings/schema"; +import { type ContextScope, parseContextList } from "@/contextChoices"; +import { + type Field, + type FieldKind, + fieldPath, + parseInput, + readContextScope, + withContextScope, +} from "@/launchSettings/schema"; /* * The inputs of the launch configurations form, laid out like the Settings @@ -16,6 +24,10 @@ export interface Editor { isMissing(path: JsonPath): boolean; /** Opens launch.json as text, for values the form cannot edit. */ openText(): void; + /** Picks the contexts of the list item at `path` from the running session. */ + pickContexts(path: JsonPath): void; + /** True if a session runs to the configuration's agent, so that pickContexts can list its contexts. */ + canPickContexts: boolean; } /** The data-focus key of a control to focus when the next state is shown. */ @@ -315,12 +327,20 @@ function ObjectList({ field, value, edit }: { field: Field; value: unknown[] | u ) : ( columns.map((c) => ( - )[c.key]} - path={[field.key, r, c.key]} - edit={edit} - /> + {c.kind === "contextScope" ? ( + } + path={[field.key, r]} + edit={edit} + /> + ) : ( + )[c.key]} + path={[field.key, r, c.key]} + edit={edit} + /> + )} )) )} @@ -348,6 +368,83 @@ function Cell(props: InputProps) { } } +type ScopeMode = "all" | "contexts" | "query"; + +const CONTEXTS_INPUT: Field = { + key: "contexts", + label: "Contexts", + kind: "string", + default: "IDs or names, separated by commas", +}; +const QUERY_INPUT: Field = { key: "contextQuery", label: "Context Query", kind: "string" }; + +/** + * The contexts of a list item: all, listed IDs or names, or a context query. + * Each change writes the whole item, so that the attributes of the other + * choices are removed at the same time. + */ +function ContextScopeCell({ item, path, edit }: { item: Record; path: JsonPath; edit: Editor }) { + const scope = readContextScope(item); + const saved: ScopeMode = "contextQuery" in scope ? "query" : scope.contexts.length > 0 ? "contexts" : "all"; + /** The choice made while nothing is saved for it yet, such as Contexts before any is typed. */ + const [chosen, setChosen] = React.useState("all"); + const mode = saved === "all" ? chosen : saved; + const write = (next: ContextScope) => edit.set(path, withContextScope(item, next)); + const textEditor = (toScope: (text: string) => ContextScope): Editor => ({ + ...edit, + set: (_path, value) => write(toScope(String(value))), + remove: () => write({ contexts: [] }), + isMissing: () => false, + }); + return ( +
+
+ + edit.pickContexts(path)} + /> +
+ {mode === "contexts" && ( + 0 ? scope.contexts.join(", ") : undefined} + path={[...path, "contexts"]} + edit={textEditor((text) => ({ contexts: parseContextList(text) }))} + /> + )} + {mode === "query" && ( + (text.trim() ? { contextQuery: text.trim() } : { contexts: [] }))} + /> + )} +
+ ); +} + export function Unsupported({ value, edit }: { value: unknown; edit: Editor }) { return (
diff --git a/src/webview/launchSettings/styles.css b/src/webview/launchSettings/styles.css index fbaee9a..a4577d6 100644 --- a/src/webview/launchSettings/styles.css +++ b/src/webview/launchSettings/styles.css @@ -371,6 +371,17 @@ button:disabled { max-width: none; } +.context-scope { + display: flex; + flex-direction: column; + gap: 2px; +} + +.context-scope select { + flex: 1; + min-width: 0; +} + .fold-down { max-width: 800px; margin-top: 16px; From a6ff452033ebac027b1cd639ef63522297f08e10 Mon Sep 17 00:00:00 2001 From: Andreas Ragnerstam Date: Wed, 25 Nov 2026 09:29:28 +0100 Subject: [PATCH 3/4] Add a scope menu and context queries to pickers Breakpoints could only be scoped to listed contexts, and symbol files hid their context query behind a small title bar button. A menu first makes the choice clear: all contexts, the selected call-stack context, a checklist of contexts, or a context query. It works like the scope picker of the Path Map view and the dropdown in the launch form. Function breakpoints keep their scope in their name, so a query is written after " @? ", which no symbol contains. It is sent as the TCF ContextQuery breakpoint property. Agents that say they do not support it get an error, so the breakpoint is never set in all contexts. Signed-off-by: Andreas Ragnerstam --- CHANGELOG.md | 10 ++- README.md | 45 +++++++----- src/breakpointManager.ts | 19 ++++- src/contextChoices.ts | 58 +++++++++++++++ src/contextPicker.ts | 105 ++++++++++++++++++--------- src/extension.ts | 52 +++++++------ src/functionBreakpoint.ts | 34 ++++++++- src/launchSettings/editorProvider.ts | 1 - src/symbolFiles.ts | 18 +++-- src/tcf/services/breakpoints.ts | 3 + src/test/breakpointManager.test.ts | 54 ++++++++++++-- src/test/contextChoices.test.ts | 26 ++++++- src/test/symbolFiles.test.ts | 18 +++-- 13 files changed, 336 insertions(+), 107 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cef71b..da21ab4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,10 @@ All notable changes to the Simics Target Debug extension will be documented here - The Path Maps view lists the agent's rules from elsewhere, for example added with `add-pathmap-entry` in Simics, read-only under **Added Elsewhere**, like the Symbol Files view does. +- Function breakpoints can be scoped with a TCF context query, written as + `start_kernel @? **/HasState=true`. It is sent as the `ContextQuery` + breakpoint property. **Add Function Breakpoint...** in Symbol Files also + works for files with a context query. - A symbol file can apply to several contexts: `symbolFiles` entries take a `contexts` list of IDs or names. The file is added to the memory map of each context. @@ -43,9 +47,9 @@ All notable changes to the Simics Target Debug extension will be documented here services and message types. Stay in Console is gone from TCF Launch Configurations, turn off `debug.focusEditorOnBreak` instead. -- Symbol files and function breakpoints pick their contexts with the same - checklist. For symbol files, a button in its title bar switches to a - context query. In TCF Launch Configurations, the Contexts column of Symbol +- Symbol files and function breakpoints pick their contexts the same way: + a menu with all contexts, the selected call-stack context, a checklist of + contexts, or a context query. In TCF Launch Configurations, the Contexts column of Symbol Files chooses all contexts, a list of contexts, or a query, and can pick contexts from a running session to the agent. - The `context` of a symbol file is deprecated, use `contexts`. A symbol file diff --git a/README.md b/README.md index c36d876..dd36de0 100644 --- a/README.md +++ b/README.md @@ -267,9 +267,11 @@ is not used, to stay within the TCF specification. Use **Simics Target Debug: Add Function Breakpoint in Context...** from the Command Palette, the Breakpoints toolbar, or a stack frame's context menu to -check one or more cores before entering the symbol. The selected call-stack -context is listed first and checked; accept with nothing checked to keep the -breakpoint global. Scoped entries appear as +choose the contexts before entering the symbol. A menu offers **All +contexts**, the selected call-stack context (chosen by default), **Pick +Contexts...** to check one or more cores, and **Context Query...** to enter a +TCF context query. The last two have a Back button to the menu. Scoped +entries appear as `start_kernel @ armv8.cluster[0].core[0]` in the Breakpoints panel, or with a comma-separated list such as `start_kernel @ armv8.cluster[0].core[0], armv8.cluster[0].core[1]` when @@ -278,26 +280,30 @@ context IDs, which are sent as the breakpoint's `ContextIds` and saved with the breakpoint; selecting another frame does not change its scope. Context IDs that contain commas cannot be used. The same syntax can be entered or edited using the built-in function-breakpoint `+` or **Edit Function Breakpoint...**. -Scoped function breakpoints require the agent's `ContextIds` support and are -never silently planted globally when it is unavailable. Their scope applies +A context query is written after ` @? ` instead, such as +`start_kernel @? **/HasState=true`, and is sent as the breakpoint's +`ContextQuery`. Scoped function breakpoints require the agent's `ContextIds` +or `ContextQuery` support and are never silently planted globally when it is +unavailable. Their scope applies to those contexts (and, for a process context, its threads), not other cores. To change the contexts of an existing function breakpoint, use **Simics Target Debug: Edit Function Breakpoint Contexts...** from the Command Palette or the edit icon in the Breakpoints toolbar. VS Code does not tell extensions which breakpoint is selected in the Breakpoints panel, so the command asks for the -function breakpoint when there is more than one. The checklist starts with the -breakpoint's current contexts checked; contexts that are not in the current -session stay listed so they are not dropped by accident. The breakpoint is +function breakpoint when there is more than one. The menu starts on the +breakpoint's current scope, and **Pick Contexts...** starts with its contexts +checked; contexts that are not in the current session stay listed so they are +not dropped by accident. The breakpoint is replaced by one with the new name and the same enabled state, condition, hit count, and log message, so it moves to the end of the Breakpoints panel. -In **Symbol Files**, right-click a configured symbol file with contexts and -select **Add Function Breakpoint...** to enter a symbol directly. The breakpoint -uses the file's contexts rather than the selected call-stack core. Context names -are resolved to exact TCF IDs; unavailable or ambiguous contexts produce an error -instead of creating a global breakpoint. Files for all contexts or for a context -query do not offer this action. +In **Symbol Files**, right-click a configured symbol file with contexts or a +context query and select **Add Function Breakpoint...** to enter a symbol +directly. The breakpoint uses the file's contexts or query rather than the +selected call-stack core. Context names are resolved to exact TCF IDs; +unavailable or ambiguous contexts produce an error instead of creating a global +breakpoint. Files for all contexts do not offer this action. An address only has a meaning in one address space, so an instruction breakpoint is limited to the process of the context shown in the Disassembly @@ -561,7 +567,7 @@ buttons in the editor title switch between the form and the text of edited in the text. - The **Contexts** column of Symbol Files chooses all contexts, a list of context IDs or names separated by commas, or a context query. Its checklist - button picks them with the checklist of the Symbol Files view, from the + button picks them with the picker of the Symbol Files view, from the contexts of a running debug session to the configuration's agent; without one, type them. Changing the contexts writes `contexts` or `contextQuery` and removes the old single `context`. @@ -632,11 +638,10 @@ folders are suggested; select a folder to browse it, or enter a path directly if the file is only available to the agent. The contexts are picked with the same checklist as for function breakpoints: it lists the cores returned by the agent's `ContextQuery.query("HasState=true")` (or stateful RunControl contexts -if that service is unavailable), with the selected call-stack context first. -Check one or more of them, or none for all contexts. Checking a listed context -uses its ID; type an ID or name that is not listed to check it too. The filter -button in its title bar switches to entering a TCF context query instead, and -the checklist button there switches back. New entries are added to those from +if that service is unavailable). Choose **All contexts**, the selected +call-stack context, **Pick Contexts...** to check one or more, or **Context +Query...** to enter a TCF context query. Checking a listed context uses its +ID; type an ID or name that is not listed to check it too. New entries are added to those from `symbolFiles` for the running session only unless explicitly saved. Use the pencil action on a file in the Symbol Files view to edit its path, contexts (or context query), or load address. The same view lets you reload or remove a diff --git a/src/breakpointManager.ts b/src/breakpointManager.ts index 046a6c0..cd25e9e 100644 --- a/src/breakpointManager.ts +++ b/src/breakpointManager.ts @@ -234,14 +234,23 @@ export class BreakpointManager { const caps = await this.capabilities(); const specs = requested.map((r): BreakpointSpec => { const spec: BreakpointSpec = { kind: "function", key: r.name }; - const { location, contextIds, hasContextDelimiter, hasEmptyContext } = parseFunctionBreakpointName(r.name); + const { location, contextIds, contextQuery, hasContextDelimiter, hasEmptyContext } = + parseFunctionBreakpointName(r.name); if (caps.Location === false) { return { ...spec, error: "The TCF agent does not support breakpoints on expressions" }; } if (hasContextDelimiter && (hasEmptyContext || !location)) { return { ...spec, - error: "Use 'symbol @ context ID' or 'symbol @ ID1, ID2' for a context-scoped function breakpoint", + error: + "Use 'symbol @ context ID', 'symbol @ ID1, ID2' or 'symbol @? context query' " + + "for a context-scoped function breakpoint", + }; + } + if (contextQuery !== undefined && caps.ContextQuery === false) { + return { + ...spec, + error: "Function breakpoints with a context query require breakpoint ContextQuery support", }; } if (contextIds.length > 0 && caps.ContextIds === false) { @@ -249,7 +258,11 @@ export class BreakpointManager { } return this.withCommonProps( spec, - { Location: location, ...(contextIds.length > 0 && { ContextIds: contextIds }) }, + { + Location: location, + ...(contextIds.length > 0 && { ContextIds: contextIds }), + ...(contextQuery !== undefined && { ContextQuery: contextQuery }), + }, r, caps, ); diff --git a/src/contextChoices.ts b/src/contextChoices.ts index 7fa2c2a..e5cf080 100644 --- a/src/contextChoices.ts +++ b/src/contextChoices.ts @@ -97,3 +97,61 @@ export function describeContextScope(scope: { contexts?: readonly string[]; cont } return scope.contexts && scope.contexts.length > 0 ? scope.contexts.join(", ") : "all contexts"; } + +export interface ScopeMenuItem { + label: string; + description?: string; + /** A scope to accept at once, or the next step: the checklist or the context query input. */ + action: { scope: ContextScope } | { step: "pick" | "query" }; + /** The item that stands for the scope the menu starts with. */ + active?: boolean; +} + +/** + * The first step of the context picker: all contexts, the selected + * call-stack context, the current scope if it is neither of those, and the + * steps to check contexts or enter a context query. Labels have codicons. + */ +export function scopeMenuItems( + scope: ContextScope, + contexts: readonly TargetContext[], + selectedId?: string, +): ScopeMenuItem[] { + const selected = contexts.find((context) => context.id === selectedId); + const checked = "contexts" in scope ? scope.contexts : []; + const isAll = "contexts" in scope && checked.length === 0; + const isSelected = selected !== undefined && checked.length === 1 && checked[0] === selected.id; + const items: ScopeMenuItem[] = []; + if (!isAll && !isSelected) { + const names = checked.map((entry) => contexts.find((context) => context.id === entry)?.name ?? entry); + items.push({ + label: `$(check) ${"contextQuery" in scope ? `Contexts matching ${scope.contextQuery}` : names.join(", ")}`, + description: "Current", + action: { scope }, + active: true, + }); + } + items.push({ + label: "$(globe) All contexts", + description: "No context filter", + action: { scope: { contexts: [] } }, + active: isAll, + }); + if (selected) { + items.push({ + label: `$(debug-stackframe) ${selected.name}`, + description: `Selected call-stack context (${selected.id})`, + action: { scope: { contexts: [selected.id] } }, + active: isSelected, + }); + } + items.push( + { label: "$(checklist) Pick Contexts...", description: "Check one or more contexts", action: { step: "pick" } }, + { + label: "$(filter) Context Query...", + description: "Enter a TCF context query", + action: { step: "query" }, + }, + ); + return items; +} diff --git a/src/contextPicker.ts b/src/contextPicker.ts index 42dfd7c..c53d247 100644 --- a/src/contextPicker.ts +++ b/src/contextPicker.ts @@ -1,5 +1,13 @@ import * as vscode from "vscode"; -import { ContextChoice, ContextScope, TargetContext, contextChoices, pickedValues } from "./contextChoices"; +import { + ContextChoice, + ContextScope, + ScopeMenuItem, + TargetContext, + contextChoices, + pickedValues, + scopeMenuItems, +} from "./contextChoices"; /** * The contexts of a session to pick from: the cores (contexts with state), @@ -18,65 +26,96 @@ export interface PickContextsOptions { contexts: readonly TargetContext[]; /** The scope to start with. */ scope: ContextScope; - /** A context to list first, such as the one selected in the Call Stack view. */ + /** A context to offer first, such as the one selected in the Call Stack view. */ selectedId?: string; + /** The placeholder of the checklist. */ placeholder?: string; - /** Offer a button to enter a TCF context query instead of checking contexts. */ - allowQuery?: boolean; /** Offer typed text as a context ID or name to check, for contexts that are not listed. */ allowTyped?: boolean; } -/** The scope picked, or what was entered when the user switched to the other way of picking. */ -type Step = { scope: ContextScope } | { switched: T } | undefined; - -const QUERY_BUTTON: vscode.QuickInputButton = { - iconPath: new vscode.ThemeIcon("filter"), - tooltip: "Use a Context Query Instead", -}; -const CONTEXTS_BUTTON: vscode.QuickInputButton = { - iconPath: new vscode.ThemeIcon("checklist"), - tooltip: "Check Contexts Instead", -}; +/** The scope picked, Back, or undefined when cancelled. */ +type Step = { scope: ContextScope } | { back: T } | undefined; /** - * Lets the user check the contexts something applies to, or enter a context - * query when `allowQuery` is set. No checked context means all contexts. - * Returns undefined if cancelled. + * Lets the user choose the contexts something applies to: first all + * contexts, the selected call-stack context or the current scope, or the + * steps to check contexts or enter a TCF context query. Those steps have a + * Back button to the first one. Returns undefined if cancelled. */ export async function pickContexts(options: PickContextsOptions): Promise { - let byQuery = "contextQuery" in options.scope; - let contexts = "contexts" in options.scope ? options.scope.contexts : []; + let checked = "contexts" in options.scope ? options.scope.contexts : []; let query = "contextQuery" in options.scope ? options.scope.contextQuery : ""; for (;;) { - if (byQuery) { - const step = await enterQuery(options, query); + const action = await chooseScope(options); + if (action === undefined || "scope" in action) { + return action?.scope; + } + if (action.step === "pick") { + const step = await check(options, checked); if (step === undefined || "scope" in step) { return step?.scope; } - query = step.switched; + checked = step.back; } else { - const step = await check(options, contexts); + const step = await enterQuery(options, query); if (step === undefined || "scope" in step) { return step?.scope; } - contexts = step.switched; + query = step.back; } - byQuery = !byQuery; } } +type MenuItem = vscode.QuickPickItem & { action: ScopeMenuItem["action"] }; + +function chooseScope(options: PickContextsOptions): Promise { + return new Promise((resolve) => { + const picker = vscode.window.createQuickPick(); + picker.title = options.title; + picker.placeholder = "Choose the contexts it applies to"; + picker.matchOnDescription = true; + const menu = scopeMenuItems(options.scope, options.contexts, options.selectedId); + const items: MenuItem[] = menu.map(({ label, description, action }) => ({ label, description, action })); + picker.items = items; + const active = items[menu.findIndex((item) => item.active)]; + if (active) { + picker.activeItems = [active]; + } + let finished = false; + + function finish(action: MenuItem["action"] | undefined): void { + if (finished) { + return; + } + finished = true; + picker.hide(); + picker.dispose(); + resolve(action); + } + + picker.onDidAccept(() => { + const item = picker.activeItems[0]; + if (item) { + finish(item.action); + } + }); + picker.onDidHide(() => finish(undefined)); + picker.show(); + }); +} + type Item = ContextChoice & vscode.QuickPickItem; function check(options: PickContextsOptions, initial: readonly string[]): Promise> { return new Promise((resolve) => { const picker = vscode.window.createQuickPick(); picker.title = options.title; - picker.placeholder = options.placeholder ?? "Check the contexts, or check none for all contexts"; + picker.placeholder = options.placeholder ?? "Check one or more contexts"; picker.canSelectMany = true; picker.matchOnDescription = true; picker.matchOnDetail = true; - picker.buttons = options.allowQuery ? [QUERY_BUTTON] : []; + picker.buttons = [vscode.QuickInputButtons.Back]; let finished = false; function finish(step: Step): void { @@ -125,7 +164,7 @@ function check(options: PickContextsOptions, initial: readonly string[]): Promis if (options.allowTyped) { picker.onDidChangeValue(() => update(pickedValues(picker.selectedItems))); } - picker.onDidTriggerButton(() => finish({ switched: pickedValues(picker.selectedItems) })); + picker.onDidTriggerButton(() => finish({ back: pickedValues(picker.selectedItems) })); picker.onDidAccept(() => { const picked = pickedValues(picker.selectedItems); if (typedItem && typedOnly && !picked.includes(typedItem.value)) { @@ -143,10 +182,10 @@ function enterQuery(options: PickContextsOptions, initial: string): Promise { const input = vscode.window.createInputBox(); input.title = options.title; - input.prompt = "TCF context query, for example **/HasState=true"; + input.prompt = "TCF context query"; input.placeholder = "Context query"; input.value = initial; - input.buttons = [CONTEXTS_BUTTON]; + input.buttons = [vscode.QuickInputButtons.Back]; let finished = false; function finish(step: Step): void { @@ -162,11 +201,11 @@ function enterQuery(options: PickContextsOptions, initial: string): Promise { input.validationMessage = undefined; }); - input.onDidTriggerButton(() => finish({ switched: input.value.trim() })); + input.onDidTriggerButton(() => finish({ back: input.value.trim() })); input.onDidAccept(() => { const query = input.value.trim(); if (!query) { - input.validationMessage = "Enter a context query, or use the button to check contexts"; + input.validationMessage = "Enter a context query"; return; } finish({ scope: { contextQuery: query } }); diff --git a/src/extension.ts b/src/extension.ts index e3155f5..6f83019 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -8,7 +8,11 @@ import { parseInstructionReference } from "./disassembly"; import { registerFunctionHeaderFileSystem } from "./functionHeaderFileSystem"; import { applyAndSave, registerLaunchSettings } from "./launchSettings/editorProvider"; import { setNamedConfigurationValue } from "./launchSettings/launchJson"; -import { formatFunctionBreakpointName, parseFunctionBreakpointName } from "./functionBreakpoint"; +import { + formatFunctionBreakpointName, + functionBreakpointScope, + parseFunctionBreakpointName, +} from "./functionBreakpoint"; import { ContextScope, TargetContext, describeContextScope } from "./contextChoices"; import { listContexts, pickContexts } from "./contextPicker"; import { MissingSource, SourceLocator } from "./locateSource"; @@ -19,7 +23,7 @@ import { ForeignSymbolFile, SymbolFileConfig, describeForeignSymbolFile, - symbolFileBreakpointContexts, + symbolFileBreakpointScope, } from "./symbolFiles"; import { suggestSymbolPaths } from "./symbolPath"; import { registerConsolesView } from "./consolesView"; @@ -261,26 +265,26 @@ async function addFunctionBreakpointInContext( try { const contexts = await listContexts(session, symbolFile !== undefined); const selected = contexts.find((context) => threadId !== undefined && context.threadId === threadId); - const contextIds = symbolFile - ? symbolFileBreakpointContexts(symbolFile.file, contexts) + const scope = symbolFile + ? symbolFileBreakpointScope(symbolFile.file, contexts) : await pickBreakpointContexts( "Function Breakpoint Contexts", contexts, - selected ? [selected.id] : [], + { contexts: selected ? [selected.id] : [] }, selected, ); - if (!contextIds) { + if (!scope) { return; } const symbol = await vscode.window.showInputBox({ title: "Add Function Breakpoint", - prompt: contextIds.length > 0 ? `Symbol in ${contextIds.join(", ")}` : "Symbol in all contexts", + prompt: `Symbol in ${describeContextScope(scope)}`, validateInput: (value) => (!value.trim() ? "Enter a symbol or expression" : undefined), }); if (!symbol?.trim()) { return; } - const name = formatFunctionBreakpointName(symbol.trim(), contextIds); + const name = formatFunctionBreakpointName(symbol.trim(), scope); if ( !vscode.debug.breakpoints.some((bp) => bp instanceof vscode.FunctionBreakpoint && bp.functionName === name) ) { @@ -293,21 +297,20 @@ async function addFunctionBreakpointInContext( } } -/** Returns the checked context IDs, empty for all contexts, or undefined if cancelled. */ -async function pickBreakpointContexts( +/** Returns the context IDs (empty for all contexts) or context query, or undefined if cancelled. */ +function pickBreakpointContexts( title: string, contexts: TargetContext[], - checked: string[], + scope: ContextScope, selected: TargetContext | undefined, -): Promise { - const scope = await pickContexts({ +): Promise { + return pickContexts({ title, contexts, - scope: { contexts: checked }, + scope, selectedId: selected?.id, - placeholder: "Check the cores to stop in, or check none for all contexts", + placeholder: "Check the cores to stop in", }); - return scope && "contexts" in scope ? scope.contexts : undefined; } /** @@ -353,7 +356,8 @@ async function editFunctionBreakpointContexts(): Promise { if (!breakpoint) { return; } - const { location, contextIds } = parseFunctionBreakpointName(breakpoint.functionName); + const parsed = parseFunctionBreakpointName(breakpoint.functionName); + const { location } = parsed; if (!location) { void vscode.window.showErrorMessage(`'${breakpoint.functionName}' has no symbol to scope.`); return; @@ -362,11 +366,16 @@ async function editFunctionBreakpointContexts(): Promise { const contexts = await listContexts(session); const threadId = active?.session.id === session.id ? active.threadId : undefined; const selected = contexts.find((context) => threadId !== undefined && context.threadId === threadId); - const ids = await pickBreakpointContexts(`Contexts for ${location}`, contexts, contextIds, selected); - if (!ids) { + const scope = await pickBreakpointContexts( + `Contexts for ${location}`, + contexts, + functionBreakpointScope(parsed), + selected, + ); + if (!scope) { return; } - const name = formatFunctionBreakpointName(location, ids); + const name = formatFunctionBreakpointName(location, scope); if (name === breakpoint.functionName) { return; } @@ -803,7 +812,6 @@ async function promptSymbolScope(session: vscode.DebugSession, scope: ContextSco scope, selectedId: contexts.find((context) => threadId !== undefined && context.threadId === threadId)?.id, placeholder: "Check the contexts the symbols apply to, or check none for all contexts", - allowQuery: true, allowTyped: true, }); } @@ -885,7 +893,7 @@ class SymbolFileViewItem extends vscode.TreeItem { readonly session: vscode.DebugSession, ) { super(path.basename(file.path)); - this.contextValue = file.contexts?.length ? "symbolFile scoped" : "symbolFile"; + this.contextValue = file.contexts?.length || file.contextQuery ? "symbolFile scoped" : "symbolFile"; this.description = `${describeContextScope(file)}${loadAddressSuffix(file)}`; this.tooltip = `${file.path}\n${this.description}`; this.iconPath = new vscode.ThemeIcon("file-code"); diff --git a/src/functionBreakpoint.ts b/src/functionBreakpoint.ts index 83e4a06..33fa95c 100644 --- a/src/functionBreakpoint.ts +++ b/src/functionBreakpoint.ts @@ -1,22 +1,43 @@ +import type { ContextScope } from "./contextChoices"; + export const FUNCTION_BREAKPOINT_CONTEXT_SEPARATOR = " @ "; export const FUNCTION_BREAKPOINT_CONTEXT_LIST_SEPARATOR = ", "; +export const FUNCTION_BREAKPOINT_QUERY_SEPARATOR = " @? "; export interface ParsedFunctionBreakpointName { location: string; /** The distinct context IDs after the separator, empty for a global breakpoint. */ contextIds: string[]; + /** The context query after " @? ", if the breakpoint has one. */ + contextQuery?: string; hasContextDelimiter: boolean; - /** True if the context list has an empty entry, for example "f @ " or "f @ a, , b". */ + /** True if the context list or query has an empty entry, for example "f @ ", "f @ a, , b" or "f @? ". */ hasEmptyContext: boolean; } -export function formatFunctionBreakpointName(location: string, contextIds: readonly string[] = []): string { - return contextIds.length > 0 - ? `${location}${FUNCTION_BREAKPOINT_CONTEXT_SEPARATOR}${contextIds.join(FUNCTION_BREAKPOINT_CONTEXT_LIST_SEPARATOR)}` +/** "f", "f @ id1, id2" for context IDs, or "f @? query" for a context query. */ +export function formatFunctionBreakpointName(location: string, scope: ContextScope = { contexts: [] }): string { + if ("contextQuery" in scope) { + return `${location}${FUNCTION_BREAKPOINT_QUERY_SEPARATOR}${scope.contextQuery}`; + } + return scope.contexts.length > 0 + ? `${location}${FUNCTION_BREAKPOINT_CONTEXT_SEPARATOR}${scope.contexts.join(FUNCTION_BREAKPOINT_CONTEXT_LIST_SEPARATOR)}` : location; } export function parseFunctionBreakpointName(name: string): ParsedFunctionBreakpointName { + // Checked first, as a query may contain " @ " but a symbol never has " @? ". + const query = name.indexOf(FUNCTION_BREAKPOINT_QUERY_SEPARATOR); + if (query >= 0) { + const contextQuery = name.slice(query + FUNCTION_BREAKPOINT_QUERY_SEPARATOR.length).trim(); + return { + location: name.slice(0, query).trim(), + contextIds: [], + ...(contextQuery && { contextQuery }), + hasContextDelimiter: true, + hasEmptyContext: !contextQuery, + }; + } const separator = name.lastIndexOf(FUNCTION_BREAKPOINT_CONTEXT_SEPARATOR); if (separator < 0) { return { location: name, contextIds: [], hasContextDelimiter: false, hasEmptyContext: false }; @@ -33,3 +54,8 @@ export function parseFunctionBreakpointName(name: string): ParsedFunctionBreakpo hasEmptyContext: entries.some((id) => !id), }; } + +/** The scope of a parsed function breakpoint name. */ +export function functionBreakpointScope(parsed: ParsedFunctionBreakpointName): ContextScope { + return parsed.contextQuery !== undefined ? { contextQuery: parsed.contextQuery } : { contexts: parsed.contextIds }; +} diff --git a/src/launchSettings/editorProvider.ts b/src/launchSettings/editorProvider.ts index 586be05..d06c406 100644 --- a/src/launchSettings/editorProvider.ts +++ b/src/launchSettings/editorProvider.ts @@ -353,7 +353,6 @@ async function pickItemContexts( contexts, scope: readContextScope(item), placeholder: "Check the contexts, or check none for all contexts", - allowQuery: true, allowTyped: true, }); if (scope === undefined) { diff --git a/src/symbolFiles.ts b/src/symbolFiles.ts index 918f622..73aa857 100644 --- a/src/symbolFiles.ts +++ b/src/symbolFiles.ts @@ -1,4 +1,5 @@ import * as fs from "fs"; +import type { ContextScope } from "./contextChoices"; import { toBigInt } from "./tcf/json"; import { MemoryMapService, MemoryRegionProperties } from "./tcf/services/memoryMap"; @@ -38,16 +39,22 @@ export interface SymbolFile { absolute?: true; } -/** The context IDs to set a function breakpoint in for the symbol file's contexts. */ -export function symbolFileBreakpointContexts( - file: Pick, +/** + * The scope of a function breakpoint for the symbol file: the IDs of its + * contexts, or its context query. + */ +export function symbolFileBreakpointScope( + file: Pick, contexts: readonly { id: string; name: string }[], -): string[] { +): ContextScope { + if (file.contextQuery) { + return { contextQuery: file.contextQuery }; + } const scope = file.contexts ?? []; if (scope.length === 0) { throw new Error("The symbol file has no contexts"); } - return [ + const ids = [ ...new Set( scope.map((entry) => { const exact = contexts.find((context) => context.id === entry); @@ -66,6 +73,7 @@ export function symbolFileBreakpointContexts( }), ), ]; + return { contexts: ids }; } /** The symbol file as a "symbolFiles" entry of a debug configuration, with the address as a string. */ diff --git a/src/tcf/services/breakpoints.ts b/src/tcf/services/breakpoints.ts index 7385ced..6036305 100644 --- a/src/tcf/services/breakpoints.ts +++ b/src/tcf/services/breakpoints.ts @@ -6,6 +6,8 @@ export interface BreakpointProperties { Enabled?: boolean; BreakpointType?: "Software" | "Hardware" | "Auto"; ContextIds?: string[]; + /** Installs the breakpoint in the contexts that match this context query. */ + ContextQuery?: string; Location?: string; /** Bit set of AccessMode values. */ AccessMode?: number; @@ -54,6 +56,7 @@ export interface BreakpointCapabilities { /** Bit set of supported AccessMode values. */ AccessMode?: number; ContextIds?: boolean; + ContextQuery?: boolean; [key: string]: unknown; } diff --git a/src/test/breakpointManager.test.ts b/src/test/breakpointManager.test.ts index e4d510b..627ce6c 100644 --- a/src/test/breakpointManager.test.ts +++ b/src/test/breakpointManager.test.ts @@ -80,13 +80,19 @@ function fakeHost(threads: string[]): BreakpointHost & { events: unknown[] } { } test("function breakpoint names preserve explicit context scopes", async () => { - assert.deepEqual(parseFunctionBreakpointName(formatFunctionBreakpointName("start_kernel", ["cpu0"])), { - location: "start_kernel", - contextIds: ["cpu0"], - hasContextDelimiter: true, - hasEmptyContext: false, - }); - assert.equal(formatFunctionBreakpointName("start_kernel", ["cpu0", "cpu1"]), "start_kernel @ cpu0, cpu1"); + assert.deepEqual( + parseFunctionBreakpointName(formatFunctionBreakpointName("start_kernel", { contexts: ["cpu0"] })), + { + location: "start_kernel", + contextIds: ["cpu0"], + hasContextDelimiter: true, + hasEmptyContext: false, + }, + ); + assert.equal( + formatFunctionBreakpointName("start_kernel", { contexts: ["cpu0", "cpu1"] }), + "start_kernel @ cpu0, cpu1", + ); assert.deepEqual(parseFunctionBreakpointName("start_kernel @ cpu0,cpu1 , cpu0"), { location: "start_kernel", contextIds: ["cpu0", "cpu1"], @@ -121,6 +127,40 @@ test("function breakpoint names preserve explicit context scopes", async () => { assert.deepEqual(changed.ContextIds, properties[0].ContextIds); }); +// " @? " gives a context query, which may itself contain " @ ". +test("function breakpoint names can have a context query", async () => { + const name = formatFunctionBreakpointName("start_kernel", { contextQuery: 'Name="a @ b"' }); + assert.equal(name, 'start_kernel @? Name="a @ b"'); + assert.deepEqual(parseFunctionBreakpointName(name), { + location: "start_kernel", + contextIds: [], + contextQuery: 'Name="a @ b"', + hasContextDelimiter: true, + hasEmptyContext: false, + }); + const agent = fakeAgent(); + const manager = new BreakpointManager(agent.service, fakeHost(["thread1"])); + const [planted, empty] = await manager.setFunctionBreakpoints([ + { name: "start_kernel @? **/HasState=true" }, + { name: "start_kernel @? " }, + ]); + assert.equal(planted.verified, true); + assert.match(empty.message ?? "", /symbol @\? context query/); + const properties = agent.commands.map(([, props]) => props as BreakpointProperties); + assert.equal(properties.length, 1); + assert.equal(properties[0].Location, "start_kernel"); + assert.equal(properties[0].ContextQuery, "**/HasState=true"); + assert.equal(properties[0].ContextIds, undefined); + + const old = fakeAgent(); + old.caps.ContextQuery = false; + const [unsupported] = await new BreakpointManager(old.service, fakeHost(["thread1"])).setFunctionBreakpoints([ + { name: "start_kernel @? **/HasState=true" }, + ]); + assert.match(unsupported.message ?? "", /ContextQuery support/); + assert.equal(old.commands.length, 0); +}); + test("scoped function breakpoints never fall back to global planting", async () => { const agent = fakeAgent(); agent.caps.ContextIds = false; diff --git a/src/test/contextChoices.test.ts b/src/test/contextChoices.test.ts index 40fd911..451f440 100644 --- a/src/test/contextChoices.test.ts +++ b/src/test/contextChoices.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { contextChoices, describeContextScope, parseContextList, pickedValues } from "@/contextChoices"; +import { contextChoices, describeContextScope, parseContextList, pickedValues, scopeMenuItems } from "@/contextChoices"; const CONTEXTS = [ { id: "core-0", name: "board.cpu0" }, @@ -44,3 +44,27 @@ test("parseContextList and describeContextScope", () => { assert.equal(describeContextScope({ contexts: ["cpu0", "cpu1"] }), "cpu0, cpu1"); assert.equal(describeContextScope({ contextQuery: "**/HasState=true" }), "contexts matching **/HasState=true"); }); + +// The menu starts on the item for the current scope. Another scope than all +// or the selected context gets an item of its own at the top. +test("scopeMenuItems offers the current scope, all, the selected context, pick and query", () => { + const menu = (scope: Parameters[0], selectedId?: string) => + scopeMenuItems(scope, CONTEXTS, selectedId).map((item) => [item.label, item.active ?? false]); + assert.deepEqual(menu({ contexts: [] }, "core-1"), [ + ["$(globe) All contexts", true], + ["$(debug-stackframe) board.cpu1", false], + ["$(checklist) Pick Contexts...", false], + ["$(filter) Context Query...", false], + ]); + assert.deepEqual(menu({ contexts: ["core-1"] }, "core-1").slice(0, 2), [ + ["$(globe) All contexts", false], + ["$(debug-stackframe) board.cpu1", true], + ]); + assert.deepEqual(menu({ contexts: ["core-0", "gone"] }).slice(0, 2), [ + ["$(check) board.cpu0, gone", true], + ["$(globe) All contexts", false], + ]); + const [current] = scopeMenuItems({ contextQuery: "HasState=true" }, CONTEXTS); + assert.equal(current.label, "$(check) Contexts matching HasState=true"); + assert.deepEqual(current.action, { scope: { contextQuery: "HasState=true" } }); +}); diff --git a/src/test/symbolFiles.test.ts b/src/test/symbolFiles.test.ts index 8a7a1b1..fc19684 100644 --- a/src/test/symbolFiles.test.ts +++ b/src/test/symbolFiles.test.ts @@ -9,7 +9,7 @@ import { describeForeignSymbolFile, formatSymbolFileAddress, parseSymbolFilesConfig, - symbolFileBreakpointContexts, + symbolFileBreakpointScope, symbolFileConfig, } from "@/symbolFiles"; import { MemoryMapService, MemoryRegionProperties } from "@/tcf/services/memoryMap"; @@ -157,17 +157,19 @@ test("applySymbolFiles sets the region in the map of each context", async () => ]); }); -test("symbolFileBreakpointContexts resolves each context of the file", () => { +test("symbolFileBreakpointScope resolves each context of the file, or uses its query", () => { const contexts = [ { id: "core-0", name: "board.cpu0" }, { id: "core-1", name: "board.cpu1" }, ]; - assert.deepEqual(symbolFileBreakpointContexts({ contexts: ["board.cpu1", "core-0", "core-1"] }, contexts), [ - "core-1", - "core-0", - ]); - assert.throws(() => symbolFileBreakpointContexts({ contexts: [] }, contexts), /no contexts/); - assert.throws(() => symbolFileBreakpointContexts({ contexts: ["core-0", "gone"] }, contexts), /'gone' is not/); + assert.deepEqual(symbolFileBreakpointScope({ contexts: ["board.cpu1", "core-0", "core-1"] }, contexts), { + contexts: ["core-1", "core-0"], + }); + assert.deepEqual(symbolFileBreakpointScope({ contextQuery: "HasState=true" }, contexts), { + contextQuery: "HasState=true", + }); + assert.throws(() => symbolFileBreakpointScope({ contexts: [] }, contexts), /no contexts/); + assert.throws(() => symbolFileBreakpointScope({ contexts: ["core-0", "gone"] }, contexts), /'gone' is not/); }); // Files for the same context share one MemoryMap.set. A missing file only From 2d7f016ec3d3c46d42509f8e6c43429e6d41d6e6 Mon Sep 17 00:00:00 2001 From: Andreas Ragnerstam Date: Wed, 25 Nov 2026 09:50:25 +0100 Subject: [PATCH 4/4] Use the shared context picker for path map rules The Path Maps view and Locate Source File had their own scope picker that took a single context ID. Using the same picker as breakpoints and symbol files makes all of them look and work the same. To pick several contexts, path map rules get a "contexts" list. The TCF context query syntax cannot select one of several IDs, so a rule with several contexts is sent to the agent as one rule per context, like symbol files get one memory map region per context. The old "context" still works but is deprecated. The launch configurations form gets the same Contexts column for path map rules as for symbol files. Signed-off-by: Andreas Ragnerstam --- CHANGELOG.md | 14 ++- README.md | 29 +++-- package.json | 18 ++- src/contextPicker.ts | 8 +- src/launchSettings/editorProvider.ts | 8 +- src/launchSettings/launchJson.ts | 1 + src/launchSettings/schema.ts | 7 +- src/locateSource.ts | 9 +- src/pathMapScope.ts | 90 ++++++++------- src/pathMapView.ts | 11 +- src/pathMapper.ts | 104 ++++++++++++------ src/test/pathMapper.test.ts | 50 ++++++++- src/test/schema.test.ts | 3 +- src/test/tcfDebugSession.test.ts | 2 +- .../launchSettings/components/controls.tsx | 2 +- 15 files changed, 236 insertions(+), 120 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da21ab4..8366679 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ All notable changes to the Simics Target Debug extension will be documented here - The Path Maps view lists the agent's rules from elsewhere, for example added with `add-pathmap-entry` in Simics, read-only under **Added Elsewhere**, like the Symbol Files view does. +- A path map rule can apply to several contexts: `pathMap` rules take a + `contexts` list of context IDs. Each context is sent to the agent as a rule + of its own. The old `context` is deprecated. - Function breakpoints can be scoped with a TCF context query, written as `start_kernel @? **/HasState=true`. It is sent as the `ContextQuery` breakpoint property. **Add Function Breakpoint...** in Symbol Files also @@ -47,11 +50,12 @@ All notable changes to the Simics Target Debug extension will be documented here services and message types. Stay in Console is gone from TCF Launch Configurations, turn off `debug.focusEditorOnBreak` instead. -- Symbol files and function breakpoints pick their contexts the same way: - a menu with all contexts, the selected call-stack context, a checklist of - contexts, or a context query. In TCF Launch Configurations, the Contexts column of Symbol - Files chooses all contexts, a list of contexts, or a query, and can pick - contexts from a running session to the agent. +- Symbol files, function breakpoints and path map rules pick their contexts + the same way: a menu with all contexts, the selected call-stack context, a + checklist of contexts, or a context query. In TCF Launch Configurations, + the Contexts column of Symbol Files and Path Map chooses all contexts, a + list of contexts, or a query, and can pick contexts from a running session + to the agent. - The `context` of a symbol file is deprecated, use `contexts`. A symbol file can no longer have both contexts and a `contextQuery`. - In TCF Launch Configurations, the Start, Duplicate and Delete buttons diff --git a/README.md b/README.md index dd36de0..2a7e950 100644 --- a/README.md +++ b/README.md @@ -565,8 +565,9 @@ buttons in the editor title switch between the form and the text of under **Advanced** at the end, with `connectTimeout`. Others, like `preLaunchTask`, are listed under **Other Attributes** when set, and can be edited in the text. -- The **Contexts** column of Symbol Files chooses all contexts, a list of - context IDs or names separated by commas, or a context query. Its checklist +- The **Contexts** column of Symbol Files and Path Map chooses all contexts, + a list of contexts separated by commas (IDs or names for symbol files, IDs + for path map rules), or a context query. Its checklist button picks them with the picker of the Symbol Files view, from the contexts of a running debug session to the configuration's agent; without one, type them. Changing the contexts writes `contexts` or `contextQuery` @@ -718,14 +719,14 @@ A prefix only matches at a path separator, so `/build/src` maps compiled paths. Invalid rules are reported in the Debug Console and ignored. Rules apply to **all contexts by default**. To scope a rule, set either -`context` to an exact context ID or `contextQuery` to a TCF query: +`contexts` to a list of exact context IDs or `contextQuery` to a TCF query: ```json "pathMap": [ { "source": "/build/src", "destination": "${workspaceFolder}/cpu0", - "context": "cpu0" + "contexts": ["cpu0", "cpu1"] }, { "source": "/build/src", @@ -736,11 +737,13 @@ Rules apply to **all contexts by default**. To scope a rule, set either ``` Both options use the protocol's `ContextQuery` property in `PathMap.set`. -For example, `context: "cpu0"` is sent as `ContextQuery: "ID=cpu0"`; -`contextQuery: "ID=cpu0"` is equivalent. IDs containing punctuation are -quoted and escaped as TCF query values. Set only one scope field per rule; -to select an ID together with additional criteria, use a query such as -`ID=cpu0,HasState=true`. +For example, `contexts: ["cpu0"]` is sent as `ContextQuery: "ID=cpu0"`; +`contextQuery: "ID=cpu0"` is equivalent. A query cannot select one of several +IDs, so a rule with several contexts is sent as one agent rule per context. +IDs containing punctuation are quoted and escaped as TCF query values. Set +only one scope field per rule; to select an ID together with additional +criteria, use a query such as `ID=cpu0,HasState=true`. The old `context`, a +single ID, still works and is deprecated. Source lookups and their caches are context-specific, including rules reported by `PathMap.get`, so identical compiled paths in different contexts @@ -759,13 +762,15 @@ path map rule is made from the part of the two paths that differs, for example `/build` → `/home/me` for `/build/fw/a.c` and `/home/me/fw/a.c`. The rule is used at once for the rest of the session, including breakpoints, and can be saved to the configuration's `pathMap` in launch.json. Before applying the -new rule, choose **All contexts**, **Context ID** (prefilled with the frame's -context ID), or **Context query**. +new rule, choose its contexts with the same picker as for breakpoints and +symbol files: **All contexts**, the frame's context, **Pick Contexts...** or +**Context Query...**. During a Simics Target Debug session, **Run and Debug > Path Maps** lists the session's rules in matching order, with the compiled prefix on the left and the host destination and scope beside it. Use **+** to add a rule, click a rule to -edit its paths and scope, or use its trash button to remove it. +edit its paths and contexts, or use its trash button to remove it. The +contexts are chosen with the same picker as for breakpoints and symbol files. The context menu has **Move Rule Up/Down** to change priority. Changes apply immediately and refresh the call stack; rules created by **Locate Source File...** appear here too. diff --git a/package.json b/package.json index 6b0b7d1..2960bfb 100644 --- a/package.json +++ b/package.json @@ -944,15 +944,25 @@ "format": "file-or-folder-path", "description": "Corresponding path prefix on this host, for example ${workspaceFolder}." }, - "context": { + "contexts": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true, + "description": "Exact context IDs. Each is sent to PathMap.set as a rule with ContextQuery=\"ID=\". Use either contexts or contextQuery, not both. Omit both to apply to all contexts." + }, + "contextQuery": { "type": "string", "minLength": 1, - "description": "Exact context ID. Sent to PathMap.set as ContextQuery=\"ID=\". Use either context or contextQuery, not both. Omit both to apply to all contexts." + "description": "TCF context query selecting a group of contexts, for example \"/server/**/HasState=true\". Sent as the ContextQuery property of PathMap.set. Use either contexts or contextQuery, not both." }, - "contextQuery": { + "context": { "type": "string", "minLength": 1, - "description": "TCF context query selecting a group of contexts, for example \"**/HasState=true\" or \"ID=cpu0\". Sent as the ContextQuery property of PathMap.set. Use either context or contextQuery, not both." + "description": "Exact context ID.", + "deprecationMessage": "Use \"contexts\" instead, a list of context IDs." } } }, diff --git a/src/contextPicker.ts b/src/contextPicker.ts index c53d247..4c0bf71 100644 --- a/src/contextPicker.ts +++ b/src/contextPicker.ts @@ -32,6 +32,8 @@ export interface PickContextsOptions { placeholder?: string; /** Offer typed text as a context ID or name to check, for contexts that are not listed. */ allowTyped?: boolean; + /** Typed text is a context ID only, not a name. */ + idsOnly?: boolean; } /** The scope picked, Back, or undefined when cancelled. */ @@ -148,9 +150,9 @@ function check(options: PickContextsOptions, initial: readonly string[]): Promis ); typedItem = { label: typed, - description: typedOnly - ? "Press Enter or check to use this context ID or name" - : "Check to use this context ID or name", + description: `${typedOnly ? "Press Enter or check" : "Check"} to use this context ${ + options.idsOnly ? "ID" : "ID or name" + }`, value: typed, picked: false, alwaysShow: true, diff --git a/src/launchSettings/editorProvider.ts b/src/launchSettings/editorProvider.ts index d06c406..9eaec35 100644 --- a/src/launchSettings/editorProvider.ts +++ b/src/launchSettings/editorProvider.ts @@ -347,13 +347,15 @@ async function pickItemContexts( `Could not list TCF contexts, type their IDs or names: ${err instanceof Error ? err.message : String(err)}`, ); } - const file = item.path; + // A symbol file has a path, a path map rule a source; path map rules take context IDs only. + const label = typeof item.path === "string" ? item.path : item.source; const scope = await pickContexts({ - title: typeof file === "string" && file ? `Contexts for ${file}` : "Contexts", + title: typeof label === "string" && label ? `Contexts for ${label}` : "Contexts", contexts, scope: readContextScope(item), - placeholder: "Check the contexts, or check none for all contexts", + placeholder: "Check the contexts", allowTyped: true, + idsOnly: itemPath[0] === "pathMap", }); if (scope === undefined) { return; diff --git a/src/launchSettings/launchJson.ts b/src/launchSettings/launchJson.ts index 4f48ed8..5298618 100644 --- a/src/launchSettings/launchJson.ts +++ b/src/launchSettings/launchJson.ts @@ -99,6 +99,7 @@ export function setPathMapRules( rules: readonly { source: string; destination: string; + contexts?: string[]; context?: string; contextQuery?: string; }[], diff --git a/src/launchSettings/schema.ts b/src/launchSettings/schema.ts index 9ab66ea..f0c4a25 100644 --- a/src/launchSettings/schema.ts +++ b/src/launchSettings/schema.ts @@ -321,7 +321,8 @@ export function readContextScope(item: unknown): ContextScope { /** * The list item with its scope attributes replaced by `scope`, where the - * first of them was, else after "path". All contexts leaves them out. + * first of them was, else after "path", else last. All contexts leaves them + * out. */ export function withContextScope(item: Record, scope: ContextScope): Record { const attributes: Record = @@ -332,7 +333,7 @@ export function withContextScope(item: Record, scope: ContextSc : {}; const keys = Object.keys(item); const after = keys.find((k) => CONTEXT_SCOPE_KEYS.includes(k)) ?? (keys.includes("path") ? "path" : undefined); - const result: Record = after === undefined ? { ...attributes } : {}; + const result: Record = {}; for (const [key, value] of Object.entries(item)) { if (!CONTEXT_SCOPE_KEYS.includes(key)) { result[key] = value; @@ -341,7 +342,7 @@ export function withContextScope(item: Record, scope: ContextSc Object.assign(result, attributes); } } - return result; + return after === undefined ? { ...result, ...attributes } : result; } interface DebuggerContribution { diff --git a/src/locateSource.ts b/src/locateSource.ts index 97837cd..e2b51ae 100644 --- a/src/locateSource.ts +++ b/src/locateSource.ts @@ -3,8 +3,9 @@ import * as path from "path"; import * as vscode from "vscode"; import { setPathMapRules } from "./launchSettings/launchJson"; import { applyAndSave } from "./launchSettings/editorProvider"; -import { PathMapRule, deriveRule, pathMapContextQuery } from "./pathMapper"; -import { promptPathMapScope } from "./pathMapScope"; +import { describeContextScope } from "./contextChoices"; +import { PathMapRule, deriveRule } from "./pathMapper"; +import { pathMapRuleScope, promptPathMapScope } from "./pathMapScope"; /** A source file of a stack frame that is not on this host. */ export interface MissingSource { @@ -85,7 +86,7 @@ export class SourceLocator { if (!picked?.[0]) { return; } - const scope = await promptPathMapScope({}, missing.contextId); + const scope = await promptPathMapScope(session, {}, missing.contextId); if (scope === undefined) { return; } @@ -114,7 +115,7 @@ export class SourceLocator { const message = `Added the path map rule ${rule.source} → ` + `${rule.destination} for this session ` + - `(${pathMapContextQuery(rule) ?? "all contexts"}).`; + `(${describeContextScope(pathMapRuleScope(rule))}).`; if (!launchJson || !fs.existsSync(launchJson.fsPath)) { void vscode.window.showInformationMessage(message); return; diff --git a/src/pathMapScope.ts b/src/pathMapScope.ts index f3e7d19..ba226eb 100644 --- a/src/pathMapScope.ts +++ b/src/pathMapScope.ts @@ -1,50 +1,58 @@ import * as vscode from "vscode"; -import { PathMapRule, pathMapContextQuery } from "./pathMapper"; +import { ContextScope, TargetContext } from "./contextChoices"; +import { listContexts, pickContexts } from "./contextPicker"; +import { PathMapRule } from "./pathMapper"; -type Scope = Pick; +type Scope = Pick; -/** Shared by the Path Map view and Locate Source File. */ -export async function promptPathMapScope(current: Scope = {}, contextId?: string): Promise { - const modes = [ - { - label: "All contexts", - description: "Default: no context filter", - mode: "all", - }, - { - label: "Context ID", - description: "One exact context ID", - mode: "id", - }, - { - label: "Context query", - description: "A TCF ContextQuery expression", - mode: "query", - }, - ]; - const mode = await vscode.window.showQuickPick(modes, { - title: "Path Map Scope", - placeHolder: `Current: ${pathMapContextQuery(current) ?? "all contexts"}`, - ignoreFocusOut: true, - }); - if (!mode) { - return undefined; +/** The scope of a rule, also of one with the old single "context". */ +export function pathMapRuleScope(rule: Pick): ContextScope { + if (rule.contextQuery) { + return { contextQuery: rule.contextQuery }; + } + return { contexts: rule.contexts ?? (rule.context ? [rule.context] : []) }; +} + +/** + * Asks which contexts a path map rule applies to, with the context picker of + * breakpoints and symbol files. `contextId` is offered first, for example the + * context of a missing source file; else the selected call-stack context. + * Shared by the Path Map view and Locate Source File. + */ +export async function promptPathMapScope( + session: vscode.DebugSession, + current: Pick = {}, + contextId?: string, +): Promise { + let contexts: TargetContext[] = []; + try { + contexts = await listContexts(session); + } catch (err) { + void vscode.window.showWarningMessage( + `Could not list TCF contexts, type their IDs: ${err instanceof Error ? err.message : String(err)}`, + ); } - if (mode.mode === "all") { - return {}; + const active = vscode.debug.activeStackItem; + const threadId = active?.session.id === session.id ? active.threadId : undefined; + const selectedId = + contextId ?? contexts.find((context) => threadId !== undefined && context.threadId === threadId)?.id; + if (selectedId !== undefined && !contexts.some((context) => context.id === selectedId)) { + contexts = [{ id: selectedId, name: selectedId }, ...contexts]; } - const value = await vscode.window.showInputBox({ - title: mode.mode === "id" ? "Context ID" : "Context Query", - prompt: - mode.mode === "id" - ? "Exact TCF context ID (sent as ContextQuery: ID=)" - : "TCF query, for example **/HasState=true", - value: mode.mode === "id" ? (current.context ?? contextId ?? "") : (current.contextQuery ?? ""), - ignoreFocusOut: true, - validateInput: (text) => (text.trim().length ? undefined : "Enter a non-empty scope."), + const scope = await pickContexts({ + title: "Path Map Contexts", + contexts, + scope: pathMapRuleScope(current), + selectedId, + placeholder: "Check the contexts the rule applies to", + allowTyped: true, + idsOnly: true, }); - if (value === undefined) { + if (scope === undefined) { return undefined; } - return mode.mode === "id" ? { context: value } : { contextQuery: value }; + if ("contextQuery" in scope) { + return { contextQuery: scope.contextQuery }; + } + return scope.contexts.length > 0 ? { contexts: scope.contexts } : {}; } diff --git a/src/pathMapView.ts b/src/pathMapView.ts index bc8d2d6..ea4e41e 100644 --- a/src/pathMapView.ts +++ b/src/pathMapView.ts @@ -2,8 +2,9 @@ import * as path from "path"; import * as vscode from "vscode"; import { activeRootSession } from "./contextSessionManager"; import { savePathMapRules, withWorkspaceFolder } from "./locateSource"; -import { ForeignPathMapRule, PathMapRule, pathMapContextQuery } from "./pathMapper"; -import { promptPathMapScope } from "./pathMapScope"; +import { describeContextScope } from "./contextChoices"; +import { ForeignPathMapRule, PathMapRule } from "./pathMapper"; +import { pathMapRuleScope, promptPathMapScope } from "./pathMapScope"; const VIEW = "simics-target-debug.pathMap"; const DEBUG_TYPE = "simics-target-debug"; @@ -17,7 +18,7 @@ class PathMapItem extends vscode.TreeItem { readonly session: vscode.DebugSession, ) { super(rule.source); - const scope = pathMapContextQuery(rule) ?? "all contexts"; + const scope = describeContextScope(pathMapRuleScope(rule)); this.description = `${rule.destination} (${scope})`; this.tooltip = `${index + 1}. ${rule.source}\n` + `To: ${rule.destination}\nScope: ${scope}`; this.iconPath = new vscode.ThemeIcon("replace-all"); @@ -161,7 +162,7 @@ function checkItem(rules: PathMapRule[], item?: PathMapItem): void { item && (rules[item.index]?.source !== item.rule.source || rules[item.index]?.destination !== item.rule.destination || - pathMapContextQuery(rules[item.index]) !== pathMapContextQuery(item.rule)) + JSON.stringify(pathMapRuleScope(rules[item.index])) !== JSON.stringify(pathMapRuleScope(item.rule))) ) { throw new Error("Path map rules changed. Refresh and retry."); } @@ -201,7 +202,7 @@ async function editRule(session: vscode.DebugSession, item?: PathMapItem): Promi if (destination === undefined) { return; } - const scope = await promptPathMapScope(item?.rule); + const scope = await promptPathMapScope(session, item?.rule); if (scope === undefined) { return; } diff --git a/src/pathMapper.ts b/src/pathMapper.ts index 7a49b6d..bdf0410 100644 --- a/src/pathMapper.ts +++ b/src/pathMapper.ts @@ -10,7 +10,9 @@ export interface PathMapRule { source: string; /** Corresponding path prefix on the host running VS Code. */ destination: string; - /** Exact context ID. Use this or contextQuery, not both. */ + /** Exact context IDs. Use this or contextQuery, not both. */ + contexts?: string[]; + /** One exact context ID, read as `contexts` with one entry. */ context?: string; /** TCF query selecting contexts. Omitted means all contexts. */ contextQuery?: string; @@ -33,13 +35,26 @@ export interface TargetPath { contextId?: string; } -/** The wire representation always uses ContextQuery, including exact IDs. */ -export function pathMapContextQuery(rule: Pick): string | undefined { - if (rule.context) { - const id = /^[A-Za-z_][A-Za-z0-9_]*$/.test(rule.context) ? rule.context : JSON.stringify(rule.context); - return `ID=${id}`; +/** + * The ContextQuery of each agent rule for the rule, empty for all contexts. + * The wire representation always uses ContextQuery, including exact IDs. + * A query cannot select one of several IDs, so a rule with several contexts + * is one agent rule per context. + */ +export function pathMapContextQueries(rule: Pick): string[] { + const contexts = rule.contexts ?? (rule.context ? [rule.context] : []); + if (contexts.length > 0) { + return contexts.map((context) => { + const id = /^[A-Za-z_][A-Za-z0-9_]*$/.test(context) ? context : JSON.stringify(context); + return `ID=${id}`; + }); } - return rule.contextQuery; + return rule.contextQuery ? [rule.contextQuery] : []; +} + +/** True if the queries limit a rule to some contexts. */ +function isScoped(queries: readonly string[]): boolean { + return queries.length > 0 && !queries.some((query) => query === "*" || query === "**"); } /** @@ -109,14 +124,20 @@ export class PathMapper { private async commitRules(rules: PathMapRule[]): Promise { await this.service?.set( - rules.map((rule, i) => ({ - ID: `${this.idPrefix}-${i + 1}`, - Source: rule.source, - Destination: rule.destination, - ...(pathMapContextQuery(rule) && { - ContextQuery: pathMapContextQuery(rule), - }), - })), + rules.flatMap((rule, i) => { + const queries = pathMapContextQueries(rule); + const base = { Source: rule.source, Destination: rule.destination }; + if (queries.length <= 1) { + return [ + { ID: `${this.idPrefix}-${i + 1}`, ...base, ...(queries[0] && { ContextQuery: queries[0] }) }, + ]; + } + return queries.map((query, j) => ({ + ID: `${this.idPrefix}-${i + 1}-${j + 1}`, + ...base, + ContextQuery: query, + })); + }), ); this.rules.splice(0, this.rules.length, ...rules); this.reset(); @@ -133,7 +154,7 @@ export class PathMapper { (r) => r.source === rule.source && r.destination === rule.destination && - pathMapContextQuery(r) === pathMapContextQuery(rule), + JSON.stringify(pathMapContextQueries(r)) === JSON.stringify(pathMapContextQueries(rule)), ); if (!known) { rules.push({ ...rule }); @@ -153,7 +174,7 @@ export class PathMapper { const candidates: string[] = []; for (const r of this.rules) { const p = mapPrefix(compiledPath, r.source, r.destination); - if (p !== undefined && (await this.matches(pathMapContextQuery(r), contextId))) { + if (p !== undefined && (await this.matchesAny(pathMapContextQueries(r), contextId))) { candidates.push(p); } } @@ -195,8 +216,8 @@ export class PathMapper { continue; } const p = mapPrefix(hostPath, r.destination, r.source); - const query = pathMapContextQuery(r); - if (p !== undefined && query && query !== "*" && query !== "**" && !contextId && !this.service) { + const queries = pathMapContextQueries(r); + if (p !== undefined && isScoped(queries) && !contextId && !this.service) { throw new Error( "Scoped breakpoint path mapping needs a context ID " + "or an agent with the PathMap service", ); @@ -206,17 +227,8 @@ export class PathMapper { if (p !== undefined && this.service && !contextId) { return { path: hostPath }; } - if (p !== undefined && (await this.matches(query, contextId))) { - return this.agentMapsPaths - ? { path: hostPath } - : { - path: p, - ...(query && - query !== "*" && - query !== "**" && { - contextId, - }), - }; + if (p !== undefined && (await this.matchesAny(queries, contextId))) { + return this.agentMapsPaths ? { path: hostPath } : { path: p, ...(isScoped(queries) && { contextId }) }; } } for (const r of await this.otherAgentRules()) { @@ -246,6 +258,19 @@ export class PathMapper { this.queryCache.clear(); } + /** True if the rule applies to the context: it has no queries, or one of them matches. */ + private async matchesAny(queries: readonly string[], contextId: string | undefined): Promise { + if (queries.length === 0) { + return true; + } + for (const query of queries) { + if (await this.matches(query, contextId)) { + return true; + } + } + return false; + } + private async matches(query: string | undefined, contextId: string | undefined): Promise { if (!query || query === "*" || query === "**") { return true; @@ -340,8 +365,21 @@ export function parsePathMapConfig(value: unknown): { rules: PathMapRule[]; erro return; } } - if (e?.context !== undefined && e.contextQuery !== undefined) { - errors.push(`pathMap[${i}] is ignored, use "context" or ` + '"contextQuery", not both'); + if ( + e?.contexts !== undefined && + (!Array.isArray(e.contexts) || + !e.contexts.every((c: unknown) => typeof c === "string" && c.trim().length > 0)) + ) { + errors.push(`pathMap[${i}] is ignored, "contexts" must be a list of non-empty strings`); + return; + } + if (e?.context !== undefined && e.contexts !== undefined) { + errors.push(`pathMap[${i}] is ignored, it has both "context" and "contexts"; use "contexts"`); + return; + } + const contexts = [...new Set(e?.contexts ?? (e?.context !== undefined ? [e.context] : []))]; + if (contexts.length > 0 && e?.contextQuery !== undefined) { + errors.push(`pathMap[${i}] is ignored, use "contexts" or ` + '"contextQuery", not both'); return; } if ( @@ -353,7 +391,7 @@ export function parsePathMapConfig(value: unknown): { rules: PathMapRule[]; erro rules.push({ source: e.source, destination: e.destination, - ...(e.context !== undefined && { context: e.context }), + ...(contexts.length > 0 && { contexts }), ...(e.contextQuery !== undefined && { contextQuery: e.contextQuery, }), diff --git a/src/test/pathMapper.test.ts b/src/test/pathMapper.test.ts index bed2419..6588321 100644 --- a/src/test/pathMapper.test.ts +++ b/src/test/pathMapper.test.ts @@ -9,7 +9,7 @@ import { mapPrefix, parsePathMapConfig, pathMapProblems, - pathMapContextQuery, + pathMapContextQueries, } from "@/pathMapper"; import { PathMapRuleProperties, PathMapService } from "@/tcf/services/pathMap"; @@ -449,11 +449,22 @@ test("scope parsing preserves IDs and queries without broadening invalid rules", const base = { source: "/build", destination: "/host" }; const valid = [ base, - { ...base, context: "cpu0" }, + { ...base, contexts: ["cpu0", "cpu1"] }, { ...base, contextQuery: "ID=cpu0" }, { ...base, contextQuery: "/server/**/HasState=true" }, ]; assert.deepEqual(parsePathMapConfig(valid), { rules: valid, errors: [] }); + // The old single "context" is read as a list of one, an empty list as all contexts. + assert.deepEqual( + parsePathMapConfig([ + { ...base, context: "cpu0" }, + { ...base, contexts: [], contextQuery: "*" }, + ]).rules, + [ + { ...base, contexts: ["cpu0"] }, + { ...base, contextQuery: "*" }, + ], + ); for (const scope of [ { context: "" }, { context: " " }, @@ -462,6 +473,10 @@ test("scope parsing preserves IDs and queries without broadening invalid rules", { contextQuery: " " }, { contextQuery: false }, { context: "cpu0", contextQuery: "*" }, + { contexts: ["cpu0"], contextQuery: "*" }, + { context: "cpu0", contexts: ["cpu1"] }, + { contexts: "cpu0" }, + { contexts: ["cpu0", " "] }, ]) { const result = parsePathMapConfig([{ ...base, ...scope }]); assert.deepEqual(result.rules, []); @@ -495,7 +510,36 @@ test("apply and replacement send exact ContextQuery wire properties", async () = } await mapper.replaceRules(mapper.getRules()); assert.deepEqual(fake.sets[1], fake.sets[0]); - assert.equal(pathMapContextQuery({ context: "cpu0" }), "ID=cpu0"); + assert.deepEqual(pathMapContextQueries({ context: "cpu0" }), ["ID=cpu0"]); +}); + +// A query cannot select one of several IDs, so a rule for several contexts +// is one agent rule per context, and maps paths in each of them. +test("a rule with several contexts is one agent rule per context", async () => { + const fake = fakePathMapService([]); + const mapper = new PathMapper( + [ + { source: "/build", destination: "/cpus", contexts: ["cpu0", "cpu1"] }, + { source: "/lib", destination: "/host-lib" }, + ], + fake.service, + ); + await mapper.apply(); + const ids = fake.sets[0].map((r) => String(r.ID).replace(/^vscode-tcf-[^-]+(-[^-]+){4}/, "")); + assert.deepEqual(ids, ["-1-1", "-1-2", "-2"]); + assert.deepEqual( + fake.sets[0].map((r) => [r.Source, r.ContextQuery]), + [ + ["/build", "ID=cpu0"], + ["/build", "ID=cpu1"], + ["/lib", undefined], + ], + ); + const local = new PathMapper([{ source: "/build", destination: "/cpus", contexts: ["cpu0", "cpu1"] }], undefined); + assert.equal(await local.toHost("/build/a.c", "cpu1"), "/cpus/a.c"); + assert.equal(await local.toHost("/build/a.c", "cpu2"), "/build/a.c"); + assert.deepEqual(await local.toTargetLocation("/cpus/a.c", "cpu0"), { path: "/build/a.c", contextId: "cpu0" }); + assert.deepEqual(await local.toTargetLocation("/cpus/a.c", "cpu2"), { path: "/cpus/a.c" }); }); test("identical compiled paths are mapped and cached separately per context", async () => { diff --git a/src/test/schema.test.ts b/src/test/schema.test.ts index 9403ac3..baf943e 100644 --- a/src/test/schema.test.ts +++ b/src/test/schema.test.ts @@ -45,8 +45,7 @@ test("launchFields reads the simics-target-debug attributes from package.json", [ ["source", "string", true, undefined], ["destination", "string", true, "fileOrFolder"], - ["context", "string", undefined, undefined], - ["contextQuery", "string", undefined, undefined], + ["contexts", "contextScope", undefined, undefined], ], ); const symbolFiles = fields.find((f) => f.key === "symbolFiles"); diff --git a/src/test/tcfDebugSession.test.ts b/src/test/tcfDebugSession.test.ts index 85ac5a9..01a2f38 100644 --- a/src/test/tcfDebugSession.test.ts +++ b/src/test/tcfDebugSession.test.ts @@ -91,7 +91,7 @@ test( { source: path.dirname(compiled), destination: path.join(dir, "cpu0"), - context: "cpu0", + contexts: ["cpu0"], }, { source: path.dirname(compiled), diff --git a/src/webview/launchSettings/components/controls.tsx b/src/webview/launchSettings/components/controls.tsx index a2182c4..d26fdef 100644 --- a/src/webview/launchSettings/components/controls.tsx +++ b/src/webview/launchSettings/components/controls.tsx @@ -374,7 +374,7 @@ const CONTEXTS_INPUT: Field = { key: "contexts", label: "Contexts", kind: "string", - default: "IDs or names, separated by commas", + default: "Separated by commas", }; const QUERY_INPUT: Field = { key: "contextQuery", label: "Context Query", kind: "string" };