Skip to content

add support for flashing direct-boot images to esp32c3 #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 29 additions & 11 deletions cargo-espflash/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{
use cargo_metadata::Message;
use clap::{App, Arg, ArgMatches, SubCommand};
use error::Error;
use espflash::{Chip, Config, FirmwareImage, Flasher, PartitionTable};
use espflash::{Chip, Config, FirmwareImage, Flasher, ImageFormatId, PartitionTable};
use miette::{IntoDiagnostic, Result, WrapErr};
use monitor::monitor;
use package_metadata::CargoEspFlashMeta;
Expand All @@ -17,6 +17,7 @@ use serial::{BaudRate, FlowControl, SerialPort};
use crate::cargo_config::CargoConfig;
use crate::error::NoTargetError;
use crate::{cargo_config::parse_cargo_config, error::UnsupportedTargetError};
use std::str::FromStr;

mod cargo_config;
mod error;
Expand All @@ -42,6 +43,11 @@ fn main() -> Result<()> {
.takes_value(true)
.value_name("FEATURES")
.help("Comma delimited list of build features"),
Arg::with_name("format")
.long("format")
.takes_value(true)
.value_name("image format")
.help("Image format to flash"),
];
let connect_args = [Arg::with_name("serial")
.takes_value(true)
Expand Down Expand Up @@ -228,12 +234,18 @@ fn flash(
None
};

let image_format = matches
.value_of("format")
.map(ImageFormatId::from_str)
.transpose()?
.or(metadata.format);

// Read the ELF data from the build path and load it to the target.
let elf_data = fs::read(path).into_diagnostic()?;
if matches.is_present("ram") {
flasher.load_elf_to_ram(&elf_data)?;
} else {
flasher.load_elf_to_flash(&elf_data, bootloader, partition_table)?;
flasher.load_elf_to_flash(&elf_data, bootloader, partition_table, image_format)?;
}
println!("\nFlashing has completed!");

Expand Down Expand Up @@ -266,13 +278,6 @@ fn build(
cargo_config: &CargoConfig,
chip: Option<Chip>,
) -> Result<PathBuf> {
// The 'build-std' unstable cargo feature is required to enable
// cross-compilation. If it has not been set then we cannot build the
// application.
if !cargo_config.has_build_std() {
return Err(Error::NoBuildStd.into());
};

let target = cargo_config
.target()
.ok_or_else(|| NoTargetError::new(chip))?;
Expand All @@ -281,6 +286,13 @@ fn build(
return Err(Error::UnsupportedTarget(UnsupportedTargetError::new(target, chip)).into());
}
}
// The 'build-std' unstable cargo feature is required to enable
// cross-compilation for xtensa targets.
// If it has not been set then we cannot build the
// application.
if !cargo_config.has_build_std() && target.starts_with("xtensa-") {
return Err(Error::NoBuildStd.into());
};

// Build the list of arguments to pass to 'cargo build'.
let mut args = vec![];
Expand Down Expand Up @@ -356,7 +368,7 @@ fn build(
fn save_image(
matches: &ArgMatches,
_config: Config,
_metadata: CargoEspFlashMeta,
metadata: CargoEspFlashMeta,
cargo_config: CargoConfig,
) -> Result<()> {
let target = cargo_config
Expand All @@ -370,7 +382,13 @@ fn save_image(

let image = FirmwareImage::from_data(&elf_data)?;

let flash_image = chip.get_flash_image(&image, None, None, None)?;
let image_format = matches
.value_of("format")
.map(ImageFormatId::from_str)
.transpose()?
.or(metadata.format);

let flash_image = chip.get_flash_image(&image, None, None, image_format, None)?;
let parts: Vec<_> = flash_image.ota_segments().collect();

let out_path = matches.value_of("file").unwrap();
Expand Down
2 changes: 2 additions & 0 deletions cargo-espflash/src/package_metadata.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::error::{Error, TomlError};
use cargo_toml::Manifest;
use espflash::ImageFormatId;
use miette::{IntoDiagnostic, Result, WrapErr};
use serde::Deserialize;
use std::fs::read_to_string;
Expand All @@ -9,6 +10,7 @@ use std::path::Path;
pub struct CargoEspFlashMeta {
pub partition_table: Option<String>,
pub bootloader: Option<String>,
pub format: Option<ImageFormatId>,
}

#[derive(Clone, Debug, Default, Deserialize)]
Expand Down
6 changes: 3 additions & 3 deletions espflash/src/chip/esp32/esp32.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::ops::Range;

use super::Esp32Params;
use crate::error::UnsupportedImageFormatError;
use crate::{
chip::{bytes_to_mac_addr, Chip, ChipType, ReadEFuse, SpiRegisters},
connection::Connection,
Expand Down Expand Up @@ -117,6 +118,7 @@ impl ChipType for Esp32 {
bootloader: Option<Vec<u8>>,
partition_table: Option<PartitionTable>,
image_format: ImageFormatId,
_chip_revision: Option<u32>,
) -> Result<Box<dyn ImageFormat<'a> + 'a>, Error> {
match image_format {
ImageFormatId::Bootloader => Ok(Box::new(Esp32BootloaderFormat::new(
Expand All @@ -126,9 +128,7 @@ impl ChipType for Esp32 {
partition_table,
bootloader,
)?)),
ImageFormatId::DirectBoot => {
todo!()
}
_ => Err(UnsupportedImageFormatError::new(image_format, Chip::Esp32, None).into()),
}
}

Expand Down
14 changes: 10 additions & 4 deletions espflash/src/chip/esp32/esp32c3.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::ops::Range;

use super::Esp32Params;
use crate::error::UnsupportedImageFormatError;
use crate::image_format::Esp32DirectBootFormat;
use crate::{
chip::{bytes_to_mac_addr, ChipType, ReadEFuse, SpiRegisters},
connection::Connection,
Expand Down Expand Up @@ -70,18 +72,22 @@ impl ChipType for Esp32c3 {
bootloader: Option<Vec<u8>>,
partition_table: Option<PartitionTable>,
image_format: ImageFormatId,
chip_revision: Option<u32>,
) -> Result<Box<dyn ImageFormat<'a> + 'a>, Error> {
match image_format {
ImageFormatId::Bootloader => Ok(Box::new(Esp32BootloaderFormat::new(
match (image_format, chip_revision) {
(ImageFormatId::Bootloader, _) => Ok(Box::new(Esp32BootloaderFormat::new(
image,
Chip::Esp32c3,
PARAMS,
partition_table,
bootloader,
)?)),
ImageFormatId::DirectBoot => {
todo!()
(ImageFormatId::DirectBoot, None | Some(3..)) => {
Ok(Box::new(Esp32DirectBootFormat::new(image)?))
}
_ => Err(
UnsupportedImageFormatError::new(image_format, Chip::Esp32c3, chip_revision).into(),
),
}
}

Expand Down
6 changes: 3 additions & 3 deletions espflash/src/chip/esp32/esp32s2.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::ops::Range;

use super::Esp32Params;
use crate::error::UnsupportedImageFormatError;
use crate::{
chip::{bytes_to_mac_addr, ChipType, ReadEFuse, SpiRegisters},
connection::Connection,
Expand Down Expand Up @@ -94,6 +95,7 @@ impl ChipType for Esp32s2 {
bootloader: Option<Vec<u8>>,
partition_table: Option<PartitionTable>,
image_format: ImageFormatId,
_chip_revision: Option<u32>,
) -> Result<Box<dyn ImageFormat<'a> + 'a>, Error> {
match image_format {
ImageFormatId::Bootloader => Ok(Box::new(Esp32BootloaderFormat::new(
Expand All @@ -103,9 +105,7 @@ impl ChipType for Esp32s2 {
partition_table,
bootloader,
)?)),
ImageFormatId::DirectBoot => {
todo!()
}
_ => Err(UnsupportedImageFormatError::new(image_format, Chip::Esp32s2, None).into()),
}
}

Expand Down
3 changes: 2 additions & 1 deletion espflash/src/chip/esp8266.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ impl ChipType for Esp8266 {
_bootloader: Option<Vec<u8>>,
_partition_table: Option<PartitionTable>,
image_format: ImageFormatId,
_chip_revision: Option<u32>,
) -> Result<Box<dyn ImageFormat<'a> + 'a>, Error> {
match image_format {
ImageFormatId::Bootloader => Ok(Box::new(Esp8266Format::new(image)?)),
_ => Err(UnsupportedImageFormatError::new(image_format, Chip::Esp8266).into()),
_ => Err(UnsupportedImageFormatError::new(image_format, Chip::Esp8266, None).into()),
}
}

Expand Down
34 changes: 25 additions & 9 deletions espflash/src/chip/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ pub trait ChipType {
bootloader: Option<Vec<u8>>,
partition_table: Option<PartitionTable>,
image_format: ImageFormatId,
chip_revision: Option<u32>,
) -> Result<Box<dyn ImageFormat<'a> + 'a>, Error>;

/// Read the MAC address of the connected chip.
Expand Down Expand Up @@ -158,20 +159,35 @@ impl Chip {
bootloader: Option<Vec<u8>>,
partition_table: Option<PartitionTable>,
image_format: Option<ImageFormatId>,
chip_revision: Option<u32>,
) -> Result<Box<dyn ImageFormat<'a> + 'a>, Error> {
let image_format = image_format.unwrap_or_else(|| self.default_image_format());

match self {
Chip::Esp32 => {
Esp32::get_flash_segments(image, bootloader, partition_table, image_format)
Chip::Esp32 => Esp32::get_flash_segments(
image,
bootloader,
partition_table,
image_format,
chip_revision,
),
Chip::Esp32c3 => Esp32c3::get_flash_segments(
image,
bootloader,
partition_table,
image_format,
chip_revision,
),
Chip::Esp32s2 => Esp32s2::get_flash_segments(
image,
bootloader,
partition_table,
image_format,
chip_revision,
),
Chip::Esp8266 => {
Esp8266::get_flash_segments(image, None, None, image_format, chip_revision)
}
Chip::Esp32c3 => {
Esp32c3::get_flash_segments(image, bootloader, partition_table, image_format)
}
Chip::Esp32s2 => {
Esp32s2::get_flash_segments(image, bootloader, partition_table, image_format)
}
Chip::Esp8266 => Esp8266::get_flash_segments(image, None, None, image_format),
}
}

Expand Down
63 changes: 39 additions & 24 deletions espflash/src/elf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::error::{ElfError, Error};
use crate::flasher::FlashSize;
use std::fmt::{Debug, Formatter};
use std::mem::take;
use std::ops::AddAssign;
use xmas_elf::sections::{SectionData, ShType};
use xmas_elf::ElfFile;

Expand Down Expand Up @@ -88,7 +89,7 @@ impl<'a> FirmwareImage<'a> {
}
}

#[derive(Eq, Clone)]
#[derive(Eq, Clone, Default)]
/// A segment of code from the source elf
pub struct CodeSegment<'a> {
pub addr: u32,
Expand All @@ -97,21 +98,12 @@ pub struct CodeSegment<'a> {

impl<'a> CodeSegment<'a> {
pub fn new(addr: u32, data: &'a [u8]) -> Self {
// pad to 4 byte
let padding = (4 - data.len() % 4) % 4;
if padding == 0 {
CodeSegment {
addr,
data: Cow::Borrowed(data),
}
} else {
let mut data = data.to_vec();
data.extend_from_slice(&[0; 4][0..padding]);
CodeSegment {
addr,
data: Cow::Owned(data),
}
}
let mut segment = CodeSegment {
addr,
data: Cow::Borrowed(data),
};
segment.pad_align(4);
segment
}

/// Split of the first `count` bytes into a new segment, adjusting the remaining segment as needed
Expand Down Expand Up @@ -142,19 +134,41 @@ impl<'a> CodeSegment<'a> {
}
}

pub fn add(&mut self, extend: &[u8]) {
let mut data = take(&mut self.data).into_owned();
data.extend_from_slice(extend);
self.data = Cow::Owned(data);
}

pub fn size(&self) -> u32 {
self.data.len() as u32
}

pub fn data(&self) -> &[u8] {
self.data.as_ref()
}

pub fn pad_align(&mut self, align: usize) {
let padding = (align - self.data.len() % align) % align;
if padding > 0 {
let mut data = take(&mut self.data).into_owned();
data.extend_from_slice(&[0; 4][0..padding]);
self.data = Cow::Owned(data);
}
}
}

impl<'a> AddAssign<&'_ [u8]> for CodeSegment<'a> {
fn add_assign(&mut self, rhs: &'_ [u8]) {
let mut data = take(&mut self.data).into_owned();
data.extend_from_slice(rhs);
self.data = Cow::Owned(data);
}
}

impl<'a> AddAssign<&'_ CodeSegment<'_>> for CodeSegment<'a> {
fn add_assign(&mut self, rhs: &'_ CodeSegment<'_>) {
let mut data = take(&mut self.data).into_owned();
// pad or truncate
#[allow(clippy::suspicious_op_assign_impl)]
data.resize((rhs.addr - self.addr) as usize, 0);
data.extend_from_slice(rhs.data());
self.data = Cow::Owned(data);
}
}

impl Debug for CodeSegment<'_> {
Expand Down Expand Up @@ -184,6 +198,7 @@ impl Ord for CodeSegment<'_> {
}
}

#[derive(Clone)]
/// A segment of data to write to the flash
pub struct RomSegment<'a> {
pub addr: u32,
Expand Down Expand Up @@ -219,14 +234,14 @@ pub fn update_checksum(data: &[u8], mut checksum: u8) -> u8 {
checksum
}

pub fn merge_segments(mut segments: Vec<CodeSegment>) -> Vec<CodeSegment> {
pub fn merge_adjacent_segments(mut segments: Vec<CodeSegment>) -> Vec<CodeSegment> {
segments.sort();

let mut merged: Vec<CodeSegment> = Vec::with_capacity(segments.len());
for segment in segments {
match merged.last_mut() {
Some(last) if last.addr + last.size() == segment.addr => {
last.add(segment.data());
*last += segment.data();
}
_ => {
merged.push(segment);
Expand Down
Loading