Skip to content

ravedude: refuse to flash firmware that overlaps the bootloader - #715

Merged
Rahix merged 3 commits into
Rahix:mainfrom
CGIFM:fix/ravedude-max-application-size
Nov 9, 2026
Merged

Rahix merged 3 commits into
Rahix:mainfrom
CGIFM:fix/ravedude-max-application-size

Conversation

@CGIFM

@CGIFM CGIFM commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

What

ravedude now refuses to flash firmware that would extend into the bootloader
region. Board definitions gain an optional max-application-size, populated for
the built-in boards from Arduino's upload.maximum_size.

The size is the end of the highest PT_LOAD segment below 0x800000; empty
segments 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):

# before
       Board Arduino Nano
 Programming firmware.elf => COM1
  Programmed firmware.elf

# after
       Board Arduino Nano
Error: firmware is too big (0x7920 bytes)!
board max-application-size=0x7800 to not overwrite the bootloader

The reproduction used real binaries from the base commit and from this branch,
with stub avrdude/avr-gcc on PATH, so no hardware was involved.

Root cause

The linker only knows the MCU's total flash size, and avrdude writes the ELF
segments without any board model. ravedude is the only component that has the
board definition, but it did not look at the image size at all.

Verification

  • cargo test --manifest-path ravedude/Cargo.toml: 17 passed, on two
    consecutive 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.
  • A/B with the real binary: the base commit accepts the oversized image, this
    branch exits 1 before invoking avrdude.
  • cargo fmt --check is clean; cargo clippy --all-targets reports only
    pre-existing findings outside this change.

Risk

  • Boards without max-application-size are unaffected.
  • The built-in limits assume the stock bootloader; a board with a different
    bootloader can override the value in Ravedude.toml.
  • A binary that is not a supported AVR ELF now fails with an error instead of
    being passed to avrdude.

jlc added 2 commits November 6, 2026 13:40
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 Rahix left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread ravedude/src/firmware.rs Outdated
}

/// Refuses to flash an image that would overlap the bootloader region.
pub fn check_application_size(path: &Path, limit: u32, board: &str) -> anyhow::Result<()> {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread ravedude/src/firmware.rs Outdated
/// 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(());

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread ravedude/src/firmware.rs Outdated
Comment on lines +101 to +103
return Err(anyhow!(
"firmware is {size} bytes, but board `{board}` allows at most {limit} bytes (bootloader region)"
));

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread ravedude/src/firmware.rs Resolved
Comment thread ravedude/src/firmware.rs Outdated
Comment on lines +15 to +21
/// 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>> {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

let mut flash_instruction: std::ffi::OsString = "flash:w:".into();
flash_instruction.push(bin);
flash_instruction.push(":e");

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"))

Comment thread ravedude/src/firmware.rs Outdated
Comment on lines +77 to +90
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);
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Comment thread ravedude/src/firmware.rs Outdated
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;

use anyhow::{Context as _, anyhow, bail};

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please only

use anyhow::Context as _;

and refer to the macros explicitly as anyhow::anyhow!() and anyhow::bail!()

Comment thread ravedude/src/main.rs Outdated
Comment on lines +80 to +83
//! # 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

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please keep this more brief:

# Maximum size of the application image in bytes (so it won't overwrite the bootloader)
# max-application-size = 32256

Comment thread ravedude/CHANGELOG.md Outdated
Comment on lines +8 to +11
### 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]).

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread ravedude/README.md Outdated
Comment on lines +174 to +177
# 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

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@CGIFM

CGIFM commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review — all points are addressed in 7858282:

  • firmware.rs: public entry point moved to the top; only ELF is parsed (.bin/HEX paths and Option skipping removed); read_elf_flash_size(&mut File) -> Result<u32> with a single filename context at the callsite.
  • Header now validates class, data, version, and machine; phnum = 0, an invalid phentsize, an oversized table, and a truncated table are errors.
  • elf.h constants for the offsets, iterator + max(), u32::from_le_bytes(..try_into().unwrap()), no u64 checked-add dance.
  • Error message uses your suggested wording; the board name is no longer passed in.
  • README and main.rs examples shortened; the CHANGELOG entry is dropped.

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.

@Rahix
Rahix self-requested a review November 9, 2026 14:42

@Rahix Rahix left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks fine, thanks.

@Rahix
Rahix merged commit 3778111 into Rahix:main Nov 9, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ravedude: check firmware size against bootloader limit before flashing (oversized image bricked Nano with old bootloader)

2 participants