1 /* fflush.c -- allow flushing input streams
2    Copyright (C) 2007-2020 Free Software Foundation, Inc.
3 
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
16 
17 /* Written by Eric Blake. */
18 
19 #include <config.h>
20 
21 /* Specification.  */
22 #include <stdio.h>
23 
24 #include <errno.h>
25 #include <unistd.h>
26 
27 #include "freading.h"
28 
29 #include "stdio-impl.h"
30 
31 #include "unused-parameter.h"
32 
33 #undef fflush
34 
35 
36 #if defined _IO_EOF_SEEN || defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1
37 /* GNU libc, BeOS, Haiku, Linux libc5 */
38 
39 /* Clear the stream's ungetc buffer, preserving the value of ftello (fp).  */
40 static void
clear_ungetc_buffer_preserving_position(FILE * fp)41 clear_ungetc_buffer_preserving_position (FILE *fp)
42 {
43   if (fp->_flags & _IO_IN_BACKUP)
44     /* _IO_free_backup_area is a bit complicated.  Simply call fseek.  */
45     fseeko (fp, 0, SEEK_CUR);
46 }
47 
48 #else
49 
50 /* Clear the stream's ungetc buffer.  May modify the value of ftello (fp).  */
51 static void
clear_ungetc_buffer(FILE * fp)52 clear_ungetc_buffer (FILE *fp)
53 {
54 # if defined __sferror || defined __DragonFly__ || defined __ANDROID__
55   /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Minix 3, Android */
56   if (HASUB (fp))
57     {
58       fp_->_p += fp_->_r;
59       fp_->_r = 0;
60     }
61 # elif defined __EMX__              /* emx+gcc */
62   if (fp->_ungetc_count > 0)
63     {
64       fp->_ungetc_count = 0;
65       fp->_rcount = - fp->_rcount;
66     }
67 # elif defined _IOERR               /* Minix, AIX, HP-UX, IRIX, OSF/1, Solaris, OpenServer, mingw, MSVC, NonStop Kernel, OpenVMS */
68   /* Nothing to do.  */
69 # else                              /* other implementations */
70   fseeko (fp, 0, SEEK_CUR);
71 # endif
72 }
73 
74 #endif
75 
76 #if ! (defined _IO_EOF_SEEN || defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1)
77 /* GNU libc, BeOS, Haiku, Linux libc5 */
78 
79 # if (defined __sferror || defined __DragonFly__ || defined __ANDROID__) && defined __SNPT
80 /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Minix 3, Android */
81 
82 static int
disable_seek_optimization(FILE * fp)83 disable_seek_optimization (FILE *fp)
84 {
85   int saved_flags = fp_->_flags & (__SOPT | __SNPT);
86   fp_->_flags = (fp_->_flags & ~__SOPT) | __SNPT;
87   return saved_flags;
88 }
89 
90 static void
restore_seek_optimization(FILE * fp,int saved_flags)91 restore_seek_optimization (FILE *fp, int saved_flags)
92 {
93   fp_->_flags = (fp_->_flags & ~(__SOPT | __SNPT)) | saved_flags;
94 }
95 
96 # else
97 
98 static void
update_fpos_cache(FILE * fp _GL_UNUSED_PARAMETER,off_t pos _GL_UNUSED_PARAMETER)99 update_fpos_cache (FILE *fp _GL_UNUSED_PARAMETER,
100                    off_t pos _GL_UNUSED_PARAMETER)
101 {
102 #  if defined __sferror || defined __DragonFly__ || defined __ANDROID__
103   /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Minix 3, Android */
104 #   if defined __CYGWIN__
105   /* fp_->_offset is typed as an integer.  */
106   fp_->_offset = pos;
107 #   else
108   /* fp_->_offset is an fpos_t.  */
109   /* Use a union, since on NetBSD, the compilation flags determine
110      whether fpos_t is typedef'd to off_t or a struct containing a
111      single off_t member.  */
112   union
113     {
114       fpos_t f;
115       off_t o;
116     } u;
117   u.o = pos;
118   fp_->_offset = u.f;
119 #   endif
120   fp_->_flags |= __SOFF;
121 #  endif
122 }
123 # endif
124 #endif
125 
126 /* Flush all pending data on STREAM according to POSIX rules.  Both
127    output and seekable input streams are supported.  */
128 int
rpl_fflush(FILE * stream)129 rpl_fflush (FILE *stream)
130 {
131   /* When stream is NULL, POSIX and C99 only require flushing of "output
132      streams and update streams in which the most recent operation was not
133      input", and all implementations do this.
134 
135      When stream is "an output stream or an update stream in which the most
136      recent operation was not input", POSIX and C99 requires that fflush
137      writes out any buffered data, and all implementations do this.
138 
139      When stream is, however, an input stream or an update stream in
140      which the most recent operation was input, C99 specifies nothing,
141      and POSIX only specifies behavior if the stream is seekable.
142      mingw, in particular, drops the input buffer, leaving the file
143      descriptor positioned at the end of the input buffer. I.e. ftell
144      (stream) is lost.  We don't want to call the implementation's
145      fflush in this case.
146 
147      We test ! freading (stream) here, rather than fwriting (stream), because
148      what we need to know is whether the stream holds a "read buffer", and on
149      mingw this is indicated by _IOREAD, regardless of _IOWRT.  */
150   if (stream == NULL || ! freading (stream))
151     return fflush (stream);
152 
153 #if defined _IO_EOF_SEEN || defined _IO_ftrylockfile || __GNU_LIBRARY__ == 1
154   /* GNU libc, BeOS, Haiku, Linux libc5 */
155 
156   clear_ungetc_buffer_preserving_position (stream);
157 
158   return fflush (stream);
159 
160 #else
161   {
162     /* What POSIX says:
163        1) About the file-position indicator (-> fseeko, ftello):
164           The file position indicator is incremented by fgetc() and decremented
165           by ungetc():
166           <https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetc.html>
167             "... the fgetc() function shall ... advance the associated file
168              position indicator for the stream ..."
169           <https://pubs.opengroup.org/onlinepubs/9699919799/functions/ungetc.html>
170             "The file-position indicator is decremented by each successful
171              call to ungetc()..."
172        2) fflush discards bytes pushed back by ungetc:
173           <https://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html>
174             "...any characters pushed back onto the stream by ungetc()
175              or ungetwc() that have not subsequently been read from the
176              stream shall be discarded..."
177           This implies implicitly: fflush does not change the file position
178           indicator.
179        3) Effects on the file descriptor, if the file descriptor is capable of
180           seeking:
181           <https://pubs.opengroup.org/onlinepubs/9699919799/functions/fflush.html>
182             "...the file offset of the underlying open file description shall
183              be set to the file position of the stream..."  */
184 
185     /* POSIX does not specify fflush behavior for non-seekable input
186        streams.  Some implementations purge unread data, some return
187        EBADF, some do nothing.  */
188     off_t pos = ftello (stream);
189     if (pos == -1)
190       {
191         errno = EBADF;
192         return EOF;
193       }
194 
195     /* Clear the ungetc buffer.  */
196     clear_ungetc_buffer (stream);
197 
198     /* To get here, we must be flushing a seekable input stream, so the
199        semantics of fpurge are now appropriate to clear the buffer.  To
200        avoid losing data, the lseek is also necessary.  */
201     {
202       int result = fpurge (stream);
203       if (result != 0)
204         return result;
205     }
206 
207 # if (defined __sferror || defined __DragonFly__ || defined __ANDROID__) && defined __SNPT
208     /* FreeBSD, NetBSD, OpenBSD, DragonFly, Mac OS X, Cygwin, Minix 3, Android */
209 
210     {
211       /* Disable seek optimization for the next fseeko call.  This tells the
212          following fseeko call to seek to the desired position directly, rather
213          than to seek to a block-aligned boundary.  */
214       int saved_flags = disable_seek_optimization (stream);
215       int result = fseeko (stream, pos, SEEK_SET);
216 
217       restore_seek_optimization (stream, saved_flags);
218       return result;
219     }
220 
221 # else
222 
223     pos = lseek (fileno (stream), pos, SEEK_SET);
224     if (pos == -1)
225       return EOF;
226     /* After a successful lseek, update the file descriptor's position cache
227        in the stream.  */
228     update_fpos_cache (stream, pos);
229 
230     return 0;
231 
232 # endif
233   }
234 #endif
235 }
236