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