feat(core/build): introduce board-driven build configuration in xtask
What changed, and why it matters
This commit is a build-system refactoring for Trezor hardware wallets. It moves model-specific settings (which CPU, which board, which features) out of hard-coded Rust code and into external TOML configuration files read at build time. There is no direct evidence this fixes a security vulnerability; it is a maintainability and architecture change.
No immediate security action required. Treat as a normal build-system refactor. Reviewers may want to verify that the new TOML-based feature resolution does not accidentally enable unintended features (e.g., optiga/tropic/debuglink) for production builds, and that model.toml/board.toml files are version-controlled and reviewed.
Security signals we found
Build-system refactoring with no runtime code changes to firmware
New TOML parsing introduces dependency on toml, serde, indexmap, hashbrown crates
Model feature selection changed from direct features to dep-features
Vendor header logic now propagates errors via Result instead of panicking/returning static str
No mention of vulnerability, CVE, security fix, or researcher attribution
Evidence from the diff
The patch introduces board-driven build configuration in the xtask build helper. It adds serde/toml dependencies, creates config.rs and model.rs modules, and replaces hard-coded Model methods (target_triple, has_optiga, has_tropic, has_secmon, openocd_target) with data loaded from models/
Changed components
core/embed/xtask build toolingcore/embed/xbuild build scriptsmodels/<MODEL>/model.toml (new configuration files not present in diff)models/<MODEL>/boards/<BOARD>.toml (new configuration files not present in diff)Inspect captured patch +471 / −152
diff --git a/core/embed/Cargo.lock b/core/embed/Cargo.lock
index c6c25a9b..dfcf5776 100644
--- a/core/embed/Cargo.lock
+++ b/core/embed/Cargo.lock
@@ -287,6 +287,12 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -368,6 +374,12 @@ dependencies = [
"byteorder",
]
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
[[package]]
name = "heapless"
version = "0.9.2"
@@ -398,6 +410,16 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5"
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
[[package]]
name = "io"
version = "0.0.0"
@@ -758,6 +780,15 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "shlex"
version = "1.3.0"
@@ -855,6 +886,47 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_edit",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_write",
+ "winnow",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
[[package]]
name = "trezor-tjpgdec"
version = "0.1.0"
@@ -981,6 +1053,15 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "without-alloc"
version = "0.2.2"
@@ -1013,8 +1094,10 @@ dependencies = [
"cargo_metadata",
"clap",
"owo-colors",
+ "serde",
"serde_json",
"tempfile",
+ "toml",
]
[[package]]
diff --git a/core/embed/Cargo.toml b/core/embed/Cargo.toml
index fa68580a..4891c86a 100644
--- a/core/embed/Cargo.toml
+++ b/core/embed/Cargo.toml
@@ -95,8 +95,10 @@ owo-colors = "4.3.0"
pathdiff = "0.2.3"
pkg-config = "0.3.28"
rand = { version = "0.10.1", default-features = false }
+serde = "1.0.228"
serde_json = "1.0.145"
tempfile = { version = "3.25.0", default-features = false }
+toml = "0.8.23"
zlib-rs = "0.6.3"
xbuild = { path = "xbuild" }
diff --git a/core/embed/xbuild/src/trezor.rs b/core/embed/xbuild/src/trezor.rs
index 17d75440..4dc83e52 100644
--- a/core/embed/xbuild/src/trezor.rs
+++ b/core/embed/xbuild/src/trezor.rs
@@ -19,16 +19,12 @@ fn package_name() -> Result<String> {
Ok(env::var("CARGO_PKG_NAME")?)
}
-/// Returns the current model id (T2T1, ..) based on the enabled feature.
+/// Returns the current model id (T2T1, ..) from the DEP_MODELS_MODEL
+/// environment variable emitted by the `models` crate's build script.
pub fn current_model_id() -> Result<String> {
- for (key, value) in env::vars() {
- if let Some(model) = key.strip_prefix("CARGO_FEATURE_MODEL_")
- && value == "1"
- {
- return Ok(model.to_string());
- }
- }
- bail!("No model feature enabled")
+ env::var("DEP_MODELS_MODEL").map_err(|_| {
+ color_eyre::eyre::eyre!("DEP_MODELS_MODEL not set — is `models` a direct dependency?")
+ })
}
/// Returns the path to the vendor header binary for the given build target.
@@ -44,10 +40,10 @@ pub fn vendor_header_path(models_dir: impl AsRef<Path>, target: &str) -> Result<
}
let vendor = if target == "prodtest" {
- get_prodtest_vendor()
+ get_prodtest_vendor()?
} else {
// firmware, secmon and kernel all must use the same vendor header
- get_firmware_vendor()
+ get_firmware_vendor()?
};
Ok(models_dir
@@ -57,8 +53,8 @@ pub fn vendor_header_path(models_dir: impl AsRef<Path>, target: &str) -> Result<
.join(format!("vendorheader_{}.bin", vendor)))
}
-fn get_firmware_vendor() -> &'static str {
- if has_feature("bootloader_devel") {
+fn get_firmware_vendor() -> Result<&'static str> {
+ Ok(if has_feature("bootloader_devel") {
if has_feature("unsafe_fw") {
"unsafe_signed_dev"
} else {
@@ -66,23 +62,23 @@ fn get_firmware_vendor() -> &'static str {
}
} else if !has_feature("production") {
"unsafe_signed_prod"
- } else if has_feature("model_t2t1") {
+ } else if current_model_id()? == "T2T1" {
"satoshilabs_signed_prod"
} else if has_feature("bitcoin_only") {
"trezor_btconly_signed_prod"
} else {
"trezor_signed_prod"
- }
+ })
}
-fn get_prodtest_vendor() -> &'static str {
- if has_feature("bootloader_devel") {
+fn get_prodtest_vendor() -> Result<&'static str> {
+ Ok(if has_feature("bootloader_devel") {
"prodtest_DO_NOT_SIGN_signed_dev"
} else if has_feature("production") {
"prodtest_signed_prod"
} else {
"unsafe_signed_prod"
- }
+ })
}
/// Entry point for build scripts that compile C libraries.
diff --git a/core/embed/xtask/Cargo.toml b/core/embed/xtask/Cargo.toml
index 66971d57..8fdfd17a 100644
--- a/core/embed/xtask/Cargo.toml
+++ b/core/embed/xtask/Cargo.toml
@@ -7,8 +7,10 @@ edition = "2024"
clap = { workspace = true, features = ["derive", "std", "help", "usage", "error-context", "suggestions"] }
anyhow.workspace = true
cargo_metadata.workspace = true
+serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
owo-colors.workspace = true
+toml.workspace = true
[dev-dependencies]
tempfile.workspace = true
diff --git a/core/embed/xtask/src/args.rs b/core/embed/xtask/src/args.rs
index 47a589f7..3b15a28a 100644
--- a/core/embed/xtask/src/args.rs
+++ b/core/embed/xtask/src/args.rs
@@ -1,95 +1,14 @@
-use anyhow::{Context, Result, anyhow, bail};
+use anyhow::{Result, anyhow, bail};
use clap::{Args, Parser, Subcommand, ValueEnum};
use std::process;
-use crate::helpers;
+use crate::config;
-#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
-pub enum Model {
- #[value(name = "d001")]
- D001,
- #[value(name = "d002")]
- D002,
- #[value(name = "t2t1")]
- T2T1,
- #[value(name = "t2b1")]
- T2B1,
- #[value(name = "t3b1")]
- T3B1,
- #[value(name = "t3t1")]
- T3T1,
- #[value(name = "t3w1")]
- T3W1,
-}
-
-impl Model {
- /// Returns feature name corresponding to the model
- pub fn feature_name(self) -> &'static str {
- match self {
- Model::D001 => "model_d001",
- Model::D002 => "model_d002",
- Model::T2T1 => "model_t2t1",
- Model::T2B1 => "model_t2b1",
- Model::T3B1 => "model_t3b1",
- Model::T3T1 => "model_t3t1",
- Model::T3W1 => "model_t3w1",
- }
- }
-
- /// Returns the Rust target triple for the building firmware for hardware target
- pub fn target_triple(self) -> &'static str {
- match self {
- Model::D001 | Model::T2T1 | Model::T2B1 => "thumbv7em-none-eabihf",
- Model::D002 | Model::T3B1 | Model::T3T1 | Model::T3W1 => "thumbv8m.main-none-eabihf",
- }
- }
-
- /// Returns the model ID used in artifact naming
- pub fn model_id(self) -> &'static str {
- match self {
- Model::D001 => "D001",
- Model::D002 => "D002",
- Model::T2T1 => "T2T1",
- Model::T2B1 => "T2B1",
- Model::T3B1 => "T3B1",
- Model::T3T1 => "T3T1",
- Model::T3W1 => "T3W1",
- }
- }
-
- /// Returns whether the model has a secure monitor
- pub fn has_secmon(self) -> bool {
- matches!(self, Model::D002 | Model::T3W1)
- }
-
- /// Returns whether the model has OPTIGA support
- pub fn has_optiga(self) -> bool {
- matches!(self, Model::T2B1 | Model::T3B1 | Model::T3T1 | Model::T3W1)
- }
-
- /// Returns whether the model has TROPIC support
- pub fn has_tropic(self) -> bool {
- matches!(self, Model::T3W1)
- }
+pub use crate::model::Model;
- /// Returns the OpenOCD target configuration file for the model
- pub fn openocd_target(self) -> &'static str {
- match self {
- Model::D001 | Model::T2T1 | Model::T2B1 => "target/stm32f4x.cfg",
- Model::D002 | Model::T3B1 | Model::T3T1 | Model::T3W1 => "target/stm32u5x.cfg",
- }
- }
-
- /// Returns the path to the model-specific memory.ld file
- pub fn model_memory_ld(self) -> Result<std::path::PathBuf> {
- let mem_ld = helpers::workspace_dir()?
- .join("models")
- .join(self.model_id())
- .join("memory.ld")
- .canonicalize()
- .with_context(|| format!("Failed to locate memory.ld for model {}", self.model_id()))?;
- Ok(mem_ld)
- }
+pub struct ResolvedBuild {
+ pub features: Vec<String>,
+ pub target_triple: Option<&'static str>,
}
#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
@@ -165,7 +84,16 @@ impl Component {
pub fn dependency(self, model: Model) -> Option<Component> {
match self {
Component::Firmware => Some(Component::Kernel),
- Component::Kernel if model.has_secmon() => Some(Component::Secmon),
+ Component::Kernel => {
+ let has_secmon = config::ModelConfig::load(model.model_id())
+ .map(|c| c.secmon)
+ .unwrap_or(false);
+ if has_secmon {
+ Some(Component::Secmon)
+ } else {
+ None
+ }
+ }
_ => None,
}
}
@@ -222,7 +150,7 @@ pub enum Cmd {
Combine(CombineArgs),
}
-#[derive(Args, Debug, Copy, Clone)]
+#[derive(Args, Debug, Clone)]
#[command(override_usage = "xtask build <COMPONENT> --model <MODEL> [OPTIONS]")]
pub struct BuildArgs {
pub component: Component,
@@ -320,6 +248,10 @@ pub struct BuildArgs {
#[arg(long)]
pub disable_optiga: bool,
+ /// Board revision to build for (defaults to model's default_board)
+ #[arg(long, short = 'b')]
+ pub board: Option<String>,
+
/// Disable TROPIC support
#[arg(long, num_args = 0..=1, default_missing_value = "true")]
pub disable_tropic: Option<bool>,
@@ -353,20 +285,20 @@ impl BuildArgs {
}
}
- /// Resolves the list of cargo features to enable based on the provided cli arguments
- pub fn resolve_features(&self) -> Result<Vec<&'static str>> {
- let mut features = vec![self.model.feature_name()];
+ /// Resolves cargo features and target triple from the provided cli arguments.
+ pub fn resolve_features(&self) -> Result<ResolvedBuild> {
+ let mut features: Vec<String> = vec![self.model.feature_name()];
if self.emulator {
- features.push("emulator");
+ features.push("emulator".into());
}
if self.production {
- features.push("production");
+ features.push("production".into());
}
if self.bootloader_devel {
- features.push("bootloader_devel");
+ features.push("bootloader_devel".into());
}
// if self.production && self.bootloader_devel {
@@ -374,24 +306,24 @@ impl BuildArgs {
// }
if self.force_bootloader_upgrade {
- features.push("force_bootloader_upgrade");
+ features.push("force_bootloader_upgrade".into());
}
if self.emulator {
- features.push("dbg_console");
+ features.push("dbg_console".into());
if self.asan {
- features.push("asan");
+ features.push("asan".into());
}
} else {
match (self.component, self.dbg_console) {
- (Component::Firmware, Some(_)) => features.push("dbg_console"),
+ (Component::Firmware, Some(_)) => features.push("dbg_console".into()),
(Component::Secmon, Some(ConsoleType::Vcp)) => (),
(Component::Boardloader, Some(ConsoleType::Vcp)) => (),
(Component::Prodtest, Some(ConsoleType::Vcp)) => (),
- (_, Some(ConsoleType::Vcp)) => features.push("dbg_console_vcp"),
- (_, Some(ConsoleType::Swo)) => features.push("dbg_console_swo"),
- (_, Some(ConsoleType::SystemView)) => features.push("dbg_console_sysview"),
+ (_, Some(ConsoleType::Vcp)) => features.push("dbg_console_vcp".into()),
+ (_, Some(ConsoleType::Swo)) => features.push("dbg_console_swo".into()),
+ (_, Some(ConsoleType::SystemView)) => features.push("dbg_console_sysview".into()),
(_, None) => (),
}
}
@@ -400,9 +332,9 @@ impl BuildArgs {
if self.component == Component::Firmware {
if pyopt {
- features.push("pyopt");
+ features.push("pyopt".into());
} else {
- features.push("debug");
+ features.push("debug".into());
}
if self.frozen || !self.emulator {
@@ -410,35 +342,35 @@ impl BuildArgs {
}
if self.source_lines.unwrap_or(self.emulator) {
- features.push("micropy_enable_source_lines");
+ features.push("micropy_enable_source_lines".into());
}
if self.benchmark {
- features.push("benchmark");
+ features.push("benchmark".into());
}
if self.log_stack_usage {
- features.push("log_stack_usage");
+ features.push("log_stack_usage".into());
}
if self.block_on_vcp {
- features.push("block_on_vcp");
+ features.push("block_on_vcp".into());
}
if self.apps {
- features.push("app_loading");
+ features.push("app_loading".into());
}
if self.mem_perf {
- features.push("memperf");
+ features.push("memperf".into());
}
if !self.production {
- features.push("dev_keys");
+ features.push("dev_keys".into());
}
if self.n4w1 {
- features.push("n4w1");
+ features.push("n4w1".into());
}
}
@@ -447,22 +379,22 @@ impl BuildArgs {
Component::Secmon | Component::Kernel | Component::Firmware
) {
if !self.btc_only {
- features.push("universal_fw");
+ features.push("universal_fw".into());
}
if !pyopt {
- features.push("optiga_testing");
+ features.push("optiga_testing".into());
}
if self.unsafe_fw {
- features.push("unsafe_fw");
+ features.push("unsafe_fw".into());
}
if self.storage_insecure_testing_mode {
if self.production {
bail!("storage_insecure_testing_mode cannot be enabled in production builds");
}
- features.push("storage_insecure_testing_mode");
+ features.push("storage_insecure_testing_mode".into());
}
}
@@ -471,21 +403,21 @@ impl BuildArgs {
Component::Firmware | Component::Bootloader | Component::Prodtest
) {
if self.perf_overlay {
- features.push("ui_performance_overlay");
+ features.push("ui_performance_overlay".into());
}
if self.debug_link.unwrap_or(!pyopt) {
- features.push("debuglink");
- features.push("ui_debug");
+ features.push("debuglink".into());
+ features.push("ui_debug".into());
}
if self.disable_animation {
- features.push("disable_animation");
+ features.push("disable_animation".into());
}
}
if matches!(self.component, Component::Kernel) && self.debug_link.unwrap_or(!pyopt) {
- features.push("debuglink");
+ features.push("debuglink".into());
}
if matches!(
@@ -493,25 +425,70 @@ impl BuildArgs {
Component::Firmware | Component::Kernel | Component::Secmon | Component::Prodtest
) {
if self.model.has_optiga() && !self.disable_optiga {
- features.push("optiga");
+ features.push("optiga".into());
}
if self.model.has_tropic() && !self.disable_tropic.unwrap_or(self.emulator) {
- features.push("tropic");
+ features.push("tropic".into());
}
}
- Ok(features)
+ // By default, we want to build with `frozen` for hardware targets
+ if self
+ .frozen
+ .unwrap_or(self.component.frozen_default(self.emulator))
+ {
+ features.push("frozen".into());
+ }
+
+ // Board and model-intrinsic features from TOML config
+ let model_config = config::ModelConfig::load(self.model.model_id())?;
+ let board_id = if self.emulator {
+ model_config
+ .emulator_board
+ .as_deref()
+ .ok_or_else(|| anyhow!("Model {} has no emulator board", self.model.model_id()))?
+ .to_string()
+ } else {
+ self.board
+ .clone()
+ .unwrap_or_else(|| model_config.default_board.clone())
+ };
+ let mut board_feat = config::resolve_board_features(
+ self.model.model_id(),
+ &model_config,
+ &board_id,
+ self.component,
+ )?
+ .features;
+ if self.disable_optiga {
+ board_feat.retain(|f| f != "optiga");
+ }
+ if self.disable_tropic.unwrap_or(self.emulator) {
+ board_feat.retain(|f| f != "tropic");
+ }
+ features.extend(board_feat);
+
+ let target_triple = if self.emulator {
+ None
+ } else {
+ Some(model_config.target_triple()?)
+ };
+
+ Ok(ResolvedBuild {
+ features,
+ target_triple,
+ })
}
// Configures the cargo command with the appropriate arguments and features
// based on the provided cli arguments
pub fn configure_cargo(&self, cmd: &mut process::Command) -> Result<()> {
- let features = self.resolve_features()?;
+ let resolved = self.resolve_features()?;
let mut rebuild_std = false;
cmd.args(["--package", self.component.package_name(self.emulator)]);
- cmd.args(["--features", &features.join(",")]);
+ cmd.args(["--features", &resolved.features.join(",")]);
cmd.args(["--profile", self.profile_name()]);
if self.profile_name() == "release" {
@@ -519,8 +496,8 @@ impl BuildArgs {
rebuild_std = true;
}
- if !self.emulator {
- cmd.args(["--target", self.model.target_triple()]);
+ if let Some(triple) = resolved.target_triple {
+ cmd.args(["--target", triple]);
}
if self.emit_memory_analysis {
diff --git a/core/embed/xtask/src/cargo.rs b/core/embed/xtask/src/cargo.rs
index cc672eca..b41375f5 100644
--- a/core/embed/xtask/src/cargo.rs
+++ b/core/embed/xtask/src/cargo.rs
@@ -8,7 +8,7 @@ use crate::{
};
pub fn build(args: BuildArgs) -> Result<()> {
- build_impl(args, false)?;
+ build_impl(args.clone(), false)?;
if args.storage_insecure_testing_mode {
println!(
@@ -95,7 +95,7 @@ fn build_impl(args: BuildArgs, is_dependency: bool) -> Result<()> {
build_impl(
BuildArgs {
component: dependency,
- ..args
+ ..args.clone()
},
true,
)?;
diff --git a/core/embed/xtask/src/config.rs b/core/embed/xtask/src/config.rs
new file mode 100644
index 00000000..86e0cf2f
--- /dev/null
+++ b/core/embed/xtask/src/config.rs
@@ -0,0 +1,198 @@
+use anyhow::{Context, Result, anyhow, bail};
+use serde::Deserialize;
+use std::collections::{HashMap, HashSet};
+
+use crate::args::Component;
+use crate::helpers::workspace_dir;
+
+#[derive(Deserialize)]
+pub struct ModelConfig {
+ /// Model identifier (e.g. "T3W1"). Not part of model.toml; populated by
+ /// [`ModelConfig::load`] from the directory the config was read from.
+ #[serde(skip)]
+ pub model_id: String,
+ pub mcu: String,
+ pub default_board: String,
+ pub emulator_board: Option<String>,
+ pub features: Vec<String>,
+ #[serde(default)]
+ pub secmon: bool,
+ #[serde(default)]
+ pub targets: HashMap<String, ModelTargetOverride>,
+}
+
+impl ModelConfig {
+ pub fn load(model_id: &str) -> Result<Self> {
+ let path = workspace_dir()?
+ .join("models")
+ .join(model_id)
+ .join("model.toml");
+ let content = std::fs::read_to_string(&path)
+ .with_context(|| format!("Failed to read model config: {}", path.display()))?;
+ let mut config: ModelConfig = toml::from_str(&content)
+ .with_context(|| format!("Failed to parse model config: {}", path.display()))?;
+ config.model_id = model_id.to_string();
+ Ok(config)
+ }
+
+ pub fn mcu_feature(&self) -> String {
+ format!("mcu_{}", self.mcu)
+ }
+
+ pub fn target_triple(&self) -> Result<&'static str> {
+ match self.mcu.as_str() {
+ "stm32f427" | "stm32f429" => Ok("thumbv7em-none-eabihf"),
+ "stm32u58" | "stm32u5g" => Ok("thumbv8m.main-none-eabihf"),
+ mcu => Err(anyhow!("Unknown MCU: {mcu}")),
+ }
+ }
+
+ pub fn openocd_target(&self) -> Result<&'static str> {
+ match self.mcu.as_str() {
+ "stm32f427" | "stm32f429" => Ok("target/stm32f4x.cfg"),
+ "stm32u58" | "stm32u5g" => Ok("target/stm32u5x.cfg"),
+ mcu => Err(anyhow!("Unknown MCU: {mcu}")),
+ }
+ }
+}
+
+pub struct Peripheral {
+ pub name: String,
+ pub features: Vec<String>,
+}
+
+pub struct BoardConfig {
+ pub header: String,
+ pub peripherals: Vec<Peripheral>,
+}
+
+impl BoardConfig {
+ pub fn load(model_id: &str, board_id: &str) -> Result<Self> {
+ let path = workspace_dir()?
+ .join("models")
+ .join(model_id)
+ .join("boards")
+ .join(format!("{}.toml", board_id));
+ let content = std::fs::read_to_string(&path)
+ .with_context(|| format!("Failed to read board config: {}", path.display()))?;
+ Self::parse(&content)
+ .with_context(|| format!("Failed to parse board config: {}", path.display()))
+ }
+
+ fn parse(content: &str) -> Result<Self> {
+ let value: toml::Value = toml::from_str(content)?;
+ let table = value
+ .as_table()
+ .ok_or_else(|| anyhow!("Board config must be a TOML table"))?;
+
+ let header = table
+ .get("header")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("Board config missing 'header' field"))?
+ .to_string();
+
+ let mut peripherals = Vec::new();
+ for (key, val) in table {
+ if key == "header" {
+ continue;
+ }
+ let features = val
+ .as_table()
+ .map(|t| {
+ t.values()
+ .filter_map(|v| v.as_str())
+ .map(|s| s.to_string())
+ .collect()
+ })
+ .unwrap_or_default();
+ peripherals.push(Peripheral {
+ name: key.clone(),
+ features,
+ });
+ }
+
+ Ok(BoardConfig {
+ header,
+ peripherals,
+ })
+ }
+}
+
+#[derive(Deserialize)]
+pub struct TargetProfile {
+ pub uses: Vec<String>,
+}
+
+impl TargetProfile {
+ pub fn load(component: Component) -> Result<Self> {
+ let pkg = component.package_name(false);
+ let path = workspace_dir()?
+ .join("projects")
+ .join(pkg)
+ .join("target.toml");
+ let content = std::fs::read_to_string(&path)
+ .with_context(|| format!("Failed to read target profile: {}", path.display()))?;
+ toml::from_str(&content)
+ .with_context(|| format!("Failed to parse target profile: {}", path.display()))
+ }
+}
+
+#[derive(Deserialize, Default, Clone)]
+pub struct ModelTargetOverride {
+ #[serde(default)]
+ pub exclude: Vec<String>,
+}
+
+pub struct BoardFeatures {
+ pub features: Vec<String>,
+ pub board_header: String,
+}
+
+pub fn resolve_board_features(
+ model_config: &ModelConfig,
+ board_id: &str,
+ component: Component,
+) -> Result<BoardFeatures> {
+ let board_config = BoardConfig::load(&model_config.model_id, board_id)?;
+ let target_profile = TargetProfile::load(component)?;
+ let pkg = component.package_name(false);
+ let model_override = model_config.targets.get(pkg).cloned().unwrap_or_default();
+
+ let uses: HashSet<&str> = target_profile.uses.iter().map(|s| s.as_str()).collect();
+ let exclude: HashSet<&str> = model_override.exclude.iter().map(|s| s.as_str()).collect();
+
+ let mut features = Vec::new();
+
+ // Model-intrinsic features filtered by target profile then model exceptions
+ for f in &model_config.features {
+ if uses.contains(f.as_str()) && !exclude.contains(f.as_str()) {
+ features.push(f.clone());
+ }
+ }
+
+ // Board peripheral features filtered by target profile then model exceptions
+ for periph in &board_config.peripherals {
+ if uses.contains(periph.name.as_str()) && !exclude.contains(periph.name.as_str()) {
+ features.push(periph.name.clone());
+ for f in &periph.features {
+ // Peripheral feature values must be crate-qualified (e.g.
+ // "io/touch_ft3168", "sys/sdram_..."), so the owning crate is explicit.
+ if !f.contains('/') {
+ bail!(
+ "board peripheral '{}': feature '{f}' must be crate-qualified (e.g. \"io/{f}\")",
+ periph.name
+ );
+ }
+ features.push(f.clone());
+ }
+ }
+ }
+
+ // MCU feature
+ features.push(model_config.mcu_feature());
+
+ Ok(BoardFeatures {
+ features,
+ board_header: board_config.header,
+ })
+}
diff --git a/core/embed/xtask/src/flash.rs b/core/embed/xtask/src/flash.rs
index 2d2bd29e..ecd49279 100644
--- a/core/embed/xtask/src/flash.rs
+++ b/core/embed/xtask/src/flash.rs
@@ -6,7 +6,7 @@ use std::{
use crate::{
args::{FlashArgs, FlashEraseArgs, FlashSection},
- helpers,
+ config, helpers,
};
/// Flashes the specified component to the device using OpenOCD.
@@ -35,11 +35,12 @@ pub fn flash(args: FlashArgs) -> Result<()> {
);
let flash_instruction = build_flash_write_instruction(&binary, address);
+ let model_config = config::ModelConfig::load(args.model.model_id())?;
let status = process::Command::new("openocd")
.args(["-f", "interface/stlink.cfg"])
.args(["-c", "transport select hla_swd"])
- .args(["-f", args.model.openocd_target()])
+ .args(["-f", model_config.openocd_target()?])
.arg("-c")
.arg(flash_instruction)
.status()
@@ -57,11 +58,12 @@ pub fn flash_erase(args: FlashEraseArgs) -> Result<()> {
let content = fs::read_to_string(&mem_ld)
.with_context(|| format!("Failed to read `{}`", mem_ld.display()))?;
let instr = build_flash_erase_instruction(&content, args.section)?;
+ let model_config = config::ModelConfig::load(args.model.model_id())?;
let status = process::Command::new("openocd")
.args(["-f", "interface/stlink.cfg"])
.args(["-c", "transport select hla_swd"])
- .args(["-f", args.model.openocd_target()])
+ .args(["-f", model_config.openocd_target()?])
.arg("-c")
.arg(instr)
.status()
diff --git a/core/embed/xtask/src/helpers.rs b/core/embed/xtask/src/helpers.rs
index b4025dee..65d96055 100644
--- a/core/embed/xtask/src/helpers.rs
+++ b/core/embed/xtask/src/helpers.rs
@@ -6,6 +6,7 @@ use std::{
};
use crate::args::{BuildArgs, Component, Model};
+use crate::config;
/// Returns the path to the built ELF file for the given build arguments.
pub fn elf_path(args: &BuildArgs) -> Result<PathBuf> {
@@ -17,7 +18,8 @@ pub fn elf_path(args: &BuildArgs) -> Result<PathBuf> {
pub fn profile_dir(args: &BuildArgs) -> Result<PathBuf> {
let mut path = build_dir()?;
if !args.emulator {
- path = path.join(args.model.target_triple());
+ let model_config = config::ModelConfig::load(args.model.model_id())?;
+ path = path.join(model_config.target_triple()?);
}
let name = match args.profile_name() {
diff --git a/core/embed/xtask/src/lib.rs b/core/embed/xtask/src/lib.rs
index 23dd4e99..6de442ca 100644
--- a/core/embed/xtask/src/lib.rs
+++ b/core/embed/xtask/src/lib.rs
@@ -2,9 +2,11 @@ pub mod args;
pub mod artifacts;
pub mod cargo;
pub mod combine;
+pub mod config;
pub mod flash;
pub mod helpers;
pub mod memusage;
+pub mod model;
pub mod postbuild;
pub mod prebuild;
pub mod upload;
diff --git a/core/embed/xtask/src/model.rs b/core/embed/xtask/src/model.rs
new file mode 100644
index 00000000..68b168ea
--- /dev/null
+++ b/core/embed/xtask/src/model.rs
@@ -0,0 +1,55 @@
+use anyhow::{Context, Result};
+use clap::ValueEnum;
+
+use crate::helpers;
+
+#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Model {
+ #[value(name = "d001")]
+ D001,
+ #[value(name = "d002")]
+ D002,
+ #[value(name = "t2t1")]
+ T2T1,
+ #[value(name = "t2b1")]
+ T2B1,
+ #[value(name = "t3b1")]
+ T3B1,
+ #[value(name = "t3t1")]
+ T3T1,
+ #[value(name = "t3w1")]
+ T3W1,
+}
+
+impl Model {
+ /// Returns the cargo feature to pass to select this model.
+ /// Uses `models/model_*` dep-feature syntax so project crates don't need
+ /// their own `model_*` feature declarations.
+ pub fn feature_name(self) -> String {
+ format!("models/model_{}", self.model_id().to_lowercase())
+ }
+
+ /// Returns the model ID used in artifact naming
+ pub fn model_id(self) -> &'static str {
+ match self {
+ Model::D001 => "D001",
+ Model::D002 => "D002",
+ Model::T2T1 => "T2T1",
+ Model::T2B1 => "T2B1",
+ Model::T3B1 => "T3B1",
+ Model::T3T1 => "T3T1",
+ Model::T3W1 => "T3W1",
+ }
+ }
+
+ /// Returns the path to the model-specific memory.ld file
+ pub fn model_memory_ld(self) -> Result<std::path::PathBuf> {
+ let mem_ld = helpers::workspace_dir()?
+ .join("models")
+ .join(self.model_id())
+ .join("memory.ld")
+ .canonicalize()
+ .with_context(|| format!("Failed to locate memory.ld for model {}", self.model_id()))?;
+ Ok(mem_ld)
+ }
+}
Why this scored 17/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.