Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <56B4C0AA.3020705@gmx.at>
Date: Fri, 5 Feb 2016 16:32:58 +0100
From: hombre <hombre67@....at>
To: musl@...ts.openwall.com
Subject: bug in fwrite/__towrite

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);
     assert(written == 1);
     nread = fread(&c, 1, 1, file);
     assert(nread == 1); /* <================== nread is 0 here ! */
     assert(c == 'c');
     fclose(file);
}

Please note that I have not tested this with the original musl-libc in 
linux. I found this bug while I was trying to port parts of musl to a 
small embedded os. But I think the bug is not in my port. Here is what I 
think is wrong:

- fwrite calls __towrite when the write buffer is not active
     if (!f->wend && __towrite(f)) return 0;
- __towrite clears the read buffer, but the underlying filepointer is 
not adjusted. I think that the filepointer should be adjusted, when the 
read buffer is not empty.
int __towrite(FILE *f)
{
     ...
     /* Clear read buffer (easier than summoning nasal demons) */
     f->rpos = f->rend = 0;
     ...

Here is my fix:
int __towrite(FILE *f)
{
     ...
     /* Clear read buffer (easier than summoning nasal demons) */
     if (f->rpos) {
         /* Adjust underlying filepointer for unread data in buffer. */
         if (f->seek(f, -(f->rend - f->rpos), SEEK_CUR) < 0)
             return -1;
         f->rpos = f->rend = 0;
     }
     ...

Regards,
Erwin

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.