Repository navigation
ravedude: refuse to flash firmware that overlaps the bootloader - #715
Conversation
The linked firmware was handed to avrdude without checking whether it fits below the board's bootloader. On boards with an Optiboot bootloader this silently overwrites the bootloader when the image grows past the application region, which leaves the board unprogrammable over USB until it is recovered with an ISP programmer. Measure the flash footprint from the ELF program headers (avrdude writes each PT_LOAD segment at its physical address, so the highest flash-resident segment end is the image size) and refuse to flash when it exceeds the limit declared by the board. Boards without a known limit keep the previous behaviour. Fixes Rahix#709.
Arduino's board definition reserves the same 2 KiB for the new and the old Nano bootloader, so 32256 would have allowed images that still overwrite the bootloader.
Rahix
left a comment
There was a problem hiding this comment.
Hi, thanks a lot for picking up the topic and submitting this PR!
I have reviewed your code and left comments, please check below.
Another thing: I assume you had LLM help in your submission text and that is the reason it is so long and detailed. If not, please don't take this personal.
Adding details can be nice, but this wall of text really is an overload. My time is limited, but as a maintainer I have to read through all of it to make sure I don't miss anything important. Almost everything in your submission text was already discussed in the linked issue. Mentioning all this again drowns out the parts that actually matter.
Try to be more brief and only mention the important details about your implementation that might not be obvious from context or reading the code.
| } | ||
|
|
||
| /// Refuses to flash an image that would overlap the bootloader region. | ||
| pub fn check_application_size(path: &Path, limit: u32, board: &str) -> anyhow::Result<()> { |
There was a problem hiding this comment.
This function is the entry point of the module and the only public API so please put it at the very top of the file.
| /// Refuses to flash an image that would overlap the bootloader region. | ||
| pub fn check_application_size(path: &Path, limit: u32, board: &str) -> anyhow::Result<()> { | ||
| let Some(size) = image_size(path)? else { | ||
| return Ok(()); |
There was a problem hiding this comment.
Silently skipping the size-check is not a good idea. But as per other comments, reading the image size cannot yield a non-supported filetype because ravedude only supports ELF binaries.
| return Err(anyhow!( | ||
| "firmware is {size} bytes, but board `{board}` allows at most {limit} bytes (bootloader region)" | ||
| )); |
There was a problem hiding this comment.
don't pass the board name to check_application_size just to display it in the error message. it is visible in the console output anyway.
also, the error message should reference the relevant config for easier troubleshooting. i would suggest:
firmware is too big (0x{size:x} bytes)!
board max-application-size=0x{limit:x} to not overwrite the bootloader
| /// Returns the number of bytes the firmware will occupy in flash, or `None` | ||
| /// if the file format does not allow a reliable size to be derived. | ||
| /// | ||
| /// ELF images are measured from their loadable segments: avrdude programs each | ||
| /// `PT_LOAD` segment at its physical address, so the end of the highest | ||
| /// flash-resident segment is the amount of flash that gets written. | ||
| pub fn image_size(path: &Path) -> anyhow::Result<Option<u64>> { |
There was a problem hiding this comment.
A few notes on this function:
I find it convoluted to place an entire ELF header parser into a function that also handles raw binaries. Really, you are missing a layer of abstraction here.
That said, ravedude only supports ELF binaries anyway, so the whole complexity for .bin handling can be avoided entirely:
avr-hal/ravedude/src/avrdude/mod.rs
Lines 175 to 177 in 0bbec46
So I would change it to
fn read_elf_flash_size(file: &mut File) -> anyhow::Result<u32> {
}(u32 is plenty since we only parse 32 bit ELF files anyway)
Pass it a File because this makes error handling cleaner. The inner errors do not reference the filename, but in the callsite you do a single .with_context(|| format!("failed reading flash size of {filename} binary"))
| let mut highest_end = 0u64; | ||
| for index in 0..usize::from(phnum) { | ||
| let offset = index * usize::from(phentsize); | ||
| let entry = &table[offset..offset + ELF_PROGRAM_HEADER_LEN]; | ||
| if read_u32(entry, 0) != PT_LOAD { | ||
| continue; | ||
| } | ||
| let paddr = u64::from(read_u32(entry, 12)); | ||
| let filesz = u64::from(read_u32(entry, 16)); | ||
| if filesz == 0 || paddr >= AVR_DATA_SPACE_START { | ||
| continue; | ||
| } | ||
| highest_end = highest_end.max(paddr + filesz); | ||
| } |
There was a problem hiding this comment.
Lends itself nicely to an iterator instead:
(..phnum)
.filter_map(|i| {
// ...
if filesz == 0 || paddr >= AVR_DATA_SPACE_START {
None
} else {
Some(paddr + filesz)
}
})
.max()| use std::io::{self, Read, Seek, SeekFrom}; | ||
| use std::path::Path; | ||
|
|
||
| use anyhow::{Context as _, anyhow, bail}; |
There was a problem hiding this comment.
Please only
use anyhow::Context as _;
and refer to the macros explicitly as anyhow::anyhow!() and anyhow::bail!()
| //! # Maximum size of the application image in bytes. ravedude measures the | ||
| //! # linked firmware and refuses to flash it if it would overlap the bootloader. | ||
| //! # Omit this option to disable the check. | ||
| //! # max-application-size = 32256 |
There was a problem hiding this comment.
Please keep this more brief:
# Maximum size of the application image in bytes (so it won't overwrite the bootloader)
# max-application-size = 32256| ### Added | ||
| - Added the `board.max-application-size` option and populated it for the | ||
| built-in boards. Firmware that would overlap the bootloader region is now | ||
| rejected before flashing instead of bricking the board ([#709]). |
There was a problem hiding this comment.
Please don't update the changelog yourself, I will take care of that once merged. Otherwise, we will often run into unnecessary merge conflicts in this file when other PRs get merged first.
| # Maximum size of the application image in bytes. ravedude measures the | ||
| # linked firmware and refuses to flash it if it would overlap the bootloader. | ||
| # Omit this option to disable the check. | ||
| # max-application-size = 32256 |
There was a problem hiding this comment.
Drop comment and make the option not commented out.
Parse only ELF images, which are the only format ravedude supports, and validate the ELF class, byte order, version, and machine instead of silently skipping unknown files. Use the elf.h field names for the offsets, keep the public entry point at the top of the module, and report the limit the same way the configuration spells it. Also drop the changelog entry; release notes are maintained separately.
|
Thanks for the review — all points are addressed in 7858282:
Rebuilt and re-ran: 17 tests pass, and the A/B still shows the base commit accepting the oversized image while this branch rejects it. I also cut the PR description down — you were right that most of it repeated the issue. |
What
ravedudenow refuses to flash firmware that would extend into the bootloaderregion. Board definitions gain an optional
max-application-size, populated forthe built-in boards from Arduino's
upload.maximum_size.The size is the end of the highest
PT_LOADsegment below0x800000; emptysegments and segments in the data address space are skipped. Only ELF images
are parsed, which is the format ravedude already hands to avrdude.
Why
Fixes #709.
Reproduction
A 31,008-byte image on
nano(application limit 30,720):The reproduction used real binaries from the base commit and from this branch,
with stub
avrdude/avr-gcconPATH, so no hardware was involved.Root cause
The linker only knows the MCU's total flash size, and
avrdudewrites the ELFsegments without any board model.
ravedudeis the only component that has theboard definition, but it did not look at the image size at all.
Verification
cargo test --manifest-path ravedude/Cargo.toml: 17 passed, on twoconsecutive runs. The tests cover the highest-segment calculation, data-space
and empty segments, the exact limit, and rejection of non-AVR/invalid ELF and
truncated program header tables.
branch exits 1 before invoking
avrdude.cargo fmt --checkis clean;cargo clippy --all-targetsreports onlypre-existing findings outside this change.
Risk
max-application-sizeare unaffected.bootloader can override the value in
Ravedude.toml.being passed to avrdude.