From d280262028c6f81e8d3bdeab0bce30ba5eafde81 Mon Sep 17 00:00:00 2001 From: Daniele Lacamera Date: Tue, 9 Jun 2026 09:19:02 +0200 Subject: [PATCH] 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. --- hal/imx_rt.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/hal/imx_rt.c b/hal/imx_rt.c index b89d93f2..dc5a62fd 100644 --- a/hal/imx_rt.c +++ b/hal/imx_rt.c @@ -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,