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