Repository navigation
Conversation
The three checks on reading the image and swap sizes in boot_swap_image() used the C library assert(). These checks depend on what is in flash, so a bad flash state can trip them. Switch them to ASSERT(), which every port maps to its normal assert handler, so behaviour on targets is unchanged. In the simulator, ASSERT() goes through sim_assert(), so a test that catches asserts can report a failure here instead of aborting the whole test process. The NULL check on the status flash area stays a plain assert(): it is a programming invariant, and continuing past it would only crash. Assisted-by: Claude:opus-5.5 Signed-off-by: David Brown <david.brown@linaro.org>
The simulator's power-loss testing interrupts boot_go between whole flash operations: when the flash counter expires, flash_area_write aborts before writing anything. Every simulated power cut is therefore write-atomic, so states left by a write torn partway through, such as a partially written trailer magic reading back as BOOT_MAGIC_BAD, are unreachable. That is why the revert interruption tests did not catch issue mcu-tools#1966: power loss inside boot_write_magic during swap-move revert fixup left a bad magic that matched no swap table row and bricked the device. Add a torn-write mode to the flash counter: on expiry the interrupted write programs all but the last byte of its payload before the simulated power loss. Write alignment is a driver interface requirement, not a power-fail atomicity guarantee, so the tear point falls inside the final write unit regardless of max-align. The simulated flash marks torn bytes as retryable: one subsequent write of the same values is allowed, since recovery replays the interrupted operation, while the write-once discipline stays enforced everywhere else. Add run_revert_with_torn_writes, a revert-only sweep: perform a test upgrade, count the flash operations of an uninterrupted revert, then for each operation clone the post-upgrade state, tear that write during revert, and verify the device recovers to the original image with clean trailers. Gated to swap-using-move. With the fix from commit 4f39356 ("bootutil: Fix device brick after power failure during swap-move revert") reverted, the new test fails at the fixup_revert magic write, including under max-align-32, while the existing whole-operation revert_with_fails sweep still passes; on current code both pass. Signed-off-by: Neil Berkman <neil@xuku.com> Signed-off-by: David Brown <david.brown@linaro.org>
The revert interruption sweeps cut power once per run. Some failures need a second power loss in the boot that resumes the revert, and neither revert_with_fails nor revert_with_torn_writes can reach them. Add run_revert_with_double_fails(). It cuts power at each flash operation of the boot that starts a revert, then again within the first 16 operations of the boot that resumes it, and checks that the following boot completes the revert without asserts. Run it twice: once with clean cuts, and once using the torn-write mode added by Neil Berkman in the previous commit (from PR mcu-tools#2648), so that each interrupted write is left partly programmed. On current main this fails for swap-using-offset in both modes: a resumed revert re-runs fixup_revert() and leaves the secondary magic good, so the next boot restarts the revert on a half-swapped primary slot. With torn writes it also fails for swap-using-move and swap-using-offset when the fixup's magic write is torn, which loses the revert. The test is gated behind MCUBOOT_RUN_SLOW_TESTS. Assisted-by: Claude:opus-5.5 Signed-off-by: David Brown <david.brown@linaro.org>
fixup_revert() protects the start of a revert by writing a trailer in the secondary slot that makes the revert restartable. Two cases left it unprotected. The fixup was only redone when the secondary magic read as unset. A power loss while writing that magic leaves it reading as bad, so the next boot skipped the fixup and went on to erase the primary trailer. A second power loss then left neither slot with a usable trailer, and the unconfirmed image booted permanently. Redo the fixup whenever the magic is not good, in both swap-using-move and swap-using-offset. In swap-using-offset the fixup ran whenever the status index was 0. Unlike swap-using-move, swap-using-offset has two states per index, so a revert resumed after its first step ran the fixup again. That wrote a good secondary magic which swap_run() erased right after; a power loss between the two made the next boot ignore the recorded progress and restart the revert on a half-swapped primary slot, which failed on every boot. Only run the fixup when no status has been written, using boot_status_is_reset() as swap_run() already does. Both cases are caught by the double-interruption revert test in the simulator. Fixes: mcu-tools#3009 Fixes: mcu-tools#3010 Assisted-by: Claude:opus-5.5 Signed-off-by: David Brown <david.brown@linaro.org>
nordicjm
approved these changes
Nov 24, 2026
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Copilot review overview
5 open issues
write_torn()currently panics on any non-erased byte whenverify_writesis enabled, even if the… · New Addingwrite_torn()as a required trait method is an API-breaking change for allFlash… · New This sweep runs boots withcatch_assertsset tofalse. If anyASSERT()/assert triggers in… · New This sweep runs boots withcatch_assertsset tofalse. If anyASSERT()/assert triggers in… · New This sweep runs boots withcatch_assertsset tofalse. If anyASSERT()/assert triggers in… · New
What changed in this PR
This PR improves MCUBoot’s resilience to repeated power loss during a revert (including torn write scenarios) and adds simulator coverage to reproduce and prevent regressions for the reported revert/fixup failure modes.
Changes:
- Add simulator support for “torn” interrupted writes and new revert interruption sweeps (single and double interruption).
- Update revert fixup logic for swap-move and swap-offset to handle torn magic writes and avoid incorrect re-running of fixup.
- Make specific boot swap size checks use
ASSERT()so simulator can catch failures without aborting the whole process.
| File | Description |
|---|---|
| sim/tests/core.rs | Registers new simulator tests for torn-write and double-interruption revert sweeps. |
| sim/src/lib.rs | Adds the torn-write revert sweep to the simulator run list. |
| sim/src/image.rs | Implements torn-write revert sweep and the new double-interruption revert sweep logic. |
| sim/simflash/src/lib.rs | Extends flash trait with write_torn, implements torn-write behavior, and adds unit tests. |
| sim/mcuboot-sys/src/c.rs | Adds boot_go_torn() plumbing into the simulator boot invocation. |
| sim/mcuboot-sys/src/api.rs | Extends the simulator context and exports sim_flash_write_torn() FFI hook. |
| sim/mcuboot-sys/csupport/run.c | Implements torn-write behavior on the interruption point in flash_area_write. |
| docs/release-notes.d/swap-revert-fixup-power-loss.md | Adds release note for the revert fixup power-loss resilience fix. |
| docs/release-notes.d/sim-torn-writes.md | Adds release note for simulator torn-write mode and sweep. |
| docs/release-notes.d/sim-revert-double-fails.md | Adds release note for the double-interruption revert sweep. |
| boot/bootutil/src/swap_offset.c | Fixes swap-offset revert fixup gating and retries fixup on bad magic (not just unset). |
| boot/bootutil/src/swap_move.c | Retries revert fixup unless secondary magic is confirmed good. |
| boot/bootutil/src/loader.c | Switches key asserts to ASSERT() so simulator can catch them as test failures. |
Review effort: Lite
Comment on lines
+242
to
265
| fn write_torn(&mut self, offset: usize, payload: &[u8]) -> Result<()> { | ||
| if offset + payload.len() > self.data.len() { | ||
| panic!("Write outside of device"); | ||
| } | ||
|
|
||
| // Verify the alignment (which must be a power of two). | ||
| if offset & (self.align - 1) != 0 { | ||
| panic!("Misaligned write address"); | ||
| } | ||
|
|
||
| for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() { | ||
| if self.verify_writes && !(*x) { | ||
| panic!("Write to unerased location at 0x{:x}", offset + i); | ||
| panic!("Torn write to unerased location at 0x{:x}", offset + i); | ||
| } | ||
| *x = false; | ||
| } | ||
|
|
||
| for x in &mut self.retryable[offset .. offset + payload.len()] { | ||
| *x = true; | ||
| } | ||
|
|
||
| let sub = &mut self.data[offset .. offset + payload.len()]; | ||
| sub.copy_from_slice(payload); | ||
| Ok(()) |
Comment on lines
54
to
58
| pub trait Flash { | ||
| fn erase(&mut self, offset: usize, len: usize) -> Result<()>; | ||
| fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()>; | ||
| fn write_torn(&mut self, offset: usize, payload: &[u8]) -> Result<()>; | ||
| fn read(&self, offset: usize, data: &mut [u8]) -> Result<()>; |
Comment on lines
+1110
to
+1114
| if !c::boot_go(&mut upgraded, &self.areadesc, None, None, | ||
| false).success() { | ||
| error!("Failed upgrade before torn-write revert"); | ||
| return true; | ||
| } |
Comment on lines
+1123
to
+1127
| if !c::boot_go(&mut clean, &self.areadesc, Some(&mut counter), None, | ||
| false).success() { | ||
| error!("Failed uninterrupted revert"); | ||
| return true; | ||
| } |
Comment on lines
+1140
to
+1145
| if !c::boot_go(&mut flash, &self.areadesc, None, None, | ||
| false).success() { | ||
| warn!("Should have finished revert after torn write at {}", | ||
| stop); | ||
| fails += 1; | ||
| } |
Copilot stopped reviewing on behalf of
d3zd3z due to an error
November 24, 2026 18:02
|
Thanks for the quick fix! |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Two revert bugs in
fixup_revert()can each be triggered by a pair of power losses during a revert. One loses the revert, so the unconfirmed image keeps booting (#3009). The other leaves a swap-using-offset device stuck in an assert on every boot (#3010). This PR adds simulator coverage that reproduces both, then fixes them.Commits
ASSERT()maps to the normal assert on every port, so targets are unchanged, but the simulator can catch it and report a test failure instead of aborting the whole test process.MCUBOOT_RUN_SLOW_TESTS.boot_status_is_reset()). Swap-offset has two states per index, so checking the index alone let a resumed revert re-run the fixup (swap-using-offset: revert fixup re-run on resume leaves the device unbootable (assert in boot_swap_image) #3010).Test results
Results of the new double-interruption sweep before and after the fix commit:
The existing
revert_with_failsand the torn-write sweep from #2648 pass throughout. The regular suite also passes for default, swap-move, swap-offset, both withmax-align-32, both with multiimage, and the RSA-encrypted swap-move and swap-offset CI combinations.The new sweep is slow: about 100 s for swap-move and about 8 minutes for swap-scratch, per feature combination, which is why it is gated.
This takes over the simulator part of #2648; that PR's CI canary commit is not included.