This is an automated email from the ASF dual-hosted git repository.

jerzy pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-core.git

commit 453498d220635b0cb8fdb1de42fc0020ffd432ea
Author: Wiktor Kwiatkowski <[email protected]>
AuthorDate: Tue Oct 7 09:24:06 2025 +0200

    hw/mcu/nxp/lpc55xx: fix crash when reading erased flash
    
    The code first attempts to read flash with FLASH_Read. If the read
    fails due to an erased area, it verifies the region with
    FLASH_VerifyErase using aligned addresses.
    When the region is erased, the buffer is filled with 0xFF.
    This prevents hard faults when reading erased memory.
---
 hw/mcu/nxp/lpc55xx/src/hal_flash.c | 26 ++++++++++++++++++++------
 1 file changed, 20 insertions(+), 6 deletions(-)

diff --git a/hw/mcu/nxp/lpc55xx/src/hal_flash.c 
b/hw/mcu/nxp/lpc55xx/src/hal_flash.c
index a330d56eb..8c0e60212 100644
--- a/hw/mcu/nxp/lpc55xx/src/hal_flash.c
+++ b/hw/mcu/nxp/lpc55xx/src/hal_flash.c
@@ -30,6 +30,8 @@
 
 #include <fsl_iap.h>
 
+#define ROUND_DOWN(a, n) (((a) / (n)) * (n))
+
 /*
  * Alignment restriction on writes.
  */
@@ -68,14 +70,26 @@ mcux_flash_read(const struct hal_flash *dev,
                 void *dst,
                 uint32_t num_bytes)
 {
-    status_t status = FLASH_VerifyErase(&mcux_config, address, num_bytes);
-    /* If flash is erased memcpy will result in hard fault, just fill 0xFF */
+    status_t status;
+
+    status = FLASH_Read(&mcux_config, address, dst, num_bytes);
     if (status == kStatus_FLASH_Success) {
-        memset(dst, 0xFF, num_bytes);
-    } else {
-        memcpy(dst, (void *)address, num_bytes);
+        return 0;
     }
-    return 0;
+
+    if (status == kStatus_FLASH_EccError) {
+        status = FLASH_VerifyErase(&mcux_config, ROUND_DOWN(address, 4),
+                                   ROUND_DOWN(address + num_bytes + 3, 4) -
+                                       ROUND_DOWN(address, 4));
+        /* If flash is erased memcpy will result in hard fault, just fill 0xFF 
*/
+        if (status == kStatus_FLASH_Success) {
+            memset(dst, 0xFF, num_bytes);
+            return 0;
+        } else {
+            return -2;
+        }
+    }
+    return -1;
 }
 
 static int

Reply via email to