blob: d482a91c5a783340b649dc26c576a43d2e9212e9 [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
Elliott Hughes468efc82018-07-10 14:39:49 -0700109static pthread_mutex_t __stdio_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
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*)) {
214 pthread_mutex_lock(&__stdio_mutex);
215 int result = 0;
216 for (glue* g = &__sglue; g != nullptr; g = g->next) {
217 FILE* fp = g->iobs;
218 for (int n = g->niobs; --n >= 0; ++fp) {
219 ScopedFileLock sfl(fp);
220 if (fp->_flags != 0 && (fp->_flags & __SIGN) == 0) {
221 result |= (*callback)(fp);
222 }
223 }
224 }
225 pthread_mutex_unlock(&__stdio_mutex);
226 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800227}
Elliott Hughes923f1652016-01-19 15:46:05 -0800228
Elliott Hughes023c3072016-01-22 15:04:51 -0800229static FILE* __fopen(int fd, int flags) {
230#if !defined(__LP64__)
231 if (fd > SHRT_MAX) {
232 errno = EMFILE;
233 return nullptr;
234 }
235#endif
236
237 FILE* fp = __sfp();
238 if (fp != nullptr) {
239 fp->_file = fd;
Josh Gaof6e5b582018-06-01 15:30:54 -0700240 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
Elliott Hughes023c3072016-01-22 15:04:51 -0800241 fp->_flags = flags;
242 fp->_cookie = fp;
243 fp->_read = __sread;
244 fp->_write = __swrite;
245 fp->_close = __sclose;
246 _EXT(fp)->_seek64 = __sseek64;
247 }
248 return fp;
249}
250
251FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700252 int mode_flags;
253 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800254 if (flags == 0) return nullptr;
255
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700256 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800257 if (fd == -1) {
258 return nullptr;
259 }
260
261 FILE* fp = __fopen(fd, flags);
262 if (fp == nullptr) {
263 ErrnoRestorer errno_restorer;
264 close(fd);
265 return nullptr;
266 }
267
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700268 // For append mode, even though we use O_APPEND, we need to seek to the end now.
269 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800270 return fp;
271}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800272__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800273
274FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700275 int mode_flags;
276 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800277 if (flags == 0) return nullptr;
278
279 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700280 int fd_flags = fcntl(fd, F_GETFL, 0);
281 if (fd_flags == -1) return nullptr;
282 int tmp = fd_flags & O_ACCMODE;
283 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800284 errno = EINVAL;
285 return nullptr;
286 }
287
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700288 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
289 // POSIX says we just take the current offset of the underlying fd.
290 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
291 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
292 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800293
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700294 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'x'.
295 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800296 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
297 }
298
299 return __fopen(fd, flags);
300}
301
302// Re-direct an existing, open (probably) file to some other file.
303// ANSI is written such that the original file gets closed if at
304// all possible, no matter what.
305// TODO: rewrite this mess completely.
306FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700307 CHECK_FP(fp);
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700308 int mode_flags;
309 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800310 if (flags == 0) {
311 fclose(fp);
312 return nullptr;
313 }
314
315 ScopedFileLock sfl(fp);
316
317 // There are actually programs that depend on being able to "freopen"
318 // descriptors that weren't originally open. Keep this from breaking.
319 // Remember whether the stream was open to begin with, and which file
320 // descriptor (if any) was associated with it. If it was attached to
321 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
322 // should work. This is unnecessary if it was not a Unix file.
323 int isopen, wantfd;
324 if (fp->_flags == 0) {
325 fp->_flags = __SEOF; // Hold on to it.
326 isopen = 0;
327 wantfd = -1;
328 } else {
329 // Flush the stream; ANSI doesn't require this.
330 if (fp->_flags & __SWR) __sflush(fp);
331
Elliott Hughes37ad9592017-10-30 17:47:12 -0700332 // If close is null, closing is a no-op, hence pointless.
333 isopen = (fp->_close != nullptr);
Elliott Hughes023c3072016-01-22 15:04:51 -0800334 if ((wantfd = fp->_file) < 0 && isopen) {
335 (*fp->_close)(fp->_cookie);
336 isopen = 0;
337 }
338 }
339
340 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700341 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800342 if (fd < 0 && isopen) {
343 // If out of fd's close the old one and try again.
344 if (errno == ENFILE || errno == EMFILE) {
345 (*fp->_close)(fp->_cookie);
346 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700347 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800348 }
349 }
350
351 int sverrno = errno;
352
353 // Finish closing fp. Even if the open succeeded above, we cannot
354 // keep fp->_base: it may be the wrong size. This loses the effect
355 // of any setbuffer calls, but stdio has always done this before.
356 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
357 if (fp->_flags & __SMBF) free(fp->_bf._base);
358 fp->_w = 0;
359 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700360 fp->_p = nullptr;
361 fp->_bf._base = nullptr;
Elliott Hughes023c3072016-01-22 15:04:51 -0800362 fp->_bf._size = 0;
363 fp->_lbfsize = 0;
364 if (HASUB(fp)) FREEUB(fp);
365 _UB(fp)._size = 0;
366 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700367 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800368 fp->_lb._size = 0;
369
370 if (fd < 0) { // Did not get it after all.
371 fp->_flags = 0; // Release.
372 errno = sverrno; // Restore errno in case _close clobbered it.
373 return nullptr;
374 }
375
376 // If reopening something that was open before on a real file, try
377 // to maintain the descriptor. Various C library routines (perror)
378 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
379 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700380 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800381 close(fd);
382 fd = wantfd;
383 }
384 }
385
386 // _file is only a short.
387 if (fd > SHRT_MAX) {
388 fp->_flags = 0; // Release.
389 errno = EMFILE;
390 return nullptr;
391 }
392
393 fp->_flags = flags;
394 fp->_file = fd;
Josh Gaof6e5b582018-06-01 15:30:54 -0700395 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
Elliott Hughes023c3072016-01-22 15:04:51 -0800396 fp->_cookie = fp;
397 fp->_read = __sread;
398 fp->_write = __swrite;
399 fp->_close = __sclose;
400 _EXT(fp)->_seek64 = __sseek64;
401
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700402 // For append mode, even though we use O_APPEND, we need to seek to the end now.
403 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800404 return fp;
405}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800406__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800407
Elliott Hughes22917f62018-10-01 14:21:07 -0700408static int __FILE_close(FILE* fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800409 if (fp->_flags == 0) {
410 // Already freed!
411 errno = EBADF;
412 return EOF;
413 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800414
Elliott Hughes2704bd12016-01-20 17:14:53 -0800415 ScopedFileLock sfl(fp);
416 WCIO_FREE(fp);
417 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700418 if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800419 r = EOF;
420 }
421 if (fp->_flags & __SMBF) free(fp->_bf._base);
422 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700423 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800424
Elliott Hughes468efc82018-07-10 14:39:49 -0700425 // If we were created by popen(3), wait for the child.
426 pid_t pid = _EXT(fp)->_popen_pid;
427 if (pid > 0) {
428 int status;
429 if (TEMP_FAILURE_RETRY(wait4(pid, &status, 0, nullptr)) != -1) {
430 r = status;
431 }
432 }
433 _EXT(fp)->_popen_pid = 0;
434
Elliott Hughes2704bd12016-01-20 17:14:53 -0800435 // Poison this FILE so accesses after fclose will be obvious.
436 fp->_file = -1;
437 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800438
Elliott Hughes2704bd12016-01-20 17:14:53 -0800439 // Release this FILE for reuse.
440 fp->_flags = 0;
441 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800442}
Elliott Hughes22917f62018-10-01 14:21:07 -0700443
444int fclose(FILE* fp) {
445 CHECK_FP(fp);
446 return __FILE_close(fp);
447}
Elliott Hughes923f1652016-01-19 15:46:05 -0800448
Elliott Hughescceaf062016-07-29 16:31:52 -0700449int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700450 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700451 int fd = fp->_file;
452 if (fd == -1) {
453 errno = EBADF;
454 return -1;
455 }
456 return fd;
457}
458
Elliott Hughes923f1652016-01-19 15:46:05 -0800459int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700460 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800461 ScopedFileLock sfl(fp);
462 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800463}
Elliott Hughes021335e2016-01-19 16:28:15 -0800464
Elliott Hughescceaf062016-07-29 16:31:52 -0700465void clearerr_unlocked(FILE* fp) {
Elliott Hughes22917f62018-10-01 14:21:07 -0700466 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700467 return __sclearerr(fp);
468}
469
470void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700471 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700472 ScopedFileLock sfl(fp);
473 clearerr_unlocked(fp);
474}
475
476int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700477 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700478 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700479}
480
481int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700482 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700483 ScopedFileLock sfl(fp);
484 return feof_unlocked(fp);
485}
486
487int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700488 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700489 return __sferror(fp);
490}
491
492int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700493 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700494 ScopedFileLock sfl(fp);
495 return ferror_unlocked(fp);
496}
497
Elliott Hughes37ad9592017-10-30 17:47:12 -0700498int __sflush(FILE* fp) {
499 // Flushing a read-only file is a no-op.
500 if ((fp->_flags & __SWR) == 0) return 0;
501
502 // Flushing a file without a buffer is a no-op.
503 unsigned char* p = fp->_bf._base;
504 if (p == nullptr) return 0;
505
506 // Set these immediately to avoid problems with longjmp and to allow
507 // exchange buffering (via setvbuf) in user write function.
508 int n = fp->_p - p;
509 fp->_p = p;
510 fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
511
512 while (n > 0) {
513 int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
514 if (written <= 0) {
515 fp->_flags |= __SERR;
516 return EOF;
517 }
518 n -= written, p += written;
519 }
520 return 0;
521}
522
Elliott Hughes021335e2016-01-19 16:28:15 -0800523int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800524 FILE* fp = reinterpret_cast<FILE*>(cookie);
525 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800526}
527
528int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800529 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800530 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800531}
532
Elliott Hughes021335e2016-01-19 16:28:15 -0800533fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800534 FILE* fp = reinterpret_cast<FILE*>(cookie);
535 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800536}
537
Elliott Hughes023c3072016-01-22 15:04:51 -0800538off64_t __sseek64(void* cookie, off64_t offset, int whence) {
539 FILE* fp = reinterpret_cast<FILE*>(cookie);
540 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
541}
542
Elliott Hughes021335e2016-01-19 16:28:15 -0800543int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800544 FILE* fp = reinterpret_cast<FILE*>(cookie);
Josh Gaof6e5b582018-06-01 15:30:54 -0700545 return android_fdsan_close_with_tag(fp->_file, __get_file_tag(fp));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800546}
547
Elliott Hughes023c3072016-01-22 15:04:51 -0800548static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
549 // Use `_seek64` if set, but fall back to `_seek`.
550 if (_EXT(fp)->_seek64 != nullptr) {
551 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
552 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800553 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
554#if !defined(__LP64__)
555 // Avoid sign extension if off64_t is larger than off_t.
556 if (result != -1) result &= 0xffffffff;
557#endif
558 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800559 } else {
560 errno = ESPIPE;
561 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800562 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800563}
564
Elliott Hughes9677fab2016-01-25 15:50:59 -0800565static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800566 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800567 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700568
Elliott Hughes9677fab2016-01-25 15:50:59 -0800569 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800570 if (result == -1) {
571 return -1;
572 }
573
574 if (fp->_flags & __SRD) {
575 // Reading. Any unread characters (including
576 // those from ungetc) cause the position to be
577 // smaller than that in the underlying object.
578 result -= fp->_r;
579 if (HASUB(fp)) result -= fp->_ur;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700580 } else if (fp->_flags & __SWR && fp->_p != nullptr) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800581 // Writing. Any buffered characters cause the
582 // position to be greater than that in the
583 // underlying object.
584 result += fp->_p - fp->_bf._base;
585 }
586 return result;
587}
588
Elliott Hughes9677fab2016-01-25 15:50:59 -0800589int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800590 ScopedFileLock sfl(fp);
591
Elliott Hughes023c3072016-01-22 15:04:51 -0800592 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800593 // After this, whence is either SEEK_SET or SEEK_END.
594 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800595 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800596 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800597 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800598 }
599 offset += current_offset;
600 whence = SEEK_SET;
601 } else if (whence != SEEK_SET && whence != SEEK_END) {
602 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800603 return -1;
604 }
605
606 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
607 if (off_t_bits == 32 && offset > LONG_MAX) {
608 errno = EOVERFLOW;
609 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800610 }
611
Elliott Hughes37ad9592017-10-30 17:47:12 -0700612 if (fp->_bf._base == nullptr) __smakebuf(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800613
614 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800615 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800616 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800617 }
618
619 // Success: clear EOF indicator and discard ungetc() data.
620 if (HASUB(fp)) FREEUB(fp);
621 fp->_p = fp->_bf._base;
622 fp->_r = 0;
623 /* fp->_w = 0; */ /* unnecessary (I think...) */
624 fp->_flags &= ~__SEOF;
625 return 0;
626}
627
Elliott Hughes9677fab2016-01-25 15:50:59 -0800628int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700629 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800630 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
631 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
632}
633__strong_alias(fseek, fseeko);
634
635int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700636 CHECK_FP(fp);
Ryan Prichardbf549862017-11-07 15:30:32 -0800637 return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800638}
639
Elliott Hughes9677fab2016-01-25 15:50:59 -0800640int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700641 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800642 return fseeko(fp, *pos, SEEK_SET);
643}
644
645int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700646 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800647 return fseeko64(fp, *pos, SEEK_SET);
648}
649
Elliott Hughes2704bd12016-01-20 17:14:53 -0800650off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700651 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800652 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
653 off64_t result = ftello64(fp);
654 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800655 errno = EOVERFLOW;
656 return -1;
657 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800658 return result;
659}
660__strong_alias(ftell, ftello);
661
662off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700663 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800664 ScopedFileLock sfl(fp);
665 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800666}
Elliott Hughes023c3072016-01-22 15:04:51 -0800667
Elliott Hughes023c3072016-01-22 15:04:51 -0800668int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700669 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800670 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800671 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800672}
673
Elliott Hughes9677fab2016-01-25 15:50:59 -0800674int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700675 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800676 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800677 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800678}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800679
680static FILE* __funopen(const void* cookie,
681 int (*read_fn)(void*, char*, int),
682 int (*write_fn)(void*, const char*, int),
683 int (*close_fn)(void*)) {
684 if (read_fn == nullptr && write_fn == nullptr) {
685 errno = EINVAL;
686 return nullptr;
687 }
688
689 FILE* fp = __sfp();
690 if (fp == nullptr) return nullptr;
691
692 if (read_fn != nullptr && write_fn != nullptr) {
693 fp->_flags = __SRW;
694 } else if (read_fn != nullptr) {
695 fp->_flags = __SRD;
696 } else if (write_fn != nullptr) {
697 fp->_flags = __SWR;
698 }
699
700 fp->_file = -1;
701 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
702 fp->_read = read_fn;
703 fp->_write = write_fn;
704 fp->_close = close_fn;
705
706 return fp;
707}
708
709FILE* funopen(const void* cookie,
710 int (*read_fn)(void*, char*, int),
711 int (*write_fn)(void*, const char*, int),
712 fpos_t (*seek_fn)(void*, fpos_t, int),
713 int (*close_fn)(void*)) {
714 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
715 if (fp != nullptr) {
716 fp->_seek = seek_fn;
717 }
718 return fp;
719}
720
721FILE* funopen64(const void* cookie,
722 int (*read_fn)(void*, char*, int),
723 int (*write_fn)(void*, const char*, int),
724 fpos64_t (*seek_fn)(void*, fpos64_t, int),
725 int (*close_fn)(void*)) {
726 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
727 if (fp != nullptr) {
728 _EXT(fp)->_seek64 = seek_fn;
729 }
730 return fp;
731}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700732
Elliott Hughes53cf3482016-08-09 13:06:41 -0700733int asprintf(char** s, const char* fmt, ...) {
734 PRINTF_IMPL(vasprintf(s, fmt, ap));
735}
736
Elliott Hughes20788ae2016-06-09 15:16:32 -0700737char* ctermid(char* s) {
738 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
739}
Elliott Hughescceaf062016-07-29 16:31:52 -0700740
Elliott Hughes70715da2016-08-01 16:35:17 -0700741int dprintf(int fd, const char* fmt, ...) {
742 PRINTF_IMPL(vdprintf(fd, fmt, ap));
743}
744
745int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700746 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700747 PRINTF_IMPL(vfprintf(fp, fmt, ap));
748}
749
Elliott Hughescceaf062016-07-29 16:31:52 -0700750int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700751 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700752 return getc(fp);
753}
754
Elliott Hughes37ad9592017-10-30 17:47:12 -0700755int fgetc_unlocked(FILE* fp) {
756 CHECK_FP(fp);
757 return getc_unlocked(fp);
758}
759
George Burgess IV90242352018-02-06 12:51:31 -0800760char* fgets(char* buf, int n, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -0700761 CHECK_FP(fp);
762 ScopedFileLock sfl(fp);
763 return fgets_unlocked(buf, n, fp);
764}
765
Elliott Hughes468efc82018-07-10 14:39:49 -0700766// Reads at most n-1 characters from the given file.
767// Stops when a newline has been read, or the count runs out.
768// Returns first argument, or nullptr if no characters were read.
769// Does not return nullptr if n == 1.
Elliott Hughes37ad9592017-10-30 17:47:12 -0700770char* fgets_unlocked(char* buf, int n, FILE* fp) {
771 if (n <= 0) {
772 errno = EINVAL;
773 return nullptr;
774 }
775
776 _SET_ORIENTATION(fp, -1);
777
778 char* s = buf;
779 n--; // Leave space for NUL.
780 while (n != 0) {
781 // If the buffer is empty, refill it.
782 if (fp->_r <= 0) {
783 if (__srefill(fp)) {
784 // EOF/error: stop with partial or no line.
785 if (s == buf) return nullptr;
786 break;
787 }
788 }
789 size_t len = fp->_r;
790 unsigned char* p = fp->_p;
791
792 // Scan through at most n bytes of the current buffer,
793 // looking for '\n'. If found, copy up to and including
794 // newline, and stop. Otherwise, copy entire chunk and loop.
795 if (len > static_cast<size_t>(n)) len = n;
796 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
797 if (t != nullptr) {
798 len = ++t - p;
799 fp->_r -= len;
800 fp->_p = t;
801 memcpy(s, p, len);
802 s[len] = '\0';
803 return buf;
804 }
805 fp->_r -= len;
806 fp->_p += len;
807 memcpy(s, p, len);
808 s += len;
809 n -= len;
810 }
811 *s = '\0';
812 return buf;
813}
814
Elliott Hughescceaf062016-07-29 16:31:52 -0700815int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700816 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700817 return putc(c, fp);
818}
819
Elliott Hughes37ad9592017-10-30 17:47:12 -0700820int fputc_unlocked(int c, FILE* fp) {
821 CHECK_FP(fp);
822 return putc_unlocked(c, fp);
823}
824
825int fputs(const char* s, FILE* fp) {
826 CHECK_FP(fp);
827 ScopedFileLock sfl(fp);
828 return fputs_unlocked(s, fp);
829}
830
831int fputs_unlocked(const char* s, FILE* fp) {
832 CHECK_FP(fp);
833 size_t length = strlen(s);
834 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
835}
836
Elliott Hughes70715da2016-08-01 16:35:17 -0700837int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700838 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700839 PRINTF_IMPL(vfscanf(fp, fmt, ap));
840}
841
842int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700843 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700844 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
845}
846
847int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700848 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700849 PRINTF_IMPL(vfwscanf(fp, fmt, ap));
850}
851
852int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700853 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700854 ScopedFileLock sfl(fp);
855 return getc_unlocked(fp);
856}
857
858int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700859 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700860 return __sgetc(fp);
861}
862
863int getchar_unlocked() {
864 return getc_unlocked(stdin);
865}
866
867int getchar() {
868 return getc(stdin);
869}
870
Elliott Hughescceaf062016-07-29 16:31:52 -0700871ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700872 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700873 return getdelim(buf, len, '\n', fp);
874}
875
876wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700877 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700878 return fgetwc(fp);
879}
880
881wint_t getwchar() {
882 return fgetwc(stdin);
883}
884
Elliott Hughes37ad9592017-10-30 17:47:12 -0700885void perror(const char* msg) {
886 if (msg == nullptr) msg = "";
887 fprintf(stderr, "%s%s%s\n", msg, (*msg == '\0') ? "" : ": ", strerror(errno));
888}
889
Elliott Hughes70715da2016-08-01 16:35:17 -0700890int printf(const char* fmt, ...) {
891 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
892}
893
894int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700895 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700896 ScopedFileLock sfl(fp);
897 return putc_unlocked(c, fp);
898}
899
900int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700901 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700902 if (cantwrite(fp)) {
903 errno = EBADF;
904 return EOF;
905 }
906 _SET_ORIENTATION(fp, -1);
907 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
908 return (*fp->_p++ = c);
909 }
910 return (__swbuf(c, fp));
911}
912
913int putchar(int c) {
914 return putc(c, stdout);
915}
916
917int putchar_unlocked(int c) {
918 return putc_unlocked(c, stdout);
919}
920
Elliott Hughes37ad9592017-10-30 17:47:12 -0700921int puts(const char* s) {
922 size_t length = strlen(s);
923 ScopedFileLock sfl(stdout);
924 return (fwrite_unlocked(s, 1, length, stdout) == length &&
925 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
926}
927
Elliott Hughescceaf062016-07-29 16:31:52 -0700928wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700929 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700930 return fputwc(wc, fp);
931}
932
933wint_t putwchar(wchar_t wc) {
934 return fputwc(wc, stdout);
935}
936
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700937int remove(const char* path) {
938 if (unlink(path) != -1) return 0;
939 if (errno != EISDIR) return -1;
940 return rmdir(path);
941}
942
Elliott Hughescceaf062016-07-29 16:31:52 -0700943void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700944 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700945 ScopedFileLock sfl(fp);
946 fseek(fp, 0, SEEK_SET);
947 clearerr_unlocked(fp);
948}
949
Elliott Hughes70715da2016-08-01 16:35:17 -0700950int scanf(const char* fmt, ...) {
951 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
952}
953
Elliott Hughescceaf062016-07-29 16:31:52 -0700954void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -0700955 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700956 setbuffer(fp, buf, BUFSIZ);
957}
958
959void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -0700960 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700961 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
962}
963
964int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700965 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700966 return setvbuf(fp, nullptr, _IOLBF, 0);
967}
968
Elliott Hughes53cf3482016-08-09 13:06:41 -0700969int snprintf(char* s, size_t n, const char* fmt, ...) {
970 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
971}
972
973int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700974 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -0700975}
976
977int sscanf(const char* s, const char* fmt, ...) {
978 PRINTF_IMPL(vsscanf(s, fmt, ap));
979}
980
Elliott Hughes70715da2016-08-01 16:35:17 -0700981int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
982 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
983}
984
985int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
986 PRINTF_IMPL(vswscanf(s, fmt, ap));
987}
988
Elliott Hughes618303c2017-11-02 16:58:44 -0700989int vfprintf(FILE* fp, const char* fmt, va_list ap) {
990 ScopedFileLock sfl(fp);
991 return __vfprintf(fp, fmt, ap);
992}
993
Elliott Hughes345b7272017-11-10 16:20:43 -0800994int vfscanf(FILE* fp, const char* fmt, va_list ap) {
995 ScopedFileLock sfl(fp);
996 return __svfscanf(fp, fmt, ap);
997}
998
Elliott Hughes618303c2017-11-02 16:58:44 -0700999int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
1000 ScopedFileLock sfl(fp);
1001 return __vfwprintf(fp, fmt, ap);
1002}
1003
Elliott Hughes345b7272017-11-10 16:20:43 -08001004int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1005 ScopedFileLock sfl(fp);
1006 return __vfwscanf(fp, fmt, ap);
1007}
1008
Elliott Hughescceaf062016-07-29 16:31:52 -07001009int vprintf(const char* fmt, va_list ap) {
1010 return vfprintf(stdout, fmt, ap);
1011}
1012
1013int vscanf(const char* fmt, va_list ap) {
1014 return vfscanf(stdin, fmt, ap);
1015}
1016
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001017int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1018 // stdio internals use int rather than size_t.
1019 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1020
1021 __check_count("vsnprintf", "size", n);
1022
1023 // Stdio internals do not deal correctly with zero length buffer.
1024 char dummy;
1025 if (n == 0) {
1026 s = &dummy;
1027 n = 1;
1028 }
1029
1030 FILE f;
1031 __sfileext fext;
1032 _FILEEXT_SETUP(&f, &fext);
1033 f._file = -1;
1034 f._flags = __SWR | __SSTR;
1035 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1036 f._bf._size = f._w = n - 1;
1037
1038 int result = __vfprintf(&f, fmt, ap);
1039 *f._p = '\0';
1040 return result;
1041}
1042
Elliott Hughes53cf3482016-08-09 13:06:41 -07001043int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001044 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -07001045}
1046
Elliott Hughescceaf062016-07-29 16:31:52 -07001047int vwprintf(const wchar_t* fmt, va_list ap) {
1048 return vfwprintf(stdout, fmt, ap);
1049}
1050
1051int vwscanf(const wchar_t* fmt, va_list ap) {
1052 return vfwscanf(stdin, fmt, ap);
1053}
Elliott Hughes70715da2016-08-01 16:35:17 -07001054
1055int wprintf(const wchar_t* fmt, ...) {
1056 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1057}
1058
1059int wscanf(const wchar_t* fmt, ...) {
1060 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1061}
Dan Albert3037ea42016-10-06 15:46:45 -07001062
Elliott Hughes37ad9592017-10-30 17:47:12 -07001063static int fflush_all() {
Elliott Hughes468efc82018-07-10 14:39:49 -07001064 return _fwalk(__sflush);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001065}
1066
1067int fflush(FILE* fp) {
1068 if (fp == nullptr) return fflush_all();
1069 ScopedFileLock sfl(fp);
1070 return fflush_unlocked(fp);
1071}
1072
1073int fflush_unlocked(FILE* fp) {
1074 if (fp == nullptr) return fflush_all();
1075 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1076 errno = EBADF;
1077 return EOF;
1078 }
1079 return __sflush(fp);
1080}
1081
George Burgess IV90242352018-02-06 12:51:31 -08001082size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -07001083 CHECK_FP(fp);
1084 ScopedFileLock sfl(fp);
1085 return fread_unlocked(buf, size, count, fp);
1086}
1087
1088size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1089 CHECK_FP(fp);
1090
1091 size_t desired_total;
1092 if (__builtin_mul_overflow(size, count, &desired_total)) {
1093 errno = EOVERFLOW;
1094 fp->_flags |= __SERR;
1095 return 0;
1096 }
1097
1098 size_t total = desired_total;
1099 if (total == 0) return 0;
1100
1101 _SET_ORIENTATION(fp, -1);
1102
1103 // TODO: how can this ever happen?!
1104 if (fp->_r < 0) fp->_r = 0;
1105
1106 // Ensure _bf._size is valid.
1107 if (fp->_bf._base == nullptr) __smakebuf(fp);
1108
1109 char* dst = static_cast<char*>(buf);
1110
1111 while (total > 0) {
1112 // Copy data out of the buffer.
1113 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1114 memcpy(dst, fp->_p, buffered_bytes);
1115 fp->_p += buffered_bytes;
1116 fp->_r -= buffered_bytes;
1117 dst += buffered_bytes;
1118 total -= buffered_bytes;
1119
1120 // Are we done?
1121 if (total == 0) goto out;
1122
1123 // Do we have so much more to read that we should avoid copying it through the buffer?
1124 if (total > static_cast<size_t>(fp->_bf._size)) break;
1125
1126 // Less than a buffer to go, so refill the buffer and go around the loop again.
1127 if (__srefill(fp)) goto out;
1128 }
1129
1130 // Read directly into the caller's buffer.
1131 while (total > 0) {
1132 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, total);
1133 if (bytes_read <= 0) {
1134 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1135 break;
1136 }
1137 dst += bytes_read;
1138 total -= bytes_read;
1139 }
1140
1141out:
1142 return ((desired_total - total) / size);
1143}
1144
1145size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1146 CHECK_FP(fp);
1147 ScopedFileLock sfl(fp);
1148 return fwrite_unlocked(buf, size, count, fp);
1149}
1150
1151size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1152 CHECK_FP(fp);
1153
1154 size_t n;
1155 if (__builtin_mul_overflow(size, count, &n)) {
1156 errno = EOVERFLOW;
1157 fp->_flags |= __SERR;
1158 return 0;
1159 }
1160
1161 if (n == 0) return 0;
1162
1163 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1164 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1165
1166 _SET_ORIENTATION(fp, -1);
1167
1168 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1169 // since divides are generally slow.
1170 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1171}
1172
Elliott Hughes468efc82018-07-10 14:39:49 -07001173static int __close_if_popened(FILE* fp) {
1174 if (_EXT(fp)->_popen_pid > 0) close(fileno(fp));
1175 return 0;
1176}
1177
1178static FILE* __popen_fail(int fds[2]) {
1179 ErrnoRestorer errno_restorer;
1180 close(fds[0]);
1181 close(fds[1]);
1182 return nullptr;
1183}
1184
1185FILE* popen(const char* cmd, const char* mode) {
Elliott Hughes468efc82018-07-10 14:39:49 -07001186 // Was the request for a socketpair or just a pipe?
1187 int fds[2];
1188 bool bidirectional = false;
1189 if (strchr(mode, '+') != nullptr) {
1190 if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1191 bidirectional = true;
1192 mode = "r+";
1193 } else {
1194 if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1195 mode = strrchr(mode, 'r') ? "r" : "w";
1196 }
1197
1198 // If the parent wants to read, the child's fd needs to be stdout.
1199 int parent, child, desired_child_fd;
1200 if (*mode == 'r') {
1201 parent = 0;
1202 child = 1;
1203 desired_child_fd = STDOUT_FILENO;
1204 } else {
1205 parent = 1;
1206 child = 0;
1207 desired_child_fd = STDIN_FILENO;
1208 }
1209
1210 // Ensure that the child fd isn't the desired child fd.
1211 if (fds[child] == desired_child_fd) {
1212 int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1213 if (new_fd == -1) return __popen_fail(fds);
1214 close(fds[child]);
1215 fds[child] = new_fd;
1216 }
1217
1218 pid_t pid = vfork();
1219 if (pid == -1) return __popen_fail(fds);
1220
1221 if (pid == 0) {
1222 close(fds[parent]);
1223 // POSIX says "The popen() function shall ensure that any streams from previous popen() calls
1224 // that remain open in the parent process are closed in the new child process."
1225 _fwalk(__close_if_popened);
1226 // dup2 so that the child fd isn't closed on exec.
1227 if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1228 close(fds[child]);
1229 if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
Elliott Hughes886370c2019-03-21 21:11:41 -07001230 execl(__bionic_get_shell_path(), "sh", "-c", cmd, nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001231 _exit(127);
1232 }
1233
1234 FILE* fp = fdopen(fds[parent], mode);
1235 if (fp == nullptr) return __popen_fail(fds);
1236
Elliott Hughes468efc82018-07-10 14:39:49 -07001237 close(fds[child]);
1238
1239 _EXT(fp)->_popen_pid = pid;
1240 return fp;
1241}
1242
Elliott Hughes22917f62018-10-01 14:21:07 -07001243int pclose(FILE* fp) {
1244 CHECK_FP(fp);
1245 return __FILE_close(fp);
1246}
1247
Dan Albert3037ea42016-10-06 15:46:45 -07001248namespace {
1249
1250namespace phony {
1251#include <bits/struct_file.h>
1252}
1253
1254static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1255 "size mismatch between `struct __sFILE` implementation and public stub");
1256static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1257 "alignment mismatch between `struct __sFILE` implementation and public stub");
1258
1259}