Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <20160205154021.GW9349@brightrain.aerifal.cx>
Date: Fri, 5 Feb 2016 10:40:21 -0500
From: Rich Felker <dalias@...c.org>
To: musl@...ts.openwall.com
Subject: Re: bug in fwrite/__towrite

On Fri, Feb 05, 2016 at 04:32:58PM +0100, hombre wrote:
> Hello,
> 
> I think there is a bug in fwrite/__towrite.
> 
> This is my unittest that fails:
> static void test_write_read2(const char *fname)
> {
>     char wbuf[3];
>     char c;
> 
>     FILE *file = fopen(fname, "wb");
>     assert(file != NULL);
>     wbuf[0] = 'a';
>     wbuf[1] = 'b';
>     wbuf[2] = 'c';
>     size_t written = fwrite(wbuf, 1, 3, file);
>     assert(written == 3);
>     fclose(file);
> 
>     file = fopen(fname, "rb+");
>     size_t nread = fread(&c, 1, 1, file);
>     assert(nread == 1);
>     assert(c == 'a');
>     c = 'B';
>     written = fwrite(&c, 1, 1, file);

This line caused undefined behavior. You cannot switch between writing
and reading on a stream without an intervening successful fseek or
fflush (the latter only in the write->read direction). See 7.21.5.3
The fopen function, paragraph 7:

"When a file is opened with update mode ('+' as the second or third
character in the above list of mode argument values), both input and
output may be performed on the associated stream. However, output
shall not be directly followed by input without an intervening call to
the fflush function or to a file positioning function (fseek, fsetpos,
or rewind), and input shall not be directly followed by output without
an intervening call to a file positioning function, unless the input
operation encounters end- of-file. Opening (or creating) a text file
with update mode may instead open (or create) a binary stream in some
implementations."

>     assert(written == 1);
>     nread = fread(&c, 1, 1, file);

And again.

>     assert(nread == 1); /* <================== nread is 0 here ! */
>     assert(c == 'c');
>     fclose(file);
> }

Rich

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.