Merge branch 'gc/branch-recurse-submodules-fix'
[alt-git.git] / wrapper.c
blob354d784c034244e4868372e1cf3b5f9a91f04cac
1 /*
2 * Various trivial helper wrappers around standard functions
3 */
4 #include "cache.h"
5 #include "config.h"
7 #ifdef HAVE_RTLGENRANDOM
8 /* This is required to get access to RtlGenRandom. */
9 #define SystemFunction036 NTAPI SystemFunction036
10 #include <NTSecAPI.h>
11 #undef SystemFunction036
12 #endif
14 static int memory_limit_check(size_t size, int gentle)
16 static size_t limit = 0;
17 if (!limit) {
18 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
19 if (!limit)
20 limit = SIZE_MAX;
22 if (size > limit) {
23 if (gentle) {
24 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
25 (uintmax_t)size, (uintmax_t)limit);
26 return -1;
27 } else
28 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
29 (uintmax_t)size, (uintmax_t)limit);
31 return 0;
34 char *xstrdup(const char *str)
36 char *ret = strdup(str);
37 if (!ret)
38 die("Out of memory, strdup failed");
39 return ret;
42 static void *do_xmalloc(size_t size, int gentle)
44 void *ret;
46 if (memory_limit_check(size, gentle))
47 return NULL;
48 ret = malloc(size);
49 if (!ret && !size)
50 ret = malloc(1);
51 if (!ret) {
52 if (!gentle)
53 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
54 (unsigned long)size);
55 else {
56 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
57 (unsigned long)size);
58 return NULL;
61 #ifdef XMALLOC_POISON
62 memset(ret, 0xA5, size);
63 #endif
64 return ret;
67 void *xmalloc(size_t size)
69 return do_xmalloc(size, 0);
72 static void *do_xmallocz(size_t size, int gentle)
74 void *ret;
75 if (unsigned_add_overflows(size, 1)) {
76 if (gentle) {
77 error("Data too large to fit into virtual memory space.");
78 return NULL;
79 } else
80 die("Data too large to fit into virtual memory space.");
82 ret = do_xmalloc(size + 1, gentle);
83 if (ret)
84 ((char*)ret)[size] = 0;
85 return ret;
88 void *xmallocz(size_t size)
90 return do_xmallocz(size, 0);
93 void *xmallocz_gently(size_t size)
95 return do_xmallocz(size, 1);
99 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
100 * "data" to the allocated memory, zero terminates the allocated memory,
101 * and returns a pointer to the allocated memory. If the allocation fails,
102 * the program dies.
104 void *xmemdupz(const void *data, size_t len)
106 return memcpy(xmallocz(len), data, len);
109 char *xstrndup(const char *str, size_t len)
111 char *p = memchr(str, '\0', len);
112 return xmemdupz(str, p ? p - str : len);
115 int xstrncmpz(const char *s, const char *t, size_t len)
117 int res = strncmp(s, t, len);
118 if (res)
119 return res;
120 return s[len] == '\0' ? 0 : 1;
123 void *xrealloc(void *ptr, size_t size)
125 void *ret;
127 if (!size) {
128 free(ptr);
129 return xmalloc(0);
132 memory_limit_check(size, 0);
133 ret = realloc(ptr, size);
134 if (!ret)
135 die("Out of memory, realloc failed");
136 return ret;
139 void *xcalloc(size_t nmemb, size_t size)
141 void *ret;
143 if (unsigned_mult_overflows(nmemb, size))
144 die("data too large to fit into virtual memory space");
146 memory_limit_check(size * nmemb, 0);
147 ret = calloc(nmemb, size);
148 if (!ret && (!nmemb || !size))
149 ret = calloc(1, 1);
150 if (!ret)
151 die("Out of memory, calloc failed");
152 return ret;
155 void xsetenv(const char *name, const char *value, int overwrite)
157 if (setenv(name, value, overwrite))
158 die_errno(_("could not setenv '%s'"), name ? name : "(null)");
162 * Limit size of IO chunks, because huge chunks only cause pain. OS X
163 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
164 * the absence of bugs, large chunks can result in bad latencies when
165 * you decide to kill the process.
167 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
168 * that is smaller than that, clip it to SSIZE_MAX, as a call to
169 * read(2) or write(2) larger than that is allowed to fail. As the last
170 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
171 * to override this, if the definition of SSIZE_MAX given by the platform
172 * is broken.
174 #ifndef MAX_IO_SIZE
175 # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
176 # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
177 # define MAX_IO_SIZE SSIZE_MAX
178 # else
179 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
180 # endif
181 #endif
184 * xopen() is the same as open(), but it die()s if the open() fails.
186 int xopen(const char *path, int oflag, ...)
188 mode_t mode = 0;
189 va_list ap;
192 * va_arg() will have undefined behavior if the specified type is not
193 * compatible with the argument type. Since integers are promoted to
194 * ints, we fetch the next argument as an int, and then cast it to a
195 * mode_t to avoid undefined behavior.
197 va_start(ap, oflag);
198 if (oflag & O_CREAT)
199 mode = va_arg(ap, int);
200 va_end(ap);
202 for (;;) {
203 int fd = open(path, oflag, mode);
204 if (fd >= 0)
205 return fd;
206 if (errno == EINTR)
207 continue;
209 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
210 die_errno(_("unable to create '%s'"), path);
211 else if ((oflag & O_RDWR) == O_RDWR)
212 die_errno(_("could not open '%s' for reading and writing"), path);
213 else if ((oflag & O_WRONLY) == O_WRONLY)
214 die_errno(_("could not open '%s' for writing"), path);
215 else
216 die_errno(_("could not open '%s' for reading"), path);
220 static int handle_nonblock(int fd, short poll_events, int err)
222 struct pollfd pfd;
224 if (err != EAGAIN && err != EWOULDBLOCK)
225 return 0;
227 pfd.fd = fd;
228 pfd.events = poll_events;
231 * no need to check for errors, here;
232 * a subsequent read/write will detect unrecoverable errors
234 poll(&pfd, 1, -1);
235 return 1;
239 * xread() is the same a read(), but it automatically restarts read()
240 * operations with a recoverable error (EAGAIN and EINTR). xread()
241 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
243 ssize_t xread(int fd, void *buf, size_t len)
245 ssize_t nr;
246 if (len > MAX_IO_SIZE)
247 len = MAX_IO_SIZE;
248 while (1) {
249 nr = read(fd, buf, len);
250 if (nr < 0) {
251 if (errno == EINTR)
252 continue;
253 if (handle_nonblock(fd, POLLIN, errno))
254 continue;
256 return nr;
261 * xwrite() is the same a write(), but it automatically restarts write()
262 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
263 * GUARANTEE that "len" bytes is written even if the operation is successful.
265 ssize_t xwrite(int fd, const void *buf, size_t len)
267 ssize_t nr;
268 if (len > MAX_IO_SIZE)
269 len = MAX_IO_SIZE;
270 while (1) {
271 nr = write(fd, buf, len);
272 if (nr < 0) {
273 if (errno == EINTR)
274 continue;
275 if (handle_nonblock(fd, POLLOUT, errno))
276 continue;
279 return nr;
284 * xpread() is the same as pread(), but it automatically restarts pread()
285 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
286 * NOT GUARANTEE that "len" bytes is read even if the data is available.
288 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
290 ssize_t nr;
291 if (len > MAX_IO_SIZE)
292 len = MAX_IO_SIZE;
293 while (1) {
294 nr = pread(fd, buf, len, offset);
295 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
296 continue;
297 return nr;
301 ssize_t read_in_full(int fd, void *buf, size_t count)
303 char *p = buf;
304 ssize_t total = 0;
306 while (count > 0) {
307 ssize_t loaded = xread(fd, p, count);
308 if (loaded < 0)
309 return -1;
310 if (loaded == 0)
311 return total;
312 count -= loaded;
313 p += loaded;
314 total += loaded;
317 return total;
320 ssize_t write_in_full(int fd, const void *buf, size_t count)
322 const char *p = buf;
323 ssize_t total = 0;
325 while (count > 0) {
326 ssize_t written = xwrite(fd, p, count);
327 if (written < 0)
328 return -1;
329 if (!written) {
330 errno = ENOSPC;
331 return -1;
333 count -= written;
334 p += written;
335 total += written;
338 return total;
341 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
343 char *p = buf;
344 ssize_t total = 0;
346 while (count > 0) {
347 ssize_t loaded = xpread(fd, p, count, offset);
348 if (loaded < 0)
349 return -1;
350 if (loaded == 0)
351 return total;
352 count -= loaded;
353 p += loaded;
354 total += loaded;
355 offset += loaded;
358 return total;
361 int xdup(int fd)
363 int ret = dup(fd);
364 if (ret < 0)
365 die_errno("dup failed");
366 return ret;
370 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
372 FILE *xfopen(const char *path, const char *mode)
374 for (;;) {
375 FILE *fp = fopen(path, mode);
376 if (fp)
377 return fp;
378 if (errno == EINTR)
379 continue;
381 if (*mode && mode[1] == '+')
382 die_errno(_("could not open '%s' for reading and writing"), path);
383 else if (*mode == 'w' || *mode == 'a')
384 die_errno(_("could not open '%s' for writing"), path);
385 else
386 die_errno(_("could not open '%s' for reading"), path);
390 FILE *xfdopen(int fd, const char *mode)
392 FILE *stream = fdopen(fd, mode);
393 if (stream == NULL)
394 die_errno("Out of memory? fdopen failed");
395 return stream;
398 FILE *fopen_for_writing(const char *path)
400 FILE *ret = fopen(path, "w");
402 if (!ret && errno == EPERM) {
403 if (!unlink(path))
404 ret = fopen(path, "w");
405 else
406 errno = EPERM;
408 return ret;
411 static void warn_on_inaccessible(const char *path)
413 warning_errno(_("unable to access '%s'"), path);
416 int warn_on_fopen_errors(const char *path)
418 if (errno != ENOENT && errno != ENOTDIR) {
419 warn_on_inaccessible(path);
420 return -1;
423 return 0;
426 FILE *fopen_or_warn(const char *path, const char *mode)
428 FILE *fp = fopen(path, mode);
430 if (fp)
431 return fp;
433 warn_on_fopen_errors(path);
434 return NULL;
437 int xmkstemp(char *filename_template)
439 int fd;
440 char origtemplate[PATH_MAX];
441 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
443 fd = mkstemp(filename_template);
444 if (fd < 0) {
445 int saved_errno = errno;
446 const char *nonrelative_template;
448 if (strlen(filename_template) != strlen(origtemplate))
449 filename_template = origtemplate;
451 nonrelative_template = absolute_path(filename_template);
452 errno = saved_errno;
453 die_errno("Unable to create temporary file '%s'",
454 nonrelative_template);
456 return fd;
459 /* Adapted from libiberty's mkstemp.c. */
461 #undef TMP_MAX
462 #define TMP_MAX 16384
464 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
466 static const char letters[] =
467 "abcdefghijklmnopqrstuvwxyz"
468 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
469 "0123456789";
470 static const int num_letters = ARRAY_SIZE(letters) - 1;
471 static const char x_pattern[] = "XXXXXX";
472 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
473 char *filename_template;
474 size_t len;
475 int fd, count;
477 len = strlen(pattern);
479 if (len < num_x + suffix_len) {
480 errno = EINVAL;
481 return -1;
484 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
485 errno = EINVAL;
486 return -1;
490 * Replace pattern's XXXXXX characters with randomness.
491 * Try TMP_MAX different filenames.
493 filename_template = &pattern[len - num_x - suffix_len];
494 for (count = 0; count < TMP_MAX; ++count) {
495 int i;
496 uint64_t v;
497 if (csprng_bytes(&v, sizeof(v)) < 0)
498 return error_errno("unable to get random bytes for temporary file");
500 /* Fill in the random bits. */
501 for (i = 0; i < num_x; i++) {
502 filename_template[i] = letters[v % num_letters];
503 v /= num_letters;
506 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
507 if (fd >= 0)
508 return fd;
510 * Fatal error (EPERM, ENOSPC etc).
511 * It doesn't make sense to loop.
513 if (errno != EEXIST)
514 break;
516 /* We return the null string if we can't find a unique file name. */
517 pattern[0] = '\0';
518 return -1;
521 int git_mkstemp_mode(char *pattern, int mode)
523 /* mkstemp is just mkstemps with no suffix */
524 return git_mkstemps_mode(pattern, 0, mode);
527 int xmkstemp_mode(char *filename_template, int mode)
529 int fd;
530 char origtemplate[PATH_MAX];
531 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
533 fd = git_mkstemp_mode(filename_template, mode);
534 if (fd < 0) {
535 int saved_errno = errno;
536 const char *nonrelative_template;
538 if (!filename_template[0])
539 filename_template = origtemplate;
541 nonrelative_template = absolute_path(filename_template);
542 errno = saved_errno;
543 die_errno("Unable to create temporary file '%s'",
544 nonrelative_template);
546 return fd;
550 * Some platforms return EINTR from fsync. Since fsync is invoked in some
551 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
553 static int fsync_loop(int fd)
555 int err;
557 do {
558 err = fsync(fd);
559 } while (err < 0 && errno == EINTR);
560 return err;
563 int git_fsync(int fd, enum fsync_action action)
565 switch (action) {
566 case FSYNC_WRITEOUT_ONLY:
568 #ifdef __APPLE__
570 * On macOS, fsync just causes filesystem cache writeback but
571 * does not flush hardware caches.
573 return fsync_loop(fd);
574 #endif
576 #ifdef HAVE_SYNC_FILE_RANGE
578 * On linux 2.6.17 and above, sync_file_range is the way to
579 * issue a writeback without a hardware flush. An offset of
580 * 0 and size of 0 indicates writeout of the entire file and the
581 * wait flags ensure that all dirty data is written to the disk
582 * (potentially in a disk-side cache) before we continue.
585 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
586 SYNC_FILE_RANGE_WRITE |
587 SYNC_FILE_RANGE_WAIT_AFTER);
588 #endif
590 #ifdef fsync_no_flush
591 return fsync_no_flush(fd);
592 #endif
594 errno = ENOSYS;
595 return -1;
597 case FSYNC_HARDWARE_FLUSH:
599 * On macOS, a special fcntl is required to really flush the
600 * caches within the storage controller. As of this writing,
601 * this is a very expensive operation on Apple SSDs.
603 #ifdef __APPLE__
604 return fcntl(fd, F_FULLFSYNC);
605 #else
606 return fsync_loop(fd);
607 #endif
608 default:
609 BUG("unexpected git_fsync(%d) call", action);
613 static int warn_if_unremovable(const char *op, const char *file, int rc)
615 int err;
616 if (!rc || errno == ENOENT)
617 return 0;
618 err = errno;
619 warning_errno("unable to %s '%s'", op, file);
620 errno = err;
621 return rc;
624 int unlink_or_msg(const char *file, struct strbuf *err)
626 int rc = unlink(file);
628 assert(err);
630 if (!rc || errno == ENOENT)
631 return 0;
633 strbuf_addf(err, "unable to unlink '%s': %s",
634 file, strerror(errno));
635 return -1;
638 int unlink_or_warn(const char *file)
640 return warn_if_unremovable("unlink", file, unlink(file));
643 int rmdir_or_warn(const char *file)
645 return warn_if_unremovable("rmdir", file, rmdir(file));
648 int remove_or_warn(unsigned int mode, const char *file)
650 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
653 static int access_error_is_ok(int err, unsigned flag)
655 return (is_missing_file_error(err) ||
656 ((flag & ACCESS_EACCES_OK) && err == EACCES));
659 int access_or_warn(const char *path, int mode, unsigned flag)
661 int ret = access(path, mode);
662 if (ret && !access_error_is_ok(errno, flag))
663 warn_on_inaccessible(path);
664 return ret;
667 int access_or_die(const char *path, int mode, unsigned flag)
669 int ret = access(path, mode);
670 if (ret && !access_error_is_ok(errno, flag))
671 die_errno(_("unable to access '%s'"), path);
672 return ret;
675 char *xgetcwd(void)
677 struct strbuf sb = STRBUF_INIT;
678 if (strbuf_getcwd(&sb))
679 die_errno(_("unable to get current working directory"));
680 return strbuf_detach(&sb, NULL);
683 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
685 va_list ap;
686 int len;
688 va_start(ap, fmt);
689 len = vsnprintf(dst, max, fmt, ap);
690 va_end(ap);
692 if (len < 0)
693 BUG("your snprintf is broken");
694 if (len >= max)
695 BUG("attempt to snprintf into too-small buffer");
696 return len;
699 void write_file_buf(const char *path, const char *buf, size_t len)
701 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
702 if (write_in_full(fd, buf, len) < 0)
703 die_errno(_("could not write to '%s'"), path);
704 if (close(fd))
705 die_errno(_("could not close '%s'"), path);
708 void write_file(const char *path, const char *fmt, ...)
710 va_list params;
711 struct strbuf sb = STRBUF_INIT;
713 va_start(params, fmt);
714 strbuf_vaddf(&sb, fmt, params);
715 va_end(params);
717 strbuf_complete_line(&sb);
719 write_file_buf(path, sb.buf, sb.len);
720 strbuf_release(&sb);
723 void sleep_millisec(int millisec)
725 poll(NULL, 0, millisec);
728 int xgethostname(char *buf, size_t len)
731 * If the full hostname doesn't fit in buf, POSIX does not
732 * specify whether the buffer will be null-terminated, so to
733 * be safe, do it ourselves.
735 int ret = gethostname(buf, len);
736 if (!ret)
737 buf[len - 1] = 0;
738 return ret;
741 int is_empty_or_missing_file(const char *filename)
743 struct stat st;
745 if (stat(filename, &st) < 0) {
746 if (errno == ENOENT)
747 return 1;
748 die_errno(_("could not stat %s"), filename);
751 return !st.st_size;
754 int open_nofollow(const char *path, int flags)
756 #ifdef O_NOFOLLOW
757 return open(path, flags | O_NOFOLLOW);
758 #else
759 struct stat st;
760 if (lstat(path, &st) < 0)
761 return -1;
762 if (S_ISLNK(st.st_mode)) {
763 errno = ELOOP;
764 return -1;
766 return open(path, flags);
767 #endif
770 int csprng_bytes(void *buf, size_t len)
772 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
773 /* This function never returns an error. */
774 arc4random_buf(buf, len);
775 return 0;
776 #elif defined(HAVE_GETRANDOM)
777 ssize_t res;
778 char *p = buf;
779 while (len) {
780 res = getrandom(p, len, 0);
781 if (res < 0)
782 return -1;
783 len -= res;
784 p += res;
786 return 0;
787 #elif defined(HAVE_GETENTROPY)
788 int res;
789 char *p = buf;
790 while (len) {
791 /* getentropy has a maximum size of 256 bytes. */
792 size_t chunk = len < 256 ? len : 256;
793 res = getentropy(p, chunk);
794 if (res < 0)
795 return -1;
796 len -= chunk;
797 p += chunk;
799 return 0;
800 #elif defined(HAVE_RTLGENRANDOM)
801 if (!RtlGenRandom(buf, len))
802 return -1;
803 return 0;
804 #elif defined(HAVE_OPENSSL_CSPRNG)
805 int res = RAND_bytes(buf, len);
806 if (res == 1)
807 return 0;
808 if (res == -1)
809 errno = ENOTSUP;
810 else
811 errno = EIO;
812 return -1;
813 #else
814 ssize_t res;
815 char *p = buf;
816 int fd, err;
817 fd = open("/dev/urandom", O_RDONLY);
818 if (fd < 0)
819 return -1;
820 while (len) {
821 res = xread(fd, p, len);
822 if (res < 0) {
823 err = errno;
824 close(fd);
825 errno = err;
826 return -1;
828 len -= res;
829 p += res;
831 close(fd);
832 return 0;
833 #endif