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