Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/git/blob/master/wrapper.c # git [Ported from github.com/git/git] Sync with Git 2.56.1 Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `git / wrapper.c` 993 lines ยท 21112 bytes Raw Blame History 1 /* 2 * Various trivial helper wrappers around standard functions 3 */ 4 5 #define DISABLE_SIGN_COMPARE_WARNINGS 6 7 #include "git-compat-util.h" 8 #include "abspath.h" 9 #include "parse.h" 10 #include "gettext.h" 11 #include "strbuf.h" 12 #include "trace2.h" 13 14 #ifdef HAVE_RTLGENRANDOM 15 /* This is required to get access to RtlGenRandom. */ 16 #define SystemFunction036 NTAPI SystemFunction036 17 #include 18 #undef SystemFunction036 19 #endif 20 21 static int memory_limit_check(size_t size, int gentle) 22 { 23 static size_t limit = 0; 24 if (!limit) { 25 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0); 26 if (!limit) 27 limit = SIZE_MAX; 28 } 29 if (size > limit) { 30 if (gentle) { 31 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX, 32 (uintmax_t)size, (uintmax_t)limit); 33 return -1; 34 } else 35 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX, 36 (uintmax_t)size, (uintmax_t)limit); 37 } 38 return 0; 39 } 40 41 char *xstrdup(const char *str) 42 { 43 char *ret = strdup(str); 44 if (!ret) 45 die("Out of memory, strdup failed"); 46 return ret; 47 } 48 49 static void *do_xmalloc(size_t size, int gentle) 50 { 51 void *ret; 52 53 if (memory_limit_check(size, gentle)) 54 return NULL; 55 ret = malloc(size); 56 if (!ret && !size) 57 ret = malloc(1); 58 if (!ret) { 59 if (!gentle) 60 die("Out of memory, malloc failed (tried to allocate %lu bytes)", 61 (unsigned long)size); 62 else { 63 error("Out of memory, malloc failed (tried to allocate %lu bytes)", 64 (unsigned long)size); 65 return NULL; 66 } 67 } 68 #ifdef XMALLOC_POISON 69 memset(ret, 0xA5, size); 70 #endif 71 return ret; 72 } 73 74 void *xmalloc(size_t size) 75 { 76 return do_xmalloc(size, 0); 77 } 78 79 static void *do_xmallocz(size_t size, int gentle) 80 { 81 void *ret; 82 if (unsigned_add_overflows(size, 1)) { 83 if (gentle) { 84 error("Data too large to fit into virtual memory space."); 85 return NULL; 86 } else 87 die("Data too large to fit into virtual memory space."); 88 } 89 ret = do_xmalloc(size + 1, gentle); 90 if (ret) 91 ((char*)ret)[size] = 0; 92 return ret; 93 } 94 95 void *xmallocz(size_t size) 96 { 97 return do_xmallocz(size, 0); 98 } 99 100 void *xmallocz_gently(size_t size) 101 { 102 return do_xmallocz(size, 1); 103 } 104 105 /* 106 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of 107 * "data" to the allocated memory, zero terminates the allocated memory, 108 * and returns a pointer to the allocated memory. If the allocation fails, 109 * the program dies. 110 */ 111 void *xmemdupz(const void *data, size_t len) 112 { 113 return memcpy(xmallocz(len), data, len); 114 } 115 116 char *xstrndup(const char *str, size_t len) 117 { 118 const char *p = memchr(str, '\0', len); 119 return xmemdupz(str, p ? p - str : len); 120 } 121 122 int xstrncmpz(const char *s, const char *t, size_t len) 123 { 124 int res = strncmp(s, t, len); 125 if (res) 126 return res; 127 return s[len] == '\0' ? 0 : 1; 128 } 129 130 void *xrealloc(void *ptr, size_t size) 131 { 132 void *ret; 133 134 if (!size) { 135 free(ptr); 136 return xmalloc(0); 137 } 138 139 memory_limit_check(size, 0); 140 ret = realloc(ptr, size); 141 if (!ret) 142 die("Out of memory, realloc failed"); 143 return ret; 144 } 145 146 void *xcalloc(size_t nmemb, size_t size) 147 { 148 void *ret; 149 150 if (unsigned_mult_overflows(nmemb, size)) 151 die("data too large to fit into virtual memory space"); 152 153 memory_limit_check(size * nmemb, 0); 154 ret = calloc(nmemb, size); 155 if (!ret && (!nmemb || !size)) 156 ret = calloc(1, 1); 157 if (!ret) 158 die("Out of memory, calloc failed"); 159 return ret; 160 } 161 162 void xsetenv(const char *name, const char *value, int overwrite) 163 { 164 if (setenv(name, value, overwrite)) 165 die_errno(_("could not setenv '%s'"), name ? name : "(null)"); 166 } 167 168 /** 169 * xopen() is the same as open(), but it die()s if the open() fails. 170 */ 171 int xopen(const char *path, int oflag, ...) 172 { 173 mode_t mode = 0; 174 va_list ap; 175 176 /* 177 * va_arg() will have undefined behavior if the specified type is not 178 * compatible with the argument type. Since integers are promoted to 179 * ints, we fetch the next argument as an int, and then cast it to a 180 * mode_t to avoid undefined behavior. 181 */ 182 va_start(ap, oflag); 183 if (oflag & O_CREAT) 184 mode = va_arg(ap, int); 185 va_end(ap); 186 187 for (;;) { 188 int fd = open(path, oflag, mode); 189 if (fd >= 0) 190 return fd; 191 if (errno == EINTR) 192 continue; 193 194 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) 195 die_errno(_("unable to create '%s'"), path); 196 else if ((oflag & O_RDWR) == O_RDWR) 197 die_errno(_("could not open '%s' for reading and writing"), path); 198 else if ((oflag & O_WRONLY) == O_WRONLY) 199 die_errno(_("could not open '%s' for writing"), path); 200 else 201 die_errno(_("could not open '%s' for reading"), path); 202 } 203 } 204 205 static int handle_nonblock(int fd, short poll_events, int err) 206 { 207 struct pollfd pfd; 208 209 if (err != EAGAIN && err != EWOULDBLOCK) 210 return 0; 211 212 pfd.fd = fd; 213 pfd.events = poll_events; 214 215 /* 216 * no need to check for errors, here; 217 * a subsequent read/write will detect unrecoverable errors 218 */ 219 poll(&pfd, 1, -1); 220 return 1; 221 } 222 223 /* 224 * xread() is the same a read(), but it automatically restarts read() 225 * operations with a recoverable error (EAGAIN and EINTR). xread() 226 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available. 227 */ 228 ssize_t xread(int fd, void *buf, size_t len) 229 { 230 ssize_t nr; 231 if (len > MAX_IO_SIZE) 232 len = MAX_IO_SIZE; 233 while (1) { 234 nr = read(fd, buf, len); 235 if (nr < 0) { 236 if (errno == EINTR) 237 continue; 238 if (handle_nonblock(fd, POLLIN, errno)) 239 continue; 240 } 241 return nr; 242 } 243 } 244 245 /* 246 * xwrite() is the same a write(), but it automatically restarts write() 247 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT 248 * GUARANTEE that "len" bytes is written even if the operation is successful. 249 */ 250 ssize_t xwrite(int fd, const void *buf, size_t len) 251 { 252 ssize_t nr; 253 if (len > MAX_IO_SIZE) 254 len = MAX_IO_SIZE; 255 while (1) { 256 nr = write(fd, buf, len); 257 if (nr < 0) { 258 if (errno == EINTR) 259 continue; 260 if (handle_nonblock(fd, POLLOUT, errno)) 261 continue; 262 } 263 264 return nr; 265 } 266 } 267 268 /* 269 * xpread() is the same as pread(), but it automatically restarts pread() 270 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES 271 * NOT GUARANTEE that "len" bytes is read even if the data is available. 272 */ 273 ssize_t xpread(int fd, void *buf, size_t len, off_t offset) 274 { 275 ssize_t nr; 276 if (len > MAX_IO_SIZE) 277 len = MAX_IO_SIZE; 278 while (1) { 279 nr = pread(fd, buf, len, offset); 280 if ((nr < 0) && (errno == EAGAIN || errno == EINTR)) 281 continue; 282 return nr; 283 } 284 } 285 286 ssize_t read_in_full(int fd, void *buf, size_t count) 287 { 288 char *p = buf; 289 ssize_t total = 0; 290 291 while (count > 0) { 292 ssize_t loaded = xread(fd, p, count); 293 if (loaded < 0) 294 return -1; 295 if (loaded == 0) 296 return total; 297 count -= loaded; 298 p += loaded; 299 total += loaded; 300 } 301 302 return total; 303 } 304 305 ssize_t write_in_full(int fd, const void *buf, size_t count) 306 { 307 const char *p = buf; 308 ssize_t total = 0; 309 310 while (count > 0) { 311 ssize_t written = xwrite(fd, p, count); 312 if (written < 0) 313 return -1; 314 if (!written) { 315 errno = ENOSPC; 316 return -1; 317 } 318 count -= written; 319 p += written; 320 total += written; 321 } 322 323 return total; 324 } 325 326 ssize_t xwritev(int fd, struct iovec *iov, int iovcnt) 327 { 328 size_t allowed = MAX_IO_SIZE; 329 int i; 330 331 /* 332 * Some platforms define a comparatively small `MAX_IO_SIZE` that 333 * limits how many bytes can be written with a single call to 334 * write(3p) or writev(3p); exceeding that limit causes the syscall to 335 * fail with EINVAL. Just like xwrite() chomps overly large requests 336 * for write(3p), pretend that the underlying writev(3p) performed a 337 * short write by only passing along the leading iovec entries that 338 * fit into that limit. 339 */ 340 for (i = 0; i < iovcnt; i++) { 341 if (iov[i].iov_len > allowed) { 342 /* 343 * If the first buffer is larger than MAX_IO_SIZE, 344 * let xwrite() deal with it. 345 */ 346 if (!i) 347 return xwrite(fd, iov->iov_base, iov->iov_len); 348 break; 349 } 350 allowed -= iov[i].iov_len; 351 } 352 353 while (1) { 354 ssize_t bytes_written = writev(fd, iov, i); 355 if (bytes_written < 0) { 356 if (errno == EINTR) 357 continue; 358 if (handle_nonblock(fd, POLLOUT, errno)) 359 continue; 360 } 361 362 return bytes_written; 363 } 364 } 365 366 ssize_t writev_in_full(int fd, struct iovec *iov, int iovcnt) 367 { 368 ssize_t total_written = 0; 369 370 while (iovcnt) { 371 ssize_t bytes_written = xwritev(fd, iov, iovcnt); 372 if (bytes_written < 0) 373 return -1; 374 if (!bytes_written) { 375 errno = ENOSPC; 376 return -1; 377 } 378 379 if (signed_add_overflows(total_written, bytes_written)) { 380 errno = EOVERFLOW; 381 return -1; 382 } 383 total_written += bytes_written; 384 385 /* 386 * We first need to discard any iovec entities that have been 387 * fully written. 388 */ 389 while (iovcnt && (size_t)bytes_written >= iov->iov_len) { 390 bytes_written -= iov->iov_len; 391 iov++; 392 iovcnt--; 393 } 394 395 /* 396 * Finally, we need to adjust the last iovec in case we have 397 * performed a partial write. 398 */ 399 if (iovcnt && bytes_written) { 400 iov->iov_base = (char *) iov->iov_base + bytes_written; 401 iov->iov_len -= bytes_written; 402 } 403 } 404 405 return total_written; 406 } 407 408 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset) 409 { 410 char *p = buf; 411 ssize_t total = 0; 412 413 while (count > 0) { 414 ssize_t loaded = xpread(fd, p, count, offset); 415 if (loaded < 0) 416 return -1; 417 if (loaded == 0) 418 return total; 419 count -= loaded; 420 p += loaded; 421 total += loaded; 422 offset += loaded; 423 } 424 425 return total; 426 } 427 428 int xdup(int fd) 429 { 430 int ret = dup(fd); 431 if (ret < 0) 432 die_errno("dup failed"); 433 return ret; 434 } 435 436 /** 437 * xfopen() is the same as fopen(), but it die()s if the fopen() fails. 438 */ 439 FILE *xfopen(const char *path, const char *mode) 440 { 441 for (;;) { 442 FILE *fp = fopen(path, mode); 443 if (fp) 444 return fp; 445 if (errno == EINTR) 446 continue; 447 448 if (*mode && mode[1] == '+') 449 die_errno(_("could not open '%s' for reading and writing"), path); 450 else if (*mode == 'w' || *mode == 'a') 451 die_errno(_("could not open '%s' for writing"), path); 452 else 453 die_errno(_("could not open '%s' for reading"), path); 454 } 455 } 456 457 FILE *xfdopen(int fd, const char *mode) 458 { 459 FILE *stream = fdopen(fd, mode); 460 if (!stream) 461 die_errno("Out of memory? fdopen failed"); 462 return stream; 463 } 464 465 FILE *fopen_for_writing(const char *path) 466 { 467 FILE *ret = fopen(path, "w"); 468 469 if (!ret && errno == EPERM) { 470 if (!unlink(path)) 471 ret = fopen(path, "w"); 472 else 473 errno = EPERM; 474 } 475 return ret; 476 } 477 478 static void warn_on_inaccessible(const char *path) 479 { 480 warning_errno(_("unable to access '%s'"), path); 481 } 482 483 int warn_on_fopen_errors(const char *path) 484 { 485 if (errno != ENOENT && errno != ENOTDIR) { 486 warn_on_inaccessible(path); 487 return -1; 488 } 489 490 return 0; 491 } 492 493 FILE *fopen_or_warn(const char *path, const char *mode) 494 { 495 FILE *fp = fopen(path, mode); 496 497 if (fp) 498 return fp; 499 500 warn_on_fopen_errors(path); 501 return NULL; 502 } 503 504 int xmkstemp(char *filename_template) 505 { 506 return xmkstemp_mode(filename_template, 0600); 507 } 508 509 /* Adapted from libiberty's mkstemp.c. */ 510 511 #undef TMP_MAX 512 #define TMP_MAX 16384 513 514 /* 515 * Returns -1 on error, 0 if it created a directory, or an open file 516 * descriptor to the created regular file. 517 */ 518 static int git_mkdstemps_mode(char *pattern, int suffix_len, int mode, bool dir) 519 { 520 static const char letters[] = 521 "abcdefghijklmnopqrstuvwxyz" 522 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 523 "`0123456789`"; 524 static const int num_letters = ARRAY_SIZE(letters) - 1; 525 static const char x_pattern[] = "XXXXXX"; 526 static const int num_x = ARRAY_SIZE(x_pattern) - 1; 527 char *filename_template; 528 size_t len; 529 int fd, count; 530 531 len = strlen(pattern); 532 533 if (len < num_x + suffix_len) { 534 errno = EINVAL; 535 return -1; 536 } 537 538 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) { 539 errno = EINVAL; 540 return -1; 541 } 542 543 /* 544 * Replace pattern's XXXXXX characters with randomness. 545 * Try TMP_MAX different filenames. 546 */ 547 filename_template = &pattern[len - num_x - suffix_len]; 548 for (count = 0; count < TMP_MAX; ++count) { 549 int i; 550 uint64_t v; 551 if (csprng_bytes(&v, sizeof(v), 0) < 0) 552 return error_errno("unable to get random bytes for temporary file"); 553 554 /* Fill in the random bits. */ 555 for (i = 0; i < num_x; i++) { 556 filename_template[i] = letters[v % num_letters]; 557 v /= num_letters; 558 } 559 560 if (dir) 561 fd = mkdir(pattern, mode); 562 else 563 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode); 564 if (fd >= 0) 565 return fd; 566 /* 567 * Fatal error (EPERM, ENOSPC etc). 568 * It doesn't make sense to loop. 569 */ 570 if (errno != EEXIST) 571 break; 572 } 573 /* We return the null string if we can't find a unique file name. */ 574 pattern[0] = '\0'; 575 return -1; 576 } 577 578 char *git_mkdtemp(char *pattern) 579 { 580 return git_mkdstemps_mode(pattern, 0, 0700, true) ? NULL : pattern; 581 } 582 583 int git_mkstemps_mode(char *pattern, int suffix_len, int mode) 584 { 585 return git_mkdstemps_mode(pattern, suffix_len, mode, false); 586 } 587 588 int git_mkstemp_mode(char *pattern, int mode) 589 { 590 /* mkstemp is just mkstemps with no suffix */ 591 return git_mkstemps_mode(pattern, 0, mode); 592 } 593 594 int xmkstemp_mode(char *filename_template, int mode) 595 { 596 int fd; 597 char origtemplate[PATH_MAX]; 598 strlcpy(origtemplate, filename_template, sizeof(origtemplate)); 599 600 fd = git_mkstemp_mode(filename_template, mode); 601 if (fd < 0) { 602 int saved_errno = errno; 603 const char *nonrelative_template; 604 605 if (!filename_template[0]) 606 filename_template = origtemplate; 607 608 nonrelative_template = absolute_path(filename_template); 609 errno = saved_errno; 610 die_errno("Unable to create temporary file '%s'", 611 nonrelative_template); 612 } 613 return fd; 614 } 615 616 /* 617 * Some platforms return EINTR from fsync. Since fsync is invoked in some 618 * cases by a wrapper that dies on failure, do not expose EINTR to callers. 619 */ 620 static int fsync_loop(int fd) 621 { 622 int err; 623 624 do { 625 err = fsync(fd); 626 } while (err < 0 && errno == EINTR); 627 return err; 628 } 629 630 int git_fsync(int fd, enum fsync_action action) 631 { 632 switch (action) { 633 case FSYNC_WRITEOUT_ONLY: 634 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_WRITEOUT_ONLY, 1); 635 636 #ifdef __APPLE__ 637 /* 638 * On macOS, fsync just causes filesystem cache writeback but 639 * does not flush hardware caches. 640 */ 641 return fsync_loop(fd); 642 #endif 643 644 #ifdef HAVE_SYNC_FILE_RANGE 645 /* 646 * On linux 2.6.17 and above, sync_file_range is the way to 647 * issue a writeback without a hardware flush. An offset of 648 * 0 and size of 0 indicates writeout of the entire file and the 649 * wait flags ensure that all dirty data is written to the disk 650 * (potentially in a disk-side cache) before we continue. 651 */ 652 653 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE | 654 SYNC_FILE_RANGE_WRITE | 655 SYNC_FILE_RANGE_WAIT_AFTER); 656 #endif 657 658 #ifdef fsync_no_flush 659 return fsync_no_flush(fd); 660 #endif 661 662 errno = ENOSYS; 663 return -1; 664 665 case FSYNC_HARDWARE_FLUSH: 666 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_HARDWARE_FLUSH, 1); 667 668 /* 669 * On macOS, a special fcntl is required to really flush the 670 * caches within the storage controller. As of this writing, 671 * this is a very expensive operation on Apple SSDs. 672 */ 673 #ifdef __APPLE__ 674 return fcntl(fd, F_FULLFSYNC); 675 #else 676 return fsync_loop(fd); 677 #endif 678 default: 679 BUG("unexpected git_fsync(%d) call", action); 680 } 681 } 682 683 static int warn_if_unremovable(const char *op, const char *file, int rc) 684 { 685 int err; 686 if (!rc || errno == ENOENT) 687 return 0; 688 err = errno; 689 warning_errno("unable to %s '%s'", op, file); 690 errno = err; 691 return rc; 692 } 693 694 int unlink_or_msg(const char *file, struct strbuf *err) 695 { 696 int rc = unlink(file); 697 698 assert(err); 699 700 if (!rc || errno == ENOENT) 701 return 0; 702 703 strbuf_addf(err, "unable to unlink '%s': %s", 704 file, strerror(errno)); 705 return -1; 706 } 707 708 int unlink_or_warn(const char *file) 709 { 710 return warn_if_unremovable("unlink", file, unlink(file)); 711 } 712 713 int rmdir_or_warn(const char *file) 714 { 715 return warn_if_unremovable("rmdir", file, rmdir(file)); 716 } 717 718 static int access_error_is_ok(int err, unsigned flag) 719 { 720 return (is_missing_file_error(err) || 721 ((flag & ACCESS_EACCES_OK) && err == EACCES)); 722 } 723 724 int access_or_warn(const char *path, int mode, unsigned flag) 725 { 726 int ret = access(path, mode); 727 if (ret && !access_error_is_ok(errno, flag)) 728 warn_on_inaccessible(path); 729 return ret; 730 } 731 732 int access_or_die(const char *path, int mode, unsigned flag) 733 { 734 int ret = access(path, mode); 735 if (ret && !access_error_is_ok(errno, flag)) 736 die_errno(_("unable to access '%s'"), path); 737 return ret; 738 } 739 740 char *xgetcwd(void) 741 { 742 struct strbuf sb = STRBUF_INIT; 743 if (strbuf_getcwd(&sb)) 744 die_errno(_("unable to get current working directory")); 745 return strbuf_detach(&sb, NULL); 746 } 747 748 int xsnprintf(char *dst, size_t max, const char *fmt, ...) 749 { 750 va_list ap; 751 int len; 752 753 va_start(ap, fmt); 754 len = vsnprintf(dst, max, fmt, ap); 755 va_end(ap); 756 757 if (len < 0) 758 die(_("unable to format message: %s"), fmt); 759 if (len >= max) 760 BUG("attempt to snprintf into too-small buffer"); 761 return len; 762 } 763 764 void write_file_buf(const char *path, const char *buf, size_t len) 765 { 766 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666); 767 if (write_in_full(fd, buf, len) < 0) 768 die_errno(_("could not write to '%s'"), path); 769 if (close(fd)) 770 die_errno(_("could not close '%s'"), path); 771 } 772 773 void write_file(const char *path, const char *fmt, ...) 774 { 775 va_list params; 776 struct strbuf sb = STRBUF_INIT; 777 778 va_start(params, fmt); 779 strbuf_vaddf(&sb, fmt, params); 780 va_end(params); 781 782 strbuf_complete_line(&sb); 783 784 write_file_buf(path, sb.buf, sb.len); 785 strbuf_release(&sb); 786 } 787 788 void sleep_millisec(int millisec) 789 { 790 poll(NULL, 0, millisec); 791 } 792 793 int xgethostname(char *buf, size_t len) 794 { 795 /* 796 * If the full hostname doesn't fit in buf, POSIX does not 797 * specify whether the buffer will be null-terminated, so to 798 * be safe, do it ourselves. 799 */ 800 int ret = gethostname(buf, len); 801 if (!ret) 802 buf[len - 1] = 0; 803 return ret; 804 } 805 806 int is_missing_file(const char *filename) 807 { 808 struct stat st; 809 810 if (stat(filename, &st) < 0) { 811 if (errno == ENOENT) 812 return 1; 813 die_errno(_("could not stat %s"), filename); 814 } 815 816 return 0; 817 } 818 819 int is_empty_or_missing_file(const char *filename) 820 { 821 struct stat st; 822 823 if (stat(filename, &st) < 0) { 824 if (errno == ENOENT) 825 return 1; 826 die_errno(_("could not stat %s"), filename); 827 } 828 829 return !st.st_size; 830 } 831 832 int open_nofollow(const char *path, int flags) 833 { 834 #ifdef O_NOFOLLOW 835 int ret = open(path, flags | O_NOFOLLOW); 836 /* 837 * NetBSD sets errno to EFTYPE when path is a symlink. The only other 838 * time this errno occurs when O_REGULAR is used. Since we don't use 839 * it anywhere we can avoid an lstat here. FreeBSD does the same with 840 * EMLINK. 841 */ 842 # ifdef __NetBSD__ 843 # define SYMLINK_ERRNO EFTYPE 844 # elif defined(__FreeBSD__) 845 # define SYMLINK_ERRNO EMLINK 846 # endif 847 # if SYMLINK_ERRNO 848 if (ret < 0 && errno == SYMLINK_ERRNO) { 849 errno = ELOOP; 850 return -1; 851 } 852 # undef SYMLINK_ERRNO 853 # endif 854 return ret; 855 #else 856 struct stat st; 857 if (lstat(path, &st) < 0) 858 return -1; 859 if (S_ISLNK(st.st_mode)) { 860 errno = ELOOP; 861 return -1; 862 } 863 return open(path, flags); 864 #endif 865 } 866 867 int csprng_bytes(void *buf, size_t len, MAYBE_UNUSED unsigned flags) 868 { 869 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD) 870 /* This function never returns an error. */ 871 arc4random_buf(buf, len); 872 return 0; 873 #elif defined(HAVE_GETRANDOM) 874 ssize_t res; 875 char *p = buf; 876 while (len) { 877 res = getrandom(p, len, 0); 878 if (res < 0) 879 return -1; 880 len -= res; 881 p += res; 882 } 883 return 0; 884 #elif defined(HAVE_GETENTROPY) 885 int res; 886 char *p = buf; 887 while (len) { 888 /* getentropy has a maximum size of 256 bytes. */ 889 size_t chunk = len < 256 ? len : 256; 890 res = getentropy(p, chunk); 891 if (res < 0) 892 return -1; 893 len -= chunk; 894 p += chunk; 895 } 896 return 0; 897 #elif defined(HAVE_RTLGENRANDOM) 898 if (!RtlGenRandom(buf, len)) 899 return -1; 900 return 0; 901 #elif defined(HAVE_OPENSSL_CSPRNG) 902 switch (RAND_pseudo_bytes(buf, len)) { 903 case 1: 904 return 0; 905 case 0: 906 if (flags & CSPRNG_BYTES_INSECURE) 907 return 0; 908 errno = EIO; 909 return -1; 910 default: 911 errno = ENOTSUP; 912 return -1; 913 } 914 #else 915 ssize_t res; 916 char *p = buf; 917 int fd, err; 918 fd = open("/dev/urandom", O_RDONLY); 919 if (fd < 0) 920 return -1; 921 while (len) { 922 res = xread(fd, p, len); 923 if (res < 0) { 924 err = errno; 925 close(fd); 926 errno = err; 927 return -1; 928 } 929 len -= res; 930 p += res; 931 } 932 close(fd); 933 return 0; 934 #endif 935 } 936 937 uint32_t git_rand(unsigned flags) 938 { 939 uint32_t result; 940 941 if (csprng_bytes(&result, sizeof(result), flags) < 0) 942 die(_("unable to get random bytes")); 943 944 return result; 945 } 946 947 static void mmap_limit_check(size_t length) 948 { 949 static size_t limit = 0; 950 if (!limit) { 951 limit = git_env_ulong("GIT_MMAP_LIMIT", 0); 952 if (!limit) 953 limit = SIZE_MAX; 954 } 955 if (length > limit) 956 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX), 957 (uintmax_t)length, (uintmax_t)limit); 958 } 959 960 void *xmmap_gently(void *start, size_t length, 961 int prot, int flags, int fd, off_t offset) 962 { 963 void *ret; 964 965 mmap_limit_check(length); 966 ret = mmap(start, length, prot, flags, fd, offset); 967 if (ret == MAP_FAILED && !length) 968 ret = NULL; 969 return ret; 970 } 971 972 const char *mmap_os_err(void) 973 { 974 static const char blank[] = ""; 975 #if defined(__linux__) 976 if (errno == ENOMEM) { 977 /* this continues an existing error message: */ 978 static const char enomem[] = 979 ", check sys.vm.max_map_count and/or RLIMIT_DATA"; 980 return enomem; 981 } 982 #endif /* OS-specific bits */ 983 return blank; 984 } 985 986 void *xmmap(void *start, size_t length, 987 int prot, int flags, int fd, off_t offset) 988 { 989 void *ret = xmmap_gently(start, length, prot, flags, fd, offset); 990 if (ret == MAP_FAILED) 991 die_errno(_("mmap failed%s"), mmap_os_err()); 992 return ret; 993 }