use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use serde::Serialize;
use crate::layout::LayoutError;
use crate::manifest::{ManifestError, Protocol};
use crate::table::TableError;
use crate::transport::{TransportError, UsbIdentity};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Error {
Transport {
error: TransportError,
during: Option<String>,
},
NoResponse {
command: &'static str,
},
NoSync {
attempts: u8,
},
NotInDownloadMode {
boot_mode: String,
},
Rom {
command: &'static str,
code: u8,
},
InvalidResponse {
command: &'static str,
message: String,
},
UnknownChip {
detail: String,
},
UnsupportedChip {
chip: String,
},
UnsupportedReset {
protocol: Protocol,
reset: String,
},
OutOfRange {
what: String,
value: u64,
},
Manifest {
error: ManifestError,
},
Layout {
errors: Vec<LayoutError>,
},
LayoutFile {
path: String,
message: String,
},
Table {
error: TableError,
},
ImageSource {
path: String,
message: String,
},
IntelHex {
path: String,
line: Option<usize>,
message: String,
},
MisplacedIntelHex {
path: String,
start: u64,
expected: u64,
base_address: u64,
partition: Option<String>,
},
ElfNotEnabled {
path: String,
},
#[cfg(feature = "elf")]
Elf {
path: String,
message: String,
},
#[cfg(feature = "elf")]
MisplacedElf {
path: String,
start: u64,
expected: u64,
base_address: u64,
partition: Option<String>,
},
#[cfg(feature = "elf")]
ApplicationImage {
path: String,
partition: Option<String>,
reason: String,
},
#[cfg(feature = "elf")]
ElfNotAnApplication {
path: String,
partition: Option<String>,
offset: u64,
},
#[cfg(feature = "elf")]
MisalignedApplicationImage {
path: String,
partition: Option<String>,
offset: u64,
},
ChecksumMismatch {
path: String,
expected: String,
actual: String,
},
ImageRejected {
path: String,
reason: String,
},
ImageNeedsLayout {
board: String,
partition: String,
},
UnknownPartition {
board: String,
partition: String,
},
MisalignedImage {
label: String,
offset: u64,
required: u64,
},
OverlappingImages {
first: String,
second: String,
first_end: u64,
second_offset: u64,
},
ImageTooLarge {
label: String,
partition: String,
image_size: u64,
partition_size: u64,
},
PartitionTableImageForDetectedFlash {
partition: String,
},
FixedOffsetOnMovingPartition {
what: String,
start: u64,
end: u64,
partition: String,
partition_offset: u64,
flash_size: u64,
addresses_in_file: bool,
},
ImageOutsideFlash {
label: String,
end: u64,
flash_size: u64,
},
MisalignedErase {
entry: String,
offset: u64,
size: u64,
required: u64,
},
EraseOutsideFlash {
entry: String,
end: u64,
flash_size: u64,
},
OutsideAddressRange {
what: String,
end: u64,
limit: u64,
protocol: Protocol,
},
OutsideDetectedFlash {
what: String,
end: u64,
flash_size: u64,
},
NothingToFlash {
board: String,
},
EmptyImage {
path: String,
},
OutOfMemory {
what: String,
size: u64,
},
UnknownBoard {
identifier: String,
known: Vec<String>,
},
NoMatchingBoard {
identity: Option<UsbIdentity>,
},
SeveralProtocols {
protocols: Vec<Protocol>,
},
SeveralBoards {
chip: String,
boards: Vec<String>,
},
BoardRequired {
boards: Vec<String>,
},
ProtocolRequired {
identity: Option<UsbIdentity>,
},
ProtocolNotEnabled {
protocol: Protocol,
},
UnknownFlashSize,
FlashSizeNeedsDetectLayout,
FlashTooSmall {
layout: u64,
detected: u64,
},
WrongChip {
detected: String,
expected: Vec<String>,
},
VerificationFailed {
label: String,
offset: u64,
size: u64,
expected: String,
actual: String,
checksum: &'static str,
},
NoBootloader {
waited_for: Option<String>,
reset: Option<&'static str>,
protocol: Protocol,
rates: Vec<u32>,
},
NotConnected {
protocol: Protocol,
},
UnsupportedBootloader {
version: String,
},
UnknownBootloaderDevice {
identity: UsbIdentity,
},
BelowWritableFlash {
what: String,
offset: u64,
writable_from: u64,
},
AboveWritableFlash {
what: String,
end: u64,
writable_to: u64,
protocol: Protocol,
},
ReadBackDiffers {
label: String,
offset: u64,
expected: u8,
actual: u8,
},
EraseShortOfFlashEnd {
chip: String,
entry: String,
offset: u64,
end: u64,
flash_size: u64,
},
ImageBelowWritten {
chip: String,
label: String,
offset: u64,
},
PageOutOfEraseOrder {
what: String,
offset: u64,
erases_next: u64,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ErrorClass {
Input,
Device,
Verification,
}
impl Error {
pub fn class(&self) -> ErrorClass {
match self {
Error::UnsupportedReset { .. }
| Error::OutOfRange { .. }
| Error::Manifest { .. }
| Error::Layout { .. }
| Error::LayoutFile { .. }
| Error::Table { .. }
| Error::ImageSource { .. }
| Error::ChecksumMismatch { .. }
| Error::ImageRejected { .. }
| Error::IntelHex { .. }
| Error::MisplacedIntelHex { .. }
| Error::ElfNotEnabled { .. }
| Error::ImageNeedsLayout { .. }
| Error::UnknownPartition { .. }
| Error::MisalignedImage { .. }
| Error::OverlappingImages { .. }
| Error::ImageTooLarge { .. }
| Error::PartitionTableImageForDetectedFlash { .. }
| Error::FixedOffsetOnMovingPartition { .. }
| Error::ImageOutsideFlash { .. }
| Error::MisalignedErase { .. }
| Error::EraseOutsideFlash { .. }
| Error::OutsideAddressRange { .. }
| Error::OutsideDetectedFlash { .. }
| Error::NothingToFlash { .. }
| Error::EmptyImage { .. }
| Error::OutOfMemory { .. }
| Error::UnknownBoard { .. }
| Error::NoMatchingBoard { .. }
| Error::SeveralProtocols { .. }
| Error::SeveralBoards { .. }
| Error::BoardRequired { .. }
| Error::ProtocolRequired { .. }
| Error::ProtocolNotEnabled { .. }
| Error::UnknownFlashSize
| Error::FlashSizeNeedsDetectLayout
| Error::FlashTooSmall { .. }
| Error::UnknownBootloaderDevice { .. }
| Error::BelowWritableFlash { .. }
| Error::AboveWritableFlash { .. }
| Error::EraseShortOfFlashEnd { .. }
| Error::ImageBelowWritten { .. }
| Error::PageOutOfEraseOrder { .. }
| Error::NotConnected { .. } => ErrorClass::Input,
#[cfg(feature = "elf")]
Error::Elf { .. }
| Error::MisplacedElf { .. }
| Error::ApplicationImage { .. }
| Error::ElfNotAnApplication { .. }
| Error::MisalignedApplicationImage { .. } => ErrorClass::Input,
Error::Transport { .. }
| Error::NoResponse { .. }
| Error::NoSync { .. }
| Error::NotInDownloadMode { .. }
| Error::Rom { .. }
| Error::InvalidResponse { .. }
| Error::UnknownChip { .. }
| Error::UnsupportedChip { .. }
| Error::WrongChip { .. }
| Error::NoBootloader { .. }
| Error::UnsupportedBootloader { .. } => ErrorClass::Device,
Error::VerificationFailed { .. } | Error::ReadBackDiffers { .. } => {
ErrorClass::Verification
}
}
}
}
impl From<TransportError> for Error {
fn from(error: TransportError) -> Self {
Error::Transport {
error,
during: None,
}
}
}
impl Error {
pub fn during(self, what: impl FnOnce() -> String) -> Error {
match self {
Error::Transport {
error,
during: None,
} => Error::Transport {
error,
during: Some(what()),
},
other => other,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Transport { error, during } => {
write!(formatter, "{error}")?;
if let Some(during) = during {
write!(formatter, " while {during}")?;
}
if *error == TransportError::Disconnected {
formatter.write_str(": check the cable and the port, then try again")?;
}
Ok(())
}
Error::NoResponse { command } => write!(
formatter,
"the board did not answer {command}: check the port and the cable, then try again"
),
Error::NoSync { attempts } => write!(
formatter,
"the board did not answer SYNC after {attempts} resets: check the port and the cable, or hold BOOT (GPIO0) while pressing RESET"
),
Error::NotInDownloadMode { boot_mode } => write!(
formatter,
"the chip booted in mode {boot_mode} instead of download mode: hold BOOT (GPIO0) while pressing RESET, or check the auto-reset circuit"
),
Error::Rom { command, code } => write!(
formatter,
"the ROM loader refused {command}: {} (0x{code:02x})",
rom_error(*code)
),
Error::InvalidResponse { command, message } => write!(
formatter,
"the board answered {command} with an invalid response: {message}"
),
Error::UnknownChip { detail } => write!(
formatter,
"the chip could not be identified ({detail}): it may be newer than this version of nanoflash"
),
Error::UnsupportedChip { chip } => {
write!(formatter, "the {chip} is not supported by nanoflash")
}
Error::UnsupportedReset { protocol, reset } => write!(
formatter,
"the {reset} reset does not apply to the {protocol} protocol: choose another reset for the board in the manifest"
),
Error::OutOfRange { what, value } => write!(
formatter,
"the {what} 0x{value:x} is beyond what the protocol can address"
),
Error::Manifest { error } => write!(formatter, "{error}"),
Error::Layout { errors } => {
for (index, error) in errors.iter().enumerate() {
if index > 0 {
formatter.write_str("\n")?;
}
write!(formatter, "{error}")?;
}
Ok(())
}
Error::LayoutFile { path, message } => write!(
formatter,
"the layout file \"{path}\" could not be read: {message}: check the \"layout\" path of the board in the manifest"
),
Error::Table { error } => write!(
formatter,
"the partition table cannot be written for the layout: {error}"
),
Error::ImageSource { path, message } => write!(
formatter,
"the image \"{path}\" could not be read: {message}: check the path in the manifest"
),
Error::ChecksumMismatch {
path,
expected,
actual,
} => write!(
formatter,
"the image \"{path}\" has the SHA-256 digest {actual} instead of {expected}: rebuild the image or update the \"sha256\" of the manifest"
),
Error::IntelHex {
path,
line,
message,
} => {
write!(formatter, "the Intel HEX image \"{path}\" is invalid")?;
if let Some(line) = line {
write!(formatter, " at line {line}")?;
}
write!(
formatter,
": {message}: rebuild it, or give its binary form"
)
}
Error::MisplacedIntelHex {
path,
start,
expected,
base_address,
partition,
} => {
write!(
formatter,
"the Intel HEX image \"{path}\" starts at 0x{start:x}, but "
)?;
match partition {
Some(partition) => write!(
formatter,
"the partition \"{partition}\" it is written to starts at 0x{expected:x}"
)?,
None => write!(formatter, "the manifest places it at 0x{expected:x}")?,
}
match (start.checked_sub(*base_address), partition) {
(Some(offset), Some(_)) => write!(
formatter,
": fix the partition of the image (it starts at the flash offset 0x{offset:x}), or rebuild it for that partition"
),
(Some(offset), None) => write!(
formatter,
": fix the offset of the image to 0x{offset:x}, or name the partition that starts there"
),
(None, _) => write!(
formatter,
": it starts below the flash, which starts at 0x{base_address:x}: rebuild it for this board, or fix the base address of the layout"
),
}
}
Error::ElfNotEnabled { path } => write!(
formatter,
"the image \"{path}\" is an ELF file, which this build of nanoflash does not read: give its binary image (objcopy -O binary) or its Intel HEX image"
),
#[cfg(feature = "elf")]
Error::Elf { path, message } => write!(
formatter,
"the ELF image \"{path}\" cannot be flashed: {message}"
),
#[cfg(feature = "elf")]
Error::MisplacedElf {
path,
start,
expected,
base_address,
partition,
} => {
write!(
formatter,
"the ELF image \"{path}\" starts at 0x{start:x}, but "
)?;
match partition {
Some(partition) => write!(
formatter,
"the partition \"{partition}\" it is written to starts at 0x{expected:x}"
)?,
None => write!(formatter, "the manifest places it at 0x{expected:x}")?,
}
match (start.checked_sub(*base_address), partition) {
(Some(offset), Some(_)) => write!(
formatter,
": link it for that partition (memory.x), or fix the partition of the image (it starts at the flash offset 0x{offset:x})"
),
(Some(offset), None) => write!(
formatter,
": fix the offset of the image to 0x{offset:x}, or name the partition that starts there"
),
(None, _) => write!(
formatter,
": it starts below the flash, which starts at 0x{base_address:x}: link it for this board, or fix the base address of the layout"
),
}
}
#[cfg(feature = "elf")]
Error::ApplicationImage {
path,
partition,
reason,
} => {
write!(
formatter,
"the Espressif application image of the ELF file \"{path}\""
)?;
if let Some(partition) = partition {
write!(formatter, " for the partition \"{partition}\"")?;
}
write!(formatter, " could not be built: {reason}")
}
#[cfg(feature = "elf")]
Error::ElfNotAnApplication {
path,
partition,
offset,
} => {
write!(formatter, "the ELF image \"{path}\" is written ")?;
if let Some(partition) = partition {
write!(formatter, "to the partition \"{partition}\" ")?;
}
write!(
formatter,
"at 0x{offset:x}, but the Espressif bootloader boots only applications from ELF files, in a \"firmware\" or \"update\" partition: give the binary image of the bootloader or of the data"
)
}
#[cfg(feature = "elf")]
Error::MisalignedApplicationImage {
path,
partition,
offset,
} => {
write!(
formatter,
"the Espressif application image of \"{path}\" goes "
)?;
if let Some(partition) = partition {
write!(formatter, "to the partition \"{partition}\" ")?;
}
write!(
formatter,
"at 0x{offset:x}, but the bootloader maps applications in pages of 0x10000 bytes: place it at a multiple of 0x10000, not below 0x10000"
)
}
Error::ImageRejected { path, reason } => {
write!(formatter, "the image \"{path}\" was rejected: {reason}")
}
Error::ImageNeedsLayout { board, partition } => write!(
formatter,
"the board \"{board}\" has a manifest image or erase entry for the partition \"{partition}\" and no layout: add a \"layout\" to the board, or use an \"offset\""
),
Error::UnknownPartition { board, partition } => write!(
formatter,
"the board \"{board}\" has a manifest image or erase entry for the partition \"{partition}\", which its layout does not define"
),
Error::MisalignedImage {
label,
offset,
required,
} => write!(
formatter,
"the image \"{label}\" starts at offset 0x{offset:x}, which is not a multiple of 0x{required:x}: the bootloader erases whole sectors of 0x{required:x} bytes, so it would erase the bytes before the image; move the image to a multiple of 0x{required:x}"
),
Error::OverlappingImages {
first,
second,
first_end,
second_offset,
} => write!(
formatter,
"the image \"{first}\" ends at 0x{first_end:x} once rounded up to whole erase sectors, past the start of the image \"{second}\" at 0x{second_offset:x}: move one of the images"
),
Error::ImageTooLarge {
label,
partition,
image_size,
partition_size,
} => write!(
formatter,
"the image \"{label}\" of 0x{image_size:x} bytes does not fit in the partition \"{partition}\" of 0x{partition_size:x} bytes: enlarge the partition in the layout or shrink the image"
),
Error::PartitionTableImageForDetectedFlash { partition } => write!(
formatter,
"the manifest writes an image to the partition table \"{partition}\", but partitions of the layout grow or move with the flash of the chip, so no fixed table fits every chip: remove the image and let nanoflash generate the table, or give the layout a fixed flash size"
),
Error::FixedOffsetOnMovingPartition {
what,
start,
end,
partition,
partition_offset,
flash_size,
addresses_in_file,
} => {
write!(
formatter,
"the {what} covers 0x{start:x}..0x{end:x}, which overlaps the partition \"{partition}\" at 0x{partition_offset:x} on 0x{flash_size:x} bytes of flash, but \"{partition}\" moves with the flash of the chip: "
)?;
formatter.write_str(if *addresses_in_file {
"give the partition a binary image (.bin), targeted by name"
} else {
"target the partition by name in the manifest"
})
}
Error::ImageOutsideFlash {
label,
end,
flash_size,
} => write!(
formatter,
"the image \"{label}\" ends at 0x{end:x}, past the end of the 0x{flash_size:x} bytes of flash of the layout: move the image or enlarge the flash in the layout"
),
Error::MisalignedErase {
entry,
offset,
size,
required,
} => write!(
formatter,
"the erase entry \"{entry}\" covers 0x{offset:x}..0x{:x}, which does not start and end on multiples of 0x{required:x}: the flash is erased in whole sectors of 0x{required:x} bytes, so the bytes around the entry would be erased too; align the entry to 0x{required:x}",
offset.saturating_add(*size)
),
Error::EraseOutsideFlash {
entry,
end,
flash_size,
} => write!(
formatter,
"the erase entry \"{entry}\" ends at 0x{end:x}, past the end of the 0x{flash_size:x} bytes of flash of the layout: shrink the entry or enlarge the flash in the layout"
),
Error::OutsideAddressRange {
what,
end,
limit,
protocol,
} => write!(
formatter,
"the {what} ends at 0x{end:x}, past 0x{limit:x}, the end of what the {protocol} protocol can address: move it below 0x{limit:x}"
),
Error::OutsideDetectedFlash {
what,
end,
flash_size,
} => write!(
formatter,
"the {what} ends at 0x{end:x}, past the end of the 0x{flash_size:x} bytes of flash the chip reports, so nothing was erased or written: move it, or connect a board with more flash"
),
Error::NothingToFlash { board } => write!(
formatter,
"the board \"{board}\" has no image and no erase entry in the manifest: add an image to write"
),
Error::EmptyImage { path } => write!(
formatter,
"the image \"{path}\" is empty: rebuild it, or remove it from the manifest"
),
Error::OutOfMemory { what, size } => write!(
formatter,
"there is not enough memory for the 0x{size:x} bytes of the {what}"
),
Error::UnknownBoard { identifier, known } => write!(
formatter,
"the manifest has no board \"{identifier}\": the boards are {}",
known.join(", ")
),
Error::NoMatchingBoard { identity } => {
match identity {
Some(identity) => write!(
formatter,
"no board of the manifest matches the device {:04x}:{:04x}",
identity.vendor, identity.product
)?,
None => formatter.write_str(
"no board of the manifest suits a device without a USB identity",
)?,
}
formatter.write_str(": pass --board-identifier, or list the device in the manifest")
}
Error::SeveralProtocols { protocols } => {
formatter.write_str("the candidate boards speak several protocols (")?;
for (index, protocol) in protocols.iter().enumerate() {
if index > 0 {
formatter.write_str(", ")?;
}
write!(formatter, "{protocol}")?;
}
formatter.write_str("): pass --board-identifier")
}
Error::SeveralBoards { chip, boards } => write!(
formatter,
"several boards have the chip {chip} ({}): pass --board-identifier",
boards.join(", ")
),
Error::BoardRequired { boards } => write!(
formatter,
"the manifest has several boards ({}): pass --board-identifier",
boards.join(", ")
),
Error::ProtocolRequired { identity } => {
match identity {
Some(identity) => write!(
formatter,
"the protocol of the device {:04x}:{:04x} is unknown",
identity.vendor, identity.product
)?,
None => formatter.write_str("the protocol of the device is unknown")?,
}
formatter.write_str(": pass --protocol")
}
Error::ProtocolNotEnabled { protocol } => write!(
formatter,
"the {protocol} protocol is not enabled in this build of nanoflash"
),
Error::UnknownFlashSize => formatter.write_str(
"the size of the flash is unknown: add a layout to the board, or connect to a chip that reports it",
),
Error::FlashSizeNeedsDetectLayout => formatter.write_str(
"a flash size needs a board with a layout that has size = \"detect\" and a minimum: this board has no layout, so drop the flash size or add such a layout",
),
Error::FlashTooSmall { layout, detected } => write!(
formatter,
"the layout needs 0x{layout:x} bytes of flash and the chip has 0x{detected:x}: use a layout that fits, or a board with more flash"
),
Error::WrongChip { detected, expected } => write!(
formatter,
"the chip found is {detected} and the selected boards have {}: pass --board-identifier of the right board, or connect the right board",
expected.join(", ")
),
Error::VerificationFailed {
label,
offset,
size,
expected,
actual,
checksum,
} => write!(
formatter,
"the image \"{label}\" at 0x{offset:x} (0x{size:x} bytes) does not read back as written: the board computed the {checksum} {actual} instead of {expected}: flash again, and check the power supply and the flash size of the board if it fails again"
),
Error::NoBootloader {
waited_for,
reset,
protocol,
rates,
} => match protocol {
Protocol::Espressif | Protocol::Samba => match (waited_for, reset) {
(Some(filter), Some("touch-1200")) => write!(
formatter,
"no bootloader device matching {filter} appeared within 15 s after the 1200-baud touch: double-tap the reset button of the board (its LED pulses in the bootloader), then try again"
),
(Some(filter), Some(reset)) => write!(
formatter,
"no bootloader device matching {filter} appeared within 15 s after the reset sequence \"{reset}\" of the board: check the reset sequence of the board in the manifest, or double-tap the reset button of the board (its LED pulses in the bootloader) and try again"
),
(Some(filter), None) => write!(
formatter,
"no bootloader device matching {filter} appeared within 15 s after the reset: double-tap the reset button of the board (its LED pulses in the bootloader), then try again"
),
(None, _) => formatter.write_str(
"no SAM-BA bootloader answered on the port: double-tap the reset button of the board (its LED pulses in the bootloader), then try again with the port it shows",
),
},
Protocol::Avr109 => match (waited_for, reset) {
(Some(filter), Some("touch-1200")) => write!(
formatter,
"no bootloader device matching {filter} appeared after the 1200-baud touch: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
),
(Some(filter), Some(reset)) => write!(
formatter,
"no bootloader device matching {filter} appeared after the reset sequence \"{reset}\" of the board: check the reset sequence of the board in the manifest, or press the reset button of the board once (its LED pulses for 8 s in the bootloader) and try again with the port it shows"
),
(Some(filter), None) => write!(
formatter,
"no bootloader device matching {filter} appeared after the reset: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
),
(None, _) => formatter.write_str(
"no AVR109 bootloader answered on the port: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows",
),
},
Protocol::Stk500v1 | Protocol::Stk500v2 => {
let name = if *protocol == Protocol::Stk500v1 {
"STK500v1"
} else {
"STK500v2"
};
write!(formatter, "no {name} bootloader answered on the port")?;
let mut rates = rates.iter();
if let Some(first) = rates.next() {
write!(formatter, " at {first}")?;
for rate in rates {
write!(formatter, " and {rate}")?;
}
formatter.write_str(" baud")?;
}
if *reset == Some("custom") {
formatter.write_str(
" after the reset sequence \"custom\" of the board: check the port and the cable and the reset sequence of the board in the manifest, or press the reset button of the board just before flashing",
)
} else if *reset == Some("none") {
formatter.write_str(
" with the reset sequence \"none\" of the board, which does not reset it: press the reset button of the board just before flashing, or check the port and the cable",
)
} else {
formatter.write_str(
": check the port and the cable, or press the reset button of the board just before flashing (its automatic reset through DTR may be missing)",
)
}
}
},
Error::NotConnected { protocol } => write!(
formatter,
"the {protocol} backend was asked to erase, write, verify or reset before it connected, so nothing was sent to the board: call connect first"
),
Error::UnsupportedBootloader { version } => write!(
formatter,
"the bootloader says \"{version}\" and lacks Arduino's SAM-BA extensions X, Y and Z, which nanoflash needs: update the bootloader, or flash with bossac"
),
Error::UnknownBootloaderDevice { identity } => write!(
formatter,
"the USB identity of the bootloader of the device {:04x}:{:04x} is unknown: list it in \"bootloader-devices\" of the board, or double-tap the reset button and pass the bootloader's port",
identity.vendor, identity.product
),
Error::BelowWritableFlash {
what,
offset,
writable_from,
} => write!(
formatter,
"the {what} starts at 0x{offset:x}, below 0x{writable_from:x}: the bootloader occupies the flash below 0x{writable_from:x} and does not write it; remove it from the manifest or move it to 0x{writable_from:x} or above"
),
Error::AboveWritableFlash {
what,
end,
writable_to,
protocol: Protocol::Stk500v2,
} => write!(
formatter,
"the {what} ends at 0x{end:x}, past 0x{writable_to:x}: the STK500v2 bootloader of the Mega 2560 erases pages only below 0x{writable_to:x}, 16 KiB under the end of flash although it occupies only the last 8 KiB, so the pages past 0x{writable_to:x} would be programmed without being erased; remove it from the manifest or make it end at 0x{writable_to:x} or below"
),
Error::AboveWritableFlash {
what,
end,
writable_to,
..
} => write!(
formatter,
"the {what} ends at 0x{end:x}, past 0x{writable_to:x}: the bootloader occupies the flash from 0x{writable_to:x} and does not write it; remove it from the manifest or make it end at 0x{writable_to:x} or below"
),
Error::ReadBackDiffers {
label,
offset,
expected,
actual,
} => write!(
formatter,
"the image \"{label}\" does not read back as written: the byte at 0x{offset:x} is 0x{actual:02x} instead of 0x{expected:02x}: flash again; if it fails at the same place, the lock bits of the chip protect that part of the flash"
),
Error::EraseShortOfFlashEnd {
chip,
entry,
offset,
end,
flash_size,
} => write!(
formatter,
"the erase entry \"{entry}\" covers 0x{offset:x}..0x{end:x}, and the bootloader of the {chip} erases from an offset to the end of flash, so erasing it would also erase 0x{end:x}..0x{flash_size:x}; it was not erased: make the erase entry end at 0x{flash_size:x}, or remove it from the manifest"
),
Error::ImageBelowWritten {
chip,
label,
offset,
} => write!(
formatter,
"the image \"{label}\" at 0x{offset:x} is written after an image above it, and the bootloader of the {chip} erases from 0x{offset:x} to the end of flash before writing it, which would erase that image, so it was not written: write the images in order of offset"
),
Error::PageOutOfEraseOrder {
what,
offset,
erases_next,
} => write!(
formatter,
"the {what} programs the page at 0x{offset:x}, but the STK500v2 bootloader of the Mega 2560 erases one page per page programmed, in order from 0x0 wherever the page goes, and erases 0x{erases_next:x} next: the page at 0x{offset:x} would not be erased, or another would be; nothing was written: write the images as one run from 0x0 in order of offset and erase only from 0x0, or first erase every page the bootloader erases (--erase-all)"
),
}
}
}
impl core::error::Error for Error {}
pub(crate) fn rom_error(code: u8) -> &'static str {
match code {
0x05 => "the message is malformed",
0x06 => "the command failed",
0x07 => "bad checksum",
0x08 => "flash write failed (read-back mismatch)",
0x09 => "flash read failed",
0x0A => "bad flash read length",
0x0B => "decompression failed",
0x0C => "decompressed data has a bad Adler-32 checksum",
0x0D => "bad decompression parameter",
0x0E => "bad RAM binary size",
0x0F => "bad RAM binary address",
0x64 => "invalid parameter",
0x65 => "invalid format",
0x66 => "description too long",
0x67 => "bad encoding description",
0x69 => "insufficient storage",
_ => "unknown error",
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
#[test]
fn bootloader_errors_have_their_class_and_hint() {
let waited = Error::NoBootloader {
waited_for: Some("2341:005a".into()),
reset: Some("touch-1200"),
protocol: Protocol::Samba,
rates: Vec::new(),
};
assert_eq!(waited.class(), ErrorClass::Device);
assert_eq!(
waited.to_string(),
"no bootloader device matching 2341:005a appeared within 15 s after the 1200-baud touch: double-tap the reset button of the board (its LED pulses in the bootloader), then try again"
);
let custom = Error::NoBootloader {
waited_for: Some("2341:005a".into()),
reset: Some("custom"),
protocol: Protocol::Samba,
rates: Vec::new(),
};
assert_eq!(
custom.to_string(),
"no bootloader device matching 2341:005a appeared within 15 s after the reset sequence \"custom\" of the board: check the reset sequence of the board in the manifest, or double-tap the reset button of the board (its LED pulses in the bootloader) and try again"
);
let silent = Error::NoBootloader {
waited_for: None,
reset: None,
protocol: Protocol::Samba,
rates: Vec::new(),
};
assert_eq!(silent.class(), ErrorClass::Device);
assert_eq!(
silent.to_string(),
"no SAM-BA bootloader answered on the port: double-tap the reset button of the board (its LED pulses in the bootloader), then try again with the port it shows"
);
let early = Error::NotConnected {
protocol: Protocol::Samba,
};
assert_eq!(early.class(), ErrorClass::Input);
assert_eq!(
early.to_string(),
"the samba backend was asked to erase, write, verify or reset before it connected, so nothing was sent to the board: call connect first"
);
let unsupported = Error::UnsupportedBootloader {
version: "v1.1 [Arduino:IKXYZ]".into(),
};
assert_eq!(unsupported.class(), ErrorClass::Device);
assert_eq!(
unsupported.to_string(),
"the bootloader says \"v1.1 [Arduino:IKXYZ]\" and lacks Arduino's SAM-BA extensions X, Y and Z, which nanoflash needs: update the bootloader, or flash with bossac"
);
let unknown = Error::UnknownBootloaderDevice {
identity: UsbIdentity {
vendor: 0x2341,
product: 0x805a,
serial_number: None,
},
};
assert_eq!(unknown.class(), ErrorClass::Input);
assert_eq!(
unknown.to_string(),
"the USB identity of the bootloader of the device 2341:805a is unknown: list it in \"bootloader-devices\" of the board, or double-tap the reset button and pass the bootloader's port"
);
let below = Error::BelowWritableFlash {
what: "image \"bootloader\"".into(),
offset: 0,
writable_from: 0x1_0000,
};
assert_eq!(below.class(), ErrorClass::Input);
assert_eq!(
below.to_string(),
"the image \"bootloader\" starts at 0x0, below 0x10000: the bootloader occupies the flash below 0x10000 and does not write it; remove it from the manifest or move it to 0x10000 or above"
);
let above = Error::AboveWritableFlash {
what: "image \"application\"".into(),
end: 0x7E01,
writable_to: 0x7E00,
protocol: Protocol::Stk500v1,
};
assert_eq!(above.class(), ErrorClass::Input);
assert_eq!(
above.to_string(),
"the image \"application\" ends at 0x7e01, past 0x7e00: the bootloader occupies the flash from 0x7e00 and does not write it; remove it from the manifest or make it end at 0x7e00 or below"
);
let mega = Error::AboveWritableFlash {
what: "image \"application\"".into(),
end: 0x3_C100,
writable_to: 0x3_C000,
protocol: Protocol::Stk500v2,
};
assert_eq!(mega.class(), ErrorClass::Input);
assert_eq!(
mega.to_string(),
"the image \"application\" ends at 0x3c100, past 0x3c000: the STK500v2 bootloader of the Mega 2560 erases pages only below 0x3c000, 16 KiB under the end of flash although it occupies only the last 8 KiB, so the pages past 0x3c000 would be programmed without being erased; remove it from the manifest or make it end at 0x3c000 or below"
);
let short = Error::EraseShortOfFlashEnd {
chip: "samd21g18a".into(),
entry: "storage".into(),
offset: 0x8000,
end: 0x9000,
flash_size: 0x4_0000,
};
assert_eq!(short.class(), ErrorClass::Input);
assert_eq!(
short.to_string(),
"the erase entry \"storage\" covers 0x8000..0x9000, and the bootloader of the samd21g18a erases from an offset to the end of flash, so erasing it would also erase 0x9000..0x40000; it was not erased: make the erase entry end at 0x40000, or remove it from the manifest"
);
let order = Error::ImageBelowWritten {
chip: "samd21g18a".into(),
label: "low".into(),
offset: 0x2000,
};
assert_eq!(order.class(), ErrorClass::Input);
assert_eq!(
order.to_string(),
"the image \"low\" at 0x2000 is written after an image above it, and the bootloader of the samd21g18a erases from 0x2000 to the end of flash before writing it, which would erase that image, so it was not written: write the images in order of offset"
);
}
#[test]
fn pages_out_of_erase_order_are_input_errors() {
let error = Error::PageOutOfEraseOrder {
what: "image \"application\"".into(),
offset: 0x100,
erases_next: 0,
};
assert_eq!(error.class(), ErrorClass::Input);
assert_eq!(
error.to_string(),
"the image \"application\" programs the page at 0x100, but the STK500v2 bootloader of the Mega 2560 erases one page per page programmed, in order from 0x0 wherever the page goes, and erases 0x0 next: the page at 0x100 would not be erased, or another would be; nothing was written: write the images as one run from 0x0 in order of offset and erase only from 0x0, or first erase every page the bootloader erases (--erase-all)"
);
}
#[test]
fn read_back_differences_are_verification_failures() {
let error = Error::ReadBackDiffers {
label: "application".into(),
offset: 0x85,
expected: 0x0f,
actual: 0xff,
};
assert_eq!(error.class(), ErrorClass::Verification);
assert_eq!(
error.to_string(),
"the image \"application\" does not read back as written: the byte at 0x85 is 0xff instead of 0x0f: flash again; if it fails at the same place, the lock bits of the chip protect that part of the flash"
);
}
#[test]
fn no_bootloader_names_the_protocol_hint() {
let caterina = Error::NoBootloader {
waited_for: Some("2341:0036".into()),
reset: Some("touch-1200"),
protocol: Protocol::Avr109,
rates: Vec::new(),
};
assert_eq!(caterina.class(), ErrorClass::Device);
assert_eq!(
caterina.to_string(),
"no bootloader device matching 2341:0036 appeared after the 1200-baud touch: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
);
let custom = Error::NoBootloader {
waited_for: Some("2341:0036".into()),
reset: Some("custom"),
protocol: Protocol::Avr109,
rates: Vec::new(),
};
assert_eq!(
custom.to_string(),
"no bootloader device matching 2341:0036 appeared after the reset sequence \"custom\" of the board: check the reset sequence of the board in the manifest, or press the reset button of the board once (its LED pulses for 8 s in the bootloader) and try again with the port it shows"
);
let silent = Error::NoBootloader {
waited_for: None,
reset: None,
protocol: Protocol::Avr109,
rates: Vec::new(),
};
assert_eq!(
silent.to_string(),
"no AVR109 bootloader answered on the port: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
);
let optiboot = Error::NoBootloader {
waited_for: None,
reset: None,
protocol: Protocol::Stk500v1,
rates: alloc::vec![115_200, 57_600],
};
assert_eq!(optiboot.class(), ErrorClass::Device);
assert_eq!(
optiboot.to_string(),
"no STK500v1 bootloader answered on the port at 115200 and 57600 baud: check the port and the cable, or press the reset button of the board just before flashing (its automatic reset through DTR may be missing)"
);
let wiring = Error::NoBootloader {
waited_for: None,
reset: Some("none"),
protocol: Protocol::Stk500v2,
rates: alloc::vec![115_200],
};
assert_eq!(
wiring.to_string(),
"no STK500v2 bootloader answered on the port at 115200 baud with the reset sequence \"none\" of the board, which does not reset it: press the reset button of the board just before flashing, or check the port and the cable"
);
let custom = Error::NoBootloader {
waited_for: None,
reset: Some("custom"),
protocol: Protocol::Stk500v1,
rates: alloc::vec![57_600],
};
assert_eq!(
custom.to_string(),
"no STK500v1 bootloader answered on the port at 57600 baud after the reset sequence \"custom\" of the board: check the port and the cable and the reset sequence of the board in the manifest, or press the reset button of the board just before flashing"
);
}
#[test]
fn verification_failures_name_their_checksum() {
let error = Error::VerificationFailed {
label: "application".into(),
offset: 0x1_1000,
size: 0x1000,
expected: "d5b0".into(),
actual: "1234".into(),
checksum: "CRC-16",
};
assert_eq!(error.class(), ErrorClass::Verification);
assert_eq!(
error.to_string(),
"the image \"application\" at 0x11000 (0x1000 bytes) does not read back as written: the board computed the CRC-16 1234 instead of d5b0: flash again, and check the power supply and the flash size of the board if it fails again"
);
}
}