Raw
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 <ntsecapi.h>
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 total_written += bytes_written;
380
381 /*
382 * We first need to discard any iovec entities that have been
383 * fully written.
384 */
385 while (iovcnt && (size_t)bytes_written >= iov->iov_len) {
386 bytes_written -= iov->iov_len;
387 iov++;
388 iovcnt--;
389 }
390
391 /*
392 * Finally, we need to adjust the last iovec in case we have
393 * performed a partial write.
394 */
395 if (iovcnt && bytes_written) {
396 iov->iov_base = (char *) iov->iov_base + bytes_written;
397 iov->iov_len -= bytes_written;
398 }
399 }
400
401 return total_written;
402 }
403
404 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
405 {
406 char *p = buf;
407 ssize_t total = 0;
408
409 while (count > 0) {
410 ssize_t loaded = xpread(fd, p, count, offset);
411 if (loaded < 0)
412 return -1;
413 if (loaded == 0)
414 return total;
415 count -= loaded;
416 p += loaded;
417 total += loaded;
418 offset += loaded;
419 }
420
421 return total;
422 }
423
424 int xdup(int fd)
425 {
426 int ret = dup(fd);
427 if (ret < 0)
428 die_errno("dup failed");
429 return ret;
430 }
431
432 /**
433 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
434 */
435 FILE *xfopen(const char *path, const char *mode)
436 {
437 for (;;) {
438 FILE *fp = fopen(path, mode);
439 if (fp)
440 return fp;
441 if (errno == EINTR)
442 continue;
443
444 if (*mode && mode[1] == '+')
445 die_errno(_("could not open '%s' for reading and writing"), path);
446 else if (*mode == 'w' || *mode == 'a')
447 die_errno(_("could not open '%s' for writing"), path);
448 else
449 die_errno(_("could not open '%s' for reading"), path);
450 }
451 }
452
453 FILE *xfdopen(int fd, const char *mode)
454 {
455 FILE *stream = fdopen(fd, mode);
456 if (!stream)
457 die_errno("Out of memory? fdopen failed");
458 return stream;
459 }
460
461 FILE *fopen_for_writing(const char *path)
462 {
463 FILE *ret = fopen(path, "w");
464
465 if (!ret && errno == EPERM) {
466 if (!unlink(path))
467 ret = fopen(path, "w");
468 else
469 errno = EPERM;
470 }
471 return ret;
472 }
473
474 static void warn_on_inaccessible(const char *path)
475 {
476 warning_errno(_("unable to access '%s'"), path);
477 }
478
479 int warn_on_fopen_errors(const char *path)
480 {
481 if (errno != ENOENT && errno != ENOTDIR) {
482 warn_on_inaccessible(path);
483 return -1;
484 }
485
486 return 0;
487 }
488
489 FILE *fopen_or_warn(const char *path, const char *mode)
490 {
491 FILE *fp = fopen(path, mode);
492
493 if (fp)
494 return fp;
495
496 warn_on_fopen_errors(path);
497 return NULL;
498 }
499
500 int xmkstemp(char *filename_template)
501 {
502 return xmkstemp_mode(filename_template, 0600);
503 }
504
505 /* Adapted from libiberty's mkstemp.c. */
506
507 #undef TMP_MAX
508 #define TMP_MAX 16384
509
510 /*
511 * Returns -1 on error, 0 if it created a directory, or an open file
512 * descriptor to the created regular file.
513 */
514 static int git_mkdstemps_mode(char *pattern, int suffix_len, int mode, bool dir)
515 {
516 static const char letters[] =
517 "abcdefghijklmnopqrstuvwxyz"
518 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
519 "0123456789";
520 static const int num_letters = ARRAY_SIZE(letters) - 1;
521 static const char x_pattern[] = "XXXXXX";
522 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
523 char *filename_template;
524 size_t len;
525 int fd, count;
526
527 len = strlen(pattern);
528
529 if (len < num_x + suffix_len) {
530 errno = EINVAL;
531 return -1;
532 }
533
534 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
535 errno = EINVAL;
536 return -1;
537 }
538
539 /*
540 * Replace pattern's XXXXXX characters with randomness.
541 * Try TMP_MAX different filenames.
542 */
543 filename_template = &pattern[len - num_x - suffix_len];
544 for (count = 0; count < TMP_MAX; ++count) {
545 int i;
546 uint64_t v;
547 if (csprng_bytes(&v, sizeof(v), 0) < 0)
548 return error_errno("unable to get random bytes for temporary file");
549
550 /* Fill in the random bits. */
551 for (i = 0; i < num_x; i++) {
552 filename_template[i] = letters[v % num_letters];
553 v /= num_letters;
554 }
555
556 if (dir)
557 fd = mkdir(pattern, mode);
558 else
559 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
560 if (fd >= 0)
561 return fd;
562 /*
563 * Fatal error (EPERM, ENOSPC etc).
564 * It doesn't make sense to loop.
565 */
566 if (errno != EEXIST)
567 break;
568 }
569 /* We return the null string if we can't find a unique file name. */
570 pattern[0] = '\0';
571 return -1;
572 }
573
574 char *git_mkdtemp(char *pattern)
575 {
576 return git_mkdstemps_mode(pattern, 0, 0700, true) ? NULL : pattern;
577 }
578
579 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
580 {
581 return git_mkdstemps_mode(pattern, suffix_len, mode, false);
582 }
583
584 int git_mkstemp_mode(char *pattern, int mode)
585 {
586 /* mkstemp is just mkstemps with no suffix */
587 return git_mkstemps_mode(pattern, 0, mode);
588 }
589
590 int xmkstemp_mode(char *filename_template, int mode)
591 {
592 int fd;
593 char origtemplate[PATH_MAX];
594 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
595
596 fd = git_mkstemp_mode(filename_template, mode);
597 if (fd < 0) {
598 int saved_errno = errno;
599 const char *nonrelative_template;
600
601 if (!filename_template[0])
602 filename_template = origtemplate;
603
604 nonrelative_template = absolute_path(filename_template);
605 errno = saved_errno;
606 die_errno("Unable to create temporary file '%s'",
607 nonrelative_template);
608 }
609 return fd;
610 }
611
612 /*
613 * Some platforms return EINTR from fsync. Since fsync is invoked in some
614 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
615 */
616 static int fsync_loop(int fd)
617 {
618 int err;
619
620 do {
621 err = fsync(fd);
622 } while (err < 0 && errno == EINTR);
623 return err;
624 }
625
626 int git_fsync(int fd, enum fsync_action action)
627 {
628 switch (action) {
629 case FSYNC_WRITEOUT_ONLY:
630 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_WRITEOUT_ONLY, 1);
631
632 #ifdef __APPLE__
633 /*
634 * On macOS, fsync just causes filesystem cache writeback but
635 * does not flush hardware caches.
636 */
637 return fsync_loop(fd);
638 #endif
639
640 #ifdef HAVE_SYNC_FILE_RANGE
641 /*
642 * On linux 2.6.17 and above, sync_file_range is the way to
643 * issue a writeback without a hardware flush. An offset of
644 * 0 and size of 0 indicates writeout of the entire file and the
645 * wait flags ensure that all dirty data is written to the disk
646 * (potentially in a disk-side cache) before we continue.
647 */
648
649 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
650 SYNC_FILE_RANGE_WRITE |
651 SYNC_FILE_RANGE_WAIT_AFTER);
652 #endif
653
654 #ifdef fsync_no_flush
655 return fsync_no_flush(fd);
656 #endif
657
658 errno = ENOSYS;
659 return -1;
660
661 case FSYNC_HARDWARE_FLUSH:
662 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_HARDWARE_FLUSH, 1);
663
664 /*
665 * On macOS, a special fcntl is required to really flush the
666 * caches within the storage controller. As of this writing,
667 * this is a very expensive operation on Apple SSDs.
668 */
669 #ifdef __APPLE__
670 return fcntl(fd, F_FULLFSYNC);
671 #else
672 return fsync_loop(fd);
673 #endif
674 default:
675 BUG("unexpected git_fsync(%d) call", action);
676 }
677 }
678
679 static int warn_if_unremovable(const char *op, const char *file, int rc)
680 {
681 int err;
682 if (!rc || errno == ENOENT)
683 return 0;
684 err = errno;
685 warning_errno("unable to %s '%s'", op, file);
686 errno = err;
687 return rc;
688 }
689
690 int unlink_or_msg(const char *file, struct strbuf *err)
691 {
692 int rc = unlink(file);
693
694 assert(err);
695
696 if (!rc || errno == ENOENT)
697 return 0;
698
699 strbuf_addf(err, "unable to unlink '%s': %s",
700 file, strerror(errno));
701 return -1;
702 }
703
704 int unlink_or_warn(const char *file)
705 {
706 return warn_if_unremovable("unlink", file, unlink(file));
707 }
708
709 int rmdir_or_warn(const char *file)
710 {
711 return warn_if_unremovable("rmdir", file, rmdir(file));
712 }
713
714 static int access_error_is_ok(int err, unsigned flag)
715 {
716 return (is_missing_file_error(err) ||
717 ((flag & ACCESS_EACCES_OK) && err == EACCES));
718 }
719
720 int access_or_warn(const char *path, int mode, unsigned flag)
721 {
722 int ret = access(path, mode);
723 if (ret && !access_error_is_ok(errno, flag))
724 warn_on_inaccessible(path);
725 return ret;
726 }
727
728 int access_or_die(const char *path, int mode, unsigned flag)
729 {
730 int ret = access(path, mode);
731 if (ret && !access_error_is_ok(errno, flag))
732 die_errno(_("unable to access '%s'"), path);
733 return ret;
734 }
735
736 char *xgetcwd(void)
737 {
738 struct strbuf sb = STRBUF_INIT;
739 if (strbuf_getcwd(&sb))
740 die_errno(_("unable to get current working directory"));
741 return strbuf_detach(&sb, NULL);
742 }
743
744 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
745 {
746 va_list ap;
747 int len;
748
749 va_start(ap, fmt);
750 len = vsnprintf(dst, max, fmt, ap);
751 va_end(ap);
752
753 if (len < 0)
754 die(_("unable to format message: %s"), fmt);
755 if (len >= max)
756 BUG("attempt to snprintf into too-small buffer");
757 return len;
758 }
759
760 void write_file_buf(const char *path, const char *buf, size_t len)
761 {
762 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
763 if (write_in_full(fd, buf, len) < 0)
764 die_errno(_("could not write to '%s'"), path);
765 if (close(fd))
766 die_errno(_("could not close '%s'"), path);
767 }
768
769 void write_file(const char *path, const char *fmt, ...)
770 {
771 va_list params;
772 struct strbuf sb = STRBUF_INIT;
773
774 va_start(params, fmt);
775 strbuf_vaddf(&sb, fmt, params);
776 va_end(params);
777
778 strbuf_complete_line(&sb);
779
780 write_file_buf(path, sb.buf, sb.len);
781 strbuf_release(&sb);
782 }
783
784 void sleep_millisec(int millisec)
785 {
786 poll(NULL, 0, millisec);
787 }
788
789 int xgethostname(char *buf, size_t len)
790 {
791 /*
792 * If the full hostname doesn't fit in buf, POSIX does not
793 * specify whether the buffer will be null-terminated, so to
794 * be safe, do it ourselves.
795 */
796 int ret = gethostname(buf, len);
797 if (!ret)
798 buf[len - 1] = 0;
799 return ret;
800 }
801
802 int is_missing_file(const char *filename)
803 {
804 struct stat st;
805
806 if (stat(filename, &st) < 0) {
807 if (errno == ENOENT)
808 return 1;
809 die_errno(_("could not stat %s"), filename);
810 }
811
812 return 0;
813 }
814
815 int is_empty_or_missing_file(const char *filename)
816 {
817 struct stat st;
818
819 if (stat(filename, &st) < 0) {
820 if (errno == ENOENT)
821 return 1;
822 die_errno(_("could not stat %s"), filename);
823 }
824
825 return !st.st_size;
826 }
827
828 int open_nofollow(const char *path, int flags)
829 {
830 #ifdef O_NOFOLLOW
831 int ret = open(path, flags | O_NOFOLLOW);
832 /*
833 * NetBSD sets errno to EFTYPE when path is a symlink. The only other
834 * time this errno occurs when O_REGULAR is used. Since we don't use
835 * it anywhere we can avoid an lstat here. FreeBSD does the same with
836 * EMLINK.
837 */
838 # ifdef __NetBSD__
839 # define SYMLINK_ERRNO EFTYPE
840 # elif defined(__FreeBSD__)
841 # define SYMLINK_ERRNO EMLINK
842 # endif
843 # if SYMLINK_ERRNO
844 if (ret < 0 && errno == SYMLINK_ERRNO) {
845 errno = ELOOP;
846 return -1;
847 }
848 # undef SYMLINK_ERRNO
849 # endif
850 return ret;
851 #else
852 struct stat st;
853 if (lstat(path, &st) < 0)
854 return -1;
855 if (S_ISLNK(st.st_mode)) {
856 errno = ELOOP;
857 return -1;
858 }
859 return open(path, flags);
860 #endif
861 }
862
863 int csprng_bytes(void *buf, size_t len, MAYBE_UNUSED unsigned flags)
864 {
865 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
866 /* This function never returns an error. */
867 arc4random_buf(buf, len);
868 return 0;
869 #elif defined(HAVE_GETRANDOM)
870 ssize_t res;
871 char *p = buf;
872 while (len) {
873 res = getrandom(p, len, 0);
874 if (res < 0)
875 return -1;
876 len -= res;
877 p += res;
878 }
879 return 0;
880 #elif defined(HAVE_GETENTROPY)
881 int res;
882 char *p = buf;
883 while (len) {
884 /* getentropy has a maximum size of 256 bytes. */
885 size_t chunk = len < 256 ? len : 256;
886 res = getentropy(p, chunk);
887 if (res < 0)
888 return -1;
889 len -= chunk;
890 p += chunk;
891 }
892 return 0;
893 #elif defined(HAVE_RTLGENRANDOM)
894 if (!RtlGenRandom(buf, len))
895 return -1;
896 return 0;
897 #elif defined(HAVE_OPENSSL_CSPRNG)
898 switch (RAND_pseudo_bytes(buf, len)) {
899 case 1:
900 return 0;
901 case 0:
902 if (flags & CSPRNG_BYTES_INSECURE)
903 return 0;
904 errno = EIO;
905 return -1;
906 default:
907 errno = ENOTSUP;
908 return -1;
909 }
910 #else
911 ssize_t res;
912 char *p = buf;
913 int fd, err;
914 fd = open("/dev/urandom", O_RDONLY);
915 if (fd < 0)
916 return -1;
917 while (len) {
918 res = xread(fd, p, len);
919 if (res < 0) {
920 err = errno;
921 close(fd);
922 errno = err;
923 return -1;
924 }
925 len -= res;
926 p += res;
927 }
928 close(fd);
929 return 0;
930 #endif
931 }
932
933 uint32_t git_rand(unsigned flags)
934 {
935 uint32_t result;
936
937 if (csprng_bytes(&result, sizeof(result), flags) < 0)
938 die(_("unable to get random bytes"));
939
940 return result;
941 }
942
943 static void mmap_limit_check(size_t length)
944 {
945 static size_t limit = 0;
946 if (!limit) {
947 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
948 if (!limit)
949 limit = SIZE_MAX;
950 }
951 if (length > limit)
952 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
953 (uintmax_t)length, (uintmax_t)limit);
954 }
955
956 void *xmmap_gently(void *start, size_t length,
957 int prot, int flags, int fd, off_t offset)
958 {
959 void *ret;
960
961 mmap_limit_check(length);
962 ret = mmap(start, length, prot, flags, fd, offset);
963 if (ret == MAP_FAILED && !length)
964 ret = NULL;
965 return ret;
966 }
967
968 const char *mmap_os_err(void)
969 {
970 static const char blank[] = "";
971 #if defined(__linux__)
972 if (errno == ENOMEM) {
973 /* this continues an existing error message: */
974 static const char enomem[] =
975 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
976 return enomem;
977 }
978 #endif /* OS-specific bits */
979 return blank;
980 }
981
982 void *xmmap(void *start, size_t length,
983 int prot, int flags, int fd, off_t offset)
984 {
985 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
986 if (ret == MAP_FAILED)
987 die_errno(_("mmap failed%s"), mmap_os_err());
988 return ret;
989 }