blob: ee42726cab2671c35f8e666ba67e9c2009974e9e [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 "glue.h"
Elliott Hughesf9cfecf2021-02-04 16:58:13 -080054#include "local.h"
55#include "private/ErrnoRestorer.h"
56#include "private/FdPath.h"
Elliott Hughes886370c2019-03-21 21:11:41 -070057#include "private/__bionic_get_shell_path.h"
Elliott Hughesfb3873d2016-08-10 11:07:54 -070058#include "private/bionic_fortify.h"
Elliott Hughes6a03abc2014-11-03 12:32:17 -080059
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060#define NDYNAMIC 10 /* add ten more whenever necessary */
61
Elliott Hughes70715da2016-08-01 16:35:17 -070062#define PRINTF_IMPL(expr) \
63 va_list ap; \
64 va_start(ap, fmt); \
65 int result = (expr); \
66 va_end(ap); \
67 return result;
68
Elliott Hughes468efc82018-07-10 14:39:49 -070069#define MAKE_STD_STREAM(flags, fd) \
70 { \
71 ._flags = flags, ._file = fd, ._cookie = __sF + fd, ._close = __sclose, \
72 ._read = __sread, ._write = __swrite, ._ext = { \
73 ._base = reinterpret_cast<uint8_t*>(__sFext + fd) \
74 } \
75 }
Elliott Hughes29ee6392015-12-07 11:07:15 -080076
Elliott Hughesbb46afd2015-12-04 18:03:12 -080077static struct __sfileext __sFext[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -070078 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
79 ._caller_handles_locking = false,
80 ._seek64 = __sseek64,
81 ._popen_pid = 0},
82 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
83 ._caller_handles_locking = false,
84 ._seek64 = __sseek64,
85 ._popen_pid = 0},
86 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
87 ._caller_handles_locking = false,
88 ._seek64 = __sseek64,
89 ._popen_pid = 0},
Elliott Hughesbb46afd2015-12-04 18:03:12 -080090};
Elliott Hughesf0141df2015-10-12 12:44:23 -070091
92// __sF is exported for backwards compatibility. Until M, we didn't have symbols
93// for stdin/stdout/stderr; they were macros accessing __sF.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080094FILE __sF[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -070095 MAKE_STD_STREAM(__SRD, STDIN_FILENO),
96 MAKE_STD_STREAM(__SWR, STDOUT_FILENO),
97 MAKE_STD_STREAM(__SWR|__SNBF, STDERR_FILENO),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080098};
Elliott Hughesf0141df2015-10-12 12:44:23 -070099
Elliott Hughes168667c2014-11-14 14:42:59 -0800100FILE* stdin = &__sF[0];
101FILE* stdout = &__sF[1];
102FILE* stderr = &__sF[2];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700104static pthread_mutex_t __stdio_mutex = PTHREAD_MUTEX_INITIALIZER;
Josh Gaof6e5b582018-06-01 15:30:54 -0700105
106static uint64_t __get_file_tag(FILE* fp) {
107 // Don't use a tag for the standard streams.
108 // They don't really own their file descriptors, because the values are well-known, and you're
109 // allowed to do things like `close(STDIN_FILENO); open("foo", O_RDONLY)` when single-threaded.
110 if (fp == stdin || fp == stderr || fp == stdout) {
111 return 0;
112 }
113
114 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE,
115 reinterpret_cast<uint64_t>(fp));
116}
117
Elliott Hughes37ad9592017-10-30 17:47:12 -0700118struct glue __sglue = { nullptr, 3, __sF };
Elliott Hughesbb46afd2015-12-04 18:03:12 -0800119static struct glue* lastglue = &__sglue;
120
Elliott Hughes2704bd12016-01-20 17:14:53 -0800121class ScopedFileLock {
122 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -0700123 explicit ScopedFileLock(FILE* fp) : fp_(fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800124 FLOCKFILE(fp_);
125 }
126 ~ScopedFileLock() {
127 FUNLOCKFILE(fp_);
128 }
129
130 private:
131 FILE* fp_;
132};
133
Elliott Hughes021335e2016-01-19 16:28:15 -0800134static glue* moreglue(int n) {
Elliott Hughese1187782024-10-16 17:50:45 +0000135 char* data = new char[sizeof(glue) +
136 alignof(FILE) + n * sizeof(FILE) +
137 alignof(__sfileext) + n * sizeof(__sfileext)];
Elliott Hughes2704bd12016-01-20 17:14:53 -0800138 if (data == nullptr) return nullptr;
Elliott Hughes021335e2016-01-19 16:28:15 -0800139
Elliott Hughes2704bd12016-01-20 17:14:53 -0800140 glue* g = reinterpret_cast<glue*>(data);
Elliott Hughese1187782024-10-16 17:50:45 +0000141 FILE* p = reinterpret_cast<FILE*>(__builtin_align_up(g + 1, alignof(FILE)));
142 __sfileext* pext = reinterpret_cast<__sfileext*>(__builtin_align_up(p + n, alignof(__sfileext)));
Elliott Hughes37ad9592017-10-30 17:47:12 -0700143 g->next = nullptr;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800144 g->niobs = n;
145 g->iobs = p;
146 while (--n >= 0) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700147 *p = {};
Elliott Hughes2704bd12016-01-20 17:14:53 -0800148 _FILEEXT_SETUP(p, pext);
149 p++;
150 pext++;
151 }
152 return g;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800153}
154
Elliott Hughes80e4c152017-07-21 13:57:55 -0700155static inline void free_fgetln_buffer(FILE* fp) {
156 if (__predict_false(fp->_lb._base != nullptr)) {
157 free(fp->_lb._base);
158 fp->_lb._base = nullptr;
159 }
160}
161
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800162/*
163 * Find a free FILE for fopen et al.
164 */
Elliott Hughes021335e2016-01-19 16:28:15 -0800165FILE* __sfp(void) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166 FILE *fp;
167 int n;
168 struct glue *g;
169
Elliott Hughes468efc82018-07-10 14:39:49 -0700170 pthread_mutex_lock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700171 for (g = &__sglue; g != nullptr; g = g->next) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800172 for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
173 if (fp->_flags == 0)
174 goto found;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800175 }
Kenny Rootf5823402011-02-12 07:13:44 -0800176
177 /* release lock while mallocing */
Elliott Hughes468efc82018-07-10 14:39:49 -0700178 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700179 if ((g = moreglue(NDYNAMIC)) == nullptr) return nullptr;
Elliott Hughes468efc82018-07-10 14:39:49 -0700180 pthread_mutex_lock(&__stdio_mutex);
Kenny Rootf5823402011-02-12 07:13:44 -0800181 lastglue->next = g;
182 lastglue = g;
183 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800184found:
185 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Elliott Hughes468efc82018-07-10 14:39:49 -0700186 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700187 fp->_p = nullptr; /* no current pointer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800188 fp->_w = 0; /* nothing to read or write */
189 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700190 fp->_bf._base = nullptr; /* no buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800191 fp->_bf._size = 0;
192 fp->_lbfsize = 0; /* not line buffered */
193 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800194
Elliott Hughes37ad9592017-10-30 17:47:12 -0700195 fp->_lb._base = nullptr; /* no line buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800196 fp->_lb._size = 0;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800197
198 memset(_EXT(fp), 0, sizeof(struct __sfileext));
Elliott Hughes20dd3fe2023-03-02 01:26:29 +0000199 _EXT(fp)->_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800200 _EXT(fp)->_caller_handles_locking = false;
Elliott Hughes023c3072016-01-22 15:04:51 -0800201
202 // Caller sets cookie, _read/_write etc.
203 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
204 fp->_seek = nullptr;
205 _EXT(fp)->_seek64 = nullptr;
206
207 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800208}
209
Elliott Hughes468efc82018-07-10 14:39:49 -0700210int _fwalk(int (*callback)(FILE*)) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700211 int result = 0;
212 for (glue* g = &__sglue; g != nullptr; g = g->next) {
213 FILE* fp = g->iobs;
214 for (int n = g->niobs; --n >= 0; ++fp) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700215 if (fp->_flags != 0 && (fp->_flags & __SIGN) == 0) {
216 result |= (*callback)(fp);
217 }
218 }
219 }
Elliott Hughes468efc82018-07-10 14:39:49 -0700220 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800221}
Elliott Hughes923f1652016-01-19 15:46:05 -0800222
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700223extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
224 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
225 _fwalk(__sflush);
226}
227
Elliott Hughesd3915c72021-02-08 16:24:46 -0800228static FILE* __FILE_init(FILE* fp, int fd, int flags) {
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800229 if (fp == nullptr) return nullptr;
230
Elliott Hughesd3915c72021-02-08 16:24:46 -0800231#if !defined(__LP64__)
232 if (fd > SHRT_MAX) __fortify_fatal("stdio: fd %d > SHRT_MAX", fd);
233#endif
234
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800235 fp->_file = fd;
236 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
237 fp->_flags = flags;
238 fp->_cookie = fp;
239 fp->_read = __sread;
240 fp->_write = __swrite;
241 fp->_close = __sclose;
242 _EXT(fp)->_seek64 = __sseek64;
Elliott Hughes023c3072016-01-22 15:04:51 -0800243 return fp;
244}
245
246FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700247 int mode_flags;
248 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800249 if (flags == 0) return nullptr;
250
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700251 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800252 if (fd == -1) {
253 return nullptr;
254 }
255
Elliott Hughesd3915c72021-02-08 16:24:46 -0800256 FILE* fp = __FILE_init(__sfp(), fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800257 if (fp == nullptr) {
258 ErrnoRestorer errno_restorer;
259 close(fd);
260 return nullptr;
261 }
262
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800263 // For append mode, O_APPEND sets the write position for free, but we need to
264 // set the read position manually.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700265 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800266 return fp;
267}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800268__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800269
270FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700271 int mode_flags;
272 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800273 if (flags == 0) return nullptr;
274
275 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700276 int fd_flags = fcntl(fd, F_GETFL, 0);
277 if (fd_flags == -1) return nullptr;
278 int tmp = fd_flags & O_ACCMODE;
279 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800280 errno = EINVAL;
281 return nullptr;
282 }
283
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700284 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
285 // POSIX says we just take the current offset of the underlying fd.
286 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
287 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
288 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800289
Dan Albertba1151c2019-03-26 13:01:22 -0700290 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'e'.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700291 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800292 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
293 }
294
Elliott Hughesd3915c72021-02-08 16:24:46 -0800295 return __FILE_init(__sfp(), fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800296}
297
Elliott Hughes023c3072016-01-22 15:04:51 -0800298FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700299 CHECK_FP(fp);
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800300
301 // POSIX says: "If pathname is a null pointer, the freopen() function shall
302 // attempt to change the mode of the stream to that specified by mode, as if
303 // the name of the file currently associated with the stream had been used. In
304 // this case, the file descriptor associated with the stream need not be
305 // closed if the call to freopen() succeeds. It is implementation-defined
306 // which changes of mode are permitted (if any), and under what
307 // circumstances."
308 //
309 // Linux is quite restrictive about what changes you can make with F_SETFL,
310 // and in particular won't let you touch the access bits. It's easiest and
311 // most effective to just rely on /proc/self/fd/...
312 FdPath fd_path(fp->_file);
313 if (file == nullptr) file = fd_path.c_str();
314
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700315 int mode_flags;
316 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800317 if (flags == 0) {
318 fclose(fp);
319 return nullptr;
320 }
321
322 ScopedFileLock sfl(fp);
323
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800324 // TODO: rewrite this mess completely.
325
Elliott Hughes023c3072016-01-22 15:04:51 -0800326 // There are actually programs that depend on being able to "freopen"
327 // descriptors that weren't originally open. Keep this from breaking.
328 // Remember whether the stream was open to begin with, and which file
329 // descriptor (if any) was associated with it. If it was attached to
330 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
331 // should work. This is unnecessary if it was not a Unix file.
332 int isopen, wantfd;
333 if (fp->_flags == 0) {
334 fp->_flags = __SEOF; // Hold on to it.
335 isopen = 0;
336 wantfd = -1;
337 } else {
338 // Flush the stream; ANSI doesn't require this.
339 if (fp->_flags & __SWR) __sflush(fp);
340
Elliott Hughes37ad9592017-10-30 17:47:12 -0700341 // If close is null, closing is a no-op, hence pointless.
342 isopen = (fp->_close != nullptr);
Elliott Hughes023c3072016-01-22 15:04:51 -0800343 if ((wantfd = fp->_file) < 0 && isopen) {
344 (*fp->_close)(fp->_cookie);
345 isopen = 0;
346 }
347 }
348
349 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700350 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800351 if (fd < 0 && isopen) {
352 // If out of fd's close the old one and try again.
353 if (errno == ENFILE || errno == EMFILE) {
354 (*fp->_close)(fp->_cookie);
355 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700356 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800357 }
358 }
359
360 int sverrno = errno;
361
362 // Finish closing fp. Even if the open succeeded above, we cannot
363 // keep fp->_base: it may be the wrong size. This loses the effect
364 // of any setbuffer calls, but stdio has always done this before.
365 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
366 if (fp->_flags & __SMBF) free(fp->_bf._base);
367 fp->_w = 0;
368 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700369 fp->_p = nullptr;
370 fp->_bf._base = nullptr;
Elliott Hughes023c3072016-01-22 15:04:51 -0800371 fp->_bf._size = 0;
372 fp->_lbfsize = 0;
373 if (HASUB(fp)) FREEUB(fp);
374 _UB(fp)._size = 0;
375 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700376 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800377 fp->_lb._size = 0;
378
379 if (fd < 0) { // Did not get it after all.
380 fp->_flags = 0; // Release.
381 errno = sverrno; // Restore errno in case _close clobbered it.
382 return nullptr;
383 }
384
385 // If reopening something that was open before on a real file, try
386 // to maintain the descriptor. Various C library routines (perror)
387 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
388 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700389 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800390 close(fd);
391 fd = wantfd;
392 }
393 }
394
Elliott Hughesd3915c72021-02-08 16:24:46 -0800395 __FILE_init(fp, fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800396
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800397 // For append mode, O_APPEND sets the write position for free, but we need to
398 // set the read position manually.
Elliott Hughesd3915c72021-02-08 16:24:46 -0800399 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800400
Elliott Hughes023c3072016-01-22 15:04:51 -0800401 return fp;
402}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800403__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800404
Elliott Hughesf2d7d012025-09-08 12:20:38 -0700405int fclose(FILE* fp) {
406 CHECK_FP(fp);
407
Elliott Hughes2704bd12016-01-20 17:14:53 -0800408 if (fp->_flags == 0) {
409 // Already freed!
410 errno = EBADF;
411 return EOF;
412 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800413
Elliott Hughes2704bd12016-01-20 17:14:53 -0800414 ScopedFileLock sfl(fp);
415 WCIO_FREE(fp);
416 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700417 if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800418 r = EOF;
419 }
420 if (fp->_flags & __SMBF) free(fp->_bf._base);
421 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700422 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800423
Elliott Hughes468efc82018-07-10 14:39:49 -0700424 // If we were created by popen(3), wait for the child.
425 pid_t pid = _EXT(fp)->_popen_pid;
426 if (pid > 0) {
427 int status;
428 if (TEMP_FAILURE_RETRY(wait4(pid, &status, 0, nullptr)) != -1) {
429 r = status;
430 }
431 }
432 _EXT(fp)->_popen_pid = 0;
433
Elliott Hughes2704bd12016-01-20 17:14:53 -0800434 // Poison this FILE so accesses after fclose will be obvious.
435 fp->_file = -1;
436 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800437
Elliott Hughes2704bd12016-01-20 17:14:53 -0800438 // Release this FILE for reuse.
439 fp->_flags = 0;
440 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800441}
Elliott Hughesf2d7d012025-09-08 12:20:38 -0700442__strong_alias(pclose, fclose);
Elliott Hughes923f1652016-01-19 15:46:05 -0800443
Elliott Hughescceaf062016-07-29 16:31:52 -0700444int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700445 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700446 int fd = fp->_file;
447 if (fd == -1) {
448 errno = EBADF;
449 return -1;
450 }
451 return fd;
452}
453
Elliott Hughes923f1652016-01-19 15:46:05 -0800454int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700455 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800456 ScopedFileLock sfl(fp);
457 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800458}
Elliott Hughes021335e2016-01-19 16:28:15 -0800459
Elliott Hughescceaf062016-07-29 16:31:52 -0700460void clearerr_unlocked(FILE* fp) {
Elliott Hughes22917f62018-10-01 14:21:07 -0700461 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700462 return __sclearerr(fp);
463}
464
465void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700466 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700467 ScopedFileLock sfl(fp);
468 clearerr_unlocked(fp);
469}
470
471int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700472 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700473 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700474}
475
476int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700477 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700478 ScopedFileLock sfl(fp);
479 return feof_unlocked(fp);
480}
481
482int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700483 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700484 return __sferror(fp);
485}
486
487int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700488 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700489 ScopedFileLock sfl(fp);
490 return ferror_unlocked(fp);
491}
492
Elliott Hughes37ad9592017-10-30 17:47:12 -0700493int __sflush(FILE* fp) {
494 // Flushing a read-only file is a no-op.
495 if ((fp->_flags & __SWR) == 0) return 0;
496
497 // Flushing a file without a buffer is a no-op.
498 unsigned char* p = fp->_bf._base;
499 if (p == nullptr) return 0;
500
501 // Set these immediately to avoid problems with longjmp and to allow
502 // exchange buffering (via setvbuf) in user write function.
503 int n = fp->_p - p;
504 fp->_p = p;
505 fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
506
507 while (n > 0) {
508 int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
509 if (written <= 0) {
510 fp->_flags |= __SERR;
511 return EOF;
512 }
513 n -= written, p += written;
514 }
515 return 0;
516}
517
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700518int __sflush_locked(FILE* fp) {
519 ScopedFileLock sfl(fp);
520 return __sflush(fp);
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) {
Elliott Hughes7cebf832020-08-12 14:25:41 -0700771 if (n <= 0) __fortify_fatal("fgets: buffer size %d <= 0", n);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700772
Elliott Hughes531199c2023-05-09 16:11:49 -0700773 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700774
775 char* s = buf;
776 n--; // Leave space for NUL.
777 while (n != 0) {
778 // If the buffer is empty, refill it.
779 if (fp->_r <= 0) {
780 if (__srefill(fp)) {
781 // EOF/error: stop with partial or no line.
782 if (s == buf) return nullptr;
783 break;
784 }
785 }
786 size_t len = fp->_r;
787 unsigned char* p = fp->_p;
788
789 // Scan through at most n bytes of the current buffer,
790 // looking for '\n'. If found, copy up to and including
791 // newline, and stop. Otherwise, copy entire chunk and loop.
792 if (len > static_cast<size_t>(n)) len = n;
793 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
794 if (t != nullptr) {
795 len = ++t - p;
796 fp->_r -= len;
797 fp->_p = t;
798 memcpy(s, p, len);
799 s[len] = '\0';
800 return buf;
801 }
802 fp->_r -= len;
803 fp->_p += len;
804 memcpy(s, p, len);
805 s += len;
806 n -= len;
807 }
808 *s = '\0';
809 return buf;
810}
811
Elliott Hughescceaf062016-07-29 16:31:52 -0700812int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700813 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700814 return putc(c, fp);
815}
816
Elliott Hughes37ad9592017-10-30 17:47:12 -0700817int fputc_unlocked(int c, FILE* fp) {
818 CHECK_FP(fp);
819 return putc_unlocked(c, fp);
820}
821
822int fputs(const char* s, FILE* fp) {
823 CHECK_FP(fp);
824 ScopedFileLock sfl(fp);
825 return fputs_unlocked(s, fp);
826}
827
828int fputs_unlocked(const char* s, FILE* fp) {
829 CHECK_FP(fp);
830 size_t length = strlen(s);
831 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
832}
833
Elliott Hughes70715da2016-08-01 16:35:17 -0700834int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700835 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700836 PRINTF_IMPL(vfscanf(fp, fmt, ap));
837}
838
839int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700840 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700841 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
842}
843
844int fwscanf(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(vfwscanf(fp, fmt, ap));
847}
848
849int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700850 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700851 ScopedFileLock sfl(fp);
852 return getc_unlocked(fp);
853}
854
855int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700856 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700857 return __sgetc(fp);
858}
859
860int getchar_unlocked() {
861 return getc_unlocked(stdin);
862}
863
864int getchar() {
865 return getc(stdin);
866}
867
Elliott Hughescceaf062016-07-29 16:31:52 -0700868ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700869 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700870 return getdelim(buf, len, '\n', fp);
871}
872
873wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700874 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700875 return fgetwc(fp);
876}
877
878wint_t getwchar() {
879 return fgetwc(stdin);
880}
881
Elliott Hughes37ad9592017-10-30 17:47:12 -0700882void perror(const char* msg) {
883 if (msg == nullptr) msg = "";
Elliott Hughesae1c64a2023-03-03 23:46:34 +0000884 fprintf(stderr, "%s%s%m\n", msg, (*msg == '\0') ? "" : ": ");
Elliott Hughes37ad9592017-10-30 17:47:12 -0700885}
886
Elliott Hughes70715da2016-08-01 16:35:17 -0700887int printf(const char* fmt, ...) {
888 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
889}
890
891int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700892 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700893 ScopedFileLock sfl(fp);
894 return putc_unlocked(c, fp);
895}
896
897int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700898 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700899 if (cantwrite(fp)) {
900 errno = EBADF;
901 return EOF;
902 }
Elliott Hughes531199c2023-05-09 16:11:49 -0700903 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes70715da2016-08-01 16:35:17 -0700904 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
905 return (*fp->_p++ = c);
906 }
907 return (__swbuf(c, fp));
908}
909
910int putchar(int c) {
911 return putc(c, stdout);
912}
913
914int putchar_unlocked(int c) {
915 return putc_unlocked(c, stdout);
916}
917
Elliott Hughes37ad9592017-10-30 17:47:12 -0700918int puts(const char* s) {
919 size_t length = strlen(s);
920 ScopedFileLock sfl(stdout);
921 return (fwrite_unlocked(s, 1, length, stdout) == length &&
922 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
923}
924
Elliott Hughescceaf062016-07-29 16:31:52 -0700925wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700926 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700927 return fputwc(wc, fp);
928}
929
930wint_t putwchar(wchar_t wc) {
931 return fputwc(wc, stdout);
932}
933
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700934int remove(const char* path) {
935 if (unlink(path) != -1) return 0;
936 if (errno != EISDIR) return -1;
937 return rmdir(path);
938}
939
Elliott Hughescceaf062016-07-29 16:31:52 -0700940void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700941 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700942 ScopedFileLock sfl(fp);
943 fseek(fp, 0, SEEK_SET);
944 clearerr_unlocked(fp);
945}
946
Elliott Hughes70715da2016-08-01 16:35:17 -0700947int scanf(const char* fmt, ...) {
948 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
949}
950
Elliott Hughescceaf062016-07-29 16:31:52 -0700951void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -0700952 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700953 setbuffer(fp, buf, BUFSIZ);
954}
955
956void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -0700957 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700958 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
959}
960
961int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700962 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700963 return setvbuf(fp, nullptr, _IOLBF, 0);
964}
965
Elliott Hughes53cf3482016-08-09 13:06:41 -0700966int snprintf(char* s, size_t n, const char* fmt, ...) {
967 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
968}
969
970int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -0700971 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -0700972}
973
974int sscanf(const char* s, const char* fmt, ...) {
975 PRINTF_IMPL(vsscanf(s, fmt, ap));
976}
977
Elliott Hughes70715da2016-08-01 16:35:17 -0700978int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
979 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
980}
981
982int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
983 PRINTF_IMPL(vswscanf(s, fmt, ap));
984}
985
Elliott Hughes618303c2017-11-02 16:58:44 -0700986int vfprintf(FILE* fp, const char* fmt, va_list ap) {
987 ScopedFileLock sfl(fp);
988 return __vfprintf(fp, fmt, ap);
989}
990
Elliott Hughes345b7272017-11-10 16:20:43 -0800991int vfscanf(FILE* fp, const char* fmt, va_list ap) {
992 ScopedFileLock sfl(fp);
993 return __svfscanf(fp, fmt, ap);
994}
995
Elliott Hughes618303c2017-11-02 16:58:44 -0700996int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
997 ScopedFileLock sfl(fp);
998 return __vfwprintf(fp, fmt, ap);
999}
1000
Elliott Hughes345b7272017-11-10 16:20:43 -08001001int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1002 ScopedFileLock sfl(fp);
1003 return __vfwscanf(fp, fmt, ap);
1004}
1005
Elliott Hughescceaf062016-07-29 16:31:52 -07001006int vprintf(const char* fmt, va_list ap) {
1007 return vfprintf(stdout, fmt, ap);
1008}
1009
1010int vscanf(const char* fmt, va_list ap) {
1011 return vfscanf(stdin, fmt, ap);
1012}
1013
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001014int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1015 // stdio internals use int rather than size_t.
1016 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1017
1018 __check_count("vsnprintf", "size", n);
1019
1020 // Stdio internals do not deal correctly with zero length buffer.
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001021 char one_byte_buffer[1];
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001022 if (n == 0) {
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001023 s = one_byte_buffer;
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001024 n = 1;
1025 }
1026
1027 FILE f;
1028 __sfileext fext;
1029 _FILEEXT_SETUP(&f, &fext);
1030 f._file = -1;
1031 f._flags = __SWR | __SSTR;
1032 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1033 f._bf._size = f._w = n - 1;
1034
1035 int result = __vfprintf(&f, fmt, ap);
1036 *f._p = '\0';
1037 return result;
1038}
1039
Elliott Hughes53cf3482016-08-09 13:06:41 -07001040int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001041 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -07001042}
1043
Elliott Hughescceaf062016-07-29 16:31:52 -07001044int vwprintf(const wchar_t* fmt, va_list ap) {
1045 return vfwprintf(stdout, fmt, ap);
1046}
1047
1048int vwscanf(const wchar_t* fmt, va_list ap) {
1049 return vfwscanf(stdin, fmt, ap);
1050}
Elliott Hughes70715da2016-08-01 16:35:17 -07001051
1052int wprintf(const wchar_t* fmt, ...) {
1053 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1054}
1055
1056int wscanf(const wchar_t* fmt, ...) {
1057 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1058}
Dan Albert3037ea42016-10-06 15:46:45 -07001059
Elliott Hughes37ad9592017-10-30 17:47:12 -07001060static int fflush_all() {
Ryan Prichardc485cdb2019-04-30 14:47:34 -07001061 return _fwalk(__sflush_locked);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001062}
1063
1064int fflush(FILE* fp) {
1065 if (fp == nullptr) return fflush_all();
1066 ScopedFileLock sfl(fp);
1067 return fflush_unlocked(fp);
1068}
1069
1070int fflush_unlocked(FILE* fp) {
1071 if (fp == nullptr) return fflush_all();
1072 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1073 errno = EBADF;
1074 return EOF;
1075 }
1076 return __sflush(fp);
1077}
1078
Elliott Hughes00a2a6f2024-08-12 21:32:07 +00001079int fpurge(FILE* fp) {
1080 CHECK_FP(fp);
1081
1082 ScopedFileLock sfl(fp);
1083
1084 if (fp->_flags == 0) {
1085 // Already freed!
1086 errno = EBADF;
1087 return EOF;
1088 }
1089
1090 if (HASUB(fp)) FREEUB(fp);
1091 WCIO_FREE(fp);
1092 fp->_p = fp->_bf._base;
1093 fp->_r = 0;
1094 fp->_w = fp->_flags & (__SLBF | __SNBF) ? 0 : fp->_bf._size;
1095 return 0;
1096}
1097__strong_alias(__fpurge, fpurge);
1098
George Burgess IV90242352018-02-06 12:51:31 -08001099size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -07001100 CHECK_FP(fp);
1101 ScopedFileLock sfl(fp);
1102 return fread_unlocked(buf, size, count, fp);
1103}
1104
1105size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1106 CHECK_FP(fp);
1107
1108 size_t desired_total;
1109 if (__builtin_mul_overflow(size, count, &desired_total)) {
1110 errno = EOVERFLOW;
1111 fp->_flags |= __SERR;
1112 return 0;
1113 }
1114
1115 size_t total = desired_total;
1116 if (total == 0) return 0;
1117
Elliott Hughes531199c2023-05-09 16:11:49 -07001118 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001119
1120 // TODO: how can this ever happen?!
1121 if (fp->_r < 0) fp->_r = 0;
1122
1123 // Ensure _bf._size is valid.
1124 if (fp->_bf._base == nullptr) __smakebuf(fp);
1125
1126 char* dst = static_cast<char*>(buf);
1127
1128 while (total > 0) {
1129 // Copy data out of the buffer.
1130 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1131 memcpy(dst, fp->_p, buffered_bytes);
1132 fp->_p += buffered_bytes;
1133 fp->_r -= buffered_bytes;
1134 dst += buffered_bytes;
1135 total -= buffered_bytes;
1136
1137 // Are we done?
1138 if (total == 0) goto out;
1139
1140 // Do we have so much more to read that we should avoid copying it through the buffer?
1141 if (total > static_cast<size_t>(fp->_bf._size)) break;
1142
1143 // Less than a buffer to go, so refill the buffer and go around the loop again.
1144 if (__srefill(fp)) goto out;
1145 }
1146
1147 // Read directly into the caller's buffer.
1148 while (total > 0) {
Elliott Hughesbe78fc92022-07-28 20:58:45 +00001149 // The _read function pointer takes an int instead of a size_t.
1150 int chunk_size = MIN(total, INT_MAX);
1151 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, chunk_size);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001152 if (bytes_read <= 0) {
1153 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1154 break;
1155 }
1156 dst += bytes_read;
1157 total -= bytes_read;
1158 }
1159
1160out:
1161 return ((desired_total - total) / size);
1162}
1163
1164size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1165 CHECK_FP(fp);
1166 ScopedFileLock sfl(fp);
1167 return fwrite_unlocked(buf, size, count, fp);
1168}
1169
1170size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1171 CHECK_FP(fp);
1172
1173 size_t n;
1174 if (__builtin_mul_overflow(size, count, &n)) {
1175 errno = EOVERFLOW;
1176 fp->_flags |= __SERR;
1177 return 0;
1178 }
1179
1180 if (n == 0) return 0;
1181
1182 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1183 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1184
Elliott Hughes531199c2023-05-09 16:11:49 -07001185 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001186
1187 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1188 // since divides are generally slow.
1189 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1190}
1191
Elliott Hughes468efc82018-07-10 14:39:49 -07001192static FILE* __popen_fail(int fds[2]) {
1193 ErrnoRestorer errno_restorer;
1194 close(fds[0]);
1195 close(fds[1]);
1196 return nullptr;
1197}
1198
1199FILE* popen(const char* cmd, const char* mode) {
Elliott Hughes468efc82018-07-10 14:39:49 -07001200 // Was the request for a socketpair or just a pipe?
1201 int fds[2];
1202 bool bidirectional = false;
1203 if (strchr(mode, '+') != nullptr) {
1204 if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1205 bidirectional = true;
1206 mode = "r+";
1207 } else {
1208 if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1209 mode = strrchr(mode, 'r') ? "r" : "w";
1210 }
1211
1212 // If the parent wants to read, the child's fd needs to be stdout.
1213 int parent, child, desired_child_fd;
1214 if (*mode == 'r') {
1215 parent = 0;
1216 child = 1;
1217 desired_child_fd = STDOUT_FILENO;
1218 } else {
1219 parent = 1;
1220 child = 0;
1221 desired_child_fd = STDIN_FILENO;
1222 }
1223
1224 // Ensure that the child fd isn't the desired child fd.
1225 if (fds[child] == desired_child_fd) {
1226 int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1227 if (new_fd == -1) return __popen_fail(fds);
1228 close(fds[child]);
1229 fds[child] = new_fd;
1230 }
1231
1232 pid_t pid = vfork();
1233 if (pid == -1) return __popen_fail(fds);
1234
1235 if (pid == 0) {
1236 close(fds[parent]);
Elliott Hughes468efc82018-07-10 14:39:49 -07001237 // dup2 so that the child fd isn't closed on exec.
1238 if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1239 close(fds[child]);
1240 if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
Elliott Hughesb6b7e2e2021-11-04 17:18:58 -07001241 execl(__bionic_get_shell_path(), "sh", "-c", "--", cmd, nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001242 _exit(127);
1243 }
1244
1245 FILE* fp = fdopen(fds[parent], mode);
1246 if (fp == nullptr) return __popen_fail(fds);
1247
Elliott Hughes468efc82018-07-10 14:39:49 -07001248 close(fds[child]);
1249
1250 _EXT(fp)->_popen_pid = pid;
1251 return fp;
1252}
1253
Elliott Hughes20dd3fe2023-03-02 01:26:29 +00001254void flockfile(FILE* fp) {
1255 CHECK_FP(fp);
1256 pthread_mutex_lock(&_EXT(fp)->_lock);
1257}
1258
1259int ftrylockfile(FILE* fp) {
1260 CHECK_FP(fp);
1261 // The specification for ftrylockfile() says it returns 0 on success,
1262 // or non-zero on error. We don't bother canonicalizing to 0/-1...
1263 return pthread_mutex_trylock(&_EXT(fp)->_lock);
1264}
1265
1266void funlockfile(FILE* fp) {
1267 CHECK_FP(fp);
1268 pthread_mutex_unlock(&_EXT(fp)->_lock);
1269}
1270
Dan Albert3037ea42016-10-06 15:46:45 -07001271namespace {
1272
1273namespace phony {
1274#include <bits/struct_file.h>
1275}
1276
1277static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1278 "size mismatch between `struct __sFILE` implementation and public stub");
1279static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1280 "alignment mismatch between `struct __sFILE` implementation and public stub");
1281
1282}