musl/src/stdio/__toread.c
Rich Felker 6d1a3dfeaf fix undefined pointer comparison in stdio-internal __toread
the comparison f->wpos > f->buf has undefined behavior when f->wpos is
a null pointer, despite the intuition (and actual compiler behavior,
for all known compilers) being that NULL > ptr is false for all valid
pointers ptr.

the purpose of the comparison is to determine if the write buffer is
non-empty, and the idiom used elsewhere for that is comparison against
f->wbase, which is either a null pointer when not writing, or equal to
f->buf when writing. in the former case, both f->wpos and f->wbase are
null; in the latter they are both non-null and point into the same
array.
2016-03-28 23:41:17 -04:00

22 lines
393 B
C

#include <stdio_impl.h>
int __toread(FILE *f)
{
f->mode |= f->mode-1;
if (f->wpos > f->wbase) f->write(f, 0, 0);
f->wpos = f->wbase = f->wend = 0;
if (f->flags & F_NORD) {
f->flags |= F_ERR;
return EOF;
}
f->rpos = f->rend = f->buf + f->buf_size;
return (f->flags & F_EOF) ? EOF : 0;
}
void __stdio_exit_needed(void);
void __toread_needs_stdio_exit()
{
__stdio_exit_needed();
}