dsh-stm32 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +59 -21
  2. package/README_EN.md +59 -21
  3. package/docs/development-notes.md +374 -3
  4. package/docs/reading-guide.md +87 -66
  5. package/lib/data/chips.js +38 -51
  6. package/lib/data/cmsis-sources.js +27 -1
  7. package/lib/data/device-facts.js +201 -0
  8. package/lib/data/stm32f1.js +94 -150
  9. package/lib/data/svd.js +627 -0
  10. package/lib/engine/assets.js +924 -0
  11. package/lib/engine/breakpoints.js +242 -0
  12. package/lib/engine/debug-session.js +153 -5
  13. package/lib/engine/debug.js +75 -41
  14. package/lib/engine/doctor.js +2 -2
  15. package/lib/engine/flash.js +31 -59
  16. package/lib/engine/ioc-plan.js +5 -5
  17. package/lib/engine/probe-error.js +212 -0
  18. package/lib/engine/probe-session.js +311 -0
  19. package/lib/engine/register-template.js +32 -8
  20. package/lib/engine/regs.js +2 -0
  21. package/lib/engine/rtt.js +600 -0
  22. package/lib/index.js +8 -0
  23. package/lib/tools/assets.js +341 -0
  24. package/lib/tools/cache.js +8 -0
  25. package/lib/tools/debug-session.js +40 -5
  26. package/lib/tools/debug.js +41 -11
  27. package/lib/tools/doctor.js +11 -0
  28. package/lib/tools/flash.js +15 -6
  29. package/lib/tools/generate.js +3 -0
  30. package/lib/tools/ioc-apply.js +2 -0
  31. package/lib/tools/ioc-inspect.js +2 -0
  32. package/lib/tools/ioc-plan.js +3 -0
  33. package/lib/tools/project-create.js +24 -0
  34. package/lib/tools/regs.js +453 -61
  35. package/lib/tools/route-plan.js +3 -0
  36. package/lib/tools/rtt.js +347 -0
  37. package/package.json +1 -1
  38. package/templates/register/CMakeLists.txt +7 -1
  39. package/templates/register/Core/Inc/rtt.h +103 -0
  40. package/templates/register/Core/Src/main.c +25 -0
  41. package/templates/register/Core/Src/rtt.c +297 -0
  42. package/templates/scaffold/RTT.md +86 -0
  43. package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
  44. package/lib/data/f1-ram.generated.js +0 -34
@@ -0,0 +1,242 @@
1
+ /**
2
+ * B4:断点预算 —— 按芯片的真实上限限制硬件断点 / 数据观察点,超限在碰探针之前就报。
3
+ *
4
+ * 为什么要有这一层:Cortex-M 的硬件断点用 FPB 代码比较器、观察点用 DWT 数据比较器,
5
+ * STM32F1 只有 6 / 4 个。第 7 个断点不是"慢一点",而是 gdb 报
6
+ * "Cannot insert breakpoint N" 然后整次调试提前收场,用户看到的是"调试莫名其妙失败"。
7
+ * 所以这里在设断点之前先把请求和预算对齐:超了就一次说清超了几个、删哪个、换成什么,
8
+ * 而且这一步发生在 spawn openocd 之前(探针不动、不占用)。
9
+ *
10
+ * 预算来源:资源包 device/f1/chips.json 里如果给某颗芯片写了 breakpoints / watchpoints,
11
+ * 就用芯片自己的值(资源仓库以后按型号补值,插件不用改);没写就按 F1 实测值 6 / 4。
12
+ */
13
+ import { readFileSync, readdirSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { findChipFact } from "../data/device-facts.js";
16
+ /** F1 实测:6 个硬件断点、4 个观察点。 */
17
+ export const F1_BREAKPOINT_BUDGET = { code: 6, data: 4 };
18
+ /** 目前插件只支持 F1:拿不到更精确的值时就用这一份。 */
19
+ export const DEFAULT_BREAKPOINT_BUDGET = F1_BREAKPOINT_BUDGET;
20
+ /** used 夹在 [0, limit] 里:报告不能让"已用"看起来超过上限或为负。 */
21
+ export function quotaOf(used, limit) {
22
+ const cap = Number.isFinite(limit) ? Math.max(0, Math.trunc(limit)) : 0;
23
+ const taken = Number.isFinite(used) ? Math.min(cap, Math.max(0, Math.trunc(used))) : 0;
24
+ return { used: taken, limit: cap, remaining: cap - taken };
25
+ }
26
+ function usableCount(value) {
27
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : null;
28
+ }
29
+ /**
30
+ * chips.json 里的芯片记录 → 预算;没写就返回 null(调用方回退 F1 默认)。
31
+ * 只写了一个字段时,另一个按 F1 默认补齐——比整份作废更有用。
32
+ */
33
+ export function budgetFromChipFact(chip) {
34
+ if (chip === null || chip === undefined)
35
+ return null;
36
+ const code = usableCount(chip.breakpoints);
37
+ const data = usableCount(chip.watchpoints);
38
+ if (code === null && data === null)
39
+ return null;
40
+ return { code: code ?? F1_BREAKPOINT_BUDGET.code, data: data ?? F1_BREAKPOINT_BUDGET.data };
41
+ }
42
+ /** 工程里 .ioc 的 Mcu.CPN(找不到就是空串;多个 .ioc 时按文件名顺序取第一个读得出来的)。 */
43
+ export function readIocCpn(projectDir) {
44
+ let names;
45
+ try {
46
+ names = readdirSync(projectDir);
47
+ }
48
+ catch {
49
+ return "";
50
+ }
51
+ const candidates = names.filter((name) => name.toLowerCase().endsWith(".ioc")).sort();
52
+ for (const name of candidates) {
53
+ try {
54
+ const text = readFileSync(join(projectDir, name), "utf8");
55
+ const match = /^Mcu\.CPN=(.+)$/mu.exec(text);
56
+ const cpn = match === null ? "" : (match[1] ?? "").trim();
57
+ if (cpn !== "")
58
+ return cpn.toUpperCase();
59
+ }
60
+ catch {
61
+ // 读不了就试下一个;没有可用的就回退默认预算(不让断点预算把调试挡在门外)。
62
+ }
63
+ }
64
+ return "";
65
+ }
66
+ /** 工程 → 芯片 → 预算。任何一步失败都退回 F1 默认并说明原因。 */
67
+ export function resolveBreakpointBudget(projectDir, env = process.env) {
68
+ const cpn = readIocCpn(projectDir);
69
+ const fallback = (why) => ({
70
+ budget: F1_BREAKPOINT_BUDGET,
71
+ source: "f1-default",
72
+ chip: cpn,
73
+ note: "断点预算按 STM32F1 默认 " + String(F1_BREAKPOINT_BUDGET.code) + " 个硬件断点 / " + String(F1_BREAKPOINT_BUDGET.data) + " 个观察点算(" + why + ")",
74
+ });
75
+ if (cpn === "")
76
+ return fallback("工程里没找到 .ioc");
77
+ let fact = null;
78
+ try {
79
+ fact = findChipFact(cpn, env);
80
+ }
81
+ catch {
82
+ fact = null;
83
+ }
84
+ if (fact === null)
85
+ return fallback("chips.json 里没有 " + cpn);
86
+ const budget = budgetFromChipFact(fact);
87
+ if (budget === null)
88
+ return fallback("chips.json 的 " + cpn + " 没写 breakpoints/watchpoints");
89
+ return {
90
+ budget,
91
+ source: "chips.json",
92
+ chip: cpn,
93
+ note: "断点预算来自 chips.json(" + cpn + "):" + String(budget.code) + " 个硬件断点 / " + String(budget.data) + " 个观察点",
94
+ };
95
+ }
96
+ const BREAK_COMMANDS = new Set(["break", "b", "tbreak", "tb", "hbreak", "thbreak", "rbreak"]);
97
+ const WATCH_COMMANDS = new Set(["watch", "rwatch", "awatch"]);
98
+ /**
99
+ * "main" / "watch:g_led_count" / "break:HAL_Delay" → 规范化断点。
100
+ * 前缀只用来标 kind,去掉前缀后的部分原样交给 gdb。空串返回 null(调用方忽略)。
101
+ */
102
+ export function parseBreakpointSpec(text) {
103
+ const raw = text.trim();
104
+ if (raw === "")
105
+ return null;
106
+ const lower = raw.toLowerCase();
107
+ for (const prefix of ["watch:", "rwatch:", "awatch:", "data:"]) {
108
+ if (lower.startsWith(prefix)) {
109
+ const location = raw.slice(prefix.length).trim();
110
+ return location === "" ? null : { location, kind: "data" };
111
+ }
112
+ }
113
+ for (const prefix of ["break:", "tbreak:", "hbreak:", "code:"]) {
114
+ if (lower.startsWith(prefix)) {
115
+ const location = raw.slice(prefix.length).trim();
116
+ return location === "" ? null : { location, kind: "code" };
117
+ }
118
+ }
119
+ return { location: raw, kind: "code" };
120
+ }
121
+ /** 一条 gdb 命令 → 断点请求(只认 break/watch 家族;别的命令原样留给 preCommands 执行)。 */
122
+ export function breakpointFromGdbCommand(command) {
123
+ const text = command.trim();
124
+ if (text === "")
125
+ return null;
126
+ const match = /^([A-Za-z]+)(?:\s+(.*))?$/u.exec(text);
127
+ if (match === null)
128
+ return null;
129
+ const verb = (match[1] ?? "").toLowerCase();
130
+ const rest = (match[2] ?? "").trim();
131
+ if (BREAK_COMMANDS.has(verb))
132
+ return { location: rest === "" ? "(当前 pc)" : rest, kind: "code" };
133
+ if (WATCH_COMMANDS.has(verb))
134
+ return { location: rest === "" ? "(当前表达式)" : rest, kind: "data" };
135
+ return null;
136
+ }
137
+ /**
138
+ * 把三处来源(breakAt / breakpoints / preCommands)收成一份不重复的请求清单。
139
+ *
140
+ * 同一位置只留一个:硬件比较器按地址分配,重复的 break 在 gdb 里会各占一个编号,
141
+ * 真到 FPB 上就是白吃一个比较器。
142
+ */
143
+ export function collectBreakpointRequests(input) {
144
+ const notes = [];
145
+ const raw = [];
146
+ const breakAt = (input.breakAt ?? "").trim();
147
+ if (breakAt !== "" && breakAt.toLowerCase() !== "none")
148
+ raw.push({ location: breakAt, kind: "code" });
149
+ for (const text of input.breakpoints ?? []) {
150
+ const spec = parseBreakpointSpec(text);
151
+ if (spec === null)
152
+ notes.push("breakpoints 里有一个空串,已经忽略");
153
+ else
154
+ raw.push(spec);
155
+ }
156
+ let fromPre = 0;
157
+ for (const command of input.preCommands ?? []) {
158
+ const spec = breakpointFromGdbCommand(command);
159
+ if (spec === null)
160
+ continue;
161
+ raw.push(spec);
162
+ fromPre += 1;
163
+ }
164
+ if (fromPre > 0)
165
+ notes.push("preCommands 里有 " + String(fromPre) + " 条 break/watch 命令,也一起算进断点预算");
166
+ const seen = new Set();
167
+ const requested = [];
168
+ for (const spec of raw) {
169
+ const key = spec.kind + "\u0000" + spec.location;
170
+ if (seen.has(key))
171
+ continue;
172
+ seen.add(key);
173
+ requested.push(spec);
174
+ }
175
+ if (requested.length !== raw.length) {
176
+ notes.push("有 " + String(raw.length - requested.length) + " 个重复断点(同一位置)并成了一个,不重复占比较器");
177
+ }
178
+ return { requested, notes };
179
+ }
180
+ /** 超预算时的一句话(放进 errors[0],用户最先看到的就是它)。 */
181
+ function overflowDetail(codeAsked, dataAsked, budget, overCode, overData) {
182
+ const parts = [];
183
+ if (overCode > 0)
184
+ parts.push("多 " + String(overCode) + " 个硬件断点");
185
+ if (overData > 0)
186
+ parts.push("多 " + String(overData) + " 个观察点");
187
+ return "这次要设 " + String(codeAsked) + " 个硬件断点 / " + String(dataAsked) + " 个观察点,芯片上限是 "
188
+ + String(budget.code) + "/" + String(budget.data) + "(" + parts.join("、") + ")";
189
+ }
190
+ /** 超预算时用户能照着做的建议(放进 notes,不塞进一行里的长句)。 */
191
+ function overflowSuggestion(budget, overCode, overData) {
192
+ const parts = [];
193
+ if (overCode > 0) {
194
+ parts.push("删掉多出来的 " + String(overCode) + " 个 break:硬件断点占 FPB 比较器,第 " + String(budget.code + 1) + " 个 gdb 只会报 Cannot insert breakpoint 并把整次调试带崩;要连着停几个点就改用 tbreak(命中即删),或者先 break 一个、到点再换下一个");
195
+ }
196
+ if (overData > 0) {
197
+ parts.push("观察点同理:DWT 只有 " + String(budget.data) + " 个数据比较器,超出的改成一次 watch 一个、或用 print / x 轮询变量");
198
+ }
199
+ parts.push("F1 的 " + String(budget.code) + "/" + String(budget.data) + " 是硅片上限(FPB/DWT 比较器数量),想同时停更多点只能换芯片");
200
+ return parts.join(";");
201
+ }
202
+ /** 请求清单 vs 预算:按顺序放到放不下为止,剩下的进 overflow。 */
203
+ export function planBreakpoints(requested, budget) {
204
+ const cap = {
205
+ code: Number.isFinite(budget.code) ? Math.max(0, Math.trunc(budget.code)) : 0,
206
+ data: Number.isFinite(budget.data) ? Math.max(0, Math.trunc(budget.data)) : 0,
207
+ };
208
+ const placed = [];
209
+ const overflow = [];
210
+ let codeUsed = 0;
211
+ let dataUsed = 0;
212
+ for (const request of requested) {
213
+ if (request.kind === "data") {
214
+ if (dataUsed < cap.data) {
215
+ dataUsed += 1;
216
+ placed.push(request);
217
+ }
218
+ else
219
+ overflow.push(request);
220
+ continue;
221
+ }
222
+ if (codeUsed < cap.code) {
223
+ codeUsed += 1;
224
+ placed.push(request);
225
+ }
226
+ else
227
+ overflow.push(request);
228
+ }
229
+ const codeAsked = codeUsed + overflow.filter((item) => item.kind === "code").length;
230
+ const dataAsked = dataUsed + overflow.filter((item) => item.kind === "data").length;
231
+ const ok = overflow.length === 0;
232
+ return {
233
+ ok,
234
+ placed,
235
+ overflow,
236
+ suggestion: ok ? "" : overflowSuggestion(cap, codeAsked - codeUsed, dataAsked - dataUsed),
237
+ detail: ok ? "" : overflowDetail(codeAsked, dataAsked, cap, codeAsked - codeUsed, dataAsked - dataUsed),
238
+ budget: cap,
239
+ used: { code: codeUsed, data: dataUsed },
240
+ remaining: { code: cap.code - codeUsed, data: cap.data - dataUsed },
241
+ };
242
+ }
@@ -11,7 +11,9 @@
11
11
  * 探针只有一块:任何时刻只允许一个会话,重复 start 会先把旧的关掉。
12
12
  */
13
13
  import { existsSync } from "node:fs";
14
+ import net from "node:net";
14
15
  import { resolveSearchConfig } from "../data/search-roots.js";
16
+ import { F1_BREAKPOINT_BUDGET, collectBreakpointRequests, planBreakpoints, quotaOf, resolveBreakpointBudget } from "./breakpoints.js";
15
17
  import { pickPort, resolveElfPath } from "./debug.js";
16
18
  import { defaultConfigs, findProjectConfig, toOpenOcdPath } from "./flash.js";
17
19
  import { resolveToolIn } from "./probe.js";
@@ -20,6 +22,14 @@ import { waitForListening } from "./debug.js";
20
22
  const DEFAULT_IDLE_TTL_MS = 90_000;
21
23
  const DEFAULT_HARD_TTL_MS = 10 * 60_000;
22
24
  const SWEEP_MS = 5_000;
25
+ /**
26
+ * 等 tcl 端口那行日志的宽限期。
27
+ *
28
+ * openocd 的三行 "Listening on port N for <svc> connections" 是分别打印的,而 waitForListening
29
+ * 一见到第一行就返回;多等 120 ms 再把 collected 缓冲从头读一遍,才不会把 tcl 端口读丢
30
+ * (读丢只是慢一点:快路径会回退到 gdb)。
31
+ */
32
+ const TCL_PORT_SETTLE_MS = 120;
23
33
  const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
24
34
  /** 把 "0x4001100c" / "4001100C" 统一成 8 位小写 0x 形式;解析不了返回 null。 */
25
35
  export function normalizeHexAddress(text) {
@@ -78,10 +88,36 @@ export function parseMarkedWords(output, addresses) {
78
88
  }
79
89
  return { pc, values };
80
90
  }
91
+ /**
92
+ * 从 openocd 启动日志里解析各服务的监听端口。
93
+ *
94
+ * openocd 0.12 会打印三行独立的 "Listening on port N for <svc> connections"(tcl / telnet / gdb)。
95
+ * B3 的读寄存器快路径只要 tcl 那个:走它的 RPC 口 halt → mdw → resume,一次连接几毫秒。
96
+ * 解析不到就是 0,调用方回退到 gdb(慢一点但能用),不把整个工具搞挂。
97
+ */
98
+ export function parseListeningPorts(text) {
99
+ const ports = { gdb: 0, tcl: 0, telnet: 0 };
100
+ for (const match of text.matchAll(/listening on port (\d+) for ([a-z]+) connections/giu)) {
101
+ const port = Number(match[1]);
102
+ const service = (match[2] ?? "").toLowerCase();
103
+ if (!Number.isFinite(port) || port <= 0)
104
+ continue;
105
+ if (service === "gdb")
106
+ ports.gdb = ports.gdb === 0 ? port : ports.gdb;
107
+ else if (service === "tcl")
108
+ ports.tcl = ports.tcl === 0 ? port : ports.tcl;
109
+ else if (service === "telnet")
110
+ ports.telnet = ports.telnet === 0 ? port : ports.telnet;
111
+ }
112
+ return ports;
113
+ }
81
114
  function emptyReport(errors, message) {
82
115
  return {
83
- ok: false, active: false, sessionId: "", port: 0, projectDir: "", elfPath: "",
84
- startedAt: 0, idleTtlMs: DEFAULT_IDLE_TTL_MS, hardTtlMs: DEFAULT_HARD_TTL_MS, remainingMs: 0, errors, message,
116
+ ok: false, active: false, sessionId: "", port: 0, tclPort: 0, projectDir: "", configFile: "", elfPath: "",
117
+ startedAt: 0, idleTtlMs: DEFAULT_IDLE_TTL_MS, hardTtlMs: DEFAULT_HARD_TTL_MS, remainingMs: 0,
118
+ breakpoints: quotaOf(0, F1_BREAKPOINT_BUDGET.code),
119
+ watchpoints: quotaOf(0, F1_BREAKPOINT_BUDGET.data),
120
+ errors, message,
85
121
  };
86
122
  }
87
123
  export class DebugSessionManager {
@@ -100,14 +136,28 @@ export class DebugSessionManager {
100
136
  isActive() {
101
137
  return this.current !== null;
102
138
  }
139
+ /**
140
+ * 续租:会话刚被用过一次(B3 的 regs 快路径每读一次都算"用过")。
141
+ * 返回是否真的有会话被续租。
142
+ */
143
+ touch() {
144
+ const session = this.current;
145
+ if (session === null)
146
+ return false;
147
+ session.lastUsedAt = this.now();
148
+ return true;
149
+ }
103
150
  status() {
104
151
  const session = this.current;
105
152
  if (session === null)
106
153
  return emptyReport([], "没有调试会话(探针空闲)");
107
154
  return {
108
- ok: true, active: true, sessionId: session.id, port: session.port, projectDir: session.projectDir,
155
+ ok: true, active: true, sessionId: session.id, port: session.port, tclPort: session.tclPort,
156
+ projectDir: session.projectDir,
157
+ configFile: session.configFile,
109
158
  elfPath: session.elfPath, startedAt: session.startedAt, idleTtlMs: session.idleTtlMs,
110
- hardTtlMs: session.hardTtlMs, remainingMs: this.remainingMs(session), errors: [],
159
+ hardTtlMs: session.hardTtlMs, remainingMs: this.remainingMs(session),
160
+ breakpoints: session.breakpoints, watchpoints: session.watchpoints, errors: [],
111
161
  message: "调试会话进行中(端口 " + String(session.port) + ",剩余 " + String(Math.ceil(this.remainingMs(session) / 1000)) + " s)",
112
162
  };
113
163
  }
@@ -145,6 +195,22 @@ export class DebugSessionManager {
145
195
  const subprocess = this.subprocess;
146
196
  if (subprocess === null)
147
197
  return emptyReport(["插件还没拿到 subprocess 服务"], "没开会话:插件未就绪");
198
+ // B4:断点预算先算(纯计算 + 读 .ioc/chips.json),超限就直接不占探针——
199
+ // 也别把已有会话关掉:这次申请本来就不会开起来。
200
+ const budgetInfo = resolveBreakpointBudget(request.projectDir);
201
+ const collected = collectBreakpointRequests({
202
+ ...(request.breakpoints === undefined ? {} : { breakpoints: request.breakpoints }),
203
+ });
204
+ const plan = planBreakpoints(collected.requested, budgetInfo.budget);
205
+ if (!plan.ok) {
206
+ const blocked = emptyReport(["断点超预算:" + plan.detail, budgetInfo.note, plan.suggestion], "没开会话:断点超预算(硬件断点 " + String(plan.used.code) + "/" + String(plan.budget.code)
207
+ + ",观察点 " + String(plan.used.data) + "/" + String(plan.budget.data) + ")");
208
+ return {
209
+ ...blocked,
210
+ breakpoints: quotaOf(plan.used.code, plan.budget.code),
211
+ watchpoints: quotaOf(plan.used.data, plan.budget.data),
212
+ };
213
+ }
148
214
  if (this.current !== null) {
149
215
  await this.stop("新的会话申请覆盖了旧会话");
150
216
  }
@@ -181,6 +247,8 @@ export class DebugSessionManager {
181
247
  projectDir,
182
248
  elfPath,
183
249
  port,
250
+ tclPort: 0,
251
+ configFile: projectConfig ?? "",
184
252
  handle,
185
253
  startedAt: this.now(),
186
254
  lastUsedAt: this.now(),
@@ -189,6 +257,8 @@ export class DebugSessionManager {
189
257
  logText: "",
190
258
  binDirs: config.binDirs,
191
259
  owner: request.owner ?? "",
260
+ breakpoints: quotaOf(plan.used.code, plan.budget.code),
261
+ watchpoints: quotaOf(plan.used.data, plan.budget.data),
192
262
  };
193
263
  const listening = await waitForListening(handle, 15_000, (text) => {
194
264
  session.logText += text + "\n";
@@ -200,6 +270,15 @@ export class DebugSessionManager {
200
270
  const tail = listening.text.split(/\r?\n/u).slice(-12).join("\n");
201
271
  return emptyReport([/Error connecting DP|no device found|CMSIS-DAP/iu.test(listening.text) ? "openocd 连不上探针/芯片(见日志)" : "openocd 没有在 15 s 内监听 " + String(port), tail], "没开会话:openocd 起不来");
202
272
  }
273
+ // tcl 那行常排在 gdb 那行之后:等一小会儿把整个 collected 缓冲从头读一遍再解析
274
+ // (readFrom(0) 对收集式缓冲是随机读,不影响 waitForListening 已经消费掉的偏移)。
275
+ await sleep(TCL_PORT_SETTLE_MS);
276
+ const fullText = [
277
+ listening.text,
278
+ handle.collected.stdout?.readFrom(0).text ?? "",
279
+ handle.collected.stderr?.readFrom(0).text ?? "",
280
+ ].join("\n");
281
+ session.tclPort = parseListeningPorts(fullText).tcl;
203
282
  this.current = session;
204
283
  this.ensureSweeper();
205
284
  if (request.reset !== undefined && request.reset !== "none") {
@@ -209,7 +288,16 @@ export class DebugSessionManager {
209
288
  return emptyReport(["复位失败:" + resetResult.output.split(/\r?\n/u).slice(-5).join(" ")], "没开会话:复位失败");
210
289
  }
211
290
  }
212
- return this.status();
291
+ const ready = this.status();
292
+ if (collected.requested.length === 0)
293
+ return ready;
294
+ // B4:把登记集合、预算来源、以及"断点不在 gdb 进程之间保留"这件事说清楚。
295
+ return {
296
+ ...ready,
297
+ message: ready.message + "\n· 断点预算已校验:登记 " + String(plan.used.code) + "/" + String(plan.budget.code)
298
+ + " 个硬件断点、观察点 " + String(plan.used.data) + "/" + String(plan.budget.data) + "(" + budgetInfo.note
299
+ + ");会话不跨 gdb 进程保存断点,实际停靠用 stm32_debug_eval 的 break <loc>",
300
+ };
213
301
  }
214
302
  async eval(request) {
215
303
  const session = this.current;
@@ -249,6 +337,21 @@ export class DebugSessionManager {
249
337
  if (commands.length === 0) {
250
338
  return { ok: false, output: "", command: "", durationMs: 0, remainingMs: this.remainingMs(session), errors: ["没有命令"], message: "没执行:commands/expression 都是空的" };
251
339
  }
340
+ // B4:eval 里的 break/watch 也占硬件比较器(一次 gdb 会话里超了,gdb 只会报
341
+ // Cannot insert breakpoint),所以同样先对预算。
342
+ const evalBreakpoints = collectBreakpointRequests({ preCommands: commands });
343
+ if (evalBreakpoints.requested.length > 0) {
344
+ const evalBudget = resolveBreakpointBudget(session.projectDir);
345
+ const evalPlan = planBreakpoints(evalBreakpoints.requested, evalBudget.budget);
346
+ if (!evalPlan.ok) {
347
+ return {
348
+ ok: false, output: "", command: "", durationMs: 0, remainingMs: this.remainingMs(session),
349
+ errors: ["断点超预算:" + evalPlan.detail, evalBudget.note, evalPlan.suggestion],
350
+ message: "没执行:断点超预算(硬件断点 " + String(evalPlan.used.code) + "/" + String(evalPlan.budget.code)
351
+ + ",观察点 " + String(evalPlan.used.data) + "/" + String(evalPlan.budget.data) + ")",
352
+ };
353
+ }
354
+ }
252
355
  const argv = [gdb, "-q", "-batch", "-nx", "-ex", "set confirm off", "-ex", "set pagination off"];
253
356
  if (session.elfPath !== "" && existsSync(session.elfPath))
254
357
  argv.push("-ex", "file " + toOpenOcdPath(session.elfPath));
@@ -395,16 +498,61 @@ export class DebugSessionManager {
395
498
  this.stopSweeper();
396
499
  if (session === null)
397
500
  return { ok: true, stopped: false, message: "本来就没有会话(" + reason + ")" };
501
+ // 先让 openocd 自己 shutdown:直接 kill 时它来不及给探针发断开命令,
502
+ // CMSIS-DAP 固件会被留在「半连接」状态,下一次 CMD_INFO 直接超时(实测踩过两次)。
503
+ await requestOpenocdShutdown(session.tclPort, 800);
504
+ await Promise.race([session.handle.waitForExit().catch(() => undefined), sleep(1200)]);
398
505
  session.handle.terminate();
399
506
  await Promise.race([session.handle.waitForExit().catch(() => undefined), sleep(3000)]);
400
507
  return { ok: true, stopped: true, message: "会话已关闭(" + reason + "),探针已释放" };
401
508
  }
509
+ /**
510
+ * 进程退出前的尽力清理(B3 第 4 条):exit 事件里不能 await,只发终止信号。
511
+ * 返回是否真的收掉了一个会话。
512
+ */
513
+ terminateSync() {
514
+ const session = this.current;
515
+ this.current = null;
516
+ this.stopSweeper();
517
+ if (session === null)
518
+ return false;
519
+ try {
520
+ session.handle.terminate();
521
+ }
522
+ catch {
523
+ // 进程可能已经没了;exit 阶段不能抛。
524
+ }
525
+ return true;
526
+ }
402
527
  async closeAll(reason) {
403
528
  await this.stop(reason);
404
529
  }
405
530
  }
406
531
  /** 进程内单例:工具、turn/end 监听、dispose 共用同一个会话。 */
407
532
  export const debugSessions = new DebugSessionManager();
533
+ /** 通过 Tcl 口让 openocd 自己 shutdown(探针能收到正常的断开序列)。失败就交给 kill 兜底。 */
534
+ function requestOpenocdShutdown(port, timeoutMs) {
535
+ if (!Number.isFinite(port) || port <= 0)
536
+ return Promise.resolve();
537
+ return new Promise((resolve) => {
538
+ const socket = net.connect({ host: "127.0.0.1", port });
539
+ let settled = false;
540
+ const done = () => {
541
+ if (settled)
542
+ return;
543
+ settled = true;
544
+ socket.destroy();
545
+ resolve();
546
+ };
547
+ socket.setTimeout(timeoutMs, done);
548
+ socket.once("connect", () => {
549
+ socket.write("shutdown\n");
550
+ setTimeout(done, 150);
551
+ });
552
+ socket.once("error", done);
553
+ socket.once("close", done);
554
+ });
555
+ }
408
556
  /** 需要独占探针的动作(build / flash / generate / debug_run)动手前调用。 */
409
557
  export async function releaseProbeFor(reason) {
410
558
  if (!debugSessions.isActive())