dsh-stm32 0.1.3 → 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 (221) hide show
  1. package/README.md +52 -38
  2. package/README_EN.md +44 -33
  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 +37 -35
  133. package/lib/data/chips.js +3 -3
  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 +239 -18
  137. package/lib/data/db-presets.js +252 -0
  138. package/lib/data/device-facts.js +99 -26
  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 +15 -14
  148. package/lib/data/svd.js +32 -16
  149. package/lib/data/toolchain-config.js +0 -14
  150. package/lib/engine/assets.js +191 -456
  151. package/lib/engine/breakpoints.js +66 -11
  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 +423 -17
  161. package/lib/engine/debug.js +25 -6
  162. package/lib/engine/doctor.js +160 -17
  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 +290 -21
  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 +1244 -60
  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 +25 -6
  177. package/lib/engine/probe-session.js +50 -14
  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 +101 -40
  183. package/lib/engine/regs.js +41 -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 +188 -30
  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 +4 -2
  192. package/lib/skill/stm32-workflow.js +2 -2
  193. package/lib/tools/assets.js +39 -108
  194. package/lib/tools/cache.js +2 -2
  195. package/lib/tools/debug-session.js +2 -2
  196. package/lib/tools/doctor.js +55 -5
  197. package/lib/tools/firmware-install.js +31 -6
  198. package/lib/tools/flash.js +32 -4
  199. package/lib/tools/generate.js +22 -0
  200. package/lib/tools/ioc-inspect.js +1 -1
  201. package/lib/tools/ioc-plan.js +56 -2
  202. package/lib/tools/ioc-verify.js +237 -0
  203. package/lib/tools/project-create.js +41 -5
  204. package/lib/tools/regs.js +8 -8
  205. package/lib/tools/route-plan.js +1 -1
  206. package/lib/tools/rtt.js +157 -34
  207. package/lib/tools/watch.js +256 -0
  208. package/package.json +5 -4
  209. package/templates/openocd/stm32c0x.cfg +83 -0
  210. package/templates/openocd/stm32u0x.cfg +64 -0
  211. package/templates/register/CMakeLists.txt +2 -2
  212. package/templates/register/Core/Inc/rtt.h +37 -2
  213. package/templates/register/Core/Src/main.c +17 -25
  214. package/templates/register/Core/Src/rtt.c +85 -9
  215. package/templates/scaffold/RTT.md +6 -2
  216. package/templates/scaffold/STM32F103XX_FLASH.ld +3 -0
  217. package/templates/scaffold/openocd.cfg +5 -3
  218. package/templates/scaffold/vscode/launch.json +8 -4
  219. package/docs/development-notes.md +0 -2487
  220. package/docs/dsh-stm32-plugin-/350/247/204/346/240/274.md +0 -673
  221. package/docs/logic-audit.md +0 -607
@@ -14,8 +14,12 @@ import { existsSync } from "node:fs";
14
14
  import net from "node:net";
15
15
  import { resolveSearchConfig } from "../data/search-roots.js";
16
16
  import { F1_BREAKPOINT_BUDGET, collectBreakpointRequests, planBreakpoints, quotaOf, resolveBreakpointBudget } from "./breakpoints.js";
17
- import { pickPort, resolveElfPath } from "./debug.js";
18
- import { defaultConfigs, findProjectConfig, toOpenOcdPath } from "./flash.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";
19
23
  import { resolveToolIn } from "./probe.js";
20
24
  import { runCapture } from "./subprocess-runner.js";
21
25
  import { waitForListening } from "./debug.js";
@@ -30,6 +34,8 @@ const SWEEP_MS = 5_000;
30
34
  * (读丢只是慢一点:快路径会回退到 gdb)。
31
35
  */
32
36
  const TCL_PORT_SETTLE_MS = 120;
37
+ /** continue/step 之后等 *stopped 的窗口:命中断点就报停点,纯主循环跑就最多等这么久。 */
38
+ const MI_STOP_WAIT_MS = 3_000;
33
39
  const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
34
40
  /** 把 "0x4001100c" / "4001100C" 统一成 8 位小写 0x 形式;解析不了返回 null。 */
35
41
  export function normalizeHexAddress(text) {
@@ -123,15 +129,27 @@ function emptyReport(errors, message) {
123
129
  export class DebugSessionManager {
124
130
  subprocess = null;
125
131
  binDirs = [];
132
+ /** 会话存活探测(默认连 openocd 的 Tcl 端口;单测用假进程替代)。 */
133
+ aliveProbe = (port) => isPortBusy(port, 500);
126
134
  current = null;
127
135
  timer = null;
128
136
  now;
129
137
  constructor(options = {}) {
130
138
  this.now = options.now ?? (() => Date.now());
131
139
  }
132
- configure(subprocess, binDirs = []) {
140
+ /**
141
+ * @param aliveProbe 起会话后探测「openocd 还活着吗」(默认连 Tcl 端口;单测注入假探针)。
142
+ * 真机踩过:探针 HID 掉线时 openocd 打完 Listening 就退出,而 status() 只看内存里的会话对象。
143
+ */
144
+ configure(subprocess, binDirs = [], aliveProbe) {
133
145
  this.subprocess = subprocess;
134
146
  this.binDirs = binDirs;
147
+ if (aliveProbe !== undefined)
148
+ this.aliveProbe = aliveProbe;
149
+ }
150
+ /** 单测注入用:替换「会话还活着吗」的探测(见 configure 的 aliveProbe)。 */
151
+ setAliveProbe(probe) {
152
+ this.aliveProbe = probe;
135
153
  }
136
154
  isActive() {
137
155
  return this.current !== null;
@@ -218,7 +236,7 @@ export class DebugSessionManager {
218
236
  const config = resolveSearchConfig(process.env, request.binDirs === undefined ? {} : { binDirs: request.binDirs });
219
237
  const openOcd = await resolveToolIn(subprocess, ["openocd"], config.binDirs);
220
238
  if (openOcd === null)
221
- return emptyReport(["找不到 openocd(先跑 stm32_env_probe)"], "没开会话:找不到 openocd");
239
+ return emptyReport(["找不到 openocd(先跑 stm32_doctor)"], "没开会话:找不到 openocd");
222
240
  // 符号表在这里解析:调用方(工具层、e2e、以后可能的 CLI)都不用自己找 .elf。
223
241
  const elfPath = request.elfPath !== undefined && request.elfPath !== ""
224
242
  ? request.elfPath
@@ -230,8 +248,15 @@ export class DebugSessionManager {
230
248
  argv.push("-f", toOpenOcdPath(projectConfig));
231
249
  }
232
250
  else {
233
- const fallback = defaultConfigs();
234
- 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);
235
260
  }
236
261
  if (request.adapterSpeed !== undefined)
237
262
  argv.push("-c", "adapter speed " + String(request.adapterSpeed));
@@ -259,6 +284,7 @@ export class DebugSessionManager {
259
284
  owner: request.owner ?? "",
260
285
  breakpoints: quotaOf(plan.used.code, plan.budget.code),
261
286
  watchpoints: quotaOf(plan.used.data, plan.budget.data),
287
+ mi: null,
262
288
  };
263
289
  const listening = await waitForListening(handle, 15_000, (text) => {
264
290
  session.logText += text + "\n";
@@ -267,7 +293,7 @@ export class DebugSessionManager {
267
293
  if (!listening.ok) {
268
294
  handle.terminate();
269
295
  await handle.waitForExit().catch(() => undefined);
270
- 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");
271
297
  return emptyReport([/Error connecting DP|no device found|CMSIS-DAP/iu.test(listening.text) ? "openocd 连不上探针/芯片(见日志)" : "openocd 没有在 15 s 内监听 " + String(port), tail], "没开会话:openocd 起不来");
272
298
  }
273
299
  // tcl 那行常排在 gdb 那行之后:等一小会儿把整个 collected 缓冲从头读一遍再解析
@@ -281,6 +307,26 @@ export class DebugSessionManager {
281
307
  session.tclPort = parseListeningPorts(fullText).tcl;
282
308
  this.current = session;
283
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
+ }
284
330
  if (request.reset !== undefined && request.reset !== "none") {
285
331
  const resetResult = await this.eval({ commands: ["monitor reset " + request.reset], keepHalted: true, timeoutMs: 20_000 });
286
332
  if (!resetResult.ok) {
@@ -299,6 +345,25 @@ export class DebugSessionManager {
299
345
  + ");会话不跨 gdb 进程保存断点,实际停靠用 stm32_debug_eval 的 break <loc>",
300
346
  };
301
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;
366
+ }
302
367
  async eval(request) {
303
368
  const session = this.current;
304
369
  const startedAt = this.now();
@@ -315,16 +380,7 @@ export class DebugSessionManager {
315
380
  }
316
381
  // 用"起会话时那份"工具链目录:只读环境变量的话,调用方传了 binDirs 也会出现
317
382
  // "openocd 起来了、eval 却说缺 gdb"的错位(也便于离线单测给假目录)。
318
- const envConfig = resolveSearchConfig(process.env, {});
319
- const searchDirs = [session.binDirs, this.binDirs, envConfig.binDirs];
320
- let gdb = null;
321
- for (const dirs of searchDirs) {
322
- if (dirs.length === 0)
323
- continue;
324
- gdb = await resolveToolIn(this.subprocess, ["gdb-multiarch", "arm-none-eabi-gdb"], dirs);
325
- if (gdb !== null)
326
- break;
327
- }
383
+ const gdb = await this.resolveGdb(session);
328
384
  if (gdb === null) {
329
385
  return { ok: false, output: "", command: "", durationMs: 0, remainingMs: this.remainingMs(session), errors: ["找不到 gdb"], message: "没执行:缺 gdb" };
330
386
  }
@@ -352,6 +408,78 @@ export class DebugSessionManager {
352
408
  };
353
409
  }
354
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
+ }
355
483
  const argv = [gdb, "-q", "-batch", "-nx", "-ex", "set confirm off", "-ex", "set pagination off"];
356
484
  if (session.elfPath !== "" && existsSync(session.elfPath))
357
485
  argv.push("-ex", "file " + toOpenOcdPath(session.elfPath));
@@ -391,6 +519,32 @@ export class DebugSessionManager {
391
519
  message: errors.length === 0 ? "执行完成(" + String(this.now() - startedAt) + " ms)" : "执行有问题:" + errors[0],
392
520
  };
393
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
+ }
394
548
  /**
395
549
  * 借正在跑的调试会话(它已经占着 openocd + CMSIS-DAP)读 32 位字。
396
550
  *
@@ -478,6 +632,245 @@ export class DebugSessionManager {
478
632
  : "读失败:" + (errors[0] ?? "未知原因"),
479
633
  };
480
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
+ }
481
874
  /**
482
875
  * 关会话。options.requireOwner 给定时,只有 owner 对得上才关(审计 A9)。
483
876
  *
@@ -496,10 +889,18 @@ export class DebugSessionManager {
496
889
  }
497
890
  this.current = null;
498
891
  this.stopSweeper();
892
+ // 观察点住在 gdb 进程里:会话一关就全没了,登记表必须跟着清,
893
+ // 否则下次会话里 action=list 会报一堆已经不存在的观察点。
894
+ resetWatchState();
499
895
  if (session === null)
500
896
  return { ok: true, stopped: false, message: "本来就没有会话(" + reason + ")" };
501
897
  // 先让 openocd 自己 shutdown:直接 kill 时它来不及给探针发断开命令,
502
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
+ }
503
904
  await requestOpenocdShutdown(session.tclPort, 800);
504
905
  await Promise.race([session.handle.waitForExit().catch(() => undefined), sleep(1200)]);
505
906
  session.handle.terminate();
@@ -516,6 +917,11 @@ export class DebugSessionManager {
516
917
  this.stopSweeper();
517
918
  if (session === null)
518
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
+ }
519
925
  try {
520
926
  session.handle.terminate();
521
927
  }
@@ -10,8 +10,9 @@ import { createConnection } from "node:net";
10
10
  import { dirname, isAbsolute, resolve } from "node:path";
11
11
  import { resolveSearchConfig } from "../data/search-roots.js";
12
12
  import { detectBuildDir, elfSelectionNote, findElf } from "./build.js";
13
- import { usbDiagnosis } from "./doctor.js";
14
- import { defaultConfigs, findProjectConfig, quoteForDisplay, toOpenOcdPath } from "./flash.js";
13
+ import { liveProbeChoice, openocdTransportArgs, usbDiagnosis } from "./doctor.js";
14
+ import { chooseOpenocdTarget, readProjectFamily } from "../data/family.js";
15
+ import { findProjectConfig, quoteForDisplay, toOpenOcdPath } from "./flash.js";
15
16
  import { collectBreakpointRequests, planBreakpoints, quotaOf, resolveBreakpointBudget } from "./breakpoints.js";
16
17
  import { classifyProbeFailure, firstProblemLine, probeMissingLines, usbNoteFor } from "./probe-error.js";
17
18
  import { resolveToolIn } from "./probe.js";
@@ -186,7 +187,7 @@ export async function runDebugRun(subprocess, request) {
186
187
  const gdb = await resolveToolIn(subprocess, ["gdb-multiarch", "arm-none-eabi-gdb"], config.binDirs);
187
188
  if (openOcd === null || gdb === null) {
188
189
  errors.push(openOcd === null ? "找不到 openocd" : "找不到 gdb(gdb-multiarch 或 arm-none-eabi-gdb)");
189
- return { ...empty, elfPath, message: "没调试:缺工具链(先跑 stm32_env_probe)", durationMs: Date.now() - startedAt };
190
+ return { ...empty, elfPath, message: "没调试:缺工具链(先跑 stm32_doctor)", durationMs: Date.now() - startedAt };
190
191
  }
191
192
  const port = request.port ?? (await pickPort(3333));
192
193
  if (request.port === undefined && port !== 3333)
@@ -197,9 +198,27 @@ export async function runDebugRun(subprocess, request) {
197
198
  openOcdArgs.push("-f", toOpenOcdPath(projectConfig));
198
199
  }
199
200
  else {
200
- const fallback = defaultConfigs();
201
- openOcdArgs.push("-f", request.interfaceConfig ?? fallback.interfaceConfig, "-f", request.targetConfig ?? fallback.targetConfig);
202
- notes.push("工程里没有 openocd 配置文件,回退到 CMSIS-DAP + stm32f1x");
201
+ // 按 .ioc 的 Mcu.Family 选 target:换族之后不能再用 F1 的脚本硬连。
202
+ const family = readProjectFamily(projectDir);
203
+ const choice = chooseOpenocdTarget(family);
204
+ if (choice.error !== "") {
205
+ errors.push(choice.error);
206
+ return {
207
+ ...empty,
208
+ elfPath,
209
+ message: "没调试:" + (family === null ? "认不出芯片族" : "本机 openocd 没有 " + family.id + " 的 target 脚本"),
210
+ durationMs: Date.now() - startedAt,
211
+ };
212
+ }
213
+ const live = request.interfaceConfig === undefined ? await liveProbeChoice(subprocess, request.signal) : null;
214
+ const interfaceConfig = request.interfaceConfig ?? (live !== null && live.swdProbes.length > 0 ? live.cfg : "interface/cmsis-dap.cfg");
215
+ const targetConfig = request.targetConfig ?? choice.targetConfig;
216
+ openOcdArgs.push("-f", interfaceConfig, ...openocdTransportArgs(interfaceConfig), "-f", targetConfig);
217
+ notes.push("工程里没有 openocd 配置文件,回退到 " + interfaceConfig + " + " + targetConfig);
218
+ if (family !== null)
219
+ notes.push("芯片族按 .ioc 判定:" + family.id + "(内核 " + family.core + ")");
220
+ if (choice.note !== "")
221
+ notes.push(choice.note);
203
222
  }
204
223
  if (request.adapterSpeed !== undefined)
205
224
  openOcdArgs.push("-c", "adapter speed " + String(request.adapterSpeed));