Merge branch 'jc/resolve-undo' into maint
[git/debian.git] / wrapper.c
blob1c3c970080b0e00169802b8de4d3f70b709b44ad
1 /*
2 * Various trivial helper wrappers around standard functions
3 */
4 #include "cache.h"
5 #include "config.h"
7 static intmax_t count_fsync_writeout_only;
8 static intmax_t count_fsync_hardware_flush;
10 #ifdef HAVE_RTLGENRANDOM
11 /* This is required to get access to RtlGenRandom. */
12 #define SystemFunction036 NTAPI SystemFunction036
13 #include <NTSecAPI.h>
14 #undef SystemFunction036
15 #endif
17 static int memory_limit_check(size_t size, int gentle)
19 static size_t limit = 0;
20 if (!limit) {
21 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
22 if (!limit)
23 limit = SIZE_MAX;
25 if (size > limit) {
26 if (gentle) {
27 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
28 (uintmax_t)size, (uintmax_t)limit);
29 return -1;
30 } else
31 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
32 (uintmax_t)size, (uintmax_t)limit);
34 return 0;
37 char *xstrdup(const char *str)
39 char *ret = strdup(str);
40 if (!ret)
41 die("Out of memory, strdup failed");
42 return ret;
45 static void *do_xmalloc(size_t size, int gentle)
47 void *ret;
49 if (memory_limit_check(size, gentle))
50 return NULL;
51 ret = malloc(size);
52 if (!ret && !size)
53 ret = malloc(1);
54 if (!ret) {
55 if (!gentle)
56 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
57 (unsigned long)size);
58 else {
59 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
60 (unsigned long)size);
61 return NULL;
64 #ifdef XMALLOC_POISON
65 memset(ret, 0xA5, size);
66 #endif
67 return ret;
70 void *xmalloc(size_t size)
72 return do_xmalloc(size, 0);
75 static void *do_xmallocz(size_t size, int gentle)
77 void *ret;
78 if (unsigned_add_overflows(size, 1)) {
79 if (gentle) {
80 error("Data too large to fit into virtual memory space.");
81 return NULL;
82 } else
83 die("Data too large to fit into virtual memory space.");
85 ret = do_xmalloc(size + 1, gentle);
86 if (ret)
87 ((char*)ret)[size] = 0;
88 return ret;
91 void *xmallocz(size_t size)
93 return do_xmallocz(size, 0);
96 void *xmallocz_gently(size_t size)
98 return do_xmallocz(size, 1);
102 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
103 * "data" to the allocated memory, zero terminates the allocated memory,
104 * and returns a pointer to the allocated memory. If the allocation fails,
105 * the program dies.
107 void *xmemdupz(const void *data, size_t len)
109 return memcpy(xmallocz(len), data, len);
112 char *xstrndup(const char *str, size_t len)
114 char *p = memchr(str, '\0', len);
115 return xmemdupz(str, p ? p - str : len);
118 int xstrncmpz(const char *s, const char *t, size_t len)
120 int res = strncmp(s, t, len);
121 if (res)
122 return res;
123 return s[len] == '\0' ? 0 : 1;
126 void *xrealloc(void *ptr, size_t size)
128 void *ret;
130 if (!size) {
131 free(ptr);
132 return xmalloc(0);
135 memory_limit_check(size, 0);
136 ret = realloc(ptr, size);
137 if (!ret)
138 die("Out of memory, realloc failed");
139 return ret;
142 void *xcalloc(size_t nmemb, size_t size)
144 void *ret;
146 if (unsigned_mult_overflows(nmemb, size))
147 die("data too large to fit into virtual memory space");
149 memory_limit_check(size * nmemb, 0);
150 ret = calloc(nmemb, size);
151 if (!ret && (!nmemb || !size))
152 ret = calloc(1, 1);
153 if (!ret)
154 die("Out of memory, calloc failed");
155 return ret;
158 void xsetenv(const char *name, const char *value, int overwrite)
160 if (setenv(name, value, overwrite))
161 die_errno(_("could not setenv '%s'"), name ? name : "(null)");
165 * Limit size of IO chunks, because huge chunks only cause pain. OS X
166 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
167 * the absence of bugs, large chunks can result in bad latencies when
168 * you decide to kill the process.
170 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
171 * that is smaller than that, clip it to SSIZE_MAX, as a call to
172 * read(2) or write(2) larger than that is allowed to fail. As the last
173 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
174 * to override this, if the definition of SSIZE_MAX given by the platform
175 * is broken.
177 #ifndef MAX_IO_SIZE
178 # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
179 # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
180 # define MAX_IO_SIZE SSIZE_MAX
181 # else
182 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
183 # endif
184 #endif
187 * xopen() is the same as open(), but it die()s if the open() fails.
189 int xopen(const char *path, int oflag, ...)
191 mode_t mode = 0;
192 va_list ap;
195 * va_arg() will have undefined behavior if the specified type is not
196 * compatible with the argument type. Since integers are promoted to
197 * ints, we fetch the next argument as an int, and then cast it to a
198 * mode_t to avoid undefined behavior.
200 va_start(ap, oflag);
201 if (oflag & O_CREAT)
202 mode = va_arg(ap, int);
203 va_end(ap);
205 for (;;) {
206 int fd = open(path, oflag, mode);
207 if (fd >= 0)
208 return fd;
209 if (errno == EINTR)
210 continue;
212 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
213 die_errno(_("unable to create '%s'"), path);
214 else if ((oflag & O_RDWR) == O_RDWR)
215 die_errno(_("could not open '%s' for reading and writing"), path);
216 else if ((oflag & O_WRONLY) == O_WRONLY)
217 die_errno(_("could not open '%s' for writing"), path);
218 else
219 die_errno(_("could not open '%s' for reading"), path);
223 static int handle_nonblock(int fd, short poll_events, int err)
225 struct pollfd pfd;
227 if (err != EAGAIN && err != EWOULDBLOCK)
228 return 0;
230 pfd.fd = fd;
231 pfd.events = poll_events;
234 * no need to check for errors, here;
235 * a subsequent read/write will detect unrecoverable errors
237 poll(&pfd, 1, -1);
238 return 1;
242 * xread() is the same a read(), but it automatically restarts read()
243 * operations with a recoverable error (EAGAIN and EINTR). xread()
244 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
246 ssize_t xread(int fd, void *buf, size_t len)
248 ssize_t nr;
249 if (len > MAX_IO_SIZE)
250 len = MAX_IO_SIZE;
251 while (1) {
252 nr = read(fd, buf, len);
253 if (nr < 0) {
254 if (errno == EINTR)
255 continue;
256 if (handle_nonblock(fd, POLLIN, errno))
257 continue;
259 return nr;
264 * xwrite() is the same a write(), but it automatically restarts write()
265 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
266 * GUARANTEE that "len" bytes is written even if the operation is successful.
268 ssize_t xwrite(int fd, const void *buf, size_t len)
270 ssize_t nr;
271 if (len > MAX_IO_SIZE)
272 len = MAX_IO_SIZE;
273 while (1) {
274 nr = write(fd, buf, len);
275 if (nr < 0) {
276 if (errno == EINTR)
277 continue;
278 if (handle_nonblock(fd, POLLOUT, errno))
279 continue;
282 return nr;
287 * xpread() is the same as pread(), but it automatically restarts pread()
288 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
289 * NOT GUARANTEE that "len" bytes is read even if the data is available.
291 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
293 ssize_t nr;
294 if (len > MAX_IO_SIZE)
295 len = MAX_IO_SIZE;
296 while (1) {
297 nr = pread(fd, buf, len, offset);
298 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
299 continue;
300 return nr;
304 ssize_t read_in_full(int fd, void *buf, size_t count)
306 char *p = buf;
307 ssize_t total = 0;
309 while (count > 0) {
310 ssize_t loaded = xread(fd, p, count);
311 if (loaded < 0)
312 return -1;
313 if (loaded == 0)
314 return total;
315 count -= loaded;
316 p += loaded;
317 total += loaded;
320 return total;
323 ssize_t write_in_full(int fd, const void *buf, size_t count)
325 const char *p = buf;
326 ssize_t total = 0;
328 while (count > 0) {
329 ssize_t written = xwrite(fd, p, count);
330 if (written < 0)
331 return -1;
332 if (!written) {
333 errno = ENOSPC;
334 return -1;
336 count -= written;
337 p += written;
338 total += written;
341 return total;
344 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
346 char *p = buf;
347 ssize_t total = 0;
349 while (count > 0) {
350 ssize_t loaded = xpread(fd, p, count, offset);
351 if (loaded < 0)
352 return -1;
353 if (loaded == 0)
354 return total;
355 count -= loaded;
356 p += loaded;
357 total += loaded;
358 offset += loaded;
361 return total;
364 int xdup(int fd)
366 int ret = dup(fd);
367 if (ret < 0)
368 die_errno("dup failed");
369 return ret;
373 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
375 FILE *xfopen(const char *path, const char *mode)
377 for (;;) {
378 FILE *fp = fopen(path, mode);
379 if (fp)
380 return fp;
381 if (errno == EINTR)
382 continue;
384 if (*mode && mode[1] == '+')
385 die_errno(_("could not open '%s' for reading and writing"), path);
386 else if (*mode == 'w' || *mode == 'a')
387 die_errno(_("could not open '%s' for writing"), path);
388 else
389 die_errno(_("could not open '%s' for reading"), path);
393 FILE *xfdopen(int fd, const char *mode)
395 FILE *stream = fdopen(fd, mode);
396 if (!stream)
397 die_errno("Out of memory? fdopen failed");
398 return stream;
401 FILE *fopen_for_writing(const char *path)
403 FILE *ret = fopen(path, "w");
405 if (!ret && errno == EPERM) {
406 if (!unlink(path))
407 ret = fopen(path, "w");
408 else
409 errno = EPERM;
411 return ret;
414 static void warn_on_inaccessible(const char *path)
416 warning_errno(_("unable to access '%s'"), path);
419 int warn_on_fopen_errors(const char *path)
421 if (errno != ENOENT && errno != ENOTDIR) {
422 warn_on_inaccessible(path);
423 return -1;
426 return 0;
429 FILE *fopen_or_warn(const char *path, const char *mode)
431 FILE *fp = fopen(path, mode);
433 if (fp)
434 return fp;
436 warn_on_fopen_errors(path);
437 return NULL;
440 int xmkstemp(char *filename_template)
442 int fd;
443 char origtemplate[PATH_MAX];
444 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
446 fd = mkstemp(filename_template);
447 if (fd < 0) {
448 int saved_errno = errno;
449 const char *nonrelative_template;
451 if (strlen(filename_template) != strlen(origtemplate))
452 filename_template = origtemplate;
454 nonrelative_template = absolute_path(filename_template);
455 errno = saved_errno;
456 die_errno("Unable to create temporary file '%s'",
457 nonrelative_template);
459 return fd;
462 /* Adapted from libiberty's mkstemp.c. */
464 #undef TMP_MAX
465 #define TMP_MAX 16384
467 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
469 static const char letters[] =
470 "abcdefghijklmnopqrstuvwxyz"
471 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
472 "0123456789";
473 static const int num_letters = ARRAY_SIZE(letters) - 1;
474 static const char x_pattern[] = "XXXXXX";
475 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
476 char *filename_template;
477 size_t len;
478 int fd, count;
480 len = strlen(pattern);
482 if (len < num_x + suffix_len) {
483 errno = EINVAL;
484 return -1;
487 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
488 errno = EINVAL;
489 return -1;
493 * Replace pattern's XXXXXX characters with randomness.
494 * Try TMP_MAX different filenames.
496 filename_template = &pattern[len - num_x - suffix_len];
497 for (count = 0; count < TMP_MAX; ++count) {
498 int i;
499 uint64_t v;
500 if (csprng_bytes(&v, sizeof(v)) < 0)
501 return error_errno("unable to get random bytes for temporary file");
503 /* Fill in the random bits. */
504 for (i = 0; i < num_x; i++) {
505 filename_template[i] = letters[v % num_letters];
506 v /= num_letters;
509 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
510 if (fd >= 0)
511 return fd;
513 * Fatal error (EPERM, ENOSPC etc).
514 * It doesn't make sense to loop.
516 if (errno != EEXIST)
517 break;
519 /* We return the null string if we can't find a unique file name. */
520 pattern[0] = '\0';
521 return -1;
524 int git_mkstemp_mode(char *pattern, int mode)
526 /* mkstemp is just mkstemps with no suffix */
527 return git_mkstemps_mode(pattern, 0, mode);
530 int xmkstemp_mode(char *filename_template, int mode)
532 int fd;
533 char origtemplate[PATH_MAX];
534 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
536 fd = git_mkstemp_mode(filename_template, mode);
537 if (fd < 0) {
538 int saved_errno = errno;
539 const char *nonrelative_template;
541 if (!filename_template[0])
542 filename_template = origtemplate;
544 nonrelative_template = absolute_path(filename_template);
545 errno = saved_errno;
546 die_errno("Unable to create temporary file '%s'",
547 nonrelative_template);
549 return fd;
553 * Some platforms return EINTR from fsync. Since fsync is invoked in some
554 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
556 static int fsync_loop(int fd)
558 int err;
560 do {
561 err = fsync(fd);
562 } while (err < 0 && errno == EINTR);
563 return err;
566 int git_fsync(int fd, enum fsync_action action)
568 switch (action) {
569 case FSYNC_WRITEOUT_ONLY:
570 count_fsync_writeout_only += 1;
572 #ifdef __APPLE__
574 * On macOS, fsync just causes filesystem cache writeback but
575 * does not flush hardware caches.
577 return fsync_loop(fd);
578 #endif
580 #ifdef HAVE_SYNC_FILE_RANGE
582 * On linux 2.6.17 and above, sync_file_range is the way to
583 * issue a writeback without a hardware flush. An offset of
584 * 0 and size of 0 indicates writeout of the entire file and the
585 * wait flags ensure that all dirty data is written to the disk
586 * (potentially in a disk-side cache) before we continue.
589 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
590 SYNC_FILE_RANGE_WRITE |
591 SYNC_FILE_RANGE_WAIT_AFTER);
592 #endif
594 #ifdef fsync_no_flush
595 return fsync_no_flush(fd);
596 #endif
598 errno = ENOSYS;
599 return -1;
601 case FSYNC_HARDWARE_FLUSH:
602 count_fsync_hardware_flush += 1;
605 * On macOS, a special fcntl is required to really flush the
606 * caches within the storage controller. As of this writing,
607 * this is a very expensive operation on Apple SSDs.
609 #ifdef __APPLE__
610 return fcntl(fd, F_FULLFSYNC);
611 #else
612 return fsync_loop(fd);
613 #endif
614 default:
615 BUG("unexpected git_fsync(%d) call", action);
619 void trace_git_fsync_stats(void)
621 trace2_data_intmax("fsync", the_repository, "fsync/writeout-only", count_fsync_writeout_only);
622 trace2_data_intmax("fsync", the_repository, "fsync/hardware-flush", count_fsync_hardware_flush);
625 static int warn_if_unremovable(const char *op, const char *file, int rc)
627 int err;
628 if (!rc || errno == ENOENT)
629 return 0;
630 err = errno;
631 warning_errno("unable to %s '%s'", op, file);
632 errno = err;
633 return rc;
636 int unlink_or_msg(const char *file, struct strbuf *err)
638 int rc = unlink(file);
640 assert(err);
642 if (!rc || errno == ENOENT)
643 return 0;
645 strbuf_addf(err, "unable to unlink '%s': %s",
646 file, strerror(errno));
647 return -1;
650 int unlink_or_warn(const char *file)
652 return warn_if_unremovable("unlink", file, unlink(file));
655 int rmdir_or_warn(const char *file)
657 return warn_if_unremovable("rmdir", file, rmdir(file));
660 int remove_or_warn(unsigned int mode, const char *file)
662 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
665 static int access_error_is_ok(int err, unsigned flag)
667 return (is_missing_file_error(err) ||
668 ((flag & ACCESS_EACCES_OK) && err == EACCES));
671 int access_or_warn(const char *path, int mode, unsigned flag)
673 int ret = access(path, mode);
674 if (ret && !access_error_is_ok(errno, flag))
675 warn_on_inaccessible(path);
676 return ret;
679 int access_or_die(const char *path, int mode, unsigned flag)
681 int ret = access(path, mode);
682 if (ret && !access_error_is_ok(errno, flag))
683 die_errno(_("unable to access '%s'"), path);
684 return ret;
687 char *xgetcwd(void)
689 struct strbuf sb = STRBUF_INIT;
690 if (strbuf_getcwd(&sb))
691 die_errno(_("unable to get current working directory"));
692 return strbuf_detach(&sb, NULL);
695 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
697 va_list ap;
698 int len;
700 va_start(ap, fmt);
701 len = vsnprintf(dst, max, fmt, ap);
702 va_end(ap);
704 if (len < 0)
705 BUG("your snprintf is broken");
706 if (len >= max)
707 BUG("attempt to snprintf into too-small buffer");
708 return len;
711 void write_file_buf(const char *path, const char *buf, size_t len)
713 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
714 if (write_in_full(fd, buf, len) < 0)
715 die_errno(_("could not write to '%s'"), path);
716 if (close(fd))
717 die_errno(_("could not close '%s'"), path);
720 void write_file(const char *path, const char *fmt, ...)
722 va_list params;
723 struct strbuf sb = STRBUF_INIT;
725 va_start(params, fmt);
726 strbuf_vaddf(&sb, fmt, params);
727 va_end(params);
729 strbuf_complete_line(&sb);
731 write_file_buf(path, sb.buf, sb.len);
732 strbuf_release(&sb);
735 void sleep_millisec(int millisec)
737 poll(NULL, 0, millisec);
740 int xgethostname(char *buf, size_t len)
743 * If the full hostname doesn't fit in buf, POSIX does not
744 * specify whether the buffer will be null-terminated, so to
745 * be safe, do it ourselves.
747 int ret = gethostname(buf, len);
748 if (!ret)
749 buf[len - 1] = 0;
750 return ret;
753 int is_empty_or_missing_file(const char *filename)
755 struct stat st;
757 if (stat(filename, &st) < 0) {
758 if (errno == ENOENT)
759 return 1;
760 die_errno(_("could not stat %s"), filename);
763 return !st.st_size;
766 int open_nofollow(const char *path, int flags)
768 #ifdef O_NOFOLLOW
769 return open(path, flags | O_NOFOLLOW);
770 #else
771 struct stat st;
772 if (lstat(path, &st) < 0)
773 return -1;
774 if (S_ISLNK(st.st_mode)) {
775 errno = ELOOP;
776 return -1;
778 return open(path, flags);
779 #endif
782 int csprng_bytes(void *buf, size_t len)
784 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
785 /* This function never returns an error. */
786 arc4random_buf(buf, len);
787 return 0;
788 #elif defined(HAVE_GETRANDOM)
789 ssize_t res;
790 char *p = buf;
791 while (len) {
792 res = getrandom(p, len, 0);
793 if (res < 0)
794 return -1;
795 len -= res;
796 p += res;
798 return 0;
799 #elif defined(HAVE_GETENTROPY)
800 int res;
801 char *p = buf;
802 while (len) {
803 /* getentropy has a maximum size of 256 bytes. */
804 size_t chunk = len < 256 ? len : 256;
805 res = getentropy(p, chunk);
806 if (res < 0)
807 return -1;
808 len -= chunk;
809 p += chunk;
811 return 0;
812 #elif defined(HAVE_RTLGENRANDOM)
813 if (!RtlGenRandom(buf, len))
814 return -1;
815 return 0;
816 #elif defined(HAVE_OPENSSL_CSPRNG)
817 int res = RAND_bytes(buf, len);
818 if (res == 1)
819 return 0;
820 if (res == -1)
821 errno = ENOTSUP;
822 else
823 errno = EIO;
824 return -1;
825 #else
826 ssize_t res;
827 char *p = buf;
828 int fd, err;
829 fd = open("/dev/urandom", O_RDONLY);
830 if (fd < 0)
831 return -1;
832 while (len) {
833 res = xread(fd, p, len);
834 if (res < 0) {
835 err = errno;
836 close(fd);
837 errno = err;
838 return -1;
840 len -= res;
841 p += res;
843 close(fd);
844 return 0;
845 #endif