xiaoxiang781216 commented on code in PR #16326: URL: https://github.com/apache/nuttx/pull/16326#discussion_r2075885368
########## fs/inode/fs_files.c: ########## @@ -317,11 +331,36 @@ static int nx_dup3_from_tcb(FAR struct tcb_s *tcb, int fd1, int fd2, return -EBADF; } + /* dup3() and dup2() dictate that fd2 must be closed prior to reuse */ + + filep = files_fget(list, fd2); + if (filep) + { + /* The file exists and is open, close it here */ + + fs_putfilep(filep); + file_close_wait(filep); + } + + /* This should not fail now */ + filep = files_fget_by_index(list, fd2 / CONFIG_NFILE_DESCRIPTORS_PER_BLOCK, fd2 % CONFIG_NFILE_DESCRIPTORS_PER_BLOCK, &new); + /* If return value is NULL, it means the file is partially open. This means + * the userspace is racing against itself. To prevent the kernel from + * crashing due to access to invalid file pointer, just make the user try Review Comment: but the spec require that open/close is atomic(https://man7.org/linux/man-pages/man2/dup.2.html): ``` If the file descriptor newfd was previously open, it is closed before being reused; the close is performed silently (i.e., any errors during the close are not reported by dup2()). The steps of closing and reusing the file descriptor newfd are performed atomically. This is important, because trying to implement equivalent functionality using [close(2)](https://man7.org/linux/man-pages/man2/close.2.html) and dup() would be subject to race conditions, whereby newfd might be reused between the two steps. Such reuse could happen because the main program is interrupted by a signal handler that allocates a file descriptor, or because a parallel thread allocates a file descriptor. ``` and shouldn't return the error code(e.g. -EBUSY) in this case. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: commits-unsubscr...@nuttx.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org