• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
__fdopen(int fd,const char * mode)9 FILE *__fdopen(int fd, const char *mode)
10 {
11 	FILE *f;
12 	struct winsize wsz;
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 		if (!(flags & O_APPEND))
36 			__syscall(SYS_fcntl, fd, F_SETFL, flags | O_APPEND);
37 		f->flags |= F_APP;
38 	}
39 
40 	f->fd = fd;
41 	f->buf = (unsigned char *)f + sizeof *f + UNGET;
42 	f->buf_size = BUFSIZ;
43 
44 	/* Activate line buffered mode for terminals */
45 	f->lbf = EOF;
46 	if (!(f->flags & F_NOWR) && !__syscall(SYS_ioctl, fd, TIOCGWINSZ, &wsz))
47 		f->lbf = '\n';
48 
49 	/* Initialize op ptrs. No problem if some are unneeded. */
50 	f->read = __stdio_read;
51 	f->write = __stdio_write;
52 	f->seek = __stdio_seek;
53 	f->close = __stdio_close;
54 
55 	if (!libc.threaded) f->lock = -1;
56 
57 	/* Add new FILE to open file list */
58 	return __ofl_add(f);
59 }
60 
61 weak_alias(__fdopen, fdopen);
62