Skip to content

Commit fbd2267

Browse files
taltenbachnordicjm
authored andcommitted
boot: bootutil: Fix invalid last sector computation for swap-scratch
At the beginning of a swap-scratch upgrade, the index of the last sector in the primary slot that need to be swapped is computed using the 'find_last_sector_idx' routine. However, if the primary slot is composed of larger sectors than the secondary slots, this routine could return a wrong sector index for the primary slot. The index might even be outside the primary slot, which would lead to (at best) a simple failure of the upgrade and at worst a corruption of the flash memory bricking the device. This commit fixes the issue by ensuring 'find_last_sector_idx' always returns a valid sector index for the primary slot. Signed-off-by: Thomas Altenbach <[email protected]>
1 parent 7724bcf commit fbd2267

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

boot/bootutil/src/swap_scratch.c

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -464,13 +464,15 @@ boot_copy_sz(const struct boot_loader_state *state, int last_sector_idx,
464464
static int
465465
find_last_sector_idx(const struct boot_loader_state *state, uint32_t copy_size)
466466
{
467-
int last_sector_idx;
467+
int last_sector_idx_primary;
468+
int last_sector_idx_secondary;
468469
uint32_t primary_slot_size;
469470
uint32_t secondary_slot_size;
470471

471472
primary_slot_size = 0;
472473
secondary_slot_size = 0;
473-
last_sector_idx = 0;
474+
last_sector_idx_primary = 0;
475+
last_sector_idx_secondary = 0;
474476

475477
/*
476478
* Knowing the size of the largest image between both slots, here we
@@ -483,23 +485,24 @@ find_last_sector_idx(const struct boot_loader_state *state, uint32_t copy_size)
483485
(primary_slot_size < secondary_slot_size)) {
484486
primary_slot_size += boot_img_sector_size(state,
485487
BOOT_PRIMARY_SLOT,
486-
last_sector_idx);
488+
last_sector_idx_primary);
489+
++last_sector_idx_primary;
487490
}
488491
if ((secondary_slot_size < copy_size) ||
489492
(secondary_slot_size < primary_slot_size)) {
490493
secondary_slot_size += boot_img_sector_size(state,
491494
BOOT_SECONDARY_SLOT,
492-
last_sector_idx);
495+
last_sector_idx_secondary);
496+
++last_sector_idx_secondary;
493497
}
494498
if (primary_slot_size >= copy_size &&
495499
secondary_slot_size >= copy_size &&
496500
primary_slot_size == secondary_slot_size) {
497501
break;
498502
}
499-
last_sector_idx++;
500503
}
501504

502-
return last_sector_idx;
505+
return last_sector_idx_primary - 1;
503506
}
504507

505508
/**

0 commit comments

Comments
 (0)