cef7bbdc37238cbc8607a0e09e68f1551567d1e5
[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                 if (libc.main_thread) {
22                         pthread_cleanup_push(cleanup, f);
23                         cnt = syscall_cp(SYS_writev, f->fd, iov, iovcnt);
24                         pthread_cleanup_pop(0);
25                 } else {
26                         cnt = syscall(SYS_writev, f->fd, iov, iovcnt);
27                 }
28                 if (cnt == rem) {
29                         f->wend = f->buf + f->buf_size;
30                         f->wpos = f->wbase = f->buf;
31                         return len;
32                 }
33                 if (cnt < 0) {
34                         f->wpos = f->wbase = f->wend = 0;
35                         f->flags |= F_ERR;
36                         return iovcnt == 2 ? 0 : len-iov[0].iov_len;
37                 }
38                 rem -= cnt;
39                 if (cnt > iov[0].iov_len) {
40                         f->wpos = f->wbase = f->buf;
41                         cnt -= iov[0].iov_len;
42                         iov++; iovcnt--;
43                 } else if (iovcnt == 2) {
44                         f->wbase += cnt;
45                 }
46                 iov[0].iov_base = (char *)iov[0].iov_base + cnt;
47                 iov[0].iov_len -= cnt;
48         }
49 }