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 <time.h>
64 #include <stdio.h>
65 #include <string.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <stdlib.h>
69 #include <sys/lock.h>
70 #include "local.h"
71 
72 /*
73  * Re-direct an existing, open (probably) file to some other file.
74  */
75 
76 FILE *
freopen(const char * __restrict file,const char * __restrict mode,register FILE * __restrict fp)77 freopen (
78        const char *__restrict file,
79        const char *__restrict mode,
80        register FILE *__restrict fp)
81 {
82   register int f;
83   int flags, oflags, oflags2;
84   int e = 0;
85 
86   CHECK_INIT (ptr, fp);
87 
88   /* We can't use the _newlib_flockfile_XXX macros here due to the
89      interlocked locking with the sfp_lock. */
90 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
91   int __oldcancel;
92   pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &__oldcancel);
93 #endif
94   oflags2 = fp->_flags2;
95   if (!(oflags2 & __SNLK))
96     _flockfile (fp);
97 
98   if ((flags = __sflags (mode, &oflags)) == 0)
99     {
100       if (!(oflags2 & __SNLK))
101 	_funlockfile (fp);
102 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
103       pthread_setcancelstate (__oldcancel, &__oldcancel);
104 #endif
105       fclose ( fp);
106       return NULL;
107     }
108 
109   /*
110    * Remember whether the stream was open to begin with, and
111    * which file descriptor (if any) was associated with it.
112    * If it was attached to a descriptor, defer closing it,
113    * so that, e.g., freopen("/dev/stdin", "r", stdin) works.
114    * This is unnecessary if it was not a Unix file.
115    */
116 
117   if (fp->_flags == 0)
118     fp->_flags = __SEOF;	/* hold on to it */
119   else
120     {
121       if (fp->_flags & __SWR)
122 	fflush ( fp);
123       /*
124        * If close is NULL, closing is a no-op, hence pointless.
125        * If file is NULL, the file should not be closed.
126        */
127       if (fp->_close != NULL && file != NULL)
128 	fp->_close (fp->_cookie);
129     }
130 
131   /*
132    * Now get a new descriptor to refer to the new file, or reuse the
133    * existing file descriptor if file is NULL.
134    */
135 
136   if (file != NULL)
137     {
138       f = open ((char *) file, oflags, 0666);
139       e = _REENT_ERRNO(ptr);
140     }
141   else
142     {
143 #ifdef _HAVE_FCNTL
144       int oldflags;
145       /*
146        * Reuse the file descriptor, but only if the new access mode is
147        * equal or less permissive than the old.  F_SETFL correctly
148        * ignores creation flags.
149        */
150       f = fp->_file;
151       if ((oldflags = fcntl (f, F_GETFL, 0)) == -1
152 	  || ! ((oldflags & O_ACCMODE) == O_RDWR
153 		|| ((oldflags ^ oflags) & O_ACCMODE) == 0)
154 	  || fcntl (f, F_SETFL, oflags) == -1)
155 	f = -1;
156 #else
157       /* We cannot modify without fcntl support.  */
158       f = -1;
159 #endif
160 
161 #ifdef __SCLE
162       /*
163        * F_SETFL doesn't change textmode.  Don't mess with modes of ttys.
164        */
165       if (0 <= f && ! isatty ( f)
166 	  && setmode (f, oflags & (O_BINARY | O_TEXT)) == -1)
167 	f = -1;
168 #endif
169 
170       if (f < 0)
171 	{
172 	  e = EBADF;
173 	  if (fp->_close != NULL)
174 	    fp->_close (fp->_cookie);
175 	}
176     }
177 
178   /*
179    * Finish closing fp.  Even if the open succeeded above,
180    * we cannot keep fp->_base: it may be the wrong size.
181    * This loses the effect of any setbuffer calls,
182    * but stdio has always done this before.
183    */
184 
185   if (fp->_flags & __SMBF)
186     free ((char *) fp->_bf._base);
187   fp->_w = 0;
188   fp->_r = 0;
189   fp->_p = NULL;
190   fp->_bf._base = NULL;
191   fp->_bf._size = 0;
192   fp->_lbfsize = 0;
193   if (HASUB (fp))
194     FREEUB (ptr, fp);
195   fp->_ub._size = 0;
196   if (HASLB (fp))
197     FREELB (ptr, fp);
198   fp->_lb._size = 0;
199   fp->_flags &= ~__SORD;
200   fp->_flags2 &= ~__SWID;
201   memset (&fp->_mbstate, 0, sizeof (_mbstate_t));
202 
203   if (f < 0)
204     {				/* did not get it after all */
205       __sfp_lock_acquire ();
206       fp->_flags = 0;		/* set it free */
207       _REENT_ERRNO(ptr) = e;	/* restore in case _close clobbered */
208       if (!(oflags2 & __SNLK))
209 	_funlockfile (fp);
210 #ifndef __SINGLE_THREAD__
211       __lock_close_recursive (fp->_lock);
212 #endif
213       __sfp_lock_release ();
214 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
215       pthread_setcancelstate (__oldcancel, &__oldcancel);
216 #endif
217       return NULL;
218     }
219 
220   fp->_flags = flags;
221   fp->_file = f;
222   fp->_cookie = (void *) fp;
223   fp->_read = __sread;
224   fp->_write = __swrite;
225   fp->_seek = __sseek;
226   fp->_close = __sclose;
227 
228 #ifdef __SCLE
229   if (__stextmode (fp->_file))
230     fp->_flags |= __SCLE;
231 #endif
232 
233   if (!(oflags2 & __SNLK))
234     _funlockfile (fp);
235 #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT
236   pthread_setcancelstate (__oldcancel, &__oldcancel);
237 #endif
238   return fp;
239 }
240