mailing list of musl libc
 help / color / mirror / code / Atom feed
* bug in fwrite/__towrite
@ 2016-02-05 15:32 hombre
  2016-02-05 15:40 ` Rich Felker
  0 siblings, 1 reply; 2+ messages in thread
From: hombre @ 2016-02-05 15:32 UTC (permalink / raw)
  To: musl

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



^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2016-02-05 15:40 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2016-02-05 15:32 bug in fwrite/__towrite hombre
2016-02-05 15:40 ` Rich Felker

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/musl/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).