blob: 91c7689f8cb48067d635ee4f6f98db5e083dd6b7 [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 Hughes468efc82018-07-10 14:39:49 -070044#include <sys/socket.h>
Elliott Hughes023c3072016-01-22 15:04:51 -080045#include <sys/stat.h>
Elliott Hughes468efc82018-07-10 14:39:49 -070046#include <sys/wait.h>
Elliott Hughes021335e2016-01-19 16:28:15 -080047#include <unistd.h>
48
Josh Gaof6e5b582018-06-01 15:30:54 -070049#include <android/fdsan.h>
50
Josh Gaod1620602017-10-05 13:48:08 -070051#include <async_safe/log.h>
52
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053#include "local.h"
54#include "glue.h"
Elliott Hughes886370c2019-03-21 21:11:41 -070055#include "private/__bionic_get_shell_path.h"
Elliott Hughesfb3873d2016-08-10 11:07:54 -070056#include "private/bionic_fortify.h"
Elliott Hughes023c3072016-01-22 15:04:51 -080057#include "private/ErrnoRestorer.h"
Elliott Hughes6a03abc2014-11-03 12:32:17 -080058#include "private/thread_private.h"
59
Josh Gaof6e5b582018-06-01 15:30:54 -070060extern "C" int ___close(int fd);
61
Elliott Hughes6a03abc2014-11-03 12:32:17 -080062#define ALIGNBYTES (sizeof(uintptr_t) - 1)
63#define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
Calin Juravlec20de902014-03-20 15:21:32 +000064
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080065#define NDYNAMIC 10 /* add ten more whenever necessary */
66
Elliott Hughes70715da2016-08-01 16:35:17 -070067#define PRINTF_IMPL(expr) \
68 va_list ap; \
69 va_start(ap, fmt); \
70 int result = (expr); \
71 va_end(ap); \
72 return result;
73
Elliott Hughes468efc82018-07-10 14:39:49 -070074#define MAKE_STD_STREAM(flags, fd) \
75 { \
76 ._flags = flags, ._file = fd, ._cookie = __sF + fd, ._close = __sclose, \
77 ._read = __sread, ._write = __swrite, ._ext = { \
78 ._base = reinterpret_cast<uint8_t*>(__sFext + fd) \
79 } \
80 }
Elliott Hughes29ee6392015-12-07 11:07:15 -080081
Elliott Hughesbb46afd2015-12-04 18:03:12 -080082static struct __sfileext __sFext[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -070083 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
84 ._caller_handles_locking = false,
85 ._seek64 = __sseek64,
86 ._popen_pid = 0},
87 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
88 ._caller_handles_locking = false,
89 ._seek64 = __sseek64,
90 ._popen_pid = 0},
91 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
92 ._caller_handles_locking = false,
93 ._seek64 = __sseek64,
94 ._popen_pid = 0},
Elliott Hughesbb46afd2015-12-04 18:03:12 -080095};
Elliott Hughesf0141df2015-10-12 12:44:23 -070096
97// __sF is exported for backwards compatibility. Until M, we didn't have symbols
98// for stdin/stdout/stderr; they were macros accessing __sF.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080099FILE __sF[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -0700100 MAKE_STD_STREAM(__SRD, STDIN_FILENO),
101 MAKE_STD_STREAM(__SWR, STDOUT_FILENO),
102 MAKE_STD_STREAM(__SWR|__SNBF, STDERR_FILENO),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103};
Elliott Hughesf0141df2015-10-12 12:44:23 -0700104
Elliott Hughes168667c2014-11-14 14:42:59 -0800105FILE* stdin = &__sF[0];
106FILE* stdout = &__sF[1];
107FILE* stderr = &__sF[2];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800108
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700109static pthread_mutex_t __stdio_mutex = PTHREAD_MUTEX_INITIALIZER;
Josh Gaof6e5b582018-06-01 15:30:54 -0700110
111static uint64_t __get_file_tag(FILE* fp) {
112 // Don't use a tag for the standard streams.
113 // They don't really own their file descriptors, because the values are well-known, and you're
114 // allowed to do things like `close(STDIN_FILENO); open("foo", O_RDONLY)` when single-threaded.
115 if (fp == stdin || fp == stderr || fp == stdout) {
116 return 0;
117 }
118
119 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE,
120 reinterpret_cast<uint64_t>(fp));
121}
122
Elliott Hughes37ad9592017-10-30 17:47:12 -0700123struct glue __sglue = { nullptr, 3, __sF };
Elliott Hughesbb46afd2015-12-04 18:03:12 -0800124static struct glue* lastglue = &__sglue;
125
Elliott Hughes2704bd12016-01-20 17:14:53 -0800126class ScopedFileLock {
127 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -0700128 explicit ScopedFileLock(FILE* fp) : fp_(fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800129 FLOCKFILE(fp_);
130 }
131 ~ScopedFileLock() {
132 FUNLOCKFILE(fp_);
133 }
134
135 private:
136 FILE* fp_;
137};
138
Elliott Hughes021335e2016-01-19 16:28:15 -0800139static glue* moreglue(int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800140 char* data = new char[sizeof(glue) + ALIGNBYTES + n * sizeof(FILE) + n * sizeof(__sfileext)];
141 if (data == nullptr) return nullptr;
Elliott Hughes021335e2016-01-19 16:28:15 -0800142
Elliott Hughes2704bd12016-01-20 17:14:53 -0800143 glue* g = reinterpret_cast<glue*>(data);
144 FILE* p = reinterpret_cast<FILE*>(ALIGN(data + sizeof(*g)));
145 __sfileext* pext = reinterpret_cast<__sfileext*>(ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
Elliott Hughes37ad9592017-10-30 17:47:12 -0700146 g->next = nullptr;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800147 g->niobs = n;
148 g->iobs = p;
149 while (--n >= 0) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700150 *p = {};
Elliott Hughes2704bd12016-01-20 17:14:53 -0800151 _FILEEXT_SETUP(p, pext);
152 p++;
153 pext++;
154 }
155 return g;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800156}
157
Elliott Hughes80e4c152017-07-21 13:57:55 -0700158static inline void free_fgetln_buffer(FILE* fp) {
159 if (__predict_false(fp->_lb._base != nullptr)) {
160 free(fp->_lb._base);
161 fp->_lb._base = nullptr;
162 }
163}
164
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800165/*
166 * Find a free FILE for fopen et al.
167 */
Elliott Hughes021335e2016-01-19 16:28:15 -0800168FILE* __sfp(void) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800169 FILE *fp;
170 int n;
171 struct glue *g;
172
Elliott Hughes468efc82018-07-10 14:39:49 -0700173 pthread_mutex_lock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700174 for (g = &__sglue; g != nullptr; g = g->next) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800175 for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
176 if (fp->_flags == 0)
177 goto found;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800178 }
Kenny Rootf5823402011-02-12 07:13:44 -0800179
180 /* release lock while mallocing */
Elliott Hughes468efc82018-07-10 14:39:49 -0700181 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700182 if ((g = moreglue(NDYNAMIC)) == nullptr) return nullptr;
Elliott Hughes468efc82018-07-10 14:39:49 -0700183 pthread_mutex_lock(&__stdio_mutex);
Kenny Rootf5823402011-02-12 07:13:44 -0800184 lastglue->next = g;
185 lastglue = g;
186 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800187found:
188 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Elliott Hughes468efc82018-07-10 14:39:49 -0700189 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700190 fp->_p = nullptr; /* no current pointer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800191 fp->_w = 0; /* nothing to read or write */
192 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700193 fp->_bf._base = nullptr; /* no buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800194 fp->_bf._size = 0;
195 fp->_lbfsize = 0; /* not line buffered */
196 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800197
Elliott Hughes37ad9592017-10-30 17:47:12 -0700198 fp->_lb._base = nullptr; /* no line buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800199 fp->_lb._size = 0;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800200
201 memset(_EXT(fp), 0, sizeof(struct __sfileext));
202 _FLOCK(fp) = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
203 _EXT(fp)->_caller_handles_locking = false;
Elliott Hughes023c3072016-01-22 15:04:51 -0800204
205 // Caller sets cookie, _read/_write etc.
206 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
207 fp->_seek = nullptr;
208 _EXT(fp)->_seek64 = nullptr;
209
210 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800211}
212
Elliott Hughes468efc82018-07-10 14:39:49 -0700213int _fwalk(int (*callback)(FILE*)) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700214 int result = 0;
215 for (glue* g = &__sglue; g != nullptr; g = g->next) {
216 FILE* fp = g->iobs;
217 for (int n = g->niobs; --n >= 0; ++fp) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700218 if (fp->_flags != 0 && (fp->_flags & __SIGN) == 0) {
219 result |= (*callback)(fp);
220 }
221 }
222 }
Elliott Hughes468efc82018-07-10 14:39:49 -0700223 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800224}
Elliott Hughes923f1652016-01-19 15:46:05 -0800225
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700226extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
227 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
228 _fwalk(__sflush);
229}
230
Elliott Hughes023c3072016-01-22 15:04:51 -0800231static FILE* __fopen(int fd, int flags) {
232#if !defined(__LP64__)
233 if (fd > SHRT_MAX) {
234 errno = EMFILE;
235 return nullptr;
236 }
237#endif
238
239 FILE* fp = __sfp();
240 if (fp != nullptr) {
241 fp->_file = fd;
Josh Gaof6e5b582018-06-01 15:30:54 -0700242 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
Elliott Hughes023c3072016-01-22 15:04:51 -0800243 fp->_flags = flags;
244 fp->_cookie = fp;
245 fp->_read = __sread;
246 fp->_write = __swrite;
247 fp->_close = __sclose;
248 _EXT(fp)->_seek64 = __sseek64;
249 }
250 return fp;
251}
252
253FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700254 int mode_flags;
255 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800256 if (flags == 0) return nullptr;
257
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700258 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800259 if (fd == -1) {
260 return nullptr;
261 }
262
263 FILE* fp = __fopen(fd, flags);
264 if (fp == nullptr) {
265 ErrnoRestorer errno_restorer;
266 close(fd);
267 return nullptr;
268 }
269
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700270 // For append mode, even though we use O_APPEND, we need to seek to the end now.
271 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800272 return fp;
273}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800274__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800275
276FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700277 int mode_flags;
278 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800279 if (flags == 0) return nullptr;
280
281 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700282 int fd_flags = fcntl(fd, F_GETFL, 0);
283 if (fd_flags == -1) return nullptr;
284 int tmp = fd_flags & O_ACCMODE;
285 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800286 errno = EINVAL;
287 return nullptr;
288 }
289
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700290 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
291 // POSIX says we just take the current offset of the underlying fd.
292 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
293 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
294 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800295
Dan Albertba1151c2019-03-26 13:01:22 -0700296 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'e'.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700297 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800298 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
299 }
300
301 return __fopen(fd, flags);
302}
303
304// Re-direct an existing, open (probably) file to some other file.
305// ANSI is written such that the original file gets closed if at
306// all possible, no matter what.
307// TODO: rewrite this mess completely.
308FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700309 CHECK_FP(fp);
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700310 int mode_flags;
311 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800312 if (flags == 0) {
313 fclose(fp);
314 return nullptr;
315 }
316
317 ScopedFileLock sfl(fp);
318
319 // There are actually programs that depend on being able to "freopen"
320 // descriptors that weren't originally open. Keep this from breaking.
321 // Remember whether the stream was open to begin with, and which file
322 // descriptor (if any) was associated with it. If it was attached to
323 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
324 // should work. This is unnecessary if it was not a Unix file.
325 int isopen, wantfd;
326 if (fp->_flags == 0) {
327 fp->_flags = __SEOF; // Hold on to it.
328 isopen = 0;
329 wantfd = -1;
330 } else {
331 // Flush the stream; ANSI doesn't require this.
332 if (fp->_flags & __SWR) __sflush(fp);
333
Elliott Hughes37ad9592017-10-30 17:47:12 -0700334 // If close is null, closing is a no-op, hence pointless.
335 isopen = (fp->_close != nullptr);
Elliott Hughes023c3072016-01-22 15:04:51 -0800336 if ((wantfd = fp->_file) < 0 && isopen) {
337 (*fp->_close)(fp->_cookie);
338 isopen = 0;
339 }
340 }
341
342 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700343 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800344 if (fd < 0 && isopen) {
345 // If out of fd's close the old one and try again.
346 if (errno == ENFILE || errno == EMFILE) {
347 (*fp->_close)(fp->_cookie);
348 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700349 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800350 }
351 }
352
353 int sverrno = errno;
354
355 // Finish closing fp. Even if the open succeeded above, we cannot
356 // keep fp->_base: it may be the wrong size. This loses the effect
357 // of any setbuffer calls, but stdio has always done this before.
358 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
359 if (fp->_flags & __SMBF) free(fp->_bf._base);
360 fp->_w = 0;
361 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700362 fp->_p = nullptr;
363 fp->_bf._base = nullptr;
Elliott Hughes023c3072016-01-22 15:04:51 -0800364 fp->_bf._size = 0;
365 fp->_lbfsize = 0;
366 if (HASUB(fp)) FREEUB(fp);
367 _UB(fp)._size = 0;
368 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700369 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800370 fp->_lb._size = 0;
371
372 if (fd < 0) { // Did not get it after all.
373 fp->_flags = 0; // Release.
374 errno = sverrno; // Restore errno in case _close clobbered it.
375 return nullptr;
376 }
377
378 // If reopening something that was open before on a real file, try
379 // to maintain the descriptor. Various C library routines (perror)
380 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
381 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700382 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800383 close(fd);
384 fd = wantfd;
385 }
386 }
387
388 // _file is only a short.
389 if (fd > SHRT_MAX) {
390 fp->_flags = 0; // Release.
391 errno = EMFILE;
392 return nullptr;
393 }
394
395 fp->_flags = flags;
396 fp->_file = fd;
Josh Gaof6e5b582018-06-01 15:30:54 -0700397 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
Elliott Hughes023c3072016-01-22 15:04:51 -0800398 fp->_cookie = fp;
399 fp->_read = __sread;
400 fp->_write = __swrite;
401 fp->_close = __sclose;
402 _EXT(fp)->_seek64 = __sseek64;
403
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700404 // For append mode, even though we use O_APPEND, we need to seek to the end now.
405 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800406 return fp;
407}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800408__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800409
Elliott Hughes22917f62018-10-01 14:21:07 -0700410static int __FILE_close(FILE* fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800411 if (fp->_flags == 0) {
412 // Already freed!
413 errno = EBADF;
414 return EOF;
415 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800416
Elliott Hughes2704bd12016-01-20 17:14:53 -0800417 ScopedFileLock sfl(fp);
418 WCIO_FREE(fp);
419 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700420 if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800421 r = EOF;
422 }
423 if (fp->_flags & __SMBF) free(fp->_bf._base);
424 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700425 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800426
Elliott Hughes468efc82018-07-10 14:39:49 -0700427 // If we were created by popen(3), wait for the child.
428 pid_t pid = _EXT(fp)->_popen_pid;
429 if (pid > 0) {
430 int status;
431 if (TEMP_FAILURE_RETRY(wait4(pid, &status, 0, nullptr)) != -1) {
432 r = status;
433 }
434 }
435 _EXT(fp)->_popen_pid = 0;
436
Elliott Hughes2704bd12016-01-20 17:14:53 -0800437 // Poison this FILE so accesses after fclose will be obvious.
438 fp->_file = -1;
439 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800440
Elliott Hughes2704bd12016-01-20 17:14:53 -0800441 // Release this FILE for reuse.
442 fp->_flags = 0;
443 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800444}
Elliott Hughes22917f62018-10-01 14:21:07 -0700445
446int fclose(FILE* fp) {
447 CHECK_FP(fp);
448 return __FILE_close(fp);
449}
Elliott Hughes923f1652016-01-19 15:46:05 -0800450
Elliott Hughescceaf062016-07-29 16:31:52 -0700451int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700452 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700453 int fd = fp->_file;
454 if (fd == -1) {
455 errno = EBADF;
456 return -1;
457 }
458 return fd;
459}
460
Elliott Hughes923f1652016-01-19 15:46:05 -0800461int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700462 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800463 ScopedFileLock sfl(fp);
464 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800465}
Elliott Hughes021335e2016-01-19 16:28:15 -0800466
Elliott Hughescceaf062016-07-29 16:31:52 -0700467void clearerr_unlocked(FILE* fp) {
Elliott Hughes22917f62018-10-01 14:21:07 -0700468 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700469 return __sclearerr(fp);
470}
471
472void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700473 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700474 ScopedFileLock sfl(fp);
475 clearerr_unlocked(fp);
476}
477
478int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700479 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700480 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700481}
482
483int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700484 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700485 ScopedFileLock sfl(fp);
486 return feof_unlocked(fp);
487}
488
489int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700490 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700491 return __sferror(fp);
492}
493
494int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700495 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700496 ScopedFileLock sfl(fp);
497 return ferror_unlocked(fp);
498}
499
Elliott Hughes37ad9592017-10-30 17:47:12 -0700500int __sflush(FILE* fp) {
501 // Flushing a read-only file is a no-op.
502 if ((fp->_flags & __SWR) == 0) return 0;
503
504 // Flushing a file without a buffer is a no-op.
505 unsigned char* p = fp->_bf._base;
506 if (p == nullptr) return 0;
507
508 // Set these immediately to avoid problems with longjmp and to allow
509 // exchange buffering (via setvbuf) in user write function.
510 int n = fp->_p - p;
511 fp->_p = p;
512 fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
513
514 while (n > 0) {
515 int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
516 if (written <= 0) {
517 fp->_flags |= __SERR;
518 return EOF;
519 }
520 n -= written, p += written;
521 }
522 return 0;
523}
524
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700525int __sflush_locked(FILE* fp) {
526 ScopedFileLock sfl(fp);
527 return __sflush(fp);
528}
529
Elliott Hughes021335e2016-01-19 16:28:15 -0800530int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800531 FILE* fp = reinterpret_cast<FILE*>(cookie);
532 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800533}
534
535int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800536 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800537 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800538}
539
Elliott Hughes021335e2016-01-19 16:28:15 -0800540fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800541 FILE* fp = reinterpret_cast<FILE*>(cookie);
542 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800543}
544
Elliott Hughes023c3072016-01-22 15:04:51 -0800545off64_t __sseek64(void* cookie, off64_t offset, int whence) {
546 FILE* fp = reinterpret_cast<FILE*>(cookie);
547 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
548}
549
Elliott Hughes021335e2016-01-19 16:28:15 -0800550int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800551 FILE* fp = reinterpret_cast<FILE*>(cookie);
Josh Gaof6e5b582018-06-01 15:30:54 -0700552 return android_fdsan_close_with_tag(fp->_file, __get_file_tag(fp));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800553}
554
Elliott Hughes023c3072016-01-22 15:04:51 -0800555static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
556 // Use `_seek64` if set, but fall back to `_seek`.
557 if (_EXT(fp)->_seek64 != nullptr) {
558 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
559 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800560 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
561#if !defined(__LP64__)
562 // Avoid sign extension if off64_t is larger than off_t.
563 if (result != -1) result &= 0xffffffff;
564#endif
565 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800566 } else {
567 errno = ESPIPE;
568 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800569 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800570}
571
Elliott Hughes9677fab2016-01-25 15:50:59 -0800572static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800573 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800574 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700575
Elliott Hughes9677fab2016-01-25 15:50:59 -0800576 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800577 if (result == -1) {
578 return -1;
579 }
580
581 if (fp->_flags & __SRD) {
582 // Reading. Any unread characters (including
583 // those from ungetc) cause the position to be
584 // smaller than that in the underlying object.
585 result -= fp->_r;
586 if (HASUB(fp)) result -= fp->_ur;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700587 } else if (fp->_flags & __SWR && fp->_p != nullptr) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800588 // Writing. Any buffered characters cause the
589 // position to be greater than that in the
590 // underlying object.
591 result += fp->_p - fp->_bf._base;
592 }
593 return result;
594}
595
Elliott Hughes9677fab2016-01-25 15:50:59 -0800596int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800597 ScopedFileLock sfl(fp);
598
Elliott Hughes023c3072016-01-22 15:04:51 -0800599 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800600 // After this, whence is either SEEK_SET or SEEK_END.
601 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800602 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800603 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800604 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800605 }
606 offset += current_offset;
607 whence = SEEK_SET;
608 } else if (whence != SEEK_SET && whence != SEEK_END) {
609 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800610 return -1;
611 }
612
613 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
614 if (off_t_bits == 32 && offset > LONG_MAX) {
615 errno = EOVERFLOW;
616 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800617 }
618
Elliott Hughes37ad9592017-10-30 17:47:12 -0700619 if (fp->_bf._base == nullptr) __smakebuf(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800620
621 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800622 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800623 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800624 }
625
626 // Success: clear EOF indicator and discard ungetc() data.
627 if (HASUB(fp)) FREEUB(fp);
628 fp->_p = fp->_bf._base;
629 fp->_r = 0;
630 /* fp->_w = 0; */ /* unnecessary (I think...) */
631 fp->_flags &= ~__SEOF;
632 return 0;
633}
634
Elliott Hughes9677fab2016-01-25 15:50:59 -0800635int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700636 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800637 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
638 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
639}
640__strong_alias(fseek, fseeko);
641
642int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700643 CHECK_FP(fp);
Ryan Prichardbf549862017-11-07 15:30:32 -0800644 return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800645}
646
Elliott Hughes9677fab2016-01-25 15:50:59 -0800647int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700648 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800649 return fseeko(fp, *pos, SEEK_SET);
650}
651
652int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700653 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800654 return fseeko64(fp, *pos, SEEK_SET);
655}
656
Elliott Hughes2704bd12016-01-20 17:14:53 -0800657off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700658 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800659 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
660 off64_t result = ftello64(fp);
661 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800662 errno = EOVERFLOW;
663 return -1;
664 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800665 return result;
666}
667__strong_alias(ftell, ftello);
668
669off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700670 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800671 ScopedFileLock sfl(fp);
672 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800673}
Elliott Hughes023c3072016-01-22 15:04:51 -0800674
Elliott Hughes023c3072016-01-22 15:04:51 -0800675int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700676 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800677 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800678 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800679}
680
Elliott Hughes9677fab2016-01-25 15:50:59 -0800681int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700682 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800683 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800684 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800685}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800686
687static FILE* __funopen(const void* cookie,
688 int (*read_fn)(void*, char*, int),
689 int (*write_fn)(void*, const char*, int),
690 int (*close_fn)(void*)) {
691 if (read_fn == nullptr && write_fn == nullptr) {
692 errno = EINVAL;
693 return nullptr;
694 }
695
696 FILE* fp = __sfp();
697 if (fp == nullptr) return nullptr;
698
699 if (read_fn != nullptr && write_fn != nullptr) {
700 fp->_flags = __SRW;
701 } else if (read_fn != nullptr) {
702 fp->_flags = __SRD;
703 } else if (write_fn != nullptr) {
704 fp->_flags = __SWR;
705 }
706
707 fp->_file = -1;
708 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
709 fp->_read = read_fn;
710 fp->_write = write_fn;
711 fp->_close = close_fn;
712
713 return fp;
714}
715
716FILE* funopen(const void* cookie,
717 int (*read_fn)(void*, char*, int),
718 int (*write_fn)(void*, const char*, int),
719 fpos_t (*seek_fn)(void*, fpos_t, int),
720 int (*close_fn)(void*)) {
721 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
722 if (fp != nullptr) {
723 fp->_seek = seek_fn;
724 }
725 return fp;
726}
727
728FILE* funopen64(const void* cookie,
729 int (*read_fn)(void*, char*, int),
730 int (*write_fn)(void*, const char*, int),
731 fpos64_t (*seek_fn)(void*, fpos64_t, int),
732 int (*close_fn)(void*)) {
733 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
734 if (fp != nullptr) {
735 _EXT(fp)->_seek64 = seek_fn;
736 }
737 return fp;
738}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700739
Elliott Hughes53cf3482016-08-09 13:06:41 -0700740int asprintf(char** s, const char* fmt, ...) {
741 PRINTF_IMPL(vasprintf(s, fmt, ap));
742}
743
Elliott Hughes20788ae2016-06-09 15:16:32 -0700744char* ctermid(char* s) {
745 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
746}
Elliott Hughescceaf062016-07-29 16:31:52 -0700747
Elliott Hughes70715da2016-08-01 16:35:17 -0700748int dprintf(int fd, const char* fmt, ...) {
749 PRINTF_IMPL(vdprintf(fd, fmt, ap));
750}
751
752int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700753 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700754 PRINTF_IMPL(vfprintf(fp, fmt, ap));
755}
756
Elliott Hughescceaf062016-07-29 16:31:52 -0700757int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700758 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700759 return getc(fp);
760}
761
Elliott Hughes37ad9592017-10-30 17:47:12 -0700762int fgetc_unlocked(FILE* fp) {
763 CHECK_FP(fp);
764 return getc_unlocked(fp);
765}
766
George Burgess IV90242352018-02-06 12:51:31 -0800767char* fgets(char* buf, int n, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -0700768 CHECK_FP(fp);
769 ScopedFileLock sfl(fp);
770 return fgets_unlocked(buf, n, fp);
771}
772
Elliott Hughes468efc82018-07-10 14:39:49 -0700773// Reads at most n-1 characters from the given file.
774// Stops when a newline has been read, or the count runs out.
775// Returns first argument, or nullptr if no characters were read.
776// Does not return nullptr if n == 1.
Elliott Hughes37ad9592017-10-30 17:47:12 -0700777char* fgets_unlocked(char* buf, int n, FILE* fp) {
778 if (n <= 0) {
779 errno = EINVAL;
780 return nullptr;
781 }
782
783 _SET_ORIENTATION(fp, -1);
784
785 char* s = buf;
786 n--; // Leave space for NUL.
787 while (n != 0) {
788 // If the buffer is empty, refill it.
789 if (fp->_r <= 0) {
790 if (__srefill(fp)) {
791 // EOF/error: stop with partial or no line.
792 if (s == buf) return nullptr;
793 break;
794 }
795 }
796 size_t len = fp->_r;
797 unsigned char* p = fp->_p;
798
799 // Scan through at most n bytes of the current buffer,
800 // looking for '\n'. If found, copy up to and including
801 // newline, and stop. Otherwise, copy entire chunk and loop.
802 if (len > static_cast<size_t>(n)) len = n;
803 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
804 if (t != nullptr) {
805 len = ++t - p;
806 fp->_r -= len;
807 fp->_p = t;
808 memcpy(s, p, len);
809 s[len] = '\0';
810 return buf;
811 }
812 fp->_r -= len;
813 fp->_p += len;
814 memcpy(s, p, len);
815 s += len;
816 n -= len;
817 }
818 *s = '\0';
819 return buf;
820}
821
Elliott Hughescceaf062016-07-29 16:31:52 -0700822int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700823 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700824 return putc(c, fp);
825}
826
Elliott Hughes37ad9592017-10-30 17:47:12 -0700827int fputc_unlocked(int c, FILE* fp) {
828 CHECK_FP(fp);
829 return putc_unlocked(c, fp);
830}
831
832int fputs(const char* s, FILE* fp) {
833 CHECK_FP(fp);
834 ScopedFileLock sfl(fp);
835 return fputs_unlocked(s, fp);
836}
837
838int fputs_unlocked(const char* s, FILE* fp) {
839 CHECK_FP(fp);
840 size_t length = strlen(s);
841 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
842}
843
Elliott Hughes70715da2016-08-01 16:35:17 -0700844int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700845 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700846 PRINTF_IMPL(vfscanf(fp, fmt, ap));
847}
848
849int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700850 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700851 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
852}
853
854int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700855 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700856 PRINTF_IMPL(vfwscanf(fp, fmt, ap));
857}
858
859int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700860 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700861 ScopedFileLock sfl(fp);
862 return getc_unlocked(fp);
863}
864
865int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700866 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700867 return __sgetc(fp);
868}
869
870int getchar_unlocked() {
871 return getc_unlocked(stdin);
872}
873
874int getchar() {
875 return getc(stdin);
876}
877
Elliott Hughescceaf062016-07-29 16:31:52 -0700878ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700879 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700880 return getdelim(buf, len, '\n', fp);
881}
882
883wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700884 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700885 return fgetwc(fp);
886}
887
888wint_t getwchar() {
889 return fgetwc(stdin);
890}
891
Elliott Hughes37ad9592017-10-30 17:47:12 -0700892void perror(const char* msg) {
893 if (msg == nullptr) msg = "";
894 fprintf(stderr, "%s%s%s\n", msg, (*msg == '\0') ? "" : ": ", strerror(errno));
895}
896
Elliott Hughes70715da2016-08-01 16:35:17 -0700897int printf(const char* fmt, ...) {
898 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
899}
900
901int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700902 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700903 ScopedFileLock sfl(fp);
904 return putc_unlocked(c, fp);
905}
906
907int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700908 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700909 if (cantwrite(fp)) {
910 errno = EBADF;
911 return EOF;
912 }
913 _SET_ORIENTATION(fp, -1);
914 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
915 return (*fp->_p++ = c);
916 }
917 return (__swbuf(c, fp));
918}
919
920int putchar(int c) {
921 return putc(c, stdout);
922}
923
924int putchar_unlocked(int c) {
925 return putc_unlocked(c, stdout);
926}
927
Elliott Hughes37ad9592017-10-30 17:47:12 -0700928int puts(const char* s) {
929 size_t length = strlen(s);
930 ScopedFileLock sfl(stdout);
931 return (fwrite_unlocked(s, 1, length, stdout) == length &&
932 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
933}
934
Elliott Hughescceaf062016-07-29 16:31:52 -0700935wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700936 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700937 return fputwc(wc, fp);
938}
939
940wint_t putwchar(wchar_t wc) {
941 return fputwc(wc, stdout);
942}
943
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700944int remove(const char* path) {
945 if (unlink(path) != -1) return 0;
946 if (errno != EISDIR) return -1;
947 return rmdir(path);
948}
949
Elliott Hughescceaf062016-07-29 16:31:52 -0700950void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700951 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700952 ScopedFileLock sfl(fp);
953 fseek(fp, 0, SEEK_SET);
954 clearerr_unlocked(fp);
955}
956
Elliott Hughes70715da2016-08-01 16:35:17 -0700957int scanf(const char* fmt, ...) {
958 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
959}
960
Elliott Hughescceaf062016-07-29 16:31:52 -0700961void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -0700962 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700963 setbuffer(fp, buf, BUFSIZ);
964}
965
966void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -0700967 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700968 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
969}
970
971int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700972 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700973 return setvbuf(fp, nullptr, _IOLBF, 0);
974}
975
Elliott Hughes53cf3482016-08-09 13:06:41 -0700976int snprintf(char* s, size_t n, const char* fmt, ...) {
977 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
978}
979
980int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700981 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -0700982}
983
984int sscanf(const char* s, const char* fmt, ...) {
985 PRINTF_IMPL(vsscanf(s, fmt, ap));
986}
987
Elliott Hughes70715da2016-08-01 16:35:17 -0700988int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
989 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
990}
991
992int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
993 PRINTF_IMPL(vswscanf(s, fmt, ap));
994}
995
Elliott Hughes618303c2017-11-02 16:58:44 -0700996int vfprintf(FILE* fp, const char* fmt, va_list ap) {
997 ScopedFileLock sfl(fp);
998 return __vfprintf(fp, fmt, ap);
999}
1000
Elliott Hughes345b7272017-11-10 16:20:43 -08001001int vfscanf(FILE* fp, const char* fmt, va_list ap) {
1002 ScopedFileLock sfl(fp);
1003 return __svfscanf(fp, fmt, ap);
1004}
1005
Elliott Hughes618303c2017-11-02 16:58:44 -07001006int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
1007 ScopedFileLock sfl(fp);
1008 return __vfwprintf(fp, fmt, ap);
1009}
1010
Elliott Hughes345b7272017-11-10 16:20:43 -08001011int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1012 ScopedFileLock sfl(fp);
1013 return __vfwscanf(fp, fmt, ap);
1014}
1015
Elliott Hughescceaf062016-07-29 16:31:52 -07001016int vprintf(const char* fmt, va_list ap) {
1017 return vfprintf(stdout, fmt, ap);
1018}
1019
1020int vscanf(const char* fmt, va_list ap) {
1021 return vfscanf(stdin, fmt, ap);
1022}
1023
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001024int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1025 // stdio internals use int rather than size_t.
1026 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1027
1028 __check_count("vsnprintf", "size", n);
1029
1030 // Stdio internals do not deal correctly with zero length buffer.
1031 char dummy;
1032 if (n == 0) {
1033 s = &dummy;
1034 n = 1;
1035 }
1036
1037 FILE f;
1038 __sfileext fext;
1039 _FILEEXT_SETUP(&f, &fext);
1040 f._file = -1;
1041 f._flags = __SWR | __SSTR;
1042 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1043 f._bf._size = f._w = n - 1;
1044
1045 int result = __vfprintf(&f, fmt, ap);
1046 *f._p = '\0';
1047 return result;
1048}
1049
Elliott Hughes53cf3482016-08-09 13:06:41 -07001050int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001051 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -07001052}
1053
Elliott Hughescceaf062016-07-29 16:31:52 -07001054int vwprintf(const wchar_t* fmt, va_list ap) {
1055 return vfwprintf(stdout, fmt, ap);
1056}
1057
1058int vwscanf(const wchar_t* fmt, va_list ap) {
1059 return vfwscanf(stdin, fmt, ap);
1060}
Elliott Hughes70715da2016-08-01 16:35:17 -07001061
1062int wprintf(const wchar_t* fmt, ...) {
1063 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1064}
1065
1066int wscanf(const wchar_t* fmt, ...) {
1067 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1068}
Dan Albert3037ea42016-10-06 15:46:45 -07001069
Elliott Hughes37ad9592017-10-30 17:47:12 -07001070static int fflush_all() {
Ryan Prichardc485cdb2019-04-30 14:47:34 -07001071 return _fwalk(__sflush_locked);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001072}
1073
1074int fflush(FILE* fp) {
1075 if (fp == nullptr) return fflush_all();
1076 ScopedFileLock sfl(fp);
1077 return fflush_unlocked(fp);
1078}
1079
1080int fflush_unlocked(FILE* fp) {
1081 if (fp == nullptr) return fflush_all();
1082 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1083 errno = EBADF;
1084 return EOF;
1085 }
1086 return __sflush(fp);
1087}
1088
George Burgess IV90242352018-02-06 12:51:31 -08001089size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -07001090 CHECK_FP(fp);
1091 ScopedFileLock sfl(fp);
1092 return fread_unlocked(buf, size, count, fp);
1093}
1094
1095size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1096 CHECK_FP(fp);
1097
1098 size_t desired_total;
1099 if (__builtin_mul_overflow(size, count, &desired_total)) {
1100 errno = EOVERFLOW;
1101 fp->_flags |= __SERR;
1102 return 0;
1103 }
1104
1105 size_t total = desired_total;
1106 if (total == 0) return 0;
1107
1108 _SET_ORIENTATION(fp, -1);
1109
1110 // TODO: how can this ever happen?!
1111 if (fp->_r < 0) fp->_r = 0;
1112
1113 // Ensure _bf._size is valid.
1114 if (fp->_bf._base == nullptr) __smakebuf(fp);
1115
1116 char* dst = static_cast<char*>(buf);
1117
1118 while (total > 0) {
1119 // Copy data out of the buffer.
1120 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1121 memcpy(dst, fp->_p, buffered_bytes);
1122 fp->_p += buffered_bytes;
1123 fp->_r -= buffered_bytes;
1124 dst += buffered_bytes;
1125 total -= buffered_bytes;
1126
1127 // Are we done?
1128 if (total == 0) goto out;
1129
1130 // Do we have so much more to read that we should avoid copying it through the buffer?
1131 if (total > static_cast<size_t>(fp->_bf._size)) break;
1132
1133 // Less than a buffer to go, so refill the buffer and go around the loop again.
1134 if (__srefill(fp)) goto out;
1135 }
1136
1137 // Read directly into the caller's buffer.
1138 while (total > 0) {
1139 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, total);
1140 if (bytes_read <= 0) {
1141 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1142 break;
1143 }
1144 dst += bytes_read;
1145 total -= bytes_read;
1146 }
1147
1148out:
1149 return ((desired_total - total) / size);
1150}
1151
1152size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1153 CHECK_FP(fp);
1154 ScopedFileLock sfl(fp);
1155 return fwrite_unlocked(buf, size, count, fp);
1156}
1157
1158size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1159 CHECK_FP(fp);
1160
1161 size_t n;
1162 if (__builtin_mul_overflow(size, count, &n)) {
1163 errno = EOVERFLOW;
1164 fp->_flags |= __SERR;
1165 return 0;
1166 }
1167
1168 if (n == 0) return 0;
1169
1170 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1171 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1172
1173 _SET_ORIENTATION(fp, -1);
1174
1175 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1176 // since divides are generally slow.
1177 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1178}
1179
Elliott Hughes468efc82018-07-10 14:39:49 -07001180static FILE* __popen_fail(int fds[2]) {
1181 ErrnoRestorer errno_restorer;
1182 close(fds[0]);
1183 close(fds[1]);
1184 return nullptr;
1185}
1186
1187FILE* popen(const char* cmd, const char* mode) {
Elliott Hughes468efc82018-07-10 14:39:49 -07001188 // Was the request for a socketpair or just a pipe?
1189 int fds[2];
1190 bool bidirectional = false;
1191 if (strchr(mode, '+') != nullptr) {
1192 if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1193 bidirectional = true;
1194 mode = "r+";
1195 } else {
1196 if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1197 mode = strrchr(mode, 'r') ? "r" : "w";
1198 }
1199
1200 // If the parent wants to read, the child's fd needs to be stdout.
1201 int parent, child, desired_child_fd;
1202 if (*mode == 'r') {
1203 parent = 0;
1204 child = 1;
1205 desired_child_fd = STDOUT_FILENO;
1206 } else {
1207 parent = 1;
1208 child = 0;
1209 desired_child_fd = STDIN_FILENO;
1210 }
1211
1212 // Ensure that the child fd isn't the desired child fd.
1213 if (fds[child] == desired_child_fd) {
1214 int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1215 if (new_fd == -1) return __popen_fail(fds);
1216 close(fds[child]);
1217 fds[child] = new_fd;
1218 }
1219
1220 pid_t pid = vfork();
1221 if (pid == -1) return __popen_fail(fds);
1222
1223 if (pid == 0) {
1224 close(fds[parent]);
Elliott Hughes468efc82018-07-10 14:39:49 -07001225 // dup2 so that the child fd isn't closed on exec.
1226 if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1227 close(fds[child]);
1228 if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
Elliott Hughes886370c2019-03-21 21:11:41 -07001229 execl(__bionic_get_shell_path(), "sh", "-c", cmd, nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001230 _exit(127);
1231 }
1232
1233 FILE* fp = fdopen(fds[parent], mode);
1234 if (fp == nullptr) return __popen_fail(fds);
1235
Elliott Hughes468efc82018-07-10 14:39:49 -07001236 close(fds[child]);
1237
1238 _EXT(fp)->_popen_pid = pid;
1239 return fp;
1240}
1241
Elliott Hughes22917f62018-10-01 14:21:07 -07001242int pclose(FILE* fp) {
1243 CHECK_FP(fp);
1244 return __FILE_close(fp);
1245}
1246
Dan Albert3037ea42016-10-06 15:46:45 -07001247namespace {
1248
1249namespace phony {
1250#include <bits/struct_file.h>
1251}
1252
1253static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1254 "size mismatch between `struct __sFILE` implementation and public stub");
1255static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1256 "alignment mismatch between `struct __sFILE` implementation and public stub");
1257
1258}