blob: 881198331032b960290f73d96948f08cbef192d0 [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
Elliott Hughesa07d9da2025-09-09 07:43:44 -070060// Check a FILE* isn't nullptr, so we can emit a clear diagnostic message
61// instead of just crashing with SIGSEGV.
62#define CHECK_FP(fp) \
63 if (fp == nullptr) __fortify_fatal("%s: null FILE*", __FUNCTION__)
64
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080065#define NDYNAMIC 10 /* add ten more whenever necessary */
66
Elliott Hughes70715da2016-08-01 16:35:17 -070067#define PRINTF_IMPL(expr) \
68 va_list ap; \
69 va_start(ap, fmt); \
70 int result = (expr); \
71 va_end(ap); \
72 return result;
73
Elliott Hughes468efc82018-07-10 14:39:49 -070074#define MAKE_STD_STREAM(flags, fd) \
75 { \
76 ._flags = flags, ._file = fd, ._cookie = __sF + fd, ._close = __sclose, \
77 ._read = __sread, ._write = __swrite, ._ext = { \
78 ._base = reinterpret_cast<uint8_t*>(__sFext + fd) \
79 } \
80 }
Elliott Hughes29ee6392015-12-07 11:07:15 -080081
Elliott Hughesbb46afd2015-12-04 18:03:12 -080082static struct __sfileext __sFext[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -070083 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
84 ._caller_handles_locking = false,
85 ._seek64 = __sseek64,
86 ._popen_pid = 0},
87 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
88 ._caller_handles_locking = false,
89 ._seek64 = __sseek64,
90 ._popen_pid = 0},
91 {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
92 ._caller_handles_locking = false,
93 ._seek64 = __sseek64,
94 ._popen_pid = 0},
Elliott Hughesbb46afd2015-12-04 18:03:12 -080095};
Elliott Hughesf0141df2015-10-12 12:44:23 -070096
97// __sF is exported for backwards compatibility. Until M, we didn't have symbols
98// for stdin/stdout/stderr; they were macros accessing __sF.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080099FILE __sF[3] = {
Elliott Hughes468efc82018-07-10 14:39:49 -0700100 MAKE_STD_STREAM(__SRD, STDIN_FILENO),
101 MAKE_STD_STREAM(__SWR, STDOUT_FILENO),
102 MAKE_STD_STREAM(__SWR|__SNBF, STDERR_FILENO),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103};
Elliott Hughesf0141df2015-10-12 12:44:23 -0700104
Elliott Hughes168667c2014-11-14 14:42:59 -0800105FILE* stdin = &__sF[0];
106FILE* stdout = &__sF[1];
107FILE* stderr = &__sF[2];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800108
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700109static pthread_mutex_t __stdio_mutex = PTHREAD_MUTEX_INITIALIZER;
Josh Gaof6e5b582018-06-01 15:30:54 -0700110
111static uint64_t __get_file_tag(FILE* fp) {
112 // Don't use a tag for the standard streams.
113 // They don't really own their file descriptors, because the values are well-known, and you're
114 // allowed to do things like `close(STDIN_FILENO); open("foo", O_RDONLY)` when single-threaded.
115 if (fp == stdin || fp == stderr || fp == stdout) {
116 return 0;
117 }
118
119 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE,
120 reinterpret_cast<uint64_t>(fp));
121}
122
Elliott Hughes37ad9592017-10-30 17:47:12 -0700123struct glue __sglue = { nullptr, 3, __sF };
Elliott Hughesbb46afd2015-12-04 18:03:12 -0800124static struct glue* lastglue = &__sglue;
125
Elliott Hughes2704bd12016-01-20 17:14:53 -0800126class ScopedFileLock {
127 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -0700128 explicit ScopedFileLock(FILE* fp) : fp_(fp) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800129 FLOCKFILE(fp_);
130 }
131 ~ScopedFileLock() {
132 FUNLOCKFILE(fp_);
133 }
134
135 private:
136 FILE* fp_;
137};
138
Elliott Hughes021335e2016-01-19 16:28:15 -0800139static glue* moreglue(int n) {
Elliott Hughese1187782024-10-16 17:50:45 +0000140 char* data = new char[sizeof(glue) +
141 alignof(FILE) + n * sizeof(FILE) +
142 alignof(__sfileext) + n * sizeof(__sfileext)];
Elliott Hughes2704bd12016-01-20 17:14:53 -0800143 if (data == nullptr) return nullptr;
Elliott Hughes021335e2016-01-19 16:28:15 -0800144
Elliott Hughes2704bd12016-01-20 17:14:53 -0800145 glue* g = reinterpret_cast<glue*>(data);
Elliott Hughese1187782024-10-16 17:50:45 +0000146 FILE* p = reinterpret_cast<FILE*>(__builtin_align_up(g + 1, alignof(FILE)));
147 __sfileext* pext = reinterpret_cast<__sfileext*>(__builtin_align_up(p + n, alignof(__sfileext)));
Elliott Hughes37ad9592017-10-30 17:47:12 -0700148 g->next = nullptr;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800149 g->niobs = n;
150 g->iobs = p;
151 while (--n >= 0) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700152 *p = {};
Elliott Hughes2704bd12016-01-20 17:14:53 -0800153 _FILEEXT_SETUP(p, pext);
154 p++;
155 pext++;
156 }
157 return g;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800158}
159
Elliott Hughes80e4c152017-07-21 13:57:55 -0700160static inline void free_fgetln_buffer(FILE* fp) {
161 if (__predict_false(fp->_lb._base != nullptr)) {
162 free(fp->_lb._base);
163 fp->_lb._base = nullptr;
164 }
165}
166
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800167/*
168 * Find a free FILE for fopen et al.
169 */
Elliott Hughes021335e2016-01-19 16:28:15 -0800170FILE* __sfp(void) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800171 FILE *fp;
172 int n;
173 struct glue *g;
174
Elliott Hughes468efc82018-07-10 14:39:49 -0700175 pthread_mutex_lock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700176 for (g = &__sglue; g != nullptr; g = g->next) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800177 for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
178 if (fp->_flags == 0)
179 goto found;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800180 }
Kenny Rootf5823402011-02-12 07:13:44 -0800181
182 /* release lock while mallocing */
Elliott Hughes468efc82018-07-10 14:39:49 -0700183 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700184 if ((g = moreglue(NDYNAMIC)) == nullptr) return nullptr;
Elliott Hughes468efc82018-07-10 14:39:49 -0700185 pthread_mutex_lock(&__stdio_mutex);
Kenny Rootf5823402011-02-12 07:13:44 -0800186 lastglue->next = g;
187 lastglue = g;
188 fp = g->iobs;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800189found:
190 fp->_flags = 1; /* reserve this slot; caller sets real flags */
Elliott Hughes468efc82018-07-10 14:39:49 -0700191 pthread_mutex_unlock(&__stdio_mutex);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700192 fp->_p = nullptr; /* no current pointer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800193 fp->_w = 0; /* nothing to read or write */
194 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700195 fp->_bf._base = nullptr; /* no buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800196 fp->_bf._size = 0;
197 fp->_lbfsize = 0; /* not line buffered */
198 fp->_file = -1; /* no file */
Elliott Hughes023c3072016-01-22 15:04:51 -0800199
Elliott Hughes37ad9592017-10-30 17:47:12 -0700200 fp->_lb._base = nullptr; /* no line buffer */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800201 fp->_lb._size = 0;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800202
203 memset(_EXT(fp), 0, sizeof(struct __sfileext));
Elliott Hughes20dd3fe2023-03-02 01:26:29 +0000204 _EXT(fp)->_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
Elliott Hughes1a56a262017-12-20 08:53:49 -0800205 _EXT(fp)->_caller_handles_locking = false;
Elliott Hughes023c3072016-01-22 15:04:51 -0800206
207 // Caller sets cookie, _read/_write etc.
208 // We explicitly clear _seek and _seek64 to prevent subtle bugs.
209 fp->_seek = nullptr;
210 _EXT(fp)->_seek64 = nullptr;
211
212 return fp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800213}
214
Elliott Hughes468efc82018-07-10 14:39:49 -0700215int _fwalk(int (*callback)(FILE*)) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700216 int result = 0;
217 for (glue* g = &__sglue; g != nullptr; g = g->next) {
218 FILE* fp = g->iobs;
219 for (int n = g->niobs; --n >= 0; ++fp) {
Elliott Hughes468efc82018-07-10 14:39:49 -0700220 if (fp->_flags != 0 && (fp->_flags & __SIGN) == 0) {
221 result |= (*callback)(fp);
222 }
223 }
224 }
Elliott Hughes468efc82018-07-10 14:39:49 -0700225 return result;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800226}
Elliott Hughes923f1652016-01-19 15:46:05 -0800227
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700228extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
229 // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
230 _fwalk(__sflush);
231}
232
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700233/*
234 * Allocate a file buffer, or switch to unbuffered I/O.
235 * Per the ANSI C standard, ALL tty devices default to line buffered.
236 *
237 * As a side effect, we set __SOPT or __SNPT (en/dis-able fseek
238 * optimisation) right after the fstat() that finds the buffer size.
239 */
240void
241__smakebuf(FILE *fp)
242{
243 unsigned char *p;
244 int flags;
245 size_t size;
246 int couldbetty;
247
248 if (fp->_flags & __SNBF) {
249 fp->_bf._base = fp->_p = fp->_nbuf;
250 fp->_bf._size = 1;
251 return;
252 }
253 flags = __swhatbuf(fp, &size, &couldbetty);
254 if ((p = static_cast<unsigned char*>(malloc(size))) == NULL) {
255 fp->_flags |= __SNBF;
256 fp->_bf._base = fp->_p = fp->_nbuf;
257 fp->_bf._size = 1;
258 return;
259 }
260 flags |= __SMBF;
261 fp->_bf._base = fp->_p = p;
262 fp->_bf._size = size;
263 if (couldbetty && isatty(fp->_file))
264 flags |= __SLBF;
265 fp->_flags |= flags;
266}
267
268/*
269 * Internal routine to determine `proper' buffering for a file.
270 */
271int
272__swhatbuf(FILE *fp, size_t *bufsize, int *couldbetty)
273{
274 struct stat st;
275
276 if (fp->_file < 0 || fstat(fp->_file, &st) == -1) {
277 *couldbetty = 0;
278 *bufsize = BUFSIZ;
279 return (__SNPT);
280 }
281
282 /* could be a tty iff it is a character device */
283 *couldbetty = S_ISCHR(st.st_mode);
284 if (st.st_blksize == 0) {
285 *bufsize = BUFSIZ;
286 return (__SNPT);
287 }
288
289 /*
290 * Optimise fseek() only if it is a regular file. (The test for
291 * __sseek is mainly paranoia.) It is safe to set _blksize
292 * unconditionally; it will only be used if __SOPT is also set.
293 */
294 *bufsize = st.st_blksize;
295 fp->_blksize = st.st_blksize;
296 return ((st.st_mode & S_IFMT) == S_IFREG && fp->_seek == __sseek ?
297 __SOPT : __SNPT);
298}
299
Elliott Hughesd3915c72021-02-08 16:24:46 -0800300static FILE* __FILE_init(FILE* fp, int fd, int flags) {
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800301 if (fp == nullptr) return nullptr;
302
Elliott Hughesd3915c72021-02-08 16:24:46 -0800303#if !defined(__LP64__)
304 if (fd > SHRT_MAX) __fortify_fatal("stdio: fd %d > SHRT_MAX", fd);
305#endif
306
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800307 fp->_file = fd;
308 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
309 fp->_flags = flags;
310 fp->_cookie = fp;
311 fp->_read = __sread;
312 fp->_write = __swrite;
313 fp->_close = __sclose;
314 _EXT(fp)->_seek64 = __sseek64;
Elliott Hughes023c3072016-01-22 15:04:51 -0800315 return fp;
316}
317
318FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700319 int mode_flags;
320 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800321 if (flags == 0) return nullptr;
322
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700323 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800324 if (fd == -1) {
325 return nullptr;
326 }
327
Elliott Hughesd3915c72021-02-08 16:24:46 -0800328 FILE* fp = __FILE_init(__sfp(), fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800329 if (fp == nullptr) {
330 ErrnoRestorer errno_restorer;
331 close(fd);
332 return nullptr;
333 }
334
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800335 // For append mode, O_APPEND sets the write position for free, but we need to
336 // set the read position manually.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700337 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800338 return fp;
339}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800340__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800341
342FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700343 int mode_flags;
344 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800345 if (flags == 0) return nullptr;
346
347 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700348 int fd_flags = fcntl(fd, F_GETFL, 0);
349 if (fd_flags == -1) return nullptr;
350 int tmp = fd_flags & O_ACCMODE;
351 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800352 errno = EINVAL;
353 return nullptr;
354 }
355
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700356 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
357 // POSIX says we just take the current offset of the underlying fd.
358 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
359 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
360 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800361
Dan Albertba1151c2019-03-26 13:01:22 -0700362 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'e'.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700363 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800364 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
365 }
366
Elliott Hughesd3915c72021-02-08 16:24:46 -0800367 return __FILE_init(__sfp(), fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800368}
369
Elliott Hughes023c3072016-01-22 15:04:51 -0800370FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700371 CHECK_FP(fp);
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800372
373 // POSIX says: "If pathname is a null pointer, the freopen() function shall
374 // attempt to change the mode of the stream to that specified by mode, as if
375 // the name of the file currently associated with the stream had been used. In
376 // this case, the file descriptor associated with the stream need not be
377 // closed if the call to freopen() succeeds. It is implementation-defined
378 // which changes of mode are permitted (if any), and under what
379 // circumstances."
380 //
381 // Linux is quite restrictive about what changes you can make with F_SETFL,
382 // and in particular won't let you touch the access bits. It's easiest and
383 // most effective to just rely on /proc/self/fd/...
384 FdPath fd_path(fp->_file);
385 if (file == nullptr) file = fd_path.c_str();
386
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700387 int mode_flags;
388 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800389 if (flags == 0) {
390 fclose(fp);
391 return nullptr;
392 }
393
394 ScopedFileLock sfl(fp);
395
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800396 // TODO: rewrite this mess completely.
397
Elliott Hughes023c3072016-01-22 15:04:51 -0800398 // There are actually programs that depend on being able to "freopen"
399 // descriptors that weren't originally open. Keep this from breaking.
400 // Remember whether the stream was open to begin with, and which file
401 // descriptor (if any) was associated with it. If it was attached to
402 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
403 // should work. This is unnecessary if it was not a Unix file.
404 int isopen, wantfd;
405 if (fp->_flags == 0) {
406 fp->_flags = __SEOF; // Hold on to it.
407 isopen = 0;
408 wantfd = -1;
409 } else {
410 // Flush the stream; ANSI doesn't require this.
411 if (fp->_flags & __SWR) __sflush(fp);
412
Elliott Hughes37ad9592017-10-30 17:47:12 -0700413 // If close is null, closing is a no-op, hence pointless.
414 isopen = (fp->_close != nullptr);
Elliott Hughes023c3072016-01-22 15:04:51 -0800415 if ((wantfd = fp->_file) < 0 && isopen) {
416 (*fp->_close)(fp->_cookie);
417 isopen = 0;
418 }
419 }
420
421 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700422 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800423 if (fd < 0 && isopen) {
424 // If out of fd's close the old one and try again.
425 if (errno == ENFILE || errno == EMFILE) {
426 (*fp->_close)(fp->_cookie);
427 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700428 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800429 }
430 }
431
432 int sverrno = errno;
433
434 // Finish closing fp. Even if the open succeeded above, we cannot
435 // keep fp->_base: it may be the wrong size. This loses the effect
436 // of any setbuffer calls, but stdio has always done this before.
437 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
438 if (fp->_flags & __SMBF) free(fp->_bf._base);
439 fp->_w = 0;
440 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700441 fp->_p = nullptr;
442 fp->_bf._base = nullptr;
Elliott Hughes023c3072016-01-22 15:04:51 -0800443 fp->_bf._size = 0;
444 fp->_lbfsize = 0;
445 if (HASUB(fp)) FREEUB(fp);
446 _UB(fp)._size = 0;
447 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700448 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800449 fp->_lb._size = 0;
450
451 if (fd < 0) { // Did not get it after all.
452 fp->_flags = 0; // Release.
453 errno = sverrno; // Restore errno in case _close clobbered it.
454 return nullptr;
455 }
456
457 // If reopening something that was open before on a real file, try
458 // to maintain the descriptor. Various C library routines (perror)
459 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
460 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700461 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800462 close(fd);
463 fd = wantfd;
464 }
465 }
466
Elliott Hughesd3915c72021-02-08 16:24:46 -0800467 __FILE_init(fp, fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800468
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800469 // For append mode, O_APPEND sets the write position for free, but we need to
470 // set the read position manually.
Elliott Hughesd3915c72021-02-08 16:24:46 -0800471 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800472
Elliott Hughes023c3072016-01-22 15:04:51 -0800473 return fp;
474}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800475__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800476
Elliott Hughesf2d7d012025-09-08 12:20:38 -0700477int fclose(FILE* fp) {
478 CHECK_FP(fp);
479
Elliott Hughes2704bd12016-01-20 17:14:53 -0800480 if (fp->_flags == 0) {
481 // Already freed!
482 errno = EBADF;
483 return EOF;
484 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800485
Elliott Hughes2704bd12016-01-20 17:14:53 -0800486 ScopedFileLock sfl(fp);
487 WCIO_FREE(fp);
488 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700489 if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800490 r = EOF;
491 }
492 if (fp->_flags & __SMBF) free(fp->_bf._base);
493 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700494 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800495
Elliott Hughes468efc82018-07-10 14:39:49 -0700496 // If we were created by popen(3), wait for the child.
497 pid_t pid = _EXT(fp)->_popen_pid;
498 if (pid > 0) {
499 int status;
500 if (TEMP_FAILURE_RETRY(wait4(pid, &status, 0, nullptr)) != -1) {
501 r = status;
502 }
503 }
504 _EXT(fp)->_popen_pid = 0;
505
Elliott Hughes2704bd12016-01-20 17:14:53 -0800506 // Poison this FILE so accesses after fclose will be obvious.
507 fp->_file = -1;
508 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800509
Elliott Hughes2704bd12016-01-20 17:14:53 -0800510 // Release this FILE for reuse.
511 fp->_flags = 0;
512 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800513}
Elliott Hughesf2d7d012025-09-08 12:20:38 -0700514__strong_alias(pclose, fclose);
Elliott Hughes923f1652016-01-19 15:46:05 -0800515
Elliott Hughescceaf062016-07-29 16:31:52 -0700516int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700517 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700518 int fd = fp->_file;
519 if (fd == -1) {
520 errno = EBADF;
521 return -1;
522 }
523 return fd;
524}
525
Elliott Hughes923f1652016-01-19 15:46:05 -0800526int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700527 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800528 ScopedFileLock sfl(fp);
529 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800530}
Elliott Hughes021335e2016-01-19 16:28:15 -0800531
Elliott Hughescceaf062016-07-29 16:31:52 -0700532void clearerr_unlocked(FILE* fp) {
Elliott Hughes22917f62018-10-01 14:21:07 -0700533 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700534 return __sclearerr(fp);
535}
536
537void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700538 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700539 ScopedFileLock sfl(fp);
540 clearerr_unlocked(fp);
541}
542
543int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700544 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700545 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700546}
547
548int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700549 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700550 ScopedFileLock sfl(fp);
551 return feof_unlocked(fp);
552}
553
554int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700555 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700556 return __sferror(fp);
557}
558
559int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700560 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700561 ScopedFileLock sfl(fp);
562 return ferror_unlocked(fp);
563}
564
Elliott Hughes37ad9592017-10-30 17:47:12 -0700565int __sflush(FILE* fp) {
566 // Flushing a read-only file is a no-op.
567 if ((fp->_flags & __SWR) == 0) return 0;
568
569 // Flushing a file without a buffer is a no-op.
570 unsigned char* p = fp->_bf._base;
571 if (p == nullptr) return 0;
572
573 // Set these immediately to avoid problems with longjmp and to allow
574 // exchange buffering (via setvbuf) in user write function.
575 int n = fp->_p - p;
576 fp->_p = p;
577 fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
578
579 while (n > 0) {
580 int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
581 if (written <= 0) {
582 fp->_flags |= __SERR;
583 return EOF;
584 }
585 n -= written, p += written;
586 }
587 return 0;
588}
589
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700590int __sflush_locked(FILE* fp) {
591 ScopedFileLock sfl(fp);
592 return __sflush(fp);
593}
594
Elliott Hughes021335e2016-01-19 16:28:15 -0800595int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800596 FILE* fp = reinterpret_cast<FILE*>(cookie);
597 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800598}
599
600int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800601 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800602 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800603}
604
Elliott Hughes021335e2016-01-19 16:28:15 -0800605fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800606 FILE* fp = reinterpret_cast<FILE*>(cookie);
607 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800608}
609
Elliott Hughes023c3072016-01-22 15:04:51 -0800610off64_t __sseek64(void* cookie, off64_t offset, int whence) {
611 FILE* fp = reinterpret_cast<FILE*>(cookie);
612 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
613}
614
Elliott Hughes021335e2016-01-19 16:28:15 -0800615int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800616 FILE* fp = reinterpret_cast<FILE*>(cookie);
Josh Gaof6e5b582018-06-01 15:30:54 -0700617 return android_fdsan_close_with_tag(fp->_file, __get_file_tag(fp));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800618}
619
Elliott Hughes023c3072016-01-22 15:04:51 -0800620static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
621 // Use `_seek64` if set, but fall back to `_seek`.
622 if (_EXT(fp)->_seek64 != nullptr) {
623 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
624 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800625 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
626#if !defined(__LP64__)
627 // Avoid sign extension if off64_t is larger than off_t.
628 if (result != -1) result &= 0xffffffff;
629#endif
630 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800631 } else {
632 errno = ESPIPE;
633 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800634 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800635}
636
Elliott Hughes9677fab2016-01-25 15:50:59 -0800637static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800638 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800639 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700640
Elliott Hughes9677fab2016-01-25 15:50:59 -0800641 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800642 if (result == -1) {
643 return -1;
644 }
645
646 if (fp->_flags & __SRD) {
647 // Reading. Any unread characters (including
648 // those from ungetc) cause the position to be
649 // smaller than that in the underlying object.
650 result -= fp->_r;
651 if (HASUB(fp)) result -= fp->_ur;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700652 } else if (fp->_flags & __SWR && fp->_p != nullptr) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800653 // Writing. Any buffered characters cause the
654 // position to be greater than that in the
655 // underlying object.
656 result += fp->_p - fp->_bf._base;
657 }
658 return result;
659}
660
Elliott Hughes9677fab2016-01-25 15:50:59 -0800661int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800662 ScopedFileLock sfl(fp);
663
Elliott Hughes023c3072016-01-22 15:04:51 -0800664 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800665 // After this, whence is either SEEK_SET or SEEK_END.
666 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800667 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800668 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800669 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800670 }
671 offset += current_offset;
672 whence = SEEK_SET;
673 } else if (whence != SEEK_SET && whence != SEEK_END) {
674 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800675 return -1;
676 }
677
678 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
679 if (off_t_bits == 32 && offset > LONG_MAX) {
680 errno = EOVERFLOW;
681 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800682 }
683
Elliott Hughes37ad9592017-10-30 17:47:12 -0700684 if (fp->_bf._base == nullptr) __smakebuf(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800685
686 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800687 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800688 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800689 }
690
691 // Success: clear EOF indicator and discard ungetc() data.
692 if (HASUB(fp)) FREEUB(fp);
693 fp->_p = fp->_bf._base;
694 fp->_r = 0;
695 /* fp->_w = 0; */ /* unnecessary (I think...) */
696 fp->_flags &= ~__SEOF;
697 return 0;
698}
699
Elliott Hughes9677fab2016-01-25 15:50:59 -0800700int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700701 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800702 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
703 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
704}
705__strong_alias(fseek, fseeko);
706
707int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700708 CHECK_FP(fp);
Ryan Prichardbf549862017-11-07 15:30:32 -0800709 return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800710}
711
Elliott Hughes9677fab2016-01-25 15:50:59 -0800712int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700713 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800714 return fseeko(fp, *pos, SEEK_SET);
715}
716
717int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700718 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800719 return fseeko64(fp, *pos, SEEK_SET);
720}
721
Elliott Hughes2704bd12016-01-20 17:14:53 -0800722off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700723 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800724 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
725 off64_t result = ftello64(fp);
726 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800727 errno = EOVERFLOW;
728 return -1;
729 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800730 return result;
731}
732__strong_alias(ftell, ftello);
733
734off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700735 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800736 ScopedFileLock sfl(fp);
737 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800738}
Elliott Hughes023c3072016-01-22 15:04:51 -0800739
Elliott Hughes023c3072016-01-22 15:04:51 -0800740int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700741 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800742 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800743 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800744}
745
Elliott Hughes9677fab2016-01-25 15:50:59 -0800746int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700747 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800748 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800749 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800750}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800751
752static FILE* __funopen(const void* cookie,
753 int (*read_fn)(void*, char*, int),
754 int (*write_fn)(void*, const char*, int),
755 int (*close_fn)(void*)) {
756 if (read_fn == nullptr && write_fn == nullptr) {
757 errno = EINVAL;
758 return nullptr;
759 }
760
761 FILE* fp = __sfp();
762 if (fp == nullptr) return nullptr;
763
764 if (read_fn != nullptr && write_fn != nullptr) {
765 fp->_flags = __SRW;
766 } else if (read_fn != nullptr) {
767 fp->_flags = __SRD;
768 } else if (write_fn != nullptr) {
769 fp->_flags = __SWR;
770 }
771
772 fp->_file = -1;
773 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
774 fp->_read = read_fn;
775 fp->_write = write_fn;
776 fp->_close = close_fn;
777
778 return fp;
779}
780
781FILE* funopen(const void* cookie,
782 int (*read_fn)(void*, char*, int),
783 int (*write_fn)(void*, const char*, int),
784 fpos_t (*seek_fn)(void*, fpos_t, int),
785 int (*close_fn)(void*)) {
786 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
787 if (fp != nullptr) {
788 fp->_seek = seek_fn;
789 }
790 return fp;
791}
792
793FILE* funopen64(const void* cookie,
794 int (*read_fn)(void*, char*, int),
795 int (*write_fn)(void*, const char*, int),
796 fpos64_t (*seek_fn)(void*, fpos64_t, int),
797 int (*close_fn)(void*)) {
798 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
799 if (fp != nullptr) {
800 _EXT(fp)->_seek64 = seek_fn;
801 }
802 return fp;
803}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700804
Elliott Hughes53cf3482016-08-09 13:06:41 -0700805int asprintf(char** s, const char* fmt, ...) {
806 PRINTF_IMPL(vasprintf(s, fmt, ap));
807}
808
Elliott Hughes20788ae2016-06-09 15:16:32 -0700809char* ctermid(char* s) {
810 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
811}
Elliott Hughescceaf062016-07-29 16:31:52 -0700812
Elliott Hughes70715da2016-08-01 16:35:17 -0700813int dprintf(int fd, const char* fmt, ...) {
814 PRINTF_IMPL(vdprintf(fd, fmt, ap));
815}
816
817int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700818 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700819 PRINTF_IMPL(vfprintf(fp, fmt, ap));
820}
821
Elliott Hughescceaf062016-07-29 16:31:52 -0700822int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700823 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700824 return getc(fp);
825}
826
Elliott Hughes37ad9592017-10-30 17:47:12 -0700827int fgetc_unlocked(FILE* fp) {
828 CHECK_FP(fp);
829 return getc_unlocked(fp);
830}
831
George Burgess IV90242352018-02-06 12:51:31 -0800832char* fgets(char* buf, int n, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -0700833 CHECK_FP(fp);
834 ScopedFileLock sfl(fp);
835 return fgets_unlocked(buf, n, fp);
836}
837
Elliott Hughes468efc82018-07-10 14:39:49 -0700838// Reads at most n-1 characters from the given file.
839// Stops when a newline has been read, or the count runs out.
840// Returns first argument, or nullptr if no characters were read.
841// Does not return nullptr if n == 1.
Elliott Hughes37ad9592017-10-30 17:47:12 -0700842char* fgets_unlocked(char* buf, int n, FILE* fp) {
Elliott Hughes7cebf832020-08-12 14:25:41 -0700843 if (n <= 0) __fortify_fatal("fgets: buffer size %d <= 0", n);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700844
Elliott Hughes531199c2023-05-09 16:11:49 -0700845 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700846
847 char* s = buf;
848 n--; // Leave space for NUL.
849 while (n != 0) {
850 // If the buffer is empty, refill it.
851 if (fp->_r <= 0) {
852 if (__srefill(fp)) {
853 // EOF/error: stop with partial or no line.
854 if (s == buf) return nullptr;
855 break;
856 }
857 }
858 size_t len = fp->_r;
859 unsigned char* p = fp->_p;
860
861 // Scan through at most n bytes of the current buffer,
862 // looking for '\n'. If found, copy up to and including
863 // newline, and stop. Otherwise, copy entire chunk and loop.
864 if (len > static_cast<size_t>(n)) len = n;
865 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
866 if (t != nullptr) {
867 len = ++t - p;
868 fp->_r -= len;
869 fp->_p = t;
870 memcpy(s, p, len);
871 s[len] = '\0';
872 return buf;
873 }
874 fp->_r -= len;
875 fp->_p += len;
876 memcpy(s, p, len);
877 s += len;
878 n -= len;
879 }
880 *s = '\0';
881 return buf;
882}
883
Elliott Hughescceaf062016-07-29 16:31:52 -0700884int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700885 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700886 return putc(c, fp);
887}
888
Elliott Hughes37ad9592017-10-30 17:47:12 -0700889int fputc_unlocked(int c, FILE* fp) {
890 CHECK_FP(fp);
891 return putc_unlocked(c, fp);
892}
893
894int fputs(const char* s, FILE* fp) {
895 CHECK_FP(fp);
896 ScopedFileLock sfl(fp);
897 return fputs_unlocked(s, fp);
898}
899
900int fputs_unlocked(const char* s, FILE* fp) {
901 CHECK_FP(fp);
902 size_t length = strlen(s);
903 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
904}
905
Elliott Hughes70715da2016-08-01 16:35:17 -0700906int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700907 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700908 PRINTF_IMPL(vfscanf(fp, fmt, ap));
909}
910
911int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700912 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700913 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
914}
915
916int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700917 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700918 PRINTF_IMPL(vfwscanf(fp, fmt, ap));
919}
920
921int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700922 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700923 ScopedFileLock sfl(fp);
924 return getc_unlocked(fp);
925}
926
927int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700928 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700929 return __sgetc(fp);
930}
931
932int getchar_unlocked() {
933 return getc_unlocked(stdin);
934}
935
936int getchar() {
937 return getc(stdin);
938}
939
Elliott Hughescceaf062016-07-29 16:31:52 -0700940ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700941 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700942 return getdelim(buf, len, '\n', fp);
943}
944
945wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700946 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700947 return fgetwc(fp);
948}
949
950wint_t getwchar() {
951 return fgetwc(stdin);
952}
953
Elliott Hughes37ad9592017-10-30 17:47:12 -0700954void perror(const char* msg) {
955 if (msg == nullptr) msg = "";
Elliott Hughesae1c64a2023-03-03 23:46:34 +0000956 fprintf(stderr, "%s%s%m\n", msg, (*msg == '\0') ? "" : ": ");
Elliott Hughes37ad9592017-10-30 17:47:12 -0700957}
958
Elliott Hughes70715da2016-08-01 16:35:17 -0700959int printf(const char* fmt, ...) {
960 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
961}
962
963int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700964 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700965 ScopedFileLock sfl(fp);
966 return putc_unlocked(c, fp);
967}
968
969int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700970 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700971 if (cantwrite(fp)) {
972 errno = EBADF;
973 return EOF;
974 }
Elliott Hughes531199c2023-05-09 16:11:49 -0700975 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes70715da2016-08-01 16:35:17 -0700976 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
977 return (*fp->_p++ = c);
978 }
979 return (__swbuf(c, fp));
980}
981
982int putchar(int c) {
983 return putc(c, stdout);
984}
985
986int putchar_unlocked(int c) {
987 return putc_unlocked(c, stdout);
988}
989
Elliott Hughes37ad9592017-10-30 17:47:12 -0700990int puts(const char* s) {
991 size_t length = strlen(s);
992 ScopedFileLock sfl(stdout);
993 return (fwrite_unlocked(s, 1, length, stdout) == length &&
994 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
995}
996
Elliott Hughescceaf062016-07-29 16:31:52 -0700997wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700998 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700999 return fputwc(wc, fp);
1000}
1001
1002wint_t putwchar(wchar_t wc) {
1003 return fputwc(wc, stdout);
1004}
1005
Elliott Hughesd1f25a72016-08-05 15:53:03 -07001006int remove(const char* path) {
1007 if (unlink(path) != -1) return 0;
1008 if (errno != EISDIR) return -1;
1009 return rmdir(path);
1010}
1011
Elliott Hughescceaf062016-07-29 16:31:52 -07001012void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -07001013 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001014 ScopedFileLock sfl(fp);
1015 fseek(fp, 0, SEEK_SET);
1016 clearerr_unlocked(fp);
1017}
1018
Elliott Hughes70715da2016-08-01 16:35:17 -07001019int scanf(const char* fmt, ...) {
1020 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
1021}
1022
Elliott Hughescceaf062016-07-29 16:31:52 -07001023void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -07001024 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001025 setbuffer(fp, buf, BUFSIZ);
1026}
1027
1028void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -07001029 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001030 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
1031}
1032
1033int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -07001034 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001035 return setvbuf(fp, nullptr, _IOLBF, 0);
1036}
1037
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001038/*
1039 * Set one of the three kinds of buffering, optionally including
1040 * a buffer.
1041 */
1042int
1043setvbuf(FILE *fp, char *buf, int mode, size_t size)
1044{
1045 int ret, flags;
1046 size_t iosize;
1047 int ttyflag;
1048
1049 /*
1050 * Verify arguments. The `int' limit on `size' is due to this
1051 * particular implementation. Note, buf and size are ignored
1052 * when setting _IONBF.
1053 */
1054 if (mode != _IONBF)
1055 if ((mode != _IOFBF && mode != _IOLBF) || size > INT_MAX)
1056 return (EOF);
1057
1058 /*
1059 * Write current buffer, if any. Discard unread input (including
1060 * ungetc data), cancel line buffering, and free old buffer if
1061 * malloc()ed. We also clear any eof condition, as if this were
1062 * a seek.
1063 */
1064 FLOCKFILE(fp);
1065 ret = 0;
1066 (void)__sflush(fp);
1067 if (HASUB(fp))
1068 FREEUB(fp);
1069 WCIO_FREE(fp);
1070 fp->_r = fp->_lbfsize = 0;
1071 flags = fp->_flags;
1072 if (flags & __SMBF)
1073 free(fp->_bf._base);
1074 flags &= ~(__SLBF | __SNBF | __SMBF | __SOPT | __SNPT | __SEOF);
1075
1076 /* If setting unbuffered mode, skip all the hard work. */
1077 if (mode == _IONBF)
1078 goto nbf;
1079
1080 /*
1081 * Find optimal I/O size for seek optimization. This also returns
1082 * a `tty flag' to suggest that we check isatty(fd), but we do not
1083 * care since our caller told us how to buffer.
1084 */
1085 flags |= __swhatbuf(fp, &iosize, &ttyflag);
1086 if (size == 0) {
1087 buf = NULL; /* force local allocation */
1088 size = iosize;
1089 }
1090
1091 /* Allocate buffer if needed. */
1092 if (buf == NULL) {
1093 if ((buf = static_cast<char*>(malloc(size))) == NULL) {
1094 /*
1095 * Unable to honor user's request. We will return
1096 * failure, but try again with file system size.
1097 */
1098 ret = EOF;
1099 if (size != iosize) {
1100 size = iosize;
1101 buf = static_cast<char*>(malloc(size));
1102 }
1103 }
1104 if (buf == NULL) {
1105 /* No luck; switch to unbuffered I/O. */
1106nbf:
1107 fp->_flags = flags | __SNBF;
1108 fp->_w = 0;
1109 fp->_bf._base = fp->_p = fp->_nbuf;
1110 fp->_bf._size = 1;
1111 FUNLOCKFILE(fp);
1112 return (ret);
1113 }
1114 flags |= __SMBF;
1115 }
1116
1117 /*
1118 * We're committed to buffering from here, so make sure we've
1119 * registered to flush buffers on exit.
1120 */
1121 if (!__sdidinit)
1122 __sinit();
1123
1124 /*
1125 * Kill any seek optimization if the buffer is not the
1126 * right size.
1127 *
1128 * SHOULD WE ALLOW MULTIPLES HERE (i.e., ok iff (size % iosize) == 0)?
1129 */
1130 if (size != iosize)
1131 flags |= __SNPT;
1132
1133 /*
1134 * Fix up the FILE fields, and set __cleanup for output flush on
1135 * exit (since we are buffered in some way).
1136 */
1137 if (mode == _IOLBF)
1138 flags |= __SLBF;
1139 fp->_flags = flags;
1140 fp->_bf._base = fp->_p = reinterpret_cast<unsigned char*>(buf);
1141 fp->_bf._size = size;
1142 /* fp->_lbfsize is still 0 */
1143 if (flags & __SWR) {
1144 /*
1145 * Begin or continue writing: see __swsetup(). Note
1146 * that __SNBF is impossible (it was handled earlier).
1147 */
1148 if (flags & __SLBF) {
1149 fp->_w = 0;
1150 fp->_lbfsize = -fp->_bf._size;
1151 } else
1152 fp->_w = size;
1153 } else {
1154 /* begin/continue reading, or stay in intermediate state */
1155 fp->_w = 0;
1156 }
1157 FUNLOCKFILE(fp);
1158
1159 return (ret);
1160}
1161
Elliott Hughes53cf3482016-08-09 13:06:41 -07001162int snprintf(char* s, size_t n, const char* fmt, ...) {
1163 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
1164}
1165
1166int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001167 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -07001168}
1169
1170int sscanf(const char* s, const char* fmt, ...) {
1171 PRINTF_IMPL(vsscanf(s, fmt, ap));
1172}
1173
Elliott Hughes70715da2016-08-01 16:35:17 -07001174int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
1175 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
1176}
1177
1178int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
1179 PRINTF_IMPL(vswscanf(s, fmt, ap));
1180}
1181
Elliott Hughes618303c2017-11-02 16:58:44 -07001182int vfprintf(FILE* fp, const char* fmt, va_list ap) {
1183 ScopedFileLock sfl(fp);
1184 return __vfprintf(fp, fmt, ap);
1185}
1186
Elliott Hughes345b7272017-11-10 16:20:43 -08001187int vfscanf(FILE* fp, const char* fmt, va_list ap) {
1188 ScopedFileLock sfl(fp);
1189 return __svfscanf(fp, fmt, ap);
1190}
1191
Elliott Hughes618303c2017-11-02 16:58:44 -07001192int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
1193 ScopedFileLock sfl(fp);
1194 return __vfwprintf(fp, fmt, ap);
1195}
1196
Elliott Hughes345b7272017-11-10 16:20:43 -08001197int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1198 ScopedFileLock sfl(fp);
1199 return __vfwscanf(fp, fmt, ap);
1200}
1201
Elliott Hughescceaf062016-07-29 16:31:52 -07001202int vprintf(const char* fmt, va_list ap) {
1203 return vfprintf(stdout, fmt, ap);
1204}
1205
1206int vscanf(const char* fmt, va_list ap) {
1207 return vfscanf(stdin, fmt, ap);
1208}
1209
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001210int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1211 // stdio internals use int rather than size_t.
1212 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1213
1214 __check_count("vsnprintf", "size", n);
1215
1216 // Stdio internals do not deal correctly with zero length buffer.
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001217 char one_byte_buffer[1];
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001218 if (n == 0) {
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001219 s = one_byte_buffer;
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001220 n = 1;
1221 }
1222
1223 FILE f;
1224 __sfileext fext;
1225 _FILEEXT_SETUP(&f, &fext);
1226 f._file = -1;
1227 f._flags = __SWR | __SSTR;
1228 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1229 f._bf._size = f._w = n - 1;
1230
1231 int result = __vfprintf(&f, fmt, ap);
1232 *f._p = '\0';
1233 return result;
1234}
1235
Elliott Hughes53cf3482016-08-09 13:06:41 -07001236int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001237 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -07001238}
1239
Elliott Hughescceaf062016-07-29 16:31:52 -07001240int vwprintf(const wchar_t* fmt, va_list ap) {
1241 return vfwprintf(stdout, fmt, ap);
1242}
1243
1244int vwscanf(const wchar_t* fmt, va_list ap) {
1245 return vfwscanf(stdin, fmt, ap);
1246}
Elliott Hughes70715da2016-08-01 16:35:17 -07001247
1248int wprintf(const wchar_t* fmt, ...) {
1249 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1250}
1251
1252int wscanf(const wchar_t* fmt, ...) {
1253 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1254}
Dan Albert3037ea42016-10-06 15:46:45 -07001255
Elliott Hughes37ad9592017-10-30 17:47:12 -07001256static int fflush_all() {
Ryan Prichardc485cdb2019-04-30 14:47:34 -07001257 return _fwalk(__sflush_locked);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001258}
1259
1260int fflush(FILE* fp) {
1261 if (fp == nullptr) return fflush_all();
1262 ScopedFileLock sfl(fp);
1263 return fflush_unlocked(fp);
1264}
1265
1266int fflush_unlocked(FILE* fp) {
1267 if (fp == nullptr) return fflush_all();
1268 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1269 errno = EBADF;
1270 return EOF;
1271 }
1272 return __sflush(fp);
1273}
1274
Elliott Hughes00a2a6f2024-08-12 21:32:07 +00001275int fpurge(FILE* fp) {
1276 CHECK_FP(fp);
1277
1278 ScopedFileLock sfl(fp);
1279
1280 if (fp->_flags == 0) {
1281 // Already freed!
1282 errno = EBADF;
1283 return EOF;
1284 }
1285
1286 if (HASUB(fp)) FREEUB(fp);
1287 WCIO_FREE(fp);
1288 fp->_p = fp->_bf._base;
1289 fp->_r = 0;
1290 fp->_w = fp->_flags & (__SLBF | __SNBF) ? 0 : fp->_bf._size;
1291 return 0;
1292}
1293__strong_alias(__fpurge, fpurge);
1294
George Burgess IV90242352018-02-06 12:51:31 -08001295size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -07001296 CHECK_FP(fp);
1297 ScopedFileLock sfl(fp);
1298 return fread_unlocked(buf, size, count, fp);
1299}
1300
1301size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1302 CHECK_FP(fp);
1303
1304 size_t desired_total;
1305 if (__builtin_mul_overflow(size, count, &desired_total)) {
1306 errno = EOVERFLOW;
1307 fp->_flags |= __SERR;
1308 return 0;
1309 }
1310
1311 size_t total = desired_total;
1312 if (total == 0) return 0;
1313
Elliott Hughes531199c2023-05-09 16:11:49 -07001314 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001315
1316 // TODO: how can this ever happen?!
1317 if (fp->_r < 0) fp->_r = 0;
1318
1319 // Ensure _bf._size is valid.
1320 if (fp->_bf._base == nullptr) __smakebuf(fp);
1321
1322 char* dst = static_cast<char*>(buf);
1323
1324 while (total > 0) {
1325 // Copy data out of the buffer.
1326 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1327 memcpy(dst, fp->_p, buffered_bytes);
1328 fp->_p += buffered_bytes;
1329 fp->_r -= buffered_bytes;
1330 dst += buffered_bytes;
1331 total -= buffered_bytes;
1332
1333 // Are we done?
1334 if (total == 0) goto out;
1335
1336 // Do we have so much more to read that we should avoid copying it through the buffer?
1337 if (total > static_cast<size_t>(fp->_bf._size)) break;
1338
1339 // Less than a buffer to go, so refill the buffer and go around the loop again.
1340 if (__srefill(fp)) goto out;
1341 }
1342
1343 // Read directly into the caller's buffer.
1344 while (total > 0) {
Elliott Hughesbe78fc92022-07-28 20:58:45 +00001345 // The _read function pointer takes an int instead of a size_t.
1346 int chunk_size = MIN(total, INT_MAX);
1347 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, chunk_size);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001348 if (bytes_read <= 0) {
1349 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1350 break;
1351 }
1352 dst += bytes_read;
1353 total -= bytes_read;
1354 }
1355
1356out:
1357 return ((desired_total - total) / size);
1358}
1359
1360size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1361 CHECK_FP(fp);
1362 ScopedFileLock sfl(fp);
1363 return fwrite_unlocked(buf, size, count, fp);
1364}
1365
1366size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1367 CHECK_FP(fp);
1368
1369 size_t n;
1370 if (__builtin_mul_overflow(size, count, &n)) {
1371 errno = EOVERFLOW;
1372 fp->_flags |= __SERR;
1373 return 0;
1374 }
1375
1376 if (n == 0) return 0;
1377
1378 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1379 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1380
Elliott Hughes531199c2023-05-09 16:11:49 -07001381 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001382
1383 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1384 // since divides are generally slow.
1385 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1386}
1387
Elliott Hughes468efc82018-07-10 14:39:49 -07001388static FILE* __popen_fail(int fds[2]) {
1389 ErrnoRestorer errno_restorer;
1390 close(fds[0]);
1391 close(fds[1]);
1392 return nullptr;
1393}
1394
1395FILE* popen(const char* cmd, const char* mode) {
Elliott Hughes468efc82018-07-10 14:39:49 -07001396 // Was the request for a socketpair or just a pipe?
1397 int fds[2];
1398 bool bidirectional = false;
1399 if (strchr(mode, '+') != nullptr) {
1400 if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1401 bidirectional = true;
1402 mode = "r+";
1403 } else {
1404 if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1405 mode = strrchr(mode, 'r') ? "r" : "w";
1406 }
1407
1408 // If the parent wants to read, the child's fd needs to be stdout.
1409 int parent, child, desired_child_fd;
1410 if (*mode == 'r') {
1411 parent = 0;
1412 child = 1;
1413 desired_child_fd = STDOUT_FILENO;
1414 } else {
1415 parent = 1;
1416 child = 0;
1417 desired_child_fd = STDIN_FILENO;
1418 }
1419
1420 // Ensure that the child fd isn't the desired child fd.
1421 if (fds[child] == desired_child_fd) {
1422 int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1423 if (new_fd == -1) return __popen_fail(fds);
1424 close(fds[child]);
1425 fds[child] = new_fd;
1426 }
1427
1428 pid_t pid = vfork();
1429 if (pid == -1) return __popen_fail(fds);
1430
1431 if (pid == 0) {
1432 close(fds[parent]);
Elliott Hughes468efc82018-07-10 14:39:49 -07001433 // dup2 so that the child fd isn't closed on exec.
1434 if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1435 close(fds[child]);
1436 if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
Elliott Hughesb6b7e2e2021-11-04 17:18:58 -07001437 execl(__bionic_get_shell_path(), "sh", "-c", "--", cmd, nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001438 _exit(127);
1439 }
1440
1441 FILE* fp = fdopen(fds[parent], mode);
1442 if (fp == nullptr) return __popen_fail(fds);
1443
Elliott Hughes468efc82018-07-10 14:39:49 -07001444 close(fds[child]);
1445
1446 _EXT(fp)->_popen_pid = pid;
1447 return fp;
1448}
1449
Elliott Hughes20dd3fe2023-03-02 01:26:29 +00001450void flockfile(FILE* fp) {
1451 CHECK_FP(fp);
1452 pthread_mutex_lock(&_EXT(fp)->_lock);
1453}
1454
1455int ftrylockfile(FILE* fp) {
1456 CHECK_FP(fp);
1457 // The specification for ftrylockfile() says it returns 0 on success,
1458 // or non-zero on error. We don't bother canonicalizing to 0/-1...
1459 return pthread_mutex_trylock(&_EXT(fp)->_lock);
1460}
1461
1462void funlockfile(FILE* fp) {
1463 CHECK_FP(fp);
1464 pthread_mutex_unlock(&_EXT(fp)->_lock);
1465}
1466
Dan Albert3037ea42016-10-06 15:46:45 -07001467namespace {
1468
1469namespace phony {
1470#include <bits/struct_file.h>
1471}
1472
1473static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1474 "size mismatch between `struct __sFILE` implementation and public stub");
1475static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1476 "alignment mismatch between `struct __sFILE` implementation and public stub");
1477
1478}