From 51d9144e9fdfab1fcb611f0c2600efc087cb7528 Mon Sep 17 00:00:00 2001 From: Ben Gras Date: Tue, 2 Nov 2010 22:02:50 +0000 Subject: [PATCH] stdio/freopen.c: fill __iotab table with stream pointer - lets fclose()d and then freopen()ed streams be fclose()d again without error --- lib/libc/stdio/freopen.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/lib/libc/stdio/freopen.c b/lib/libc/stdio/freopen.c index 2e8014de2..48549fdc7 100644 --- a/lib/libc/stdio/freopen.c +++ b/lib/libc/stdio/freopen.c @@ -39,6 +39,22 @@ freopen(const char *name, const char *mode, FILE *stream) (void) fflush(stream); /* ignore errors */ (void) _close(fileno(stream)); + /* Find the slot the stream had, if any. */ + for(i = 0; i < FOPEN_MAX; i++) + if (stream == __iotab[i]) + break; + + /* If none, it might've been fclose()d; find a new slot for it. */ + if(i >= FOPEN_MAX) { + for (i = 0; __iotab[i] != 0 ; i++) { + if ( i >= FOPEN_MAX-1 ) + return (FILE *)NULL; + } + } + + /* If it was valid, it isn't any more until the freopen() succeeds. */ + __iotab[i] = 0; + switch(*mode++) { case 'r': flags |= _IOREAD; @@ -95,15 +111,10 @@ freopen(const char *name, const char *mode, FILE *stream) stream->_count = 0; stream->_fd = fd; stream->_flags = flags; + __iotab[i] = stream; return stream; loser: - for( i = 0; i < FOPEN_MAX; i++) { - if (stream == __iotab[i]) { - __iotab[i] = 0; - break; - } - } if (stream != stdin && stream != stdout && stream != stderr) free((void *)stream); return (FILE *)NULL; -- 2.44.0