blob: b8aced83bc5ef20981e5353df6068999aca95f71 [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
60#define ALIGNBYTES (sizeof(uintptr_t) - 1)
61#define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
Calin Juravlec20de902014-03-20 15:21:32 +000062
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080063#define NDYNAMIC 10 /* add ten more whenever necessary */
64
Elliott Hughes70715da2016-08-01 16:35:17 -070065#define PRINTF_IMPL(expr) \
66 va_list ap; \
67 va_start(ap, fmt); \
68 int result = (expr); \
69 va_end(ap); \
70 return result;
71
Elliott Hughes468efc82018-07-10 14:39:49 -070072#define MAKE_STD_STREAM(flags, fd) \
73 { \
74 ._flags = flags, ._file = fd, ._cookie = __sF + fd, ._close = __sclose, \
75 ._read = __sread, ._write = __swrite, ._ext = { \
76 ._base = reinterpret_cast<uint8_t*>(__sFext + fd) \
77 } \
78 }
Elliott Hughes29ee6392015-12-07 11:07:15 -080079
Elliott Hughesbb46afd2015-12-04 18:03:12 -080080static struct __sfileext __sFext[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -070081 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
82 ._caller_handles_locking = false,
83 ._seek64 = __sseek64,
84 ._popen_pid = 0},
85 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
86 ._caller_handles_locking = false,
87 ._seek64 = __sseek64,
88 ._popen_pid = 0},
89 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
90 ._caller_handles_locking = false,
91 ._seek64 = __sseek64,
92 ._popen_pid = 0},
Elliott Hughesbb46afd2015-12-04 18:03:12 -080093};
Elliott Hughesf0141df2015-10-12 12:44:23 -070094
95// __sF is exported for backwards compatibility. Until M, we didn't have symbols
96// for stdin/stdout/stderr; they were macros accessing __sF.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080097FILE __sF[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -070098 MAKE_STD_STREAM(__SRD, STDIN_FILENO),
99 MAKE_STD_STREAM(__SWR, STDOUT_FILENO),
100 MAKE_STD_STREAM(__SWR|__SNBF, STDERR_FILENO),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800101};
Elliott Hughesf0141df2015-10-12 12:44:23 -0700102
Elliott Hughes168667c2014-11-14 14:42:59 -0800103FILE* stdin = &__sF[0];
104FILE* stdout = &__sF[1];
105FILE* stderr = &__sF[2];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800106
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700107static pthread_mutex_t __stdio_mutex = PTHREAD_MUTEX_INITIALIZER;
Josh Gaof6e5b582018-06-01 15:30:54 -0700108
109static uint64_t __get_file_tag(FILE* fp) {
110 // Don't use a tag for the standard streams.
111 // They don't really own their file descriptors, because the values are well-known, and you're
112 // allowed to do things like `close(STDIN_FILENO); open("foo", O_RDONLY)` when single-threaded.
113 if (fp == stdin || fp == stderr || fp == stdout) {
114 return 0;
115 }
116
117 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE,
118 reinterpret_cast<uint64_t>(fp));
119}
120
Elliott Hughes37ad9592017-10-30 17:47:12 -0700121struct glue __sglue = { nullptr, 3, __sF };
Elliott Hughesbb46afd2015-12-04 18:03:12 -0800122static struct glue* lastglue = &__sglue;
123
Elliott Hughes2704bd12016-01-20 17:14:53 -0800124class ScopedFileLock {
125 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -0700126 explicit ScopedFileLock(FILE* fp) : fp_(fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800127 FLOCKFILE(fp_);
128 }
129 ~ScopedFileLock() {
130 FUNLOCKFILE(fp_);
131 }
132
133 private:
134 FILE* fp_;
135};
136
Elliott Hughes021335e2016-01-19 16:28:15 -0800137static glue* moreglue(int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800138 char* data = new char[sizeof(glue) + ALIGNBYTES + n * sizeof(FILE) + n * sizeof(__sfileext)];
139 if (data == nullptr) return nullptr;
Elliott Hughes021335e2016-01-19 16:28:15 -0800140
Elliott Hughes2704bd12016-01-20 17:14:53 -0800141 glue* g = reinterpret_cast<glue*>(data);
142 FILE* p = reinterpret_cast<FILE*>(ALIGN(data + sizeof(*g)));
143 __sfileext* pext = reinterpret_cast<__sfileext*>(ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
Elliott Hughes37ad9592017-10-30 17:47:12 -0700144 g->next = nullptr;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800145 g->niobs = n;
146 g->iobs = p;
147 while (--n >= 0) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700148 *p = {};
Elliott Hughes2704bd12016-01-20 17:14:53 -0800149 _FILEEXT_SETUP(p, pext);
150 p++;
151 pext++;
152 }
153 return g;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800154}
155
Elliott Hughes80e4c152017-07-21 13:57:55 -0700156static inline void free_fgetln_buffer(FILE* fp) {
157 if (__predict_false(fp->_lb._base != nullptr)) {
158 free(fp->_lb._base);
159 fp->_lb._base = nullptr;
160 }
161}
162
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800163/*
164 * Find a free FILE for fopen et al.
165 */
Elliott Hughes021335e2016-01-19 16:28:15 -0800166FILE* __sfp(void) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800167 FILE *fp;
168 int n;
169 struct glue *g;
170
Elliott Hughes468efc82018-07-10 14:39:49 -0700171 pthread_mutex_lock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700172 for (g = &__sglue; g != nullptr; g = g->next) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800173 for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
174 if (fp->_flags == 0)
175 goto found;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800176 }
Kenny Rootf5823402011-02-12 07:13:44 -0800177
178 /* release lock while mallocing */
Elliott Hughes468efc82018-07-10 14:39:49 -0700179 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700180 if ((g = moreglue(NDYNAMIC)) == nullptr) return nullptr;
Elliott Hughes468efc82018-07-10 14:39:49 -0700181 pthread_mutex_lock(&__stdio_mutex);
Kenny Rootf5823402011-02-12 07:13:44 -0800182 lastglue->next = g;
183 lastglue = g;
184 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800185found:
186 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Elliott Hughes468efc82018-07-10 14:39:49 -0700187 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700188 fp->_p = nullptr; /* no current pointer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800189 fp->_w = 0; /* nothing to read or write */
190 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700191 fp->_bf._base = nullptr; /* no buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800192 fp->_bf._size = 0;
193 fp->_lbfsize = 0; /* not line buffered */
194 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800195
Elliott Hughes37ad9592017-10-30 17:47:12 -0700196 fp->_lb._base = nullptr; /* no line buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800197 fp->_lb._size = 0;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800198
199 memset(_EXT(fp), 0, sizeof(struct __sfileext));
200 _FLOCK(fp) = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
201 _EXT(fp)->_caller_handles_locking = false;
Elliott Hughes023c3072016-01-22 15:04:51 -0800202
203 // Caller sets cookie, _read/_write etc.
204 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
205 fp->_seek = nullptr;
206 _EXT(fp)->_seek64 = nullptr;
207
208 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800209}
210
Elliott Hughes468efc82018-07-10 14:39:49 -0700211int _fwalk(int (*callback)(FILE*)) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700212 int result = 0;
213 for (glue* g = &__sglue; g != nullptr; g = g->next) {
214 FILE* fp = g->iobs;
215 for (int n = g->niobs; --n >= 0; ++fp) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700216 if (fp->_flags != 0 && (fp->_flags & __SIGN) == 0) {
217 result |= (*callback)(fp);
218 }
219 }
220 }
Elliott Hughes468efc82018-07-10 14:39:49 -0700221 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800222}
Elliott Hughes923f1652016-01-19 15:46:05 -0800223
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700224extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
225 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
226 _fwalk(__sflush);
227}
228
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
Dan Albertba1151c2019-03-26 13:01:22 -0700294 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'e'.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700295 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
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700523int __sflush_locked(FILE* fp) {
524 ScopedFileLock sfl(fp);
525 return __sflush(fp);
526}
527
Elliott Hughes021335e2016-01-19 16:28:15 -0800528int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800529 FILE* fp = reinterpret_cast<FILE*>(cookie);
530 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800531}
532
533int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800534 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800535 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800536}
537
Elliott Hughes021335e2016-01-19 16:28:15 -0800538fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800539 FILE* fp = reinterpret_cast<FILE*>(cookie);
540 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800541}
542
Elliott Hughes023c3072016-01-22 15:04:51 -0800543off64_t __sseek64(void* cookie, off64_t offset, int whence) {
544 FILE* fp = reinterpret_cast<FILE*>(cookie);
545 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
546}
547
Elliott Hughes021335e2016-01-19 16:28:15 -0800548int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800549 FILE* fp = reinterpret_cast<FILE*>(cookie);
Josh Gaof6e5b582018-06-01 15:30:54 -0700550 return android_fdsan_close_with_tag(fp->_file, __get_file_tag(fp));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800551}
552
Elliott Hughes023c3072016-01-22 15:04:51 -0800553static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
554 // Use `_seek64` if set, but fall back to `_seek`.
555 if (_EXT(fp)->_seek64 != nullptr) {
556 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
557 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800558 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
559#if !defined(__LP64__)
560 // Avoid sign extension if off64_t is larger than off_t.
561 if (result != -1) result &= 0xffffffff;
562#endif
563 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800564 } else {
565 errno = ESPIPE;
566 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800567 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800568}
569
Elliott Hughes9677fab2016-01-25 15:50:59 -0800570static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800571 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800572 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700573
Elliott Hughes9677fab2016-01-25 15:50:59 -0800574 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800575 if (result == -1) {
576 return -1;
577 }
578
579 if (fp->_flags & __SRD) {
580 // Reading. Any unread characters (including
581 // those from ungetc) cause the position to be
582 // smaller than that in the underlying object.
583 result -= fp->_r;
584 if (HASUB(fp)) result -= fp->_ur;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700585 } else if (fp->_flags & __SWR && fp->_p != nullptr) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800586 // Writing. Any buffered characters cause the
587 // position to be greater than that in the
588 // underlying object.
589 result += fp->_p - fp->_bf._base;
590 }
591 return result;
592}
593
Elliott Hughes9677fab2016-01-25 15:50:59 -0800594int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800595 ScopedFileLock sfl(fp);
596
Elliott Hughes023c3072016-01-22 15:04:51 -0800597 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800598 // After this, whence is either SEEK_SET or SEEK_END.
599 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800600 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800601 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800602 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800603 }
604 offset += current_offset;
605 whence = SEEK_SET;
606 } else if (whence != SEEK_SET && whence != SEEK_END) {
607 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800608 return -1;
609 }
610
611 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
612 if (off_t_bits == 32 && offset > LONG_MAX) {
613 errno = EOVERFLOW;
614 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800615 }
616
Elliott Hughes37ad9592017-10-30 17:47:12 -0700617 if (fp->_bf._base == nullptr) __smakebuf(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800618
619 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800620 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800621 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800622 }
623
624 // Success: clear EOF indicator and discard ungetc() data.
625 if (HASUB(fp)) FREEUB(fp);
626 fp->_p = fp->_bf._base;
627 fp->_r = 0;
628 /* fp->_w = 0; */ /* unnecessary (I think...) */
629 fp->_flags &= ~__SEOF;
630 return 0;
631}
632
Elliott Hughes9677fab2016-01-25 15:50:59 -0800633int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700634 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800635 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
636 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
637}
638__strong_alias(fseek, fseeko);
639
640int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700641 CHECK_FP(fp);
Ryan Prichardbf549862017-11-07 15:30:32 -0800642 return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800643}
644
Elliott Hughes9677fab2016-01-25 15:50:59 -0800645int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700646 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800647 return fseeko(fp, *pos, SEEK_SET);
648}
649
650int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700651 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800652 return fseeko64(fp, *pos, SEEK_SET);
653}
654
Elliott Hughes2704bd12016-01-20 17:14:53 -0800655off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700656 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800657 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
658 off64_t result = ftello64(fp);
659 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800660 errno = EOVERFLOW;
661 return -1;
662 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800663 return result;
664}
665__strong_alias(ftell, ftello);
666
667off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700668 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800669 ScopedFileLock sfl(fp);
670 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800671}
Elliott Hughes023c3072016-01-22 15:04:51 -0800672
Elliott Hughes023c3072016-01-22 15:04:51 -0800673int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700674 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800675 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800676 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800677}
678
Elliott Hughes9677fab2016-01-25 15:50:59 -0800679int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700680 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800681 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800682 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800683}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800684
685static FILE* __funopen(const void* cookie,
686 int (*read_fn)(void*, char*, int),
687 int (*write_fn)(void*, const char*, int),
688 int (*close_fn)(void*)) {
689 if (read_fn == nullptr && write_fn == nullptr) {
690 errno = EINVAL;
691 return nullptr;
692 }
693
694 FILE* fp = __sfp();
695 if (fp == nullptr) return nullptr;
696
697 if (read_fn != nullptr && write_fn != nullptr) {
698 fp->_flags = __SRW;
699 } else if (read_fn != nullptr) {
700 fp->_flags = __SRD;
701 } else if (write_fn != nullptr) {
702 fp->_flags = __SWR;
703 }
704
705 fp->_file = -1;
706 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
707 fp->_read = read_fn;
708 fp->_write = write_fn;
709 fp->_close = close_fn;
710
711 return fp;
712}
713
714FILE* funopen(const void* cookie,
715 int (*read_fn)(void*, char*, int),
716 int (*write_fn)(void*, const char*, int),
717 fpos_t (*seek_fn)(void*, fpos_t, int),
718 int (*close_fn)(void*)) {
719 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
720 if (fp != nullptr) {
721 fp->_seek = seek_fn;
722 }
723 return fp;
724}
725
726FILE* funopen64(const void* cookie,
727 int (*read_fn)(void*, char*, int),
728 int (*write_fn)(void*, const char*, int),
729 fpos64_t (*seek_fn)(void*, fpos64_t, int),
730 int (*close_fn)(void*)) {
731 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
732 if (fp != nullptr) {
733 _EXT(fp)->_seek64 = seek_fn;
734 }
735 return fp;
736}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700737
Elliott Hughes53cf3482016-08-09 13:06:41 -0700738int asprintf(char** s, const char* fmt, ...) {
739 PRINTF_IMPL(vasprintf(s, fmt, ap));
740}
741
Elliott Hughes20788ae2016-06-09 15:16:32 -0700742char* ctermid(char* s) {
743 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
744}
Elliott Hughescceaf062016-07-29 16:31:52 -0700745
Elliott Hughes70715da2016-08-01 16:35:17 -0700746int dprintf(int fd, const char* fmt, ...) {
747 PRINTF_IMPL(vdprintf(fd, fmt, ap));
748}
749
750int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700751 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700752 PRINTF_IMPL(vfprintf(fp, fmt, ap));
753}
754
Elliott Hughescceaf062016-07-29 16:31:52 -0700755int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700756 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700757 return getc(fp);
758}
759
Elliott Hughes37ad9592017-10-30 17:47:12 -0700760int fgetc_unlocked(FILE* fp) {
761 CHECK_FP(fp);
762 return getc_unlocked(fp);
763}
764
George Burgess IV90242352018-02-06 12:51:31 -0800765char* fgets(char* buf, int n, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -0700766 CHECK_FP(fp);
767 ScopedFileLock sfl(fp);
768 return fgets_unlocked(buf, n, fp);
769}
770
Elliott Hughes468efc82018-07-10 14:39:49 -0700771// Reads at most n-1 characters from the given file.
772// Stops when a newline has been read, or the count runs out.
773// Returns first argument, or nullptr if no characters were read.
774// Does not return nullptr if n == 1.
Elliott Hughes37ad9592017-10-30 17:47:12 -0700775char* fgets_unlocked(char* buf, int n, FILE* fp) {
Elliott Hughes7cebf832020-08-12 14:25:41 -0700776 if (n <= 0) __fortify_fatal("fgets: buffer size %d <= 0", n);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700777
778 _SET_ORIENTATION(fp, -1);
779
780 char* s = buf;
781 n--; // Leave space for NUL.
782 while (n != 0) {
783 // If the buffer is empty, refill it.
784 if (fp->_r <= 0) {
785 if (__srefill(fp)) {
786 // EOF/error: stop with partial or no line.
787 if (s == buf) return nullptr;
788 break;
789 }
790 }
791 size_t len = fp->_r;
792 unsigned char* p = fp->_p;
793
794 // Scan through at most n bytes of the current buffer,
795 // looking for '\n'. If found, copy up to and including
796 // newline, and stop. Otherwise, copy entire chunk and loop.
797 if (len > static_cast<size_t>(n)) len = n;
798 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
799 if (t != nullptr) {
800 len = ++t - p;
801 fp->_r -= len;
802 fp->_p = t;
803 memcpy(s, p, len);
804 s[len] = '\0';
805 return buf;
806 }
807 fp->_r -= len;
808 fp->_p += len;
809 memcpy(s, p, len);
810 s += len;
811 n -= len;
812 }
813 *s = '\0';
814 return buf;
815}
816
Elliott Hughescceaf062016-07-29 16:31:52 -0700817int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700818 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700819 return putc(c, fp);
820}
821
Elliott Hughes37ad9592017-10-30 17:47:12 -0700822int fputc_unlocked(int c, FILE* fp) {
823 CHECK_FP(fp);
824 return putc_unlocked(c, fp);
825}
826
827int fputs(const char* s, FILE* fp) {
828 CHECK_FP(fp);
829 ScopedFileLock sfl(fp);
830 return fputs_unlocked(s, fp);
831}
832
833int fputs_unlocked(const char* s, FILE* fp) {
834 CHECK_FP(fp);
835 size_t length = strlen(s);
836 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
837}
838
Elliott Hughes70715da2016-08-01 16:35:17 -0700839int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700840 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700841 PRINTF_IMPL(vfscanf(fp, fmt, ap));
842}
843
844int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700845 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700846 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
847}
848
849int fwscanf(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(vfwscanf(fp, fmt, ap));
852}
853
854int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700855 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700856 ScopedFileLock sfl(fp);
857 return getc_unlocked(fp);
858}
859
860int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700861 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700862 return __sgetc(fp);
863}
864
865int getchar_unlocked() {
866 return getc_unlocked(stdin);
867}
868
869int getchar() {
870 return getc(stdin);
871}
872
Elliott Hughescceaf062016-07-29 16:31:52 -0700873ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700874 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700875 return getdelim(buf, len, '\n', fp);
876}
877
878wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700879 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700880 return fgetwc(fp);
881}
882
883wint_t getwchar() {
884 return fgetwc(stdin);
885}
886
Elliott Hughes37ad9592017-10-30 17:47:12 -0700887void perror(const char* msg) {
888 if (msg == nullptr) msg = "";
889 fprintf(stderr, "%s%s%s\n", msg, (*msg == '\0') ? "" : ": ", strerror(errno));
890}
891
Elliott Hughes70715da2016-08-01 16:35:17 -0700892int printf(const char* fmt, ...) {
893 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
894}
895
896int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700897 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700898 ScopedFileLock sfl(fp);
899 return putc_unlocked(c, fp);
900}
901
902int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700903 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700904 if (cantwrite(fp)) {
905 errno = EBADF;
906 return EOF;
907 }
908 _SET_ORIENTATION(fp, -1);
909 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
910 return (*fp->_p++ = c);
911 }
912 return (__swbuf(c, fp));
913}
914
915int putchar(int c) {
916 return putc(c, stdout);
917}
918
919int putchar_unlocked(int c) {
920 return putc_unlocked(c, stdout);
921}
922
Elliott Hughes37ad9592017-10-30 17:47:12 -0700923int puts(const char* s) {
924 size_t length = strlen(s);
925 ScopedFileLock sfl(stdout);
926 return (fwrite_unlocked(s, 1, length, stdout) == length &&
927 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
928}
929
Elliott Hughescceaf062016-07-29 16:31:52 -0700930wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700931 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700932 return fputwc(wc, fp);
933}
934
935wint_t putwchar(wchar_t wc) {
936 return fputwc(wc, stdout);
937}
938
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700939int remove(const char* path) {
940 if (unlink(path) != -1) return 0;
941 if (errno != EISDIR) return -1;
942 return rmdir(path);
943}
944
Elliott Hughescceaf062016-07-29 16:31:52 -0700945void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700946 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700947 ScopedFileLock sfl(fp);
948 fseek(fp, 0, SEEK_SET);
949 clearerr_unlocked(fp);
950}
951
Elliott Hughes70715da2016-08-01 16:35:17 -0700952int scanf(const char* fmt, ...) {
953 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
954}
955
Elliott Hughescceaf062016-07-29 16:31:52 -0700956void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -0700957 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700958 setbuffer(fp, buf, BUFSIZ);
959}
960
961void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -0700962 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700963 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
964}
965
966int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700967 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700968 return setvbuf(fp, nullptr, _IOLBF, 0);
969}
970
Elliott Hughes53cf3482016-08-09 13:06:41 -0700971int snprintf(char* s, size_t n, const char* fmt, ...) {
972 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
973}
974
975int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700976 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -0700977}
978
979int sscanf(const char* s, const char* fmt, ...) {
980 PRINTF_IMPL(vsscanf(s, fmt, ap));
981}
982
Elliott Hughes70715da2016-08-01 16:35:17 -0700983int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
984 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
985}
986
987int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
988 PRINTF_IMPL(vswscanf(s, fmt, ap));
989}
990
Elliott Hughes618303c2017-11-02 16:58:44 -0700991int vfprintf(FILE* fp, const char* fmt, va_list ap) {
992 ScopedFileLock sfl(fp);
993 return __vfprintf(fp, fmt, ap);
994}
995
Elliott Hughes345b7272017-11-10 16:20:43 -0800996int vfscanf(FILE* fp, const char* fmt, va_list ap) {
997 ScopedFileLock sfl(fp);
998 return __svfscanf(fp, fmt, ap);
999}
1000
Elliott Hughes618303c2017-11-02 16:58:44 -07001001int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
1002 ScopedFileLock sfl(fp);
1003 return __vfwprintf(fp, fmt, ap);
1004}
1005
Elliott Hughes345b7272017-11-10 16:20:43 -08001006int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1007 ScopedFileLock sfl(fp);
1008 return __vfwscanf(fp, fmt, ap);
1009}
1010
Elliott Hughescceaf062016-07-29 16:31:52 -07001011int vprintf(const char* fmt, va_list ap) {
1012 return vfprintf(stdout, fmt, ap);
1013}
1014
1015int vscanf(const char* fmt, va_list ap) {
1016 return vfscanf(stdin, fmt, ap);
1017}
1018
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001019int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1020 // stdio internals use int rather than size_t.
1021 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1022
1023 __check_count("vsnprintf", "size", n);
1024
1025 // Stdio internals do not deal correctly with zero length buffer.
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001026 char one_byte_buffer[1];
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001027 if (n == 0) {
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001028 s = one_byte_buffer;
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001029 n = 1;
1030 }
1031
1032 FILE f;
1033 __sfileext fext;
1034 _FILEEXT_SETUP(&f, &fext);
1035 f._file = -1;
1036 f._flags = __SWR | __SSTR;
1037 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1038 f._bf._size = f._w = n - 1;
1039
1040 int result = __vfprintf(&f, fmt, ap);
1041 *f._p = '\0';
1042 return result;
1043}
1044
Elliott Hughes53cf3482016-08-09 13:06:41 -07001045int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001046 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -07001047}
1048
Elliott Hughescceaf062016-07-29 16:31:52 -07001049int vwprintf(const wchar_t* fmt, va_list ap) {
1050 return vfwprintf(stdout, fmt, ap);
1051}
1052
1053int vwscanf(const wchar_t* fmt, va_list ap) {
1054 return vfwscanf(stdin, fmt, ap);
1055}
Elliott Hughes70715da2016-08-01 16:35:17 -07001056
1057int wprintf(const wchar_t* fmt, ...) {
1058 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1059}
1060
1061int wscanf(const wchar_t* fmt, ...) {
1062 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1063}
Dan Albert3037ea42016-10-06 15:46:45 -07001064
Elliott Hughes37ad9592017-10-30 17:47:12 -07001065static int fflush_all() {
Ryan Prichardc485cdb2019-04-30 14:47:34 -07001066 return _fwalk(__sflush_locked);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001067}
1068
1069int fflush(FILE* fp) {
1070 if (fp == nullptr) return fflush_all();
1071 ScopedFileLock sfl(fp);
1072 return fflush_unlocked(fp);
1073}
1074
1075int fflush_unlocked(FILE* fp) {
1076 if (fp == nullptr) return fflush_all();
1077 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1078 errno = EBADF;
1079 return EOF;
1080 }
1081 return __sflush(fp);
1082}
1083
George Burgess IV90242352018-02-06 12:51:31 -08001084size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -07001085 CHECK_FP(fp);
1086 ScopedFileLock sfl(fp);
1087 return fread_unlocked(buf, size, count, fp);
1088}
1089
1090size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1091 CHECK_FP(fp);
1092
1093 size_t desired_total;
1094 if (__builtin_mul_overflow(size, count, &desired_total)) {
1095 errno = EOVERFLOW;
1096 fp->_flags |= __SERR;
1097 return 0;
1098 }
1099
1100 size_t total = desired_total;
1101 if (total == 0) return 0;
1102
1103 _SET_ORIENTATION(fp, -1);
1104
1105 // TODO: how can this ever happen?!
1106 if (fp->_r < 0) fp->_r = 0;
1107
1108 // Ensure _bf._size is valid.
1109 if (fp->_bf._base == nullptr) __smakebuf(fp);
1110
1111 char* dst = static_cast<char*>(buf);
1112
1113 while (total > 0) {
1114 // Copy data out of the buffer.
1115 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1116 memcpy(dst, fp->_p, buffered_bytes);
1117 fp->_p += buffered_bytes;
1118 fp->_r -= buffered_bytes;
1119 dst += buffered_bytes;
1120 total -= buffered_bytes;
1121
1122 // Are we done?
1123 if (total == 0) goto out;
1124
1125 // Do we have so much more to read that we should avoid copying it through the buffer?
1126 if (total > static_cast<size_t>(fp->_bf._size)) break;
1127
1128 // Less than a buffer to go, so refill the buffer and go around the loop again.
1129 if (__srefill(fp)) goto out;
1130 }
1131
1132 // Read directly into the caller's buffer.
1133 while (total > 0) {
1134 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, total);
1135 if (bytes_read <= 0) {
1136 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1137 break;
1138 }
1139 dst += bytes_read;
1140 total -= bytes_read;
1141 }
1142
1143out:
1144 return ((desired_total - total) / size);
1145}
1146
1147size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1148 CHECK_FP(fp);
1149 ScopedFileLock sfl(fp);
1150 return fwrite_unlocked(buf, size, count, fp);
1151}
1152
1153size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1154 CHECK_FP(fp);
1155
1156 size_t n;
1157 if (__builtin_mul_overflow(size, count, &n)) {
1158 errno = EOVERFLOW;
1159 fp->_flags |= __SERR;
1160 return 0;
1161 }
1162
1163 if (n == 0) return 0;
1164
1165 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1166 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1167
1168 _SET_ORIENTATION(fp, -1);
1169
1170 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1171 // since divides are generally slow.
1172 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1173}
1174
Elliott Hughes468efc82018-07-10 14:39:49 -07001175static FILE* __popen_fail(int fds[2]) {
1176 ErrnoRestorer errno_restorer;
1177 close(fds[0]);
1178 close(fds[1]);
1179 return nullptr;
1180}
1181
1182FILE* popen(const char* cmd, const char* mode) {
Elliott Hughes468efc82018-07-10 14:39:49 -07001183 // Was the request for a socketpair or just a pipe?
1184 int fds[2];
1185 bool bidirectional = false;
1186 if (strchr(mode, '+') != nullptr) {
1187 if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1188 bidirectional = true;
1189 mode = "r+";
1190 } else {
1191 if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1192 mode = strrchr(mode, 'r') ? "r" : "w";
1193 }
1194
1195 // If the parent wants to read, the child's fd needs to be stdout.
1196 int parent, child, desired_child_fd;
1197 if (*mode == 'r') {
1198 parent = 0;
1199 child = 1;
1200 desired_child_fd = STDOUT_FILENO;
1201 } else {
1202 parent = 1;
1203 child = 0;
1204 desired_child_fd = STDIN_FILENO;
1205 }
1206
1207 // Ensure that the child fd isn't the desired child fd.
1208 if (fds[child] == desired_child_fd) {
1209 int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1210 if (new_fd == -1) return __popen_fail(fds);
1211 close(fds[child]);
1212 fds[child] = new_fd;
1213 }
1214
1215 pid_t pid = vfork();
1216 if (pid == -1) return __popen_fail(fds);
1217
1218 if (pid == 0) {
1219 close(fds[parent]);
Elliott Hughes468efc82018-07-10 14:39:49 -07001220 // dup2 so that the child fd isn't closed on exec.
1221 if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1222 close(fds[child]);
1223 if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
Elliott Hughes886370c2019-03-21 21:11:41 -07001224 execl(__bionic_get_shell_path(), "sh", "-c", cmd, nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001225 _exit(127);
1226 }
1227
1228 FILE* fp = fdopen(fds[parent], mode);
1229 if (fp == nullptr) return __popen_fail(fds);
1230
Elliott Hughes468efc82018-07-10 14:39:49 -07001231 close(fds[child]);
1232
1233 _EXT(fp)->_popen_pid = pid;
1234 return fp;
1235}
1236
Elliott Hughes22917f62018-10-01 14:21:07 -07001237int pclose(FILE* fp) {
1238 CHECK_FP(fp);
1239 return __FILE_close(fp);
1240}
1241
Dan Albert3037ea42016-10-06 15:46:45 -07001242namespace {
1243
1244namespace phony {
1245#include <bits/struct_file.h>
1246}
1247
1248static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1249 "size mismatch between `struct __sFILE` implementation and public stub");
1250static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1251 "alignment mismatch between `struct __sFILE` implementation and public stub");
1252
1253}