This is an automated email from the ASF dual-hosted git repository. xiaoxiang781216 pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/nuttx.git
commit 395e99ac35982719db8c5874e37aacad34cb63dc Author: pangzhen1 <[email protected]> AuthorDate: Fri Sep 18 19:27:55 2026 +0800 libc/stdio: fix freopen errno clobbered by fdsan on failed open When open() fails in freopen(), the fdsan owner-tag exchange ran before the fd<0 check; ioctl(-1) in the exchange set errno=EBADF and overwrote the real cause (ENOENT/EACCES/EISDIR/ENAMETOOLONG). Move the exchange after the fd<0 check so open's errno reaches the caller. Signed-off-by: pangzhen1 <[email protected]> --- libs/libc/stdio/lib_freopen.c | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/libs/libc/stdio/lib_freopen.c b/libs/libc/stdio/lib_freopen.c index 2b506d5ad03..c9096589b99 100644 --- a/libs/libc/stdio/lib_freopen.c +++ b/libs/libc/stdio/lib_freopen.c @@ -138,26 +138,28 @@ FAR FILE *freopen(FAR const char *path, FAR const char *mode, /* Open the new file and reused the fd */ fd = open(path, oflags, 0666); -#ifdef CONFIG_FDSAN - if (stream != stdin && stream != stdout && stream != stderr) - { - android_fdsan_exchange_owner_tag(fd, 0, - android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE, - (uintptr_t)stream)); - } - -#endif flockfile(stream); stream->fs_cookie = (FAR void *)(intptr_t)fd; funlockfile(stream); - /* To clear the stale fd */ + /* Return on open failure before fdsan exchange: ioctl(-1) would + * set errno=EBADF and clobber the real failure cause. + */ if (fd < 0) { return NULL; } +#ifdef CONFIG_FDSAN + if (stream != stdin && stream != stdout && stream != stderr) + { + android_fdsan_exchange_owner_tag(fd, 0, + android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE, + (uintptr_t)stream)); + } +#endif + clearerr(stream); return stream; }
