diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8a1a599 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,288 @@ +# Agent guide + +Notes for AI coding agents (and developers) working on this repository. The +[README](README.md) is the user guide and is shown on the extension's +Marketplace page; keep implementation details here instead. + +## Commands + +Requirements: Node.js (>= 24) and npm. + +```sh +npm ci # install dependencies from package-lock.json +npm run build # type check and bundle the extension into out/ +npm run check # type check and run the unit tests +npm test # bundle and run the unit tests only +npm run test:fuzz # run the fuzzing tests +npm run package # build simics-target-debug-.vsix +npm run watch # rebuild on changes +npm run compile:production # minified bundle without source maps +npx prettier --write +``` + +## Conventions + +- Format every TypeScript file you create or change with Prettier, see + [.github/instructions/typescript.instructions.md](.github/instructions/typescript.instructions.md). +- Unit tests use `node:test` and need no TCF agent. `npm test` only bundles + and runs `src/test/**/*.test.ts`; the root `test/` folder is neither run nor + type checked. Add tests in `src/test/`. +- Options that are the same for all sessions are VS Code settings, not + `launch.json` attributes. `sessionSettings()` in `src/settings.ts` maps them + to `TcfAttachArguments`, and `resolveDebugConfiguration` overwrites + `launch.json` values with them. +- Only standard TCF services and properties are used, so the extension works + with any agent that follows the TCF specification. Simics-only services + (`CommandLine`, `SimUtils`, `SimicsLogs`) are optional and degrade + gracefully. +- Fields of the launch configurations editor come from + `configurationAttributes` in `package.json`; a new attribute needs no form + changes. +- Commit messages: see the `git-commit-message` skill in `.github/skills/`. + Commits need a `Signed-off-by` line, see [CONTRIBUTING.md](CONTRIBUTING.md). +- For TCF protocol details and a CLI to query a live agent, see the `tcf` + skill in `.github/skills/`. + +## Source layout + +- `src/extension.ts` – VS Code entry point, registers the `simics-target-debug` + debug type. +- `src/tcfDebugSession.ts` – DAP implementation (no `vscode` dependency, so it + can also be run as a standalone debug adapter later). +- `src/contextSession.ts` – adapter of the child sessions that show the + threads of a container context; passes requests on to the root session's + adapter. +- `src/contextSessionManager.ts` – starts the child sessions in VS Code and + maps them to their root session for the extension's views and commands. +- `src/breakpointManager.ts` – keeps the agent's breakpoint table in sync with + VS Code. +- `src/variables.ts` – local variables and expressions through the + `Expressions` and `Symbols` services. +- `src/pathMapper.ts` – path mapping between compiled and host paths. +- `src/symbolFiles.ts` – symbol files from the debug configuration, sent to + the agent's memory map. +- `src/settings.ts` – VS Code settings passed to the debug adapter. +- `src/targetMemory/` – Target Memory panels and commands (extension side). +- `src/webview/targetMemory/` – Target Memory UI (React), bundled to + `out/target-memory.{js,css}`. +- `src/shared/targetMemory/` – code shared by the Target Memory extension + side, webview and debug adapter: messages, formatting, search needles and + the memory search. +- `src/tcfRequests.ts` – custom DAP requests used by the Target Memory view. +- `src/simicsConsole.ts` – the Simics console: keys to `CommandLine` key + presses, events to VT text (no `vscode` dependency). +- `src/simicsConsoleManager.ts` – the Simics CLI terminals and their commands. +- `src/consolesView.ts` – the Consoles view. +- `src/snapshots.ts` – Simics snapshots in the adapter, and the custom + requests of the Snapshots view (no `vscode` dependency). +- `src/snapshotsView.ts` – the Snapshots view and its commands. +- `src/launchSettings/` – the launch configurations editor: reading and + editing `launch.json` (`launchJson.ts`), form fields from `package.json` + (`schema.ts`), the custom editor (`editorProvider.ts`) and the form in its + webview (`src/webview/launchSettings/`). +- `src/tcf/channel.ts` – TCF TCP channel: framing, escaping, tokens, events. +- `src/tcf/json.ts` – JSON parsing that keeps 64-bit integers exact (`bigint`). +- `src/tcf/traceSilence.ts` – the `tcfTrace.silence` rules. +- `src/tcf/services/` – typed wrappers for TCF services. +- `src/test/` – unit tests. + +## DAP to TCF mapping + +The extension implements the VS Code Debug Adapter Protocol (DAP) in-process +and translates DAP requests to TCF commands: + +| VS Code (DAP) | TCF | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| attach | TCP connection + `Locator.Hello` | +| threads | `RunControl` contexts with `HasState`, grouped in a session per container context | +| pause / continue | `RunControl.suspend` / `RunControl.resume` | +| step over / into / out | `RunControl.resume` with a step mode | +| stopped / continued | `contextSuspended`, `containerSuspended`, `contextResumed`, `containerResumed` events | +| call stack | `StackTrace.getChildrenRange` / `getChildren` / `getContext` | +| Locals scope | `Expressions.getChildren` of the selected frame | +| watch / hover / Debug Console | `Expressions.create` / `evaluate` in the selected frame | +| Registers scope | `Registers.getChildren` / `getContext` / `get` for the selected frame, hierarchical | +| disassembly | `Disassembly.disassemble` in the frame's context | +| breakpoints | `Breakpoints.add` / `change` / `remove`, `status` events | +| Target Memory (custom) | `Memory.get` / `set` / `getChildren` / `getContext`, `memoryChanged` events, search in the adapter | +| Snapshots view (custom) | Simics `SimUtils.getSnapshotIDs` / `takeSnapshot` / `restoreSnapshot` / `deleteSnapshot`, `snapshotsChanged` events | +| Simics console | Simics `CommandLine` service over the debug session's connection | + +Register contexts without a readable value (for example Simics register +groups) are shown as expandable groups. Registers with fields can be expanded +to show the fields. + +### Variables and expressions + +Variables work like in the Eclipse TCF client; the agent does all parsing and +evaluation. + +- The Locals scope lists what `Expressions.getChildren()` returns. +- Values are evaluated with `Expressions.evaluate` and formatted using the + value's type class and the type from the `Symbols` service. +- Children are new expressions built from the parent expression and member + symbol IDs, for example `(parent).${}`, `(parent)[3]` and + `*(parent)`; pointers to structs expand directly to the members. Arrays with + more than 100 elements are paged. +- "Add to Watch" and "Copy as Expression" use a readable expression such as + `s->corners[2].x`. + +### Call stack + +- Threads are grouped into a child debug session per container context + (`src/contextSession.ts`, `src/contextSessionManager.ts`). All sessions + share the root session's adapter, breakpoints and Debug Console. +- Frames come from `StackTrace.getChildrenRange` in pages; agents without it + fall back to `getChildren`. Without `StackTrace`, or if it fails, a single + frame for the PC is shown. +- Function and line come from the frame's `FuncID` and `CodeArea` when + reported (inlined frames), otherwise from `Symbols.findByAddr` and + `LineNumbers.mapToSource`. Caller frames use the address before the return + address, so they show the line of the call. +- A last frame with IP 0, where the agent stopped unwinding, is left out. + +### Disassembly + +- Frame references keep their TCF context so several CPUs can be inspected. + Plain address references use the first suspended thread. +- On variable-length instruction sets (x86) decoding is kept in step with + addresses known to start an instruction: PCs where a context stopped (the + most recent 4096 per context, dropped when the memory map changes) and line + starts from `LineNumbers`. Decoding starts at such an address shortly before + the range when there is one, and restarts at one when a decoded instruction + runs over it. Otherwise, start addresses up to 15 bytes later are tried + until decoding lands on the next known address. +- The agent decodes from the start of the function (or line area) containing + the address and stops at its end, so the adapter keeps requesting from where + each reply ended. Instructions before an address that cannot be decoded up + to it (unreadable memory) are returned with address `-1`, which VS Code + skips, so it keeps the instructions it already shows. +- Replies are cached per context and kept when stepping. After a resume or a + memory write, cached replies are only reused once a single `Memory.get` + shows that their opcode bytes are unchanged; a memory map change clears the + cache. +- Function header rows use VS Code's source line support. The documents come + from a file system (scheme `simics-target-debug-function`) because VS Code + fails to re-render rows whose document comes from a content provider. A + function is looked up once (`Symbols.findByAddr` and `getContext`); results + are kept until the memory map changes. Code without symbols needs a lookup + per instruction, so at most 64 lookups are made per request, nearest the + requested address first. Inlined functions get no header. + +### Stepping + +Steps are sent to the thread's own run control context: + +| VS Code | TCF resume mode (default) | TCF resume mode (instruction granularity) | +| --------- | ------------------------- | ----------------------------------------- | +| Step Over | `RM_STEP_OVER_LINE` (3) | `RM_STEP_OVER` (1) | +| Step Into | `RM_STEP_INTO_LINE` (4) | `RM_STEP_INTO` (2) | +| Step Out | `RM_STEP_OUT` (5) | `RM_STEP_OUT` (5) | + +If the context does not support line stepping (its `CanResume` bit is not +set), instruction stepping is used. The Simics agent itself falls back to +instruction stepping when there is no line information for the PC. A line +with several code addresses gets a line breakpoint at each, so a step can stop +on the same line with reason "breakpoint". + +### Breakpoints + +| VS Code | TCF breakpoint properties | +| ---------------------- | ----------------------------------------------------------------- | +| Source line breakpoint | `File` (path as in VS Code), `Line`, `Column` | +| Function breakpoint | `Location` = the function name (any expression the agent accepts) | +| Data breakpoint | `Location` = address, `Size`, `AccessMode` read/write | +| Instruction breakpoint | `Location` = address, `ContextIds` = the process and its threads | +| Scoped function bp | `ContextIds` (` @ ` suffix) or `ContextQuery` (` @? ` suffix) | +| Condition | `Condition`, evaluated by the agent | +| Hit count `N` / `>= N` | `IgnoreCount` = N - 1 | +| Logpoint | a normal breakpoint; the adapter prints and resumes | + +- A breakpoint is verified when the agent's status reports at least one + planted instance; the line is moved to where it was planted. +- The reference agent's non-standard `SkipPrologue` is not used. +- The ` @ ` suffix holds exact TCF context IDs, saved with the breakpoint, so + IDs containing commas cannot be used. Scoped breakpoints are never planted + globally when the agent lacks `ContextIds` / `ContextQuery` support. +- Editing a breakpoint's contexts replaces it with a new one with the same + enabled state, condition, hit count and log message. VS Code does not tell + extensions which breakpoint is selected in the Breakpoints panel, so the + command asks when there is more than one. +- Instruction breakpoints are limited to the frame's `ProcessID`. With OS + awareness the Simics agent plants breakpoints per thread (a process has no + breakpoint group), while the reference agent plants them in the process, so + `ContextIds` lists the process and all its threads and is updated with + `Breakpoints.change` as threads come and go. Agents without `ContextIds` + get the breakpoint in all contexts. + +### Target Memory + +- The webview talks to the extension, which uses custom DAP requests + (`src/tcfRequests.ts`) to reach the agent through the debug adapter. +- Physical memory contexts are Memory contexts with the `physical` access + type, for example a Simics memory space. +- Search runs in the adapter (`tcfFindMemory`): 64 KiB chunks with several + reads in flight, progress through `tcfFindMemoryProgress` events, MMIO not + read (`BlockMemoryMappedIO`). +- Ctrl+G and Ctrl+F are keybindings of the view + (`simics-target-debug.targetMemory.goto` / `.find`). + +### Symbol files + +Works like "Load symbols" in the Eclipse TCF client: + +- Each file becomes a memory map region sent with `MemoryMap.set` when + attaching, for each listed context, or for all contexts (`""`) with a + `ContextQuery`. `MemoryMap.set` takes a single context, so a file with + several contexts is set in each one's map. +- The region has `FileName`, plus `BaseAddress` for an offset (as Simics + `add-symbol-file -relative` uses) or `Addr` for an absolute load address. + The agent removes the regions when the session ends. +- File names in the memory map are translated with the path map rules. +- The session's own regions are recognized by their `ID`, unique per session. + Regions from elsewhere are read with `MemoryMap.get` for the `ProcessID` of + each core or thread. +- The context picker lists `ContextQuery.query("HasState=true")`, or stateful + RunControl contexts without that service. +- Saving rewrites `symbolFiles` of the uniquely named configuration in + `.vscode/launch.json`, keeping other properties and comments. + +### Path mapping + +Works like the path map in the Eclipse TCF client: + +- On attach the rules are sent with `PathMap.set`; the agent matches host + breakpoint paths against compiled paths. +- Agent-reported paths are mapped to host paths by the extension: configured + rules first, then rules from `PathMap.get`. The first mapped file that + exists on the host wins. +- The agent only uses the client's own rules for breakpoints, so rules from + elsewhere are applied in reverse by the extension. Without the `PathMap` + service the configured rules are applied in reverse as well. +- Scopes use the `ContextQuery` property of `PathMap.set`: + `contexts: ["cpu0"]` is sent as `ContextQuery: "ID=cpu0"`. A query cannot select one + of several IDs, so a rule with several contexts becomes one agent rule per + context. IDs with punctuation are quoted and escaped. +- Lookups and caches are per context. General queries are evaluated by the + agent's `ContextQuery` service; exact `ID=...` filters work without it. + Unscoped breakpoint requests leave scoped rules to the agent. Without + `PathMap`, scoped reverse mapping requires a context-bearing source and + breakpoint `ContextIds` support; an unsafe global mapping is rejected. + +### TCF trace + +`tcfTrace.silence` rules are `service/type/name`. Types are `command` (a +command C and its results R, P and N, matched by token, with the command's +service and name), `event` (E) and `flowControl` (F). Flow control messages +have no service or name, so only `*/flowControl` silences them. + +## Known limitations + +- No exception breakpoints. +- Breakpoints created by other TCF clients (or the Simics CLI) are not shown. +- Variables and registers are read-only, there is no "Set Value". +- `char *` and `char[]` are not shown as strings. +- No "Restart Frame". +- Path map rules from the agent are read when attaching; rules added in + Simics while attached apply to new breakpoints only. +- Only TCP transport. diff --git a/README.md b/README.md index 2a7e950..a9420ae 100644 --- a/README.md +++ b/README.md @@ -12,454 +12,31 @@ -A VS Code debugger extension that connects to a -[TCF](https://download.eclipse.org/tools/tcf/tcf-docs/) agent, for example the -Simics TCF agent. It only uses standard TCF services (`Locator`, `RunControl`, -`Registers`, `LineNumbers`, `Symbols`, `StackTrace`, `Breakpoints`, -`Expressions`, `Memory`), so it should work with any agent that follows the TCF -pspecification. - -The extension implements the VS Code Debug Adapter Protocol (DAP) in-process -and translates DAP requests to TCF commands: - -| VS Code (DAP) | TCF | -|--------------------------|------------------------------------------------------------| -| attach | TCP connection + `Locator.Hello` | -| threads | `RunControl` contexts with `HasState`, grouped in a session per container context, see below | -| pause / continue | `RunControl.suspend` / `RunControl.resume` | -| step over / into / out | `RunControl.resume` with a step mode, see below | -| stopped / continued | `contextSuspended`, `containerSuspended`, `contextResumed`, `containerResumed` events | -| call stack | `StackTrace.getChildrenRange` / `getChildren` / `getContext`, see below | -| Locals scope | `Expressions.getChildren` of the selected frame, see below | -| watch / hover / Debug Console | `Expressions.create` / `evaluate` in the selected frame | -| Registers scope | `Registers.getChildren` / `getContext` / `get` for the selected frame, hierarchical | -| disassembly | `Disassembly.disassemble` in the frame's context | -| breakpoints | `Breakpoints.add` / `change` / `remove`, `status` events, see below | -| Target Memory (custom requests) | `Memory.get` / `set` / `getChildren` / `getContext`, `memoryChanged` events, search in the adapter, see below | -| Snapshots view (custom requests) | Simics `SimUtils.getSnapshotIDs` / `takeSnapshot` / `restoreSnapshot` / `deleteSnapshot`, `snapshotsChanged` events, see below | - -Register contexts without a readable value (for example Simics register groups) -are shown as expandable groups. Registers with fields can be expanded to show -the fields. - -### Variables and expressions - -Variables work like in the Eclipse TCF client; the agent does all parsing and -evaluation: - -- The Locals scope lists what `Expressions.getChildren()` returns: - local variables and arguments of the frame. -- Values are evaluated by the agent (`Expressions.evaluate`) and formatted - using the value's type class and the type from the `Symbols` service: - integers, characters, booleans, enumerators (by name), floating point and - pointers. Structs, unions and arrays are summarized as `{...}` and `[N]`. -- Structs, unions, arrays and non-null pointers can be expanded. The children - are new expressions built from the parent expression and member symbol IDs, - for example `(parent).${}`, `(parent)[3]` and - `*(parent)`; pointers to structs expand directly to the members. Arrays with - more than 100 elements are shown in pages. -- Watch expressions, hovers and expressions typed in the Debug Console are - evaluated in the selected frame. "Add to Watch" and "Copy as Expression" use - a readable expression such as `s->corners[2].x`. - -Values are read when the thread is suspended and are refreshed after each -resume or step. - -### Call stack - -The Call Stack view shows the parts of the target that can run and be -stopped: processors and, with OS awareness, the processes and threads of the -operating system. They are shown as a tree that follows the structure of the -target. Parts with several threads, such as a board with several CPUs, an OS -awareness tracker or a multi-threaded process, are shown as groups that can -be expanded. Expand a thread to see its call stack. - -To keep the tree short: - -- Only parts with at least two threads get a group. A part with a single - thread, such as most Linux processes, gets no group: its thread is listed - in the group above. -- A thread listed in a group above is named by the parts in between, so - thread `worker` of process `p3` is listed as `p3.worker`. A repeated name, - such as process `init` with thread `init`, is shown once. -- If a group would hold only one thread next to other groups, that thread - gets a row of its own, with its call stack right below it. - -In a group, the threads are listed first, then the single threads with rows -of their own, then the other groups, each in the order of the target. - -For example, take this target with a Linux OS awareness tracker, with -simplified names: - -```text -Linux -├── Kernel -│ ├── Other ── core[0][0] -│ ├── Idle ──┬── core[0][0] -│ │ └── core[1][0] -│ └── Threads ──┬── kthreadd -│ └── kworker/0:0 -└── Userspace ──┬── init ── init - ├── rc ── rc - └── udevd ── udevd -``` - -The Call Stack view shows it like this: - -```text -Linux group, in the row of the debug configuration -├── Kernel group -│ ├── Other.core[0][0] single thread with a row of its own -│ ├── Idle group -│ │ ├── core[0][0] thread -│ │ └── core[1][0] thread -│ └── Threads group -│ ├── kthreadd thread -│ └── kworker/0:0 thread -└── Userspace group - ├── init thread - ├── rc thread - └── udevd thread -``` - -`Other` and the processes in `Userspace` have a single thread each, so they -get no group. The thread of `Other` is next to the groups `Idle` and -`Threads`, so it gets a row of its own. - -Groups come and go as processes and threads start and end. All groups share -the breakpoints and the Debug Console. Stopping or restarting any of them -stops or restarts the whole debug session. - -Two [settings](#settings) change the layout: - -- Turning off `simics-target-debug.callStack.hierarchy` shows no groups. All - threads are listed directly under the debug configuration, named by all the - parts above them, like `board.cpu0`. In the example, the threads are named - `Linux.Kernel.Idle.core[0][0]`, `Linux.Userspace.init.init` and so on. -- Turning off `simics-target-debug.callStack.compact` gives every group a row - of its own. By default, a group that is alone in its parent shares the - parent's row and shows its own name only, like `Linux` in the example. When - off, the name of the debug configuration gets a row of its own above `Linux`. - -The call stack of a suspended thread comes from the `StackTrace` service. VS -Code first loads the top frame and then the rest in pages ("Load More Stack -Frames"), which uses `getChildrenRange`; agents without it fall back to -`getChildren`. - -For each frame the function name and source line are taken from the frame's -`FuncID` and `CodeArea` when the agent reports them (inlined frames), otherwise -they are looked up with `Symbols.findByAddr` and `LineNumbers.mapToSource`. For -caller frames the address before the return address is used, so the frame -shows the line of the call. Frames without source are shown dimmed, and frames -without a known function show the address instead. To get the address of any -frame (the PC, or the return address for caller frames), right-click it and -select **Copy Address**. A last frame without return address (IP 0), where the -agent stopped unwinding, is left out. - -Selecting a frame shows the local variables and registers of that frame, as -unwound by the agent. -Without the `StackTrace` service, or if it fails, a single frame for the PC is -shown. - -### Disassembly - -When the agent offers the `Disassembly` service, open a stack frame's context -menu and select **Open Disassembly View**. The view shows decoded instructions -and opcode bytes when the agent provides them. It works without source files; -the frame's reference keeps its TCF context so multiple CPUs can be inspected. -Plain address references use the first suspended thread. - -The service decodes a byte range, so on instruction sets with variable length -(x86) the instructions before an address have to be found by decoding from -an earlier address, which can get out of step with the real instructions. -The adapter keeps decoding in step with addresses known to start an -instruction: PCs where a context stopped (the most recent 4096 per context, -dropped when the memory map changes) and line starts from the -`LineNumbers` service. Decoding starts at such an address shortly before the -range when there is one, and restarts at one when a decoded instruction runs -over it. Otherwise, start addresses up to 15 bytes later are tried until -decoding lands on the next known address. - -The agent decodes from the start of the function (or line area) containing -the requested address and stops at its end, so the adapter keeps requesting -from where each reply ended until the range is covered. When the instructions -before an address cannot be decoded up to it (unreadable memory), they are -returned with address `-1`, which VS Code skips, so instructions it already -shows there are kept instead of being replaced by `??`. - -Some agents take long per request (slow symbol lookup in large modules), so -replies are cached per context. Code rarely changes, so the cache is kept when -stepping. After a resume or a memory write, cached replies are only used once a -single `Memory.get` shows that their opcode bytes are unchanged; a memory map -change clears the cache. - -Function entries get a header row, like `objdump`, when the agent offers the -`Symbols` service. VS Code shows it through its source line support, which -puts the line number first: `22: dummy-prog1.c: ` gives the source -line and file of the entry (from `LineNumbers`), or `1: ` without -line information. It needs `debug.disassemblyView.showSourceCode` (default on); -double-clicking it opens a read-only document with the header on that line. The -documents come from a file system (scheme `simics-target-debug-function`) -because VS Code fails to re-render rows whose document comes from a content -provider. Inlined functions get no header. A function is looked up once -(`Symbols.findByAddr` and `getContext`) and covers all its instructions; -results are kept until the memory map changes. Code without symbols needs a -lookup per instruction, so at most 64 lookups are made per request, nearest the -requested address first. Turn them off with the setting -`simics-target-debug.disassembly.functionHeaders`. - -### Stepping - -Steps are sent to the thread's own run control context: - -| VS Code | TCF resume mode (default) | TCF resume mode (instruction granularity) | -|--------------|----------------------------|-------------------------------------------| -| Step Over | `RM_STEP_OVER_LINE` (3) | `RM_STEP_OVER` (1) | -| Step Into | `RM_STEP_INTO_LINE` (4) | `RM_STEP_INTO` (2) | -| Step Out | `RM_STEP_OUT` (5) | `RM_STEP_OUT` (5) | - -Line stepping requires that the agent knows the symbol files for the target, -for example loaded with `add-symbol-file` in Simics or with `symbolFiles` in -the debug configuration. If the context does not -support line stepping (its `CanResume` bit set) instruction stepping is used -instead. The Simics agent itself falls back to instruction stepping when there -is no line information for the current PC. - -A line step only completes when execution reaches another line, so stepping -over a line that loops forever keeps the target running until it is paused. - -A line can have several code addresses (for example several line table rows -for one statement), and the agent plants a line breakpoint at all of them. A -step from the first address then stops at the next one on the same line with -reason "breakpoint"; step again to continue. - -### Breakpoints - -Breakpoints are kept in sync with the agent's breakpoint table: adding, -editing and removing breakpoints in VS Code sends `Breakpoints.add`, `change` -and `remove`. Breakpoints apply to all contexts the agent debugs, except -explicitly scoped function breakpoints and instruction breakpoints, see below. - -| VS Code | TCF breakpoint properties | -|---------------------------------|----------------------------------------------------| -| Source line breakpoint | `File` (path as in VS Code), `Line`, `Column` | -| Function breakpoint | `Location` = the function name (any expression the agent accepts) | -| Data breakpoint (Breakpoints view: "Add Data Breakpoint at Address") | `Location` = address, `Size`, `AccessMode` read/write | -| Instruction breakpoint (click left of an instruction in the Disassembly view) | `Location` = address, `ContextIds` = the process and its threads | -| Condition | `Condition`, evaluated by the agent | -| Hit count `N` or `>= N` | `IgnoreCount` = N - 1 (break from the N:th hit) | -| Logpoint | a normal breakpoint, see below | - -A breakpoint is shown as verified when the agent reports at least one planted -instance in its status. The line is moved to where the agent planted it, for -example from a line without code to the next line with code. Errors from the -agent (unknown file, line without code, invalid expression) are shown on the -breakpoint. - -Logpoints are planted as breakpoints. When one is hit, the adapter prints the -message to the Debug Console, with `{expression}` evaluated by the agent's -`Expressions` service, and resumes the target. A step that is interrupted by -a logpoint stops there. - -Function breakpoints stop at the first instruction of the function. The -reference TCF agent also supports a non-standard `SkipPrologue` property which -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 -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 -several cores are checked. The ` @ ` suffix is reserved for the exact TCF -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...**. -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 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 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 -view (its `ProcessID`). `ContextIds` lists the process and all its threads: -with OS awareness the Simics agent plants breakpoints per thread (a process -has no breakpoint group), while the reference agent plants them in the -process. The list is updated with `Breakpoints.change` when threads are -created or exit. Without OS awareness the process of a CPU context is the CPU -itself. Agents that do not support `ContextIds` get the breakpoint in all -contexts. - -### Target Memory - -**Simics Target Debug: Open Target Memory** (also in the debug toolbar) opens a -hex view of target memory. **Open in Target Memory** in the Variables view -context menu shows what a pointer points to, or where any other variable is -stored, with the variable's bytes selected. **New Target Memory View** (in the -editor title bar of the view) opens another one. Unreadable bytes are shown as -`??`. The webview talks to the extension, which uses custom DAP requests -(`src/tcfRequests.ts`) to access the agent's memory through the debug adapter. - -- The view shows the memory of the focused thread, or of a physical memory - context (a Memory context with the `physical` access type, for example a - Simics memory space) selected in the drop-down list. Physical memory - contexts have full names like the threads in the call stack, for example - `board.mb.phys_mem`. -- Enter an address (`0x1000`, or decimal) or an expression (`&buffer`, - `$sp`) evaluated in the selected frame, and press Enter to go there. Ctrl+G - moves to the address box. Ctrl+G and Ctrl+F are keybindings of the view - (`simics-target-debug.targetMemory.goto` / `.find`), active while it is the - active editor, so they replace VS Code's Go to Line and Find there. Scroll - anywhere in the address space. -- Memory is read again automatically when the target stops, when another - thread gets the focus and when the agent reports `Memory.memoryChanged`. - Bytes that changed are shown in red. The refresh button reads memory again - on demand. While the target runs, thread memory is dimmed and cannot be - changed; physical memory can still be read. -- Group 1, 2, 4 or 8 bytes. Groups are shown as numbers in little (default) - or big endian. The number of bytes per row is fixed or fits the width. -- Edit memory by typing hex digits over the groups, or text in the text - column. Click a digit, or move with Left/Right, to put the caret on it; - typing replaces just that digit. Up/Down keep the digit, Ctrl+Left/Right - move by group and Shift+arrows select. Changed bytes are shown underlined - until written: an Apply/Discard bar appears (Enter/Escape). Backspace moves - back one digit and restores its original value. -- Ctrl+F finds hex numbers (in the selected byte order, so `12345678` in - little endian is the bytes `78 56 34 12`; single bytes such as `de ad be ef` - are a byte sequence), ASCII text, or an 8 to 64-bit integer. The search can - be limited to aligned addresses, for example to find an 8-byte integer only - at multiples of 8, and to a range (by default the low 1 TiB). Enter and - Shift+Enter search forward and backward from the selection and wrap around - in the range. The buttons next to the range fields set it to start or end at - the cursor; a hint offers that when the cursor is outside the range. -- The search runs in the debug adapter (`tcfFindMemory`), which reads 64 KiB - chunks with several reads in flight and reports progress with - `tcfFindMemoryProgress` events; MMIO is not read (`BlockMemoryMappedIO`). -- The data inspector shows the bytes at the cursor as integers and floating - point numbers. Right-click for copy (hex, text or address) commands; they - act on the right-clicked entry, or on the selection if it is in it. - -### Simics console - -When the agent has the Simics `CommandLine` service, the Simics command line -opens in a terminal named **Simics CLI** after attaching. Its options are the -`simics-target-debug.console.*` [settings](#settings): - -- `open`: open the console after attaching. When off, open it from the - Consoles view. When on, the Debug Console does not open at start. -- Simics does all line editing, history and tab completion. -- The console uses the debug session's connection. When the session ends, - it stays open, read-only and grayed out. -- The **Consoles** view in the Run and Debug side bar lists the console of - each agent and its state. Click it to show it, or to connect it when it - is not open or disconnected. -- The next session with the same agent shows the output of earlier - sessions above the command line, also after a window reload. - `historySessions` sets how many; 0 turns it off. **Clear History** in the - Consoles view deletes them. -- Ctrl+C copies the selection and stops the simulation. Ctrl+D is not sent. -- `editingKeys` sends Ctrl+E, F, G, K, P, R, W (and Ctrl+_ on Windows) to - Simics instead of VS Code while the console has focus. The lock button in - the Consoles view switches it, in the workspace settings if they set it, - else in the user settings. -- To keep the focus in the console when the target stops, so that Enter - repeats for example `step-line`, turn off the VS Code setting - `debug.focusEditorOnBreak`. -- Simics log messages are shown in the console. The console's TCF traffic is - left out of the [TCF trace](#tcf-trace) unless the silence list is changed. - -### Snapshots - -The **Snapshots** view in the Run and Debug side bar lists the Simics -in-memory snapshots of the active session's agent, through the snapshot -commands of the Simics `SimUtils` service. - -- **Take Snapshot** (camera button) names the snapshot like the Simics - `take-snapshot` command does: `snapshot`, `snapshot1`, `snapshot2`, ... -- **Take Named Snapshot...** (tag button) asks for the name. -- The buttons on a snapshot restore or delete it. Deleting asks first. -- **Delete All Snapshots...** (clear-all button, shown when there are - snapshots) deletes every snapshot of the agent, after asking. -- The commands are also in the Command Palette; there, restore and delete - ask which snapshot. -- The list follows snapshots taken or deleted elsewhere, for example in - the Simics CLI. -- Without the `SimUtils` service or its snapshot commands, such as with - other TCF agents or older Simics versions, the view says that snapshots - are not available and the take buttons are disabled. - -## Building - -Requirements: Node.js (>= 20) and npm. - -```sh -npm ci # install dependencies from package-lock.json -npm run build # type check and bundle the extension into out/ -npm run check # type check and run the unit tests -npm run package # build and package simics-target-debug-.vsix -``` - -Use `npm run watch` while developing, or `npm run compile:production` for a -minified bundle without source maps. `npm run package` builds a production-ready -`.vsix` file. +Debug software running in Simics, or on any other +[TCF](https://download.eclipse.org/tools/tcf/tcf-docs/) agent, from VS Code. +The extension uses only standard TCF services, so Simics-specific features +(the Simics CLI and snapshots) are simply unavailable on other agents. ## Installation -Clone the repository, then run these commands from its root directory: - +Build the `.vsix` by running ```sh npm ci npm run package ``` +Then in VS Code run +**Extensions: Install from VSIX...** and select the generated file. -Install the generated `.vsix` file in VS Code: +## Getting started -1. Press Ctrl + Shift + P to open the Command Palette. -2. Run `Extensions: Install from VSIX...`. -3. Select the generated `.vsix` file. - -## Running - -1. Start a TCF agent, for example in Simics: +1. Start a TCF agent in Simics. It listens on port 1534 by default: ``` simics> new-tcf-agent ``` - This listens on TCP port 1534 by default. Use - `new-tcf-agent parameters = "TCP::"` to select another port. - -2. Open this folder in VS Code and press F5 ("Run Extension"). This builds the - extension, watches for changes, and starts an Extension Development Host. - Alternatively install the `.vsix` with "Extensions: Install from VSIX...". - -3. In the Extension Development Host, start debugging with a launch - configuration like: +2. In VS Code, start debugging and select **Simics Target Debug**. Without a + `launch.json` this attaches to `localhost:1534`. To configure it, add: ```json { @@ -471,370 +48,155 @@ Install the generated `.vsix` file in VS Code: } ``` - Without a `launch.json`, selecting the "Simics Target Debug" debugger - attaches to `localhost:1534`. - -Configuration attributes: - -| Attribute | Default | Description | -|------------------|-------------|------------------------------------------------------| -| `host` | `localhost` | Host of the TCF agent | -| `port` | `1534` | TCP port of the TCF agent | -| `connectTimeout` | `10000` | Milliseconds to wait for the agent's `Locator.Hello` | -| `pathMap` | `[]` | Source path mapping rules, see below | -| `symbolFiles` | `[]` | Symbol files to load, see below | +**Simics Target Debug: Edit Launch Configurations** edits these +configurations in a form instead of JSON. + +## Features + +- **Call stack** – processors, and with OS awareness processes and threads, + shown as a tree. Expand a thread to see its stack. Right-click a frame for + **Copy Address**. +- **Stepping** – step over, into and out by source line, or by instruction + in the Disassembly view. Line stepping needs symbol files. +- **Breakpoints** – line, function, data, instruction and logpoints, with + conditions and hit counts. Function breakpoints can be limited to some + cores, see below. +- **Variables and watches** – locals, registers, hovers and expressions in + the Debug Console, evaluated by the agent in the selected frame. +- **Disassembly** – right-click a frame and select **Open Disassembly View**. +- **Target Memory** – a hex editor for target memory: **Simics Target Debug: + Open Target Memory**, or **Open in Target Memory** on a variable. Supports + editing, search (Ctrl+F) and go to address (Ctrl+G). +- **Simics CLI** – the Simics command line opens in a terminal after + attaching. The **Consoles** view in Run and Debug reconnects it. +- **Snapshots** – take, restore and delete Simics snapshots from the + **Snapshots** view in Run and Debug. + +### Function breakpoints for some cores + +Run **Simics Target Debug: Add Function Breakpoint in Context...** (also in +the Breakpoints toolbar and a frame's context menu) and choose the cores. +You can also type the scope directly in a function breakpoint: + +- `start_kernel @ board.cpu[0], board.cpu[1]` – the listed context IDs +- `start_kernel @? **/HasState=true` – a TCF context query + +## Configuration + +### Launch configuration + +| Attribute | Default | Description | +| ---------------- | ----------- | ------------------------------------------------- | +| `host` | `localhost` | Host of the TCF agent | +| `port` | `1534` | TCP port of the TCF agent | +| `connectTimeout` | `10000` | Milliseconds to wait for the agent to answer | +| `symbolFiles` | `[]` | Symbol files to load, see [below](#symbol-files) | +| `pathMap` | `[]` | Source path rules, see [below](#path-mapping) | ### Settings -Options that are the same for all debug sessions are VS Code settings, in -the user or workspace settings. +Options shared by all sessions are VS Code settings. **Simics Target Debug: +Open Settings** shows them. -| Setting (`simics-target-debug.` ...) | Default | Description | -|--------------------------------------|-----------|------------------------------------------------------| -| `console.open` | `true` | Open the Simics CLI after attaching, see [Simics console](#simics-console) | -| `console.historySessions` | `3` | Earlier sessions shown above the Simics CLI | -| `console.editingKeys` | `true` | Send editing keys such as Ctrl+P to Simics | -| `callStack.hierarchy` | `true` | A nested session per container context in the Call Stack view | -| `callStack.compact` | `true` | Contexts that are the only child share a row with their parent | -| `disassembly.functionHeaders` | `true` | Function header rows in the Disassembly view | -| `tcfTrace.enabled` | `false` | Log TCF messages to Output › Simics Target Debug | -| `tcfTrace.silence` | see below | TCF messages left out of the TCF trace | +| Setting (`simics-target-debug.` ...) | Default | Description | +| ------------------------------------ | ------- | ------------------------------------------------- | +| `console.open` | `true` | Open the Simics CLI after attaching | +| `console.historySessions` | `3` | Earlier sessions shown in the Simics CLI | +| `console.editingKeys` | `true` | Send editing keys such as Ctrl+P to Simics | +| `callStack.hierarchy` | `true` | Group threads in the Call Stack view | +| `callStack.compact` | `true` | A group that is the only child shares its parent's row | +| `disassembly.functionHeaders` | `true` | Show function names in the Disassembly view | +| `tcfTrace.enabled` | `false` | Log TCF messages to Output › Simics Target Debug | +| `tcfTrace.silence` | (list) | `service/type/name` rules for messages not to log | -The call stack, disassembly and TCF trace settings are read when a debug -session starts. +Call stack, disassembly and trace settings apply to new sessions. -**Simics Target Debug: Open Settings** in the Command Palette, or the gear -button in the Consoles view and in the launch configurations editor, shows -them in the Settings editor. - -### TCF trace +### Symbol files -Turn on `simics-target-debug.tcfTrace.enabled` to log the TCF messages -between VS Code and the agent in Output › Simics Target Debug. -`simics-target-debug.tcfTrace.silence` lists the messages to leave out, as -`service/type/name` rules. The default silences the agent's `Locator` peer -events, such as the heartbeat, the Simics console (the `CommandLine` -service) and Simics log events (`SimicsLogs`): +Load symbol files when attaching, in addition to `add-symbol-file` in Simics: ```json -"simics-target-debug.tcfTrace.silence": [ - "Locator/event/peerHeartBeat", - "Locator/event/peerAdded", - "Locator/event/peerRemoved", - "Locator/event/peerChanged", - "CommandLine", - "SimicsLogs/event" +"symbolFiles": [ + { "path": "${workspaceFolder}/build/firmware.elf" }, + { "path": "build/app.elf", "contexts": ["board.mb.cpu0.core[0][0]"] }, + { "path": "build/driver.elf", "contextQuery": "**/HasState=true", "address": "0x40000000" }, + { "path": "build/module.elf", "address": "0xff000", "absolute": true } ] ``` -- A rule silences the messages of `service` that have one of the types and - are called `name`. `*`, or a part left out, matches anything. -- The types are `command` (a command C and its results R, P and N, which the - agent sends back with the command's token), `event` (E) and `flowControl` - (F), separated by commas, for example `Memory/command,event`. A command's - results have its service and name. -- Flow control messages have no service or name, so only `*/flowControl` - silences them. -- Rules for services the agent does not have match nothing and do no harm. -- A list in the settings replaces the default. Remove a rule to log its - messages, `[]` logs everything. -- In `settings.json`, the services of the Simics TCF agent and the message - types are suggested while you type a rule. - -### Launch configurations editor - -**Simics Target Debug: Edit Launch Configurations** in the Command Palette -opens the `simics-target-debug` configurations of `.vscode/launch.json` in a -form, like the Settings editor: the configuration names on the left, the -attributes of the selected one on the right. With several workspace folders it -asks which folder to use, and it creates `launch.json` if there is none. The -buttons in the editor title switch between the form and the text of -`launch.json`, and **Open With...** on `launch.json` offers the form too. - -- Each change is written to `launch.json` and saved at once. Only the changed - value is rewritten, so comments, formatting and other debug types are kept. -- Text boxes write their value when they lose focus or Enter is pressed. - **Reset** removes an attribute, so its default is used. -- **Add**, **Duplicate** and **Delete** manage whole configurations. New names - are made unique. -- Changes made in the text editor show up in the form at once. While - `launch.json` has syntax errors the form is read-only. -- The fields come from `configurationAttributes` in `package.json`, so new - attributes appear without changes to the form. Of VS Code's own options - only `internalConsoleOptions` (when to open the Debug Console) is shown, - under **Advanced** at the end, with `connectTimeout`. Others, like - `preLaunchTask`, are listed under **Other Attributes** when set, and can be - edited in the text. -- 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` - 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. - -Attributes in the `launch` section of a `.code-workspace` file are not shown. +| Property | Description | +| -------------- | --------------------------------------------------------------------------- | +| `path` | ELF file as seen by the agent, relative to the workspace folder | +| `contexts` | Context IDs or names the symbols apply to (default: all) | +| `contextQuery` | A TCF context query instead of `contexts` | +| `address` | Offset added to all addresses, like `add-symbol-file -relative` | +| `absolute` | If `true`, `address` is where the first loadable segment is loaded | -### Symbol files +The **Symbol Files** view in Run and Debug adds, edits, reloads and removes +files during a session, and its save button writes them back to +`launch.json`. Files loaded elsewhere, for example in Simics, are listed +under **Added Elsewhere**. -Symbol files can be loaded from the debug configuration instead of (or in -addition to) `add-symbol-file` in Simics: +### Path mapping + +If the sources are not at the path in the debug information, map the +compiled path prefix to the local one: ```json -{ - "type": "simics-target-debug", - "request": "attach", - "name": "Attach to TCF agent", - "port": 1534, - "symbolFiles": [ - { "path": "${workspaceFolder}/build/firmware.elf" }, - { "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 } - ] -} +"pathMap": [ + { "source": "/build/firmware", "destination": "${workspaceFolder}/firmware" }, + { "source": "/build/src", "destination": "${workspaceFolder}/cpu0", "contexts": ["cpu0"] } +] ``` -| Property | Description | -|----------------|-------------| -| `path` | The symbol file (ELF with debug information), as seen by the agent. Relative paths are relative to the workspace folder. | -| `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 `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: - -- `"address": "-0x300000"` subtracts 0x300000 from every address in the file, - so `.text` ends up at 0x100000. -- `"address": "0xff000", "absolute": true` gives the same result by placing - that segment at 0xff000. The value must be the segment address, not the - `.text` address. - -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 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 -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, 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). 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 -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 -affect only the current session unless explicitly saved. -The view's reload button clears and reapplies all symbol mappings so the -agent can load updated files; removing the last file for a context clears -that context's map. - -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, 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. -Other configuration properties and surrounding comments are preserved. - -Files that are in the agent's memory maps but were not added by this -session, for example with `add-symbol-file` in Simics, by OS awareness, or by -another client, are listed read-only under **Added Elsewhere** in the -Symbol Files view. They are read with `MemoryMap.get` for the memory context -(`ProcessID`) of each core or thread, and grouped by file. The description -shows the context, or the number of contexts, and the relocation offset or -lowest mapped address; the tooltip lists the contexts, the region IDs set by -other clients, and the mapped regions. The session's own regions are -recognized by their `ID`, which is unique per debug session. - -When the agent reports that the memory map changed while the target is -suspended, for example after `add-symbol-file` in Simics, the call stack and -variables are refreshed. The Symbol Files view is refreshed on any memory map -change. +Rules apply to all contexts unless `contexts` or `contextQuery` is set. When +a source file is not found, VS Code offers to locate it and creates a rule +for you. The **Path Maps** view in Run and Debug edits, reorders and saves +the rules. -### Path mapping +## Limitations -When the sources are not at the path compiled into the debug information, -for example when the target software was built on another machine or in a -container, add `pathMap` rules that map a compiled path prefix (`source`) to -the path prefix on this host (`destination`): +- No exception breakpoints. +- Breakpoints set by other TCF clients or the Simics CLI are not shown. +- Variables and registers are read-only. +- `char *` and `char[]` are not shown as strings. +- No "Restart Frame". +- Only TCP transport. -```json -{ - "type": "simics-target-debug", - "request": "attach", - "name": "Attach to TCF agent", - "port": 1534, - "pathMap": [ - { "source": "/build/firmware", "destination": "${workspaceFolder}/firmware" }, - { "source": "C:\\work\\libs", "destination": "/home/me/libs" } - ] -} -``` +## Development -This works like the path map in the Eclipse TCF client: +Requires Node.js 24 or later and npm. Run the commands from the repository +root. -- On attach the rules are sent to the agent with `PathMap.set`. The agent then - matches breakpoints set on host paths against the compiled paths. -- Source paths reported by the agent (call stack, moved breakpoints) are mapped - to host paths by VS Code. The configured rules are tried in order, followed - by rules the agent has from elsewhere (`PathMap.get`, for example added with - the Simics command `add-pathmap-entry`). The first mapped file that exists on - the host is used. Mapped frames show the compiled path in the Call Stack - tooltip. -- For breakpoints, rules the agent has from elsewhere are applied in reverse by - VS Code, since the agent only uses the client's own rules for breakpoints. - With agents without the `PathMap` service, the configured rules are applied - in reverse as well. +Install the dependencies: -A prefix only matches at a path separator, so `/build/src` maps -`/build/src/a.c` but not `/build/src2/a.c`. Both `/` and `\` are accepted in -compiled paths. Invalid rules are reported in the Debug Console and ignored. +```sh +npm ci +``` -Rules apply to **all contexts by default**. To scope a rule, set either -`contexts` to a list of exact context IDs or `contextQuery` to a TCF query: +Build, test and package: -```json -"pathMap": [ - { - "source": "/build/src", - "destination": "${workspaceFolder}/cpu0", - "contexts": ["cpu0", "cpu1"] - }, - { - "source": "/build/src", - "destination": "${workspaceFolder}/workers", - "contextQuery": "/server/**/HasState=true" - } -] +```sh +npm run build # type check and bundle the extension +npm test # run the unit tests +npm run package # create simics-target-debug-.vsix ``` -Both options use the protocol's `ContextQuery` property in `PathMap.set`. -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 -can resolve to different host files. General queries are evaluated by the -agent's `ContextQuery` service; exact `ID=...` filters work without it. -Unscoped breakpoint requests leave scoped rules to the agent's `PathMap` -service rather than applying one context's mapping globally. Without that -service, scoped reverse mapping requires a context-bearing source and -breakpoint `ContextIds` support; an unsafe global mapping is rejected. - -When a call stack frame's source file is not found on this host, VS Code -shows a placeholder for it instead of offering to create the file, and asks -whether to locate the file. You can also run **Simics Target Debug: Locate -Source File...** from the Command Palette. Pick the file on this host, and a -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 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 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. - -The view's **Save Path Map to Debug Configuration** button replaces `pathMap` -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. 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 - -- `src/extension.ts` – VS Code entry point, registers the `simics-target-debug` - debug type. -- `src/tcfDebugSession.ts` – DAP implementation (no `vscode` dependency, so it - can also be run as a standalone debug adapter later). -- `src/contextSession.ts` – adapter of the child sessions that show the - threads of a container context; passes requests on to the root session's - adapter. -- `src/contextSessionManager.ts` – starts the child sessions in VS Code and - maps them to their root session for the extension's views and commands. -- `src/breakpointManager.ts` – keeps the agent's breakpoint table in sync with - VS Code. -- `src/variables.ts` – local variables and expressions through the - `Expressions` and `Symbols` services. -- `src/pathMapper.ts` – path mapping between compiled and host paths. -- `src/symbolFiles.ts` – symbol files from the debug configuration, sent to - the agent's memory map. -- `src/targetMemory/` – Target Memory panels and commands (extension side). -- `src/webview/targetMemory/` – Target Memory UI (React), bundled to - `out/target-memory.{js,css}`. -- `src/shared/targetMemory/` – code shared by the Target Memory extension - side, webview and debug adapter: messages, formatting, search needles and - the memory search. -- `src/tcfRequests.ts` – custom DAP requests used by the Target Memory view. -- `src/simicsConsole.ts` – the Simics console: keys to `CommandLine` key - presses, events to VT text (no `vscode` dependency). -- `src/simicsConsoleManager.ts` – the Simics CLI terminals and their commands. -- `src/consolesView.ts` – the Consoles view. -- `src/snapshots.ts` – Simics snapshots in the adapter, and the custom - requests of the Snapshots view (no `vscode` dependency). -- `src/snapshotsView.ts` – the Snapshots view and its commands. -- `src/launchSettings/` – the TCF Launch Configurations editor: reading and editing - `launch.json` (`launchJson.ts`), form fields from `package.json` - (`schema.ts`), the custom editor (`editorProvider.ts`) and the form in its - webview (`webview/`). -- `src/tcf/channel.ts` – TCF TCP channel: framing, escaping, tokens, events. -- `src/tcf/json.ts` – JSON parsing that keeps 64-bit integers exact (`bigint`). -- `src/tcf/services/` – typed wrappers for TCF services. -- `src/test/` – unit tests (`node:test`), they need no TCF agent. - -## Current limitations +Format the code with Prettier before committing: -- No exception breakpoints. -- Breakpoints created by other TCF clients (or the Simics CLI) are not shown. -- Variables and registers are read-only, there is no "Set Value". -- `char *` and `char[]` are not shown as strings; expand them to see the - characters. -- No "Restart Frame". -- Path map rules are read when attaching; changing them requires a new debug - session. Rules added in Simics while attached apply to new breakpoints only. -- Only TCP transport. +```sh +npm run format +``` + +Other useful commands: + +```sh +npm run check # type check and run the unit tests +npm run watch # rebuild on changes +npm run compile:production # minified bundle without source maps +``` + +To develop in VS Code, open the repository, select **Run Extension** in the +Run and Debug view and press F5. This starts `npm run watch` and opens an +Extension Development Host with the extension loaded. **Run Extension +(Clean)** does the same with all other extensions disabled.