• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*	$OpenBSD: findfp.c,v 1.15 2013/12/17 16:33:27 deraadt Exp $ */
2 /*-
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 
34 #define __BIONIC_NO_STDIO_FORTIFY
35 #include <stdio.h>
36 
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <limits.h>
40 #include <paths.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <sys/stat.h>
46 #include <sys/wait.h>
47 #include <unistd.h>
48 
49 #include <android/fdsan.h>
50 
51 #include <async_safe/log.h>
52 
53 #include "local.h"
54 #include "glue.h"
55 #include "private/__bionic_get_shell_path.h"
56 #include "private/bionic_fortify.h"
57 #include "private/ErrnoRestorer.h"
58 #include "private/thread_private.h"
59 
60 #define ALIGNBYTES (sizeof(uintptr_t) - 1)
61 #define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
62 
63 #define	NDYNAMIC 10		/* add ten more whenever necessary */
64 
65 #define PRINTF_IMPL(expr) \
66     va_list ap; \
67     va_start(ap, fmt); \
68     int result = (expr); \
69     va_end(ap); \
70     return result;
71 
72 #define MAKE_STD_STREAM(flags, fd)                                          \
73   {                                                                         \
74     ._flags = flags, ._file = fd, ._cookie = __sF + fd, ._close = __sclose, \
75     ._read = __sread, ._write = __swrite, ._ext = {                         \
76       ._base = reinterpret_cast<uint8_t*>(__sFext + fd)                     \
77     }                                                                       \
78   }
79 
80 static struct __sfileext __sFext[3] = {
81     {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
82      ._caller_handles_locking = false,
83      ._seek64 = __sseek64,
84      ._popen_pid = 0},
85     {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
86      ._caller_handles_locking = false,
87      ._seek64 = __sseek64,
88      ._popen_pid = 0},
89     {._lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP,
90      ._caller_handles_locking = false,
91      ._seek64 = __sseek64,
92      ._popen_pid = 0},
93 };
94 
95 // __sF is exported for backwards compatibility. Until M, we didn't have symbols
96 // for stdin/stdout/stderr; they were macros accessing __sF.
97 FILE __sF[3] = {
98     MAKE_STD_STREAM(__SRD, STDIN_FILENO),
99     MAKE_STD_STREAM(__SWR, STDOUT_FILENO),
100     MAKE_STD_STREAM(__SWR|__SNBF, STDERR_FILENO),
101 };
102 
103 FILE* stdin = &__sF[0];
104 FILE* stdout = &__sF[1];
105 FILE* stderr = &__sF[2];
106 
107 static pthread_mutex_t __stdio_mutex = PTHREAD_MUTEX_INITIALIZER;
108 
__get_file_tag(FILE * fp)109 static uint64_t __get_file_tag(FILE* fp) {
110   // Don't use a tag for the standard streams.
111   // They don't really own their file descriptors, because the values are well-known, and you're
112   // allowed to do things like `close(STDIN_FILENO); open("foo", O_RDONLY)` when single-threaded.
113   if (fp == stdin || fp == stderr || fp == stdout) {
114     return 0;
115   }
116 
117   return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_FILE,
118                                         reinterpret_cast<uint64_t>(fp));
119 }
120 
121 struct glue __sglue = { nullptr, 3, __sF };
122 static struct glue* lastglue = &__sglue;
123 
124 class ScopedFileLock {
125  public:
ScopedFileLock(FILE * fp)126   explicit ScopedFileLock(FILE* fp) : fp_(fp) {
127     FLOCKFILE(fp_);
128   }
~ScopedFileLock()129   ~ScopedFileLock() {
130     FUNLOCKFILE(fp_);
131   }
132 
133  private:
134   FILE* fp_;
135 };
136 
moreglue(int n)137 static glue* moreglue(int n) {
138   char* data = new char[sizeof(glue) + ALIGNBYTES + n * sizeof(FILE) + n * sizeof(__sfileext)];
139   if (data == nullptr) return nullptr;
140 
141   glue* g = reinterpret_cast<glue*>(data);
142   FILE* p = reinterpret_cast<FILE*>(ALIGN(data + sizeof(*g)));
143   __sfileext* pext = reinterpret_cast<__sfileext*>(ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
144   g->next = nullptr;
145   g->niobs = n;
146   g->iobs = p;
147   while (--n >= 0) {
148     *p = {};
149     _FILEEXT_SETUP(p, pext);
150     p++;
151     pext++;
152   }
153   return g;
154 }
155 
free_fgetln_buffer(FILE * fp)156 static inline void free_fgetln_buffer(FILE* fp) {
157   if (__predict_false(fp->_lb._base != nullptr)) {
158     free(fp->_lb._base);
159     fp->_lb._base = nullptr;
160   }
161 }
162 
163 /*
164  * Find a free FILE for fopen et al.
165  */
__sfp(void)166 FILE* __sfp(void) {
167 	FILE *fp;
168 	int n;
169 	struct glue *g;
170 
171 	pthread_mutex_lock(&__stdio_mutex);
172 	for (g = &__sglue; g != nullptr; g = g->next) {
173 		for (fp = g->iobs, n = g->niobs; --n >= 0; fp++)
174 			if (fp->_flags == 0)
175 				goto found;
176 	}
177 
178 	/* release lock while mallocing */
179 	pthread_mutex_unlock(&__stdio_mutex);
180 	if ((g = moreglue(NDYNAMIC)) == nullptr) return nullptr;
181 	pthread_mutex_lock(&__stdio_mutex);
182 	lastglue->next = g;
183 	lastglue = g;
184 	fp = g->iobs;
185 found:
186 	fp->_flags = 1;		/* reserve this slot; caller sets real flags */
187 	pthread_mutex_unlock(&__stdio_mutex);
188 	fp->_p = nullptr;		/* no current pointer */
189 	fp->_w = 0;		/* nothing to read or write */
190 	fp->_r = 0;
191 	fp->_bf._base = nullptr;	/* no buffer */
192 	fp->_bf._size = 0;
193 	fp->_lbfsize = 0;	/* not line buffered */
194 	fp->_file = -1;		/* no file */
195 
196 	fp->_lb._base = nullptr;	/* no line buffer */
197 	fp->_lb._size = 0;
198 
199 	memset(_EXT(fp), 0, sizeof(struct __sfileext));
200 	_FLOCK(fp) = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
201 	_EXT(fp)->_caller_handles_locking = false;
202 
203 	// Caller sets cookie, _read/_write etc.
204 	// We explicitly clear _seek and _seek64 to prevent subtle bugs.
205 	fp->_seek = nullptr;
206 	_EXT(fp)->_seek64 = nullptr;
207 
208 	return fp;
209 }
210 
_fwalk(int (* callback)(FILE *))211 int _fwalk(int (*callback)(FILE*)) {
212   int result = 0;
213   for (glue* g = &__sglue; g != nullptr; g = g->next) {
214     FILE* fp = g->iobs;
215     for (int n = g->niobs; --n >= 0; ++fp) {
216       if (fp->_flags != 0 && (fp->_flags & __SIGN) == 0) {
217         result |= (*callback)(fp);
218       }
219     }
220   }
221   return result;
222 }
223 
__libc_stdio_cleanup(void)224 extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
225   // Equivalent to fflush(nullptr), but without all the locking since we're shutting down anyway.
226   _fwalk(__sflush);
227 }
228 
__fopen(int fd,int flags)229 static FILE* __fopen(int fd, int flags) {
230 #if !defined(__LP64__)
231   if (fd > SHRT_MAX) {
232     errno = EMFILE;
233     return nullptr;
234   }
235 #endif
236 
237   FILE* fp = __sfp();
238   if (fp != nullptr) {
239     fp->_file = fd;
240     android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
241     fp->_flags = flags;
242     fp->_cookie = fp;
243     fp->_read = __sread;
244     fp->_write = __swrite;
245     fp->_close = __sclose;
246     _EXT(fp)->_seek64 = __sseek64;
247   }
248   return fp;
249 }
250 
fopen(const char * file,const char * mode)251 FILE* fopen(const char* file, const char* mode) {
252   int mode_flags;
253   int flags = __sflags(mode, &mode_flags);
254   if (flags == 0) return nullptr;
255 
256   int fd = open(file, mode_flags, DEFFILEMODE);
257   if (fd == -1) {
258     return nullptr;
259   }
260 
261   FILE* fp = __fopen(fd, flags);
262   if (fp == nullptr) {
263     ErrnoRestorer errno_restorer;
264     close(fd);
265     return nullptr;
266   }
267 
268   // For append mode, even though we use O_APPEND, we need to seek to the end now.
269   if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
270   return fp;
271 }
272 __strong_alias(fopen64, fopen);
273 
fdopen(int fd,const char * mode)274 FILE* fdopen(int fd, const char* mode) {
275   int mode_flags;
276   int flags = __sflags(mode, &mode_flags);
277   if (flags == 0) return nullptr;
278 
279   // Make sure the mode the user wants is a subset of the actual mode.
280   int fd_flags = fcntl(fd, F_GETFL, 0);
281   if (fd_flags == -1) return nullptr;
282   int tmp = fd_flags & O_ACCMODE;
283   if (tmp != O_RDWR && (tmp != (mode_flags & O_ACCMODE))) {
284     errno = EINVAL;
285     return nullptr;
286   }
287 
288   // Make sure O_APPEND is set on the underlying fd if our mode has 'a'.
289   // POSIX says we just take the current offset of the underlying fd.
290   if ((mode_flags & O_APPEND) && !(fd_flags & O_APPEND)) {
291     if (fcntl(fd, F_SETFL, fd_flags | O_APPEND) == -1) return nullptr;
292   }
293 
294   // Make sure O_CLOEXEC is set on the underlying fd if our mode has 'e'.
295   if ((mode_flags & O_CLOEXEC) && !((tmp = fcntl(fd, F_GETFD)) & FD_CLOEXEC)) {
296     fcntl(fd, F_SETFD, tmp | FD_CLOEXEC);
297   }
298 
299   return __fopen(fd, flags);
300 }
301 
302 // Re-direct an existing, open (probably) file to some other file.
303 // ANSI is written such that the original file gets closed if at
304 // all possible, no matter what.
305 // TODO: rewrite this mess completely.
freopen(const char * file,const char * mode,FILE * fp)306 FILE* freopen(const char* file, const char* mode, FILE* fp) {
307   CHECK_FP(fp);
308   int mode_flags;
309   int flags = __sflags(mode, &mode_flags);
310   if (flags == 0) {
311     fclose(fp);
312     return nullptr;
313   }
314 
315   ScopedFileLock sfl(fp);
316 
317   // There are actually programs that depend on being able to "freopen"
318   // descriptors that weren't originally open.  Keep this from breaking.
319   // Remember whether the stream was open to begin with, and which file
320   // descriptor (if any) was associated with it.  If it was attached to
321   // a descriptor, defer closing it; freopen("/dev/stdin", "r", stdin)
322   // should work.  This is unnecessary if it was not a Unix file.
323   int isopen, wantfd;
324   if (fp->_flags == 0) {
325     fp->_flags = __SEOF; // Hold on to it.
326     isopen = 0;
327     wantfd = -1;
328   } else {
329     // Flush the stream; ANSI doesn't require this.
330     if (fp->_flags & __SWR) __sflush(fp);
331 
332     // If close is null, closing is a no-op, hence pointless.
333     isopen = (fp->_close != nullptr);
334     if ((wantfd = fp->_file) < 0 && isopen) {
335         (*fp->_close)(fp->_cookie);
336         isopen = 0;
337     }
338   }
339 
340   // Get a new descriptor to refer to the new file.
341   int fd = open(file, mode_flags, DEFFILEMODE);
342   if (fd < 0 && isopen) {
343     // If out of fd's close the old one and try again.
344     if (errno == ENFILE || errno == EMFILE) {
345       (*fp->_close)(fp->_cookie);
346       isopen = 0;
347       fd = open(file, mode_flags, DEFFILEMODE);
348     }
349   }
350 
351   int sverrno = errno;
352 
353   // Finish closing fp.  Even if the open succeeded above, we cannot
354   // keep fp->_base: it may be the wrong size.  This loses the effect
355   // of any setbuffer calls, but stdio has always done this before.
356   if (isopen && fd != wantfd) (*fp->_close)(fp->_cookie);
357   if (fp->_flags & __SMBF) free(fp->_bf._base);
358   fp->_w = 0;
359   fp->_r = 0;
360   fp->_p = nullptr;
361   fp->_bf._base = nullptr;
362   fp->_bf._size = 0;
363   fp->_lbfsize = 0;
364   if (HASUB(fp)) FREEUB(fp);
365   _UB(fp)._size = 0;
366   WCIO_FREE(fp);
367   free_fgetln_buffer(fp);
368   fp->_lb._size = 0;
369 
370   if (fd < 0) { // Did not get it after all.
371     fp->_flags = 0; // Release.
372     errno = sverrno; // Restore errno in case _close clobbered it.
373     return nullptr;
374   }
375 
376   // If reopening something that was open before on a real file, try
377   // to maintain the descriptor.  Various C library routines (perror)
378   // assume stderr is always fd STDERR_FILENO, even if being freopen'd.
379   if (wantfd >= 0 && fd != wantfd) {
380     if (dup3(fd, wantfd, mode_flags & O_CLOEXEC) >= 0) {
381       close(fd);
382       fd = wantfd;
383     }
384   }
385 
386   // _file is only a short.
387   if (fd > SHRT_MAX) {
388       fp->_flags = 0; // Release.
389       errno = EMFILE;
390       return nullptr;
391   }
392 
393   fp->_flags = flags;
394   fp->_file = fd;
395   android_fdsan_exchange_owner_tag(fd, 0, __get_file_tag(fp));
396   fp->_cookie = fp;
397   fp->_read = __sread;
398   fp->_write = __swrite;
399   fp->_close = __sclose;
400   _EXT(fp)->_seek64 = __sseek64;
401 
402   // For append mode, even though we use O_APPEND, we need to seek to the end now.
403   if ((mode_flags & O_APPEND) != 0) __sseek64(fp, 0, SEEK_END);
404   return fp;
405 }
406 __strong_alias(freopen64, freopen);
407 
__FILE_close(FILE * fp)408 static int __FILE_close(FILE* fp) {
409   if (fp->_flags == 0) {
410     // Already freed!
411     errno = EBADF;
412     return EOF;
413   }
414 
415   ScopedFileLock sfl(fp);
416   WCIO_FREE(fp);
417   int r = fp->_flags & __SWR ? __sflush(fp) : 0;
418   if (fp->_close != nullptr && (*fp->_close)(fp->_cookie) < 0) {
419     r = EOF;
420   }
421   if (fp->_flags & __SMBF) free(fp->_bf._base);
422   if (HASUB(fp)) FREEUB(fp);
423   free_fgetln_buffer(fp);
424 
425   // If we were created by popen(3), wait for the child.
426   pid_t pid = _EXT(fp)->_popen_pid;
427   if (pid > 0) {
428     int status;
429     if (TEMP_FAILURE_RETRY(wait4(pid, &status, 0, nullptr)) != -1) {
430       r = status;
431     }
432   }
433   _EXT(fp)->_popen_pid = 0;
434 
435   // Poison this FILE so accesses after fclose will be obvious.
436   fp->_file = -1;
437   fp->_r = fp->_w = 0;
438 
439   // Release this FILE for reuse.
440   fp->_flags = 0;
441   return r;
442 }
443 
fclose(FILE * fp)444 int fclose(FILE* fp) {
445   CHECK_FP(fp);
446   return __FILE_close(fp);
447 }
448 
fileno_unlocked(FILE * fp)449 int fileno_unlocked(FILE* fp) {
450   CHECK_FP(fp);
451   int fd = fp->_file;
452   if (fd == -1) {
453     errno = EBADF;
454     return -1;
455   }
456   return fd;
457 }
458 
fileno(FILE * fp)459 int fileno(FILE* fp) {
460   CHECK_FP(fp);
461   ScopedFileLock sfl(fp);
462   return fileno_unlocked(fp);
463 }
464 
clearerr_unlocked(FILE * fp)465 void clearerr_unlocked(FILE* fp) {
466   CHECK_FP(fp);
467   return __sclearerr(fp);
468 }
469 
clearerr(FILE * fp)470 void clearerr(FILE* fp) {
471   CHECK_FP(fp);
472   ScopedFileLock sfl(fp);
473   clearerr_unlocked(fp);
474 }
475 
feof_unlocked(FILE * fp)476 int feof_unlocked(FILE* fp) {
477   CHECK_FP(fp);
478   return ((fp->_flags & __SEOF) != 0);
479 }
480 
feof(FILE * fp)481 int feof(FILE* fp) {
482   CHECK_FP(fp);
483   ScopedFileLock sfl(fp);
484   return feof_unlocked(fp);
485 }
486 
ferror_unlocked(FILE * fp)487 int ferror_unlocked(FILE* fp) {
488   CHECK_FP(fp);
489   return __sferror(fp);
490 }
491 
ferror(FILE * fp)492 int ferror(FILE* fp) {
493   CHECK_FP(fp);
494   ScopedFileLock sfl(fp);
495   return ferror_unlocked(fp);
496 }
497 
__sflush(FILE * fp)498 int __sflush(FILE* fp) {
499   // Flushing a read-only file is a no-op.
500   if ((fp->_flags & __SWR) == 0) return 0;
501 
502   // Flushing a file without a buffer is a no-op.
503   unsigned char* p = fp->_bf._base;
504   if (p == nullptr) return 0;
505 
506   // Set these immediately to avoid problems with longjmp and to allow
507   // exchange buffering (via setvbuf) in user write function.
508   int n = fp->_p - p;
509   fp->_p = p;
510   fp->_w = (fp->_flags & (__SLBF|__SNBF)) ? 0 : fp->_bf._size;
511 
512   while (n > 0) {
513     int written = (*fp->_write)(fp->_cookie, reinterpret_cast<char*>(p), n);
514     if (written <= 0) {
515       fp->_flags |= __SERR;
516       return EOF;
517     }
518     n -= written, p += written;
519   }
520   return 0;
521 }
522 
__sflush_locked(FILE * fp)523 int __sflush_locked(FILE* fp) {
524   ScopedFileLock sfl(fp);
525   return __sflush(fp);
526 }
527 
__sread(void * cookie,char * buf,int n)528 int __sread(void* cookie, char* buf, int n) {
529   FILE* fp = reinterpret_cast<FILE*>(cookie);
530   return TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
531 }
532 
__swrite(void * cookie,const char * buf,int n)533 int __swrite(void* cookie, const char* buf, int n) {
534   FILE* fp = reinterpret_cast<FILE*>(cookie);
535   return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
536 }
537 
__sseek(void * cookie,fpos_t offset,int whence)538 fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
539   FILE* fp = reinterpret_cast<FILE*>(cookie);
540   return TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
541 }
542 
__sseek64(void * cookie,off64_t offset,int whence)543 off64_t __sseek64(void* cookie, off64_t offset, int whence) {
544   FILE* fp = reinterpret_cast<FILE*>(cookie);
545   return TEMP_FAILURE_RETRY(lseek64(fp->_file, offset, whence));
546 }
547 
__sclose(void * cookie)548 int __sclose(void* cookie) {
549   FILE* fp = reinterpret_cast<FILE*>(cookie);
550   return android_fdsan_close_with_tag(fp->_file, __get_file_tag(fp));
551 }
552 
__seek_unlocked(FILE * fp,off64_t offset,int whence)553 static off64_t __seek_unlocked(FILE* fp, off64_t offset, int whence) {
554   // Use `_seek64` if set, but fall back to `_seek`.
555   if (_EXT(fp)->_seek64 != nullptr) {
556     return (*_EXT(fp)->_seek64)(fp->_cookie, offset, whence);
557   } else if (fp->_seek != nullptr) {
558     off64_t result = (*fp->_seek)(fp->_cookie, offset, whence);
559 #if !defined(__LP64__)
560     // Avoid sign extension if off64_t is larger than off_t.
561     if (result != -1) result &= 0xffffffff;
562 #endif
563     return result;
564   } else {
565     errno = ESPIPE;
566     return -1;
567   }
568 }
569 
__ftello64_unlocked(FILE * fp)570 static off64_t __ftello64_unlocked(FILE* fp) {
571   // Find offset of underlying I/O object, then adjust for buffered bytes.
572   __sflush(fp);  // May adjust seek offset on append stream.
573 
574   off64_t result = __seek_unlocked(fp, 0, SEEK_CUR);
575   if (result == -1) {
576     return -1;
577   }
578 
579   if (fp->_flags & __SRD) {
580     // Reading.  Any unread characters (including
581     // those from ungetc) cause the position to be
582     // smaller than that in the underlying object.
583     result -= fp->_r;
584     if (HASUB(fp)) result -= fp->_ur;
585   } else if (fp->_flags & __SWR && fp->_p != nullptr) {
586     // Writing.  Any buffered characters cause the
587     // position to be greater than that in the
588     // underlying object.
589     result += fp->_p - fp->_bf._base;
590   }
591   return result;
592 }
593 
__fseeko64(FILE * fp,off64_t offset,int whence,int off_t_bits)594 int __fseeko64(FILE* fp, off64_t offset, int whence, int off_t_bits) {
595   ScopedFileLock sfl(fp);
596 
597   // Change any SEEK_CUR to SEEK_SET, and check `whence` argument.
598   // After this, whence is either SEEK_SET or SEEK_END.
599   if (whence == SEEK_CUR) {
600     fpos64_t current_offset = __ftello64_unlocked(fp);
601     if (current_offset == -1) {
602       return -1;
603     }
604     offset += current_offset;
605     whence = SEEK_SET;
606   } else if (whence != SEEK_SET && whence != SEEK_END) {
607     errno = EINVAL;
608     return -1;
609   }
610 
611   // If our caller has a 32-bit interface, refuse to go past a 32-bit file offset.
612   if (off_t_bits == 32 && offset > LONG_MAX) {
613     errno = EOVERFLOW;
614     return -1;
615   }
616 
617   if (fp->_bf._base == nullptr) __smakebuf(fp);
618 
619   // Flush unwritten data and attempt the seek.
620   if (__sflush(fp) || __seek_unlocked(fp, offset, whence) == -1) {
621     return -1;
622   }
623 
624   // Success: clear EOF indicator and discard ungetc() data.
625   if (HASUB(fp)) FREEUB(fp);
626   fp->_p = fp->_bf._base;
627   fp->_r = 0;
628   /* fp->_w = 0; */	/* unnecessary (I think...) */
629   fp->_flags &= ~__SEOF;
630   return 0;
631 }
632 
fseeko(FILE * fp,off_t offset,int whence)633 int fseeko(FILE* fp, off_t offset, int whence) {
634   CHECK_FP(fp);
635   static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
636   return __fseeko64(fp, offset, whence, 8*sizeof(off_t));
637 }
638 __strong_alias(fseek, fseeko);
639 
fseeko64(FILE * fp,off64_t offset,int whence)640 int fseeko64(FILE* fp, off64_t offset, int whence) {
641   CHECK_FP(fp);
642   return __fseeko64(fp, offset, whence, 8*sizeof(off64_t));
643 }
644 
fsetpos(FILE * fp,const fpos_t * pos)645 int fsetpos(FILE* fp, const fpos_t* pos) {
646   CHECK_FP(fp);
647   return fseeko(fp, *pos, SEEK_SET);
648 }
649 
fsetpos64(FILE * fp,const fpos64_t * pos)650 int fsetpos64(FILE* fp, const fpos64_t* pos) {
651   CHECK_FP(fp);
652   return fseeko64(fp, *pos, SEEK_SET);
653 }
654 
ftello(FILE * fp)655 off_t ftello(FILE* fp) {
656   CHECK_FP(fp);
657   static_assert(sizeof(off_t) == sizeof(long), "sizeof(off_t) != sizeof(long)");
658   off64_t result = ftello64(fp);
659   if (result > LONG_MAX) {
660     errno = EOVERFLOW;
661     return -1;
662   }
663   return result;
664 }
665 __strong_alias(ftell, ftello);
666 
ftello64(FILE * fp)667 off64_t ftello64(FILE* fp) {
668   CHECK_FP(fp);
669   ScopedFileLock sfl(fp);
670   return __ftello64_unlocked(fp);
671 }
672 
fgetpos(FILE * fp,fpos_t * pos)673 int fgetpos(FILE* fp, fpos_t* pos) {
674   CHECK_FP(fp);
675   *pos = ftello(fp);
676   return (*pos == -1) ? -1 : 0;
677 }
678 
fgetpos64(FILE * fp,fpos64_t * pos)679 int fgetpos64(FILE* fp, fpos64_t* pos) {
680   CHECK_FP(fp);
681   *pos = ftello64(fp);
682   return (*pos == -1) ? -1 : 0;
683 }
684 
__funopen(const void * cookie,int (* read_fn)(void *,char *,int),int (* write_fn)(void *,const char *,int),int (* close_fn)(void *))685 static FILE* __funopen(const void* cookie,
686                        int (*read_fn)(void*, char*, int),
687                        int (*write_fn)(void*, const char*, int),
688                        int (*close_fn)(void*)) {
689   if (read_fn == nullptr && write_fn == nullptr) {
690     errno = EINVAL;
691     return nullptr;
692   }
693 
694   FILE* fp = __sfp();
695   if (fp == nullptr) return nullptr;
696 
697   if (read_fn != nullptr && write_fn != nullptr) {
698     fp->_flags = __SRW;
699   } else if (read_fn != nullptr) {
700     fp->_flags = __SRD;
701   } else if (write_fn != nullptr) {
702     fp->_flags = __SWR;
703   }
704 
705   fp->_file = -1;
706   fp->_cookie = const_cast<void*>(cookie); // The funopen(3) API is incoherent.
707   fp->_read = read_fn;
708   fp->_write = write_fn;
709   fp->_close = close_fn;
710 
711   return fp;
712 }
713 
funopen(const void * cookie,int (* read_fn)(void *,char *,int),int (* write_fn)(void *,const char *,int),fpos_t (* seek_fn)(void *,fpos_t,int),int (* close_fn)(void *))714 FILE* funopen(const void* cookie,
715               int (*read_fn)(void*, char*, int),
716               int (*write_fn)(void*, const char*, int),
717               fpos_t (*seek_fn)(void*, fpos_t, int),
718               int (*close_fn)(void*)) {
719   FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
720   if (fp != nullptr) {
721     fp->_seek = seek_fn;
722   }
723   return fp;
724 }
725 
funopen64(const void * cookie,int (* read_fn)(void *,char *,int),int (* write_fn)(void *,const char *,int),fpos64_t (* seek_fn)(void *,fpos64_t,int),int (* close_fn)(void *))726 FILE* funopen64(const void* cookie,
727                 int (*read_fn)(void*, char*, int),
728                 int (*write_fn)(void*, const char*, int),
729                 fpos64_t (*seek_fn)(void*, fpos64_t, int),
730                 int (*close_fn)(void*)) {
731   FILE* fp = __funopen(cookie, read_fn, write_fn, close_fn);
732   if (fp != nullptr) {
733     _EXT(fp)->_seek64 = seek_fn;
734   }
735   return fp;
736 }
737 
asprintf(char ** s,const char * fmt,...)738 int asprintf(char** s, const char* fmt, ...) {
739   PRINTF_IMPL(vasprintf(s, fmt, ap));
740 }
741 
ctermid(char * s)742 char* ctermid(char* s) {
743   return s ? strcpy(s, _PATH_TTY) : const_cast<char*>(_PATH_TTY);
744 }
745 
dprintf(int fd,const char * fmt,...)746 int dprintf(int fd, const char* fmt, ...) {
747   PRINTF_IMPL(vdprintf(fd, fmt, ap));
748 }
749 
fprintf(FILE * fp,const char * fmt,...)750 int fprintf(FILE* fp, const char* fmt, ...) {
751   CHECK_FP(fp);
752   PRINTF_IMPL(vfprintf(fp, fmt, ap));
753 }
754 
fgetc(FILE * fp)755 int fgetc(FILE* fp) {
756   CHECK_FP(fp);
757   return getc(fp);
758 }
759 
fgetc_unlocked(FILE * fp)760 int fgetc_unlocked(FILE* fp) {
761   CHECK_FP(fp);
762   return getc_unlocked(fp);
763 }
764 
fgets(char * buf,int n,FILE * fp)765 char* fgets(char* buf, int n, FILE* fp) {
766   CHECK_FP(fp);
767   ScopedFileLock sfl(fp);
768   return fgets_unlocked(buf, n, fp);
769 }
770 
771 // Reads at most n-1 characters from the given file.
772 // Stops when a newline has been read, or the count runs out.
773 // Returns first argument, or nullptr if no characters were read.
774 // Does not return nullptr if n == 1.
fgets_unlocked(char * buf,int n,FILE * fp)775 char* fgets_unlocked(char* buf, int n, FILE* fp) {
776   if (n <= 0) {
777     errno = EINVAL;
778     return nullptr;
779   }
780 
781   _SET_ORIENTATION(fp, -1);
782 
783   char* s = buf;
784   n--; // Leave space for NUL.
785   while (n != 0) {
786     // If the buffer is empty, refill it.
787     if (fp->_r <= 0) {
788       if (__srefill(fp)) {
789         // EOF/error: stop with partial or no line.
790         if (s == buf) return nullptr;
791         break;
792       }
793     }
794     size_t len = fp->_r;
795     unsigned char* p = fp->_p;
796 
797     // Scan through at most n bytes of the current buffer,
798     // looking for '\n'.  If found, copy up to and including
799     // newline, and stop.  Otherwise, copy entire chunk and loop.
800     if (len > static_cast<size_t>(n)) len = n;
801     unsigned char* t = static_cast<unsigned char*>(memchr(p, '\n', len));
802     if (t != nullptr) {
803       len = ++t - p;
804       fp->_r -= len;
805       fp->_p = t;
806       memcpy(s, p, len);
807       s[len] = '\0';
808       return buf;
809     }
810     fp->_r -= len;
811     fp->_p += len;
812     memcpy(s, p, len);
813     s += len;
814     n -= len;
815   }
816   *s = '\0';
817   return buf;
818 }
819 
fputc(int c,FILE * fp)820 int fputc(int c, FILE* fp) {
821   CHECK_FP(fp);
822   return putc(c, fp);
823 }
824 
fputc_unlocked(int c,FILE * fp)825 int fputc_unlocked(int c, FILE* fp) {
826   CHECK_FP(fp);
827   return putc_unlocked(c, fp);
828 }
829 
fputs(const char * s,FILE * fp)830 int fputs(const char* s, FILE* fp) {
831   CHECK_FP(fp);
832   ScopedFileLock sfl(fp);
833   return fputs_unlocked(s, fp);
834 }
835 
fputs_unlocked(const char * s,FILE * fp)836 int fputs_unlocked(const char* s, FILE* fp) {
837   CHECK_FP(fp);
838   size_t length = strlen(s);
839   return (fwrite_unlocked(s, 1, length, fp) == length) ? 0 : EOF;
840 }
841 
fscanf(FILE * fp,const char * fmt,...)842 int fscanf(FILE* fp, const char* fmt, ...) {
843   CHECK_FP(fp);
844   PRINTF_IMPL(vfscanf(fp, fmt, ap));
845 }
846 
fwprintf(FILE * fp,const wchar_t * fmt,...)847 int fwprintf(FILE* fp, const wchar_t* fmt, ...) {
848   CHECK_FP(fp);
849   PRINTF_IMPL(vfwprintf(fp, fmt, ap));
850 }
851 
fwscanf(FILE * fp,const wchar_t * fmt,...)852 int fwscanf(FILE* fp, const wchar_t* fmt, ...) {
853   CHECK_FP(fp);
854   PRINTF_IMPL(vfwscanf(fp, fmt, ap));
855 }
856 
getc(FILE * fp)857 int getc(FILE* fp) {
858   CHECK_FP(fp);
859   ScopedFileLock sfl(fp);
860   return getc_unlocked(fp);
861 }
862 
getc_unlocked(FILE * fp)863 int getc_unlocked(FILE* fp) {
864   CHECK_FP(fp);
865   return __sgetc(fp);
866 }
867 
getchar_unlocked()868 int getchar_unlocked() {
869   return getc_unlocked(stdin);
870 }
871 
getchar()872 int getchar() {
873   return getc(stdin);
874 }
875 
getline(char ** buf,size_t * len,FILE * fp)876 ssize_t getline(char** buf, size_t* len, FILE* fp) {
877   CHECK_FP(fp);
878   return getdelim(buf, len, '\n', fp);
879 }
880 
getwc(FILE * fp)881 wint_t getwc(FILE* fp) {
882   CHECK_FP(fp);
883   return fgetwc(fp);
884 }
885 
getwchar()886 wint_t getwchar() {
887   return fgetwc(stdin);
888 }
889 
perror(const char * msg)890 void perror(const char* msg) {
891   if (msg == nullptr) msg = "";
892   fprintf(stderr, "%s%s%s\n", msg, (*msg == '\0') ? "" : ": ", strerror(errno));
893 }
894 
printf(const char * fmt,...)895 int printf(const char* fmt, ...) {
896   PRINTF_IMPL(vfprintf(stdout, fmt, ap));
897 }
898 
putc(int c,FILE * fp)899 int putc(int c, FILE* fp) {
900   CHECK_FP(fp);
901   ScopedFileLock sfl(fp);
902   return putc_unlocked(c, fp);
903 }
904 
putc_unlocked(int c,FILE * fp)905 int putc_unlocked(int c, FILE* fp) {
906   CHECK_FP(fp);
907   if (cantwrite(fp)) {
908     errno = EBADF;
909     return EOF;
910   }
911   _SET_ORIENTATION(fp, -1);
912   if (--fp->_w >= 0 || (fp->_w >= fp->_lbfsize && c != '\n')) {
913     return (*fp->_p++ = c);
914   }
915   return (__swbuf(c, fp));
916 }
917 
putchar(int c)918 int putchar(int c) {
919   return putc(c, stdout);
920 }
921 
putchar_unlocked(int c)922 int putchar_unlocked(int c) {
923   return putc_unlocked(c, stdout);
924 }
925 
puts(const char * s)926 int puts(const char* s) {
927   size_t length = strlen(s);
928   ScopedFileLock sfl(stdout);
929   return (fwrite_unlocked(s, 1, length, stdout) == length &&
930           putc_unlocked('\n', stdout) != EOF) ? 0 : EOF;
931 }
932 
putwc(wchar_t wc,FILE * fp)933 wint_t putwc(wchar_t wc, FILE* fp) {
934   CHECK_FP(fp);
935   return fputwc(wc, fp);
936 }
937 
putwchar(wchar_t wc)938 wint_t putwchar(wchar_t wc) {
939   return fputwc(wc, stdout);
940 }
941 
remove(const char * path)942 int remove(const char* path) {
943   if (unlink(path) != -1) return 0;
944   if (errno != EISDIR) return -1;
945   return rmdir(path);
946 }
947 
rewind(FILE * fp)948 void rewind(FILE* fp) {
949   CHECK_FP(fp);
950   ScopedFileLock sfl(fp);
951   fseek(fp, 0, SEEK_SET);
952   clearerr_unlocked(fp);
953 }
954 
scanf(const char * fmt,...)955 int scanf(const char* fmt, ...) {
956   PRINTF_IMPL(vfscanf(stdin, fmt, ap));
957 }
958 
setbuf(FILE * fp,char * buf)959 void setbuf(FILE* fp, char* buf) {
960   CHECK_FP(fp);
961   setbuffer(fp, buf, BUFSIZ);
962 }
963 
setbuffer(FILE * fp,char * buf,int size)964 void setbuffer(FILE* fp, char* buf, int size) {
965   CHECK_FP(fp);
966   setvbuf(fp, buf, buf ? _IOFBF : _IONBF, size);
967 }
968 
setlinebuf(FILE * fp)969 int setlinebuf(FILE* fp) {
970   CHECK_FP(fp);
971   return setvbuf(fp, nullptr, _IOLBF, 0);
972 }
973 
snprintf(char * s,size_t n,const char * fmt,...)974 int snprintf(char* s, size_t n, const char* fmt, ...) {
975   PRINTF_IMPL(vsnprintf(s, n, fmt, ap));
976 }
977 
sprintf(char * s,const char * fmt,...)978 int sprintf(char* s, const char* fmt, ...) {
979   PRINTF_IMPL(vsprintf(s, fmt, ap));
980 }
981 
sscanf(const char * s,const char * fmt,...)982 int sscanf(const char* s, const char* fmt, ...) {
983   PRINTF_IMPL(vsscanf(s, fmt, ap));
984 }
985 
swprintf(wchar_t * s,size_t n,const wchar_t * fmt,...)986 int swprintf(wchar_t* s, size_t n, const wchar_t* fmt, ...) {
987   PRINTF_IMPL(vswprintf(s, n, fmt, ap));
988 }
989 
swscanf(const wchar_t * s,const wchar_t * fmt,...)990 int swscanf(const wchar_t* s, const wchar_t* fmt, ...) {
991   PRINTF_IMPL(vswscanf(s, fmt, ap));
992 }
993 
vfprintf(FILE * fp,const char * fmt,va_list ap)994 int vfprintf(FILE* fp, const char* fmt, va_list ap) {
995   ScopedFileLock sfl(fp);
996   return __vfprintf(fp, fmt, ap);
997 }
998 
vfscanf(FILE * fp,const char * fmt,va_list ap)999 int vfscanf(FILE* fp, const char* fmt, va_list ap) {
1000   ScopedFileLock sfl(fp);
1001   return __svfscanf(fp, fmt, ap);
1002 }
1003 
vfwprintf(FILE * fp,const wchar_t * fmt,va_list ap)1004 int vfwprintf(FILE* fp, const wchar_t* fmt, va_list ap) {
1005   ScopedFileLock sfl(fp);
1006   return __vfwprintf(fp, fmt, ap);
1007 }
1008 
vfwscanf(FILE * fp,const wchar_t * fmt,va_list ap)1009 int vfwscanf(FILE* fp, const wchar_t* fmt, va_list ap) {
1010   ScopedFileLock sfl(fp);
1011   return __vfwscanf(fp, fmt, ap);
1012 }
1013 
vprintf(const char * fmt,va_list ap)1014 int vprintf(const char* fmt, va_list ap) {
1015   return vfprintf(stdout, fmt, ap);
1016 }
1017 
vscanf(const char * fmt,va_list ap)1018 int vscanf(const char* fmt, va_list ap) {
1019   return vfscanf(stdin, fmt, ap);
1020 }
1021 
vsnprintf(char * s,size_t n,const char * fmt,va_list ap)1022 int vsnprintf(char* s, size_t n, const char* fmt, va_list ap) {
1023   // stdio internals use int rather than size_t.
1024   static_assert(INT_MAX <= SSIZE_MAX, "SSIZE_MAX too large to fit in int");
1025 
1026   __check_count("vsnprintf", "size", n);
1027 
1028   // Stdio internals do not deal correctly with zero length buffer.
1029   char dummy;
1030   if (n == 0) {
1031     s = &dummy;
1032     n = 1;
1033   }
1034 
1035   FILE f;
1036   __sfileext fext;
1037   _FILEEXT_SETUP(&f, &fext);
1038   f._file = -1;
1039   f._flags = __SWR | __SSTR;
1040   f._bf._base = f._p = reinterpret_cast<unsigned char*>(s);
1041   f._bf._size = f._w = n - 1;
1042 
1043   int result = __vfprintf(&f, fmt, ap);
1044   *f._p = '\0';
1045   return result;
1046 }
1047 
vsprintf(char * s,const char * fmt,va_list ap)1048 int vsprintf(char* s, const char* fmt, va_list ap) {
1049   return vsnprintf(s, SSIZE_MAX, fmt, ap);
1050 }
1051 
vwprintf(const wchar_t * fmt,va_list ap)1052 int vwprintf(const wchar_t* fmt, va_list ap) {
1053   return vfwprintf(stdout, fmt, ap);
1054 }
1055 
vwscanf(const wchar_t * fmt,va_list ap)1056 int vwscanf(const wchar_t* fmt, va_list ap) {
1057   return vfwscanf(stdin, fmt, ap);
1058 }
1059 
wprintf(const wchar_t * fmt,...)1060 int wprintf(const wchar_t* fmt, ...) {
1061   PRINTF_IMPL(vfwprintf(stdout, fmt, ap));
1062 }
1063 
wscanf(const wchar_t * fmt,...)1064 int wscanf(const wchar_t* fmt, ...) {
1065   PRINTF_IMPL(vfwscanf(stdin, fmt, ap));
1066 }
1067 
fflush_all()1068 static int fflush_all() {
1069   return _fwalk(__sflush_locked);
1070 }
1071 
fflush(FILE * fp)1072 int fflush(FILE* fp) {
1073   if (fp == nullptr) return fflush_all();
1074   ScopedFileLock sfl(fp);
1075   return fflush_unlocked(fp);
1076 }
1077 
fflush_unlocked(FILE * fp)1078 int fflush_unlocked(FILE* fp) {
1079   if (fp == nullptr) return fflush_all();
1080   if ((fp->_flags & (__SWR | __SRW)) == 0) {
1081     errno = EBADF;
1082     return EOF;
1083   }
1084   return __sflush(fp);
1085 }
1086 
fread(void * buf,size_t size,size_t count,FILE * fp)1087 size_t fread(void* buf, size_t size, size_t count, FILE* fp) {
1088   CHECK_FP(fp);
1089   ScopedFileLock sfl(fp);
1090   return fread_unlocked(buf, size, count, fp);
1091 }
1092 
fread_unlocked(void * buf,size_t size,size_t count,FILE * fp)1093 size_t fread_unlocked(void* buf, size_t size, size_t count, FILE* fp) {
1094   CHECK_FP(fp);
1095 
1096   size_t desired_total;
1097   if (__builtin_mul_overflow(size, count, &desired_total)) {
1098     errno = EOVERFLOW;
1099     fp->_flags |= __SERR;
1100     return 0;
1101   }
1102 
1103   size_t total = desired_total;
1104   if (total == 0) return 0;
1105 
1106   _SET_ORIENTATION(fp, -1);
1107 
1108   // TODO: how can this ever happen?!
1109   if (fp->_r < 0) fp->_r = 0;
1110 
1111   // Ensure _bf._size is valid.
1112   if (fp->_bf._base == nullptr) __smakebuf(fp);
1113 
1114   char* dst = static_cast<char*>(buf);
1115 
1116   while (total > 0) {
1117     // Copy data out of the buffer.
1118     size_t buffered_bytes = MIN(static_cast<size_t>(fp->_r), total);
1119     memcpy(dst, fp->_p, buffered_bytes);
1120     fp->_p += buffered_bytes;
1121     fp->_r -= buffered_bytes;
1122     dst += buffered_bytes;
1123     total -= buffered_bytes;
1124 
1125     // Are we done?
1126     if (total == 0) goto out;
1127 
1128     // Do we have so much more to read that we should avoid copying it through the buffer?
1129     if (total > static_cast<size_t>(fp->_bf._size)) break;
1130 
1131     // Less than a buffer to go, so refill the buffer and go around the loop again.
1132     if (__srefill(fp)) goto out;
1133   }
1134 
1135   // Read directly into the caller's buffer.
1136   while (total > 0) {
1137     ssize_t bytes_read = (*fp->_read)(fp->_cookie, dst, total);
1138     if (bytes_read <= 0) {
1139       fp->_flags |= (bytes_read == 0) ? __SEOF : __SERR;
1140       break;
1141     }
1142     dst += bytes_read;
1143     total -= bytes_read;
1144   }
1145 
1146 out:
1147   return ((desired_total - total) / size);
1148 }
1149 
fwrite(const void * buf,size_t size,size_t count,FILE * fp)1150 size_t fwrite(const void* buf, size_t size, size_t count, FILE* fp) {
1151   CHECK_FP(fp);
1152   ScopedFileLock sfl(fp);
1153   return fwrite_unlocked(buf, size, count, fp);
1154 }
1155 
fwrite_unlocked(const void * buf,size_t size,size_t count,FILE * fp)1156 size_t fwrite_unlocked(const void* buf, size_t size, size_t count, FILE* fp) {
1157   CHECK_FP(fp);
1158 
1159   size_t n;
1160   if (__builtin_mul_overflow(size, count, &n)) {
1161     errno = EOVERFLOW;
1162     fp->_flags |= __SERR;
1163     return 0;
1164   }
1165 
1166   if (n == 0) return 0;
1167 
1168   __siov iov = { .iov_base = const_cast<void*>(buf), .iov_len = n };
1169   __suio uio = { .uio_iov = &iov, .uio_iovcnt = 1, .uio_resid = n };
1170 
1171   _SET_ORIENTATION(fp, -1);
1172 
1173   // The usual case is success (__sfvwrite returns 0); skip the divide if this happens,
1174   // since divides are generally slow.
1175   return (__sfvwrite(fp, &uio) == 0) ? count : ((n - uio.uio_resid) / size);
1176 }
1177 
__popen_fail(int fds[2])1178 static FILE* __popen_fail(int fds[2]) {
1179   ErrnoRestorer errno_restorer;
1180   close(fds[0]);
1181   close(fds[1]);
1182   return nullptr;
1183 }
1184 
popen(const char * cmd,const char * mode)1185 FILE* popen(const char* cmd, const char* mode) {
1186   // Was the request for a socketpair or just a pipe?
1187   int fds[2];
1188   bool bidirectional = false;
1189   if (strchr(mode, '+') != nullptr) {
1190     if (socketpair(AF_LOCAL, SOCK_CLOEXEC | SOCK_STREAM, 0, fds) == -1) return nullptr;
1191     bidirectional = true;
1192     mode = "r+";
1193   } else {
1194     if (pipe2(fds, O_CLOEXEC) == -1) return nullptr;
1195     mode = strrchr(mode, 'r') ? "r" : "w";
1196   }
1197 
1198   // If the parent wants to read, the child's fd needs to be stdout.
1199   int parent, child, desired_child_fd;
1200   if (*mode == 'r') {
1201     parent = 0;
1202     child = 1;
1203     desired_child_fd = STDOUT_FILENO;
1204   } else {
1205     parent = 1;
1206     child = 0;
1207     desired_child_fd = STDIN_FILENO;
1208   }
1209 
1210   // Ensure that the child fd isn't the desired child fd.
1211   if (fds[child] == desired_child_fd) {
1212     int new_fd = fcntl(fds[child], F_DUPFD_CLOEXEC, 0);
1213     if (new_fd == -1) return __popen_fail(fds);
1214     close(fds[child]);
1215     fds[child] = new_fd;
1216   }
1217 
1218   pid_t pid = vfork();
1219   if (pid == -1) return __popen_fail(fds);
1220 
1221   if (pid == 0) {
1222     close(fds[parent]);
1223     // dup2 so that the child fd isn't closed on exec.
1224     if (dup2(fds[child], desired_child_fd) == -1) _exit(127);
1225     close(fds[child]);
1226     if (bidirectional) dup2(STDOUT_FILENO, STDIN_FILENO);
1227     execl(__bionic_get_shell_path(), "sh", "-c", cmd, nullptr);
1228     _exit(127);
1229   }
1230 
1231   FILE* fp = fdopen(fds[parent], mode);
1232   if (fp == nullptr) return __popen_fail(fds);
1233 
1234   close(fds[child]);
1235 
1236   _EXT(fp)->_popen_pid = pid;
1237   return fp;
1238 }
1239 
pclose(FILE * fp)1240 int pclose(FILE* fp) {
1241   CHECK_FP(fp);
1242   return __FILE_close(fp);
1243 }
1244 
1245 namespace {
1246 
1247 namespace phony {
1248 #include <bits/struct_file.h>
1249 }
1250 
1251 static_assert(sizeof(::__sFILE) == sizeof(phony::__sFILE),
1252               "size mismatch between `struct __sFILE` implementation and public stub");
1253 static_assert(alignof(::__sFILE) == alignof(phony::__sFILE),
1254               "alignment mismatch between `struct __sFILE` implementation and public stub");
1255 
1256 }
1257