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
@@ -0,0 +1,476 @@
1
+ /**
2
+ * L2:gdb MI 常驻会话(P3)。
3
+ *
4
+ * 为什么要有这一层:`stm32_debug_eval` 原来是"每次调用临时起一个 gdb -batch → 连上 → 跑几条命令 →
5
+ * detach",断点、变量、栈这些状态在调用之间全丢,而且每次都要重连(实测约 1.5 s)。排障时想
6
+ * "先断在 HardFault_Handler,再连读几次栈/寄存器",这条路根本走不通。
7
+ *
8
+ * MI(Machine Interface)是 gdb 的机器可读协议(`--interpreter=mi2`):命令带 token、
9
+ * 结果以 `^done`/`^error`/`^running` 回,异步事件以 `*stopped`/`*running` 推。VS Code 的
10
+ * C/C++ 调试器也是这么驱动 gdb 的。这里实现最小可用子集:结果/异步记录解析、带 token 的请求队列、
11
+ * 把 `~"..."` 控制台流挂到当前请求上(否则 `print` 的输出找不到归属)。
12
+ *
13
+ * 只读设计约束:零依赖、可单测(解析是纯函数;进程通过 MiSpawner 注入,测试给假进程)。
14
+ */
15
+ import { spawn } from "node:child_process";
16
+ /**
17
+ * 步进命令映射到 MI 的 -exec-*:n/next、s/step 走整行(-exec-next / -exec-step),
18
+ * ni/nexti、si/stepi 走单指令(-exec-next-instruction / -exec-step-instruction)。
19
+ * continue 不在这里(它走 continueTarget,要先清掉旧的停止记录)。返回 null 表示不是步进命令。
20
+ */
21
+ export function steppingCommandFor(command) {
22
+ const normalized = command.trim().toLowerCase();
23
+ if (normalized === "n" || normalized === "next")
24
+ return "-exec-next";
25
+ if (normalized === "s" || normalized === "step")
26
+ return "-exec-step";
27
+ if (normalized === "ni" || normalized === "nexti")
28
+ return "-exec-next-instruction";
29
+ if (normalized === "si" || normalized === "stepi")
30
+ return "-exec-step-instruction";
31
+ return null;
32
+ }
33
+ /** 把 *stopped 记录描述成一行「func file:line @addr (reason)」,continue/step 报停点用。 */
34
+ export function formatStopLocation(record) {
35
+ const reason = typeof record.data["reason"] === "string" ? record.data["reason"] : "";
36
+ const parts = [];
37
+ const frame = record.data["frame"];
38
+ if (typeof frame === "object" && frame !== null) {
39
+ const item = frame;
40
+ const func = typeof item["func"] === "string" ? item["func"] : "";
41
+ const file = typeof item["file"] === "string" ? item["file"] : "";
42
+ const line = typeof item["line"] === "string" ? item["line"] : typeof item["line"] === "number" ? String(item["line"]) : "";
43
+ const addr = typeof item["addr"] === "string" ? item["addr"] : "";
44
+ if (func !== "")
45
+ parts.push(func);
46
+ if (file !== "" && line !== "")
47
+ parts.push(file + ":" + line);
48
+ else if (line !== "")
49
+ parts.push("行 " + line);
50
+ if (addr !== "")
51
+ parts.push("@" + addr);
52
+ }
53
+ if (reason !== "")
54
+ parts.push("(" + reason + ")");
55
+ return parts.length === 0 ? "位置未知" : parts.join(" ");
56
+ }
57
+ /** MI 的 C 字符串转义:\\ \" \n \t \r 以及 \xNN。 */
58
+ export function decodeMiString(text) {
59
+ let out = "";
60
+ for (let index = 0; index < text.length; index += 1) {
61
+ const ch = text[index];
62
+ if (ch !== "\\") {
63
+ out += ch;
64
+ continue;
65
+ }
66
+ const next = text[index + 1] ?? "";
67
+ index += 1;
68
+ if (next === "n")
69
+ out += "\n";
70
+ else if (next === "t")
71
+ out += "\t";
72
+ else if (next === "r")
73
+ out += "\r";
74
+ else if (next === "0")
75
+ out += "\0";
76
+ else if (next === "x") {
77
+ const hex = text.slice(index + 1, index + 3);
78
+ const parsed = Number.parseInt(hex, 16);
79
+ if (Number.isFinite(parsed)) {
80
+ out += String.fromCharCode(parsed);
81
+ index += 2;
82
+ }
83
+ }
84
+ else
85
+ out += next;
86
+ }
87
+ return out;
88
+ }
89
+ /** 解析一个 MI 值:带引号的字符串、{...} tuple、或裸 token。返回解析后的值与下一处位置。 */
90
+ export function parseMiValue(text, start = 0) {
91
+ let index = start;
92
+ while (index < text.length && text[index] === " ")
93
+ index += 1;
94
+ const first = text[index] ?? "";
95
+ if (first === '"') {
96
+ index += 1;
97
+ let raw = "";
98
+ while (index < text.length) {
99
+ const ch = text[index];
100
+ if (ch === "\\") {
101
+ raw += ch + (text[index + 1] ?? "");
102
+ index += 2;
103
+ continue;
104
+ }
105
+ if (ch === '"')
106
+ return { value: decodeMiString(raw), next: index + 1 };
107
+ raw += ch;
108
+ index += 1;
109
+ }
110
+ return { value: decodeMiString(raw), next: index };
111
+ }
112
+ if (first === "{") {
113
+ const parsed = parseMiTuple(text, index + 1);
114
+ return { value: parsed.data, next: parsed.next };
115
+ }
116
+ if (first === "[") {
117
+ // MI 的列表元素是「结果」不是「值」:stack=[frame={…},frame={…}] 的每一项都是 key=value。
118
+ const items = [];
119
+ let pos = index + 1;
120
+ while (pos < text.length) {
121
+ while (pos < text.length && (text[pos] === " " || text[pos] === ","))
122
+ pos += 1;
123
+ if (text[pos] === "]")
124
+ return { value: items, next: pos + 1 };
125
+ const eq = text.indexOf("=", pos);
126
+ const closing = text.indexOf("]", pos);
127
+ if (eq >= 0 && (closing < 0 || eq < closing)) {
128
+ const key = text.slice(pos, eq).trim();
129
+ const parsed = parseMiValue(text, eq + 1);
130
+ items.push({ [key]: parsed.value });
131
+ pos = parsed.next;
132
+ continue;
133
+ }
134
+ const parsed = parseMiValue(text, pos);
135
+ items.push(parsed.value);
136
+ pos = parsed.next;
137
+ }
138
+ return { value: items, next: pos };
139
+ }
140
+ let raw = "";
141
+ while (index < text.length && text[index] !== ",") {
142
+ raw += text[index];
143
+ index += 1;
144
+ }
145
+ return { value: raw.trim(), next: index };
146
+ }
147
+ export function parseMiTuple(text, start = 0) {
148
+ const data = {};
149
+ let index = start;
150
+ while (index < text.length) {
151
+ while (index < text.length && (text[index] === " " || text[index] === ","))
152
+ index += 1;
153
+ if (text[index] === "}")
154
+ return { data, next: index + 1 };
155
+ const eq = text.indexOf("=", index);
156
+ if (eq < 0)
157
+ return { data, next: text.length };
158
+ const key = text.slice(index, eq).trim();
159
+ const parsed = parseMiValue(text, eq + 1);
160
+ data[key] = parsed.value;
161
+ index = parsed.next;
162
+ }
163
+ return { data, next: index };
164
+ }
165
+ /** 一行 MI 输出 → 记录;认不出返回 null(gdb 偶尔会吐空行/纯文本)。 */
166
+ export function parseMiLine(line) {
167
+ const text = line.replace(/\r$/u, "");
168
+ if (text === "")
169
+ return null;
170
+ if (text === "(gdb)")
171
+ return { token: null, kind: "prompt", class: "", data: {}, text: "" };
172
+ const match = /^(\d*)([\^\*\+=~@&])(.*)$/u.exec(text);
173
+ if (match === null)
174
+ return null;
175
+ const token = (match[1] ?? "") === "" ? null : Number.parseInt(match[1], 10);
176
+ const sigil = match[2];
177
+ const rest = (match[3] ?? "").trim();
178
+ if (sigil === "~" || sigil === "@" || sigil === "&") {
179
+ const parsed = parseMiValue(rest, 0);
180
+ const kind = sigil === "~" ? "console" : sigil === "@" ? "target" : "log";
181
+ return { token, kind, class: "", data: {}, text: String(parsed.value ?? "") };
182
+ }
183
+ const comma = rest.indexOf(",");
184
+ const head = comma < 0 ? rest : rest.slice(0, comma);
185
+ const dataText = comma < 0 ? "" : rest.slice(comma + 1);
186
+ const data = dataText === "" ? {} : parseMiTuple(dataText, 0).data;
187
+ const kind = sigil === "^" ? "result" : sigil === "*" ? "exec" : sigil === "+" ? "status" : "notify";
188
+ return { token, kind, class: head, data, text: "" };
189
+ }
190
+ /** 常驻的 gdb MI 会话:保持连接,命令带 token 排队,控制台输出挂到当前请求上。 */
191
+ export class MiSession {
192
+ child = null;
193
+ buffer = "";
194
+ token = 0;
195
+ pending = null;
196
+ lastStopped = null;
197
+ /** 目标是否在跑。运行态下 gdb 不回任何命令(连 console 的 break 都卡),所以动它之前先看这个。 */
198
+ runningState = false;
199
+ stopWaiters = [];
200
+ lastPromptResolve = null;
201
+ exited = false;
202
+ miLog = [];
203
+ constructor() { }
204
+ static async start(options) {
205
+ const spawner = options.spawner ?? defaultSpawner;
206
+ const session = new MiSession();
207
+ const argv = [options.gdb, "--interpreter=mi2", "-q", "-nx"];
208
+ session.child = spawner(argv, options.cwd ?? process.cwd());
209
+ session.attach();
210
+ // MI 模式下 gdb 不一定先吐提示符(而且 "(gdb) " 没有换行,按行读会一直卡着)。
211
+ // 所以握手改成「发一条必须有 ^done 的命令」:等到它就算连上了。
212
+ await session.send("-gdb-set confirm off", options.timeoutMs ?? 20_000);
213
+ await session.send("-gdb-set pagination off", options.timeoutMs ?? 20_000);
214
+ if (options.elfPath !== undefined && options.elfPath !== "") {
215
+ await session.send("-file-exec-and-symbols " + toGdbPath(options.elfPath), options.timeoutMs ?? 20_000);
216
+ }
217
+ await session.send("-target-select extended-remote 127.0.0.1:" + String(options.port), options.timeoutMs ?? 20_000);
218
+ await session.console("monitor halt", options.timeoutMs ?? 20_000);
219
+ return session;
220
+ }
221
+ get alive() {
222
+ return this.child !== null && !this.exited;
223
+ }
224
+ /** 最近一次 *stopped 记录(断点命中/单步结束)。 */
225
+ get stopped() {
226
+ return this.lastStopped;
227
+ }
228
+ /** 目标现在是不是在跑(continue / monitor resume / 断点放过之后)。 */
229
+ get targetRunning() {
230
+ return this.runningState;
231
+ }
232
+ /** 会话日志(调试用:记录所有收到的记录类别)。 */
233
+ get log() {
234
+ return this.miLog;
235
+ }
236
+ attach() {
237
+ const child = this.child;
238
+ if (child === null)
239
+ return;
240
+ const onData = (chunk) => {
241
+ this.buffer += chunk.toString();
242
+ let index = this.buffer.indexOf("\n");
243
+ while (index >= 0) {
244
+ const line = this.buffer.slice(0, index);
245
+ this.buffer = this.buffer.slice(index + 1);
246
+ this.consume(line);
247
+ index = this.buffer.indexOf("\n");
248
+ }
249
+ };
250
+ child.stdout.on("data", onData);
251
+ child.stderr.on("data", onData);
252
+ child.on("exit", () => {
253
+ this.exited = true;
254
+ const pending = this.pending;
255
+ if (pending !== null) {
256
+ clearTimeout(pending.timer);
257
+ this.pending = null;
258
+ pending.reject(new Error("gdb 进程已退出"));
259
+ }
260
+ });
261
+ child.on("error", () => {
262
+ this.exited = true;
263
+ });
264
+ }
265
+ consume(rawLine) {
266
+ // gdb 的 "(gdb) " 提示符没有换行,会和下一条记录黏在一行里,先剥掉。
267
+ const line = rawLine.replace(/^(?:\(gdb\)\s*)+/u, "").trimEnd();
268
+ if (line === "") {
269
+ const resolve = this.lastPromptResolve;
270
+ this.lastPromptResolve = null;
271
+ resolve?.();
272
+ return;
273
+ }
274
+ const record = parseMiLine(line);
275
+ if (record === null)
276
+ return;
277
+ // 目标重新跑起来(^running / *running)后,旧的停止记录就作废——否则 waitStopped
278
+ // 会把上一条(比如 start 时 monitor halt 产生的)当成这次 continue 的结果。
279
+ if (record.class === "running") {
280
+ this.runningState = true;
281
+ this.lastStopped = null;
282
+ }
283
+ if (record.kind === "prompt") {
284
+ const resolve = this.lastPromptResolve;
285
+ this.lastPromptResolve = null;
286
+ resolve?.();
287
+ return;
288
+ }
289
+ if (record.kind === "console" || record.kind === "target" || record.kind === "log") {
290
+ if (this.pending !== null)
291
+ this.pending.text += record.text;
292
+ this.miLog.push(record.kind + ":" + record.text.trimEnd());
293
+ return;
294
+ }
295
+ if (record.kind === "exec") {
296
+ if (record.class === "stopped") {
297
+ this.runningState = false;
298
+ this.lastStopped = record;
299
+ const waiters = this.stopWaiters;
300
+ this.stopWaiters = [];
301
+ for (const waiter of waiters)
302
+ waiter(record);
303
+ // 已经被 waitStopped 取走的停止记录不再留档,避免下一次重复报告。
304
+ if (waiters.length > 0)
305
+ this.lastStopped = null;
306
+ }
307
+ this.miLog.push("exec:" + record.class);
308
+ return;
309
+ }
310
+ if (record.kind === "result") {
311
+ const pending = this.pending;
312
+ if (pending !== null && record.token === pending.token) {
313
+ clearTimeout(pending.timer);
314
+ this.pending = null;
315
+ pending.resolve({ record, text: pending.text });
316
+ }
317
+ else if (record.token === null && pending !== null) {
318
+ // 有些 gdb 版本对 -interpreter-exec 不给 token:归给当前请求。
319
+ clearTimeout(pending.timer);
320
+ this.pending = null;
321
+ pending.resolve({ record, text: pending.text });
322
+ }
323
+ }
324
+ }
325
+ waitPrompt(timeoutMs) {
326
+ if (this.exited)
327
+ return Promise.reject(new Error("gdb 没起来"));
328
+ return new Promise((resolve, reject) => {
329
+ const timer = setTimeout(() => {
330
+ this.lastPromptResolve = null;
331
+ reject(new Error("等 gdb 提示符超时(" + String(timeoutMs) + " ms)"));
332
+ }, timeoutMs);
333
+ this.lastPromptResolve = () => {
334
+ clearTimeout(timer);
335
+ resolve();
336
+ };
337
+ });
338
+ }
339
+ /** 发一条 MI 命令,等它自己的 ^done/^error/^running。 */
340
+ send(command, timeoutMs = 20_000) {
341
+ const child = this.child;
342
+ if (child === null || this.exited)
343
+ return Promise.reject(new Error("gdb 会话已结束"));
344
+ this.token += 1;
345
+ const token = this.token;
346
+ const line = String(token) + command + "\n";
347
+ return new Promise((resolve, reject) => {
348
+ const timer = setTimeout(() => {
349
+ if (this.pending !== null && this.pending.token === token)
350
+ this.pending = null;
351
+ reject(new Error("gdb 命令超时(" + String(timeoutMs) + " ms):" + command));
352
+ }, timeoutMs);
353
+ this.pending = { token, resolve, reject, text: "", timer };
354
+ writeTo(child, line);
355
+ });
356
+ }
357
+ /** 用 gdb 控制台语法执行(等价于 -interpreter-exec console),返回控制台输出文本。 */
358
+ async console(command, timeoutMs = 20_000) {
359
+ const result = await this.send('-interpreter-exec console "' + escapeMi(command) + '"', timeoutMs);
360
+ if (result.record.class !== "error") {
361
+ // monitor halt/resume 不会产生 *stopped / ^running,运行态只能从命令本身记。
362
+ if (/^monitor\s+halt\b/iu.test(command))
363
+ this.runningState = false;
364
+ if (/^monitor\s+resume\b/iu.test(command))
365
+ this.runningState = true;
366
+ }
367
+ return result;
368
+ }
369
+ /**
370
+ * 确保目标停着。跑着就用 -exec-interrupt:运行态下 console 命令(连 "break")都不会回,
371
+ * 只有 -exec-interrupt 是异步感知的。返回 true 表示这次真的打断过。
372
+ */
373
+ async ensureHalted(timeoutMs = 10_000) {
374
+ if (!this.runningState)
375
+ return false;
376
+ this.runningState = false;
377
+ const result = await this.send("-exec-interrupt", timeoutMs);
378
+ if (result.record.class === "error") {
379
+ this.runningState = true;
380
+ throw new Error("打断运行中的目标失败:" + String(result.record.data["msg"] ?? "未知原因"));
381
+ }
382
+ return true;
383
+ }
384
+ /** 求值一个 gdb 表达式,返回打印出来的字符串(如 "0x20004fd0")。 */
385
+ async evaluate(expression, timeoutMs = 20_000) {
386
+ const result = await this.send("-data-evaluate-expression " + JSON.stringify(expression), timeoutMs);
387
+ const value = result.record.data["value"];
388
+ return typeof value === "string" ? value : result.text.trim();
389
+ }
390
+ /** -exec-continue:目标开跑,本方法在 ^running 时返回(不等到下一个断点)。 */
391
+ async continueTarget(timeoutMs = 20_000) {
392
+ this.lastStopped = null;
393
+ const result = await this.send("-exec-continue", timeoutMs);
394
+ return result.record;
395
+ }
396
+ /** -exec-interrupt:把跑着的目标停下来。 */
397
+ async interrupt(timeoutMs = 10_000) {
398
+ const result = await this.send("-exec-interrupt", timeoutMs);
399
+ return result.record;
400
+ }
401
+ /** -stack-list-frames:拿调用栈(每帧 level/func/addr/file/line)。 */
402
+ async stackFrames(timeoutMs = 20_000) {
403
+ const result = await this.send("-stack-list-frames", timeoutMs);
404
+ const frames = result.record.data["stack"];
405
+ if (!Array.isArray(frames))
406
+ return [];
407
+ const out = [];
408
+ for (const item of frames) {
409
+ if (typeof item !== "object" || item === null)
410
+ continue;
411
+ const frame = item["frame"];
412
+ if (typeof frame === "object" && frame !== null)
413
+ out.push(frame);
414
+ }
415
+ return out;
416
+ }
417
+ /**
418
+ * 等下一个 *stopped(断点命中/单步结束/信号)。
419
+ * continueTarget / -exec-next 只在 ^running 时返回,真正"停在哪"要靠这个方法。
420
+ */
421
+ waitStopped(timeoutMs = 20_000) {
422
+ const stopped = this.lastStopped;
423
+ if (stopped !== null) {
424
+ // 已经停住了(比如断点在别的命令里命中了):立刻返回并标记已消费。
425
+ this.lastStopped = null;
426
+ return Promise.resolve(stopped);
427
+ }
428
+ return new Promise((resolve, reject) => {
429
+ const timer = setTimeout(() => {
430
+ this.stopWaiters = this.stopWaiters.filter((item) => item !== waiter);
431
+ reject(new Error("等 *stopped 超时(" + String(timeoutMs) + " ms)"));
432
+ }, timeoutMs);
433
+ const waiter = (record) => {
434
+ clearTimeout(timer);
435
+ resolve(record);
436
+ };
437
+ this.stopWaiters.push(waiter);
438
+ });
439
+ }
440
+ /** 结束会话:-gdb-exit,超时就 kill。 */
441
+ async stop(timeoutMs = 5000) {
442
+ if (this.child === null || this.exited)
443
+ return;
444
+ try {
445
+ await this.send("-gdb-exit", timeoutMs);
446
+ }
447
+ catch {
448
+ // 退出时 gdb 常常不回 ^done:忽略,下面兜底 kill。
449
+ }
450
+ const child = this.child;
451
+ this.child = null;
452
+ try {
453
+ child.kill();
454
+ }
455
+ catch {
456
+ // 已经退出就无所谓。
457
+ }
458
+ }
459
+ }
460
+ /** MI 命令里的字符串转义。 */
461
+ export function escapeMi(text) {
462
+ return text.replace(/\\/gu, "\\\\").replace(/"/gu, '\\"');
463
+ }
464
+ /** Windows 路径 → gdb 认的斜杠路径。 */
465
+ export function toGdbPath(path) {
466
+ return path.replace(/\\/gu, "/");
467
+ }
468
+ function writeTo(child, line) {
469
+ const writer = child.stdin;
470
+ if (writer?.write !== undefined)
471
+ writer.write(line);
472
+ }
473
+ const defaultSpawner = (argv, cwd) => {
474
+ const child = spawn(argv[0], argv.slice(1), { cwd, stdio: ["pipe", "pipe", "pipe"] });
475
+ return child;
476
+ };
@@ -17,6 +17,7 @@ import { describeSearchScope, resolveSearchConfig } from "../data/search-roots.j
17
17
  import { buildGenerateScript, parseGenerateLog } from "./generate-script.js";
18
18
  import { firmwareExtraDirs } from "./firmware-install.js";
19
19
  import { describeRefresh, refreshCubemxCmakeLists } from "./cmake-sources.js";
20
+ import { describeCubeMxGuiConflict, findRunningCubeMxGui } from "./cube-mx-guard.js";
20
21
  import { cacheHit, cacheKeyFor, entryFromFiles, readCache, writeCache } from "./generate-cache.js";
21
22
  import { cubeMxUserHome, needsThirdpartyPacks, parkThirdpartyDb } from "./thirdparty.js";
22
23
  import { listGeneratedFiles, mapGeneratedPath } from "./layout.js";
@@ -113,7 +114,7 @@ export function isProcessAlive(pid) {
113
114
  return error.code === "EPERM";
114
115
  }
115
116
  }
116
- function acquireLock(projectDir, purpose) {
117
+ export function acquireLock(projectDir, purpose) {
117
118
  const dir = join(projectDir, STATE_DIR);
118
119
  mkdirSync(dir, { recursive: true });
119
120
  const lockPath = join(dir, "lock.json");
@@ -165,7 +166,7 @@ function acquireLock(projectDir, purpose) {
165
166
  ...(staleNote === undefined ? {} : { note: staleNote }),
166
167
  };
167
168
  }
168
- function cubeMxLaunch(cubeMxRoots) {
169
+ export function cubeMxLaunch(cubeMxRoots) {
169
170
  for (const root of cubeMxRoots) {
170
171
  const java = root + "/jre/bin/java.exe";
171
172
  const jar = root + "/STM32CubeMX.exe";
@@ -465,6 +466,12 @@ export async function runGenerate(subprocess, request) {
465
466
  // 路径含中文时脚本会乱码,这里逼 JVM 用 UTF-8 读文件。
466
467
  const argv = [launch.java, "-Dfile.encoding=UTF-8", "-jar", launch.jar, "-q", scriptPath];
467
468
  const command = argv.map((part) => (part.includes(" ") ? '"' + part + '"' : part)).join(" ");
469
+ // CubeMX 单实例:GUI 开着时 -q 会被转发过去、弹出模态框,生成会一直挂着(实测卡 4 分钟以上)。
470
+ // 这里先探测、先拒绝,别让用户对着一个不动的进度条猜。
471
+ const guiProcesses = await findRunningCubeMxGui(subprocess, request.signal);
472
+ if (guiProcesses.length > 0) {
473
+ return fail(request, describeCubeMxGuiConflict(guiProcesses));
474
+ }
468
475
  const startedAt = Date.now();
469
476
  if (skipMiss !== "")
470
477
  progress("未跳过 CubeMX:" + skipMiss);