1 /*
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright © 2019 Keith Packard
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above
14  *    copyright notice, this list of conditions and the following
15  *    disclaimer in the documentation and/or other materials provided
16  *    with the distribution.
17  *
18  * 3. Neither the name of the copyright holder nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
27  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
33  * OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 #include "stdio_private.h"
37 #include <stdlib.h>
38 #include <fcntl.h>
39 #include <unistd.h>
40 
41 FILE *
freopen(const char * pathname,const char * mode,FILE * stream)42 freopen(const char *pathname, const char *mode, FILE *stream)
43 {
44 	struct __file_bufio *pf = (struct __file_bufio *) stream;
45 	int fd;
46 	int stdio_flags;
47 	int open_flags;
48 
49         /* Can't reopen FILEs which aren't buffered */
50         if (!(stream->flags & __SBUF))
51             return NULL;
52 
53 	stdio_flags = __posix_sflags(mode, &open_flags);
54 	if (stdio_flags == 0)
55 		return NULL;
56 
57 	fd = open(pathname, open_flags, 0666);
58 	if (fd < 0)
59 		return NULL;
60 
61         fflush(stream);
62 
63         __bufio_lock(stream);
64         close(pf->fd);
65         stream->flags = (stream->flags & ~(__SRD|__SWR|__SERR|__SEOF)) | stdio_flags;
66         pf->pos = 0;
67         pf->fd = fd;
68 
69         /* Switch to POSIX backend */
70         pf->read = read;
71         pf->write = write;
72         pf->lseek = lseek;
73         pf->close = close;
74 
75         __bufio_unlock(stream);
76 
77         return stream;
78 }
79