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

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


The following commit(s) were added to refs/heads/master by this push:
     new cd8e3e18a8f fs/file: add reference count protection for 
stack-allocated file structures
cd8e3e18a8f is described below

commit cd8e3e18a8fcbb70beee166771b22a86341e8356
Author: dongjiuzhu1 <[email protected]>
AuthorDate: Thu Oct 9 20:26:02 2025 +0800

    fs/file: add reference count protection for stack-allocated file structures
    
    Issue:
    When using a stack-allocated file structure, the sequence:
    1. file_open() initializes the stack file structure
    2. file_mmap() creates memory mapping and increments reference count
    3. file_munmap() decrements reference count and may free the file structure
    4. file_close() attempts to close already freed structure → crash
    
    Root cause:
    The memory mapping operations (fs_reffilep/fs_putfilep) manage reference 
counts
    independently and can free the stack-allocated file structure prematurely.
    
    Solution:
    - Add reference count protection during file_open() for stack-allocated 
files
    - Clear reference count appropriately during file_close()
    - This ensures the file structure remains valid throughout its lifetime
    
    Signed-off-by: dongjiuzhu1 <[email protected]>
---
 fs/vfs/fs_open.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/fs/vfs/fs_open.c b/fs/vfs/fs_open.c
index 84fd3f251bc..bab898463bf 100644
--- a/fs/vfs/fs_open.c
+++ b/fs/vfs/fs_open.c
@@ -373,6 +373,11 @@ int file_open(FAR struct file *filep, FAR const char 
*path, int oflags, ...)
   ret = file_vopen(filep, path, oflags, 0, ap);
   va_end(ap);
 
+  if (ret >= OK)
+    {
+      atomic_fetch_add(&filep->f_refs, 1);
+    }
+
   return ret;
 }
 

Reply via email to