clean up stdio_impl.h
[musl] / src / stdio / __fdopen.c
1 #include "stdio_impl.h"
2 #include <stdlib.h>
3 #include <termios.h>
4 #include <sys/ioctl.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 #include <string.h>
8
9 FILE *__fdopen(int fd, const char *mode)
10 {
11         FILE *f;
12         struct termios tio;
13
14         /* Check for valid initial mode character */
15         if (!strchr("rwa", *mode)) {
16                 errno = EINVAL;
17                 return 0;
18         }
19
20         /* Allocate FILE+buffer or fail */
21         if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
22
23         /* Zero-fill only the struct, not the buffer */
24         memset(f, 0, sizeof *f);
25
26         /* Impose mode restrictions */
27         if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
28
29         /* Apply close-on-exec flag */
30         if (strchr(mode, 'e')) __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
31
32         /* Set append mode on fd if opened for append */
33         if (*mode == 'a') {
34                 int flags = __syscall(SYS_fcntl, fd, F_GETFL);
35                 __syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
36         }
37
38         f->fd = fd;
39         f->buf = (unsigned char *)f + sizeof *f + UNGET;
40         f->buf_size = BUFSIZ;
41
42         /* Activate line buffered mode for terminals */
43         f->lbf = EOF;
44         if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TCGETS, &tio))
45                 f->lbf = '\n';
46
47         /* Initialize op ptrs. No problem if some are unneeded. */
48         f->read = __stdio_read;
49         f->write = __stdio_write;
50         f->seek = __stdio_seek;
51         f->close = __stdio_close;
52
53         if (!libc.threaded) f->lock = -1;
54
55         /* Add new FILE to open file list */
56         OFLLOCK();
57         f->next = libc.ofl_head;
58         if (libc.ofl_head) libc.ofl_head->prev = f;
59         libc.ofl_head = f;
60         OFLUNLOCK();
61
62         return f;
63 }
64
65 weak_alias(__fdopen, fdopen);