blob: 7b16485d06eb819d55191e9506247e5197e42312 [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.
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700236 */
237void
238__smakebuf(FILE *fp)
239{
240 unsigned char *p;
Elliott Hughesb906f7d2025-09-10 06:13:38 -0700241 int flags = 0;
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700242 size_t size;
243 int couldbetty;
244
245 if (fp->_flags & __SNBF) {
246 fp->_bf._base = fp->_p = fp->_nbuf;
247 fp->_bf._size = 1;
248 return;
249 }
Elliott Hughesb906f7d2025-09-10 06:13:38 -0700250 __swhatbuf(fp, &size, &couldbetty);
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700251 if ((p = static_cast<unsigned char*>(malloc(size))) == NULL) {
252 fp->_flags |= __SNBF;
253 fp->_bf._base = fp->_p = fp->_nbuf;
254 fp->_bf._size = 1;
255 return;
256 }
257 flags |= __SMBF;
258 fp->_bf._base = fp->_p = p;
259 fp->_bf._size = size;
260 if (couldbetty && isatty(fp->_file))
261 flags |= __SLBF;
262 fp->_flags |= flags;
263}
264
265/*
266 * Internal routine to determine `proper' buffering for a file.
267 */
Elliott Hughesb906f7d2025-09-10 06:13:38 -0700268void __swhatbuf(FILE* fp, size_t* bufsize, int* couldbetty) {
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700269 struct stat st;
270
271 if (fp->_file < 0 || fstat(fp->_file, &st) == -1) {
272 *couldbetty = 0;
273 *bufsize = BUFSIZ;
Elliott Hughesb906f7d2025-09-10 06:13:38 -0700274 return;
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700275 }
276
277 /* could be a tty iff it is a character device */
278 *couldbetty = S_ISCHR(st.st_mode);
279 if (st.st_blksize == 0) {
280 *bufsize = BUFSIZ;
Elliott Hughesb906f7d2025-09-10 06:13:38 -0700281 return;
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700282 }
283
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700284 *bufsize = st.st_blksize;
Elliott Hughesdc0836d2025-09-09 12:05:33 -0700285}
286
Elliott Hughesd3915c72021-02-08 16:24:46 -0800287static FILE* __FILE_init(FILE* fp, int fd, int flags) {
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800288 if (fp == nullptr) return nullptr;
289
Elliott Hughesd3915c72021-02-08 16:24:46 -0800290#if !defined(__LP64__)
291 if (fd > SHRT_MAX) __fortify_fatal("stdio: fd %d > SHRT_MAX", fd);
292#endif
293
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800294 fp->_file = fd;
295 android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
296 fp->_flags = flags;
297 fp->_cookie = fp;
298 fp->_read = __sread;
299 fp->_write = __swrite;
300 fp->_close = __sclose;
301 _EXT(fp)->_seek64 = __sseek64;
Elliott Hughes023c3072016-01-22 15:04:51 -0800302 return fp;
303}
304
305FILE* fopen(const char* file, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700306 int mode_flags;
307 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800308 if (flags == 0) return nullptr;
309
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700310 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800311 if (fd == -1) {
312 return nullptr;
313 }
314
Elliott Hughesd3915c72021-02-08 16:24:46 -0800315 FILE* fp = __FILE_init(__sfp(), fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800316 if (fp == nullptr) {
317 ErrnoRestorer errno_restorer;
318 close(fd);
319 return nullptr;
320 }
321
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800322 // For append mode, O_APPEND sets the write position for free, but we need to
323 // set the read position manually.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700324 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800325 return fp;
326}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800327__strong_alias(fopen64, fopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800328
329FILE* fdopen(int fd, const char* mode) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700330 int mode_flags;
331 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800332 if (flags == 0) return nullptr;
333
334 // Make sure the mode the user wants is a subset of the actual mode.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700335 int fd_flags = fcntl(fd, F_GETFL, 0);
336 if (fd_flags == -1) return nullptr;
337 int tmp = fd_flags & O_ACCMODE;
338 if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800339 errno = EINVAL;
340 return nullptr;
341 }
342
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700343 // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
344 // POSIX says we just take the current offset of the underlying fd.
345 if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
346 if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
347 }
Elliott Hughes023c3072016-01-22 15:04:51 -0800348
Dan Albertba1151c2019-03-26 13:01:22 -0700349 // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'e'.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700350 if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800351 fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
352 }
353
Elliott Hughesd3915c72021-02-08 16:24:46 -0800354 return __FILE_init(__sfp(), fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800355}
356
Elliott Hughes023c3072016-01-22 15:04:51 -0800357FILE* freopen(const char* file, const char* mode, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700358 CHECK_FP(fp);
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800359
360 // POSIX says: "If pathname is a null pointer, the freopen() function shall
361 // attempt to change the mode of the stream to that specified by mode, as if
362 // the name of the file currently associated with the stream had been used. In
363 // this case, the file descriptor associated with the stream need not be
364 // closed if the call to freopen() succeeds. It is implementation-defined
365 // which changes of mode are permitted (if any), and under what
366 // circumstances."
367 //
368 // Linux is quite restrictive about what changes you can make with F_SETFL,
369 // and in particular won't let you touch the access bits. It's easiest and
370 // most effective to just rely on /proc/self/fd/...
371 FdPath fd_path(fp->_file);
372 if (file == nullptr) file = fd_path.c_str();
373
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700374 int mode_flags;
375 int flags = __sflags(mode, &mode_flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800376 if (flags == 0) {
377 fclose(fp);
378 return nullptr;
379 }
380
381 ScopedFileLock sfl(fp);
382
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800383 // TODO: rewrite this mess completely.
384
Elliott Hughes023c3072016-01-22 15:04:51 -0800385 // There are actually programs that depend on being able to "freopen"
386 // descriptors that weren't originally open. Keep this from breaking.
387 // Remember whether the stream was open to begin with, and which file
388 // descriptor (if any) was associated with it. If it was attached to
389 // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
390 // should work. This is unnecessary if it was not a Unix file.
391 int isopen, wantfd;
392 if (fp->_flags == 0) {
393 fp->_flags = __SEOF; // Hold on to it.
394 isopen = 0;
395 wantfd = -1;
396 } else {
397 // Flush the stream; ANSI doesn't require this.
398 if (fp->_flags & __SWR) __sflush(fp);
399
Elliott Hughes37ad9592017-10-30 17:47:12 -0700400 // If close is null, closing is a no-op, hence pointless.
401 isopen = (fp->_close != nullptr);
Elliott Hughes023c3072016-01-22 15:04:51 -0800402 if ((wantfd = fp->_file) < 0 && isopen) {
403 (*fp->_close)(fp->_cookie);
404 isopen = 0;
405 }
406 }
407
408 // Get a new descriptor to refer to the new file.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700409 int fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800410 if (fd < 0 && isopen) {
411 // If out of fd's close the old one and try again.
412 if (errno == ENFILE || errno == EMFILE) {
413 (*fp->_close)(fp->_cookie);
414 isopen = 0;
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700415 fd = open(file, mode_flags, DEFFILEMODE);
Elliott Hughes023c3072016-01-22 15:04:51 -0800416 }
417 }
418
419 int sverrno = errno;
420
421 // Finish closing fp. Even if the open succeeded above, we cannot
422 // keep fp->_base: it may be the wrong size. This loses the effect
423 // of any setbuffer calls, but stdio has always done this before.
424 if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
425 if (fp->_flags & __SMBF) free(fp->_bf._base);
426 fp->_w = 0;
427 fp->_r = 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700428 fp->_p = nullptr;
429 fp->_bf._base = nullptr;
Elliott Hughes023c3072016-01-22 15:04:51 -0800430 fp->_bf._size = 0;
431 fp->_lbfsize = 0;
432 if (HASUB(fp)) FREEUB(fp);
433 _UB(fp)._size = 0;
434 WCIO_FREE(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700435 free_fgetln_buffer(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800436 fp->_lb._size = 0;
437
438 if (fd < 0) { // Did not get it after all.
439 fp->_flags = 0; // Release.
440 errno = sverrno; // Restore errno in case _close clobbered it.
441 return nullptr;
442 }
443
444 // If reopening something that was open before on a real file, try
445 // to maintain the descriptor. Various C library routines (perror)
446 // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
447 if (wantfd >= 0 && fd != wantfd) {
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700448 if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800449 close(fd);
450 fd = wantfd;
451 }
452 }
453
Elliott Hughesd3915c72021-02-08 16:24:46 -0800454 __FILE_init(fp, fd, flags);
Elliott Hughes023c3072016-01-22 15:04:51 -0800455
Elliott Hughesf9cfecf2021-02-04 16:58:13 -0800456 // For append mode, O_APPEND sets the write position for free, but we need to
457 // set the read position manually.
Elliott Hughesd3915c72021-02-08 16:24:46 -0800458 if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
Elliott Hughes023c3072016-01-22 15:04:51 -0800459
Elliott Hughes023c3072016-01-22 15:04:51 -0800460 return fp;
461}
Elliott Hughesf226ee52016-02-03 11:24:28 -0800462__strong_alias(freopen64, freopen);
Elliott Hughes023c3072016-01-22 15:04:51 -0800463
Elliott Hughesf2d7d012025-09-08 12:20:38 -0700464int fclose(FILE* fp) {
465 CHECK_FP(fp);
466
Elliott Hughes2704bd12016-01-20 17:14:53 -0800467 if (fp->_flags == 0) {
468 // Already freed!
469 errno = EBADF;
470 return EOF;
471 }
Elliott Hughes923f1652016-01-19 15:46:05 -0800472
Elliott Hughes2704bd12016-01-20 17:14:53 -0800473 ScopedFileLock sfl(fp);
474 WCIO_FREE(fp);
475 int r = fp->_flags & __SWR ? __sflush(fp) : 0;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700476 if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800477 r = EOF;
478 }
479 if (fp->_flags & __SMBF) free(fp->_bf._base);
480 if (HASUB(fp)) FREEUB(fp);
Elliott Hughes80e4c152017-07-21 13:57:55 -0700481 free_fgetln_buffer(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800482
Elliott Hughes468efc82018-07-10 14:39:49 -0700483 // If we were created by popen(3), wait for the child.
484 pid_t pid = _EXT(fp)->_popen_pid;
485 if (pid > 0) {
486 int status;
487 if (TEMP_FAILURE_RETRY(wait4(pid, &status, 0, nullptr)) != -1) {
488 r = status;
489 }
490 }
491 _EXT(fp)->_popen_pid = 0;
492
Elliott Hughes2704bd12016-01-20 17:14:53 -0800493 // Poison this FILE so accesses after fclose will be obvious.
494 fp->_file = -1;
495 fp->_r = fp->_w = 0;
Elliott Hughes923f1652016-01-19 15:46:05 -0800496
Elliott Hughes2704bd12016-01-20 17:14:53 -0800497 // Release this FILE for reuse.
498 fp->_flags = 0;
499 return r;
Elliott Hughes923f1652016-01-19 15:46:05 -0800500}
Elliott Hughesf2d7d012025-09-08 12:20:38 -0700501__strong_alias(pclose, fclose);
Elliott Hughes923f1652016-01-19 15:46:05 -0800502
Elliott Hughescceaf062016-07-29 16:31:52 -0700503int fileno_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700504 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700505 int fd = fp->_file;
506 if (fd == -1) {
507 errno = EBADF;
508 return -1;
509 }
510 return fd;
511}
512
Elliott Hughes923f1652016-01-19 15:46:05 -0800513int fileno(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700514 CHECK_FP(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800515 ScopedFileLock sfl(fp);
516 return fileno_unlocked(fp);
Elliott Hughes923f1652016-01-19 15:46:05 -0800517}
Elliott Hughes021335e2016-01-19 16:28:15 -0800518
Elliott Hughescceaf062016-07-29 16:31:52 -0700519void clearerr_unlocked(FILE* fp) {
Elliott Hughes22917f62018-10-01 14:21:07 -0700520 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700521 return __sclearerr(fp);
522}
523
524void clearerr(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700525 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700526 ScopedFileLock sfl(fp);
527 clearerr_unlocked(fp);
528}
529
530int feof_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700531 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700532 return ((fp->_flags & __SEOF) != 0);
Elliott Hughescceaf062016-07-29 16:31:52 -0700533}
534
535int feof(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700536 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700537 ScopedFileLock sfl(fp);
538 return feof_unlocked(fp);
539}
540
541int ferror_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700542 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700543 return __sferror(fp);
544}
545
546int ferror(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700547 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700548 ScopedFileLock sfl(fp);
549 return ferror_unlocked(fp);
550}
551
Elliott Hughes37ad9592017-10-30 17:47:12 -0700552int __sflush(FILE* fp) {
553 // Flushing a read-only file is a no-op.
554 if ((fp->_flags & __SWR) == 0) return 0;
555
556 // Flushing a file without a buffer is a no-op.
557 unsigned char* p = fp->_bf._base;
558 if (p == nullptr) return 0;
559
560 // Set these immediately to avoid problems with longjmp and to allow
561 // exchange buffering (via setvbuf) in user write function.
562 int n = fp->_p - p;
563 fp->_p = p;
564 fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
565
566 while (n > 0) {
567 int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
568 if (written <= 0) {
569 fp->_flags |= __SERR;
570 return EOF;
571 }
572 n -= written, p += written;
573 }
574 return 0;
575}
576
Ryan Prichardc485cdb2019-04-30 14:47:34 -0700577int __sflush_locked(FILE* fp) {
578 ScopedFileLock sfl(fp);
579 return __sflush(fp);
580}
581
Elliott Hughes021335e2016-01-19 16:28:15 -0800582int __sread(void* cookie, char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800583 FILE* fp = reinterpret_cast<FILE*>(cookie);
584 return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800585}
586
587int __swrite(void* cookie, const char* buf, int n) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800588 FILE* fp = reinterpret_cast<FILE*>(cookie);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800589 return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
Elliott Hughes021335e2016-01-19 16:28:15 -0800590}
591
Elliott Hughes021335e2016-01-19 16:28:15 -0800592fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800593 FILE* fp = reinterpret_cast<FILE*>(cookie);
594 return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
Elliott Hughes021335e2016-01-19 16:28:15 -0800595}
596
Elliott Hughes023c3072016-01-22 15:04:51 -0800597off64_t __sseek64(void* cookie, off64_t offset, int whence) {
598 FILE* fp = reinterpret_cast<FILE*>(cookie);
599 return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
600}
601
Elliott Hughes021335e2016-01-19 16:28:15 -0800602int __sclose(void* cookie) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800603 FILE* fp = reinterpret_cast<FILE*>(cookie);
Josh Gaof6e5b582018-06-01 15:30:54 -0700604 return android_fdsan_close_with_tag(fp->_file, __get_file_tag(fp));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800605}
606
Elliott Hughes023c3072016-01-22 15:04:51 -0800607static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
608 // Use `_seek64` if set, but fall back to `_seek`.
609 if (_EXT(fp)->_seek64 != nullptr) {
610 return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
611 } else if (fp->_seek != nullptr) {
Elliott Hughes955426e2016-01-26 18:25:52 -0800612 off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
613#if !defined(__LP64__)
614 // Avoid sign extension if off64_t is larger than off_t.
615 if (result != -1) result &= 0xffffffff;
616#endif
617 return result;
Elliott Hughes023c3072016-01-22 15:04:51 -0800618 } else {
619 errno = ESPIPE;
620 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800621 }
Elliott Hughes2704bd12016-01-20 17:14:53 -0800622}
623
Elliott Hughes9677fab2016-01-25 15:50:59 -0800624static off64_t __ftello64_unlocked(FILE* fp) {
Elliott Hughes023c3072016-01-22 15:04:51 -0800625 // Find offset of underlying I/O object, then adjust for buffered bytes.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800626 __sflush(fp); // May adjust seek offset on append stream.
Elliott Hughes33a8cb12017-07-25 18:06:46 -0700627
Elliott Hughes9677fab2016-01-25 15:50:59 -0800628 off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800629 if (result == -1) {
630 return -1;
631 }
632
633 if (fp->_flags & __SRD) {
634 // Reading. Any unread characters (including
635 // those from ungetc) cause the position to be
636 // smaller than that in the underlying object.
637 result -= fp->_r;
638 if (HASUB(fp)) result -= fp->_ur;
Elliott Hughes37ad9592017-10-30 17:47:12 -0700639 } else if (fp->_flags & __SWR && fp->_p != nullptr) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800640 // Writing. Any buffered characters cause the
641 // position to be greater than that in the
642 // underlying object.
643 result += fp->_p - fp->_bf._base;
644 }
645 return result;
646}
647
Elliott Hughes9677fab2016-01-25 15:50:59 -0800648int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800649 ScopedFileLock sfl(fp);
650
Elliott Hughes023c3072016-01-22 15:04:51 -0800651 // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
Elliott Hughes2704bd12016-01-20 17:14:53 -0800652 // After this, whence is either SEEK_SET or SEEK_END.
653 if (whence == SEEK_CUR) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800654 fpos64_t current_offset = __ftello64_unlocked(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800655 if (current_offset == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800656 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800657 }
658 offset += current_offset;
659 whence = SEEK_SET;
660 } else if (whence != SEEK_SET && whence != SEEK_END) {
661 errno = EINVAL;
Elliott Hughes9677fab2016-01-25 15:50:59 -0800662 return -1;
663 }
664
665 // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
666 if (off_t_bits == 32 && offset > LONG_MAX) {
667 errno = EOVERFLOW;
668 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800669 }
670
Elliott Hughes37ad9592017-10-30 17:47:12 -0700671 if (fp->_bf._base == nullptr) __smakebuf(fp);
Elliott Hughes2704bd12016-01-20 17:14:53 -0800672
673 // Flush unwritten data and attempt the seek.
Elliott Hughes023c3072016-01-22 15:04:51 -0800674 if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
Elliott Hughes9677fab2016-01-25 15:50:59 -0800675 return -1;
Elliott Hughes2704bd12016-01-20 17:14:53 -0800676 }
677
678 // Success: clear EOF indicator and discard ungetc() data.
679 if (HASUB(fp)) FREEUB(fp);
680 fp->_p = fp->_bf._base;
681 fp->_r = 0;
682 /* fp->_w = 0; */ /* unnecessary (I think...) */
683 fp->_flags &= ~__SEOF;
684 return 0;
685}
686
Elliott Hughes9677fab2016-01-25 15:50:59 -0800687int fseeko(FILE* fp, off_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700688 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800689 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
690 return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
691}
692__strong_alias(fseek, fseeko);
693
694int fseeko64(FILE* fp, off64_t offset, int whence) {
Josh Gaod1620602017-10-05 13:48:08 -0700695 CHECK_FP(fp);
Ryan Prichardbf549862017-11-07 15:30:32 -0800696 return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
Elliott Hughes2704bd12016-01-20 17:14:53 -0800697}
698
Elliott Hughes9677fab2016-01-25 15:50:59 -0800699int fsetpos(FILE* fp, const fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700700 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800701 return fseeko(fp, *pos, SEEK_SET);
702}
703
704int fsetpos64(FILE* fp, const fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700705 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800706 return fseeko64(fp, *pos, SEEK_SET);
707}
708
Elliott Hughes2704bd12016-01-20 17:14:53 -0800709off_t ftello(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700710 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800711 static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
712 off64_t result = ftello64(fp);
713 if (result > LONG_MAX) {
Elliott Hughes2704bd12016-01-20 17:14:53 -0800714 errno = EOVERFLOW;
715 return -1;
716 }
Elliott Hughes9677fab2016-01-25 15:50:59 -0800717 return result;
718}
719__strong_alias(ftell, ftello);
720
721off64_t ftello64(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700722 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800723 ScopedFileLock sfl(fp);
724 return __ftello64_unlocked(fp);
Elliott Hughes021335e2016-01-19 16:28:15 -0800725}
Elliott Hughes023c3072016-01-22 15:04:51 -0800726
Elliott Hughes023c3072016-01-22 15:04:51 -0800727int fgetpos(FILE* fp, fpos_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700728 CHECK_FP(fp);
Elliott Hughes023c3072016-01-22 15:04:51 -0800729 *pos = ftello(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800730 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800731}
732
Elliott Hughes9677fab2016-01-25 15:50:59 -0800733int fgetpos64(FILE* fp, fpos64_t* pos) {
Josh Gaod1620602017-10-05 13:48:08 -0700734 CHECK_FP(fp);
Elliott Hughes9677fab2016-01-25 15:50:59 -0800735 *pos = ftello64(fp);
Elliott Hughes955426e2016-01-26 18:25:52 -0800736 return (*pos == -1) ? -1 : 0;
Elliott Hughes023c3072016-01-22 15:04:51 -0800737}
Elliott Hughes03e65eb2016-01-26 14:13:04 -0800738
739static FILE* __funopen(const void* cookie,
740 int (*read_fn)(void*, char*, int),
741 int (*write_fn)(void*, const char*, int),
742 int (*close_fn)(void*)) {
743 if (read_fn == nullptr && write_fn == nullptr) {
744 errno = EINVAL;
745 return nullptr;
746 }
747
748 FILE* fp = __sfp();
749 if (fp == nullptr) return nullptr;
750
751 if (read_fn != nullptr && write_fn != nullptr) {
752 fp->_flags = __SRW;
753 } else if (read_fn != nullptr) {
754 fp->_flags = __SRD;
755 } else if (write_fn != nullptr) {
756 fp->_flags = __SWR;
757 }
758
759 fp->_file = -1;
760 fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
761 fp->_read = read_fn;
762 fp->_write = write_fn;
763 fp->_close = close_fn;
764
765 return fp;
766}
767
768FILE* funopen(const void* cookie,
769 int (*read_fn)(void*, char*, int),
770 int (*write_fn)(void*, const char*, int),
771 fpos_t (*seek_fn)(void*, fpos_t, int),
772 int (*close_fn)(void*)) {
773 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
774 if (fp != nullptr) {
775 fp->_seek = seek_fn;
776 }
777 return fp;
778}
779
780FILE* funopen64(const void* cookie,
781 int (*read_fn)(void*, char*, int),
782 int (*write_fn)(void*, const char*, int),
783 fpos64_t (*seek_fn)(void*, fpos64_t, int),
784 int (*close_fn)(void*)) {
785 FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
786 if (fp != nullptr) {
787 _EXT(fp)->_seek64 = seek_fn;
788 }
789 return fp;
790}
Elliott Hughes20788ae2016-06-09 15:16:32 -0700791
Elliott Hughes53cf3482016-08-09 13:06:41 -0700792int asprintf(char** s, const char* fmt, ...) {
793 PRINTF_IMPL(vasprintf(s, fmt, ap));
794}
795
Elliott Hughes20788ae2016-06-09 15:16:32 -0700796char* ctermid(char* s) {
797 return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
798}
Elliott Hughescceaf062016-07-29 16:31:52 -0700799
Elliott Hughes70715da2016-08-01 16:35:17 -0700800int dprintf(int fd, const char* fmt, ...) {
801 PRINTF_IMPL(vdprintf(fd, fmt, ap));
802}
803
804int fprintf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700805 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700806 PRINTF_IMPL(vfprintf(fp, fmt, ap));
807}
808
Elliott Hughescceaf062016-07-29 16:31:52 -0700809int fgetc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700810 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700811 return getc(fp);
812}
813
Elliott Hughes37ad9592017-10-30 17:47:12 -0700814int fgetc_unlocked(FILE* fp) {
815 CHECK_FP(fp);
816 return getc_unlocked(fp);
817}
818
George Burgess IV90242352018-02-06 12:51:31 -0800819char* fgets(char* buf, int n, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -0700820 CHECK_FP(fp);
821 ScopedFileLock sfl(fp);
822 return fgets_unlocked(buf, n, fp);
823}
824
Elliott Hughes468efc82018-07-10 14:39:49 -0700825// Reads at most n-1 characters from the given file.
826// Stops when a newline has been read, or the count runs out.
827// Returns first argument, or nullptr if no characters were read.
828// Does not return nullptr if n == 1.
Elliott Hughes37ad9592017-10-30 17:47:12 -0700829char* fgets_unlocked(char* buf, int n, FILE* fp) {
Elliott Hughes7cebf832020-08-12 14:25:41 -0700830 if (n <= 0) __fortify_fatal("fgets: buffer size %d <= 0", n);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700831
Elliott Hughes531199c2023-05-09 16:11:49 -0700832 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -0700833
834 char* s = buf;
835 n--; // Leave space for NUL.
836 while (n != 0) {
837 // If the buffer is empty, refill it.
838 if (fp->_r <= 0) {
839 if (__srefill(fp)) {
840 // EOF/error: stop with partial or no line.
841 if (s == buf) return nullptr;
842 break;
843 }
844 }
845 size_t len = fp->_r;
846 unsigned char* p = fp->_p;
847
848 // Scan through at most n bytes of the current buffer,
849 // looking for '\n'. If found, copy up to and including
850 // newline, and stop. Otherwise, copy entire chunk and loop.
851 if (len > static_cast<size_t>(n)) len = n;
852 unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
853 if (t != nullptr) {
854 len = ++t - p;
855 fp->_r -= len;
856 fp->_p = t;
857 memcpy(s, p, len);
858 s[len] = '\0';
859 return buf;
860 }
861 fp->_r -= len;
862 fp->_p += len;
863 memcpy(s, p, len);
864 s += len;
865 n -= len;
866 }
867 *s = '\0';
868 return buf;
869}
870
Elliott Hughescceaf062016-07-29 16:31:52 -0700871int fputc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700872 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700873 return putc(c, fp);
874}
875
Elliott Hughes37ad9592017-10-30 17:47:12 -0700876int fputc_unlocked(int c, FILE* fp) {
877 CHECK_FP(fp);
878 return putc_unlocked(c, fp);
879}
880
881int fputs(const char* s, FILE* fp) {
882 CHECK_FP(fp);
883 ScopedFileLock sfl(fp);
884 return fputs_unlocked(s, fp);
885}
886
887int fputs_unlocked(const char* s, FILE* fp) {
888 CHECK_FP(fp);
889 size_t length = strlen(s);
890 return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
891}
892
Elliott Hughes70715da2016-08-01 16:35:17 -0700893int fscanf(FILE* fp, const char* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700894 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700895 PRINTF_IMPL(vfscanf(fp, fmt, ap));
896}
897
898int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700899 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700900 PRINTF_IMPL(vfwprintf(fp, fmt, ap));
901}
902
903int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
Josh Gaod1620602017-10-05 13:48:08 -0700904 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700905 PRINTF_IMPL(vfwscanf(fp, fmt, ap));
906}
907
908int getc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700909 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700910 ScopedFileLock sfl(fp);
911 return getc_unlocked(fp);
912}
913
914int getc_unlocked(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700915 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700916 return __sgetc(fp);
917}
918
919int getchar_unlocked() {
920 return getc_unlocked(stdin);
921}
922
923int getchar() {
924 return getc(stdin);
925}
926
Elliott Hughescceaf062016-07-29 16:31:52 -0700927ssize_t getline(char** buf, size_t* len, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700928 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700929 return getdelim(buf, len, '\n', fp);
930}
931
932wint_t getwc(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700933 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700934 return fgetwc(fp);
935}
936
937wint_t getwchar() {
938 return fgetwc(stdin);
939}
940
Elliott Hughes37ad9592017-10-30 17:47:12 -0700941void perror(const char* msg) {
942 if (msg == nullptr) msg = "";
Elliott Hughesae1c64a2023-03-03 23:46:34 +0000943 fprintf(stderr, "%s%s%m\n", msg, (*msg == '\0') ? "" : ": ");
Elliott Hughes37ad9592017-10-30 17:47:12 -0700944}
945
Elliott Hughes70715da2016-08-01 16:35:17 -0700946int printf(const char* fmt, ...) {
947 PRINTF_IMPL(vfprintf(stdout, fmt, ap));
948}
949
950int putc(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700951 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700952 ScopedFileLock sfl(fp);
953 return putc_unlocked(c, fp);
954}
955
956int putc_unlocked(int c, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700957 CHECK_FP(fp);
Elliott Hughes70715da2016-08-01 16:35:17 -0700958 if (cantwrite(fp)) {
959 errno = EBADF;
960 return EOF;
961 }
Elliott Hughes531199c2023-05-09 16:11:49 -0700962 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes70715da2016-08-01 16:35:17 -0700963 if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
964 return (*fp->_p++ = c);
965 }
966 return (__swbuf(c, fp));
967}
968
969int putchar(int c) {
970 return putc(c, stdout);
971}
972
973int putchar_unlocked(int c) {
974 return putc_unlocked(c, stdout);
975}
976
Elliott Hughes37ad9592017-10-30 17:47:12 -0700977int puts(const char* s) {
978 size_t length = strlen(s);
979 ScopedFileLock sfl(stdout);
980 return (fwrite_unlocked(s, 1, length, stdout) == length &&
981 putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
982}
983
Elliott Hughescceaf062016-07-29 16:31:52 -0700984wint_t putwc(wchar_t wc, FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -0700985 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -0700986 return fputwc(wc, fp);
987}
988
989wint_t putwchar(wchar_t wc) {
990 return fputwc(wc, stdout);
991}
992
Elliott Hughesd1f25a72016-08-05 15:53:03 -0700993int remove(const char* path) {
994 if (unlink(path) != -1) return 0;
995 if (errno != EISDIR) return -1;
996 return rmdir(path);
997}
998
Elliott Hughescceaf062016-07-29 16:31:52 -0700999void rewind(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -07001000 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001001 ScopedFileLock sfl(fp);
1002 fseek(fp, 0, SEEK_SET);
1003 clearerr_unlocked(fp);
1004}
1005
Elliott Hughes70715da2016-08-01 16:35:17 -07001006int scanf(const char* fmt, ...) {
1007 PRINTF_IMPL(vfscanf(stdin, fmt, ap));
1008}
1009
Elliott Hughescceaf062016-07-29 16:31:52 -07001010void setbuf(FILE* fp, char* buf) {
Josh Gaod1620602017-10-05 13:48:08 -07001011 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001012 setbuffer(fp, buf, BUFSIZ);
1013}
1014
1015void setbuffer(FILE* fp, char* buf, int size) {
Josh Gaod1620602017-10-05 13:48:08 -07001016 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001017 setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
1018}
1019
1020int setlinebuf(FILE* fp) {
Josh Gaod1620602017-10-05 13:48:08 -07001021 CHECK_FP(fp);
Elliott Hughescceaf062016-07-29 16:31:52 -07001022 return setvbuf(fp, nullptr, _IOLBF, 0);
1023}
1024
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001025/*
1026 * Set one of the three kinds of buffering, optionally including
1027 * a buffer.
1028 */
1029int
1030setvbuf(FILE *fp, char *buf, int mode, size_t size)
1031{
1032 int ret, flags;
1033 size_t iosize;
Elliott Hughesb906f7d2025-09-10 06:13:38 -07001034 int ignored;
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001035
1036 /*
1037 * Verify arguments. The `int' limit on `size' is due to this
1038 * particular implementation. Note, buf and size are ignored
1039 * when setting _IONBF.
1040 */
1041 if (mode != _IONBF)
1042 if ((mode != _IOFBF && mode != _IOLBF) || size > INT_MAX)
1043 return (EOF);
1044
1045 /*
1046 * Write current buffer, if any. Discard unread input (including
1047 * ungetc data), cancel line buffering, and free old buffer if
1048 * malloc()ed. We also clear any eof condition, as if this were
1049 * a seek.
1050 */
1051 FLOCKFILE(fp);
1052 ret = 0;
1053 (void)__sflush(fp);
1054 if (HASUB(fp))
1055 FREEUB(fp);
1056 WCIO_FREE(fp);
1057 fp->_r = fp->_lbfsize = 0;
1058 flags = fp->_flags;
1059 if (flags & __SMBF)
1060 free(fp->_bf._base);
Elliott Hughesb906f7d2025-09-10 06:13:38 -07001061 flags &= ~(__SLBF | __SNBF | __SMBF | __SEOF);
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001062
1063 /* If setting unbuffered mode, skip all the hard work. */
1064 if (mode == _IONBF)
1065 goto nbf;
1066
1067 /*
Elliott Hughesb906f7d2025-09-10 06:13:38 -07001068 * Note that size == 0 is unspecified behavior:
1069 *
1070 * musl returns an error,
1071 * glibc interprets it as "unbuffered",
1072 * macOS' man page says it interprets it as "defer allocation" --
1073 * the default if you hadn't called setvbuf() --
1074 * but it actually seems to have the same BSD behavior we currently see here.
1075 *
1076 * TODO: investigate whether this whole "i/o size" thing is actually useful.
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001077 */
Elliott Hughesb906f7d2025-09-10 06:13:38 -07001078 __swhatbuf(fp, &iosize, &ignored);
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001079 if (size == 0) {
1080 buf = NULL; /* force local allocation */
1081 size = iosize;
1082 }
1083
1084 /* Allocate buffer if needed. */
1085 if (buf == NULL) {
1086 if ((buf = static_cast<char*>(malloc(size))) == NULL) {
1087 /*
1088 * Unable to honor user's request. We will return
1089 * failure, but try again with file system size.
1090 */
1091 ret = EOF;
1092 if (size != iosize) {
1093 size = iosize;
1094 buf = static_cast<char*>(malloc(size));
1095 }
1096 }
1097 if (buf == NULL) {
1098 /* No luck; switch to unbuffered I/O. */
1099nbf:
1100 fp->_flags = flags | __SNBF;
1101 fp->_w = 0;
1102 fp->_bf._base = fp->_p = fp->_nbuf;
1103 fp->_bf._size = 1;
1104 FUNLOCKFILE(fp);
1105 return (ret);
1106 }
1107 flags |= __SMBF;
1108 }
1109
1110 /*
1111 * We're committed to buffering from here, so make sure we've
1112 * registered to flush buffers on exit.
1113 */
1114 if (!__sdidinit)
1115 __sinit();
1116
1117 /*
Elliott Hughesdc0836d2025-09-09 12:05:33 -07001118 * Fix up the FILE fields, and set __cleanup for output flush on
1119 * exit (since we are buffered in some way).
1120 */
1121 if (mode == _IOLBF)
1122 flags |= __SLBF;
1123 fp->_flags = flags;
1124 fp->_bf._base = fp->_p = reinterpret_cast<unsigned char*>(buf);
1125 fp->_bf._size = size;
1126 /* fp->_lbfsize is still 0 */
1127 if (flags & __SWR) {
1128 /*
1129 * Begin or continue writing: see __swsetup(). Note
1130 * that __SNBF is impossible (it was handled earlier).
1131 */
1132 if (flags & __SLBF) {
1133 fp->_w = 0;
1134 fp->_lbfsize = -fp->_bf._size;
1135 } else
1136 fp->_w = size;
1137 } else {
1138 /* begin/continue reading, or stay in intermediate state */
1139 fp->_w = 0;
1140 }
1141 FUNLOCKFILE(fp);
1142
1143 return (ret);
1144}
1145
Elliott Hughes53cf3482016-08-09 13:06:41 -07001146int snprintf(char* s, size_t n, const char* fmt, ...) {
1147 PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
1148}
1149
1150int sprintf(char* s, const char* fmt, ...) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001151 PRINTF_IMPL(vsprintf(s, fmt, ap));
Elliott Hughes53cf3482016-08-09 13:06:41 -07001152}
1153
1154int sscanf(const char* s, const char* fmt, ...) {
1155 PRINTF_IMPL(vsscanf(s, fmt, ap));
1156}
1157
Elliott Hughes70715da2016-08-01 16:35:17 -07001158int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
1159 PRINTF_IMPL(vswprintf(s, n, fmt, ap));
1160}
1161
1162int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
1163 PRINTF_IMPL(vswscanf(s, fmt, ap));
1164}
1165
Elliott Hughes618303c2017-11-02 16:58:44 -07001166int vfprintf(FILE* fp, const char* fmt, va_list ap) {
1167 ScopedFileLock sfl(fp);
1168 return __vfprintf(fp, fmt, ap);
1169}
1170
Elliott Hughes345b7272017-11-10 16:20:43 -08001171int vfscanf(FILE* fp, const char* fmt, va_list ap) {
1172 ScopedFileLock sfl(fp);
1173 return __svfscanf(fp, fmt, ap);
1174}
1175
Elliott Hughes618303c2017-11-02 16:58:44 -07001176int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
1177 ScopedFileLock sfl(fp);
1178 return __vfwprintf(fp, fmt, ap);
1179}
1180
Elliott Hughes345b7272017-11-10 16:20:43 -08001181int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1182 ScopedFileLock sfl(fp);
1183 return __vfwscanf(fp, fmt, ap);
1184}
1185
Elliott Hughescceaf062016-07-29 16:31:52 -07001186int vprintf(const char* fmt, va_list ap) {
1187 return vfprintf(stdout, fmt, ap);
1188}
1189
1190int vscanf(const char* fmt, va_list ap) {
1191 return vfscanf(stdin, fmt, ap);
1192}
1193
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001194int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1195 // stdio internals use int rather than size_t.
1196 static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1197
1198 __check_count("vsnprintf", "size", n);
1199
1200 // Stdio internals do not deal correctly with zero length buffer.
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001201 char one_byte_buffer[1];
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001202 if (n == 0) {
Elliott Hughes68ae6ad2020-07-21 16:11:30 -07001203 s = one_byte_buffer;
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001204 n = 1;
1205 }
1206
1207 FILE f;
1208 __sfileext fext;
1209 _FILEEXT_SETUP(&f, &fext);
1210 f._file = -1;
1211 f._flags = __SWR | __SSTR;
1212 f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1213 f._bf._size = f._w = n - 1;
1214
1215 int result = __vfprintf(&f, fmt, ap);
1216 *f._p = '\0';
1217 return result;
1218}
1219
Elliott Hughes53cf3482016-08-09 13:06:41 -07001220int vsprintf(char* s, const char* fmt, va_list ap) {
Elliott Hughesfb3873d2016-08-10 11:07:54 -07001221 return vsnprintf(s, SSIZE_MAX, fmt, ap);
Elliott Hughes53cf3482016-08-09 13:06:41 -07001222}
1223
Elliott Hughescceaf062016-07-29 16:31:52 -07001224int vwprintf(const wchar_t* fmt, va_list ap) {
1225 return vfwprintf(stdout, fmt, ap);
1226}
1227
1228int vwscanf(const wchar_t* fmt, va_list ap) {
1229 return vfwscanf(stdin, fmt, ap);
1230}
Elliott Hughes70715da2016-08-01 16:35:17 -07001231
1232int wprintf(const wchar_t* fmt, ...) {
1233 PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1234}
1235
1236int wscanf(const wchar_t* fmt, ...) {
1237 PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1238}
Dan Albert3037ea42016-10-06 15:46:45 -07001239
Elliott Hughes37ad9592017-10-30 17:47:12 -07001240static int fflush_all() {
Ryan Prichardc485cdb2019-04-30 14:47:34 -07001241 return _fwalk(__sflush_locked);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001242}
1243
1244int fflush(FILE* fp) {
1245 if (fp == nullptr) return fflush_all();
1246 ScopedFileLock sfl(fp);
1247 return fflush_unlocked(fp);
1248}
1249
1250int fflush_unlocked(FILE* fp) {
1251 if (fp == nullptr) return fflush_all();
1252 if ((fp->_flags & (__SWR | __SRW)) == 0) {
1253 errno = EBADF;
1254 return EOF;
1255 }
1256 return __sflush(fp);
1257}
1258
Elliott Hughes00a2a6f2024-08-12 21:32:07 +00001259int fpurge(FILE* fp) {
1260 CHECK_FP(fp);
1261
1262 ScopedFileLock sfl(fp);
1263
1264 if (fp->_flags == 0) {
1265 // Already freed!
1266 errno = EBADF;
1267 return EOF;
1268 }
1269
1270 if (HASUB(fp)) FREEUB(fp);
1271 WCIO_FREE(fp);
1272 fp->_p = fp->_bf._base;
1273 fp->_r = 0;
1274 fp->_w = fp->_flags & (__SLBF | __SNBF) ? 0 : fp->_bf._size;
1275 return 0;
1276}
1277__strong_alias(__fpurge, fpurge);
1278
George Burgess IV90242352018-02-06 12:51:31 -08001279size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
Elliott Hughes37ad9592017-10-30 17:47:12 -07001280 CHECK_FP(fp);
1281 ScopedFileLock sfl(fp);
1282 return fread_unlocked(buf, size, count, fp);
1283}
1284
1285size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1286 CHECK_FP(fp);
1287
1288 size_t desired_total;
1289 if (__builtin_mul_overflow(size, count, &desired_total)) {
1290 errno = EOVERFLOW;
1291 fp->_flags |= __SERR;
1292 return 0;
1293 }
1294
1295 size_t total = desired_total;
1296 if (total == 0) return 0;
1297
Elliott Hughes531199c2023-05-09 16:11:49 -07001298 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001299
1300 // TODO: how can this ever happen?!
1301 if (fp->_r < 0) fp->_r = 0;
1302
1303 // Ensure _bf._size is valid.
1304 if (fp->_bf._base == nullptr) __smakebuf(fp);
1305
1306 char* dst = static_cast<char*>(buf);
1307
1308 while (total > 0) {
1309 // Copy data out of the buffer.
1310 size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1311 memcpy(dst, fp->_p, buffered_bytes);
1312 fp->_p += buffered_bytes;
1313 fp->_r -= buffered_bytes;
1314 dst += buffered_bytes;
1315 total -= buffered_bytes;
1316
1317 // Are we done?
1318 if (total == 0) goto out;
1319
1320 // Do we have so much more to read that we should avoid copying it through the buffer?
1321 if (total > static_cast<size_t>(fp->_bf._size)) break;
1322
1323 // Less than a buffer to go, so refill the buffer and go around the loop again.
1324 if (__srefill(fp)) goto out;
1325 }
1326
1327 // Read directly into the caller's buffer.
1328 while (total > 0) {
Elliott Hughesbe78fc92022-07-28 20:58:45 +00001329 // The _read function pointer takes an int instead of a size_t.
1330 int chunk_size = MIN(total, INT_MAX);
1331 ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, chunk_size);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001332 if (bytes_read <= 0) {
1333 fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1334 break;
1335 }
1336 dst += bytes_read;
1337 total -= bytes_read;
1338 }
1339
1340out:
1341 return ((desired_total - total) / size);
1342}
1343
1344size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1345 CHECK_FP(fp);
1346 ScopedFileLock sfl(fp);
1347 return fwrite_unlocked(buf, size, count, fp);
1348}
1349
1350size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1351 CHECK_FP(fp);
1352
1353 size_t n;
1354 if (__builtin_mul_overflow(size, count, &n)) {
1355 errno = EOVERFLOW;
1356 fp->_flags |= __SERR;
1357 return 0;
1358 }
1359
1360 if (n == 0) return 0;
1361
1362 __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1363 __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1364
Elliott Hughes531199c2023-05-09 16:11:49 -07001365 _SET_ORIENTATION(fp, ORIENT_BYTES);
Elliott Hughes37ad9592017-10-30 17:47:12 -07001366
1367 // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1368 // since divides are generally slow.
1369 return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1370}
1371
Elliott Hughes468efc82018-07-10 14:39:49 -07001372static FILE* __popen_fail(int fds[2]) {
1373 ErrnoRestorer errno_restorer;
1374 close(fds[0]);
1375 close(fds[1]);
1376 return nullptr;
1377}
1378
1379FILE* popen(const char* cmd, const char* mode) {
Elliott Hughes468efc82018-07-10 14:39:49 -07001380 // Was the request for a socketpair or just a pipe?
1381 int fds[2];
1382 bool bidirectional = false;
1383 if (strchr(mode, '+') != nullptr) {
1384 if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1385 bidirectional = true;
1386 mode = "r+";
1387 } else {
1388 if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1389 mode = strrchr(mode, 'r') ? "r" : "w";
1390 }
1391
1392 // If the parent wants to read, the child's fd needs to be stdout.
1393 int parent, child, desired_child_fd;
1394 if (*mode == 'r') {
1395 parent = 0;
1396 child = 1;
1397 desired_child_fd = STDOUT_FILENO;
1398 } else {
1399 parent = 1;
1400 child = 0;
1401 desired_child_fd = STDIN_FILENO;
1402 }
1403
1404 // Ensure that the child fd isn't the desired child fd.
1405 if (fds[child] == desired_child_fd) {
1406 int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1407 if (new_fd == -1) return __popen_fail(fds);
1408 close(fds[child]);
1409 fds[child] = new_fd;
1410 }
1411
1412 pid_t pid = vfork();
1413 if (pid == -1) return __popen_fail(fds);
1414
1415 if (pid == 0) {
1416 close(fds[parent]);
Elliott Hughes468efc82018-07-10 14:39:49 -07001417 // dup2 so that the child fd isn't closed on exec.
1418 if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1419 close(fds[child]);
1420 if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
Elliott Hughesb6b7e2e2021-11-04 17:18:58 -07001421 execl(__bionic_get_shell_path(), "sh", "-c", "--", cmd, nullptr);
Elliott Hughes468efc82018-07-10 14:39:49 -07001422 _exit(127);
1423 }
1424
1425 FILE* fp = fdopen(fds[parent], mode);
1426 if (fp == nullptr) return __popen_fail(fds);
1427
Elliott Hughes468efc82018-07-10 14:39:49 -07001428 close(fds[child]);
1429
1430 _EXT(fp)->_popen_pid = pid;
1431 return fp;
1432}
1433
Elliott Hughes20dd3fe2023-03-02 01:26:29 +00001434void flockfile(FILE* fp) {
1435 CHECK_FP(fp);
1436 pthread_mutex_lock(&_EXT(fp)->_lock);
1437}
1438
1439int ftrylockfile(FILE* fp) {
1440 CHECK_FP(fp);
1441 // The specification for ftrylockfile() says it returns 0 on success,
1442 // or non-zero on error. We don't bother canonicalizing to 0/-1...
1443 return pthread_mutex_trylock(&_EXT(fp)->_lock);
1444}
1445
1446void funlockfile(FILE* fp) {
1447 CHECK_FP(fp);
1448 pthread_mutex_unlock(&_EXT(fp)->_lock);
1449}
1450
Dan Albert3037ea42016-10-06 15:46:45 -07001451namespace {
1452
1453namespace phony {
1454#include <bits/struct_file.h>
1455}
1456
1457static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1458 "size mismatch between `struct __sFILE` implementation and public stub");
1459static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1460 "alignment mismatch between `struct __sFILE` implementation and public stub");
1461
1462}