Skip to content

Commit 473701c

Browse files
authored
Fix write-bin for files whose lengths are not divisible by 4 by padding FF bytes (#780)
* Fix write-bin for files whose lengths are not divisible by 4 by pading FF bytes * changelog
1 parent 7e96628 commit 473701c

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2020
- Normalized arguments of the CLI commands (#759)
2121
- `board-info` now prints `Security information`. (#758)
2222
- The `command`, `elf` and `error` modules are no longer public (#772)
23+
- `write-bin` now works for files whose lengths are not divisible by 4 (#780)
2324

2425
### Fixed
2526

espflash/src/bin/espflash.rs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::{
2-
fs::{self, File},
3-
io::Read,
2+
fs::{self, File, OpenOptions},
3+
io::{Read, Seek, SeekFrom, Write},
44
path::PathBuf,
55
};
66

@@ -342,11 +342,35 @@ fn save_image(args: SaveImageArgs, config: &Config) -> Result<()> {
342342
Ok(())
343343
}
344344

345+
fn pad_to(file: &mut File, alignment: u64, pad_character: u8) -> Result<()> {
346+
let current_size = file.metadata().into_diagnostic()?.len();
347+
let pad_mod = current_size % alignment;
348+
349+
if pad_mod != 0 {
350+
let pad_size = alignment - pad_mod;
351+
352+
// Move the file cursor to the end of the file
353+
file.seek(SeekFrom::End(0)).into_diagnostic()?;
354+
355+
file.write_all(&vec![pad_character; pad_size as usize])
356+
.into_diagnostic()?;
357+
}
358+
359+
Ok(())
360+
}
361+
345362
fn write_bin(args: WriteBinArgs, config: &Config) -> Result<()> {
346363
let mut flasher = connect(&args.connect_args, config, false, false)?;
347364
print_board_info(&mut flasher)?;
348365

349-
let mut f = File::open(&args.file).into_diagnostic()?;
366+
// if the file size is not divisible by 4, we need to pad FF bytes to the end of
367+
// the file, that's why we need `write` permission as well
368+
let mut f = OpenOptions::new()
369+
.read(true)
370+
.write(true)
371+
.open(&args.file)
372+
.into_diagnostic()?;
373+
pad_to(&mut f, 4, 0xFF)?;
350374
let size = f.metadata().into_diagnostic()?.len();
351375
let mut buffer = Vec::with_capacity(size.try_into().into_diagnostic()?);
352376
f.read_to_end(&mut buffer).into_diagnostic()?;

0 commit comments

Comments
 (0)