master
 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 "libc.h"
 8#ifdef __wasilibc_unmodified_upstream // WASI has no syscall
 9#else
10#include <__function___isatty.h>
11#endif
12
13FILE *__fdopen(int fd, const char *mode)
14{
15	FILE *f;
16#ifdef __wasilibc_unmodified_upstream // WASI has no syscall
17	struct winsize wsz;
18#endif
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))) 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#ifdef __wasilibc_unmodified_upstream // WASI has no syscall
37	if (strchr(mode, 'e')) __syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC);
38#else
39	if (strchr(mode, 'e')) fcntl(fd, F_SETFD, FD_CLOEXEC);
40#endif
41
42	/* Set append mode on fd if opened for append */
43	if (*mode == 'a') {
44#ifdef __wasilibc_unmodified_upstream // WASI has no syscall
45		int flags = __syscall(SYS_fcntl, fd, F_GETFL);
46#else
47		int flags = fcntl(fd, F_GETFL);
48#endif
49		if (!(flags & O_APPEND))
50#ifdef __wasilibc_unmodified_upstream // WASI has no syscall
51			__syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
52#else
53			fcntl(fd, F_SETFL, flags | O_APPEND);
54#endif
55		f->flags |= F_APP;
56	}
57
58	f->fd = fd;
59	f->buf = (unsigned char *)f + sizeof *f + UNGET;
60	f->buf_size = BUFSIZ;
61
62	/* Activate line buffered mode for terminals */
63	f->lbf = EOF;
64#ifdef __wasilibc_unmodified_upstream // WASI has no syscall
65	if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TIOCGWINSZ, &wsz))
66#else
67	if (!(f->flags & F_NOWR) && __isatty(fd))
68#endif
69		f->lbf = '\n';
70
71	/* Initialize op ptrs. No problem if some are unneeded. */
72	f->read = __stdio_read;
73	f->write = __stdio_write;
74	f->seek = __stdio_seek;
75	f->close = __stdio_close;
76
77#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
78	if (!libc.threaded) f->lock = -1;
79#endif
80
81	/* Add new FILE to open file list */
82	return __ofl_add(f);
83}
84
85weak_alias(__fdopen, fdopen);