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