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