From abe70c37a2cafbe072d3890d65a0ec771dd035df Mon Sep 17 00:00:00 2001 From: wangzhi16 Date: Thu, 22 May 2025 19:36:29 +0800 Subject: [PATCH] libc/shmfs: Ensure uniqueness of memfd. Use mktemp to create unique path for memfd, so other thread can't find file by path. If don't do this, error will ocurr in this case: thread 1: thread2: open() -- refs = 1 open() -- refs = 2 unlink() unlink() thread1 and thread2 will map one buffer by using file path but not fd or address of buffer. Signed-off-by: wangzhi16 --- libs/libc/misc/lib_memfd.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/libs/libc/misc/lib_memfd.c b/libs/libc/misc/lib_memfd.c index 9b45d2a22e5..050e6938a9a 100644 --- a/libs/libc/misc/lib_memfd.c +++ b/libs/libc/misc/lib_memfd.c @@ -43,7 +43,7 @@ # define LIBC_MEM_FD_VFS_PATH CONFIG_LIBC_MEM_FD_VFS_PATH #endif -#define LIBC_MEM_FD_VFS_PATH_FMT LIBC_MEM_FD_VFS_PATH "/%s" +#define LIBC_MEM_FD_VFS_PATH_FMT LIBC_MEM_FD_VFS_PATH "/%sXXXXXX" /**************************************************************************** * Public Functions @@ -65,22 +65,30 @@ int memfd_create(FAR const char *name, unsigned int flags) return -1; } +retry: snprintf(path, PATH_MAX, LIBC_MEM_FD_VFS_PATH_FMT, name); + mktemp(path); + # ifdef CONFIG_LIBC_MEMFD_SHMFS - ret = shm_open(path, O_RDWR | flags, 0660); + ret = shm_open(path, O_RDWR | O_EXCL | flags, 0660); if (ret >= 0) { shm_unlink(path); } # else mkdir(LIBC_MEM_FD_VFS_PATH, 0666); - ret = open(path, O_RDWR | flags, 0660); + ret = open(path, O_RDWR | O_EXCL | flags, 0660); if (ret >= 0) { unlink(path); } # endif + if (ret < 0 && get_errno() == EEXIST) + { + goto retry; + } + lib_put_pathbuffer(path); return ret; #endif