@@ -816,6 +816,35 @@ swap_run(struct boot_loader_state *state, struct boot_status *bs,
816816}
817817#endif /* !MCUBOOT_OVERWRITE_ONLY */
818818
819+ static app_max_size_adjust_to_trailer (struct boot_loader_state * state , uint32_t slot ,
820+ size_t slot_size )
821+ {
822+ size_t slot_trailer_sz = boot_trailer_sz (BOOT_WRITE_SZ (state ));
823+ size_t slot_trailer_off = slot_size - slot_trailer_sz ;
824+
825+ /* If the trailer doesn't fit in the last sector of the primary or secondary slot, some padding
826+ * might have to be inserted between the end of the firmware image and the beginning of the
827+ * trailer to ensure there is enough space for the trailer in the scratch area when the last
828+ * sector of the secondary will be copied to the scratch area.
829+ *
830+ * The value of the padding depends on the amount of trailer data that is contained in the first
831+ * trailer containing part of the trailer in the primary and secondary slot.
832+ */
833+ size_t trailer_sector_end_off =
834+ get_first_trailer_sector_end_off (state , slot , slot_trailer_sz );
835+
836+ size_t trailer_sz_in_first_sector = trailer_sector_end_off - slot_trailer_off ;
837+
838+ size_t trailer_padding = 0 ;
839+ size_t scratch_trailer_sz = boot_scratch_trailer_sz (BOOT_WRITE_SZ (state ));
840+
841+ if (scratch_trailer_sz > trailer_sz_in_first_sector ) {
842+ trailer_padding = scratch_trailer_sz - trailer_sz_in_first_sector ;
843+ }
844+
845+ return slot_trailer_off - trailer_padding ;
846+ }
847+
819848int app_max_size (struct boot_loader_state * state )
820849{
821850 size_t num_sectors_primary ;
@@ -893,7 +922,14 @@ int app_max_size(struct boot_loader_state *state)
893922#ifdef MCUBOOT_OVERWRITE_ONLY
894923 return (sz1 < sz0 ? sz1 : sz0 );
895924#else
896- return (secondary_slot_sz < primary_slot_sz ? secondary_slot_sz : primary_slot_sz );
925+ size_t primary_max_app_sz = app_max_size_adjust_to_trailer (state ,
926+ BOOT_PRIMARY_SLOT ,
927+ primary_slot_sz );
928+ size_t secondary_max_app_sz = app_max_size_adjust_to_trailer (state ,
929+ BOOT_SECONDARY_SLOT ,
930+ secondary_slot_sz );
931+ return (primary_max_app_sz < secondary_max_app_sz ?
932+ primary_max_app_sz : secondary_max_app_sz );
897933#endif
898934}
899935#else
@@ -920,6 +956,14 @@ int app_max_size(struct boot_loader_state *state)
920956 secondary_sz = flash_area_get_size (fap );
921957
922958 return (secondary_sz < primary_sz ? secondary_sz : primary_sz );
959+ size_t primary_max_app_sz = app_max_size_adjust_to_trailer (state ,
960+ BOOT_PRIMARY_SLOT ,
961+ primary_sz );
962+ size_t secondary_max_app_sz = app_max_size_adjust_to_trailer (state ,
963+ BOOT_SECONDARY_SLOT ,
964+ secondary_sz );
965+ return (primary_max_app_sz < secondary_max_app_sz ?
966+ primary_max_app_sz : secondary_max_app_sz );
923967}
924968
925969#endif /* !MCUBOOT_DIRECT_XIP && !MCUBOOT_RAM_LOAD */
0 commit comments