[PATCH 2/3] tools/nolibc: fix fopen() with the "rb+", "wb+" and "ab+" modes

From: Danish Khateeb

Date: Wed Oct 28 2026 - 16:08:41 EST


The C standard allows the '+' of an update mode to come before or after
the 'b', so "rb+" means the same as "r+b". fopen() only looks for the
'+' right after the first character, so it opens a file read-only in
"rb+" mode, and write-only in "wb+" and "ab+" modes. Writing to such a
stream, or reading from it, then fails with EBADF.

Look for the '+' anywhere in the mode string.

Fixes: a009a0c6faa9 ("tools/nolibc: add fopen()")
Signed-off-by: Danish Khateeb <danishkhateeb03@xxxxxxxxx>
---
tools/include/nolibc/stdio.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/include/nolibc/stdio.h b/tools/include/nolibc/stdio.h
index 00a95a267d90..205b06f18b4b 100644
--- a/tools/include/nolibc/stdio.h
+++ b/tools/include/nolibc/stdio.h
@@ -75,7 +75,7 @@ FILE *fopen(const char *pathname, const char *mode)
SET_ERRNO(EINVAL); return NULL;
}

- if (mode[1] == '+')
+ if (strchr(mode, '+'))
flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;

fd = open(pathname, flags, 0666);
--
2.56.0