blob: d3ac0436e03efa8bbfdc5430f2a7e38938509bf5 [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 Hughes37ad9592017-10-30 17:47:12 -070094struct glue __sglue = { nullptr, 3, __sF };
Elliott Hughesbb46afd2015-12-04 18:03:12 -080095static 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));
Elliott Hughes37ad9592017-10-30 17:47:12 -0700119 g->next = nullptr;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800120 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);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700147 for (g = &__sglue; g != nullptr; 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);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700155 if ((g = moreglue(NDYNAMIC)) == nullptr) return nullptr;
Kenny Rootf5823402011-02-12 07:13:44 -0800156 _THREAD_PRIVATE_MUTEX_LOCK(__sfp_mutex);
157 lastglue->next = g;
158 lastglue = g;
159 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800160found:
161 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Kenny Rootf5823402011-02-12 07:13:44 -0800162 _THREAD_PRIVATE_MUTEX_UNLOCK(__sfp_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700163 fp->_p = nullptr; /* no current pointer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800164 fp->_w = 0; /* nothing to read or write */
165 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700166 fp->_bf._base = nullptr; /* no buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800167 fp->_bf._size = 0;
168 fp->_lbfsize = 0; /* not line buffered */
169 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800170
Elliott Hughes37ad9592017-10-30 17:47:12 -0700171 fp->_lb._base = nullptr; /* no line buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800172 fp->_lb._size = 0;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800173
174 memset(_EXT(fp), 0, sizeof(struct __sfileext));
175 _FLOCK(fp) = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
176 _EXT(fp)->_caller_handles_locking = false;
Elliott Hughes023c3072016-01-22 15:04:51 -0800177
178 // Caller sets cookie, _read/_write etc.
179 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
180 fp->_seek = nullptr;
181 _EXT(fp)->_seek64 = nullptr;
182
183 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800184}
185
Elliott Hughes021335e2016-01-19 16:28:15 -0800186extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800187 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
188 _fwalk(__sflush);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800189}
Elliott Hughes923f1652016-01-19 15:46:05 -0800190
Elliott Hughes023c3072016-01-22 15:04:51 -0800191static FILE* __fopen(int fd, int flags) {
192#if !defined(__LP64__)
193 if (fd > SHRT_MAX) {
194 errno = EMFILE;
195 return nullptr;
196 }
197#endif
198
199 FILE* fp = __sfp();
200 if (fp != nullptr) {
201 fp->_file = fd;
202 fp->_flags = flags;
203 fp->_cookie = fp;
204 fp->_read = __sread;
205 fp->_write = __swrite;
206 fp->_close = __sclose;
207 _EXT(fp)->_seek64 = __sseek64;
208 }
209 return fp;
210}
211
212FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700213 int mode_flags;
214 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800215 if (flags == 0) return nullptr;
216
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700217 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800218 if (fd == -1) {
219 return nullptr;
220 }
221
222 FILE* fp = __fopen(fd, flags);
223 if (fp == nullptr) {
224 ErrnoRestorer errno_restorer;
225 close(fd);
226 return nullptr;
227 }
228
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700229 // For append mode, even though we use O_APPEND, we need to seek to the end now.
230 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800231 return fp;
232}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800233__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800234
235FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700236 int mode_flags;
237 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800238 if (flags == 0) return nullptr;
239
240 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700241 int fd_flags = fcntl(fd, F_GETFL, 0);
242 if (fd_flags == -1) return nullptr;
243 int tmp = fd_flags & O_ACCMODE;
244 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800245 errno = EINVAL;
246 return nullptr;
247 }
248
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700249 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
250 // POSIX says we just take the current offset of the underlying fd.
251 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
252 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
253 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800254
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700255 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'x'.
256 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800257 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
258 }
259
260 return __fopen(fd, flags);
261}
262
263// Re-direct an existing, open (probably) file to some other file.
264// ANSI is written such that the original file gets closed if at
265// all possible, no matter what.
266// TODO: rewrite this mess completely.
267FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700268 CHECK_FP(fp);
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700269 int mode_flags;
270 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800271 if (flags == 0) {
272 fclose(fp);
273 return nullptr;
274 }
275
276 ScopedFileLock sfl(fp);
277
278 // There are actually programs that depend on being able to "freopen"
279 // descriptors that weren't originally open. Keep this from breaking.
280 // Remember whether the stream was open to begin with, and which file
281 // descriptor (if any) was associated with it. If it was attached to
282 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
283 // should work. This is unnecessary if it was not a Unix file.
284 int isopen, wantfd;
285 if (fp->_flags == 0) {
286 fp->_flags = __SEOF; // Hold on to it.
287 isopen = 0;
288 wantfd = -1;
289 } else {
290 // Flush the stream; ANSI doesn't require this.
291 if (fp->_flags & __SWR) __sflush(fp);
292
Elliott Hughes37ad9592017-10-30 17:47:12 -0700293 // If close is null, closing is a no-op, hence pointless.
294 isopen = (fp->_close != nullptr);
Elliott Hughes023c3072016-01-22 15:04:51 -0800295 if ((wantfd = fp->_file) < 0 && isopen) {
296 (*fp->_close)(fp->_cookie);
297 isopen = 0;
298 }
299 }
300
301 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700302 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800303 if (fd < 0 && isopen) {
304 // If out of fd's close the old one and try again.
305 if (errno == ENFILE || errno == EMFILE) {
306 (*fp->_close)(fp->_cookie);
307 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700308 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800309 }
310 }
311
312 int sverrno = errno;
313
314 // Finish closing fp. Even if the open succeeded above, we cannot
315 // keep fp->_base: it may be the wrong size. This loses the effect
316 // of any setbuffer calls, but stdio has always done this before.
317 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
318 if (fp->_flags & __SMBF) free(fp->_bf._base);
319 fp->_w = 0;
320 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700321 fp->_p = nullptr;
322 fp->_bf._base = nullptr;
Elliott Hughes023c3072016-01-22 15:04:51 -0800323 fp->_bf._size = 0;
324 fp->_lbfsize = 0;
325 if (HASUB(fp)) FREEUB(fp);
326 _UB(fp)._size = 0;
327 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700328 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800329 fp->_lb._size = 0;
330
331 if (fd < 0) { // Did not get it after all.
332 fp->_flags = 0; // Release.
333 errno = sverrno; // Restore errno in case _close clobbered it.
334 return nullptr;
335 }
336
337 // If reopening something that was open before on a real file, try
338 // to maintain the descriptor. Various C library routines (perror)
339 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
340 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700341 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800342 close(fd);
343 fd = wantfd;
344 }
345 }
346
347 // _file is only a short.
348 if (fd > SHRT_MAX) {
349 fp->_flags = 0; // Release.
350 errno = EMFILE;
351 return nullptr;
352 }
353
354 fp->_flags = flags;
355 fp->_file = fd;
356 fp->_cookie = fp;
357 fp->_read = __sread;
358 fp->_write = __swrite;
359 fp->_close = __sclose;
360 _EXT(fp)->_seek64 = __sseek64;
361
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700362 // For append mode, even though we use O_APPEND, we need to seek to the end now.
363 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800364 return fp;
365}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800366__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800367
Elliott Hughes923f1652016-01-19 15:46:05 -0800368int fclose(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700369 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800370 if (fp->_flags == 0) {
371 // Already freed!
372 errno = EBADF;
373 return EOF;
374 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800375
Elliott Hughes2704bd12016-01-20 17:14:53 -0800376 ScopedFileLock sfl(fp);
377 WCIO_FREE(fp);
378 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700379 if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800380 r = EOF;
381 }
382 if (fp->_flags & __SMBF) free(fp->_bf._base);
383 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700384 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800385
Elliott Hughes2704bd12016-01-20 17:14:53 -0800386 // Poison this FILE so accesses after fclose will be obvious.
387 fp->_file = -1;
388 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800389
Elliott Hughes2704bd12016-01-20 17:14:53 -0800390 // Release this FILE for reuse.
391 fp->_flags = 0;
392 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800393}
394
Elliott Hughescceaf062016-07-29 16:31:52 -0700395int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700396 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700397 int fd = fp->_file;
398 if (fd == -1) {
399 errno = EBADF;
400 return -1;
401 }
402 return fd;
403}
404
Elliott Hughes923f1652016-01-19 15:46:05 -0800405int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700406 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800407 ScopedFileLock sfl(fp);
408 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800409}
Elliott Hughes021335e2016-01-19 16:28:15 -0800410
Elliott Hughescceaf062016-07-29 16:31:52 -0700411void clearerr_unlocked(FILE* fp) {
412 return __sclearerr(fp);
413}
414
415void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700416 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700417 ScopedFileLock sfl(fp);
418 clearerr_unlocked(fp);
419}
420
421int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700422 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700423 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700424}
425
426int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700427 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700428 ScopedFileLock sfl(fp);
429 return feof_unlocked(fp);
430}
431
432int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700433 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700434 return __sferror(fp);
435}
436
437int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700438 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700439 ScopedFileLock sfl(fp);
440 return ferror_unlocked(fp);
441}
442
Elliott Hughes37ad9592017-10-30 17:47:12 -0700443int __sflush(FILE* fp) {
444 // Flushing a read-only file is a no-op.
445 if ((fp->_flags & __SWR) == 0) return 0;
446
447 // Flushing a file without a buffer is a no-op.
448 unsigned char* p = fp->_bf._base;
449 if (p == nullptr) return 0;
450
451 // Set these immediately to avoid problems with longjmp and to allow
452 // exchange buffering (via setvbuf) in user write function.
453 int n = fp->_p - p;
454 fp->_p = p;
455 fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
456
457 while (n > 0) {
458 int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
459 if (written <= 0) {
460 fp->_flags |= __SERR;
461 return EOF;
462 }
463 n -= written, p += written;
464 }
465 return 0;
466}
467
468int __sflush_locked(FILE* fp) {
469 ScopedFileLock sfl(fp);
470 return __sflush(fp);
471}
472
Elliott Hughes021335e2016-01-19 16:28:15 -0800473int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800474 FILE* fp = reinterpret_cast<FILE*>(cookie);
475 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800476}
477
478int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800479 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800480 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800481}
482
Elliott Hughes021335e2016-01-19 16:28:15 -0800483fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800484 FILE* fp = reinterpret_cast<FILE*>(cookie);
485 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800486}
487
Elliott Hughes023c3072016-01-22 15:04:51 -0800488off64_t __sseek64(void* cookie, off64_t offset, int whence) {
489 FILE* fp = reinterpret_cast<FILE*>(cookie);
490 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
491}
492
Elliott Hughes021335e2016-01-19 16:28:15 -0800493int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800494 FILE* fp = reinterpret_cast<FILE*>(cookie);
495 return close(fp->_file);
496}
497
Elliott Hughes023c3072016-01-22 15:04:51 -0800498static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
499 // Use `_seek64` if set, but fall back to `_seek`.
500 if (_EXT(fp)->_seek64 != nullptr) {
501 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
502 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800503 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
504#if !defined(__LP64__)
505 // Avoid sign extension if off64_t is larger than off_t.
506 if (result != -1) result &= 0xffffffff;
507#endif
508 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800509 } else {
510 errno = ESPIPE;
511 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800512 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800513}
514
Elliott Hughes9677fab2016-01-25 15:50:59 -0800515static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800516 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800517 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700518
Elliott Hughes9677fab2016-01-25 15:50:59 -0800519 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800520 if (result == -1) {
521 return -1;
522 }
523
524 if (fp->_flags & __SRD) {
525 // Reading. Any unread characters (including
526 // those from ungetc) cause the position to be
527 // smaller than that in the underlying object.
528 result -= fp->_r;
529 if (HASUB(fp)) result -= fp->_ur;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700530 } else if (fp->_flags & __SWR && fp->_p != nullptr) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800531 // Writing. Any buffered characters cause the
532 // position to be greater than that in the
533 // underlying object.
534 result += fp->_p - fp->_bf._base;
535 }
536 return result;
537}
538
Elliott Hughes9677fab2016-01-25 15:50:59 -0800539int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800540 ScopedFileLock sfl(fp);
541
Elliott Hughes023c3072016-01-22 15:04:51 -0800542 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800543 // After this, whence is either SEEK_SET or SEEK_END.
544 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800545 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800546 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800547 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800548 }
549 offset += current_offset;
550 whence = SEEK_SET;
551 } else if (whence != SEEK_SET && whence != SEEK_END) {
552 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800553 return -1;
554 }
555
556 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
557 if (off_t_bits == 32 && offset > LONG_MAX) {
558 errno = EOVERFLOW;
559 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800560 }
561
Elliott Hughes37ad9592017-10-30 17:47:12 -0700562 if (fp->_bf._base == nullptr) __smakebuf(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800563
564 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800565 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800566 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800567 }
568
569 // Success: clear EOF indicator and discard ungetc() data.
570 if (HASUB(fp)) FREEUB(fp);
571 fp->_p = fp->_bf._base;
572 fp->_r = 0;
573 /* fp->_w = 0; */ /* unnecessary (I think...) */
574 fp->_flags &= ~__SEOF;
575 return 0;
576}
577
Elliott Hughes9677fab2016-01-25 15:50:59 -0800578int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700579 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800580 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
581 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
582}
583__strong_alias(fseek, fseeko);
584
585int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700586 CHECK_FP(fp);
Ryan Prichardbf549862017-11-07 15:30:32 -0800587 return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800588}
589
Elliott Hughes9677fab2016-01-25 15:50:59 -0800590int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700591 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800592 return fseeko(fp, *pos, SEEK_SET);
593}
594
595int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700596 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800597 return fseeko64(fp, *pos, SEEK_SET);
598}
599
Elliott Hughes2704bd12016-01-20 17:14:53 -0800600off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700601 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800602 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
603 off64_t result = ftello64(fp);
604 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800605 errno = EOVERFLOW;
606 return -1;
607 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800608 return result;
609}
610__strong_alias(ftell, ftello);
611
612off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700613 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800614 ScopedFileLock sfl(fp);
615 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800616}
Elliott Hughes023c3072016-01-22 15:04:51 -0800617
Elliott Hughes023c3072016-01-22 15:04:51 -0800618int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700619 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800620 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800621 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800622}
623
Elliott Hughes9677fab2016-01-25 15:50:59 -0800624int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700625 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800626 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800627 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800628}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800629
630static FILE* __funopen(const void* cookie,
631 int (*read_fn)(void*, char*, int),
632 int (*write_fn)(void*, const char*, int),
633 int (*close_fn)(void*)) {
634 if (read_fn == nullptr && write_fn == nullptr) {
635 errno = EINVAL;
636 return nullptr;
637 }
638
639 FILE* fp = __sfp();
640 if (fp == nullptr) return nullptr;
641
642 if (read_fn != nullptr && write_fn != nullptr) {
643 fp->_flags = __SRW;
644 } else if (read_fn != nullptr) {
645 fp->_flags = __SRD;
646 } else if (write_fn != nullptr) {
647 fp->_flags = __SWR;
648 }
649
650 fp->_file = -1;
651 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
652 fp->_read = read_fn;
653 fp->_write = write_fn;
654 fp->_close = close_fn;
655
656 return fp;
657}
658
659FILE* funopen(const void* cookie,
660 int (*read_fn)(void*, char*, int),
661 int (*write_fn)(void*, const char*, int),
662 fpos_t (*seek_fn)(void*, fpos_t, int),
663 int (*close_fn)(void*)) {
664 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
665 if (fp != nullptr) {
666 fp->_seek = seek_fn;
667 }
668 return fp;
669}
670
671FILE* funopen64(const void* cookie,
672 int (*read_fn)(void*, char*, int),
673 int (*write_fn)(void*, const char*, int),
674 fpos64_t (*seek_fn)(void*, fpos64_t, int),
675 int (*close_fn)(void*)) {
676 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
677 if (fp != nullptr) {
678 _EXT(fp)->_seek64 = seek_fn;
679 }
680 return fp;
681}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700682
Elliott Hughes53cf3482016-08-09 13:06:41 -0700683int asprintf(char** s, const char* fmt, ...) {
684 PRINTF_IMPL(vasprintf(s, fmt, ap));
685}
686
Elliott Hughes20788ae2016-06-09 15:16:32 -0700687char* ctermid(char* s) {
688 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
689}
Elliott Hughescceaf062016-07-29 16:31:52 -0700690
Elliott Hughes70715da2016-08-01 16:35:17 -0700691int dprintf(int fd, const char* fmt, ...) {
692 PRINTF_IMPL(vdprintf(fd, fmt, ap));
693}
694
695int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700696 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700697 PRINTF_IMPL(vfprintf(fp, fmt, ap));
698}
699
Elliott Hughescceaf062016-07-29 16:31:52 -0700700int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700701 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700702 return getc(fp);
703}
704
Elliott Hughes37ad9592017-10-30 17:47:12 -0700705int fgetc_unlocked(FILE* fp) {
706 CHECK_FP(fp);
707 return getc_unlocked(fp);
708}
709
710/*
711 * Read at most n-1 characters from the given file.
712 * Stop when a newline has been read, or the count runs out.
713 * Return first argument, or NULL if no characters were read.
714 * Do not return NULL if n == 1.
715 */
716char* fgets(char* buf, int n, FILE* fp) __overloadable {
717 CHECK_FP(fp);
718 ScopedFileLock sfl(fp);
719 return fgets_unlocked(buf, n, fp);
720}
721
722char* fgets_unlocked(char* buf, int n, FILE* fp) {
723 if (n <= 0) {
724 errno = EINVAL;
725 return nullptr;
726 }
727
728 _SET_ORIENTATION(fp, -1);
729
730 char* s = buf;
731 n--; // Leave space for NUL.
732 while (n != 0) {
733 // If the buffer is empty, refill it.
734 if (fp->_r <= 0) {
735 if (__srefill(fp)) {
736 // EOF/error: stop with partial or no line.
737 if (s == buf) return nullptr;
738 break;
739 }
740 }
741 size_t len = fp->_r;
742 unsigned char* p = fp->_p;
743
744 // Scan through at most n bytes of the current buffer,
745 // looking for '\n'. If found, copy up to and including
746 // newline, and stop. Otherwise, copy entire chunk and loop.
747 if (len > static_cast<size_t>(n)) len = n;
748 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
749 if (t != nullptr) {
750 len = ++t - p;
751 fp->_r -= len;
752 fp->_p = t;
753 memcpy(s, p, len);
754 s[len] = '\0';
755 return buf;
756 }
757 fp->_r -= len;
758 fp->_p += len;
759 memcpy(s, p, len);
760 s += len;
761 n -= len;
762 }
763 *s = '\0';
764 return buf;
765}
766
Elliott Hughescceaf062016-07-29 16:31:52 -0700767int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700768 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700769 return putc(c, fp);
770}
771
Elliott Hughes37ad9592017-10-30 17:47:12 -0700772int fputc_unlocked(int c, FILE* fp) {
773 CHECK_FP(fp);
774 return putc_unlocked(c, fp);
775}
776
777int fputs(const char* s, FILE* fp) {
778 CHECK_FP(fp);
779 ScopedFileLock sfl(fp);
780 return fputs_unlocked(s, fp);
781}
782
783int fputs_unlocked(const char* s, FILE* fp) {
784 CHECK_FP(fp);
785 size_t length = strlen(s);
786 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
787}
788
Elliott Hughes70715da2016-08-01 16:35:17 -0700789int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700790 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700791 PRINTF_IMPL(vfscanf(fp, fmt, ap));
792}
793
794int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700795 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700796 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
797}
798
799int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700800 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700801 PRINTF_IMPL(vfwscanf(fp, fmt, ap));
802}
803
804int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700805 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700806 ScopedFileLock sfl(fp);
807 return getc_unlocked(fp);
808}
809
810int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700811 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700812 return __sgetc(fp);
813}
814
815int getchar_unlocked() {
816 return getc_unlocked(stdin);
817}
818
819int getchar() {
820 return getc(stdin);
821}
822
Elliott Hughescceaf062016-07-29 16:31:52 -0700823ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700824 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700825 return getdelim(buf, len, '\n', fp);
826}
827
828wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700829 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700830 return fgetwc(fp);
831}
832
833wint_t getwchar() {
834 return fgetwc(stdin);
835}
836
Elliott Hughes37ad9592017-10-30 17:47:12 -0700837void perror(const char* msg) {
838 if (msg == nullptr) msg = "";
839 fprintf(stderr, "%s%s%s\n", msg, (*msg == '\0') ? "" : ": ", strerror(errno));
840}
841
Elliott Hughes70715da2016-08-01 16:35:17 -0700842int printf(const char* fmt, ...) {
843 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
844}
845
846int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700847 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700848 ScopedFileLock sfl(fp);
849 return putc_unlocked(c, fp);
850}
851
852int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700853 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700854 if (cantwrite(fp)) {
855 errno = EBADF;
856 return EOF;
857 }
858 _SET_ORIENTATION(fp, -1);
859 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
860 return (*fp->_p++ = c);
861 }
862 return (__swbuf(c, fp));
863}
864
865int putchar(int c) {
866 return putc(c, stdout);
867}
868
869int putchar_unlocked(int c) {
870 return putc_unlocked(c, stdout);
871}
872
Elliott Hughes37ad9592017-10-30 17:47:12 -0700873int puts(const char* s) {
874 size_t length = strlen(s);
875 ScopedFileLock sfl(stdout);
876 return (fwrite_unlocked(s, 1, length, stdout) == length &&
877 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
878}
879
Elliott Hughescceaf062016-07-29 16:31:52 -0700880wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700881 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700882 return fputwc(wc, fp);
883}
884
885wint_t putwchar(wchar_t wc) {
886 return fputwc(wc, stdout);
887}
888
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700889int remove(const char* path) {
890 if (unlink(path) != -1) return 0;
891 if (errno != EISDIR) return -1;
892 return rmdir(path);
893}
894
Elliott Hughescceaf062016-07-29 16:31:52 -0700895void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700896 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700897 ScopedFileLock sfl(fp);
898 fseek(fp, 0, SEEK_SET);
899 clearerr_unlocked(fp);
900}
901
Elliott Hughes70715da2016-08-01 16:35:17 -0700902int scanf(const char* fmt, ...) {
903 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
904}
905
Elliott Hughescceaf062016-07-29 16:31:52 -0700906void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -0700907 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700908 setbuffer(fp, buf, BUFSIZ);
909}
910
911void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -0700912 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700913 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
914}
915
916int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700917 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700918 return setvbuf(fp, nullptr, _IOLBF, 0);
919}
920
Elliott Hughes53cf3482016-08-09 13:06:41 -0700921int snprintf(char* s, size_t n, const char* fmt, ...) {
922 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
923}
924
925int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700926 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -0700927}
928
929int sscanf(const char* s, const char* fmt, ...) {
930 PRINTF_IMPL(vsscanf(s, fmt, ap));
931}
932
Elliott Hughes70715da2016-08-01 16:35:17 -0700933int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
934 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
935}
936
937int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
938 PRINTF_IMPL(vswscanf(s, fmt, ap));
939}
940
Elliott Hughes618303c2017-11-02 16:58:44 -0700941int vfprintf(FILE* fp, const char* fmt, va_list ap) {
942 ScopedFileLock sfl(fp);
943 return __vfprintf(fp, fmt, ap);
944}
945
Elliott Hughes345b7272017-11-10 16:20:43 -0800946int vfscanf(FILE* fp, const char* fmt, va_list ap) {
947 ScopedFileLock sfl(fp);
948 return __svfscanf(fp, fmt, ap);
949}
950
Elliott Hughes618303c2017-11-02 16:58:44 -0700951int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
952 ScopedFileLock sfl(fp);
953 return __vfwprintf(fp, fmt, ap);
954}
955
Elliott Hughes345b7272017-11-10 16:20:43 -0800956int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
957 ScopedFileLock sfl(fp);
958 return __vfwscanf(fp, fmt, ap);
959}
960
Elliott Hughescceaf062016-07-29 16:31:52 -0700961int vprintf(const char* fmt, va_list ap) {
962 return vfprintf(stdout, fmt, ap);
963}
964
965int vscanf(const char* fmt, va_list ap) {
966 return vfscanf(stdin, fmt, ap);
967}
968
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700969int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
970 // stdio internals use int rather than size_t.
971 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
972
973 __check_count("vsnprintf", "size", n);
974
975 // Stdio internals do not deal correctly with zero length buffer.
976 char dummy;
977 if (n == 0) {
978 s = &dummy;
979 n = 1;
980 }
981
982 FILE f;
983 __sfileext fext;
984 _FILEEXT_SETUP(&f, &fext);
985 f._file = -1;
986 f._flags = __SWR | __SSTR;
987 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
988 f._bf._size = f._w = n - 1;
989
990 int result = __vfprintf(&f, fmt, ap);
991 *f._p = '\0';
992 return result;
993}
994
Elliott Hughes53cf3482016-08-09 13:06:41 -0700995int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700996 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -0700997}
998
Elliott Hughescceaf062016-07-29 16:31:52 -0700999int vwprintf(const wchar_t* fmt, va_list ap) {
1000 return vfwprintf(stdout, fmt, ap);
1001}
1002
1003int vwscanf(const wchar_t* fmt, va_list ap) {
1004 return vfwscanf(stdin, fmt, ap);
1005}
Elliott Hughes70715da2016-08-01 16:35:17 -07001006
1007int wprintf(const wchar_t* fmt, ...) {
1008 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1009}
1010
1011int wscanf(const wchar_t* fmt, ...) {
1012 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1013}
Dan Albert3037ea42016-10-06 15:46:45 -07001014
Elliott Hughes37ad9592017-10-30 17:47:12 -07001015static int fflush_all() {
1016 return _fwalk(__sflush_locked);
1017}
1018
1019int fflush(FILE* fp) {
1020 if (fp == nullptr) return fflush_all();
1021 ScopedFileLock sfl(fp);
1022 return fflush_unlocked(fp);
1023}
1024
1025int fflush_unlocked(FILE* fp) {
1026 if (fp == nullptr) return fflush_all();
1027 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1028 errno = EBADF;
1029 return EOF;
1030 }
1031 return __sflush(fp);
1032}
1033
1034size_t fread(void* buf, size_t size, size_t count, FILE* fp) __overloadable {
1035 CHECK_FP(fp);
1036 ScopedFileLock sfl(fp);
1037 return fread_unlocked(buf, size, count, fp);
1038}
1039
1040size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1041 CHECK_FP(fp);
1042
1043 size_t desired_total;
1044 if (__builtin_mul_overflow(size, count, &desired_total)) {
1045 errno = EOVERFLOW;
1046 fp->_flags |= __SERR;
1047 return 0;
1048 }
1049
1050 size_t total = desired_total;
1051 if (total == 0) return 0;
1052
1053 _SET_ORIENTATION(fp, -1);
1054
1055 // TODO: how can this ever happen?!
1056 if (fp->_r < 0) fp->_r = 0;
1057
1058 // Ensure _bf._size is valid.
1059 if (fp->_bf._base == nullptr) __smakebuf(fp);
1060
1061 char* dst = static_cast<char*>(buf);
1062
1063 while (total > 0) {
1064 // Copy data out of the buffer.
1065 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1066 memcpy(dst, fp->_p, buffered_bytes);
1067 fp->_p += buffered_bytes;
1068 fp->_r -= buffered_bytes;
1069 dst += buffered_bytes;
1070 total -= buffered_bytes;
1071
1072 // Are we done?
1073 if (total == 0) goto out;
1074
1075 // Do we have so much more to read that we should avoid copying it through the buffer?
1076 if (total > static_cast<size_t>(fp->_bf._size)) break;
1077
1078 // Less than a buffer to go, so refill the buffer and go around the loop again.
1079 if (__srefill(fp)) goto out;
1080 }
1081
1082 // Read directly into the caller's buffer.
1083 while (total > 0) {
1084 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, total);
1085 if (bytes_read <= 0) {
1086 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1087 break;
1088 }
1089 dst += bytes_read;
1090 total -= bytes_read;
1091 }
1092
1093out:
1094 return ((desired_total - total) / size);
1095}
1096
1097size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1098 CHECK_FP(fp);
1099 ScopedFileLock sfl(fp);
1100 return fwrite_unlocked(buf, size, count, fp);
1101}
1102
1103size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1104 CHECK_FP(fp);
1105
1106 size_t n;
1107 if (__builtin_mul_overflow(size, count, &n)) {
1108 errno = EOVERFLOW;
1109 fp->_flags |= __SERR;
1110 return 0;
1111 }
1112
1113 if (n == 0) return 0;
1114
1115 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1116 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1117
1118 _SET_ORIENTATION(fp, -1);
1119
1120 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1121 // since divides are generally slow.
1122 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1123}
1124
Dan Albert3037ea42016-10-06 15:46:45 -07001125namespace {
1126
1127namespace phony {
1128#include <bits/struct_file.h>
1129}
1130
1131static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1132 "size mismatch between `struct __sFILE` implementation and public stub");
1133static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1134 "alignment mismatch between `struct __sFILE` implementation and public stub");
1135
1136}