1 #include "stdio_impl.h"
2 #include <fcntl.h>
3 #include <unistd.h>
4
5 /* The basic idea of this implementation is to open a new FILE,
6 * hack the necessary parts of the new FILE into the old one, then
7 * close the new FILE. */
8
9 /* Locking IS necessary because another thread may provably hold the
10 * lock, via flockfile or otherwise, when freopen is called, and in that
11 * case, freopen cannot act until the lock is released. */
12
freopen(const char * restrict filename,const char * restrict mode,FILE * restrict f)13 FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
14 {
15 int file_flags = 0;
16 int fl = __fmodeflags(mode, &file_flags);
17 FILE *f2;
18
19 FLOCK(f);
20
21 fflush(f);
22
23 if (!filename) {
24 if (fl&O_CLOEXEC)
25 __syscall(SYS_fcntl, f->fd, F_SETFD, FD_CLOEXEC);
26 fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC);
27 if (syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0) {
28 goto fail;
29 }
30 } else {
31 f2 = fopen(filename, mode);
32 if (!f2) goto fail;
33 if (f2->fd == f->fd) {
34 f2->fd = -1; /* avoid closing in fclose */
35 }
36 else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) {
37 goto fail2;
38 }
39
40 f->flags = (f->flags & F_PERM) | f2->flags;
41 f->read = f2->read;
42 f->readx = f2->readx;
43 f->write = f2->write;
44 f->seek = f2->seek;
45 f->close = f2->close;
46
47 fclose(f2);
48 }
49
50 FUNLOCK(f);
51 return f;
52
53 fail2:
54 fclose(f2);
55 fail:
56 fclose(f);
57 return NULL;
58 }
59
60 weak_alias(freopen, freopen64);
61