• 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 
__fdopen(int fd,const char * mode)9 FILE *__fdopen(int fd, const char *mode)
10 {
11 	FILE *f;
12 	struct winsize wsz;
13 	pthread_mutex_t filelockinit = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
14 
15 	/* Check for valid initial mode character */
16 	if (!strchr("rwa", *mode)) {
17 		errno = EINVAL;
18 		return 0;
19 	}
20 
21 	/* Allocate FILE+buffer or fail */
22 	if (!(f=malloc(sizeof *f + UNGET + BUFSIZ + sizeof(pthread_mutex_t)))) return 0;
23 
24 	/* Zero-fill only the struct, not the buffer */
25 	memset(f, 0, sizeof *f);
26 
27 	/* Impose mode restrictions */
28 	if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
29 
30 	/* Set append mode on fd if opened for append */
31 	if (*mode == 'a') {
32 		int flags = fcntl(fd, F_GETFL);
33 		if (!(flags & O_APPEND))
34 			fcntl(fd, F_SETFL, flags | O_APPEND);
35 		f->flags |= F_APP;
36 	}
37 
38 	f->fd = fd;
39 	f->buf = (unsigned char *)f + sizeof *f + UNGET;
40 	f->buf_size = BUFSIZ;
41 	f->lock = (pthread_mutex_t *)((unsigned char *)f + sizeof *f + UNGET + BUFSIZ);
42 	memcpy(f->lock, &filelockinit, sizeof(pthread_mutex_t));
43 
44 	/* Activate line buffered mode for terminals */
45 	f->lbf = EOF;
46 	if (!(f->flags & F_NOWR))
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 	/* Add new FILE to open file list */
56 	return __ofl_add(f);
57 }
58 
59 weak_alias(__fdopen, fdopen);
60