use super::TableError;
use crate::layout::{ResolvedLayout, ResolvedPartition, Role};
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt::Write;
const REGIONS_WRITER: &str = "linker";
const CONSTANTS_WRITER: &str = "constants";
const DEFAULT_REGION: &str = "FLASH";
const KEYWORDS: &[&str] = &[
"abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn",
"else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let",
"loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref", "return",
"static", "struct", "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use",
"virtual", "where", "while", "yield",
];
const NOT_RAW: &[&str] = &["self", "super", "crate"];
pub fn memory_regions(layout: &ResolvedLayout) -> Result<String, TableError> {
memory_script(layout, &[])
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryRegion {
pub name: String,
pub origin: u64,
pub length: u64,
}
pub fn memory_script(
layout: &ResolvedLayout,
extra: &[MemoryRegion],
) -> Result<String, TableError> {
at_minimum(layout, REGIONS_WRITER)?;
let firmware_without_region: Vec<&ResolvedPartition> = layout
.partitions
.iter()
.filter(|partition| {
partition.definition.role == Role::Firmware && explicit_region(partition).is_none()
})
.collect();
if let [first, second, ..] = firmware_without_region.as_slice() {
return Err(TableError::SeveralFirmware {
writer: REGIONS_WRITER,
first: first.definition.name.clone(),
second: second.definition.name.clone(),
});
}
let mut taken: Vec<(String, String)> = Vec::new();
let mut text = String::from(
"/* Generated by nanoflash from the board layout. Do not edit. */\nMEMORY\n{\n",
);
for partition in &layout.partitions {
let name = partition.definition.name.as_str();
let region = match explicit_region(partition) {
Some(region) => {
if !valid_region_name(region) {
return Err(unknown_value(
REGIONS_WRITER,
name,
"region",
String::from(region),
));
}
String::from(region)
}
None if partition.definition.role == Role::Firmware => String::from(DEFAULT_REGION),
None => region_from_name(name),
};
if let Some(error) = collision(REGIONS_WRITER, &taken, name, ®ion) {
return Err(error);
}
taken.push((region.clone(), name.into()));
if partition.moves_with_flash {
let what = if partition.grows_with_flash {
"grows and moves"
} else {
"moves"
};
let _ = writeln!(
text,
" /* {region} {what} with the flash of the device: no region. */"
);
continue;
}
if partition.grows_with_flash {
let _ = writeln!(
text,
" /* {region} grows with the flash of the device: LENGTH is its size on the minimum flash. */"
);
}
let out_of_range = || TableError::OutOfRange {
partition: name.into(),
writer: REGIONS_WRITER,
};
let origin = partition.address(&layout.flash).ok_or_else(out_of_range)?;
let _ = writeln!(
text,
" {region} : ORIGIN = {origin:#010X}, LENGTH = {:#010X}",
partition.size
);
}
for (index, region) in extra.iter().enumerate() {
if !valid_region_name(®ion.name) {
return Err(TableError::InvalidRegionName {
name: region.name.clone(),
});
}
if taken.iter().any(|(name, _)| *name == region.name) {
return Err(TableError::DuplicateRegion {
name: region.name.clone(),
});
}
if extra
.iter()
.take(index)
.any(|earlier| earlier.name == region.name)
{
return Err(TableError::RepeatedRegion {
name: region.name.clone(),
});
}
let _ = writeln!(
text,
" {} : ORIGIN = {:#010X}, LENGTH = {:#010X}",
region.name, region.origin, region.length
);
}
text.push_str("}\n");
Ok(text)
}
pub fn rust_constants(layout: &ResolvedLayout) -> Result<String, TableError> {
at_minimum(layout, CONSTANTS_WRITER)?;
let mut values = Vec::new();
values.push(layout.flash.size);
values.push(layout.flash.base_address);
let mut addresses = Vec::new();
for partition in &layout.partitions {
let address = partition
.address(&layout.flash)
.ok_or_else(|| TableError::OutOfRange {
partition: partition.definition.name.clone(),
writer: CONSTANTS_WRITER,
})?;
if !partition.moves_with_flash {
values.push(partition.offset);
values.push(address);
}
values.push(partition.size);
addresses.push(address);
}
let wide = values.iter().any(|value| u32::try_from(*value).is_err());
let (kind, digits) = if wide { ("u64", 16) } else { ("u32", 8) };
let flash_size = if layout.minimum_flash_size.is_some() {
"FLASH_MINIMUM_SIZE"
} else {
"FLASH_SIZE"
};
let mut taken: Vec<(String, String)> = Vec::new();
let mut text = String::from("// Generated by nanoflash from the board layout. Do not edit.\n");
let _ = writeln!(
text,
"pub const {flash_size}: {kind} = {};",
literal(layout.flash.size, digits)
);
let _ = writeln!(
text,
"pub const FLASH_BASE_ADDRESS: {kind} = {};",
literal(layout.flash.base_address, digits)
);
for (partition, address) in layout.partitions.iter().zip(addresses) {
let name = partition.definition.name.as_str();
let module = module_name(name);
if let Some(error) = collision(CONSTANTS_WRITER, &taken, name, &module) {
return Err(error);
}
let _ = writeln!(text, "pub mod {module} {{");
match (partition.grows_with_flash, partition.moves_with_flash) {
(true, true) => text.push_str(
" // Grows and moves with the flash of the device: MINIMUM_SIZE is its size on the minimum flash, and its offset is only known once the flash is.\n",
),
(true, false) => text.push_str(
" // Grows with the flash of the device: MINIMUM_SIZE is its size on the minimum flash.\n",
),
(false, true) => text.push_str(
" // Moves with the flash of the device: its offset is only known once the flash is.\n",
),
(false, false) => {}
}
if !partition.moves_with_flash {
let _ = writeln!(
text,
" pub const OFFSET: {kind} = {};",
literal(partition.offset, digits)
);
}
let size_name = if partition.grows_with_flash {
"MINIMUM_SIZE"
} else {
"SIZE"
};
let _ = writeln!(
text,
" pub const {size_name}: {kind} = {};",
literal(partition.size, digits)
);
if !partition.moves_with_flash {
let _ = writeln!(
text,
" pub const ADDRESS: {kind} = {};",
literal(address, digits)
);
}
text.push_str("}\n");
taken.push((module, name.into()));
}
Ok(text)
}
fn at_minimum(layout: &ResolvedLayout, writer: &'static str) -> Result<(), TableError> {
match layout.minimum_flash_size {
Some(minimum_flash_size) if minimum_flash_size != layout.flash.size => {
Err(TableError::NotAtMinimum {
writer,
flash_size: layout.flash.size,
minimum_flash_size,
})
}
_ => Ok(()),
}
}
fn explicit_region(partition: &ResolvedPartition) -> Option<&str> {
partition
.definition
.linker
.as_ref()
.and_then(|attributes| attributes.region.as_deref())
}
fn valid_region_name(name: &str) -> bool {
!name.is_empty()
&& !name.starts_with(|character: char| character.is_ascii_digit())
&& name
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '_')
}
fn collision(
writer: &'static str,
taken: &[(String, String)],
name: &str,
identifier: &str,
) -> Option<TableError> {
taken
.iter()
.find(|(taken_identifier, _)| taken_identifier == identifier)
.map(|(_, first)| TableError::NameCollision {
writer,
first: first.clone(),
second: name.into(),
identifier: identifier.into(),
})
}
fn unknown_value(
writer: &'static str,
partition: &str,
attribute: &'static str,
value: String,
) -> TableError {
TableError::UnknownValue {
writer,
partition: partition.into(),
attribute,
value,
}
}
fn region_from_name(name: &str) -> String {
let mut region: String = name
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || character == '_' {
character.to_ascii_uppercase()
} else {
'_'
}
})
.collect();
if region.is_empty() || region.starts_with(|character: char| character.is_ascii_digit()) {
region.insert(0, '_');
}
region
}
fn module_name(name: &str) -> String {
let lower: String = name
.chars()
.map(|character| {
if character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' {
character
} else if character.is_ascii_uppercase() {
character.to_ascii_lowercase()
} else {
'_'
}
})
.collect();
if lower.is_empty() || lower == "_" || lower.starts_with(|c: char| c.is_ascii_digit()) {
format!("partition_{lower}")
} else if NOT_RAW.contains(&lower.as_str()) {
format!("{lower}_partition")
} else if KEYWORDS.contains(&lower.as_str()) {
format!("r#{lower}")
} else {
lower
}
}
fn literal(value: u64, digits: usize) -> String {
let plain = format!("{value:0digits$X}");
let mut text = String::from("0x");
let length = plain.len();
for (index, digit) in plain.chars().enumerate() {
if index > 0 && (length - index) % 4 == 0 {
text.push('_');
}
text.push(digit);
}
text
}
#[cfg(all(test, feature = "toml"))]
mod tests {
use super::*;
use crate::layout::Layout;
use alloc::string::ToString;
use std::path::Path;
fn resolved(text: &str) -> ResolvedLayout {
Layout::from_toml(text).unwrap().resolve().unwrap()
}
fn fixture(name: &str) -> ResolvedLayout {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/layouts")
.join(name);
resolved(&std::fs::read_to_string(path).unwrap())
}
#[test]
fn nrf52840_memory_regions() {
let text = memory_regions(&fixture("nrf52840-arduino.toml")).unwrap();
assert_eq!(
text,
"/* Generated by nanoflash from the board layout. Do not edit. */\n\
MEMORY\n{\n\
\x20 BOOTLOADER : ORIGIN = 0x00000000, LENGTH = 0x00010000\n\
\x20 FLASH : ORIGIN = 0x00010000, LENGTH = 0x000E0000\n\
\x20 STORAGE : ORIGIN = 0x000F0000, LENGTH = 0x00010000\n\
}\n"
);
}
#[test]
fn nrf52840_constants() {
let text = rust_constants(&fixture("nrf52840-arduino.toml")).unwrap();
assert_eq!(
text,
"// Generated by nanoflash from the board layout. Do not edit.\n\
pub const FLASH_SIZE: u32 = 0x0010_0000;\n\
pub const FLASH_BASE_ADDRESS: u32 = 0x0000_0000;\n\
pub mod bootloader {\n\
\x20 pub const OFFSET: u32 = 0x0000_0000;\n\
\x20 pub const SIZE: u32 = 0x0001_0000;\n\
\x20 pub const ADDRESS: u32 = 0x0000_0000;\n\
}\n\
pub mod application {\n\
\x20 pub const OFFSET: u32 = 0x0001_0000;\n\
\x20 pub const SIZE: u32 = 0x000E_0000;\n\
\x20 pub const ADDRESS: u32 = 0x0001_0000;\n\
}\n\
pub mod storage {\n\
\x20 pub const OFFSET: u32 = 0x000F_0000;\n\
\x20 pub const SIZE: u32 = 0x0001_0000;\n\
\x20 pub const ADDRESS: u32 = 0x000F_0000;\n\
}\n"
);
}
#[test]
fn growing_constants() {
assert_eq!(
rust_constants(&fixture("growing.toml")).unwrap(),
"// Generated by nanoflash from the board layout. Do not edit.\n\
pub const FLASH_MINIMUM_SIZE: u32 = 0x0008_0000;\n\
pub const FLASH_BASE_ADDRESS: u32 = 0x0000_0000;\n\
pub mod bootloader {\n pub const OFFSET: u32 = 0x0000_0000;\n pub const SIZE: u32 = 0x0001_0000;\n pub const ADDRESS: u32 = 0x0000_0000;\n}\n\
pub mod application {\n pub const OFFSET: u32 = 0x0001_0000;\n pub const SIZE: u32 = 0x0004_0000;\n pub const ADDRESS: u32 = 0x0001_0000;\n}\n\
pub mod storage {\n // Grows with the flash of the device: MINIMUM_SIZE is its size on the minimum flash.\n pub const OFFSET: u32 = 0x0005_0000;\n pub const MINIMUM_SIZE: u32 = 0x0002_F000;\n pub const ADDRESS: u32 = 0x0005_0000;\n}\n\
pub mod log {\n // Moves with the flash of the device: its offset is only known once the flash is.\n pub const SIZE: u32 = 0x0000_1000;\n}\n"
);
}
#[test]
fn growing_memory_regions() {
assert_eq!(
memory_regions(&fixture("growing.toml")).unwrap(),
"/* Generated by nanoflash from the board layout. Do not edit. */\nMEMORY\n{\n\
\x20 BOOTLOADER : ORIGIN = 0x00000000, LENGTH = 0x00010000\n\
\x20 FLASH : ORIGIN = 0x00010000, LENGTH = 0x00040000\n\
\x20 /* STORAGE grows with the flash of the device: LENGTH is its size on the minimum flash. */\n\
\x20 STORAGE : ORIGIN = 0x00050000, LENGTH = 0x0002F000\n\
\x20 /* LOG moves with the flash of the device: no region. */\n}\n"
);
}
#[test]
fn memory_script_adds_regions() {
let layout = fixture("nrf52840-arduino.toml");
let regions = [MemoryRegion {
name: "RAM".into(),
origin: 0x2000_0000,
length: 0x40000,
}];
let text = memory_script(&layout, ®ions).unwrap();
let mut expected = memory_regions(&layout).unwrap();
expected.truncate(expected.len() - "}\n".len());
expected.push_str("\x20 RAM : ORIGIN = 0x20000000, LENGTH = 0x00040000\n}\n");
assert_eq!(text, expected);
assert_eq!(
memory_script(&layout, &[]).unwrap(),
memory_regions(&layout).unwrap()
);
}
#[test]
fn memory_script_refuses_a_duplicate() {
let layout = fixture("nrf52840-arduino.toml");
let regions = [MemoryRegion {
name: "FLASH".into(),
origin: 0x2000_0000,
length: 0x40000,
}];
let error = memory_script(&layout, ®ions).unwrap_err();
assert_eq!(
error,
TableError::DuplicateRegion {
name: "FLASH".into()
}
);
assert_eq!(
error.to_string(),
"the region FLASH is both a partition of the layout and a memory region given to the build: rename one"
);
}
#[test]
fn memory_script_refuses_a_region_name_the_linker_cannot_read() {
let layout = fixture("nrf52840-arduino.toml");
for name in ["", "2RAM", "RA M", "RAM:", "RAM\n}", "R\u{c4}M"] {
let regions = [MemoryRegion {
name: name.into(),
origin: 0x2000_0000,
length: 0x40000,
}];
let error = memory_script(&layout, ®ions).unwrap_err();
assert_eq!(
error,
TableError::InvalidRegionName { name: name.into() },
"{name:?}"
);
}
let error = memory_script(
&layout,
&[MemoryRegion {
name: "RA M".into(),
origin: 0,
length: 1,
}],
)
.unwrap_err();
assert_eq!(
error.to_string(),
"the memory region \"RA M\" given to the build has a name that the linker cannot read: use ASCII letters, digits and _, and do not start with a digit"
);
}
#[test]
fn memory_script_refuses_a_region_given_twice() {
let layout = fixture("nrf52840-arduino.toml");
let region = |origin| MemoryRegion {
name: "RAM".into(),
origin,
length: 0x1000,
};
let error =
memory_script(&layout, &[region(0x2000_0000), region(0x3000_0000)]).unwrap_err();
assert_eq!(error, TableError::RepeatedRegion { name: "RAM".into() });
assert_eq!(
error.to_string(),
"the memory region RAM is given to the build more than once: give each region once"
);
}
const GROW_AND_MOVE: &str = "[flash]\nsize = \"detect\"\nminimum = \"1 MiB\"\nbase-address = 0x0\n\n\
[[partition]]\nname = \"bootloader\"\nrole = \"bootloader\"\noffset = 0x0\nsize = \"64 KiB\"\n\n\
[[partition]]\nname = \"data\"\nrole = \"custom\"\nsize = { minimum = \"64 KiB\", grow = 1 }\n\n\
[[partition]]\nname = \"storage\"\nrole = \"storage\"\nsize = { minimum = \"64 KiB\", grow = 1 }\n";
#[test]
fn a_partition_that_grows_and_moves_gets_neither_offset_nor_region() {
let layout = resolved(GROW_AND_MOVE);
let constants = rust_constants(&layout).unwrap();
assert!(
constants.contains(
"pub mod storage {\n // Grows and moves with the flash of the device: MINIMUM_SIZE is its size on the minimum flash, and its offset is only known once the flash is.\n pub const MINIMUM_SIZE: u32 = 0x"
),
"{constants}"
);
assert!(!constants.contains("pub mod storage {\n pub const OFFSET"));
let regions = memory_regions(&layout).unwrap();
assert!(
regions.contains(
" /* STORAGE grows and moves with the flash of the device: no region. */\n"
),
"{regions}"
);
assert!(!regions.contains("STORAGE :"), "{regions}");
}
#[test]
fn writers_refuse_a_layout_resolved_above_its_minimum() {
let text = std::fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/layouts/growing.toml"),
)
.unwrap();
let layout = Layout::from_toml(&text)
.unwrap()
.resolve_for(Some(0x100000))
.unwrap();
let expected = TableError::NotAtMinimum {
writer: "constants",
flash_size: 0x100000,
minimum_flash_size: 0x80000,
};
assert_eq!(rust_constants(&layout).unwrap_err(), expected);
let error = memory_regions(&layout).unwrap_err();
assert!(matches!(
error,
TableError::NotAtMinimum {
writer: "linker",
..
}
));
let message = error.to_string();
assert!(
message.contains("0x80000") && message.contains("0x100000"),
"{message}"
);
}
#[test]
fn identifiers_are_sanitised() {
let layout = resolved(
"[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
[[partition]]\nname = \"nvs-keys\"\nrole = \"storage\"\noffset = 0x0\nsize = 0x1000\n\n\
[[partition]]\nname = \"2nd\"\nrole = \"storage\"\noffset = 0x1000\nsize = 0x1000\n\n\
[[partition]]\nname = \"type\"\nrole = \"storage\"\noffset = 0x2000\nsize = 0x1000\n\n\
[[partition]]\nname = \"self\"\nrole = \"storage\"\noffset = 0x3000\nsize = 0x1000\n",
);
let constants = rust_constants(&layout).unwrap();
for module in ["nvs_keys", "partition_2nd", "r#type", "self_partition"] {
assert!(
constants.contains(&std::format!("pub mod {module} {{")),
"{module}"
);
}
let regions = memory_regions(&layout).unwrap();
for region in ["NVS_KEYS", "_2ND", "TYPE", "SELF"] {
assert!(
regions.contains(&std::format!(" {region} : ORIGIN")),
"{region}"
);
}
}
#[test]
fn identifier_collisions_name_both_partitions() {
let layout = resolved(
"[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
[[partition]]\nname = \"a-b\"\nrole = \"storage\"\noffset = 0x0\nsize = 0x1000\n\n\
[[partition]]\nname = \"a_b\"\nrole = \"storage\"\noffset = 0x1000\nsize = 0x1000\n",
);
for error in [
rust_constants(&layout).unwrap_err(),
memory_regions(&layout).unwrap_err(),
] {
assert!(
matches!(&error, TableError::NameCollision { first, second, .. } if first == "a-b" && second == "a_b"),
"{error}"
);
let message = error.to_string();
assert!(
message.contains("\"a-b\"") && message.contains("\"a_b\""),
"{message}"
);
}
}
#[test]
fn several_firmware_partitions_are_refused() {
let layout = resolved(
"[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
[[partition]]\nname = \"a\"\nrole = \"firmware\"\noffset = 0x0\nsize = 0x1000\n\n\
[[partition]]\nname = \"b\"\nrole = \"firmware\"\noffset = 0x1000\nsize = 0x1000\n",
);
assert!(matches!(
memory_regions(&layout),
Err(TableError::SeveralFirmware { .. })
));
}
#[test]
fn explicit_regions_and_wide_values() {
let layout = resolved(
"[flash]\nsize = \"1 MiB\"\nbase-address = 0x1_0000_0000\n\n\
[[partition]]\nname = \"a\"\nrole = \"firmware\"\noffset = 0x0\nsize = 0x1000\nlinker = { region = \"RAM_CODE\" }\n",
);
assert!(
memory_regions(&layout)
.unwrap()
.contains(" RAM_CODE : ORIGIN = 0x100000000, LENGTH = 0x00001000")
);
let constants = rust_constants(&layout).unwrap();
assert!(constants.contains("pub const FLASH_BASE_ADDRESS: u64 = 0x0000_0001_0000_0000;"));
}
#[test]
fn constants_compile() {
for (index, text) in [
rust_constants(&fixture("esp32-s3-8mb.toml")).unwrap(),
rust_constants(&fixture("growing.toml")).unwrap(),
rust_constants(&resolved(GROW_AND_MOVE)).unwrap(),
]
.into_iter()
.enumerate()
{
compiles(index, &text);
}
}
fn compiles(index: usize, text: &str) {
let directory = std::path::Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../target/test-scratch"
))
.join(std::format!(
"nanoflash-constants-{}-{index}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory).unwrap();
let source = directory.join("constants.rs");
std::fs::write(&source, text).unwrap();
let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
let output = std::process::Command::new(rustc)
.args([
"--crate-type",
"lib",
"--edition",
"2024",
"--emit",
"metadata",
"-o",
])
.arg(directory.join("constants.rmeta"))
.arg(&source)
.output()
.unwrap();
let success = output.status.success();
let stderr = std::string::String::from_utf8_lossy(&output.stderr).into_owned();
std::fs::remove_dir_all(&directory).unwrap();
assert!(success, "{stderr}");
}
}