use std::collections::BTreeMap;
use std::path::Path;
use nanoflash::Error;
use nanoflash::backend::{BackendOptions, Progress, ProgressEvent, Stage};
use nanoflash::flash::{FlashOptions, Hooks, Warning, detect, flash};
use nanoflash::layout::GrownPartition;
use nanoflash::manifest::{EraseTarget, Manifest, Protocol};
use nanoflash::testing::{MemorySource, ReplayProvider, Transcript, replay};
use pollster::block_on;
const MEBIBYTE: u64 = 1024 * 1024;
fn fixture(relative: &str) -> Vec<u8> {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join(relative);
std::fs::read(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()))
}
fn transcript(name: &str) -> String {
String::from_utf8(fixture(&format!("transcripts/espressif/{name}.transcript"))).unwrap()
}
fn manifest() -> Manifest {
Manifest::from_json(core::str::from_utf8(&fixture("boards/esp32-s3-usb.json")).unwrap())
.unwrap()
}
fn fixture_source() -> MemorySource {
let mut files = BTreeMap::new();
for path in [
"../layouts/esp32-s3-8mb.toml",
"../layouts/esp32-s3-detect.toml",
"../images/bootloader.bin",
"../images/application.bin",
] {
files.insert(path.to_string(), fixture(&path[3..]));
}
MemorySource { files }
}
#[derive(Default)]
struct Recorder {
stages: Vec<Stage>,
events: Vec<ProgressEvent>,
messages: Vec<String>,
}
impl Progress for Recorder {
fn report(&mut self, event: ProgressEvent) {
if self.stages.last() != Some(&event.stage) {
self.stages.push(event.stage);
}
self.events.push(event);
}
fn message(&mut self, text: &str) {
self.messages.push(text.to_string());
}
}
fn run_flash(
manifest: &Manifest,
text: &str,
source: &mut MemorySource,
options: &FlashOptions,
progress: &mut Recorder,
) -> (Result<nanoflash::flash::FlashReport, Error>, ReplayProvider) {
let (port, mut provider) = replay(Transcript::parse(text).unwrap());
let hooks = Hooks {
source,
verifier: &mut (),
progress,
};
let result = block_on(flash(manifest, port, &mut provider, hooks, options));
(result, provider)
}
fn run_detect(
text: &str,
protocol: Option<Protocol>,
) -> (
Result<nanoflash::backend::ChipInformation, Error>,
ReplayProvider,
) {
let (port, mut provider) = replay(Transcript::parse(text).unwrap());
let result = block_on(detect(port, &mut provider, protocol, &mut ()));
(result, provider)
}
#[test]
fn flashes_the_fixture_board() {
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&manifest(),
&transcript("flash-esp32s3-usb"),
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
let report = result.unwrap();
assert_eq!(report.board, "esp32-s3-devkitc");
assert_eq!(report.chip.chip, "esp32-s3");
assert_eq!(report.chip.flash_size, Some(8 * MEBIBYTE));
let images: Vec<(&str, u64, u64)> = report
.images
.iter()
.map(|image| (image.label.as_str(), image.offset, image.size))
.collect();
assert_eq!(
images,
[
("bootloader", 0x0, 4096),
("partition-table", 0x8000, 0xC00),
("application", 0x20000, 8192),
]
);
assert!(report.verified);
assert!(report.warnings.is_empty());
provider.finish().unwrap();
assert_eq!(
progress.stages,
[
Stage::Connecting,
Stage::Writing,
Stage::Verifying,
Stage::Resetting
]
);
}
#[cfg(feature = "elf")]
struct BuildingSource(MemorySource);
#[cfg(feature = "elf")]
impl nanoflash::flash::ImageSource for BuildingSource {
async fn read(&mut self, path: &str) -> Result<Vec<u8>, String> {
nanoflash::flash::ImageSource::read(&mut self.0, path).await
}
async fn application_image(
&mut self,
request: &nanoflash::flash::ApplicationImageRequest<'_>,
) -> Result<Vec<u8>, String> {
assert_eq!(request.chip, "esp32-s3");
assert_eq!(request.partition, Some("application"));
Ok(fixture("images/application.bin"))
}
}
#[cfg(feature = "elf")]
#[test]
fn flashes_an_espressif_elf() {
let manifest =
Manifest::from_json(core::str::from_utf8(&fixture("boards/esp32-s3-elf.json")).unwrap())
.unwrap();
let mut source = fixture_source();
source.files.insert(
"../images/esp32s3-application.elf".into(),
fixture("images/esp32s3-application.elf"),
);
let mut source = BuildingSource(source);
let mut progress = Recorder::default();
let (port, mut provider) = replay(Transcript::parse(&transcript("flash-esp32s3-usb")).unwrap());
let hooks = Hooks {
source: &mut source,
verifier: &mut (),
progress: &mut progress,
};
let report = block_on(flash(
&manifest,
port,
&mut provider,
hooks,
&FlashOptions::default(),
))
.unwrap();
assert_eq!(report.board, "esp32-s3-devkitc");
let images: Vec<(&str, u64, u64)> = report
.images
.iter()
.map(|image| (image.label.as_str(), image.offset, image.size))
.collect();
assert_eq!(
images,
[
("bootloader", 0x0, 4096),
("partition-table", 0x8000, 0xC00),
("application", 0x20000, 8192),
]
);
assert!(report.verified);
assert!(report.warnings.is_empty());
provider.finish().unwrap();
}
#[test]
fn no_verify_skips_the_digests() {
let text: String = transcript("flash-esp32s3-usb")
.lines()
.filter(|line| !line.contains(" 13 "))
.map(|line| format!("{line}\n"))
.collect();
let mut progress = Recorder::default();
let options = FlashOptions {
verify: false,
..FlashOptions::default()
};
let (result, provider) = run_flash(
&manifest(),
&text,
&mut fixture_source(),
&options,
&mut progress,
);
assert!(!result.unwrap().verified);
provider.finish().unwrap();
assert!(!progress.stages.contains(&Stage::Verifying));
}
#[test]
fn a_failed_verification_names_the_image() {
let text = transcript("flash-esp32s3-usb").replace(
"37 30 30 37 64 64 39 63 30 36 31 33 61 37 31 62 35 38 33 65 66 37 61 62 35 65 62 65 63 38 31 31",
&["30"; 32].join(" "),
);
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&manifest(),
&text,
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
let error = result.unwrap_err();
assert!(
matches!(
&error,
Error::VerificationFailed { label, offset: 0x20000, .. } if label == "application"
),
"{error:?}"
);
assert!(error.to_string().contains("\"application\""), "{error}");
provider.finish().unwrap();
assert_eq!(progress.stages.last(), Some(&Stage::Resetting));
}
#[test]
fn layout_larger_than_flash_stops_before_writing() {
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&manifest(),
&transcript("flash-too-small"),
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
assert_eq!(
result.unwrap_err(),
Error::FlashTooSmall {
layout: 8 * MEBIBYTE,
detected: 4 * MEBIBYTE,
}
);
provider.finish().unwrap();
assert_eq!(progress.stages, [Stage::Connecting, Stage::Resetting]);
}
fn detect_manifest() -> Manifest {
Manifest::from_json(core::str::from_utf8(&fixture("boards/esp32-s3-detect.json")).unwrap())
.unwrap()
}
#[test]
fn flashes_a_detect_layout_for_the_flash_of_the_chip() {
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&detect_manifest(),
&transcript("flash-esp32s3-usb"),
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
let report = result.unwrap();
provider.finish().unwrap();
assert_eq!(report.board, "esp32-s3-devkitc-detect");
let images: Vec<(&str, u64, u64)> = report
.images
.iter()
.map(|image| (image.label.as_str(), image.offset, image.size))
.collect();
assert_eq!(
images,
[
("bootloader", 0x0, 4096),
("partition-table", 0x8000, 0xC00),
("application", 0x20000, 8192),
]
);
let grew = Warning::PartitionsGrew {
flash_size: 8 * MEBIBYTE,
minimum_flash_size: 4 * MEBIBYTE,
partitions: vec![GrownPartition {
name: "storage".into(),
size_at_minimum: 0xE_0000,
size: 0x4E_0000,
}],
protocol: Protocol::Espressif,
};
assert_eq!(report.warnings, std::slice::from_ref(&grew));
assert!(
progress.messages.contains(&grew.to_string()),
"{:?}",
progress.messages
);
assert!(report.verified);
}
#[test]
fn a_chip_below_the_minimum_stops_before_writing() {
let mut source = fixture_source();
let layout = String::from_utf8(fixture("layouts/esp32-s3-detect.toml"))
.unwrap()
.replace("minimum = \"4 MiB\"", "minimum = \"8 MiB\"");
source.files.insert(
"../layouts/esp32-s3-detect.toml".into(),
layout.into_bytes(),
);
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&detect_manifest(),
&transcript("flash-too-small"),
&mut source,
&FlashOptions::default(),
&mut progress,
);
assert_eq!(
result.unwrap_err(),
Error::FlashTooSmall {
layout: 8 * MEBIBYTE,
detected: 4 * MEBIBYTE,
}
);
provider.finish().unwrap();
assert_eq!(progress.stages, [Stage::Connecting, Stage::Resetting]);
}
#[test]
fn a_failed_reset_after_an_error_is_reported() {
let full = transcript("flash-too-small");
let lines: Vec<&str> = full.lines().collect();
let text: String = lines[..lines.len() - 5]
.iter()
.map(|line| format!("{line}\n"))
.collect();
let mut progress = Recorder::default();
let (result, _provider) = run_flash(
&manifest(),
&text,
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
assert!(
matches!(result, Err(Error::FlashTooSmall { .. })),
"{result:?}"
);
assert!(
progress.messages.iter().any(|message| message
.starts_with("could not reset into the application: ")
&& message.ends_with("; press the board's reset button")),
"{:?}",
progress.messages
);
}
#[test]
fn erases_everything_first_when_asked() {
let text = transcript("flash-esp32s3-usb").replacen(
"> c0 00 10 ",
"> c0 00 02 14 00 00 00 00 00 00 00 80 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 c0\n\
< c0 01 02 04 00 00 00 00 00 00 00 00 00 c0\n> c0 00 10 ",
1,
);
let mut progress = Recorder::default();
let options = FlashOptions {
erase_all: true,
..FlashOptions::default()
};
let (result, provider) = run_flash(
&manifest(),
&text,
&mut fixture_source(),
&options,
&mut progress,
);
result.unwrap();
provider.finish().unwrap();
assert_eq!(
progress.stages,
[
Stage::Connecting,
Stage::Erasing,
Stage::Writing,
Stage::Verifying,
Stage::Resetting
]
);
let erasing: Vec<&ProgressEvent> = progress
.events
.iter()
.filter(|event| event.stage == Stage::Erasing)
.collect();
assert_eq!(erasing.len(), 2);
assert_eq!(
(erasing[0].offset, erasing[0].done, erasing[0].total),
(0, 0, 8 * MEBIBYTE)
);
assert_eq!(erasing[1].done, 8 * MEBIBYTE);
}
#[test]
fn missing_image_fails_before_connecting() {
let mut source = fixture_source();
source.files.remove("../images/application.bin");
let (result, provider) = run_flash(
&manifest(),
"! identity 303a:1001\n",
&mut source,
&FlashOptions::default(),
&mut Recorder::default(),
);
match result {
Err(Error::ImageSource { path, .. }) => assert_eq!(path, "../images/application.bin"),
other => panic!("{other:?}"),
}
provider.finish().unwrap();
}
#[test]
fn detects_with_the_identity_table() {
let (result, provider) = run_detect(&transcript("detect-esp32s3-usb"), None);
let chip = result.unwrap();
assert_eq!(chip.chip, "esp32-s3");
assert_eq!(chip.protocol, Protocol::Espressif);
provider.finish().unwrap();
}
#[test]
fn detect_without_identity_needs_a_protocol() {
let (result, provider) = run_detect("# no identity\n", None);
assert_eq!(
result.unwrap_err(),
Error::ProtocolRequired { identity: None }
);
provider.finish().unwrap();
}
#[cfg(not(feature = "samba"))]
#[test]
fn disabled_protocol() {
let manifest = Manifest::from_toml(
r#"
[[board]]
identifier = "samd21"
protocol = "samba"
chip = "samd21"
[[board.image]]
offset = 0x2000
path = "firmware.bin"
"#,
)
.unwrap();
let mut source = MemorySource::default();
source.files.insert("firmware.bin".to_string(), vec![0; 16]);
let (result, provider) = run_flash(
&manifest,
"# a serial bridge\n",
&mut source,
&FlashOptions::default(),
&mut Recorder::default(),
);
assert_eq!(
result.unwrap_err(),
Error::ProtocolNotEnabled {
protocol: Protocol::Samba
}
);
provider.finish().unwrap();
}
#[test]
fn erase_all_erases_the_flash_of_the_chip() {
let text = transcript("flash-esp32s3-usb")
.replace(
"< c0 01 0a 04 00 c8 40 17 00 00 00 00 00 c0",
"< c0 01 0a 04 00 c8 40 18 00 00 00 00 00 c0",
)
.replace(
"> c0 00 0b 18 00 00 00 00 00 00 00 00 00 00 00 80 00",
"> c0 00 0b 18 00 00 00 00 00 00 00 00 00 00 00 00 01",
)
.replacen(
"> c0 00 10 ",
"> c0 00 02 14 00 00 00 00 00 00 00 00 01 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 c0\n\
< c0 01 02 04 00 00 00 00 00 00 00 00 00 c0\n> c0 00 10 ",
1,
);
let mut progress = Recorder::default();
let options = FlashOptions {
erase_all: true,
..FlashOptions::default()
};
let (result, provider) = run_flash(
&manifest(),
&text,
&mut fixture_source(),
&options,
&mut progress,
);
assert_eq!(result.unwrap().chip.flash_size, Some(16 * MEBIBYTE));
provider.finish().unwrap();
let erasing = progress
.events
.iter()
.find(|event| event.stage == Stage::Erasing)
.unwrap();
assert_eq!((erasing.offset, erasing.total), (0, 16 * MEBIBYTE));
}
#[test]
fn a_misaligned_erase_entry_fails_before_connecting() {
let mut manifest = manifest();
manifest.boards[0].erase.push(EraseTarget::Region {
offset: 0x9800,
size: 0x100,
});
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&manifest,
"! identity 303a:1001\n",
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
let error = result.unwrap_err();
assert_eq!(
error,
Error::MisalignedErase {
entry: "region at 0x9800".into(),
offset: 0x9800,
size: 0x100,
required: 0x1000,
}
);
assert!(error.to_string().contains("region at 0x9800"), "{error}");
provider.finish().unwrap();
assert!(progress.stages.is_empty(), "{:?}", progress.stages);
}
fn esp_web_tools(builds: &[(&str, u64)]) -> Manifest {
let builds: Vec<String> = builds
.iter()
.map(|(chip, offset)| {
format!(
r#"{{"chipFamily":"{chip}","parts":[{{"path":"../images/bootloader.bin","offset":{offset}}}]}}"#
)
})
.collect();
Manifest::from_json(&format!(r#"{{"builds":[{}]}}"#, builds.join(","))).unwrap()
}
#[test]
fn a_part_beyond_four_gibibytes_is_refused_before_erasing() {
let manifest = esp_web_tools(&[("ESP32", 0x1000), ("ESP32-S3", 0x1_0000_0000)]);
let mut progress = Recorder::default();
let options = FlashOptions {
erase_all: true,
..FlashOptions::default()
};
let (result, provider) = run_flash(
&manifest,
&transcript("detect-esp32s3-usb"),
&mut fixture_source(),
&options,
&mut progress,
);
assert_eq!(
result.unwrap_err(),
Error::OutsideAddressRange {
what: "image \"image at 0x100000000\"".into(),
end: 0x1_0000_1000,
limit: 0x1_0000_0000,
protocol: Protocol::Espressif,
}
);
provider.finish().unwrap();
assert_eq!(progress.stages, [Stage::Connecting, Stage::Resetting]);
}
#[test]
fn a_part_beyond_the_flash_of_the_chip_is_refused_before_erasing() {
let manifest = esp_web_tools(&[("ESP32-S3", 0x40_0000)]);
let mut progress = Recorder::default();
let options = FlashOptions {
erase_all: true,
..FlashOptions::default()
};
let (result, provider) = run_flash(
&manifest,
&transcript("flash-too-small"),
&mut fixture_source(),
&options,
&mut progress,
);
let error = result.unwrap_err();
assert_eq!(
error,
Error::OutsideDetectedFlash {
what: "image \"image at 0x400000\"".into(),
end: 0x40_1000,
flash_size: 4 * MEBIBYTE,
}
);
assert!(error.to_string().contains("nothing was erased"), "{error}");
provider.finish().unwrap();
assert_eq!(progress.stages, [Stage::Connecting, Stage::Resetting]);
}
#[test]
fn a_disconnection_says_what_was_being_done() {
let mut progress = Recorder::default();
let (result, _provider) = run_flash(
&manifest(),
&transcript("flash-disconnect"),
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
let error = result.unwrap_err();
assert_eq!(
error,
Error::Transport {
error: nanoflash::transport::TransportError::Disconnected,
during: Some("writing \"bootloader\" at 0x0".into()),
}
);
assert_eq!(
error.to_string(),
"the device disconnected while writing \"bootloader\" at 0x0: check the cable and the port, then try again"
);
}
fn secure_download_flash() -> String {
let flash = transcript("flash-esp32s3-usb");
let writes = flash.split_once("> c0 00 10 ").unwrap().1;
let writes: String = format!("> c0 00 10 {writes}")
.lines()
.filter(|line| !line.starts_with("> c0 00 13") && !line.starts_with("< c0 01 13"))
.map(|line| format!("{line}\n"))
.collect();
transcript("connect-secure-download") + &writes
}
#[test]
fn secure_download_mode_skips_the_verification() {
let mut progress = Recorder::default();
let (result, provider) = run_flash(
&manifest(),
&secure_download_flash(),
&mut fixture_source(),
&FlashOptions::default(),
&mut progress,
);
let report = result.unwrap();
provider.finish().unwrap();
assert!(!report.verified);
assert!(report.chip.secure_download_mode);
assert_eq!(
report.warnings,
[nanoflash::flash::Warning::NotVerifiedInSecureDownloadMode]
);
assert!(
progress
.messages
.iter()
.any(|message| message.contains("secure download mode")),
"{:?}",
progress.messages
);
assert!(!progress.stages.contains(&Stage::Verifying));
}
#[test]
fn detect_keeps_the_baud_rate_of_the_bootloader() {
let text = transcript("connect-esp32-classic")
+ "! signals dtr=0 rts=1\n! sleep 100\n! signals dtr=0 rts=0\n";
let (result, provider) = run_detect(&text, Some(Protocol::Espressif));
assert_eq!(result.unwrap().chip, "esp32");
provider.finish().unwrap();
}
fn flash_qemu(chip: &str, first_offset: u64, baud_rate: Option<u32>, opcode: &str) {
let manifest = Manifest::from_toml(&format!(
"[[board]]\nidentifier = \"{chip}-qemu\"\nprotocol = \"espressif\"\nchip = \"{chip}\"\n\
layout = \"layout.toml\"\nreset = \"none\"\n\n\
[[board.image]]\npartition = \"bootloader\"\npath = \"../images/bootloader.bin\"\n\n\
[[board.image]]\npartition = \"application\"\npath = \"../images/application.bin\"\n"
))
.unwrap();
let mut source = fixture_source();
source.files.insert(
"layout.toml".into(),
format!(
"[flash]\nsize = \"4 MiB\"\nalignment = \"4 KiB\"\n\n\
[[partition]]\nname = \"bootloader\"\nrole = \"bootloader\"\noffset = {first_offset}\nsize = \"28 KiB\"\n\n\
[[partition]]\nname = \"partition-table\"\nrole = \"partition-table\"\noffset = 0x8000\nsize = \"4 KiB\"\n\n\
[[partition]]\nname = \"application\"\nrole = \"firmware\"\noffset = 0x10000\nsize = \"1 MiB\"\n"
)
.into_bytes(),
);
let text = transcript(&format!("flash-{chip}-qemu"));
assert!(text.contains(opcode), "{chip}: {opcode}");
let options = FlashOptions {
backend: BackendOptions {
baud_rate,
..BackendOptions::default()
},
..FlashOptions::default()
};
let mut progress = Recorder::default();
let (result, provider) = run_flash(&manifest, &text, &mut source, &options, &mut progress);
let report = result.unwrap();
provider.finish().unwrap();
assert!(report.verified);
assert_eq!(report.chip.flash_size, Some(4 * MEBIBYTE));
}
#[test]
fn the_esp32_rom_is_written_uncompressed() {
flash_qemu("esp32", 0x1000, Some(115_200), "> c0 00 03 10 04");
assert!(!transcript("flash-esp32-qemu").contains("> c0 00 10 "));
}
#[test]
fn the_esp32_c3_rom_is_written_compressed() {
flash_qemu("esp32c3", 0x0, None, "> c0 00 11 ");
}
#[cfg(not(feature = "elf"))]
#[test]
fn an_elf_needs_the_feature() {
let text = String::from_utf8(fixture("boards/nano33ble-elf.toml")).unwrap();
let manifest = Manifest::from_toml(&text).unwrap();
let mut files = BTreeMap::new();
for path in [
"../layouts/nrf52840-arduino.toml",
"../images/application.elf",
] {
files.insert(path.to_string(), fixture(&path[3..]));
}
let mut source = MemorySource { files };
let error = block_on(nanoflash::flash::prepare(
&manifest.boards[0],
&mut source,
&mut (),
))
.unwrap_err();
assert!(matches!(error, Error::ElfNotEnabled { .. }), "{error:?}");
assert!(error.to_string().contains("objcopy -O binary"), "{error}");
}