blob: cf97a3f8d01236bd4a96d5b5193aa0b65cb08640 [file] [log] [blame]
Dmitriy Ivanov623b0d02014-05-14 23:11:05 -07001/* $OpenBSD: findfp.c,v 1.15 2013/12/17 16:33:27 deraadt Exp $ */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002/*-
3 * Copyright (c) 1990, 1993
4 * The Regents of the University of California. All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Chris Torek.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
Elliott Hughes53cf3482016-08-09 13:06:41 -070034#define __BIONIC_NO_STDIO_FORTIFY
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080035#include <stdio.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080036
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080037#include <errno.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080038#include <fcntl.h>
Elliott Hughes2704bd12016-01-20 17:14:53 -080039#include <limits.h>
Elliott Hughes20788ae2016-06-09 15:16:32 -070040#include <paths.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041#include <stdlib.h>
42#include <string.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080043#include <sys/param.h>
Elliott Hughes023c3072016-01-22 15:04:51 -080044#include <sys/stat.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080045#include <unistd.h>
46
Josh Gaod1620602017-10-05 13:48:08 -070047#include <async_safe/log.h>
48
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080049#include "local.h"
50#include "glue.h"
Elliott Hughesfb3873d2016-08-10 11:07:54 -070051#include "private/bionic_fortify.h"
Elliott Hughes023c3072016-01-22 15:04:51 -080052#include "private/ErrnoRestorer.h"
Elliott Hughes6a03abc2014-11-03 12:32:17 -080053#include "private/thread_private.h"
54
55#define ALIGNBYTES (sizeof(uintptr_t) - 1)
56#define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
Calin Juravlec20de902014-03-20 15:21:32 +000057
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080058#define NDYNAMIC 10 /* add ten more whenever necessary */
59
Elliott Hughes70715da2016-08-01 16:35:17 -070060#define PRINTF_IMPL(expr) \
61 va_list ap; \
62 va_start(ap, fmt); \
63 int result = (expr); \
64 va_end(ap); \
65 return result;
66
Elliott Hughes023c3072016-01-22 15:04:51 -080067#define std(flags, file) \
68 {0,0,0,flags,file,{0,0},0,__sF+file,__sclose,__sread,nullptr,__swrite, \
69 {(unsigned char *)(__sFext+file), 0},nullptr,0,{0},{0},{0,0},0,0}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080070
Kenny Rootf5823402011-02-12 07:13:44 -080071_THREAD_PRIVATE_MUTEX(__sfp_mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080072
Elliott Hughes33a8cb12017-07-25 18:06:46 -070073#define SBUF_INIT {}
74#define WCHAR_IO_DATA_INIT {}
Elliott Hughes29ee6392015-12-07 11:07:15 -080075
Elliott Hughesbb46afd2015-12-04 18:03:12 -080076static struct __sfileext __sFext[3] = {
Elliott Hughes023c3072016-01-22 15:04:51 -080077 { SBUF_INIT, WCHAR_IO_DATA_INIT, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, false, __sseek64 },
78 { SBUF_INIT, WCHAR_IO_DATA_INIT, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, false, __sseek64 },
79 { SBUF_INIT, WCHAR_IO_DATA_INIT, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, false, __sseek64 },
Elliott Hughesbb46afd2015-12-04 18:03:12 -080080};
Elliott Hughesf0141df2015-10-12 12:44:23 -070081
82// __sF is exported for backwards compatibility. Until M, we didn't have symbols
83// for stdin/stdout/stderr; they were macros accessing __sF.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084FILE __sF[3] = {
Elliott Hughesbb46afd2015-12-04 18:03:12 -080085 std(__SRD, STDIN_FILENO),
86 std(__SWR, STDOUT_FILENO),
87 std(__SWR|__SNBF, STDERR_FILENO),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080088};
Elliott Hughesf0141df2015-10-12 12:44:23 -070089
Elliott Hughes168667c2014-11-14 14:42:59 -080090FILE* stdin = &__sF[0];
91FILE* stdout = &__sF[1];
92FILE* stderr = &__sF[2];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080093
Elliott Hughesbb46afd2015-12-04 18:03:12 -080094struct glue __sglue = { NULL, 3, __sF };
95static struct glue* lastglue = &__sglue;
96
Elliott Hughes2704bd12016-01-20 17:14:53 -080097class ScopedFileLock {
98 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -070099 explicit ScopedFileLock(FILE* fp) : fp_(fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800100 FLOCKFILE(fp_);
101 }
102 ~ScopedFileLock() {
103 FUNLOCKFILE(fp_);
104 }
105
106 private:
107 FILE* fp_;
108};
109
Elliott Hughes021335e2016-01-19 16:28:15 -0800110static glue* moreglue(int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800111 static FILE empty;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800112
Elliott Hughes2704bd12016-01-20 17:14:53 -0800113 char* data = new char[sizeof(glue) + ALIGNBYTES + n * sizeof(FILE) + n * sizeof(__sfileext)];
114 if (data == nullptr) return nullptr;
Elliott Hughes021335e2016-01-19 16:28:15 -0800115
Elliott Hughes2704bd12016-01-20 17:14:53 -0800116 glue* g = reinterpret_cast<glue*>(data);
117 FILE* p = reinterpret_cast<FILE*>(ALIGN(data + sizeof(*g)));
118 __sfileext* pext = reinterpret_cast<__sfileext*>(ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
119 g->next = NULL;
120 g->niobs = n;
121 g->iobs = p;
122 while (--n >= 0) {
123 *p = empty;
124 _FILEEXT_SETUP(p, pext);
125 p++;
126 pext++;
127 }
128 return g;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800129}
130
Elliott Hughes80e4c152017-07-21 13:57:55 -0700131static inline void free_fgetln_buffer(FILE* fp) {
132 if (__predict_false(fp->_lb._base != nullptr)) {
133 free(fp->_lb._base);
134 fp->_lb._base = nullptr;
135 }
136}
137
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800138/*
139 * Find a free FILE for fopen et al.
140 */
Elliott Hughes021335e2016-01-19 16:28:15 -0800141FILE* __sfp(void) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800142 FILE *fp;
143 int n;
144 struct glue *g;
145
Kenny Rootf5823402011-02-12 07:13:44 -0800146 _THREAD_PRIVATE_MUTEX_LOCK(__sfp_mutex);
147 for (g = &__sglue; g != NULL; g = g->next) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800148 for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
149 if (fp->_flags == 0)
150 goto found;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800151 }
Kenny Rootf5823402011-02-12 07:13:44 -0800152
153 /* release lock while mallocing */
154 _THREAD_PRIVATE_MUTEX_UNLOCK(__sfp_mutex);
155 if ((g = moreglue(NDYNAMIC)) == NULL)
156 return (NULL);
157 _THREAD_PRIVATE_MUTEX_LOCK(__sfp_mutex);
158 lastglue->next = g;
159 lastglue = g;
160 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800161found:
162 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Kenny Rootf5823402011-02-12 07:13:44 -0800163 _THREAD_PRIVATE_MUTEX_UNLOCK(__sfp_mutex);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800164 fp->_p = NULL; /* no current pointer */
165 fp->_w = 0; /* nothing to read or write */
166 fp->_r = 0;
167 fp->_bf._base = NULL; /* no buffer */
168 fp->_bf._size = 0;
169 fp->_lbfsize = 0; /* not line buffered */
170 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800171
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800172 fp->_lb._base = NULL; /* no line buffer */
173 fp->_lb._size = 0;
174 _FILEEXT_INIT(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800175
176 // Caller sets cookie, _read/_write etc.
177 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
178 fp->_seek = nullptr;
179 _EXT(fp)->_seek64 = nullptr;
180
181 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800182}
183
Elliott Hughes021335e2016-01-19 16:28:15 -0800184extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800185 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
186 _fwalk(__sflush);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800187}
Elliott Hughes923f1652016-01-19 15:46:05 -0800188
Elliott Hughes023c3072016-01-22 15:04:51 -0800189static FILE* __fopen(int fd, int flags) {
190#if !defined(__LP64__)
191 if (fd > SHRT_MAX) {
192 errno = EMFILE;
193 return nullptr;
194 }
195#endif
196
197 FILE* fp = __sfp();
198 if (fp != nullptr) {
199 fp->_file = fd;
200 fp->_flags = flags;
201 fp->_cookie = fp;
202 fp->_read = __sread;
203 fp->_write = __swrite;
204 fp->_close = __sclose;
205 _EXT(fp)->_seek64 = __sseek64;
206 }
207 return fp;
208}
209
210FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700211 int mode_flags;
212 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800213 if (flags == 0) return nullptr;
214
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700215 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800216 if (fd == -1) {
217 return nullptr;
218 }
219
220 FILE* fp = __fopen(fd, flags);
221 if (fp == nullptr) {
222 ErrnoRestorer errno_restorer;
223 close(fd);
224 return nullptr;
225 }
226
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700227 // For append mode, even though we use O_APPEND, we need to seek to the end now.
228 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800229 return fp;
230}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800231__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800232
233FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700234 int mode_flags;
235 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800236 if (flags == 0) return nullptr;
237
238 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700239 int fd_flags = fcntl(fd, F_GETFL, 0);
240 if (fd_flags == -1) return nullptr;
241 int tmp = fd_flags & O_ACCMODE;
242 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800243 errno = EINVAL;
244 return nullptr;
245 }
246
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700247 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
248 // POSIX says we just take the current offset of the underlying fd.
249 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
250 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
251 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800252
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700253 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'x'.
254 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800255 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
256 }
257
258 return __fopen(fd, flags);
259}
260
261// Re-direct an existing, open (probably) file to some other file.
262// ANSI is written such that the original file gets closed if at
263// all possible, no matter what.
264// TODO: rewrite this mess completely.
265FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700266 CHECK_FP(fp);
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700267 int mode_flags;
268 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800269 if (flags == 0) {
270 fclose(fp);
271 return nullptr;
272 }
273
274 ScopedFileLock sfl(fp);
275
276 // There are actually programs that depend on being able to "freopen"
277 // descriptors that weren't originally open. Keep this from breaking.
278 // Remember whether the stream was open to begin with, and which file
279 // descriptor (if any) was associated with it. If it was attached to
280 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
281 // should work. This is unnecessary if it was not a Unix file.
282 int isopen, wantfd;
283 if (fp->_flags == 0) {
284 fp->_flags = __SEOF; // Hold on to it.
285 isopen = 0;
286 wantfd = -1;
287 } else {
288 // Flush the stream; ANSI doesn't require this.
289 if (fp->_flags & __SWR) __sflush(fp);
290
291 // If close is NULL, closing is a no-op, hence pointless.
292 isopen = fp->_close != NULL;
293 if ((wantfd = fp->_file) < 0 && isopen) {
294 (*fp->_close)(fp->_cookie);
295 isopen = 0;
296 }
297 }
298
299 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700300 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800301 if (fd < 0 && isopen) {
302 // If out of fd's close the old one and try again.
303 if (errno == ENFILE || errno == EMFILE) {
304 (*fp->_close)(fp->_cookie);
305 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700306 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800307 }
308 }
309
310 int sverrno = errno;
311
312 // Finish closing fp. Even if the open succeeded above, we cannot
313 // keep fp->_base: it may be the wrong size. This loses the effect
314 // of any setbuffer calls, but stdio has always done this before.
315 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
316 if (fp->_flags & __SMBF) free(fp->_bf._base);
317 fp->_w = 0;
318 fp->_r = 0;
319 fp->_p = NULL;
320 fp->_bf._base = NULL;
321 fp->_bf._size = 0;
322 fp->_lbfsize = 0;
323 if (HASUB(fp)) FREEUB(fp);
324 _UB(fp)._size = 0;
325 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700326 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800327 fp->_lb._size = 0;
328
329 if (fd < 0) { // Did not get it after all.
330 fp->_flags = 0; // Release.
331 errno = sverrno; // Restore errno in case _close clobbered it.
332 return nullptr;
333 }
334
335 // If reopening something that was open before on a real file, try
336 // to maintain the descriptor. Various C library routines (perror)
337 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
338 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700339 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800340 close(fd);
341 fd = wantfd;
342 }
343 }
344
345 // _file is only a short.
346 if (fd > SHRT_MAX) {
347 fp->_flags = 0; // Release.
348 errno = EMFILE;
349 return nullptr;
350 }
351
352 fp->_flags = flags;
353 fp->_file = fd;
354 fp->_cookie = fp;
355 fp->_read = __sread;
356 fp->_write = __swrite;
357 fp->_close = __sclose;
358 _EXT(fp)->_seek64 = __sseek64;
359
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700360 // For append mode, even though we use O_APPEND, we need to seek to the end now.
361 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800362 return fp;
363}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800364__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800365
Elliott Hughes923f1652016-01-19 15:46:05 -0800366int fclose(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700367 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800368 if (fp->_flags == 0) {
369 // Already freed!
370 errno = EBADF;
371 return EOF;
372 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800373
Elliott Hughes2704bd12016-01-20 17:14:53 -0800374 ScopedFileLock sfl(fp);
375 WCIO_FREE(fp);
376 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
377 if (fp->_close != NULL && (*fp->_close)(fp->_cookie) < 0) {
378 r = EOF;
379 }
380 if (fp->_flags & __SMBF) free(fp->_bf._base);
381 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700382 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800383
Elliott Hughes2704bd12016-01-20 17:14:53 -0800384 // Poison this FILE so accesses after fclose will be obvious.
385 fp->_file = -1;
386 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800387
Elliott Hughes2704bd12016-01-20 17:14:53 -0800388 // Release this FILE for reuse.
389 fp->_flags = 0;
390 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800391}
392
Elliott Hughescceaf062016-07-29 16:31:52 -0700393int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700394 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700395 int fd = fp->_file;
396 if (fd == -1) {
397 errno = EBADF;
398 return -1;
399 }
400 return fd;
401}
402
Elliott Hughes923f1652016-01-19 15:46:05 -0800403int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700404 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800405 ScopedFileLock sfl(fp);
406 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800407}
Elliott Hughes021335e2016-01-19 16:28:15 -0800408
Elliott Hughescceaf062016-07-29 16:31:52 -0700409void clearerr_unlocked(FILE* fp) {
410 return __sclearerr(fp);
411}
412
413void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700414 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700415 ScopedFileLock sfl(fp);
416 clearerr_unlocked(fp);
417}
418
419int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700420 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700421 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700422}
423
424int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700425 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700426 ScopedFileLock sfl(fp);
427 return feof_unlocked(fp);
428}
429
430int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700431 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700432 return __sferror(fp);
433}
434
435int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700436 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700437 ScopedFileLock sfl(fp);
438 return ferror_unlocked(fp);
439}
440
Elliott Hughes021335e2016-01-19 16:28:15 -0800441int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800442 FILE* fp = reinterpret_cast<FILE*>(cookie);
443 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800444}
445
446int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800447 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800448 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800449}
450
Elliott Hughes021335e2016-01-19 16:28:15 -0800451fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800452 FILE* fp = reinterpret_cast<FILE*>(cookie);
453 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800454}
455
Elliott Hughes023c3072016-01-22 15:04:51 -0800456off64_t __sseek64(void* cookie, off64_t offset, int whence) {
457 FILE* fp = reinterpret_cast<FILE*>(cookie);
458 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
459}
460
Elliott Hughes021335e2016-01-19 16:28:15 -0800461int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800462 FILE* fp = reinterpret_cast<FILE*>(cookie);
463 return close(fp->_file);
464}
465
Elliott Hughes023c3072016-01-22 15:04:51 -0800466static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
467 // Use `_seek64` if set, but fall back to `_seek`.
468 if (_EXT(fp)->_seek64 != nullptr) {
469 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
470 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800471 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
472#if !defined(__LP64__)
473 // Avoid sign extension if off64_t is larger than off_t.
474 if (result != -1) result &= 0xffffffff;
475#endif
476 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800477 } else {
478 errno = ESPIPE;
479 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800480 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800481}
482
Elliott Hughes9677fab2016-01-25 15:50:59 -0800483static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800484 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800485 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700486
Elliott Hughes9677fab2016-01-25 15:50:59 -0800487 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800488 if (result == -1) {
489 return -1;
490 }
491
492 if (fp->_flags & __SRD) {
493 // Reading. Any unread characters (including
494 // those from ungetc) cause the position to be
495 // smaller than that in the underlying object.
496 result -= fp->_r;
497 if (HASUB(fp)) result -= fp->_ur;
498 } else if (fp->_flags & __SWR && fp->_p != NULL) {
499 // Writing. Any buffered characters cause the
500 // position to be greater than that in the
501 // underlying object.
502 result += fp->_p - fp->_bf._base;
503 }
504 return result;
505}
506
Elliott Hughes9677fab2016-01-25 15:50:59 -0800507int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800508 ScopedFileLock sfl(fp);
509
Elliott Hughes023c3072016-01-22 15:04:51 -0800510 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800511 // After this, whence is either SEEK_SET or SEEK_END.
512 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800513 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800514 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800515 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800516 }
517 offset += current_offset;
518 whence = SEEK_SET;
519 } else if (whence != SEEK_SET && whence != SEEK_END) {
520 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800521 return -1;
522 }
523
524 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
525 if (off_t_bits == 32 && offset > LONG_MAX) {
526 errno = EOVERFLOW;
527 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800528 }
529
530 if (fp->_bf._base == NULL) __smakebuf(fp);
531
532 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800533 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800534 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800535 }
536
537 // Success: clear EOF indicator and discard ungetc() data.
538 if (HASUB(fp)) FREEUB(fp);
539 fp->_p = fp->_bf._base;
540 fp->_r = 0;
541 /* fp->_w = 0; */ /* unnecessary (I think...) */
542 fp->_flags &= ~__SEOF;
543 return 0;
544}
545
Elliott Hughes9677fab2016-01-25 15:50:59 -0800546int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700547 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800548 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
549 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
550}
551__strong_alias(fseek, fseeko);
552
553int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700554 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800555 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800556}
557
Elliott Hughes9677fab2016-01-25 15:50:59 -0800558int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700559 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800560 return fseeko(fp, *pos, SEEK_SET);
561}
562
563int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700564 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800565 return fseeko64(fp, *pos, SEEK_SET);
566}
567
Elliott Hughes2704bd12016-01-20 17:14:53 -0800568off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700569 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800570 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
571 off64_t result = ftello64(fp);
572 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800573 errno = EOVERFLOW;
574 return -1;
575 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800576 return result;
577}
578__strong_alias(ftell, ftello);
579
580off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700581 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800582 ScopedFileLock sfl(fp);
583 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800584}
Elliott Hughes023c3072016-01-22 15:04:51 -0800585
Elliott Hughes023c3072016-01-22 15:04:51 -0800586int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700587 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800588 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800589 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800590}
591
Elliott Hughes9677fab2016-01-25 15:50:59 -0800592int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700593 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800594 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800595 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800596}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800597
598static FILE* __funopen(const void* cookie,
599 int (*read_fn)(void*, char*, int),
600 int (*write_fn)(void*, const char*, int),
601 int (*close_fn)(void*)) {
602 if (read_fn == nullptr && write_fn == nullptr) {
603 errno = EINVAL;
604 return nullptr;
605 }
606
607 FILE* fp = __sfp();
608 if (fp == nullptr) return nullptr;
609
610 if (read_fn != nullptr && write_fn != nullptr) {
611 fp->_flags = __SRW;
612 } else if (read_fn != nullptr) {
613 fp->_flags = __SRD;
614 } else if (write_fn != nullptr) {
615 fp->_flags = __SWR;
616 }
617
618 fp->_file = -1;
619 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
620 fp->_read = read_fn;
621 fp->_write = write_fn;
622 fp->_close = close_fn;
623
624 return fp;
625}
626
627FILE* funopen(const void* cookie,
628 int (*read_fn)(void*, char*, int),
629 int (*write_fn)(void*, const char*, int),
630 fpos_t (*seek_fn)(void*, fpos_t, int),
631 int (*close_fn)(void*)) {
632 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
633 if (fp != nullptr) {
634 fp->_seek = seek_fn;
635 }
636 return fp;
637}
638
639FILE* funopen64(const void* cookie,
640 int (*read_fn)(void*, char*, int),
641 int (*write_fn)(void*, const char*, int),
642 fpos64_t (*seek_fn)(void*, fpos64_t, int),
643 int (*close_fn)(void*)) {
644 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
645 if (fp != nullptr) {
646 _EXT(fp)->_seek64 = seek_fn;
647 }
648 return fp;
649}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700650
Elliott Hughes53cf3482016-08-09 13:06:41 -0700651int asprintf(char** s, const char* fmt, ...) {
652 PRINTF_IMPL(vasprintf(s, fmt, ap));
653}
654
Elliott Hughes20788ae2016-06-09 15:16:32 -0700655char* ctermid(char* s) {
656 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
657}
Elliott Hughescceaf062016-07-29 16:31:52 -0700658
Elliott Hughes70715da2016-08-01 16:35:17 -0700659int dprintf(int fd, const char* fmt, ...) {
660 PRINTF_IMPL(vdprintf(fd, fmt, ap));
661}
662
663int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700664 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700665 PRINTF_IMPL(vfprintf(fp, fmt, ap));
666}
667
Elliott Hughescceaf062016-07-29 16:31:52 -0700668int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700669 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700670 return getc(fp);
671}
672
673int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700674 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700675 return putc(c, fp);
676}
677
Elliott Hughes70715da2016-08-01 16:35:17 -0700678int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700679 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700680 PRINTF_IMPL(vfscanf(fp, fmt, ap));
681}
682
683int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700684 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700685 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
686}
687
688int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700689 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700690 PRINTF_IMPL(vfwscanf(fp, fmt, ap));
691}
692
693int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700694 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700695 ScopedFileLock sfl(fp);
696 return getc_unlocked(fp);
697}
698
699int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700700 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700701 return __sgetc(fp);
702}
703
704int getchar_unlocked() {
705 return getc_unlocked(stdin);
706}
707
708int getchar() {
709 return getc(stdin);
710}
711
Elliott Hughescceaf062016-07-29 16:31:52 -0700712ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700713 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700714 return getdelim(buf, len, '\n', fp);
715}
716
717wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700718 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700719 return fgetwc(fp);
720}
721
722wint_t getwchar() {
723 return fgetwc(stdin);
724}
725
Elliott Hughes70715da2016-08-01 16:35:17 -0700726int printf(const char* fmt, ...) {
727 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
728}
729
730int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700731 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700732 ScopedFileLock sfl(fp);
733 return putc_unlocked(c, fp);
734}
735
736int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700737 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700738 if (cantwrite(fp)) {
739 errno = EBADF;
740 return EOF;
741 }
742 _SET_ORIENTATION(fp, -1);
743 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
744 return (*fp->_p++ = c);
745 }
746 return (__swbuf(c, fp));
747}
748
749int putchar(int c) {
750 return putc(c, stdout);
751}
752
753int putchar_unlocked(int c) {
754 return putc_unlocked(c, stdout);
755}
756
Elliott Hughescceaf062016-07-29 16:31:52 -0700757wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700758 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700759 return fputwc(wc, fp);
760}
761
762wint_t putwchar(wchar_t wc) {
763 return fputwc(wc, stdout);
764}
765
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700766int remove(const char* path) {
767 if (unlink(path) != -1) return 0;
768 if (errno != EISDIR) return -1;
769 return rmdir(path);
770}
771
Elliott Hughescceaf062016-07-29 16:31:52 -0700772void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700773 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700774 ScopedFileLock sfl(fp);
775 fseek(fp, 0, SEEK_SET);
776 clearerr_unlocked(fp);
777}
778
Elliott Hughes70715da2016-08-01 16:35:17 -0700779int scanf(const char* fmt, ...) {
780 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
781}
782
Elliott Hughescceaf062016-07-29 16:31:52 -0700783void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -0700784 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700785 setbuffer(fp, buf, BUFSIZ);
786}
787
788void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -0700789 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700790 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
791}
792
793int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700794 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700795 return setvbuf(fp, nullptr, _IOLBF, 0);
796}
797
Elliott Hughes53cf3482016-08-09 13:06:41 -0700798int snprintf(char* s, size_t n, const char* fmt, ...) {
799 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
800}
801
802int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700803 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -0700804}
805
806int sscanf(const char* s, const char* fmt, ...) {
807 PRINTF_IMPL(vsscanf(s, fmt, ap));
808}
809
Elliott Hughes70715da2016-08-01 16:35:17 -0700810int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
811 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
812}
813
814int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
815 PRINTF_IMPL(vswscanf(s, fmt, ap));
816}
817
Elliott Hughescceaf062016-07-29 16:31:52 -0700818int vprintf(const char* fmt, va_list ap) {
819 return vfprintf(stdout, fmt, ap);
820}
821
822int vscanf(const char* fmt, va_list ap) {
823 return vfscanf(stdin, fmt, ap);
824}
825
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700826int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
827 // stdio internals use int rather than size_t.
828 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
829
830 __check_count("vsnprintf", "size", n);
831
832 // Stdio internals do not deal correctly with zero length buffer.
833 char dummy;
834 if (n == 0) {
835 s = &dummy;
836 n = 1;
837 }
838
839 FILE f;
840 __sfileext fext;
841 _FILEEXT_SETUP(&f, &fext);
842 f._file = -1;
843 f._flags = __SWR | __SSTR;
844 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
845 f._bf._size = f._w = n - 1;
846
847 int result = __vfprintf(&f, fmt, ap);
848 *f._p = '\0';
849 return result;
850}
851
Elliott Hughes53cf3482016-08-09 13:06:41 -0700852int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700853 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -0700854}
855
Elliott Hughescceaf062016-07-29 16:31:52 -0700856int vwprintf(const wchar_t* fmt, va_list ap) {
857 return vfwprintf(stdout, fmt, ap);
858}
859
860int vwscanf(const wchar_t* fmt, va_list ap) {
861 return vfwscanf(stdin, fmt, ap);
862}
Elliott Hughes70715da2016-08-01 16:35:17 -0700863
864int wprintf(const wchar_t* fmt, ...) {
865 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
866}
867
868int wscanf(const wchar_t* fmt, ...) {
869 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
870}
Dan Albert3037ea42016-10-06 15:46:45 -0700871
872namespace {
873
874namespace phony {
875#include <bits/struct_file.h>
876}
877
878static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
879 "size mismatch between `struct __sFILE` implementation and public stub");
880static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
881 "alignment mismatch between `struct __sFILE` implementation and public stub");
882
883}