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

GUIDINGLI pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit 64cc386be25dbb6b36a43ead8b61e47c4c1c8e85
Author: pangzhen1 <[email protected]>
AuthorDate: Wed Aug 19 18:42:53 2026 +0800

    mtd: filemtd: check file_read() return to prevent stack canary corruption
    
    filemtd_write() assigns the return value of file_read() to the int
    variables buflen and remain without validation. When the underlying
    file becomes invalid during umount, file_read() (via file_readv())
    returns a negative errno (-EBADF = -9), leaving buflen/remain negative.
    
    Because the loop guards use equality with zero (if (buflen == 0) and
    if (remain == 0)), a negative value never satisfies either guard:
    pout is never reset and the write-back path is never taken, so the
    pointer advances past the 128-byte stack buffer and overwrites the
    stack canary stored above it, triggering __stack_chk_fail.
    
    Signed-off-by: pangzhen1 <[email protected]>
    Signed-off-by: jingfei <[email protected]>
---
 drivers/mtd/filemtd.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/drivers/mtd/filemtd.c b/drivers/mtd/filemtd.c
index f0f9556716e..6e3f3bb16c1 100644
--- a/drivers/mtd/filemtd.c
+++ b/drivers/mtd/filemtd.c
@@ -208,6 +208,16 @@ static ssize_t filemtd_write(FAR struct file_dev_s *priv, 
size_t offset,
 
           file_seek(&priv->mtdfile, seekpos, SEEK_SET);
           buflen = file_read(&priv->mtdfile, buf, MIN(len, sizeof(buf)));
+
+          /* A negative errno or EOF must not reach the guards below,
+           * which would let pout run past buf[] and corrupt the stack.
+           */
+
+          if (buflen <= 0)
+            {
+              return buflen < 0 ? buflen : -EIO;
+            }
+
           pout   = (FAR uint8_t *)buf;
           remain = buflen;
         }

Reply via email to