also ensure that write buffer is bounded when __stdio_write returns
[musl] / src / stdio / __stdio_write.c
1 #include "stdio_impl.h"
2 #include <pthread.h>
3
4 static void cleanup(void *p)
5 {
6         FILE *f = p;
7         if (!f->lockcount) __unlockfile(f);
8 }
9
10 size_t __stdio_write(FILE *f, const unsigned char *buf, size_t len)
11 {
12         struct iovec iovs[2] = {
13                 { .iov_base = f->wbase, .iov_len = f->wpos-f->wbase },
14                 { .iov_base = (void *)buf, .iov_len = len }
15         };
16         struct iovec *iov = iovs;
17         size_t rem = iov[0].iov_len + iov[1].iov_len;
18         int iovcnt = 2;
19         ssize_t cnt;
20         for (;;) {
21                 pthread_cleanup_push(cleanup, f);
22                 cnt = syscall_cp(SYS_writev, f->fd, iov, iovcnt);
23                 pthread_cleanup_pop(0);
24                 if (cnt == rem) {
25                         f->wend = f->buf + f->buf_size;
26                         f->wpos = f->wbase = f->buf;
27                         return len;
28                 }
29                 if (cnt < 0) {
30                         f->wpos = f->wbase = f->wend = 0;
31                         f->flags |= F_ERR;
32                         return iovcnt == 2 ? 0 : len-iov[0].iov_len;
33                 }
34                 rem -= cnt;
35                 if (cnt > iov[0].iov_len) {
36                         f->wpos = f->wbase = f->buf;
37                         cnt -= iov[0].iov_len;
38                         iov++; iovcnt--;
39                 } else if (iovcnt == 2) {
40                         f->wbase += cnt;
41                 }
42                 iov[0].iov_base = (char *)iov[0].iov_base + cnt;
43                 iov[0].iov_len -= cnt;
44         }
45 }