dsh-stm32 0.1.2 → 0.1.4

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 (225) hide show
  1. package/README.md +92 -40
  2. package/README_EN.md +85 -36
  3. package/assets/README.md +85 -0
  4. package/assets/VERSION +1 -0
  5. package/assets/device/c0/chips.json +1108 -0
  6. package/assets/device/f0/chips.json +1570 -0
  7. package/assets/device/f1/chips.json +1238 -0
  8. package/assets/device/f1/svd/100.json +943 -0
  9. package/assets/device/f1/svd/101.json +901 -0
  10. package/assets/device/f1/svd/102.json +522 -0
  11. package/assets/device/f1/svd/103.json +1139 -0
  12. package/assets/device/f1/svd/105.json +1117 -0
  13. package/assets/device/f1/svd/107.json +1195 -0
  14. package/assets/device/f2/chips.json +674 -0
  15. package/assets/device/f3/chips.json +1318 -0
  16. package/assets/device/f4/chips.json +2942 -0
  17. package/assets/device/f7/chips.json +1710 -0
  18. package/assets/device/g0/chips.json +2102 -0
  19. package/assets/device/g4/chips.json +2494 -0
  20. package/assets/device/h5/chips.json +898 -0
  21. package/assets/device/h7/chips.json +1948 -0
  22. package/assets/device/l0/chips.json +2494 -0
  23. package/assets/device/l1/chips.json +1234 -0
  24. package/assets/device/l4/chips.json +2130 -0
  25. package/assets/device/l4+/chips.json +856 -0
  26. package/assets/device/l5/chips.json +226 -0
  27. package/assets/device/u0/chips.json +688 -0
  28. package/assets/device/u3/chips.json +310 -0
  29. package/assets/device/u5/chips.json +884 -0
  30. package/assets/device/wba/chips.json +506 -0
  31. package/assets/device/wl/chips.json +184 -0
  32. package/assets/headers/f1/stm32f100xb.h +5972 -0
  33. package/assets/headers/f1/stm32f100xe.h +6587 -0
  34. package/assets/headers/f1/stm32f101x6.h +5315 -0
  35. package/assets/headers/f1/stm32f101xb.h +5446 -0
  36. package/assets/headers/f1/stm32f101xe.h +6503 -0
  37. package/assets/headers/f1/stm32f101xg.h +6713 -0
  38. package/assets/headers/f1/stm32f102x6.h +6448 -0
  39. package/assets/headers/f1/stm32f102xb.h +6570 -0
  40. package/assets/headers/f1/stm32f103x6.h +10109 -0
  41. package/assets/headers/f1/stm32f103xb.h +10240 -0
  42. package/assets/headers/f1/stm32f103xe.h +11767 -0
  43. package/assets/headers/f1/stm32f103xg.h +11951 -0
  44. package/assets/headers/f1/stm32f105xc.h +14340 -0
  45. package/assets/headers/f1/stm32f107xc.h +15253 -0
  46. package/assets/headers/f1/stm32f1xx.h +273 -0
  47. package/assets/headers/f1/system_stm32f1xx.h +96 -0
  48. package/assets/ioc/family/C0.ioc +82 -0
  49. package/assets/ioc/family/F0.ioc +71 -0
  50. package/assets/ioc/family/F2.ioc +91 -0
  51. package/assets/ioc/family/F3.ioc +94 -0
  52. package/assets/ioc/family/F4.ioc +91 -0
  53. package/assets/ioc/family/F7.ioc +102 -0
  54. package/assets/ioc/family/G0.ioc +90 -0
  55. package/assets/ioc/family/G4.ioc +110 -0
  56. package/assets/ioc/family/H5.ioc +116 -0
  57. package/assets/ioc/family/H7.ioc +133 -0
  58. package/assets/ioc/family/L0.ioc +92 -0
  59. package/assets/ioc/family/L1.ioc +87 -0
  60. package/assets/ioc/family/L4+.ioc +92 -0
  61. package/assets/ioc/family/L4.ioc +93 -0
  62. package/assets/ioc/family/L5.ioc +91 -0
  63. package/assets/ioc/family/U0.ioc +103 -0
  64. package/assets/ioc/family/U3.ioc +113 -0
  65. package/assets/ioc/family/U5.ioc +102 -0
  66. package/assets/ioc/family/WBA.ioc +100 -0
  67. package/assets/ioc/family/WL.ioc +93 -0
  68. package/assets/ioc/minimal/STM32F100C8Tx.ioc +113 -0
  69. package/assets/ioc/minimal/STM32F100RCTx.ioc +113 -0
  70. package/assets/ioc/minimal/STM32F101C4Tx.ioc +113 -0
  71. package/assets/ioc/minimal/STM32F101C8Tx.ioc +113 -0
  72. package/assets/ioc/minimal/STM32F101RCTx.ioc +113 -0
  73. package/assets/ioc/minimal/STM32F101RFTx.ioc +113 -0
  74. package/assets/ioc/minimal/STM32F102C4Tx.ioc +113 -0
  75. package/assets/ioc/minimal/STM32F102C8Tx.ioc +113 -0
  76. package/assets/ioc/minimal/STM32F103C4Tx.ioc +113 -0
  77. package/assets/ioc/minimal/STM32F103C8Tx.ioc +113 -0
  78. package/assets/ioc/minimal/STM32F103RCTx.ioc +113 -0
  79. package/assets/ioc/minimal/STM32F103RFTx.ioc +113 -0
  80. package/assets/ioc/minimal/STM32F105RCTx.ioc +113 -0
  81. package/assets/ioc/minimal/STM32F107RCTx.ioc +113 -0
  82. package/assets/ld/f1/STM32F100C8Tx_FLASH.ld +249 -0
  83. package/assets/ld/f1/STM32F100RCTx_FLASH.ld +249 -0
  84. package/assets/ld/f1/STM32F101C4Tx_FLASH.ld +249 -0
  85. package/assets/ld/f1/STM32F101C8Tx_FLASH.ld +249 -0
  86. package/assets/ld/f1/STM32F101RCTx_FLASH.ld +249 -0
  87. package/assets/ld/f1/STM32F101RFTx_FLASH.ld +249 -0
  88. package/assets/ld/f1/STM32F102C4Tx_FLASH.ld +249 -0
  89. package/assets/ld/f1/STM32F102C8Tx_FLASH.ld +249 -0
  90. package/assets/ld/f1/STM32F103C4Tx_FLASH.ld +249 -0
  91. package/assets/ld/f1/STM32F103C8Tx_FLASH.ld +249 -0
  92. package/assets/ld/f1/STM32F103RCTx_FLASH.ld +249 -0
  93. package/assets/ld/f1/STM32F103RFTx_FLASH.ld +249 -0
  94. package/assets/ld/f1/STM32F105RCTx_FLASH.ld +249 -0
  95. package/assets/ld/f1/STM32F107RCTx_FLASH.ld +249 -0
  96. package/assets/manifest.json +1130 -0
  97. package/assets/startup/f1/startup_stm32f100xb.s +407 -0
  98. package/assets/startup/f1/startup_stm32f100xe.s +449 -0
  99. package/assets/startup/f1/startup_stm32f101x6.s +322 -0
  100. package/assets/startup/f1/startup_stm32f101xb.s +338 -0
  101. package/assets/startup/f1/startup_stm32f101xe.s +423 -0
  102. package/assets/startup/f1/startup_stm32f101xg.s +439 -0
  103. package/assets/startup/f1/startup_stm32f102x6.s +330 -0
  104. package/assets/startup/f1/startup_stm32f102xb.s +346 -0
  105. package/assets/startup/f1/startup_stm32f103x6.s +348 -0
  106. package/assets/startup/f1/startup_stm32f103xb.s +364 -0
  107. package/assets/startup/f1/startup_stm32f103xe.s +470 -0
  108. package/assets/startup/f1/startup_stm32f103xg.s +466 -0
  109. package/assets/startup/f1/startup_stm32f105xc.s +463 -0
  110. package/assets/startup/f1/startup_stm32f107xc.s +472 -0
  111. package/assets/templates/family/C0.ioc +82 -0
  112. package/assets/templates/family/F0.ioc +71 -0
  113. package/assets/templates/family/F2.ioc +91 -0
  114. package/assets/templates/family/F3.ioc +94 -0
  115. package/assets/templates/family/F4.ioc +91 -0
  116. package/assets/templates/family/F7.ioc +102 -0
  117. package/assets/templates/family/G0.ioc +90 -0
  118. package/assets/templates/family/G4.ioc +110 -0
  119. package/assets/templates/family/H5.ioc +116 -0
  120. package/assets/templates/family/H7.ioc +133 -0
  121. package/assets/templates/family/L0.ioc +92 -0
  122. package/assets/templates/family/L1.ioc +87 -0
  123. package/assets/templates/family/L4+.ioc +92 -0
  124. package/assets/templates/family/L4.ioc +93 -0
  125. package/assets/templates/family/L5.ioc +91 -0
  126. package/assets/templates/family/U0.ioc +103 -0
  127. package/assets/templates/family/U3.ioc +113 -0
  128. package/assets/templates/family/U5.ioc +102 -0
  129. package/assets/templates/family/WB.ioc +81 -0
  130. package/assets/templates/family/WBA.ioc +100 -0
  131. package/assets/templates/family/WL.ioc +93 -0
  132. package/docs/reading-guide.md +94 -71
  133. package/lib/data/chips.js +38 -51
  134. package/lib/data/clock-db.js +830 -0
  135. package/lib/data/clock-f1.js +12 -45
  136. package/lib/data/cmsis-sources.js +264 -17
  137. package/lib/data/db-presets.js +252 -0
  138. package/lib/data/device-facts.js +274 -0
  139. package/lib/data/family.js +515 -0
  140. package/lib/data/firmware-packages.js +562 -0
  141. package/lib/data/install-guides.js +2 -2
  142. package/lib/data/ioc-presets.js +248 -0
  143. package/lib/data/ioc-schema.js +1058 -0
  144. package/lib/data/rm-topics/stm32c0.json +227 -0
  145. package/lib/data/rm-topics.js +103 -0
  146. package/lib/data/search-roots.js +42 -1
  147. package/lib/data/stm32f1.js +95 -150
  148. package/lib/data/svd.js +643 -0
  149. package/lib/data/toolchain-config.js +0 -14
  150. package/lib/engine/assets.js +659 -0
  151. package/lib/engine/breakpoints.js +297 -0
  152. package/lib/engine/clock-derived.js +101 -0
  153. package/lib/engine/clock-direct.js +313 -0
  154. package/lib/engine/clock-plan.js +96 -52
  155. package/lib/engine/clock-pllmn.js +319 -0
  156. package/lib/engine/cmake-sources.js +67 -13
  157. package/lib/engine/cube-mx-guard.js +44 -0
  158. package/lib/engine/cube-programmer.js +137 -0
  159. package/lib/engine/cubemx-db.js +273 -0
  160. package/lib/engine/debug-session.js +576 -22
  161. package/lib/engine/debug.js +99 -46
  162. package/lib/engine/doctor.js +162 -19
  163. package/lib/engine/facts-acquire.js +416 -0
  164. package/lib/engine/facts.js +134 -0
  165. package/lib/engine/firmware-install.js +176 -5
  166. package/lib/engine/firmware-official.js +451 -0
  167. package/lib/engine/flash.js +317 -76
  168. package/lib/engine/gdb-mi.js +476 -0
  169. package/lib/engine/generate.js +9 -2
  170. package/lib/engine/hal-chip.js +124 -41
  171. package/lib/engine/ioc-plan.js +1247 -63
  172. package/lib/engine/ioc-rules.js +698 -0
  173. package/lib/engine/ioc-verify.js +706 -0
  174. package/lib/engine/ioc.js +43 -4
  175. package/lib/engine/msys2-install.js +4 -4
  176. package/lib/engine/probe-error.js +231 -0
  177. package/lib/engine/probe-session.js +347 -0
  178. package/lib/engine/probe.js +18 -3
  179. package/lib/engine/register-clock.js +41 -0
  180. package/lib/engine/register-gpio.js +115 -0
  181. package/lib/engine/register-linker.js +12 -7
  182. package/lib/engine/register-template.js +130 -45
  183. package/lib/engine/regs.js +43 -8
  184. package/lib/engine/rm-extract.js +144 -0
  185. package/lib/engine/rm-sources.js +360 -0
  186. package/lib/engine/rm-text.js +56 -0
  187. package/lib/engine/rtt.js +758 -0
  188. package/lib/engine/scaffold.js +185 -18
  189. package/lib/engine/toolchain-gate.js +0 -4
  190. package/lib/engine/watch.js +227 -0
  191. package/lib/index.js +12 -2
  192. package/lib/skill/stm32-workflow.js +2 -2
  193. package/lib/tools/assets.js +272 -0
  194. package/lib/tools/cache.js +8 -0
  195. package/lib/tools/debug-session.js +41 -6
  196. package/lib/tools/debug.js +41 -11
  197. package/lib/tools/doctor.js +65 -4
  198. package/lib/tools/firmware-install.js +31 -6
  199. package/lib/tools/flash.js +47 -10
  200. package/lib/tools/generate.js +25 -0
  201. package/lib/tools/ioc-apply.js +2 -0
  202. package/lib/tools/ioc-inspect.js +2 -0
  203. package/lib/tools/ioc-plan.js +59 -2
  204. package/lib/tools/ioc-verify.js +237 -0
  205. package/lib/tools/project-create.js +63 -3
  206. package/lib/tools/regs.js +453 -61
  207. package/lib/tools/route-plan.js +3 -0
  208. package/lib/tools/rtt.js +470 -0
  209. package/lib/tools/watch.js +256 -0
  210. package/package.json +5 -4
  211. package/templates/openocd/stm32c0x.cfg +83 -0
  212. package/templates/openocd/stm32u0x.cfg +64 -0
  213. package/templates/register/CMakeLists.txt +8 -2
  214. package/templates/register/Core/Inc/rtt.h +138 -0
  215. package/templates/register/Core/Src/main.c +42 -25
  216. package/templates/register/Core/Src/rtt.c +373 -0
  217. package/templates/scaffold/RTT.md +90 -0
  218. package/templates/scaffold/STM32F103XX_FLASH.ld +3 -0
  219. package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
  220. package/templates/scaffold/openocd.cfg +5 -3
  221. package/templates/scaffold/vscode/launch.json +8 -4
  222. package/docs/development-notes.md +0 -2116
  223. package/docs/dsh-stm32-plugin-/350/247/204/346/240/274.md +0 -673
  224. package/docs/logic-audit.md +0 -607
  225. package/lib/data/f1-ram.generated.js +0 -34
@@ -11,15 +11,31 @@
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";
15
- import { pickPort, resolveElfPath } from "./debug.js";
16
- import { defaultConfigs, findProjectConfig, toOpenOcdPath } from "./flash.js";
16
+ import { F1_BREAKPOINT_BUDGET, collectBreakpointRequests, planBreakpoints, quotaOf, resolveBreakpointBudget } from "./breakpoints.js";
17
+ import { isPortBusy, pickPort, resolveElfPath } from "./debug.js";
18
+ import { MiSession, formatStopLocation, steppingCommandFor } from "./gdb-mi.js";
19
+ import { WATCH_KIND_LABELS, formatWatchDelta, formatWatchSampleNote, hardwareWatchpoints, isHardwareWatchpoint, markWatchpointsStale, normalizeWatchExpression, parseWatchMarkers, parseWatchpointNumber, recordWatchSample, registerWatch, removeWatchByIds, resetWatchState, sampledWatches, watchState, } from "./watch.js";
20
+ import { chooseOpenocdTarget, readProjectFamily } from "../data/family.js";
21
+ import { findProjectConfig, toOpenOcdPath } from "./flash.js";
22
+ import { liveProbeChoice, openocdTransportArgs } from "./doctor.js";
17
23
  import { resolveToolIn } from "./probe.js";
18
24
  import { runCapture } from "./subprocess-runner.js";
19
25
  import { waitForListening } from "./debug.js";
20
26
  const DEFAULT_IDLE_TTL_MS = 90_000;
21
27
  const DEFAULT_HARD_TTL_MS = 10 * 60_000;
22
28
  const SWEEP_MS = 5_000;
29
+ /**
30
+ * 等 tcl 端口那行日志的宽限期。
31
+ *
32
+ * openocd 的三行 "Listening on port N for <svc> connections" 是分别打印的,而 waitForListening
33
+ * 一见到第一行就返回;多等 120 ms 再把 collected 缓冲从头读一遍,才不会把 tcl 端口读丢
34
+ * (读丢只是慢一点:快路径会回退到 gdb)。
35
+ */
36
+ const TCL_PORT_SETTLE_MS = 120;
37
+ /** continue/step 之后等 *stopped 的窗口:命中断点就报停点,纯主循环跑就最多等这么久。 */
38
+ const MI_STOP_WAIT_MS = 3_000;
23
39
  const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
24
40
  /** 把 "0x4001100c" / "4001100C" 统一成 8 位小写 0x 形式;解析不了返回 null。 */
25
41
  export function normalizeHexAddress(text) {
@@ -78,36 +94,88 @@ export function parseMarkedWords(output, addresses) {
78
94
  }
79
95
  return { pc, values };
80
96
  }
97
+ /**
98
+ * 从 openocd 启动日志里解析各服务的监听端口。
99
+ *
100
+ * openocd 0.12 会打印三行独立的 "Listening on port N for <svc> connections"(tcl / telnet / gdb)。
101
+ * B3 的读寄存器快路径只要 tcl 那个:走它的 RPC 口 halt → mdw → resume,一次连接几毫秒。
102
+ * 解析不到就是 0,调用方回退到 gdb(慢一点但能用),不把整个工具搞挂。
103
+ */
104
+ export function parseListeningPorts(text) {
105
+ const ports = { gdb: 0, tcl: 0, telnet: 0 };
106
+ for (const match of text.matchAll(/listening on port (\d+) for ([a-z]+) connections/giu)) {
107
+ const port = Number(match[1]);
108
+ const service = (match[2] ?? "").toLowerCase();
109
+ if (!Number.isFinite(port) || port <= 0)
110
+ continue;
111
+ if (service === "gdb")
112
+ ports.gdb = ports.gdb === 0 ? port : ports.gdb;
113
+ else if (service === "tcl")
114
+ ports.tcl = ports.tcl === 0 ? port : ports.tcl;
115
+ else if (service === "telnet")
116
+ ports.telnet = ports.telnet === 0 ? port : ports.telnet;
117
+ }
118
+ return ports;
119
+ }
81
120
  function emptyReport(errors, message) {
82
121
  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,
122
+ ok: false, active: false, sessionId: "", port: 0, tclPort: 0, projectDir: "", configFile: "", elfPath: "",
123
+ startedAt: 0, idleTtlMs: DEFAULT_IDLE_TTL_MS, hardTtlMs: DEFAULT_HARD_TTL_MS, remainingMs: 0,
124
+ breakpoints: quotaOf(0, F1_BREAKPOINT_BUDGET.code),
125
+ watchpoints: quotaOf(0, F1_BREAKPOINT_BUDGET.data),
126
+ errors, message,
85
127
  };
86
128
  }
87
129
  export class DebugSessionManager {
88
130
  subprocess = null;
89
131
  binDirs = [];
132
+ /** 会话存活探测(默认连 openocd 的 Tcl 端口;单测用假进程替代)。 */
133
+ aliveProbe = (port) => isPortBusy(port, 500);
90
134
  current = null;
91
135
  timer = null;
92
136
  now;
93
137
  constructor(options = {}) {
94
138
  this.now = options.now ?? (() => Date.now());
95
139
  }
96
- configure(subprocess, binDirs = []) {
140
+ /**
141
+ * @param aliveProbe 起会话后探测「openocd 还活着吗」(默认连 Tcl 端口;单测注入假探针)。
142
+ * 真机踩过:探针 HID 掉线时 openocd 打完 Listening 就退出,而 status() 只看内存里的会话对象。
143
+ */
144
+ configure(subprocess, binDirs = [], aliveProbe) {
97
145
  this.subprocess = subprocess;
98
146
  this.binDirs = binDirs;
147
+ if (aliveProbe !== undefined)
148
+ this.aliveProbe = aliveProbe;
149
+ }
150
+ /** 单测注入用:替换「会话还活着吗」的探测(见 configure 的 aliveProbe)。 */
151
+ setAliveProbe(probe) {
152
+ this.aliveProbe = probe;
99
153
  }
100
154
  isActive() {
101
155
  return this.current !== null;
102
156
  }
157
+ /**
158
+ * 续租:会话刚被用过一次(B3 的 regs 快路径每读一次都算"用过")。
159
+ * 返回是否真的有会话被续租。
160
+ */
161
+ touch() {
162
+ const session = this.current;
163
+ if (session === null)
164
+ return false;
165
+ session.lastUsedAt = this.now();
166
+ return true;
167
+ }
103
168
  status() {
104
169
  const session = this.current;
105
170
  if (session === null)
106
171
  return emptyReport([], "没有调试会话(探针空闲)");
107
172
  return {
108
- ok: true, active: true, sessionId: session.id, port: session.port, projectDir: session.projectDir,
173
+ ok: true, active: true, sessionId: session.id, port: session.port, tclPort: session.tclPort,
174
+ projectDir: session.projectDir,
175
+ configFile: session.configFile,
109
176
  elfPath: session.elfPath, startedAt: session.startedAt, idleTtlMs: session.idleTtlMs,
110
- hardTtlMs: session.hardTtlMs, remainingMs: this.remainingMs(session), errors: [],
177
+ hardTtlMs: session.hardTtlMs, remainingMs: this.remainingMs(session),
178
+ breakpoints: session.breakpoints, watchpoints: session.watchpoints, errors: [],
111
179
  message: "调试会话进行中(端口 " + String(session.port) + ",剩余 " + String(Math.ceil(this.remainingMs(session) / 1000)) + " s)",
112
180
  };
113
181
  }
@@ -145,6 +213,22 @@ export class DebugSessionManager {
145
213
  const subprocess = this.subprocess;
146
214
  if (subprocess === null)
147
215
  return emptyReport(["插件还没拿到 subprocess 服务"], "没开会话:插件未就绪");
216
+ // B4:断点预算先算(纯计算 + 读 .ioc/chips.json),超限就直接不占探针——
217
+ // 也别把已有会话关掉:这次申请本来就不会开起来。
218
+ const budgetInfo = resolveBreakpointBudget(request.projectDir);
219
+ const collected = collectBreakpointRequests({
220
+ ...(request.breakpoints === undefined ? {} : { breakpoints: request.breakpoints }),
221
+ });
222
+ const plan = planBreakpoints(collected.requested, budgetInfo.budget);
223
+ if (!plan.ok) {
224
+ const blocked = emptyReport(["断点超预算:" + plan.detail, budgetInfo.note, plan.suggestion], "没开会话:断点超预算(硬件断点 " + String(plan.used.code) + "/" + String(plan.budget.code)
225
+ + ",观察点 " + String(plan.used.data) + "/" + String(plan.budget.data) + ")");
226
+ return {
227
+ ...blocked,
228
+ breakpoints: quotaOf(plan.used.code, plan.budget.code),
229
+ watchpoints: quotaOf(plan.used.data, plan.budget.data),
230
+ };
231
+ }
148
232
  if (this.current !== null) {
149
233
  await this.stop("新的会话申请覆盖了旧会话");
150
234
  }
@@ -152,7 +236,7 @@ export class DebugSessionManager {
152
236
  const config = resolveSearchConfig(process.env, request.binDirs === undefined ? {} : { binDirs: request.binDirs });
153
237
  const openOcd = await resolveToolIn(subprocess, ["openocd"], config.binDirs);
154
238
  if (openOcd === null)
155
- return emptyReport(["找不到 openocd(先跑 stm32_env_probe)"], "没开会话:找不到 openocd");
239
+ return emptyReport(["找不到 openocd(先跑 stm32_doctor)"], "没开会话:找不到 openocd");
156
240
  // 符号表在这里解析:调用方(工具层、e2e、以后可能的 CLI)都不用自己找 .elf。
157
241
  const elfPath = request.elfPath !== undefined && request.elfPath !== ""
158
242
  ? request.elfPath
@@ -164,8 +248,15 @@ export class DebugSessionManager {
164
248
  argv.push("-f", toOpenOcdPath(projectConfig));
165
249
  }
166
250
  else {
167
- const fallback = defaultConfigs();
168
- argv.push("-f", fallback.interfaceConfig, "-f", fallback.targetConfig);
251
+ // 按 .ioc 的 Mcu.Family 选 target(与 stm32_flash / stm32_debug_run 同一套规则)。
252
+ const family = readProjectFamily(projectDir);
253
+ const choice = chooseOpenocdTarget(family);
254
+ if (choice.error !== "") {
255
+ return emptyReport([choice.error], "没开会话:" + (family === null ? "认不出芯片族" : "本机 openocd 没有 " + family.id + " 的 target 脚本"));
256
+ }
257
+ const live = await liveProbeChoice(subprocess);
258
+ const interfaceConfig = live.swdProbes.length > 0 ? live.cfg : "interface/cmsis-dap.cfg";
259
+ argv.push("-f", interfaceConfig, ...openocdTransportArgs(interfaceConfig), "-f", choice.targetConfig);
169
260
  }
170
261
  if (request.adapterSpeed !== undefined)
171
262
  argv.push("-c", "adapter speed " + String(request.adapterSpeed));
@@ -181,6 +272,8 @@ export class DebugSessionManager {
181
272
  projectDir,
182
273
  elfPath,
183
274
  port,
275
+ tclPort: 0,
276
+ configFile: projectConfig ?? "",
184
277
  handle,
185
278
  startedAt: this.now(),
186
279
  lastUsedAt: this.now(),
@@ -189,6 +282,9 @@ export class DebugSessionManager {
189
282
  logText: "",
190
283
  binDirs: config.binDirs,
191
284
  owner: request.owner ?? "",
285
+ breakpoints: quotaOf(plan.used.code, plan.budget.code),
286
+ watchpoints: quotaOf(plan.used.data, plan.budget.data),
287
+ mi: null,
192
288
  };
193
289
  const listening = await waitForListening(handle, 15_000, (text) => {
194
290
  session.logText += text + "\n";
@@ -197,11 +293,40 @@ export class DebugSessionManager {
197
293
  if (!listening.ok) {
198
294
  handle.terminate();
199
295
  await handle.waitForExit().catch(() => undefined);
200
- const tail = listening.text.split(/\r?\n/u).slice(-12).join("\n");
296
+ const tail = listening.text.split(/\r\n|\r|\n/u).slice(-12).join("\n");
201
297
  return emptyReport([/Error connecting DP|no device found|CMSIS-DAP/iu.test(listening.text) ? "openocd 连不上探针/芯片(见日志)" : "openocd 没有在 15 s 内监听 " + String(port), tail], "没开会话:openocd 起不来");
202
298
  }
299
+ // tcl 那行常排在 gdb 那行之后:等一小会儿把整个 collected 缓冲从头读一遍再解析
300
+ // (readFrom(0) 对收集式缓冲是随机读,不影响 waitForListening 已经消费掉的偏移)。
301
+ await sleep(TCL_PORT_SETTLE_MS);
302
+ const fullText = [
303
+ listening.text,
304
+ handle.collected.stdout?.readFrom(0).text ?? "",
305
+ handle.collected.stderr?.readFrom(0).text ?? "",
306
+ ].join("\n");
307
+ session.tclPort = parseListeningPorts(fullText).tcl;
203
308
  this.current = session;
204
309
  this.ensureSweeper();
310
+ // 真机踩过:openocd 打完 "Listening on port …" 之后仍可能因为探针 HID 错误当场退出
311
+ // (hid_write/WaitForSingleObject 0x3E5 + CMSIS-DAP CMD_INFO failed)。status() 只看内存里的
312
+ // 会话对象,于是后面每个工具都报「会话进行中」,实际全程失败。这里连一下 Tcl 口确认它真活着
313
+ // (探针可注入,单测用假进程替代)。
314
+ if (session.tclPort > 0) {
315
+ let alive = await this.aliveProbe(session.tclPort);
316
+ if (!alive) {
317
+ await sleep(300);
318
+ alive = await this.aliveProbe(session.tclPort);
319
+ }
320
+ if (!alive) {
321
+ const tail = [session.logText, handle.collected.stderr?.readFrom(0).text ?? ""]
322
+ .join("\n").split(/\r\n|\r|\n/u).filter((line) => line.trim() !== "").slice(-10).join("\n");
323
+ this.current = null;
324
+ this.stopSweeper();
325
+ handle.terminate();
326
+ await handle.waitForExit().catch(() => undefined);
327
+ return emptyReport(["会话的 openocd 起来后立刻没了:Tcl 端口 " + String(session.tclPort) + " 连不上(探针掉线?插拔探针后重试)", tail], "没开会话:openocd 起来后立刻退出");
328
+ }
329
+ }
205
330
  if (request.reset !== undefined && request.reset !== "none") {
206
331
  const resetResult = await this.eval({ commands: ["monitor reset " + request.reset], keepHalted: true, timeoutMs: 20_000 });
207
332
  if (!resetResult.ok) {
@@ -209,7 +334,35 @@ export class DebugSessionManager {
209
334
  return emptyReport(["复位失败:" + resetResult.output.split(/\r?\n/u).slice(-5).join(" ")], "没开会话:复位失败");
210
335
  }
211
336
  }
212
- return this.status();
337
+ const ready = this.status();
338
+ if (collected.requested.length === 0)
339
+ return ready;
340
+ // B4:把登记集合、预算来源、以及"断点不在 gdb 进程之间保留"这件事说清楚。
341
+ return {
342
+ ...ready,
343
+ message: ready.message + "\n· 断点预算已校验:登记 " + String(plan.used.code) + "/" + String(plan.budget.code)
344
+ + " 个硬件断点、观察点 " + String(plan.used.data) + "/" + String(plan.budget.data) + "(" + budgetInfo.note
345
+ + ");会话不跨 gdb 进程保存断点,实际停靠用 stm32_debug_eval 的 break <loc>",
346
+ };
347
+ }
348
+ /**
349
+ * 取这次会话该用的 gdb:会话起的目录优先,其次工具层配置,最后环境变量。
350
+ * eval 与 watch(采样/观察点)共用——换一台机器时不会出现"openocd 找得到、gdb 找不到"的错位。
351
+ */
352
+ async resolveGdb(session) {
353
+ const subprocess = this.subprocess;
354
+ if (subprocess === null)
355
+ return null;
356
+ const envConfig = resolveSearchConfig(process.env, {});
357
+ const searchDirs = [session.binDirs, this.binDirs, envConfig.binDirs];
358
+ for (const dirs of searchDirs) {
359
+ if (dirs.length === 0)
360
+ continue;
361
+ const gdb = await resolveToolIn(subprocess, ["gdb-multiarch", "arm-none-eabi-gdb"], dirs);
362
+ if (gdb !== null)
363
+ return gdb;
364
+ }
365
+ return null;
213
366
  }
214
367
  async eval(request) {
215
368
  const session = this.current;
@@ -227,16 +380,7 @@ export class DebugSessionManager {
227
380
  }
228
381
  // 用"起会话时那份"工具链目录:只读环境变量的话,调用方传了 binDirs 也会出现
229
382
  // "openocd 起来了、eval 却说缺 gdb"的错位(也便于离线单测给假目录)。
230
- const envConfig = resolveSearchConfig(process.env, {});
231
- const searchDirs = [session.binDirs, this.binDirs, envConfig.binDirs];
232
- let gdb = null;
233
- for (const dirs of searchDirs) {
234
- if (dirs.length === 0)
235
- continue;
236
- gdb = await resolveToolIn(this.subprocess, ["gdb-multiarch", "arm-none-eabi-gdb"], dirs);
237
- if (gdb !== null)
238
- break;
239
- }
383
+ const gdb = await this.resolveGdb(session);
240
384
  if (gdb === null) {
241
385
  return { ok: false, output: "", command: "", durationMs: 0, remainingMs: this.remainingMs(session), errors: ["找不到 gdb"], message: "没执行:缺 gdb" };
242
386
  }
@@ -249,6 +393,93 @@ export class DebugSessionManager {
249
393
  if (commands.length === 0) {
250
394
  return { ok: false, output: "", command: "", durationMs: 0, remainingMs: this.remainingMs(session), errors: ["没有命令"], message: "没执行:commands/expression 都是空的" };
251
395
  }
396
+ // B4:eval 里的 break/watch 也占硬件比较器(一次 gdb 会话里超了,gdb 只会报
397
+ // Cannot insert breakpoint),所以同样先对预算。
398
+ const evalBreakpoints = collectBreakpointRequests({ preCommands: commands });
399
+ if (evalBreakpoints.requested.length > 0) {
400
+ const evalBudget = resolveBreakpointBudget(session.projectDir);
401
+ const evalPlan = planBreakpoints(evalBreakpoints.requested, evalBudget.budget);
402
+ if (!evalPlan.ok) {
403
+ return {
404
+ ok: false, output: "", command: "", durationMs: 0, remainingMs: this.remainingMs(session),
405
+ errors: ["断点超预算:" + evalPlan.detail, evalBudget.note, evalPlan.suggestion],
406
+ message: "没执行:断点超预算(硬件断点 " + String(evalPlan.used.code) + "/" + String(evalPlan.budget.code)
407
+ + ",观察点 " + String(evalPlan.used.data) + "/" + String(evalPlan.budget.data) + ")",
408
+ };
409
+ }
410
+ }
411
+ // P3:优先走常驻 MI 会话(断点/变量/栈跨调用保留,也不再每次重连)。
412
+ // 连不上(比如 VS Code 正连着同一个 gdb server)就安静退回 -batch 老路径。
413
+ const mi = await this.ensureMi(session, gdb, request.timeoutMs ?? 30_000);
414
+ if (mi !== null) {
415
+ const miStartedAt = this.now();
416
+ const lines = [];
417
+ const miErrors = [];
418
+ let commandLine = "";
419
+ try {
420
+ for (const command of commands) {
421
+ const normalized = command.trim();
422
+ commandLine = (commandLine === "" ? "" : commandLine + " ;; ") + normalized;
423
+ // 目标在跑时 gdb 不回命令(-exec-next、连 console 的 break 都会卡到超时),先打断。
424
+ if (mi.targetRunning) {
425
+ const interrupted = await mi.ensureHalted(request.timeoutMs ?? 30_000);
426
+ if (interrupted)
427
+ lines.push("(目标在跑,已用 -exec-interrupt 停下)");
428
+ }
429
+ // continue / next / step / si / ni:MI 的 -exec-* 在 ^running 就返回,真正"停在哪"要等 *stopped。
430
+ const isContinue = /^(?:c|cont|continue)$/u.test(normalized);
431
+ const stepCommand = steppingCommandFor(normalized);
432
+ if (isContinue || stepCommand !== null) {
433
+ const timeout = request.timeoutMs ?? 30_000;
434
+ const sentRecord = isContinue
435
+ ? await mi.continueTarget(timeout)
436
+ : (await mi.send(stepCommand, timeout)).record;
437
+ if (sentRecord.class !== "running") {
438
+ lines.push(normalized + ":没有跑起来(" + String(sentRecord.data["msg"] ?? sentRecord.class) + ")");
439
+ continue;
440
+ }
441
+ const waitMs = Math.min(timeout, MI_STOP_WAIT_MS);
442
+ try {
443
+ const stopped = await mi.waitStopped(waitMs);
444
+ const keepHint = request.keepHalted === true ? "" : "(本次 eval 结束会按默认再 resume;要停在那里用 keepHalted=true)";
445
+ lines.push(normalized + ":已停下 —— " + formatStopLocation(stopped) + keepHint);
446
+ }
447
+ catch {
448
+ lines.push(normalized + ":目标已继续运行(" + String(waitMs) + " ms 内没命中断点);下条命令会先 -exec-interrupt 把它停下");
449
+ }
450
+ continue;
451
+ }
452
+ const result = await mi.console(normalized, request.timeoutMs ?? 30_000);
453
+ const text = result.text.trimEnd();
454
+ if (text !== "")
455
+ lines.push(text);
456
+ if (result.record.class === "error") {
457
+ miErrors.push("命令失败:" + normalized + ":" + String(result.record.data["msg"] ?? ""));
458
+ }
459
+ }
460
+ if (request.keepHalted !== true)
461
+ await mi.console("monitor resume", request.timeoutMs ?? 30_000);
462
+ }
463
+ catch (error) {
464
+ miErrors.push("MI 会话出错:" + (error instanceof Error ? error.message : String(error)));
465
+ }
466
+ session.lastUsedAt = this.now();
467
+ const miStillActive = this.current === session;
468
+ if (!miStillActive)
469
+ miErrors.push("会话在本次 eval 期间已关闭");
470
+ const miOutput = lines.join("\n").trim();
471
+ return {
472
+ ok: miErrors.length === 0,
473
+ output: miOutput,
474
+ command: "gdb --interpreter=mi2(常驻): " + commandLine,
475
+ durationMs: this.now() - miStartedAt,
476
+ remainingMs: miStillActive ? this.remainingMs(session) : 0,
477
+ errors: miErrors,
478
+ message: miErrors.length === 0
479
+ ? "执行完成(MI 常驻," + String(this.now() - miStartedAt) + " ms)"
480
+ : "执行有问题:" + miErrors[0],
481
+ };
482
+ }
252
483
  const argv = [gdb, "-q", "-batch", "-nx", "-ex", "set confirm off", "-ex", "set pagination off"];
253
484
  if (session.elfPath !== "" && existsSync(session.elfPath))
254
485
  argv.push("-ex", "file " + toOpenOcdPath(session.elfPath));
@@ -288,6 +519,32 @@ export class DebugSessionManager {
288
519
  message: errors.length === 0 ? "执行完成(" + String(this.now() - startedAt) + " ms)" : "执行有问题:" + errors[0],
289
520
  };
290
521
  }
522
+ /**
523
+ * P3:按需起一个常驻 gdb MI 会话(连的是本会话 openocd 的 gdb server)。
524
+ * 失败返回 null —— 调用方退回每次 gdb -batch 的老路径,本次 eval 照样能用。
525
+ */
526
+ async ensureMi(session, gdb, timeoutMs) {
527
+ if (session.mi !== null && session.mi.alive)
528
+ return session.mi;
529
+ session.mi = null;
530
+ try {
531
+ const mi = await MiSession.start({
532
+ gdb,
533
+ port: session.port,
534
+ ...(session.elfPath === "" ? {} : { elfPath: session.elfPath }),
535
+ cwd: session.projectDir,
536
+ timeoutMs: Math.max(3000, Math.min(timeoutMs, 30_000)),
537
+ });
538
+ session.mi = mi;
539
+ // 新 MI 进程里没有任何观察点:登记表里那些编号指向的旧进程已经没了,
540
+ // 留着编号会让人以为还在拦(delete N 也删不掉别的东西),标成失效更诚实。
541
+ markWatchpointsStale(watchState, "gdb MI 会话重建,观察点已随旧进程丢失:重新 action=add");
542
+ return mi;
543
+ }
544
+ catch {
545
+ return null;
546
+ }
547
+ }
291
548
  /**
292
549
  * 借正在跑的调试会话(它已经占着 openocd + CMSIS-DAP)读 32 位字。
293
550
  *
@@ -375,6 +632,245 @@ export class DebugSessionManager {
375
632
  : "读失败:" + (errors[0] ?? "未知原因"),
376
633
  };
377
634
  }
635
+ /**
636
+ * P3:一次值采样(stm32_watch action=sample)。
637
+ *
638
+ * 语义:目标在跑就先 -exec-interrupt 停住(读变量必须在停止态),逐项 mi.evaluate,
639
+ * 再按原状态放回去;原本就停着的不会被偷偷 resume。
640
+ * MI 起不来(VS Code 正连着同一个 gdb server)时退回一次性 gdb -batch + 标记解析。
641
+ */
642
+ async sampleWatches(request = {}) {
643
+ const startedAt = this.now();
644
+ const session = this.current;
645
+ const timeout = request.timeoutMs ?? 20_000;
646
+ const entries = sampledWatches(watchState);
647
+ const fail = (errors, message) => ({
648
+ ok: false, halted: false, resumed: false, samples: [], durationMs: this.now() - startedAt, errors, message,
649
+ });
650
+ if (session === null)
651
+ return fail(["没有调试会话(先 stm32_debug_session;短任务用 stm32_debug_run)"], "没采样:没有调试会话");
652
+ if (entries.length === 0)
653
+ return fail(["还没有值监视项:先 action=add 登记表达式"], "没采样:没有登记值监视项");
654
+ const gdb = await this.resolveGdb(session);
655
+ if (gdb === null)
656
+ return fail(["找不到 gdb"], "没采样:缺 gdb");
657
+ const samples = [];
658
+ const errors = [];
659
+ let halted = false;
660
+ let resumed = false;
661
+ const mi = await this.ensureMi(session, gdb, timeout);
662
+ /** MI 路径下才知道目标原本跑没跑:用来区分「采不动」和「本来就在停着」。 */
663
+ let targetWasRunning = false;
664
+ if (mi !== null) {
665
+ try {
666
+ const wasRunning = mi.targetRunning;
667
+ targetWasRunning = wasRunning;
668
+ if (wasRunning)
669
+ halted = await mi.ensureHalted(timeout);
670
+ for (const entry of entries) {
671
+ const previous = entry.lastValue;
672
+ let value = "";
673
+ let error = "";
674
+ try {
675
+ value = (await mi.evaluate(entry.expression, timeout)).trim();
676
+ }
677
+ catch (caught) {
678
+ error = caught instanceof Error ? caught.message : String(caught);
679
+ }
680
+ const now = this.now();
681
+ recordWatchSample(entry, value, error, now);
682
+ samples.push({
683
+ id: entry.id, expression: entry.expression, kind: entry.kind,
684
+ value, previous, delta: formatWatchDelta(previous, value), ok: error === "", error, lastAt: now,
685
+ });
686
+ }
687
+ if (wasRunning && request.resume !== false) {
688
+ await mi.console("monitor resume", timeout);
689
+ resumed = true;
690
+ }
691
+ }
692
+ catch (caught) {
693
+ errors.push("采样出错:" + (caught instanceof Error ? caught.message : String(caught)));
694
+ }
695
+ session.lastUsedAt = this.now();
696
+ }
697
+ else {
698
+ // MI 起不来时退回一次性 gdb:每项前面打标记,结构体/数组的多行输出也能对上号。
699
+ const commands = [];
700
+ for (const entry of entries)
701
+ commands.push("echo ===DSH:W" + String(entry.id) + "===", "print " + entry.expression);
702
+ const evaluated = await this.eval({
703
+ commands,
704
+ timeoutMs: timeout,
705
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
706
+ });
707
+ errors.push(...evaluated.errors);
708
+ const parsed = parseWatchMarkers(evaluated.output);
709
+ const now = this.now();
710
+ for (const entry of entries) {
711
+ const hit = parsed.get(entry.id) ?? { value: "", error: "没拿到这条的输出" };
712
+ const previous = entry.lastValue;
713
+ recordWatchSample(entry, hit.value, hit.error, now);
714
+ samples.push({
715
+ id: entry.id, expression: entry.expression, kind: entry.kind,
716
+ value: hit.value, previous, delta: formatWatchDelta(previous, hit.value), ok: hit.error === "", error: hit.error, lastAt: now,
717
+ });
718
+ }
719
+ }
720
+ const failed = samples.filter((sample) => !sample.ok);
721
+ const ok = errors.length === 0 && failed.length === 0;
722
+ const resumedNote = mi !== null ? formatWatchSampleNote(halted, resumed, targetWasRunning) : "";
723
+ return {
724
+ ok, halted, resumed, samples, durationMs: this.now() - startedAt, errors,
725
+ message: ok
726
+ ? "采样 " + String(samples.length) + " 项" + resumedNote
727
+ : "采样有问题:" + String(failed.length) + " 项失败",
728
+ };
729
+ }
730
+ /**
731
+ * P3:装硬件观察点(stm32_watch action=add,kind=write/read/access)。
732
+ *
733
+ * 先做纯校验(表达式、重复、F1 的 4 个数据比较器预算),一个都不通过就不碰目标;
734
+ * 真正装的时候目标必须停着(gdb 写比较器),装完按原状态放回去。
735
+ */
736
+ async addWatchpoints(request) {
737
+ const startedAt = this.now();
738
+ const session = this.current;
739
+ const timeout = request.timeoutMs ?? 20_000;
740
+ const budgetInfo = resolveBreakpointBudget(session === null ? "" : session.projectDir);
741
+ const quota = () => quotaOf(hardwareWatchpoints(watchState).length, budgetInfo.budget.data);
742
+ const fail = (errors, notes = []) => ({
743
+ ok: false, added: [], resumed: false, budget: quota(), durationMs: this.now() - startedAt, errors, notes,
744
+ message: "没装观察点:" + (errors[0] ?? "未知原因"),
745
+ });
746
+ if (session === null)
747
+ return fail(["没有调试会话(先 stm32_debug_session)"]);
748
+ if (request.entries.length === 0)
749
+ return fail(["没有表达式"]);
750
+ const normalized = [];
751
+ for (const item of request.entries) {
752
+ const expression = normalizeWatchExpression(item.expression);
753
+ if (expression === null)
754
+ return fail(["表达式不合法:" + JSON.stringify(item.expression)]);
755
+ if (watchState.entries.some((entry) => entry.expression === expression && entry.kind === item.kind)) {
756
+ return fail(["已经登记过:" + expression + "(" + WATCH_KIND_LABELS[item.kind] + ")"]);
757
+ }
758
+ normalized.push({ expression, kind: item.kind });
759
+ }
760
+ const used = hardwareWatchpoints(watchState).length;
761
+ if (used + normalized.length > budgetInfo.budget.data) {
762
+ return fail([
763
+ "观察点超预算:要用 " + String(used + normalized.length) + " 个,芯片上限 " + String(budgetInfo.budget.data) + "(已用 " + String(used) + ")",
764
+ budgetInfo.note,
765
+ "先 remove 掉不用的观察点;F1 的观察点与硬件断点共用比较器",
766
+ ]);
767
+ }
768
+ const gdb = await this.resolveGdb(session);
769
+ if (gdb === null)
770
+ return fail(["找不到 gdb"]);
771
+ const mi = await this.ensureMi(session, gdb, timeout);
772
+ if (mi === null)
773
+ return fail(["常驻 MI 会话起不来(VS Code 可能正连着同一个 gdb server):观察点必须装在 gdb 里"]);
774
+ const added = [];
775
+ const notes = [];
776
+ const errors = [];
777
+ let resumed = false;
778
+ try {
779
+ const wasRunning = mi.targetRunning;
780
+ if (wasRunning)
781
+ await mi.ensureHalted(timeout);
782
+ for (const item of normalized) {
783
+ const command = item.kind === "write" ? "watch " : (item.kind === "read" ? "rwatch " : "awatch ");
784
+ const result = await mi.console(command + item.expression, timeout);
785
+ const text = result.text.trim();
786
+ if (result.record.class === "error") {
787
+ errors.push("装观察点失败:" + item.expression + ":" + String(result.record.data["msg"] ?? text));
788
+ continue;
789
+ }
790
+ const number = parseWatchpointNumber(text);
791
+ if (number === null) {
792
+ const tail = text === "" ? "空" : text.split(/\r\n|\r|\n/u).slice(-3).join(" ");
793
+ errors.push("没解析出观察点编号:" + item.expression + "(gdb 回:" + tail + ")");
794
+ continue;
795
+ }
796
+ if (!isHardwareWatchpoint(text))
797
+ notes.push(item.expression + " 装成了软件观察点(硬件比较器不够,gdb 退化成单步,会拖慢目标)");
798
+ const registered = registerWatch(watchState, item.expression, item.kind, this.now(), number);
799
+ if (registered.entry === null) {
800
+ errors.push(registered.error);
801
+ continue;
802
+ }
803
+ added.push(registered.entry);
804
+ }
805
+ if (wasRunning) {
806
+ await mi.console("monitor resume", timeout);
807
+ resumed = true;
808
+ }
809
+ session.lastUsedAt = this.now();
810
+ }
811
+ catch (caught) {
812
+ errors.push("装观察点出错:" + (caught instanceof Error ? caught.message : String(caught)));
813
+ }
814
+ session.watchpoints = quotaOf(hardwareWatchpoints(watchState).length, budgetInfo.budget.data);
815
+ const ok = errors.length === 0;
816
+ return {
817
+ ok, added, resumed, budget: quota(), durationMs: this.now() - startedAt, errors, notes,
818
+ message: ok
819
+ ? "装了 " + String(added.length) + " 个观察点(硬件 " + String(quota().used) + "/" + String(quota().limit) + ")"
820
+ : "装观察点有问题:" + errors[0],
821
+ };
822
+ }
823
+ /** P3:删观察点(先删登记项,再让 gdb delete 对应编号;目标在跑就先停)。 */
824
+ async removeWatchpoints(ids) {
825
+ const startedAt = this.now();
826
+ const session = this.current;
827
+ const budgetInfo = resolveBreakpointBudget(session === null ? "" : session.projectDir);
828
+ const quota = () => quotaOf(hardwareWatchpoints(watchState).length, budgetInfo.budget.data);
829
+ const removed = removeWatchByIds(watchState, ids);
830
+ if (removed.length === 0) {
831
+ return { ok: false, removed: [], resumed: false, budget: quota(), durationMs: this.now() - startedAt, errors: ["没有匹配的 id"], message: "没删:没有匹配的 id" };
832
+ }
833
+ const errors = [];
834
+ let resumed = false;
835
+ const withNumber = removed.filter((entry) => entry.kind !== "value" && entry.gdbNumber > 0);
836
+ if (withNumber.length > 0 && session !== null) {
837
+ const gdb = await this.resolveGdb(session);
838
+ const mi = gdb === null ? null : await this.ensureMi(session, gdb, 20_000);
839
+ if (mi === null) {
840
+ errors.push("旧 gdb 已经不在了(观察点随进程消失):登记项已删,芯片侧不用再动");
841
+ }
842
+ else {
843
+ try {
844
+ const wasRunning = mi.targetRunning;
845
+ if (wasRunning)
846
+ await mi.ensureHalted(20_000);
847
+ for (const entry of withNumber) {
848
+ const result = await mi.console("delete " + String(entry.gdbNumber), 20_000);
849
+ if (result.record.class === "error") {
850
+ errors.push("删观察点失败:#" + String(entry.id) + "(gdb #" + String(entry.gdbNumber) + "):" + String(result.record.data["msg"] ?? ""));
851
+ }
852
+ }
853
+ if (wasRunning) {
854
+ await mi.console("monitor resume", 20_000);
855
+ resumed = true;
856
+ }
857
+ session.lastUsedAt = this.now();
858
+ }
859
+ catch (caught) {
860
+ errors.push("删观察点出错:" + (caught instanceof Error ? caught.message : String(caught)));
861
+ }
862
+ }
863
+ }
864
+ if (session !== null)
865
+ session.watchpoints = quotaOf(hardwareWatchpoints(watchState).length, budgetInfo.budget.data);
866
+ const ok = errors.length === 0;
867
+ return {
868
+ ok, removed, resumed, budget: quota(), durationMs: this.now() - startedAt, errors,
869
+ message: ok
870
+ ? "删了 " + String(removed.length) + " 项(硬件观察点还剩 " + String(quota().used) + "/" + String(quota().limit) + ")"
871
+ : "删了 " + String(removed.length) + " 项,但有 " + String(errors.length) + " 个问题:" + errors[0],
872
+ };
873
+ }
378
874
  /**
379
875
  * 关会话。options.requireOwner 给定时,只有 owner 对得上才关(审计 A9)。
380
876
  *
@@ -393,18 +889,76 @@ export class DebugSessionManager {
393
889
  }
394
890
  this.current = null;
395
891
  this.stopSweeper();
892
+ // 观察点住在 gdb 进程里:会话一关就全没了,登记表必须跟着清,
893
+ // 否则下次会话里 action=list 会报一堆已经不存在的观察点。
894
+ resetWatchState();
396
895
  if (session === null)
397
896
  return { ok: true, stopped: false, message: "本来就没有会话(" + reason + ")" };
897
+ // 先让 openocd 自己 shutdown:直接 kill 时它来不及给探针发断开命令,
898
+ // CMSIS-DAP 固件会被留在「半连接」状态,下一次 CMD_INFO 直接超时(实测踩过两次)。
899
+ // P3:先收掉常驻 gdb(它握着 gdb server 端口),再让 openocd shutdown。
900
+ if (session.mi !== null) {
901
+ await session.mi.stop().catch(() => undefined);
902
+ session.mi = null;
903
+ }
904
+ await requestOpenocdShutdown(session.tclPort, 800);
905
+ await Promise.race([session.handle.waitForExit().catch(() => undefined), sleep(1200)]);
398
906
  session.handle.terminate();
399
907
  await Promise.race([session.handle.waitForExit().catch(() => undefined), sleep(3000)]);
400
908
  return { ok: true, stopped: true, message: "会话已关闭(" + reason + "),探针已释放" };
401
909
  }
910
+ /**
911
+ * 进程退出前的尽力清理(B3 第 4 条):exit 事件里不能 await,只发终止信号。
912
+ * 返回是否真的收掉了一个会话。
913
+ */
914
+ terminateSync() {
915
+ const session = this.current;
916
+ this.current = null;
917
+ this.stopSweeper();
918
+ if (session === null)
919
+ return false;
920
+ if (session.mi !== null) {
921
+ // exit 阶段不能 await:尽力发退出命令,随后连同 openocd 一起终止。
922
+ void session.mi.stop(500).catch(() => undefined);
923
+ session.mi = null;
924
+ }
925
+ try {
926
+ session.handle.terminate();
927
+ }
928
+ catch {
929
+ // 进程可能已经没了;exit 阶段不能抛。
930
+ }
931
+ return true;
932
+ }
402
933
  async closeAll(reason) {
403
934
  await this.stop(reason);
404
935
  }
405
936
  }
406
937
  /** 进程内单例:工具、turn/end 监听、dispose 共用同一个会话。 */
407
938
  export const debugSessions = new DebugSessionManager();
939
+ /** 通过 Tcl 口让 openocd 自己 shutdown(探针能收到正常的断开序列)。失败就交给 kill 兜底。 */
940
+ function requestOpenocdShutdown(port, timeoutMs) {
941
+ if (!Number.isFinite(port) || port <= 0)
942
+ return Promise.resolve();
943
+ return new Promise((resolve) => {
944
+ const socket = net.connect({ host: "127.0.0.1", port });
945
+ let settled = false;
946
+ const done = () => {
947
+ if (settled)
948
+ return;
949
+ settled = true;
950
+ socket.destroy();
951
+ resolve();
952
+ };
953
+ socket.setTimeout(timeoutMs, done);
954
+ socket.once("connect", () => {
955
+ socket.write("shutdown\n");
956
+ setTimeout(done, 150);
957
+ });
958
+ socket.once("error", done);
959
+ socket.once("close", done);
960
+ });
961
+ }
408
962
  /** 需要独占探针的动作(build / flash / generate / debug_run)动手前调用。 */
409
963
  export async function releaseProbeFor(reason) {
410
964
  if (!debugSessions.isActive())