1 /*
2  * Copyright (c) 1990, 2007 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * and/or other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 /*
19 FUNCTION
20 <<freopen>>---open a file using an existing file descriptor
21 
22 INDEX
23 	freopen
24 INDEX
25 	_freopen_r
26 
27 SYNOPSIS
28 	#include <stdio.h>
29 	FILE *freopen(const char *restrict <[file]>, const char *restrict <[mode]>,
30 		      FILE *restrict <[fp]>);
31 	FILE *freopen( const char *restrict <[file]>,
32 		      const char *restrict <[mode]>, FILE *restrict <[fp]>);
33 
34 DESCRIPTION
35 Use this variant of <<fopen>> if you wish to specify a particular file
36 descriptor <[fp]> (notably <<stdin>>, <<stdout>>, or <<stderr>>) for
37 the file.
38 
39 If <[fp]> was associated with another file or stream, <<freopen>>
40 closes that other file or stream (but ignores any errors while closing
41 it).
42 
43 <[file]> and <[mode]> are used just as in <<fopen>>.
44 
45 If <[file]> is <<NULL>>, the underlying stream is modified rather than
46 closed.  The file cannot be given a more permissive access mode (for
47 example, a <[mode]> of "w" will fail on a read-only file descriptor),
48 but can change status such as append or binary mode.  If modification
49 is not possible, failure occurs.
50 
51 RETURNS
52 If successful, the result is the same as the argument <[fp]>.  If the
53 file cannot be opened as specified, the result is <<NULL>>.
54 
55 PORTABILITY
56 ANSI C requires <<freopen>>.
57 
58 Supporting OS subroutines required: <<close>>, <<fstat>>, <<isatty>>,
59 <<lseek>>, <<open>>, <<read>>, <<sbrk>>, <<write>>.
60 */
61 
62 #define _DEFAULT_SOURCE
63 #include <_ansi.h>
64 #include <time.h>
65 #include <stdio.h>
66 #include <string.h>
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <stdlib.h>
70 #include <sys/lock.h>
71 #include "local.h"
72 
73 /*
74  * Re-direct an existing, open (probably) file to some other file.
75  */
76 
77 FILE *
freopen(const char * __restrict file,const char * __restrict mode,register FILE * __restrict fp)78 freopen (
79        const char *__restrict file,
80        const char *__restrict mode,
81        register FILE *__restrict fp)
82 {
83   register int f;
84   int flags, oflags, oflags2;
85   int e = 0;
86 
87   CHECK_INIT (ptr, fp);
88 
89   /* We can't use the _newlib_flockfile_XXX macros here due to the
90      interlocked locking with the sfp_lock. */
91 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
92   int __oldcancel;
93   pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &__oldcancel);
94 #endif
95   oflags2 = fp->_flags2;
96   if (!(oflags2 & __SNLK))
97     _flockfile (fp);
98 
99   if ((flags = __sflags (mode, &oflags)) == 0)
100     {
101       if (!(oflags2 & __SNLK))
102 	_funlockfile (fp);
103 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
104       pthread_setcancelstate (__oldcancel, &__oldcancel);
105 #endif
106       fclose ( fp);
107       return NULL;
108     }
109 
110   /*
111    * Remember whether the stream was open to begin with, and
112    * which file descriptor (if any) was associated with it.
113    * If it was attached to a descriptor, defer closing it,
114    * so that, e.g., freopen("/dev/stdin", "r", stdin) works.
115    * This is unnecessary if it was not a Unix file.
116    */
117 
118   if (fp->_flags == 0)
119     fp->_flags = __SEOF;	/* hold on to it */
120   else
121     {
122       if (fp->_flags & __SWR)
123 	fflush ( fp);
124       /*
125        * If close is NULL, closing is a no-op, hence pointless.
126        * If file is NULL, the file should not be closed.
127        */
128       if (fp->_close != NULL && file != NULL)
129 	fp->_close (fp->_cookie);
130     }
131 
132   /*
133    * Now get a new descriptor to refer to the new file, or reuse the
134    * existing file descriptor if file is NULL.
135    */
136 
137   if (file != NULL)
138     {
139       f = open ((char *) file, oflags, 0666);
140       e = _REENT_ERRNO(ptr);
141     }
142   else
143     {
144 #ifdef _HAVE_FCNTL
145       int oldflags;
146       /*
147        * Reuse the file descriptor, but only if the new access mode is
148        * equal or less permissive than the old.  F_SETFL correctly
149        * ignores creation flags.
150        */
151       f = fp->_file;
152       if ((oldflags = fcntl (f, F_GETFL, 0)) == -1
153 	  || ! ((oldflags & O_ACCMODE) == O_RDWR
154 		|| ((oldflags ^ oflags) & O_ACCMODE) == 0)
155 	  || fcntl (f, F_SETFL, oflags) == -1)
156 	f = -1;
157 #else
158       /* We cannot modify without fcntl support.  */
159       f = -1;
160 #endif
161 
162 #ifdef __SCLE
163       /*
164        * F_SETFL doesn't change textmode.  Don't mess with modes of ttys.
165        */
166       if (0 <= f && ! isatty ( f)
167 	  && setmode (f, oflags & (O_BINARY | O_TEXT)) == -1)
168 	f = -1;
169 #endif
170 
171       if (f < 0)
172 	{
173 	  e = EBADF;
174 	  if (fp->_close != NULL)
175 	    fp->_close (fp->_cookie);
176 	}
177     }
178 
179   /*
180    * Finish closing fp.  Even if the open succeeded above,
181    * we cannot keep fp->_base: it may be the wrong size.
182    * This loses the effect of any setbuffer calls,
183    * but stdio has always done this before.
184    */
185 
186   if (fp->_flags & __SMBF)
187     free ((char *) fp->_bf._base);
188   fp->_w = 0;
189   fp->_r = 0;
190   fp->_p = NULL;
191   fp->_bf._base = NULL;
192   fp->_bf._size = 0;
193   fp->_lbfsize = 0;
194   if (HASUB (fp))
195     FREEUB (ptr, fp);
196   fp->_ub._size = 0;
197   if (HASLB (fp))
198     FREELB (ptr, fp);
199   fp->_lb._size = 0;
200   fp->_flags &= ~__SORD;
201   fp->_flags2 &= ~__SWID;
202   memset (&fp->_mbstate, 0, sizeof (_mbstate_t));
203 
204   if (f < 0)
205     {				/* did not get it after all */
206       __sfp_lock_acquire ();
207       fp->_flags = 0;		/* set it free */
208       _REENT_ERRNO(ptr) = e;	/* restore in case _close clobbered */
209       if (!(oflags2 & __SNLK))
210 	_funlockfile (fp);
211 #ifndef __SINGLE_THREAD__
212       __lock_close_recursive (fp->_lock);
213 #endif
214       __sfp_lock_release ();
215 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
216       pthread_setcancelstate (__oldcancel, &__oldcancel);
217 #endif
218       return NULL;
219     }
220 
221   fp->_flags = flags;
222   fp->_file = f;
223   fp->_cookie = (void *) fp;
224   fp->_read = __sread;
225   fp->_write = __swrite;
226   fp->_seek = __sseek;
227   fp->_close = __sclose;
228 
229 #ifdef __SCLE
230   if (__stextmode (fp->_file))
231     fp->_flags |= __SCLE;
232 #endif
233 
234   if (!(oflags2 & __SNLK))
235     _funlockfile (fp);
236 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
237   pthread_setcancelstate (__oldcancel, &__oldcancel);
238 #endif
239   return fp;
240 }
241