5151#include <os/os_malloc.h>
5252
5353#include <bootutil/image.h>
54+ #include <bootutil/bootutil.h>
5455
5556#include "boot_serial/boot_serial.h"
5657#include "boot_serial_priv.h"
@@ -312,11 +313,17 @@ bs_upload(char *buf, int len)
312313 rc = 0 ;
313314 goto out ;
314315 }
315- if (curr_off + img_blen < img_size ) {
316- rem_bytes = img_blen % flash_area_align (fap );
317- if (rem_bytes ) {
318- img_blen -= rem_bytes ;
319- }
316+
317+ if (curr_off + img_blen > img_size ) {
318+ rc = MGMT_ERR_EINVAL ;
319+ goto out ;
320+ }
321+
322+ rem_bytes = img_blen % flash_area_align (fap );
323+
324+ if ((curr_off + img_blen < img_size ) && rem_bytes ) {
325+ img_blen -= rem_bytes ;
326+ rem_bytes = 0 ;
320327 }
321328
322329#ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
@@ -337,7 +344,32 @@ bs_upload(char *buf, int len)
337344#endif
338345
339346 BOOT_LOG_INF ("Writing at 0x%x until 0x%x" , curr_off , curr_off + img_blen );
340- rc = flash_area_write (fap , curr_off , img_data , img_blen );
347+ if (rem_bytes ) {
348+ /* the last chunk of the image might be unaligned */
349+ uint8_t wbs_aligned [BOOT_MAX_ALIGN ];
350+ size_t w_size = img_blen - rem_bytes ;
351+
352+ if (w_size ) {
353+ rc = flash_area_write (fap , curr_off , img_data , w_size );
354+ if (rc ) {
355+ goto out_invalid_data ;
356+ }
357+ curr_off += w_size ;
358+ img_blen -= w_size ;
359+ img_data += w_size ;
360+ }
361+
362+ if (img_blen ) {
363+ memcpy (wbs_aligned , img_data , rem_bytes );
364+ memset (wbs_aligned + rem_bytes , flash_area_erased_val (fap ),
365+ sizeof (wbs_aligned ) - rem_bytes );
366+ rc = flash_area_write (fap , curr_off , wbs_aligned , flash_area_align (fap ));
367+ }
368+
369+ } else {
370+ rc = flash_area_write (fap , curr_off , img_data , img_blen );
371+ }
372+
341373 if (rc == 0 ) {
342374 curr_off += img_blen ;
343375#ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
0 commit comments