F-5356: bound i.MX RT flash write copy to caller buffer length

hal_flash_write() programs one full CONFIG_FLASH_PAGE_SIZE (256/512 byte)
page per loop iteration but unconditionally memcpy'd a whole page out of
the caller's buffer regardless of len. Sub-page writes - notably the
1-byte trailer updates from set_trailer_at()/trailer_write() on the
non-NVM_FLASH_WRITEONCE i.MX RT configs - therefore overread the source
buffer (e.g. 255 bytes past a 1-byte stack value) and could program
adjacent stack/RAM contents into flash.

Bound the copy to min(page, len - i) and pad the rest of the page buffer
with the erased value (0xFF). 0xFF is a no-op for NOR programming, so the
existing flash contents of the rest of the page are preserved.
pull/791/head
Daniele Lacamera 2026-06-09 09:19:02 +02:00
parent 3bfd7de34d
commit d280262028
1 changed files with 10 additions and 1 deletions

View File

@ -936,7 +936,16 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len)
asm volatile("cpsid i");
int write_success = 0;
for (i = 0; i < len; i+= CONFIG_FLASH_PAGE_SIZE) {
memcpy(wbuf, data + i, CONFIG_FLASH_PAGE_SIZE);
/* The NOR program command always writes a full page. Bound the copy
* to the bytes actually provided by the caller so sub-page writes
* (e.g. the 1-byte trailer updates) do not overread the source buffer.
* Pad the remainder of the page with the erased value (0xFF), which is
* a no-op for NOR programming and preserves existing flash contents. */
int chunk = len - i;
if (chunk > (int)CONFIG_FLASH_PAGE_SIZE)
chunk = (int)CONFIG_FLASH_PAGE_SIZE;
memset(wbuf, 0xFF, sizeof(wbuf));
memcpy(wbuf, data + i, chunk);
status = g_bootloaderTree->flexSpiNorDriver->program(
CONFIG_FLASH_FLEXSPI_INSTANCE,
FLEXSPI_CONFIG,