dsh-stm32 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +59 -21
  2. package/README_EN.md +59 -21
  3. package/docs/development-notes.md +374 -3
  4. package/docs/reading-guide.md +87 -66
  5. package/lib/data/chips.js +38 -51
  6. package/lib/data/cmsis-sources.js +27 -1
  7. package/lib/data/device-facts.js +201 -0
  8. package/lib/data/stm32f1.js +94 -150
  9. package/lib/data/svd.js +627 -0
  10. package/lib/engine/assets.js +924 -0
  11. package/lib/engine/breakpoints.js +242 -0
  12. package/lib/engine/debug-session.js +153 -5
  13. package/lib/engine/debug.js +75 -41
  14. package/lib/engine/doctor.js +2 -2
  15. package/lib/engine/flash.js +31 -59
  16. package/lib/engine/ioc-plan.js +5 -5
  17. package/lib/engine/probe-error.js +212 -0
  18. package/lib/engine/probe-session.js +311 -0
  19. package/lib/engine/register-template.js +32 -8
  20. package/lib/engine/regs.js +2 -0
  21. package/lib/engine/rtt.js +600 -0
  22. package/lib/index.js +8 -0
  23. package/lib/tools/assets.js +341 -0
  24. package/lib/tools/cache.js +8 -0
  25. package/lib/tools/debug-session.js +40 -5
  26. package/lib/tools/debug.js +41 -11
  27. package/lib/tools/doctor.js +11 -0
  28. package/lib/tools/flash.js +15 -6
  29. package/lib/tools/generate.js +3 -0
  30. package/lib/tools/ioc-apply.js +2 -0
  31. package/lib/tools/ioc-inspect.js +2 -0
  32. package/lib/tools/ioc-plan.js +3 -0
  33. package/lib/tools/project-create.js +24 -0
  34. package/lib/tools/regs.js +453 -61
  35. package/lib/tools/route-plan.js +3 -0
  36. package/lib/tools/rtt.js +347 -0
  37. package/package.json +1 -1
  38. package/templates/register/CMakeLists.txt +7 -1
  39. package/templates/register/Core/Inc/rtt.h +103 -0
  40. package/templates/register/Core/Src/main.c +25 -0
  41. package/templates/register/Core/Src/rtt.c +297 -0
  42. package/templates/scaffold/RTT.md +86 -0
  43. package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
  44. package/lib/data/f1-ram.generated.js +0 -34
@@ -0,0 +1,311 @@
1
+ /**
2
+ * B3:探针会话复用快路径(把 regs_read 从"每次 spawn 一个 openocd"降到毫秒级)。
3
+ *
4
+ * 背景:`stm32_regs_read` 原来是"起 openocd → mdw → shutdown",实测 1493 ms;而
5
+ * `stm32_debug_eval` 每次也要新起一个 `gdb -batch`。两者都太慢,但慢的不是"读",
6
+ * 是进程启动。这里把"常驻 openocd"这件事抽成一个小门面,让两条路都走它:
7
+ *
8
+ * - `ensureSession()`:没有会话就起一个(复用 `debug-session.ts` 的租约/Turn 收尾/端口让位),
9
+ * 有同项目的会话就直接复用(`reused=true`);
10
+ * - `readWordsViaSession()`:走 openocd 的 **Tcl RPC 口**(`halt` → `reg pc` → `mdw ...` →
11
+ * `resume`,一条 TCP 连接、几毫秒),这是 1493 ms → <150 ms 的关键;解析不到 Tcl 端口时
12
+ * 调用方回退到 gdb 路径;
13
+ * - `release()` / `touch()`:显式释放与续租(`turn/end`、90 s 空闲、`stm32_debug_stop` 都走 manager)。
14
+ *
15
+ * 唯一真相仍然是 `debugSessions`(单例):这里不自己存句柄、不自己算租约,只做"要不要起、
16
+ * 起完怎么用"的编排,避免出现两个都说自己握着探针的状态。
17
+ */
18
+ import { createConnection } from "node:net";
19
+ import { debugSessions } from "./debug-session.js";
20
+ import { isPortBusy } from "./debug.js";
21
+ import { classifyProbeFailure, formatProbeError, makeProbeError } from "./probe-error.js";
22
+ /** 默认 gdb 端口(与 debug_run / debug_session 一致)。 */
23
+ export const DEFAULT_PROBE_PORT = 3333;
24
+ /** 空闲多久自动关(沿用 L2 会话的 90 s 租约)。 */
25
+ export const DEFAULT_SESSION_IDLE_TTL_MS = 90_000;
26
+ /**
27
+ * Tcl RPC 协议:每条命令以 0x1a 结尾,每个响应也以 0x1a 结尾(不含回显)。
28
+ * 这里不用 `\n`——openocd 的 Tcl 口按 0x1a 分帧,用换行会卡住等不到响应。
29
+ */
30
+ const TCL_FRAME = String.fromCharCode(0x1a);
31
+ /**
32
+ * 响应帧收齐后立刻收尾:帧是按 0x1a 完整切出来的,计数够了就说明每条命令都回了,
33
+ * 不需要再等一个"庄家时间"(那会让每次读白等几十毫秒)。
34
+ */
35
+ const TCL_DONE_MS = 0;
36
+ /** 响应不齐(比如某条命令被 openocd 拒了但没回帧)时的兜底等待。 */
37
+ const TCL_IDLE_MS = 120;
38
+ /** 并发去重:同时来两个 ensureSession 时只起一个 openocd(后到的直接复用同一个 Promise)。 */
39
+ let starting = null;
40
+ function normalizeDir(dir) {
41
+ return dir.trim().replace(/[\\/]+$/u, "").replace(/\\/gu, "/").toLowerCase();
42
+ }
43
+ function sameProject(left, right) {
44
+ return normalizeDir(left) === normalizeDir(right);
45
+ }
46
+ /** 当前会话信息(没有就是 null)。idleDeadline 由 manager 的 remainingMs 反推,不另算一套。 */
47
+ export function sessionInfo() {
48
+ const status = debugSessions.status();
49
+ if (!status.active)
50
+ return null;
51
+ return {
52
+ port: status.port,
53
+ tclPort: status.tclPort,
54
+ configFile: status.configFile,
55
+ projectDir: status.projectDir,
56
+ startedAt: status.startedAt,
57
+ idleDeadline: Date.now() + status.remainingMs,
58
+ };
59
+ }
60
+ /** 续租(每读一次都算"用过")。 */
61
+ export function touch() {
62
+ return debugSessions.touch();
63
+ }
64
+ /** 显式释放(stm32_debug_stop、进程退出等)。 */
65
+ export async function release(reason = "显式释放") {
66
+ return await debugSessions.stop(reason);
67
+ }
68
+ /**
69
+ * 保证有一个可用的调试会话:
70
+ * - 已有同项目会话 → 直接复用(续租);
71
+ * - 没有 → 起一个(端口被占先报 probe-busy,不让 openocd 顺延到别的口偷偷抢探针);
72
+ * - 并发调用 → 只起一个进程。
73
+ */
74
+ export async function ensureSession(projectDir, options = {}) {
75
+ const current = sessionInfo();
76
+ if (current !== null && sameProject(current.projectDir, projectDir)) {
77
+ touch();
78
+ return {
79
+ ok: true,
80
+ reused: true,
81
+ session: sessionInfo(),
82
+ probeError: null,
83
+ message: "复用已有调试会话(gdb 端口 " + String(current.port) + ",tcl 端口 " + String(current.tclPort) + ")",
84
+ };
85
+ }
86
+ if (starting !== null)
87
+ return await starting;
88
+ const idleTtlMs = options.idleTtlMs ?? DEFAULT_SESSION_IDLE_TTL_MS;
89
+ const promise = startSession(projectDir.trim() === "" ? projectDir : projectDir, idleTtlMs, options).finally(() => {
90
+ starting = null;
91
+ });
92
+ starting = promise;
93
+ return await promise;
94
+ }
95
+ async function startSession(projectDir, idleTtlMs, options) {
96
+ if (options.subprocess !== undefined)
97
+ debugSessions.configure(options.subprocess, options.binDirs ?? []);
98
+ const port = options.port ?? DEFAULT_PROBE_PORT;
99
+ const checkBusy = options.checkPortBusy ?? isPortBusy;
100
+ if (options.portBusyIsError !== false && (await checkBusy(port))) {
101
+ const probeError = makeProbeError("probe-busy", {
102
+ cause: "gdb 端口 " + String(port) + " 已被占用(多半是 VS Code 的调试会话或另一个 openocd 还握着探针)",
103
+ evidence: ["probe port " + String(port) + " busy"],
104
+ });
105
+ return { ok: false, reused: false, session: null, probeError, message: formatProbeError(probeError) };
106
+ }
107
+ const started = await debugSessions.start({
108
+ projectDir,
109
+ port,
110
+ idleTtlMs,
111
+ ...(options.elfPath === undefined ? {} : { elfPath: options.elfPath }),
112
+ ...(options.configFile === undefined || options.configFile === "" ? {} : { configFile: options.configFile }),
113
+ ...(options.adapterSpeed === undefined ? {} : { adapterSpeed: options.adapterSpeed }),
114
+ ...(options.binDirs === undefined ? {} : { binDirs: options.binDirs }),
115
+ ...(options.owner === undefined ? {} : { owner: options.owner }),
116
+ });
117
+ if (!started.ok) {
118
+ // 起会话失败的日志已经在 report.errors 里:归类只走 probe-error 那一张表。
119
+ const probeError = classifyProbeFailure({ lines: started.errors, stage: "session" });
120
+ return { ok: false, reused: false, session: null, probeError, message: formatProbeError(probeError) };
121
+ }
122
+ return {
123
+ ok: true,
124
+ reused: false,
125
+ session: sessionInfo(),
126
+ probeError: null,
127
+ message: "起了调试会话(gdb 端口 " + String(started.port) + ",tcl 端口 " + String(started.tclPort) + ",空闲 " + String(Math.round(idleTtlMs / 1000)) + " s 后自动关)",
128
+ };
129
+ }
130
+ /**
131
+ * 在会话里跑一段操作:拿不到会话就把 probeError 原样带出来(调用方只负责格式化)。
132
+ * 失败也 touch()——会话本身是好的,只是一次读取失败,不该被提前回收。
133
+ */
134
+ export async function withSession(fn, projectDir, options = {}) {
135
+ const ensured = await ensureSession(projectDir, options);
136
+ if (!ensured.ok || ensured.session === null) {
137
+ return { ok: false, reused: ensured.reused, session: null, value: null, probeError: ensured.probeError, message: ensured.message };
138
+ }
139
+ try {
140
+ const value = await fn(ensured.session);
141
+ touch();
142
+ return { ok: true, reused: ensured.reused, session: ensured.session, value, probeError: null, message: ensured.message };
143
+ }
144
+ catch (error) {
145
+ touch();
146
+ const detail = error instanceof Error ? error.message : String(error);
147
+ const probeError = makeProbeError("unknown", { cause: "会话内操作失败:" + detail, evidence: [detail] });
148
+ return { ok: false, reused: ensured.reused, session: ensured.session, value: null, probeError, message: formatProbeError(probeError) };
149
+ }
150
+ }
151
+ /** 把 "0x4001100c" / "4001100C" 统一成 8 位小写 0x 形式;解析不了返回 null。 */
152
+ export function normalizeWordAddress(text) {
153
+ const body = text.trim().replace(/^0x/iu, "");
154
+ if (!/^[0-9a-f]{1,8}$/iu.test(body))
155
+ return null;
156
+ return "0x" + body.toLowerCase().padStart(8, "0");
157
+ }
158
+ /**
159
+ * 解析 `mdw <addr>` 的响应:openocd 回 `0x4001100c: 00000020`(值可能不带 0x)。
160
+ * 少数构建只回一个裸值,那就把地址留空、由调用方按序号对齐。
161
+ */
162
+ export function parseMdwReply(reply) {
163
+ const framed = /(?:0x)?([0-9a-f]{1,16})\s*:\s*(?:0x)?([0-9a-f]{1,8})/iu.exec(reply);
164
+ if (framed !== null) {
165
+ const address = normalizeWordAddress(framed[1] ?? "");
166
+ const value = "0x" + (framed[2] ?? "").toLowerCase().padStart(8, "0");
167
+ if (address === null)
168
+ return null;
169
+ return { address, value };
170
+ }
171
+ const bare = /^\s*(?:0x)?([0-9a-f]{1,8})\s*$/iu.exec(reply);
172
+ if (bare === null)
173
+ return null;
174
+ return { address: "", value: "0x" + (bare[1] ?? "").toLowerCase().padStart(8, "0") };
175
+ }
176
+ /** 解析 `reg pc` 的响应:Tcl 的 reg 返回 `pc (/32): 0x0800012c`,也兼容裸 0x 值。 */
177
+ export function parsePcReply(reply) {
178
+ const named = /pc\s*(?:\(\s*\/\s*32\s*\))?\s*:?\s*(0x[0-9a-f]{1,8})/iu.exec(reply);
179
+ if (named !== null)
180
+ return (named[1] ?? "").toLowerCase();
181
+ const any = /(0x[0-9a-f]{1,8})/iu.exec(reply);
182
+ if (any !== null)
183
+ return (any[1] ?? "").toLowerCase();
184
+ const bare = /^\s*([0-9a-f]{1,8})\s*$/iu.exec(reply);
185
+ return bare === null ? "" : "0x" + (bare[1] ?? "").toLowerCase().padStart(8, "0");
186
+ }
187
+ /**
188
+ * 一次 Tcl RPC 往返:连上 openocd 的 Tcl 口,按 0x1a 分帧发命令,收齐响应就断开。
189
+ * 返回 ok=false 时调用方应回退到 gdb 路径(不该把整个 regs_read 判死)。
190
+ */
191
+ export async function tclRoundTrip(port, commands, timeoutMs = 5_000, signal) {
192
+ const startedAt = Date.now();
193
+ const empty = { ok: false, replies: [], output: "", durationMs: 0 };
194
+ if (!Number.isInteger(port) || port <= 0)
195
+ return { ...empty, error: "没有可用的 Tcl 端口(openocd 日志里没有 tcl 那一行)" };
196
+ if (signal?.aborted === true)
197
+ return { ...empty, error: "已取消" };
198
+ return await new Promise((resolve) => {
199
+ const socket = createConnection({ host: "127.0.0.1", port });
200
+ const replies = [];
201
+ let buffer = "";
202
+ let settled = false;
203
+ let idleTimer = null;
204
+ let hardTimer = null;
205
+ const finish = (error) => {
206
+ if (settled)
207
+ return;
208
+ settled = true;
209
+ if (idleTimer !== null)
210
+ clearTimeout(idleTimer);
211
+ if (hardTimer !== null)
212
+ clearTimeout(hardTimer);
213
+ signal?.removeEventListener("abort", onAbort);
214
+ socket.destroy();
215
+ resolve({ ok: error === null && replies.length > 0, replies, output: replies.join("\n"), error, durationMs: Date.now() - startedAt });
216
+ };
217
+ const onAbort = () => {
218
+ finish("已取消");
219
+ };
220
+ const onData = (chunk) => {
221
+ buffer += chunk;
222
+ let frame = buffer.indexOf(TCL_FRAME);
223
+ while (frame >= 0) {
224
+ replies.push(buffer.slice(0, frame));
225
+ buffer = buffer.slice(frame + TCL_FRAME.length);
226
+ frame = buffer.indexOf(TCL_FRAME);
227
+ }
228
+ if (idleTimer !== null)
229
+ clearTimeout(idleTimer);
230
+ // 收齐了就立刻收尾;没齐就按空闲兜底(万一某条命令没回帧,也不至于卡死)。
231
+ idleTimer = setTimeout(() => { finish(null); }, replies.length >= commands.length ? TCL_DONE_MS : TCL_IDLE_MS);
232
+ };
233
+ signal?.addEventListener("abort", onAbort, { once: true });
234
+ hardTimer = setTimeout(() => { finish("Tcl 往返超时(" + String(timeoutMs) + " ms)"); }, Math.max(500, timeoutMs));
235
+ socket.setEncoding("utf8");
236
+ socket.on("connect", () => {
237
+ for (const command of commands)
238
+ socket.write(command + TCL_FRAME);
239
+ });
240
+ socket.on("data", onData);
241
+ socket.on("error", (error) => {
242
+ finish("连不上 openocd 的 Tcl 口:" + error.message);
243
+ });
244
+ });
245
+ }
246
+ /**
247
+ * 走会话的 Tcl 口读 pc + 一组字:`halt` → `reg pc` → `mdw x N` → `resume`。
248
+ * 这是 B3 的主路径(本机实测单次 < 150 ms);失败时调用方回退到 gdb(debug_sessions.read_words)。
249
+ */
250
+ export async function readWordsViaSession(request) {
251
+ const startedAt = Date.now();
252
+ const info = sessionInfo();
253
+ const base = { ok: false, pc: "", samples: [], command: "", output: "" };
254
+ if (info === null)
255
+ return { ...base, durationMs: 0, error: "没有可复用的调试会话(先 ensureSession)" };
256
+ if (info.tclPort <= 0)
257
+ return { ...base, durationMs: 0, error: "会话没有 Tcl 端口(openocd 日志里没有 tcl 那一行),改用 gdb 读" };
258
+ const wanted = [];
259
+ for (const address of request.addresses) {
260
+ const normalized = normalizeWordAddress(address);
261
+ if (normalized !== null)
262
+ wanted.push(normalized);
263
+ }
264
+ const commands = ["halt", "reg pc", ...wanted.map((address) => "mdw " + address), "resume"];
265
+ const round = await tclRoundTrip(info.tclPort, commands, request.timeoutMs ?? 5_000, request.signal);
266
+ if (!round.ok) {
267
+ return { ...base, command: commands.join("; "), output: round.output, durationMs: Date.now() - startedAt, error: round.error };
268
+ }
269
+ touch();
270
+ const pcReply = round.replies[1] ?? "";
271
+ const pc = parsePcReply(pcReply);
272
+ const byAddress = new Map();
273
+ const byIndex = [];
274
+ for (let index = 0; index < wanted.length; index += 1) {
275
+ const reply = round.replies[2 + index] ?? "";
276
+ const parsed = parseMdwReply(reply);
277
+ if (parsed === null) {
278
+ byIndex.push("");
279
+ continue;
280
+ }
281
+ byIndex.push(parsed.value);
282
+ if (parsed.address !== "")
283
+ byAddress.set(parsed.address, parsed.value);
284
+ }
285
+ const samples = wanted.map((address, index) => {
286
+ const value = byAddress.get(address) ?? byIndex[index] ?? "";
287
+ return { address, value, ok: value !== "" };
288
+ });
289
+ const failed = samples.filter((sample) => !sample.ok).length;
290
+ return {
291
+ ok: failed === 0,
292
+ pc,
293
+ samples,
294
+ command: commands.join("; "),
295
+ output: round.output,
296
+ durationMs: Date.now() - startedAt,
297
+ error: failed === 0 ? null : "有 " + String(failed) + " 个地址没读到值",
298
+ };
299
+ }
300
+ /**
301
+ * 进程退出前的尽力清理:exit 里不能 await,只让 manager 发终止信号。
302
+ * 不这么做的话,插件宿主重启后可能留下一个握死探针的 openocd(VS Code 那边就 F5 不动了)。
303
+ */
304
+ process.once("exit", () => {
305
+ try {
306
+ debugSessions.terminateSync();
307
+ }
308
+ catch {
309
+ // exit 阶段不能抛。
310
+ }
311
+ });
@@ -13,6 +13,7 @@ import fs from "node:fs";
13
13
  import path from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { CMSIS_FAMILIES, cmsisTemplatePlan, startupChoiceFor } from "../data/cmsis-sources.js";
16
+ import { deviceFactsSource } from "../data/device-facts.js";
16
17
  import { cacheRootInfo, checkCacheEntry, readCacheIndex, resolveCacheEntry, sha256OfFile, upsertCacheEntry } from "./cache.js";
17
18
  import { fetchAll } from "./fetch.js";
18
19
  import { planRegisterClock, renderClockInit } from "./register-clock.js";
@@ -47,6 +48,10 @@ export async function ensureCmsisTemplate(request = {}) {
47
48
  const choice = resolveStartupChoice(request);
48
49
  if (choice === null) {
49
50
  const asked = (request.mcu ?? request.family ?? "").trim();
51
+ // 资源包没装时,型号解析必然是空——这种时候要说清「先拉资源包」,别让人以为型号写错了。
52
+ if (deviceFactsSource({ ...process.env, ...env }) === "none") {
53
+ return emptyResult(info.root, "facts-missing", "设备事实还没就绪:插件不内置芯片表,先跑 stm32_assets refresh(或检查网络),再建工程。");
54
+ }
50
55
  // F103 家族里上游没有的容量档要单独说清楚(A24):说"认不出"会让人以为插件坏了。
51
56
  const f103 = /^STM32F103([A-Z])([0-9A-Z])/u.exec(asked.toUpperCase());
52
57
  const densityNote = f103 !== null
@@ -214,7 +219,8 @@ export async function ensureCmsisTemplate(request = {}) {
214
219
  *
215
220
  * 链接脚本不在这张表里:它是寄存器路线里唯一必须按型号改的模板(ST 那份写死
216
221
  * 64K FLASH / 20K RAM),所以从 HAL 骨架读原文本、改 MEMORY 两行、另存为
217
- * <DeviceId>_FLASH.ld(见 register-linker.ts)。拷贝数不变,工程文件总数还是 7 个。
222
+ * <DeviceId>_FLASH.ld(见 register-linker.ts)。这四个文件数目固定;工程文件总数由
223
+ * templateFiles 计数(CMakeLists + main.c + rtt.c/rtt.h + 这四个 + 链接脚本 = 9)。
218
224
  */
219
225
  const SHARED_TEMPLATE_FILES = ["CMakePresets.json", ".gitignore", "cmake/gcc-arm-none-eabi.cmake", "openocd.cfg"];
220
226
  /** 链接脚本的"源模板"(HAL 骨架里那份,按型号渲染后另存)。 */
@@ -234,8 +240,12 @@ function countFiles(root) {
234
240
  return count;
235
241
  }
236
242
  /**
237
- * 建一个寄存器版工程:模板(CMakeLists + main.c)来自插件,CMSIS/启动文件来自缓存,
238
- * 工具链与链接脚本复用 HAL 骨架里那几份**不含 HAL 内容**的文件。
243
+ * 建一个寄存器版工程:模板(CMakeLists + main.c + 可选 RTT 的 rtt.c/rtt.h)来自插件,
244
+ * CMSIS/启动文件来自缓存,工具链与链接脚本复用 HAL 骨架里那几份**不含 HAL 内容**的文件。
245
+ *
246
+ * RTT 那两个文件是"编进来但默认不启用":main.c 里 rtt_init() 是注释掉的,工具链开了
247
+ * --gc-sections,所以不调用时 rtt.c 的代码与 3 KB 控制块缓冲会被链接器丢掉,不占 RAM/Flash。
248
+ * 这样模板既能被 stm32_rtt 直接支持,又不给不用 RTT 的人增加成本。
239
249
  */
240
250
  export async function createRegisterProject(request) {
241
251
  const startedAt = Date.now();
@@ -315,6 +325,10 @@ export async function createRegisterProject(request) {
315
325
  const required = [
316
326
  path.join(regTpl, "CMakeLists.txt"),
317
327
  path.join(regTpl, "Core", "Src", "main.c"),
328
+ // 极简 RTT:CMakeLists 已经 add_executable 了 Core/Src/rtt.c,缺了会 link error;
329
+ // main.c 里也 include 了 rtt.h,缺了连编译都过不了。所以两个都算必需文件。
330
+ path.join(regTpl, "Core", "Src", "rtt.c"),
331
+ path.join(regTpl, "Core", "Inc", "rtt.h"),
318
332
  // 链接脚本模板:按型号渲染的那份是从它改出来的,缺了就只能建 C8T6 尺寸的工程
319
333
  path.join(halTpl, LINKER_TEMPLATE_FILE),
320
334
  ...SHARED_TEMPLATE_FILES.filter((rel) => rel !== ".gitignore").map((rel) => path.join(halTpl, rel)),
@@ -334,7 +348,7 @@ export async function createRegisterProject(request) {
334
348
  // 覆盖前先备份将被覆盖的同名文件;备份失败就一个字节都不写(否则用户的 main.c 就没了)。
335
349
  let backup;
336
350
  try {
337
- backup = backupBeforeOverwrite(targetDir, ["CMakeLists.txt", "Core/Src/main.c", linker.fileName, ...SHARED_TEMPLATE_FILES], "register");
351
+ backup = backupBeforeOverwrite(targetDir, ["CMakeLists.txt", "Core/Src/main.c", "Core/Src/rtt.c", "Core/Inc/rtt.h", linker.fileName, ...SHARED_TEMPLATE_FILES], "register");
338
352
  }
339
353
  catch (error) {
340
354
  return fail("没写任何文件:覆盖前的备份失败(" + String(error.message) + ")。目标目录 " + targetDir + " 未被改动。");
@@ -368,7 +382,8 @@ export async function createRegisterProject(request) {
368
382
  const targetExistedBefore = fs.existsSync(targetDir);
369
383
  const driversExistedBefore = fs.existsSync(path.join(targetDir, "Drivers"));
370
384
  const createdDirs = [];
371
- let templateFiles = 2;
385
+ // 2 = CMakeLists.txt + Core/Src/main.c;rtt.c/rtt.h 也是模板直接拷的,一并计数(见下面 3)。
386
+ let templateFiles = 4;
372
387
  try {
373
388
  mkdirTracked(path.join(targetDir, "Core", "Src"), createdDirs);
374
389
  mkdirTracked(path.join(targetDir, "Core", "Inc"), createdDirs);
@@ -376,7 +391,11 @@ export async function createRegisterProject(request) {
376
391
  fs.writeFileSync(path.join(targetDir, "CMakeLists.txt"), fill(fs.readFileSync(path.join(regTpl, "CMakeLists.txt"), "utf8")), "utf8");
377
392
  // 2) 寄存器版 main.c:芯片注释 + 按型号生成的 clock_init()
378
393
  fs.writeFileSync(path.join(targetDir, "Core", "Src", "main.c"), fill(fs.readFileSync(path.join(regTpl, "Core", "Src", "main.c"), "utf8")), "utf8");
379
- // 3) 与 HAL 无关的公共文件:工具链 / presets(.gitignore 缺失时跳过,见上面 missingOptional)
394
+ // 3) 极简 RTT(SEGGER 兼容控制块 + 我们的 4+1+8+payload 帧):原样拷,不做占位符替换。
395
+ // CMakeLists 已经编它,main.c 已经 include 它;rtt_init() 是否调用由用户在 USER CODE 2 决定。
396
+ fs.writeFileSync(path.join(targetDir, "Core", "Src", "rtt.c"), fs.readFileSync(path.join(regTpl, "Core", "Src", "rtt.c"), "utf8"), "utf8");
397
+ fs.writeFileSync(path.join(targetDir, "Core", "Inc", "rtt.h"), fs.readFileSync(path.join(regTpl, "Core", "Inc", "rtt.h"), "utf8"), "utf8");
398
+ // 4) 与 HAL 无关的公共文件:工具链 / presets(.gitignore 缺失时跳过,见上面 missingOptional)
380
399
  for (const rel of SHARED_TEMPLATE_FILES) {
381
400
  if (rel === ".gitignore" && missingOptional.includes(rel))
382
401
  continue;
@@ -385,10 +404,10 @@ export async function createRegisterProject(request) {
385
404
  fs.copyFileSync(path.join(halTpl, rel), dest);
386
405
  templateFiles += 1;
387
406
  }
388
- // 4) 按型号渲染的链接脚本:MEMORY 两行 + 注释两行换成本芯片的真实 Flash/RAM
407
+ // 5) 按型号渲染的链接脚本:MEMORY 两行 + 注释两行换成本芯片的真实 Flash/RAM
389
408
  fs.writeFileSync(path.join(targetDir, linker.fileName), linkerText, "utf8");
390
409
  templateFiles += 1;
391
- // 5) CMSIS:缓存条目里的 Drivers 整棵拷进工程(与 HAL 工程布局一致)
410
+ // 6) CMSIS:缓存条目里的 Drivers 整棵拷进工程(与 HAL 工程布局一致)
392
411
  fs.cpSync(driversSrc, path.join(targetDir, "Drivers"), { recursive: true });
393
412
  }
394
413
  catch (error) {
@@ -417,6 +436,11 @@ export async function createRegisterProject(request) {
417
436
  // 链接脚本/时钟的告警来自按型号推导本身(RAM 用了保守下限、F100 没有延迟位、HSI 到不了上限…),
418
437
  // 用户需要知道"为什么是 64 MHz 而不是 72"。
419
438
  warnings.push(...linker.warnings, ...clock.warnings);
439
+ // RTT 是"编进来但默认不启用",用户得知道怎么开、以及它会吃多少 RAM——
440
+ // 否则 dump 时只会看到"控制块是空的",得回头翻模板。
441
+ warnings.push("RTT 已随工程就位(Core/Src/rtt.c + Core/Inc/rtt.h,SEGGER 兼容控制块、通道 0 按 4+1+8+payload 写帧)," +
442
+ "但默认没启用:取消 main.c 里 USER CODE BEGIN 2 的 rtt_init() 注释才会链进来(否则 --gc-sections 会丢掉它)。" +
443
+ "启用后 3 个通道 × 1 KB = 3 KB RAM;dump 前先用 nm 拿 _SEGGER_RTT 地址再 stm32_rtt action=start addr=…。");
420
444
  if (template.cacheHit)
421
445
  warnings.push("这次用的是缓存模板(" + template.entryDir + "),没有联网。");
422
446
  else
@@ -78,6 +78,7 @@ export async function runRegsRead(subprocess, request) {
78
78
  const errors = [];
79
79
  const notes = [];
80
80
  const base = {
81
+ reusedSession: false,
81
82
  projectDir,
82
83
  configFile: "",
83
84
  command: "",
@@ -192,6 +193,7 @@ export async function runRegsRead(subprocess, request) {
192
193
  : "读寄存器失败:" + (errors[0] ?? "未知原因");
193
194
  return {
194
195
  ok,
196
+ reusedSession: false,
195
197
  projectDir,
196
198
  configFile: configs.join(" "),
197
199
  command,