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