Skip to content
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

Add checksum-md5 command #536

Merged
merged 5 commits into from
Dec 28, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add --chip argument for flash and write-bin commands (#514)
- Add --partition-table-offset argument for specifying the partition table offset (#516)
- Add `Serialize` and `Deserialize` to `FlashFrequency`, `FlashMode` and `FlashSize`. (#528)
- Add `checksum-md5` command (#536)

### Fixed

Expand Down
31 changes: 0 additions & 31 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion espflash/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ required-features = ["cli"]
[dependencies]
addr2line = { version = "0.21.0", optional = true }
base64 = "0.21.4"
binrw = "0.12.0"
bytemuck = { version = "1.14.0", features = ["derive"] }
clap = { version = "4.4.6", features = ["derive", "env", "wrap_help"], optional = true }
clap_complete = { version = "4.4.3", optional = true }
Expand Down
32 changes: 32 additions & 0 deletions espflash/src/bin/espflash.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{
fs::{self, File},
io::Read,
num::ParseIntError,
path::PathBuf,
};

Expand Down Expand Up @@ -83,6 +84,8 @@ enum Commands {
SaveImage(SaveImageArgs),
/// Write a binary file to a specific address in a target device's flash
WriteBin(WriteBinArgs),
/// Calculate the MD5 checksum of the given region
ChecksumMd5(ChecksumMd5Args),
}

/// Erase named partitions based on provided partition table
Expand Down Expand Up @@ -146,6 +149,24 @@ struct WriteBinArgs {
connect_args: ConnectArgs,
}

#[derive(Debug, Args)]
#[non_exhaustive]
struct ChecksumMd5Args {
/// Start address
#[clap(short, long, value_parser=parse_u32)]
address: u32,
/// Length
#[clap(short, long, value_parser=parse_u32)]
length: u32,
/// Connection configuration
#[clap(flatten)]
connect_args: ConnectArgs,
}

pub fn parse_u32(input: &str) -> Result<u32, ParseIntError> {
parse_int::parse(input)
}

fn main() -> Result<()> {
miette::set_panic_hook();
initialize_logger(LevelFilter::Info);
Expand Down Expand Up @@ -176,6 +197,7 @@ fn main() -> Result<()> {
Commands::PartitionTable(args) => partition_table(args),
Commands::SaveImage(args) => save_image(args),
Commands::WriteBin(args) => write_bin(args, &config),
Commands::ChecksumMd5(args) => checksum_md5(&args, &config),
}
}

Expand Down Expand Up @@ -334,3 +356,13 @@ fn write_bin(args: WriteBinArgs, config: &Config) -> Result<()> {

Ok(())
}

/// Connect to a target device and calculate the checksum of the given region
fn checksum_md5(args: &ChecksumMd5Args, config: &Config) -> Result<()> {
let mut flasher = connect(&args.connect_args, config)?;

let checksum = flasher.checksum_md5(args.address, args.length)?;
println!("0x{:x}", checksum);

Ok(())
}
16 changes: 16 additions & 0 deletions espflash/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ pub enum Command<'a> {
offset: u32,
size: u32,
},
FlashMd5 {
offset: u32,
size: u32,
},
}

impl<'a> Command<'a> {
Expand All @@ -184,6 +188,7 @@ impl<'a> Command<'a> {
Command::FlashDetect => CommandType::FlashDetect,
Command::EraseFlash { .. } => CommandType::EraseFlash,
Command::EraseRegion { .. } => CommandType::EraseRegion,
Command::FlashMd5 { .. } => CommandType::FlashMd5,
}
}

Expand Down Expand Up @@ -361,6 +366,17 @@ impl<'a> Command<'a> {
writer.write_all(&offset.to_le_bytes())?;
writer.write_all(&size.to_le_bytes())?;
}
Command::FlashMd5 { offset, size } => {
// length
writer.write_all(&(16u16.to_le_bytes()))?;
// checksum
writer.write_all(&(0u32.to_le_bytes()))?;
// data
writer.write_all(&offset.to_le_bytes())?;
writer.write_all(&size.to_le_bytes())?;
writer.write_all(&(0u32.to_le_bytes()))?;
writer.write_all(&(0u32.to_le_bytes()))?;
}
};
Ok(())
}
Expand Down
82 changes: 76 additions & 6 deletions espflash/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use std::{
time::Duration,
};

use binrw::{io::Cursor, BinRead, BinReaderExt};
use log::debug;
use serialport::UsbPortInfo;
use slip_codec::SlipDecoder;
Expand All @@ -34,13 +33,41 @@ const MAX_CONNECT_ATTEMPTS: usize = 7;
const MAX_SYNC_ATTEMPTS: usize = 5;
pub(crate) const USB_SERIAL_JTAG_PID: u16 = 0x1001;

#[derive(Debug, Copy, Clone)]
pub enum CommandResponseValue {
ValueU32(u32),
ValueU128(u128),
}

impl TryInto<u32> for CommandResponseValue {
type Error = crate::error::Error;

fn try_into(self) -> Result<u32, Self::Error> {
match self {
CommandResponseValue::ValueU32(value) => Ok(value),
CommandResponseValue::ValueU128(_) => Err(crate::error::Error::InternalError),
}
}
}

impl TryInto<u128> for CommandResponseValue {
type Error = crate::error::Error;

fn try_into(self) -> Result<u128, Self::Error> {
match self {
CommandResponseValue::ValueU32(_) => Err(crate::error::Error::InternalError),
CommandResponseValue::ValueU128(value) => Ok(value),
}
}
}

/// A response from a target device following a command
#[derive(Debug, Copy, Clone, BinRead)]
#[derive(Debug, Copy, Clone)]
pub struct CommandResponse {
pub resp: u8,
pub return_op: u8,
pub return_length: u16,
pub value: u32,
pub value: CommandResponseValue,
pub error: u8,
pub status: u8,
}
Expand Down Expand Up @@ -195,8 +222,50 @@ impl Connection {
match self.read(10)? {
None => Ok(None),
Some(response) => {
let mut cursor = Cursor::new(response);
let header = cursor.read_le()?;
// here is what esptool does: https://github.com/espressif/esptool/blob/master/esptool/loader.py#L458
// from esptool: things are a bit weird here, bear with us

// we rely on the known and expected response sizes
let status_len = if response.len() == 10 || response.len() == 26 {
2
} else {
4
};

let value = match response.len() {
10 | 12 => CommandResponseValue::ValueU32(u32::from_le_bytes(
response[4..][..4].try_into().unwrap(),
)),
44 => {
// MD5 is in ASCII
CommandResponseValue::ValueU128(
u128::from_str_radix(
std::str::from_utf8(&response[8..][..32]).unwrap(),
16,
)
.unwrap(),
)
}
26 => {
// MD5 is BE bytes
CommandResponseValue::ValueU128(u128::from_be_bytes(
response[8..][..16].try_into().unwrap(),
))
}
_ => {
return Err(Error::InternalError);
}
};

let header = CommandResponse {
resp: response[0],
return_op: response[1],
return_length: u16::from_le_bytes(response[2..][..2].try_into().unwrap()),
value,
error: response[response.len() - status_len],
status: response[response.len() - status_len + 1],
};

Ok(Some(header))
}
}
Expand All @@ -217,7 +286,7 @@ impl Connection {
}

/// Write a command and reads the response
pub fn command(&mut self, command: Command) -> Result<u32, Error> {
pub fn command(&mut self, command: Command) -> Result<CommandResponseValue, Error> {
let ty = command.command_type();
self.write_command(command).for_command(ty)?;

Expand Down Expand Up @@ -247,6 +316,7 @@ impl Connection {
self.with_timeout(CommandType::ReadReg.timeout(), |connection| {
connection.command(Command::ReadReg { address: reg })
})
.map(|v| v.try_into().unwrap())
}

/// Write a register command with a timeout
Expand Down
18 changes: 3 additions & 15 deletions espflash/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,9 @@ pub enum Error {
#[error(transparent)]
#[diagnostic(transparent)]
Defmt(#[from] DefmtError),

#[error("Internal Error")]
InternalError,
}

impl From<io::Error> for Error {
Expand All @@ -187,12 +190,6 @@ impl From<io::Error> for Error {
}
}

impl From<binrw::Error> for Error {
fn from(err: binrw::Error) -> Self {
Self::Connection(err.into())
}
}

impl From<serialport::Error> for Error {
fn from(err: serialport::Error) -> Self {
Self::Connection(err.into())
Expand Down Expand Up @@ -261,15 +258,6 @@ impl From<io::Error> for ConnectionError {
}
}

impl From<binrw::Error> for ConnectionError {
fn from(err: binrw::Error) -> Self {
match err {
binrw::Error::Io(e) => ConnectionError::from(e),
_ => unreachable!(),
}
}
}

impl From<serialport::Error> for ConnectionError {
fn from(err: serialport::Error) -> Self {
use serialport::ErrorKind;
Expand Down
10 changes: 10 additions & 0 deletions espflash/src/flasher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,16 @@ impl Flasher {
Ok(())
}

/// Get MD5 of region
pub fn checksum_md5(&mut self, addr: u32, length: u32) -> Result<u128, Error> {
self.connection
SergioGasquez marked this conversation as resolved.
Show resolved Hide resolved
.command(crate::command::Command::FlashMd5 {
offset: addr,
size: length,
})?
.try_into()
}

/// Load an ELF image to flash and execute it
pub fn load_elf_to_flash(
&mut self,
Expand Down