Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

All notable changes to the "zephyr-tools" extension will be documented in this file.

### [0.7.1] - 2026-11-07

**Fixed:**
- probe-rs flashing of sysbuild builds (NCS 3.5+) now programs the SDK's `merged_<board_target>.hex` in a single download per board target. Bootloader/UICR images were flashed in a separate probe-rs session from the application, so the chip reset in between with UICR written but no application to reopen the debug port; the nRF91x1 locked it and the application download failed
- nRF91: after a flash that writes UICR (following a chip erase), the post-flash `probe-rs reset` is skipped and you're asked to press the board's reset button or power-cycle it. New UICR values, including the debug access words, only take effect on a pin or power-on reset, so until then the debug port is locked and the reset always failed

**Changed:**
- Sysbuild builds flashed with probe-rs need `SB_CONFIG_MERGED_HEX_FILES=y` (in `sysbuild.conf` or the board's `Kconfig.sysbuild`; the nRF9151 Feather board in nfed v3.5.x defaults it on). Without it, flashing stops with a message saying what to set. The separate bootloader download and its automatic `--preverify` are gone; the probe-rs preverify setting still applies. Partition Manager builds (NCS 3.4 and earlier) and single-image builds are unchanged

### [0.7.0] - 2026-10-15

**Added:**
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "zephyr-tools",
"displayName": "Circuit Dojo Zephyr SDK Tools",
"description": "Used for building your Zephyr projects.",
"version": "0.7.0",
"version": "0.7.1",
"license": "Apache-2.0",
"publisher": "circuitdojo",
"icon": "img/bulb.png",
Expand Down
169 changes: 64 additions & 105 deletions src/build/flash-hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import * as fs from "fs-extra";
import * as path from "path";
import * as yaml from "yaml";
import { hexRanges, mergeHexTexts, rangesOverlap } from "./intel-hex";

/**
* Resolve what probe-rs should program for a build.
Expand All @@ -17,11 +16,12 @@ import { hexRanges, mergeHexTexts, rangesOverlap } from "./intel-hex";
* build's current `zephyr/.config`, not from files on disk, since an SDK
* upgrade without a pristine build leaves the old `partitions.yml` and
* `merged.hex` behind.
* - Sysbuild without Partition Manager (NCS 3.5+, vanilla Zephyr): each image
* in `domains.yaml` `flash_order` names its hex in its `runners.yaml`. The
* non-application images (b0, MCUboot, provisioning, UICR) are merged into
* one bootloader hex, like Zephyr's `merged_<board>.hex`, which only exists
* when SB_CONFIG_MERGED_HEX_FILES is set.
* - Sysbuild without Partition Manager (NCS 3.5+, vanilla Zephyr): the SDK's
* `merged_<board_target>.hex`, one per board target in `domains.yaml`
* `flash_order`, generated when the board or project sets
* SB_CONFIG_MERGED_HEX_FILES=y. Every image goes down in one probe-rs
* download per board target, so the chip is never reset between images with
* only some of them written.
* - Single-image builds: the hex named in `zephyr/runners.yaml`.
*/

Expand All @@ -30,11 +30,6 @@ export interface FlashImage {
label: string;
/** Absolute path to the hex file. */
hexPath: string;
/**
* Bootloader images rarely change between builds; preverify them so
* probe-rs skips programming when the device already matches.
*/
preverify: boolean;
}

export type FlashPlan =
Expand All @@ -44,13 +39,30 @@ export type FlashPlan =
/** Directory under the build dir for hex files generated for flashing. */
export const FLASH_WORK_DIR = "zephyr-tools";

/** Sysbuild Kconfig symbol that makes the SDK write `merged_<board_target>.hex`. */
const MERGED_HEX_FILES_SYMBOL = "SB_CONFIG_MERGED_HEX_FILES";

const SYSBUILD_MERGED_HEX = /^merged_.+\.hex$/;

/** `merged_<board_target>.hex` from Zephyr sysbuild (or `merged_CPUNET.hex` from Partition Manager). */
export function isSysbuildMergedHex(fileName: string): boolean {
return SYSBUILD_MERGED_HEX.test(fileName);
}

/**
* The `merged_<board_target>.hex` name sysbuild uses for a CONFIG_BOARD_TARGET
* (see zephyr/share/sysbuild/cmake/modules/sysbuild_merged_hex.cmake).
*/
export function mergedHexFileName(boardTarget: string): string {
return `merged_${boardTarget.replace(/[/.@]/g, "_")}.hex`;
}

/** CONFIG_BOARD_TARGET from an image's `zephyr/.config`. */
export function dotConfigBoardTarget(dotConfig: string): string | undefined {
const match = /^CONFIG_BOARD_TARGET="([^"]+)"\s*$/m.exec(dotConfig);
return match?.[1];
}

/**
* Which Partition Manager layout a build's `zephyr/.config` uses, if any:
* sysbuild (SB_CONFIG_PARTITION_MANAGER, merged.hex in the build root) or
Expand All @@ -66,34 +78,14 @@ export function partitionManagerLayout(dotConfig: string): "sysbuild" | "child-i
return undefined;
}

/**
* probe-rs erases whole sectors, so two downloads must not share one. 4 KiB
* is the flash page size on nRF5x/nRF91.
*/
const FLASH_PAGE_SIZE = 0x1000;

function toPages(ranges: Array<[number, number]>): Array<[number, number]> {
return ranges.map(([start, end]) => [
Math.floor(start / FLASH_PAGE_SIZE) * FLASH_PAGE_SIZE,
Math.ceil(end / FLASH_PAGE_SIZE) * FLASH_PAGE_SIZE,
]);
}

export interface SysbuildDomains {
defaultDomain: string;
flashOrder: string[];
}

export function parseDomainsYaml(text: string): SysbuildDomains | string {
const parsed = yaml.parse(text) as { default?: unknown; flash_order?: unknown } | null;
if (!parsed || typeof parsed.default !== "string") {
return "domains.yaml has no default domain";
}
const order = parsed.flash_order;
/** `flash_order` from a sysbuild `domains.yaml`. */
export function parseDomainsFlashOrder(text: string): string[] | string {
const parsed = yaml.parse(text) as { flash_order?: unknown } | null;
const order = parsed?.flash_order;
if (!Array.isArray(order) || order.length === 0 || !order.every(name => typeof name === "string")) {
return "domains.yaml has no flash_order";
}
return { defaultDomain: parsed.default, flashOrder: order as string[] };
return order as string[];
}

/** `config.hex_file` from a runners.yaml. */
Expand All @@ -103,52 +95,15 @@ export function runnersYamlHexFile(text: string): string | undefined {
return typeof hexFile === "string" && hexFile !== "" ? hexFile : undefined;
}

export interface SysbuildImage {
name: string;
hexPath: string;
hexText: string;
}

export type SysbuildFlashSplit =
| { ok: true; bootloaders: SysbuildImage[]; bootloaderHex?: string; app: SysbuildImage }
| { ok: false; error: string };

/**
* Split sysbuild images (in flash order) into one merged bootloader hex and
* the application image. Fails if they share a flash page, since flashing
* them as two downloads would then erase or overwrite each other.
*/
export function splitSysbuildImages(defaultDomain: string, images: SysbuildImage[]): SysbuildFlashSplit {
const app = images.find(image => image.name === defaultDomain);
if (!app) {
return { ok: false, error: `The default image "${defaultDomain}" is not in domains.yaml flash_order.` };
}
const bootloaders = images.filter(image => image !== app);
if (bootloaders.length === 0) {
return { ok: true, bootloaders, app };
}
const bootloaderHex = mergeHexTexts(bootloaders.map(image => image.hexText));
if (rangesOverlap(toPages(hexRanges(bootloaderHex)), toPages(hexRanges(app.hexText)))) {
return {
ok: false,
error: `Images ${bootloaders.map(image => image.name).join(", ")} share flash pages with the application image "${app.name}".`,
};
}
return { ok: true, bootloaders, bootloaderHex, app };
}

async function hexFromRunnersYaml(zephyrDir: string, imageName: string): Promise<string | { error: string }> {
async function hexFromRunnersYaml(zephyrDir: string): Promise<string | { error: string }> {
const runnersPath = path.join(zephyrDir, "runners.yaml");
if (!(await fs.pathExists(runnersPath))) {
return { error: `Image "${imageName}" has no ${runnersPath}. Build project before flashing.` };
}
const hexFile = runnersYamlHexFile(await fs.readFile(runnersPath, "utf8"));
if (!hexFile) {
return { error: `${runnersPath} has no hex_file.` };
}
const hexPath = path.isAbsolute(hexFile) ? hexFile : path.join(zephyrDir, hexFile);
if (!(await fs.pathExists(hexPath))) {
return { error: `Hex for image "${imageName}" not found at ${hexPath}. Build project before flashing.` };
return { error: `${hexPath} not found. Build project before flashing.` };
}
return hexPath;
}
Expand All @@ -158,41 +113,45 @@ async function resolvePartitionManager(buildDir: string, layout: "sysbuild" | "c
if (!(await fs.pathExists(hexPath))) {
return { ok: false, error: `Partition Manager build has no ${hexPath}. Build project before flashing.` };
}
return { ok: true, images: [{ label: "merged.hex", hexPath, preverify: false }] };
return { ok: true, images: [{ label: "merged.hex", hexPath }] };
}

async function resolveSysbuild(buildDir: string): Promise<FlashPlan> {
const domains = parseDomainsYaml(await fs.readFile(path.join(buildDir, "domains.yaml"), "utf8"));
if (typeof domains === "string") {
return { ok: false, error: `${path.join(buildDir, "domains.yaml")}: ${domains}` };
}

const images: SysbuildImage[] = [];
for (const name of domains.flashOrder) {
const hexPath = await hexFromRunnersYaml(path.join(buildDir, name, "zephyr"), name);
if (typeof hexPath !== "string") {
return { ok: false, error: hexPath.error };
const domainsPath = path.join(buildDir, "domains.yaml");
const flashOrder = parseDomainsFlashOrder(await fs.readFile(domainsPath, "utf8"));
if (typeof flashOrder === "string") {
return { ok: false, error: `${domainsPath}: ${flashOrder}` };
}

// One merged hex per board target, in the order the targets first appear.
const fileNames: string[] = [];
for (const image of flashOrder) {
const dotConfigPath = path.join(buildDir, image, "zephyr", ".config");
if (!(await fs.pathExists(dotConfigPath))) {
return { ok: false, error: `Image "${image}" has no ${dotConfigPath}. Build project before flashing.` };
}
const boardTarget = dotConfigBoardTarget(await fs.readFile(dotConfigPath, "utf8"));
if (!boardTarget) {
return { ok: false, error: `${dotConfigPath} has no CONFIG_BOARD_TARGET.` };
}
const fileName = mergedHexFileName(boardTarget);
if (!fileNames.includes(fileName)) {
fileNames.push(fileName);
}
images.push({ name, hexPath, hexText: await fs.readFile(hexPath, "utf8") });
}

const split = splitSysbuildImages(domains.defaultDomain, images);
if (!split.ok) {
return split;
}

const plan: FlashImage[] = [];
if (split.bootloaderHex !== undefined) {
const bootloaderPath = path.join(buildDir, FLASH_WORK_DIR, "bootloaders.hex");
await fs.outputFile(bootloaderPath, split.bootloaderHex);
plan.push({
label: `bootloaders (${split.bootloaders.map(image => image.name).join(", ")})`,
hexPath: bootloaderPath,
preverify: true,
});
const images: FlashImage[] = [];
for (const fileName of fileNames) {
const hexPath = path.join(buildDir, fileName);
if (!(await fs.pathExists(hexPath))) {
return {
ok: false,
error: `${hexPath} not found. Set ${MERGED_HEX_FILES_SYMBOL}=y in the project's sysbuild.conf (or the board's Kconfig.sysbuild) and rebuild.`,
};
}
images.push({ label: fileName, hexPath });
}
plan.push({ label: split.app.name, hexPath: split.app.hexPath, preverify: false });
return { ok: true, images: plan };
return { ok: true, images };
}

export async function resolveFlashImages(buildDir: string): Promise<FlashPlan> {
Expand All @@ -209,11 +168,11 @@ export async function resolveFlashImages(buildDir: string): Promise<FlashPlan> {
}
const zephyrDir = path.join(buildDir, "zephyr");
if (await fs.pathExists(path.join(zephyrDir, "runners.yaml"))) {
const hexPath = await hexFromRunnersYaml(zephyrDir, "zephyr");
const hexPath = await hexFromRunnersYaml(zephyrDir);
if (typeof hexPath !== "string") {
return { ok: false, error: hexPath.error };
}
return { ok: true, images: [{ label: path.basename(hexPath), hexPath, preverify: false }] };
return { ok: true, images: [{ label: path.basename(hexPath), hexPath }] };
}
return { ok: false, error: `No build output found in ${buildDir}. Build project before flashing.` };
}
40 changes: 0 additions & 40 deletions src/build/intel-hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,32 +77,6 @@ export function readHexBytes(hexText: string): HexBytes {
return bytes;
}

/** Contiguous [start, end) address ranges covered by a hex file's data. */
export function hexRanges(hexText: string): Array<[number, number]> {
const ranges: Array<[number, number]> = [];
forEachRecord(hexText, (_line, record, base) => {
if (record?.type !== 0x00 || record.data.length === 0) {
return;
}
ranges.push([base + record.offset, base + record.offset + record.data.length]);
});
ranges.sort((a, b) => a[0] - b[0]);
const merged: Array<[number, number]> = [];
for (const range of ranges) {
const last = merged[merged.length - 1];
if (last && range[0] <= last[1]) {
last[1] = Math.max(last[1], range[1]);
} else {
merged.push([range[0], range[1]]);
}
}
return merged;
}

export function rangesOverlap(a: Array<[number, number]>, b: Array<[number, number]>): boolean {
return a.some(([aStart, aEnd]) => b.some(([bStart, bEnd]) => aStart < bEnd && bStart < aEnd));
}

/** Whether a hex file contains any data bytes. */
export function hexHasData(hexText: string): boolean {
let found = false;
Expand All @@ -114,20 +88,6 @@ export function hexHasData(hexText: string): boolean {
return found;
}

/**
* Merge hex files in order; a later file replaces earlier data at the same
* address. Same semantics as Zephyr's `mergehex.py --overlap replace`.
*/
export function mergeHexTexts(hexTexts: string[]): string {
const bytes: HexBytes = new Map();
for (const text of hexTexts) {
for (const [address, byte] of readHexBytes(text)) {
bytes.set(address, byte);
}
}
return writeHex(bytes);
}

/** Serialize bytes as Intel HEX with 16-byte data records. */
export function writeHex(bytes: HexBytes): string {
const addresses = [...bytes.keys()].sort((a, b) => a - b);
Expand Down
Loading
Loading