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