diff --git a/.agents/skills/trace-stack-magic-corruption-test/SKILL.md b/.agents/skills/trace-stack-magic-corruption-test/SKILL.md new file mode 100644 index 0000000..d93d9f5 --- /dev/null +++ b/.agents/skills/trace-stack-magic-corruption-test/SKILL.md @@ -0,0 +1,242 @@ +--- +name: trace-stack-magic-corruption-test +description: Capture the stack-magic write trace for this project's active CMSIS target set, or analyze an existing CSV without a build or debug session. Resolve recorded PCs with arm-none-eabi-addr2line, and create a separate Markdown report with source text, project-relative locations and source-based explanations, one section per CSV record. Keep the CSV unchanged, create no capture archives or sidecar files, and open the completed report in VS Code. Use to automate the existing StackCorruption experiment; it does not add targets or invent a missing trace watch. +--- + +# Trace Stack Magic corruption test + +Run this repository's existing stack-corruption experiment for the **currently +selected target and set**, or create a report from an existing CSV. Deliver a +separate Markdown report with one section per CSV record, including legitimate +initialization writes and records without a PC. Never add columns to or rewrite +the CSV. + +The **only additional output file** is the Markdown report beside the selected +CSV (normally `.trace/.SWO.md`). Use existing build/debug outputs in place. +Do not create capture directories, ELF/profile copies, manifests, JSON result files or diagnostic logs. Keep verification state +and tool diagnostics in memory/tool output. Leave existing archives untouched. + +The repository root contains `Trace.csolution.yml`. Read the +[stack experiment](../../../docs/TRACE_APP.md#stack-corruption-watch-nucleo-l552ze-q) +and its [validation limits](../../../docs/VALIDATION.md#nucleo-l552ze-q-stackcorruption--2026-10-05) +when preparing a capture. Do not encode the board, probe ID, ELF address or source +line number from a previous run into the workflow. + +## Choose the mode + +For "only create the MD", "use the existing CSV", "report only" or equivalent, +use **report-only mode** below. An unspecified mode runs the full capture workflow. +Both modes explain and automatically open the report. + +## Report only from an existing CSV + +1. Use the CSV named by the user; otherwise select the existing CSV for the active + target/set. Read local solution/runtime metadata to identify it. Require a + completed, stable CSV; do not change a running debug session to obtain one. +2. Find the ELF associated with that CSV, preferably supplied by the user or + referenced by its existing runtime profile. Use the source tree and + `arm-none-eabi-addr2line` as in the full workflow. Do not choose an arbitrary + newer build; if the association is ambiguous, ask which ELF belongs to the CSV. + Successful address resolution alone does not prove the ELF matches the capture. +3. Set `trace_report` to the CSV path with its `.csv` suffix replaced by `.md`. + Run the helper on these existing files: + + ```sh + python3 .agents/skills/trace-stack-magic-corruption-test/scripts/report_trace.py \ + --report-only --csv "$trace_csv" --elf "$trace_elf" \ + --addr2line "$trace_addr2line" --source-root "$trace_workspace" \ + --output "$trace_report" + ``` + + If verified state from that exact capture is still available in memory, pass + it with `--capture-state "$trace_state"`. Otherwise the report identifies its + ELF/source association as unverified and displays current source with that + limitation. Never manufacture capture-time verification from current hashes. +4. Continue at **Report content and explanation** below. Retain the provenance + note when adding code context and explanations. Only summarize findings in + the supplied capture; do not claim a new successful hardware test. + +This mode does not build, flash, start/stop debugging, generate trace profiles, +convert RAW, or run `capture_state.py`. It needs no connected board and does not +require the current trace profile still to have the original watch enabled. +Only the Markdown report is written; the CSV, ELF and source remain unchanged. + +## Bind the active target and verify its trace (full capture) + +Use `cmsis-debug-live` for hardware operations and the CMSIS Developer Assistant +MCP tools for build/load/debug. Select this repository's VS Code window with +`list_debug_windows` / `select_debug_window`; leave other projects' sessions alone. +Apply the user's physical probe-selection rules. Allow up to **10 attempts** +per failing CMSIS operation, correcting the cause between attempts. After ten +failures, call `get_session_status` and `get_recent_problems`, then stop and +explain the required VS Code action; do not substitute shell board access. +Shell helpers below operate on local files only. This workflow intentionally +uses the user-requested `arm-none-eabi-addr2line` for offline PC resolution. + +1. Read `.vscode/cmsis.json` (`activeSolution`, `activeTarget`) and + `Trace.cbuild-idx.yml` (`build-idx.target`, `cbuild-run`). The selected target + includes `@` for a named set. Build **that selection** with + `cmsis_action build`, using `check-cmsis-environment` when a build environment + check is needed. If this project already has a debug session, check its state + and end it before rebuilding/starting a fresh capture. Do not switch to the + example L552 set merely because another selected set has no magic watch. +2. From the indexed `.cbuild-run.yml`, read `solution`, `target-type`, `target-set`, + `output` and `debugger.trace`. Require agreement with the active selection. + Resolve the one symbol-bearing ELF from its `output` entry, relative to the + run file. For multiple images/cores, require an unambiguous association with + the watch before continuing. Require SWO file capture. +3. Form the profile stem from the solution name, target and optional set: + `Trace+[@]`. Read `.cmsis/.ctrace.yml`. It must contain a data + watch for `g_stack_corruption_stack` (or its first element), with a write access, + **four-byte size** and **PC output**. Check this against the workload's actual + RTX stack storage, not a similarly named spare canary. If missing or incompatible, + report the exact active set and deficiency; do not enable a different demo. +4. Regenerate with the installed CMSIS Debugger's pyTS against the indexed run + file. Check its missing-symbol list and `.trace/.ctrace-run.yml`: the + magic watch resolves to the first stack word, has size four and PC output, and + its `symbol-file` is the selected ELF. Resolve the corresponding DWT index for + later CSV checks. Retain protocol synchronization; this experiment needs + `sync-on-run` to decode its short capture. Other demo sources should remain + disabled in the StackCorruption profile. Do not change Pack/pyOCD sources. +5. Find `arm-none-eabi-addr2line` beside the selected GCC compiler (the active + `compile_commands.json` records its path), from the tools environment, or on + the activated PATH. Do not install a compiler. Missing tools are a setup issue. + +## Prepare and record + +The helpers require Python 3 and only its standard library. Use arguments, not +shell interpolation of untrusted YAML/CSV contents. Quote paths containing spaces. + +Run `scripts/capture_state.py prepare` with the resolved values: + +```sh +python3 .agents/skills/trace-stack-magic-corruption-test/scripts/capture_state.py prepare \ + --workspace "$trace_workspace" --target "$trace_target" \ + --elf "$trace_elf" --compile-commands "$trace_compile_commands" \ + --run-description "$trace_run" --source-profile "$trace_profile" \ + --runtime-profile "$trace_runtime_profile" \ + --raw "$trace_raw" --csv "$trace_csv" +``` + +Keep the returned JSON as `trace_state` in memory across tool calls. It records +the selected ELF path, input/source hashes and capture start time without writing +files. Pass that JSON directly to the following helpers; never save it to disk. +Prepare again after any build, profile or target change. Keep sources unchanged +between the build, capture and report; if they change, rebuild and capture again. + +- Check `get_session_status` and `list_breakpoints`. A clean capture must pass the + corruption store without breakpoints or single stepping. Remove only this + workflow's own breakpoints; if user breakpoints interrupt the path, arrange for + them to be disabled/restored rather than silently clearing all breakpoints. +- Use `cmsis_action load_and_debug` with the exact active target/set. Confirm the + image/probe match. From the initial halt at `main`, use `continue_execution` + with a **4500 ms** wait for the current two-second workload. A `running` result + is expected. If the workload delay changes, use its delay plus sufficient drain + time instead. If execution stops early, investigate before calling it a capture. +- Pause after the uninterrupted run, then **end the debug session** with + `stop_debugging`. The pause lets the existing IDE workflow convert the drained + RAW; ending the session fixes the final input for the report. + This experiment normally ends in `osRtxErrorNotify` after the deliberate error. +- Run `capture_state.py verify --state-json "$trace_state"`. It waits up to + 15 seconds for a fresh, nonempty, stable RAW/CSV pair and rechecks the inputs. + Replace the in-memory `trace_state` with its returned JSON, which includes the + final RAW/CSV hashes. Do not accept a previous CSV because it exists. Inspect + decoder diagnostics in tool output. If automatic conversion is missing or + stale, run the installed `ctrace` offline on this exact stem and final RAW/profile, + then verify again; report that manual fallback was used. Do not save check logs. + +## Resolve PCs and write the Markdown report + +After the session and final conversion have ended, run: + +```sh +python3 .agents/skills/trace-stack-magic-corruption-test/scripts/report_trace.py \ + --csv "$trace_csv" --elf "$trace_elf" \ + --addr2line "$trace_addr2line" --source-root "$trace_workspace" \ + --capture-state "$trace_state" --output "$trace_report" +``` + +Set `trace_report` to `.trace/.SWO.md`; by default the helper replaces the +input CSV's `.csv` suffix with `.md`. Use the ELF selected before this capture. +The helper checks its hash and the final CSV hash against the in-memory state, +batches distinct PCs through `addr2line`, and writes only the Markdown file. +**Leave CSV bytes, columns, cells and row order unchanged.** Use trace PCs exactly +as recorded; do not subtract a Thumb or return-address offset. If the matching +ELF or source is no longer available, report that limitation instead of guessing. + +## Report content and explanation + +Create exactly one `## Entry N` section per CSV data record, in original order, +including duplicates, decoder diagnostics and records without a PC. The header +is not an entry. For a resolved PC, show the source code first and the location +next, for example: + +````markdown +## Entry 2 + +```c +*bad_destination = 0xDEADC0DEU; +``` + +Location: `Common/Workloads/stack_corruption.c:39` +```` + +Follow this with the record's trace fields, including its PC and any original +notes. Make all source paths project-relative, including `../` for external +Pack files. Pair each inline frame's source and location within the same entry. +For missing/invalid PCs or unavailable/changed source text, state the actual +status and retain the original CSV information; never invent a source line. +Use capture-time source hashes when available; an uncaptured inline header can +have a valid DWARF location without verified source text. In report-only mode, +current source may be shown with an explicit unverified-source note; known hash +mismatches must still be reported and their text omitted. Repeating the helper +with unchanged inputs must produce identical base Markdown. + +After the helper finishes, **explain what happened** in the report. Use its +`addr2line` results (or call that tool again with the selected ELF) to locate the +actual functions, then read the surrounding source, relevant callers and symbol +or constant definitions. Check available source hashes against the capture. +Add a compact context excerpt when needed to explain the resolved store, retaining +the exact recorded source line and its location. Use the matching code-fence +language, including `asm` for assembly. Add one to three explanatory sentences to +each entry and a brief overall interpretation before the entries. Preserve the +entry count/order and original trace fields; leave the CSV untouched. + +Distinguish normal startup/RTX initialization from deliberate corruption using +the source context, never fixed PC addresses, row numbers or a matching literal +alone. Separate recorded evidence from source-based interpretation: PC-only +trace identifies writes but does not directly record their stored values or +elapsed time. Explain subsequent stack checking from its actual code; claim an +observed error-handler stop only when this run has corresponding debugger +inspection. Mark missing evidence or unresolved entries explicitly. Do not +rerun the helper after adding explanations, because it replaces the report; +open the explained report as the final artifact. + +Check that the report section count equals the CSV record count, and that the +CSV hash is unchanged. Report-only mode retains unresolved/incomplete entries +and explains their limitations; it does not start a capture to fill missing data. +For a successful full capture test, the magic-watch DWT index must contain a PC +resolving to the corruption store, without decoder errors. An initialization +write remains a separate entry and is not evidence of corruption by itself. +Do not treat cycle fields as elapsed time when timestamps are disabled. + +**Automatically open the newly generated report in VS Code before the +final response**, including reports that document unresolved entries. Use a +workspace-targeted editor tool if available; otherwise use the installed VS Code +CLI with both absolute paths: + +```sh +code "$trace_workspace" "$trace_report" +``` + +Passing the project folder lets VS Code select its existing workspace window. +Respect its Markdown editor/preview association. Do not force a new/reused window +or use `--wait`, which would block until the user closes the report. Open only the +report generated and checked in this invocation, never a stale file after generation +failed. If no GUI/editor is available (for example in CI), keep the report and +state that it could not be opened; do not rerun the capture for this reason. + +Finish with the mode, identified target/set or ELF, report result, resolved store +location when present, and links to the report and original CSV. Include material +decoder/capture limitations. Do not restart debugging after reporting. Later captures replace +the current files; this skill keeps no archive. diff --git a/.agents/skills/trace-stack-magic-corruption-test/agents/openai.yaml b/.agents/skills/trace-stack-magic-corruption-test/agents/openai.yaml new file mode 100644 index 0000000..b09d767 --- /dev/null +++ b/.agents/skills/trace-stack-magic-corruption-test/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Trace Stack Magic corruption test" + short_description: "Capture or explain an existing trace CSV in Markdown" + default_prompt: "Use $trace-stack-magic-corruption-test to capture the active target's stack-magic writes, or use an existing CSV when requested, and create and explain a Markdown report with one section per CSV record, leaving the CSV unchanged and creating no archives or other output files, then open the report in VS Code." diff --git a/.agents/skills/trace-stack-magic-corruption-test/scripts/capture_state.py b/.agents/skills/trace-stack-magic-corruption-test/scripts/capture_state.py new file mode 100644 index 0000000..43911a5 --- /dev/null +++ b/.agents/skills/trace-stack-magic-corruption-test/scripts/capture_state.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Bind a CMSIS trace capture to its inputs using JSON on stdout; write no files.""" + +import argparse +import csv +import hashlib +import json +from pathlib import Path +import sys +import time + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def prepare(args): + paths = {key: Path(getattr(args, key)).resolve() for key in ( + "elf", "csv", "raw", "source_profile", "runtime_profile", + "run_description", "compile_commands", "workspace")} + for key in ("elf", "source_profile", "runtime_profile", "run_description", + "compile_commands"): + if not paths[key].is_file(): + raise ValueError(f"Missing {key}: {paths[key]}") + if paths["elf"].read_bytes()[:4] != b"\x7fELF": + raise ValueError("Selected image is not an ELF file") + active_file = paths["workspace"] / ".vscode/cmsis.json" + if active_file.is_file(): + active = json.loads(active_file.read_text()).get("activeTarget") + if active and active != args.target: + raise ValueError(f"Selected target is {active!r}, not {args.target!r}") + sources = {} + for entry in json.loads(paths["compile_commands"].read_text()): + source = Path(entry["file"]) + if not source.is_absolute(): + source = Path(entry["directory"]) / source + source = source.resolve() + sources[str(source)] = digest(source) + if not sources: + raise ValueError("The compilation database has no sources") + + state = { + "version": 1, + "target": args.target, + "workspace": str(paths["workspace"]), + "elf": str(paths["elf"]), + "elf_sha256": digest(paths["elf"]), + "csv": str(paths["csv"]), + "raw": str(paths["raw"]), + "sources": sources, + "inputs": {str(paths[key]): digest(paths[key]) for key in ( + "source_profile", "runtime_profile", "run_description", "compile_commands")}, + "capture_started_ns": time.time_ns(), + } + print(json.dumps(state, indent=2)) + + +def verify_inputs(state): + if digest(state["elf"]) != state["elf_sha256"]: + raise ValueError("ELF changed; build, regenerate and prepare a new capture") + for source, expected in state["inputs"].items(): + if digest(source) != expected: + raise ValueError(f"Capture input changed: {source}") + active_file = Path(state["workspace"]) / ".vscode/cmsis.json" + if active_file.is_file(): + active = json.loads(active_file.read_text()).get("activeTarget") + if active and active != state["target"]: + raise ValueError("Active target changed since capture preparation") + + +def verify(args): + state = json.loads(args.state_json) + if not isinstance(state, dict): + raise ValueError("Capture state must be a JSON object") + verify_inputs(state) + files = [Path(state[key]) for key in ("raw", "csv")] + deadline = time.monotonic() + args.timeout + previous = None + stable_since = time.monotonic() + while time.monotonic() < deadline: + try: + sample = [(p.stat().st_size, p.stat().st_mtime_ns) for p in files] + except FileNotFoundError: + sample = None + fresh = sample is not None and all( + size > 0 and modified >= state["capture_started_ns"] + for size, modified in sample) + # The final CSV must have been decoded after the last RAW write. + fresh = fresh and sample[1][1] >= sample[0][1] + if not fresh or sample != previous: + stable_since = time.monotonic() + elif time.monotonic() - stable_since >= 1.0: + break + previous = sample + time.sleep(0.2) + else: + raise ValueError("No fresh, stable RAW/CSV pair; await conversion or decode the final RAW with ctrace") + with files[1].open(newline="", encoding="utf-8-sig") as handle: + reader = csv.DictReader(handle) + if not reader.fieldnames or "pc" not in reader.fieldnames: + raise ValueError("CSV has no pc column") + rows = list(reader) + if any(None in row or None in row.values() for row in rows): + raise ValueError("CSV row length differs from its header") + pc_rows = sum(bool(row.get("pc", "").strip()) for row in rows) + if not pc_rows: + raise ValueError("CSV contains no PC records; do not claim a successful magic-word capture") + # The selected context may change while waiting for asynchronous conversion. + verify_inputs(state) + for key, source in zip(("raw", "csv"), files): + state[f"{key}_sha256"] = digest(source) + state["verified_ns"] = time.time_ns() + state.update(raw_bytes=files[0].stat().st_size, rows=len(rows), pc_rows=pc_rows) + print(json.dumps(state, indent=2)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + prepare_parser = commands.add_parser("prepare", help="Read capture inputs into JSON on stdout before starting debug") + for name in ("target", "workspace", "elf", "csv", "raw", "source-profile", + "runtime-profile", "run-description", "compile-commands"): + prepare_parser.add_argument("--" + name, required=True) + verify_parser = commands.add_parser("verify", help="Wait for final conversion after debug has ended") + verify_parser.add_argument("--state-json", required=True, + help="JSON returned by prepare; retained in memory, not a file") + verify_parser.add_argument("--timeout", type=float, default=15.0) + args = parser.parse_args() + try: + (prepare if args.command == "prepare" else verify)(args) + except (OSError, ValueError, KeyError, csv.Error) as error: + print(f"error: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.agents/skills/trace-stack-magic-corruption-test/scripts/report_trace.py b/.agents/skills/trace-stack-magic-corruption-test/scripts/report_trace.py new file mode 100644 index 0000000..8eb6dcf --- /dev/null +++ b/.agents/skills/trace-stack-magic-corruption-test/scripts/report_trace.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Write a Markdown source report for a completed ctrace CSV; keep inputs intact.""" + +import argparse +import csv +import hashlib +import io +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import sys +import tempfile + + +ADDRESS = re.compile(r"^(?:0[xX])?[0-9a-fA-F]+$") +LOCATION = re.compile(r"^(.*):(\d+|\?)(?: \(discriminator \d+\))?$") +HASH = re.compile(r"[0-9a-fA-F]{64}") + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def file_hash(path): + digest = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def local_path(name, root): + path = Path(name) + return (path if path.is_absolute() else root / path).resolve() + + +def relative_name(path, root): + return Path(os.path.relpath(path, root)).as_posix() + + +def read_capture_state(value, root): + if value is None: + return {}, {}, set() + state = json.loads(value) + if not isinstance(state, dict) or not isinstance(state.get("sources"), dict): + raise ValueError("Capture state requires a sources path/hash object") + if not isinstance(state.get("elf_sha256"), str) or not HASH.fullmatch(state["elf_sha256"]): + raise ValueError("Capture state requires a valid elf_sha256") + sources = {} + for name, digest in state["sources"].items(): + if not isinstance(digest, str) or not HASH.fullmatch(digest): + raise ValueError(f"Invalid source SHA-256 in capture state: {name}") + sources[local_path(name, root)] = digest.lower() + protected = set(sources) + protected.update(local_path(name, root) for name in state.get("inputs", {})) + for key, value in state.items(): + if isinstance(value, str) and (Path(value).is_absolute() or key in ("elf", "csv", "raw", "profile")): + protected.add(local_path(value, root)) + return state, sources, protected + + +def check_output(output, protected): + if output.suffix.casefold() != ".md": + raise ValueError("Report output must have a .md extension") + resolved = output.resolve() + for path in protected: + if resolved == path.resolve() or (output.exists() and path.exists() and output.samefile(path)): + raise ValueError(f"Report output aliases an input: {path}") + + +def inline_code(value): + # Escape embedded newlines in names; multiline values use fenced blocks below. + value = str(value).replace("\r", "\\r").replace("\n", "\\n") + length = max((len(match) for match in re.findall(r"`+", value)), default=0) + 1 + fence = "`" * length + padding = " " if value.startswith(("`", " ")) or value.endswith(("`", " ")) else "" + return fence + padding + value + padding + fence + + +def fenced(value, language="text"): + length = max(3, max((len(match) for match in re.findall(r"`+", value)), default=0) + 1) + fence = "`" * length + return f"{fence}{language}\n{value}\n{fence}" + + +def resolve_addresses(tool, elf, addresses): + """Parse address/function/location pairs, preserving all inline frames.""" + if not addresses: + return {} + result = subprocess.run( + [str(tool), "-a", "-f", "-C", "-i", "-e", str(elf)], + input="".join(f"0x{address:x}\n" for address in addresses), + text=True, encoding="utf-8", errors="replace", capture_output=True, + check=False, timeout=60, + ) + if result.returncode: + raise ValueError(f"addr2line failed ({result.returncode}): {result.stderr.strip()}") + blocks, seen, current = {}, [], None + for line in result.stdout.splitlines(): + if re.fullmatch(r"0[xX][0-9a-fA-F]+", line): + current = int(line, 16) + if current in blocks: + raise ValueError("addr2line returned a duplicate address block") + blocks[current] = [] + seen.append(current) + elif current is None: + raise ValueError("addr2line output has no initial address marker") + else: + blocks[current].append(line) + if seen != addresses: + raise ValueError("addr2line did not return the requested addresses in order") + for address, lines in blocks.items(): + if not lines or len(lines) % 2: + raise ValueError(f"Incomplete addr2line frames for 0x{address:x}") + blocks[address] = list(zip(lines[0::2], lines[1::2])) + return blocks + + +def source_details(location, root, hashes, cache, warnings, protected, allow_unverified=False): + match = LOCATION.fullmatch(location) + if not match or match[1] == "??" or match[2] in ("?", "0"): + return None, None, "Source location unresolved." + path = local_path(match[1], root) + protected.add(path) + number = int(match[2]) + label = f"{relative_name(path, root)}:{number}" + if path not in cache: + if path not in hashes and not allow_unverified: + cache[path] = (None, "Source hash unavailable in capture state; text omitted.") + else: + try: + raw = path.read_bytes() + if path in hashes and sha256(raw) != hashes[path]: + cache[path] = (None, "Source changed since capture; text omitted.") + else: + cache[path] = (raw.decode("utf-8").splitlines(), None) + except (OSError, UnicodeError): + cache[path] = (None, "Source unavailable; text omitted.") + lines, error = cache[path] + if not error and number > len(lines): + error = "Source line outside file; text omitted." + if error: + warnings.append(f"{label}: {error}") + return label, None, error + return label, lines[number - 1].strip(), None + + +def trace_fields(header, row, pc_index): + """Retain original nonempty values, including decoder notes and extra columns.""" + fields = [(header[i] if i < len(header) else f"column {i + 1}", value) + for i, value in enumerate(row) if value != "" and i != pc_index] + if pc_index is not None and pc_index < len(row) and row[pc_index] != "": + fields.insert(0, (header[pc_index], row[pc_index])) + compact, multiline = [], [] + for name, value in fields: + label = inline_code(name) + if "\n" in value or "\r" in value: + multiline.extend([f"CSV {label}:", fenced(value)]) + else: + compact.append(f"{label}: {inline_code(value)}") + return ([" · ".join(compact)] if compact else []) + multiline + + +def report(args): + csv_path = args.csv.resolve() + elf = args.elf.resolve() + root = args.source_root.resolve() + output = (args.output or args.csv.with_suffix(".md")).absolute() + state, hashes, protected = read_capture_state(args.capture_state, root) + protected.update((csv_path, elf, args.addr2line.resolve())) + check_output(output, protected) + + state_elf = state.get("elf_sha256", "").lower() or None + expected = args.elf_sha256.lower() if args.elf_sha256 else state_elf + if expected is not None and not HASH.fullmatch(expected): + raise ValueError("ELF SHA-256 must contain 64 hexadecimal characters") + if state_elf is not None and expected != state_elf: + raise ValueError("--elf-sha256 disagrees with capture state") + elf_hash = file_hash(elf) + if expected is not None and elf_hash != expected: + raise ValueError("ELF differs from capture SHA-256; report left unchanged") + csv_bytes = csv_path.read_bytes() + csv_hash = sha256(csv_bytes) + if state.get("csv_sha256") is not None and csv_hash != state["csv_sha256"]: + raise ValueError("CSV differs from capture SHA-256; prepare a new capture") + rows = list(csv.reader(io.StringIO(csv_bytes.decode("utf-8-sig"), newline=""), strict=True)) + if not rows or not rows[0]: + raise ValueError("CSV has no header") + header, records = rows[0], rows[1:] + pc_columns = [i for i, name in enumerate(header) if name.casefold() == "pc"] + if len(pc_columns) > 1: + raise ValueError("CSV has multiple PC columns") + pc_index = pc_columns[0] if pc_columns else None + raw_pcs = [row[pc_index].strip() if pc_index is not None and pc_index < len(row) else "" for row in records] + parsed = [int(raw, 16) if raw and ADDRESS.fullmatch(raw) else None for raw in raw_pcs] + addresses = list(dict.fromkeys(address for address in parsed if address is not None)) + resolved = resolve_addresses(args.addr2line, elf, addresses) + + parts = ["# Stack magic trace", f"CSV: {inline_code(relative_name(csv_path, root))}"] + if isinstance(state.get("target"), str): + parts.append(f"Target: {inline_code(state['target'])}") + if args.report_only: + if not state.get("csv_sha256"): + parts.append( + "**Capture provenance: unverified.** PCs are resolved with the selected ELF and " + "source text is read from current files. Their association with the original " + "capture has not been established. Any supplied hashes are still enforced." + ) + else: + parts.append( + "**Report-only analysis.** Supplied capture hashes are enforced. Source text " + "without a capture-time hash is marked as current-file content; its association " + "with the original capture is unverified." + ) + cache, warnings, unresolved = {}, [], 0 + unverified_sources = set() + for index, (row, raw_pc, address) in enumerate(zip(records, raw_pcs, parsed), start=1): + parts.append(f"## Entry {index}") + located = False + if not raw_pc: + parts.append("Status: No PC recorded; source lookup not applicable.") + elif address is None: + parts.append("Status: Invalid PC; source unresolved.") + else: + frames = resolved[address] + for frame_index, (function, location) in enumerate(frames): + if frame_index: + parts.append(f"**Inline caller {frame_index}** ({inline_code(function)})") + label, source, error = source_details( + location, root, hashes, cache, warnings, protected, args.report_only) + located = located or label is not None + if source is not None: + path = local_path(LOCATION.fullmatch(location)[1], root) + language = "asm" if path.suffix.casefold() in (".s", ".asm") else "c" + parts.append(fenced(source, language)) + else: + parts.append(f"Status: {error}") + if label is not None: + parts.append(f"Location: {inline_code(label)}") + if source is not None and path not in hashes: + unverified_sources.add(relative_name(path, root)) + parts.append("Source provenance: current file; no capture-time source hash available.") + if raw_pc and not located: + unresolved += 1 + parts.extend(trace_fields(header, row, pc_index)) + updated = ("\n\n".join(parts) + "\n").encode("utf-8") + + def recheck_inputs(): + check_output(output, protected) + if csv_path.read_bytes() != csv_bytes: + raise ValueError("CSV changed during reporting; stop capture/conversion first") + if file_hash(elf) != elf_hash: + raise ValueError("ELF changed during reporting; report left unchanged") + + recheck_inputs() + changed = not output.exists() or output.read_bytes() != updated + if changed: + temporary = None + try: + with tempfile.NamedTemporaryFile(dir=output.parent, delete=False) as handle: + temporary = Path(handle.name) + handle.write(updated) + handle.flush() + os.fsync(handle.fileno()) + if output.exists(): + temporary.chmod(stat.S_IMODE(output.stat().st_mode)) + recheck_inputs() + os.replace(temporary, output) + finally: + if temporary is not None and temporary.exists(): + temporary.unlink() + print(json.dumps({ + "rows": len(records), "sections": len(records), + "pc_rows": sum(bool(raw) for raw in raw_pcs), "unique_pcs": len(addresses), + "unresolved_rows": unresolved, "source_warnings": list(dict.fromkeys(warnings)), + "report": str(output), "csv_sha256": csv_hash, "elf_sha256": elf_hash, + "changed": changed, "report_only": args.report_only, + "unverified_sources": sorted(unverified_sources), + }, ensure_ascii=False, indent=2)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--csv", type=Path, required=True) + parser.add_argument("--elf", type=Path, required=True) + parser.add_argument("--addr2line", type=Path, required=True) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--report-only", action="store_true", + help="Read current source without capture state; mark missing capture provenance") + parser.add_argument("--capture-state", + help="Capture-state JSON retained in memory after verification") + parser.add_argument("--elf-sha256") + parser.add_argument("--output", type=Path) + try: + report(parser.parse_args()) + except (OSError, ValueError, csv.Error, subprocess.SubprocessError) as error: + print(f"report_trace: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.cmsis/Trace+NUCLEO-L552ZE-Q@ULINKplus StackCorruption.ctrace.yml b/.cmsis/Trace+NUCLEO-L552ZE-Q@ULINKplus StackCorruption.ctrace.yml new file mode 100644 index 0000000..aedc5c4 --- /dev/null +++ b/.cmsis/Trace+NUCLEO-L552ZE-Q@ULINKplus StackCorruption.ctrace.yml @@ -0,0 +1,22 @@ +# Watch only the first word of this thread's stack: RTX writes its magic here. +# Resolve the address from the selected ELF; size: 4 excludes the rest of the stack. +ctrace: + setup: + - core: Cortex-M33 + data: + - location: g_stack_corruption_stack + label: StackMagic + access: W + size: 4 + output: PC + itm: + enable: 0x00000000 + pcsampling: + period: 0 + synchronization: + DWT: 16M + sync-on-run: true + +# No timestamps, exception events, or other trace sources. pyTS clears the +# previous ITM/DWT configuration before enabling this single data watch. +# Protocol synchronization lets ctrace decode even this very short capture. diff --git a/Board/NUCLEO-L552ZE-Q/README.md b/Board/NUCLEO-L552ZE-Q/README.md index a2a0ca0..e3b43fd 100644 --- a/Board/NUCLEO-L552ZE-Q/README.md +++ b/Board/NUCLEO-L552ZE-Q/README.md @@ -11,7 +11,7 @@ with `trustzone: off`. | Linked SRAM | 256 KiB at `0x20000000` | | Main stack | 4 KiB | | Nominal reset clock | 4 MHz MSI | -| Debugger sets | `ULINKplus`, `STLink`; same firmware, SWD / 1 Mbaud SWO | +| Debugger sets | `ULINKplus`, `STLink` (shared `Debug` image); `ULINKplus StackCorruption` (separate build); SWD / 1 Mbaud SWO | The layer follows the [shared board design](../../docs/BOARD_SUPPORT.md#shared-layer-design). DFP sequences provide the PB3 SWO pin/clock setup; no local override is used. @@ -24,3 +24,11 @@ MB1361 uses different connector/jumper names from F756; follow the [L552 wiring table](../../docs/ST_BOARD_BRINGUP.md#nucleo-l552ze-q--mb1361). See [Validation](../../docs/VALIDATION.md) for hardware results and recording limits, and [debugger profiles](../../docs/DEBUG_PROBES.md) for capture setup. + +`ULINKplus StackCorruption` adds a `StackCorruption` thread with a 256-byte stack. +After two seconds it deliberately overwrites the first stack word, RTX's +`0xE25A2EA5` magic, with `0xDEADC0DE`. Its trace profile watches only writes to +that word and emits the writing PC; the normal demo trace sources are disabled. +RTX stack checking then enters its stack-overflow error handler. Select this set, +build and regenerate its trace profile before capture; see the +[stack-corruption workflow](../../docs/TRACE_APP.md#stack-corruption-watch-nucleo-l552ze-q). diff --git a/Common/App/app_main.c b/Common/App/app_main.c index 57824c1..5ba9db5 100644 --- a/Common/App/app_main.c +++ b/Common/App/app_main.c @@ -4,6 +4,9 @@ #include "target.h" #include "dwt_workload.h" #include "trace.h" +#if defined(TRACE_STACK_CORRUPTION) +#include "stack_corruption.h" +#endif enum app_state { APP_STARTING, @@ -116,6 +119,13 @@ int app_main(void) return -1; } +#if defined(TRACE_STACK_CORRUPTION) + if (!stack_corruption_start(2U * tick_hz)) { + g_app_state = APP_ERROR; + return -1; + } +#endif + g_app_state = APP_RUNNING; (void)osKernelStart(); g_app_state = APP_ERROR; diff --git a/Common/Include/stack_corruption.h b/Common/Include/stack_corruption.h new file mode 100644 index 0000000..a4dddc6 --- /dev/null +++ b/Common/Include/stack_corruption.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#ifndef TRACE_STACK_CORRUPTION_H +#define TRACE_STACK_CORRUPTION_H + +#include +#include + +/* Create the fault-injection thread before starting the RTX kernel. */ +bool stack_corruption_start(uint32_t delay_ticks); + +#endif diff --git a/Common/Workloads/stack_corruption.c b/Common/Workloads/stack_corruption.c new file mode 100644 index 0000000..1523bb7 --- /dev/null +++ b/Common/Workloads/stack_corruption.c @@ -0,0 +1,61 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +#include "cmsis_compiler.h" +#include "cmsis_os2.h" +#include "rtx_os.h" +#include "stack_corruption.h" + +/* RTX initializes word 0 to osRtxStackMagicWord (0xE25A2EA5). The trace watch + * resolves this symbol to the actual thread stack, not a separate test canary. + */ +__ALIGNED(8) uint32_t g_stack_corruption_stack[64]; + +static osRtxThread_t thread_control_block; +static uint32_t corruption_delay_ticks; + +static void stack_corruption_thread(void *argument) +{ + volatile uint32_t local_words[8]; + (void)argument; + + /* Leave time to inspect the intact RTX stack before the deliberate fault. */ + if (osDelay(corruption_delay_ticks) != osOK) { + osThreadExit(); + } + for (uint32_t i = 0U; i < 8U; ++i) { + local_words[i] = i; + } + + /* Inject an array-underflow write with a deliberately invalid byte offset. + * Integer address arithmetic confines the injected error to the magic word: + * no intermediate writes damage the live frame, saved registers or returns. + * PSP stays within the 256-byte stack, so Cortex-M33 PSPLIM does not fault + * before the watched STR instruction can emit its PC through DWT/SWO. + */ + const uintptr_t local_address = (uintptr_t)&local_words[0]; + const uintptr_t invalid_offset = + local_address - (uintptr_t)&g_stack_corruption_stack[0]; + volatile uint32_t *bad_destination = + (volatile uint32_t *)(local_address - invalid_offset); + *bad_destination = 0xDEADC0DEU; + + /* Keep RTX stack checking enabled. This switch detects the overwritten + * magic and enters the standard osRtxErrorNotify stack-overflow handler. + */ + (void)osDelay(1U); + osThreadExit(); +} + +bool stack_corruption_start(uint32_t delay_ticks) +{ + static const osThreadAttr_t attributes = { + .name = "StackCorruption", + .cb_mem = &thread_control_block, + .cb_size = sizeof(thread_control_block), + .stack_mem = g_stack_corruption_stack, + .stack_size = sizeof(g_stack_corruption_stack), + .priority = osPriorityNormal + }; + + corruption_delay_ticks = delay_ticks; + return osThreadNew(stack_corruption_thread, NULL, &attributes) != NULL; +} diff --git a/Projects/TraceDemo/TraceDemo.cproject.yml b/Projects/TraceDemo/TraceDemo.cproject.yml index 5b2d2f0..8563561 100644 --- a/Projects/TraceDemo/TraceDemo.cproject.yml +++ b/Projects/TraceDemo/TraceDemo.cproject.yml @@ -26,6 +26,12 @@ project: - file: ../../Common/Workloads/dwt_workload.c - file: ../../Common/Include/dwt_workload.h + - group: Stack Corruption + for-context: .StackCorruption+NUCLEO-L552ZE-Q + files: + - file: ../../Common/Workloads/stack_corruption.c + - file: ../../Common/Include/stack_corruption.h + - group: Trace Output files: - file: ../../Common/Trace/itm_output.c diff --git a/README.md b/README.md index 43d5c75..6b2c7f6 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,9 @@ local board layers, covering Cortex-M4, Cortex-M7 and Cortex-M33. The workload updates sine and deterministic-noise variables every 100 ms for DWT and emits an ITM channel 1 counter every 200 ms. Debugger profiles add PC sampling and timestamps. pyOCD captures SWO; ctrace converts recordings to CSV. +NUCLEO-L552ZE-Q also provides `ULINKplus StackCorruption`: a fourth thread +deliberately overwrites its RTX stack magic word, and a single DWT watch reports +the writing PC over SWO. See the [stack-corruption workflow](docs/TRACE_APP.md#stack-corruption-watch-nucleo-l552ze-q). **Status: experimental SWO demo.** Trace Generation and automatic CSV conversion require the [listed development tool versions](docs/BUILD.md#trace-toolchain). @@ -48,8 +51,9 @@ Missing CMSIS packs are installed by `cbuild --packs` using the pinned dependenc 1. Open this folder in VS Code and activate the build environment described in the [build guide](docs/BUILD.md). 2. Select `Trace.csolution.yml` as the active solution. Open **CMSIS: Manage Solution - Settings**, choose a board and, where available, the `ULINKplus` or `STLink` set. - Both use automatic probe selection. Check the + Settings**, choose a board and its target set (`ULINKplus`, `STLink`, or the + L552-only `ULINKplus StackCorruption`). Sets use automatic probe selection; + select the intended probe locally when several are connected. Check the board README linked above and the [ST board wiring notes](docs/ST_BOARD_BRINGUP.md). 3. Build the selected target. Enable `vscode-cmsis-debugger.enableTraceGenerationView` in local VS Code settings. In the CMSIS Debugger **Trace Generation** view, @@ -60,14 +64,22 @@ Missing CMSIS packs are installed by `cbuild --packs` using the pinned dependenc trigger CSV conversion when new trace data is available. Inspect decoder errors as well as the CSV. See the [trace workflow](docs/TRACE_APP.md). +For an agent-driven stack-magic capture, invoke `Use $trace-stack-magic-corruption-test` with the +intended target set active. The project +[trace-stack-magic-corruption-test skill](.agents/skills/trace-stack-magic-corruption-test/SKILL.md) checks its +trace watch, runs and ends debugging, then creates a Markdown report with one +section per CSV entry, source text and project-relative locations. The CSV remains +unchanged. See the [workflow](docs/TRACE_APP.md#stack-magic-agent-workflow). + Command-line build from an activated tool environment: ```sh cbuild Trace.csolution.yml --active 'STM32F429I-DISCO@STLink' --packs --frozen-packs --update-rte ``` -Changing the debugger set keeps the same application image for that board. Changing -boards selects another local board layer. Firmware produces the signals; Pack +The regular `ULINKplus` and `STLink` sets share the board's `Debug` image. +`ULINKplus StackCorruption` selects the separate `StackCorruption` build. +Changing boards selects another local board layer. Firmware produces the signals; Pack sequences, pyOCD and ctrace configuration own trace initialization. ## Add a board diff --git a/Trace.csolution.yml b/Trace.csolution.yml index 356df42..581ed65 100644 --- a/Trace.csolution.yml +++ b/Trace.csolution.yml @@ -12,6 +12,11 @@ solution: - type: Debug debug: on optimize: none + - type: StackCorruption + debug: on + optimize: none + define: + - TRACE_STACK_CORRUPTION: 1 target-types: - type: MCBSTM32F400 @@ -50,6 +55,20 @@ solution: mode: file input-clock: 4000000 output-clock: 1000000 + - set: ULINKplus StackCorruption + images: + - project-context: TraceDemo.StackCorruption + debugger: + name: ULINKplus@pyOCD + protocol: swd + clock: 10000000 + gdbserver: + - port: 43333 + trace: + - swo-uart: + mode: file + input-clock: 4000000 + output-clock: 1000000 - set: STLink images: - project-context: TraceDemo.Debug @@ -251,3 +270,6 @@ solution: projects: - project: Projects/TraceDemo/TraceDemo.cproject.yml + for-context: + - .Debug + - .StackCorruption+NUCLEO-L552ZE-Q diff --git a/docs/BUILD.md b/docs/BUILD.md index 79c35cd..a3c3bc7 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -44,6 +44,13 @@ The debugger and pyOCD links identify source revisions; pyTS and ctrace link to releases. Together they describe the reference toolchain, not a stable debugger release. +The L552 `StackCorruption` profile was built and tested on hardware with the +installed validation tools: CMSIS Debugger `1.8.1-64-g28c1601`, pyOCD +`0.45.2.dev36+g74e3290d8`, pyTS `0.6.1` and ctrace `0.4.0`. Its short capture +requires `sync-on-run` support in trace generation and runtime setup; compatibility +with the reference versions above has not been established for this profile. +The capture results and remaining limitations are recorded in [Validation](VALIDATION.md#nucleo-l552ze-q-stackcorruption--2026-10-05). + ## Build and select a target ```sh @@ -53,6 +60,9 @@ cbuild Trace.csolution.yml --active MCBSTM32F400 --packs --frozen-packs --update # Select a board and named debugger set. cbuild Trace.csolution.yml --active 'NUCLEO-F756ZG@STLink' --packs --frozen-packs +# Build the L552-only stack-corruption experiment. +cbuild Trace.csolution.yml --active 'NUCLEO-L552ZE-Q@ULINKplus StackCorruption' --packs --frozen-packs + # Build all Debug contexts. cbuild Trace.csolution.yml --context 'TraceDemo.Debug+*' --packs --frozen-packs ``` @@ -60,7 +70,10 @@ cbuild Trace.csolution.yml --context 'TraceDemo.Debug+*' --packs --frozen-packs `--active ` selects an unnamed target set; `--active '@'` selects a named debugger set. It also generates `out/Trace+.cbuild-run.yml` for that selection. `--context` selects the project/build/target context matrix. -Named sets reuse the same application image; see [debugger selection](DEBUG_PROBES.md). +The regular `ULINKplus` and `STLink` sets reuse the board's `Debug` image. +`NUCLEO-L552ZE-Q@ULINKplus StackCorruption` selects `TraceDemo.StackCorruption`, +which defines `TRACE_STACK_CORRUPTION=1` and includes the additional thread. +This build context is restricted to L552; see [debugger selection](DEBUG_PROBES.md). In VS Code, select `Trace.csolution.yml` as the active solution and choose the target/set in **CMSIS: Manage Solution Settings**. The `Board-Layer` variable @@ -68,7 +81,8 @@ selects the matching local layer automatically. ## Generated files and editor setup -ELF, HEX and BIN outputs are in `out/TraceDemo//Debug/`; intermediates and +ELF, HEX and BIN outputs are in `out/TraceDemo///` +(`Debug` or the L552-only `StackCorruption`); intermediates and link maps are under `tmp/`. Build/run descriptions, context-specific RTE headers and `.trace/` runtime profiles are generated. Keep the solution, CProject, layers, pack lock, active `RTX_Config.c`/`RTX_Config.h`, `.cmsis/*.dbgconf` and source diff --git a/docs/DEBUG_PROBES.md b/docs/DEBUG_PROBES.md index 697eec5..11fa4e8 100644 --- a/docs/DEBUG_PROBES.md +++ b/docs/DEBUG_PROBES.md @@ -1,8 +1,10 @@ # Debugger selection Debugger target sets in [`Trace.csolution.yml`](../Trace.csolution.yml) select the -probe and trace profile. Both probes use the same board layer and application -image. Build commands are in [BUILD.md](BUILD.md); measured results are in +probe and, where configured, trace profile. The regular `ULINKplus` and `STLink` +sets use the same board layer and `Debug` application image. L552's +`ULINKplus StackCorruption` selects a separate build and watch-only profile. +Build commands are in [BUILD.md](BUILD.md); measured results are in [Validation](VALIDATION.md). ## Configured probes and profiles @@ -12,6 +14,7 @@ All sets use SWD and SWO UART/NRZ file capture at **1 Mbaud**. | Probe | Debugger name | Selection | SWD clock | PC period | | --- | --- | --- | --- | --- | | ULINK+ | `ULINKplus@pyOCD` | Automatic | 10 MHz; MCB uses the tool default | 8192 cycles | +| ULINK+ (L552 StackCorruption) | `ULINKplus@pyOCD` | Automatic | 10 MHz | Disabled | | ST-LINK | `ST-Link@pyOCD` | Automatic | 4 MHz | 16384 cycles | Both probe types use automatic selection without a fixed `probe-id`. @@ -21,7 +24,7 @@ type are connected, select the intended probe before loading an image. | Target | Available target sets | Core / timestamp clock | | --- | --- | --- | | MCBSTM32F400 | `ULINKplus` (unnamed set) | 16 MHz | -| NUCLEO-L552ZE-Q | `ULINKplus`, `STLink` | 4 MHz | +| NUCLEO-L552ZE-Q | `ULINKplus`, `STLink`, `ULINKplus StackCorruption` | 4 MHz (no timestamps in StackCorruption) | | NUCLEO-F756ZG | `ULINKplus`, `STLink` | 16 MHz | | NUCLEO-G474RE | `ULINKplus`, `STLink` | 16 MHz | | STM32F429I-DISCO | `ULINKplus`, `STLink` | 16 MHz | @@ -34,9 +37,12 @@ For the two unnamed sets, select `--active MCBSTM32F400` or `--active STM32H7B3I-DK`, without an `@ULINKplus` suffix. The other boards use named sets, for example `--active NUCLEO-F756ZG@ULINKplus`. -Only the PC-sampling period differs between a board's two trace profiles; +For the regular STM32 `ULINKplus` and `STLink` profiles, only the PC-sampling period differs; ST-LINK uses half the PC sample rate. The common sources and timestamp/sync settings are described in [Trace application](TRACE_APP.md#configuration-ownership). +The L552 `ULINKplus StackCorruption` profile instead enables one write watch on +the additional thread's stack magic word, with `output: PC`; see the +[experiment workflow](TRACE_APP.md#stack-corruption-watch-nucleo-l552ze-q). ## Switch sets diff --git a/docs/DESIGN.md b/docs/DESIGN.md index fbcd12f..bdf4796 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -17,6 +17,10 @@ hardware results and capture limitations are in [Validation](VALIDATION.md). - Run separate sine and deterministic-noise threads at 100 ms and an ITM channel 1 counter thread at 200 ms. Configure two DWT sources, PC sampling and timestamps through the Trace Generation view and `.ctrace.yml`. +- Provide an L552-only `ULINKplus StackCorruption` target set with a fourth, + 256-byte-stack thread that deliberately corrupts its RTX stack magic. Capture + the writing PC through a single DWT watch over SWO, with other trace sources + disabled. - Keep trace initialization in the debugger. Firmware writes the watched variables and makes nonblocking ITM writes; it does not enable or configure the trace path. - Use ULINK+ through pyOCD as the baseline. Provide ST-LINK profiles with a lower @@ -38,8 +42,8 @@ then NUCLEO-F446RE. | Element | Responsibility | | --- | --- | -| `Trace.csolution.yml` | Device-based targets, Debug build, layer selection and debugger sets | -| `Projects/TraceDemo/TraceDemo.cproject.yml` | One application image per selected board; shared sources and CMSIS/RTX components | +| `Trace.csolution.yml` | Device-based targets, Debug and L552-only StackCorruption builds, layer selection and debugger sets | +| `Projects/TraceDemo/TraceDemo.cproject.yml` | One application image per selected context; shared sources and CMSIS/RTX components | | `Board//Board.clayer.yml` | Device header/startup/system selection, board `main()`, target adaptation and linker regions | | `Common/App`, `Common/Workloads`, `Common/Trace` | RTX startup, periodic signal generation and nonblocking ITM output | | `Projects/TraceDemo/RTE/CMSIS` | Shared RTX5 component configuration | @@ -62,6 +66,11 @@ Reset → device SystemInit / C runtime → board main() → target_init() → shared app_main() → RTX5 and the three signal threads ``` +The L552 `StackCorruption` context additionally creates its fault-injection thread. +The normal `Debug` contexts exclude that source and thread. See the +[stack-corruption workflow](TRACE_APP.md#stack-corruption-watch-nucleo-l552ze-q) +for the injected store and watch-only trace profile. + `target_init()` retains the vendor clock baseline and updates `SystemCoreClock`. RTX5/CMSIS OS Tick supply SVC, PendSV and SysTick handling. The Trace application is currently a CProject, not an application clayer. Explicit layer selection and diff --git a/docs/TRACE_APP.md b/docs/TRACE_APP.md index c218496..fd19f3f 100644 --- a/docs/TRACE_APP.md +++ b/docs/TRACE_APP.md @@ -1,6 +1,8 @@ # Trace application and workflow -All targets use the shared RTX5 workload. See [Validation](VALIDATION.md) +All targets use the shared RTX5 workload. L552's `ULINKplus StackCorruption` +adds one fault-injection thread and selects a dedicated trace profile. +See [Validation](VALIDATION.md) for measured results and remaining limits; [BUILD.md](BUILD.md) covers build and board prerequisites, and [DEBUG_PROBES.md](DEBUG_PROBES.md) covers probe selection. @@ -28,13 +30,90 @@ not console text; `g_app_state` and `g_app_core_clock_hz` support runtime inspec The RTX idle thread spins without `WFE`/`WFI`, so most PC samples can be in idle. PC sampling observes locations periodically; it need not catch each short update function. +## Stack-corruption watch (NUCLEO-L552ZE-Q) + +The `ULINKplus StackCorruption` set selects the `StackCorruption` build with +`TRACE_STACK_CORRUPTION=1`. Only this context includes and creates the fourth +thread, `StackCorruption`, from +[`stack_corruption.c`](../Common/Workloads/stack_corruption.c). +Its 256-byte stack is the aligned `g_stack_corruption_stack[64]` array; RTX writes +its `0xE25A2EA5` magic to the first word at the lowest stack address. + +After a two-second delay the thread fills a small local array, then uses a +deliberately invalid offset from that array to write `0xDEADC0DE` into the magic +word. The injected store uses integer address arithmetic and a volatile pointer +to target that one word while keeping the live stack pointer within its limits. +The next RTX context switch detects the changed magic and enters the existing +`osRtxErrorNotify` stack-overflow loop. This is an intentional terminal error; +restart the session to repeat it. + +The matching +[`ULINKplus StackCorruption` profile](<../.cmsis/Trace+NUCLEO-L552ZE-Q@ULINKplus StackCorruption.ctrace.yml>) +configures a single watch at `g_stack_corruption_stack`, `access: W`, `size: 4`, +`output: PC`. It disables ITM channels and periodic PC sampling, and requests no +timestamps or exception events. DWT synchronization (`16M`, `sync-on-run: true`) +provides the protocol framing needed to decode the short capture. The three +normal workload threads remain present, but their outputs are not selected for +capture. + +1. Select `NUCLEO-L552ZE-Q` / `ULINKplus StackCorruption`, build, and regenerate + the matching trace runtime profile against the `StackCorruption` ELF. +2. Check that the watch resolves to the first stack word and retains `output: PC`. + Start debugging with ULINK+ and run continuously from `main` for at least + three seconds, through the two-second injection delay and into the error + handler. Avoid breakpoints around the store: short breakpoint-to-breakpoint + runs have lost its PC packet at the capture boundary. +3. Pause to convert the pyOCD SWO recording with ctrace. Inspect + `.trace/Trace+NUCLEO-L552ZE-Q@ULINKplus StackCorruption.SWO.csv` for the PC of + the store in `stack_corruption_thread`. + +The watch reports every write to that address. A capture from reset can also +contain PCs from BSS initialization and RTX stack initialization; these are not +corruption events. The profile reports writing PCs rather than stored values; +without timestamps, CSV cycle fields do not measure elapsed time. +The verified continuous run captured both the RTX initialization PC and the +corruption-store PC. See [Validation](VALIDATION.md#nucleo-l552ze-q-stackcorruption--2026-10-05) +for the measured result and remaining pause-boundary limitation. + +## Stack-magic agent workflow + +Invoke `Use $trace-stack-magic-corruption-test` to use the project +[trace-stack-magic-corruption-test skill](../.agents/skills/trace-stack-magic-corruption-test/SKILL.md). +For a report from an existing CSV, request `Use $trace-stack-magic-corruption-test: +create only the MD report from the existing CSV`. This mode uses the associated +ELF and source without building, debugging, regenerating profiles or converting +RAW. No board is required. When capture-time verification is unavailable, the +report labels its use of the selected ELF and current source as unverified. + +The full capture workflow derives the profile and ELF from the active target set +and keeps that selection. Before running, it checks that the stack-magic watch uses `access: W`, +`size: 4` and `output: PC` and resolves to the intended stack word. + +During a full capture, the skill starts debugging, lets the application run, ends +the debug session and waits for final CSV conversion. Its `report_trace.py` helper uses `addr2line` +with the matching ELF to create `.trace/.SWO.md`, leaving the CSV unchanged. +Every CSV entry gets a section, including entries without a PC. Resolved source +code appears first, followed by `project-relative/file:line`, the original trace +fields and any resolution diagnostics. External Pack paths use `../` relative +to the project root. The agent then reads the surrounding source at the resolved +locations and adds a short explanation per entry, with relevant code context. +It distinguishes initialization from corruption and separates recorded PCs from +values or behavior inferred from the source. + +The Markdown report is the skill's only additional output file. Capture checks +keep their hashes and state in memory; the skill creates no capture archive, +manifest, ELF copy or check log. It uses the normal build/debug files in place +and automatically opens the completed report in VS Code. In a headless environment +it keeps the report and reports that opening was unavailable. Later captures +replace the current files. The capture-boundary limitations above still apply. + ## Configuration ownership In filenames below, `[@]` is omitted for an unnamed target set. | Owner / file | Responsibility | | --- | --- | -| Shared firmware | Periodic variable updates and nonblocking ITM writes. | +| Shared firmware | Periodic variable updates, nonblocking ITM writes and the optional stack-corruption thread. | | `Trace.csolution.yml` | Target set, probe, SWD and SWO transport, input/output clocks. | | `.cmsis/Trace+[@].ctrace.yml` | Editable DWT symbols, ITM channels, PC sampling, timestamps and synchronization. | | `out/Trace+.cbuild-run.yml` | Generated active-set description: image, debugger and Pack sequences. | @@ -46,7 +125,7 @@ clocks, pyOCD supplies standard ITM/TPIU setup in legacy mode, and the generated profile configures sources. Firmware does not configure comparators, enable ITM, or initialize trace pins/path. -Current profiles select both DWT variables with `access: W`, `size: 4`, and +The regular demo profiles select both DWT variables with `access: W`, `size: 4`, and `output: value`; ITM mask `0x00000002`; timestamp prescaler 1; and DWT sync `16M`. Board clocks, SWO rate and per-probe PC periods are listed in [Debugger profiles](DEBUG_PROBES.md#configured-probes-and-profiles). A clock change @@ -57,7 +136,8 @@ requires matching solution transport and profile timestamp settings, then regene This workflow uses the [reference trace-tool versions](BUILD.md#trace-toolchain). Their development status and source/release links are recorded there. -1. Select the target and, where available, `ULINKplus` or `STLink` in CMSIS +1. Select the target and available set (`ULINKplus`, `STLink`, or L552's + `ULINKplus StackCorruption`) in CMSIS **Manage Solution**; [build](BUILD.md) the selected image. 2. Enable `vscode-cmsis-debugger.enableTraceGenerationView` in local VS Code settings. Open **Trace Generation** and review the matching source `.ctrace.yml`. @@ -65,8 +145,10 @@ Their development status and source/release links are recorded there. 3. Run **CMSIS Debugger: Convert *.ctrace.yml to *.ctrace-run.yml** after every build and source-profile change. pyTS uses the active `.cbuild-run.yml` and current ELF; relinking can move variables without changing their names. -4. Check the generated profile resolves both symbols as signed 32-bit values and - includes the intended DWT, ITM, PC, timestamp and synchronization settings. +4. For the regular demo, check the generated profile resolves both symbols as + signed 32-bit values and includes the intended DWT, ITM, PC, timestamp and + synchronization settings. For StackCorruption, check the single stack-word + watch and its writing-PC output as described above. Start the matching debugger configuration and inspect the resulting capture. Equivalent offline generation with the bundled pyTS executable, for example: @@ -91,8 +173,9 @@ is not automatic. Manual decoding uses the matching profile beside the RAW: ``` Inspect decoder errors as well as the CSV; apply the checks in -[Validation](VALIDATION.md#test-scope). Keep RAW/CSV together for diagnosis. -The project currently has no reusable automated capture/check runner. +[Validation](VALIDATION.md#stm32-capture-test-scope). Keep RAW/CSV together for diagnosis. +The [stack-magic agent workflow](#stack-magic-agent-workflow) provides a reusable +capture and Markdown source-report workflow for stack-word PC watches. ## Temporary run-description overrides diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 8e666f6..7b51c62 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -3,10 +3,12 @@ Status: **2026-10-08**. Build, Flash loading/readback and RTX5 execution passed on all eight boards: the original six on 2026-09-28, STM32F4-DISCO on 2026-09-29, and NUCLEO-F446RE on 2026-10-01. -Both debuggers use the same image where tested. Board prerequisites +The regular demo uses the same image with both debuggers where tested. Board prerequisites and configuration are in [Board support](BOARD_SUPPORT.md); capture settings and commands are in [Debugger profiles](DEBUG_PROBES.md) and [Trace workflow](TRACE_APP.md). An additional L552 board passed the ST-LINK retest below after TrustZone/RDP recovery. +L552's separate StackCorruption build and its watch-only SWO capture passed the +specific checks recorded below. ## Results @@ -14,6 +16,7 @@ An additional L552 board passed the ST-LINK retest below after TrustZone/RDP rec PC range checks, and decoder error/overflow checks. **FAIL** means a capture check failed; **OPEN** means a finding remains unresolved; **—** means untested. A PASS does not establish complete capture from reset or repeatable start/pause/end behavior. +This table covers the regular demo; the StackCorruption experiment has its own scope below. | Board | Controlled SWO: ULINK+ | Controlled SWO: ST-LINK | IDE pause / debug end | | --- | --- | --- | --- | @@ -38,7 +41,7 @@ or decoder exit 0 alone is insufficient. On F429, opening the RAW file before tr setup passes a diagnostic ULINK+ capture; this is not an installed IDE fix. The same ordering still fails initial synchronization on MCB and H7. -## Test scope +## STM32 capture test scope - Controlled captures run for 30 s, then halt the core and drain for 50 ms before stopping. A fixed drain delay does not prove an empty probe queue. @@ -50,6 +53,106 @@ same ordering still fails initial synchronization on MCB and H7. - L552 was tested with hardware TrustZone disabled. Tests use the internal-memory and reset-clock baseline; they do not qualify external memory or other clock setups. +## NUCLEO-L552ZE-Q StackCorruption — 2026-10-05 + +**Build, load/debug, deliberate stack corruption and uninterrupted SWO capture: +PASS.** The dedicated `ULINKplus StackCorruption` set was tested on L552 with +ULINK+ `L39352482A`, a 4 MHz core clock and 1 Mbaud SWO, using the installed +[validation tools](BUILD.md#trace-toolchain). The set uses GDB server port +`43333`; the generated launch configuration left the other board's session on +port `3333` untouched. Installed pyOCD and Pack sources were unchanged. + +pyTS `0.6.1` resolved `g_stack_corruption_stack` to `0x200000F8` and configured +its first four bytes as the sole DWT write watch with PC output +(`COMP0=0x200000F8`, `FUNCTION0=0x835`). ITM channels, periodic PC sampling, +timestamps and exception events were disabled. Protocol synchronization and +`sync-on-run` remained enabled; an offline synthetic test demonstrated that ctrace +otherwise discarded these short PC captures before synchronization. + +Runtime inspection found four application threads plus RTX idle and timer +threads. Before the injected store, the first stack word held RTX's `0xE25A2EA5` +magic and `bad_destination` equalled the stack base. After the store it held +`0xDEADC0DE`. `PSP=0x200001A8` remained 176 bytes above the stack base. The next +context switch reached `osRtxErrorNotify` with stack-overflow code `1` and thread +object `0x200001F8`, matching `thread_control_block`; `CFSR=HFSR=0`. + +Running continuously from `main` for 4.5 seconds and then pausing produced a +34-byte RAW capture and automatic CSV with exactly two DWT PC records: +`0x08003388` from RTX stack initialization and `0x080005B2` from the corruption +store. Symbol lookup placed the latter at `stack_corruption_thread+82`; target +instruction readback confirmed opcode `0x601A` (`STR r2, [r3]`). Independent +decoding with ctrace `0.4.0` exited successfully and reproduced both PCs, with no +other trace records, decoder warnings/errors or overflow records. With timestamps +disabled, CSV cycle fields do not establish timing. + +**Pause-boundary limitation:** an earlier run with breakpoints immediately before +the store and in the error handler omitted the store's PC packet, although the +overwrite and RTX error were confirmed. The installed pyOCD capture path has a +3 ms flush interval and can discard bytes arriving after the RAW file closes; +this is a plausible explanation, not a proven cause of that missing packet. +For this experiment, run continuously through the two-second injection delay and +pause after at least three seconds; avoid breakpoints around the store when +checking trace delivery. Repeatable breakpoint/pause/end capture remains open. + +Local evidence (ignored by Git) is under +`.trace/captures/L552-StackCorruption-20261005/uninterrupted/`, including the +RAW/CSV, profile and independent decoder logs; the earlier breakpoint-driven run +is under the adjacent `stepped/` directory. The regular `ULINKplus`/`Debug` image +also rebuilt successfully after the shared-source changes; symbol lookup found +no `stack_corruption` symbols. Switching back to `StackCorruption` and rebuilding +retained the verified addresses above. A second uninterrupted load/debug run after +that switch reproduced the 34-byte capture and the same two PCs; its automatic +CSV and check results are saved in the adjacent `repeat/` directory. + +The [`trace-stack-magic-corruption-test` skill](../.agents/skills/trace-stack-magic-corruption-test/SKILL.md) +subsequently passed the complete build, trace-generation, load/run/end and CSV +annotation workflow on the same active set. This capture contained 69 RAW bytes +and three DWT writes: BSS clearing at `Reset_Handler` (`0x080006A0`, +`startup_stm32l552xx.s:88`), RTX initialization (`0x08003388`, +`rtx_thread.c:1039`) and corruption (`0x080005B2`, `stack_corruption.c:39`). +`arm-none-eabi-addr2line` resolved all three against the captured ELF. The final +annotation format then put matching, hash-verified source text in `note` and the +project-relative location in `info`. All other CSV cells were preserved, and a +repeated annotation was byte-identical. Original decoder notes are archived. + +The automatic CSV matched an independent ctrace decode with no decoder warnings, +errors or overflows. Original RAW/CSV, ELF, profiles, the capture manifest, +annotated CSV and check results are saved locally under +`.trace/captures/stack-magic-9nrr48yr/`. Isolated helper checks also passed for +stale CSVs, target/input changes, unresolved PCs, changed source text, CSV quoting +and failed symbolization without CSV modification. The debugger separately +reported failed evaluate responses and an adapter read error at session shutdown; +these diagnostics are not a decoder failure and were not investigated further. + +**Skill retest after capture cleanup: PASS.** After the previous `.trace` +captures were deleted, the skill regenerated the runtime profile, built and +loaded the active set, ran through the corruption without breakpoints, and ended +the debug session. Automatic conversion produced a fresh 46-byte RAW and two PC +records (RTX initialization and corruption); no manual conversion fallback was +needed. Independent decoding matched with no decoder warnings/errors. Both PCs +resolved into separate `note` (source text) and `info` (project-relative location) +fields, and repeating annotation was byte-identical. Current evidence is under +`.trace/captures/stack-magic-wbxrgwwb/`; the earlier local capture directories +listed above were removed by that cleanup. The debugger diagnostics above +recurred; the capture and annotation checks passed. + +**Markdown report: PASS (offline).** The revised skill leaves the CSV unchanged +and writes one Markdown section per CSV record. Against the archived original +capture in `stack-magic-wbxrgwwb`, both records produced sections with verified +source text, project-relative locations and original trace fields. The input CSV, +current CSV, ELF and manifest hashes stayed unchanged; a repeated report was +byte-identical. The report and `report-validation.json` are archived beside the +capture. Separate checks covered records without PCs, invalid PCs, inline frames, +decoder notes, Markdown escaping and failure without input/report replacement. +This output-format change did not require another hardware capture. + +A subsequent complete hardware run of the Markdown skill also passed: a fresh +69-byte RAW and automatic CSV contained BSS initialization, RTX initialization +and corruption. All three PCs resolved into three report sections; the CSV hash +remained unchanged after report generation. Independent decoding matched without +warnings/errors, and the debug session ended. Evidence and the archived report +are under `.trace/captures/stack-magic-yk0r6ae8/`. + ## NUCLEO-L552ZE-Q recovery and ST-LINK retest — 2026-09-30 **Build, Flash readback, RTX5 execution and controlled SWO: PASS.** This retest