From 04e5527eeca240ca81b0b95b58c50ef6a16b8030 Mon Sep 17 00:00:00 2001 From: Jakob Kaivo Date: Mon, 27 May 2024 12:49:46 -0400 Subject: handle UB for invalid fflush() operations and mixing input and output without intervening fflush() or repositioning --- src/stdio/freopen.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src/stdio/freopen.c') diff --git a/src/stdio/freopen.c b/src/stdio/freopen.c index d431b0e3..f2238ff9 100644 --- a/src/stdio/freopen.c +++ b/src/stdio/freopen.c @@ -78,10 +78,12 @@ FILE * freopen(const char * restrict filename, const char * restrict mode, FILE } flockfile(stream); - fflush(stream); + if (stream->write) { + fflush(stream); + } if (filename != NULL) { - fd = open(filename, openmode, 0); + fd = open(filename, openmode, 0755); /* TODO: umask */ if (fd < 0) { /* open() already sets errno */ funlockfile(stream); @@ -103,6 +105,8 @@ FILE * freopen(const char * restrict filename, const char * restrict mode, FILE stream->nvalid_ftell = 0; stream->text = !(strchr(mode, 'b')); + stream->read = ((openmode & O_RDONLY) == O_RDONLY) || ((openmode & O_RDWR) == O_RDWR); + stream->write = ((openmode & O_WRONLY) == O_WRONLY) || ((openmode & O_RDWR) == O_RDWR); /* RETURN_SUCCESS(ARGUMENT(stream)); -- cgit v1.2.1