dd97cf68ac15f08a3c71fc6553418f39185539d4
[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->wpos = f->wbase = f->buf;
26                         return len;
27                 }
28                 if (cnt < 0) {
29                         f->wpos = f->wbase = f->wend = 0;
30                         f->flags |= F_ERR;
31                         return iovcnt == 2 ? 0 : len-iov[0].iov_len;
32                 }
33                 rem -= cnt;
34                 if (cnt > iov[0].iov_len) {
35                         f->wpos = f->wbase = f->buf;
36                         cnt -= iov[0].iov_len;
37                         iov++; iovcnt--;
38                 } else if (iovcnt == 2) {
39                         f->wbase += cnt;
40                 }
41                 iov[0].iov_base = (char *)iov[0].iov_base + cnt;
42                 iov[0].iov_len -= cnt;
43         }
44 }