replay: remove progress and info output
[alt-git.git] / wrapper.c
blob7da15a56da614ce82ca1d6a5c6e2277b444f1063
1 /*
2 * Various trivial helper wrappers around standard functions
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "parse.h"
7 #include "gettext.h"
8 #include "repository.h"
9 #include "strbuf.h"
10 #include "trace2.h"
12 #ifdef HAVE_RTLGENRANDOM
13 /* This is required to get access to RtlGenRandom. */
14 #define SystemFunction036 NTAPI SystemFunction036
15 #include <ntsecapi.h>
16 #undef SystemFunction036
17 #endif
19 static int memory_limit_check(size_t size, int gentle)
21 static size_t limit = 0;
22 if (!limit) {
23 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
24 if (!limit)
25 limit = SIZE_MAX;
27 if (size > limit) {
28 if (gentle) {
29 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
30 (uintmax_t)size, (uintmax_t)limit);
31 return -1;
32 } else
33 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
34 (uintmax_t)size, (uintmax_t)limit);
36 return 0;
39 char *xstrdup(const char *str)
41 char *ret = strdup(str);
42 if (!ret)
43 die("Out of memory, strdup failed");
44 return ret;
47 static void *do_xmalloc(size_t size, int gentle)
49 void *ret;
51 if (memory_limit_check(size, gentle))
52 return NULL;
53 ret = malloc(size);
54 if (!ret && !size)
55 ret = malloc(1);
56 if (!ret) {
57 if (!gentle)
58 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
59 (unsigned long)size);
60 else {
61 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
62 (unsigned long)size);
63 return NULL;
66 #ifdef XMALLOC_POISON
67 memset(ret, 0xA5, size);
68 #endif
69 return ret;
72 void *xmalloc(size_t size)
74 return do_xmalloc(size, 0);
77 static void *do_xmallocz(size_t size, int gentle)
79 void *ret;
80 if (unsigned_add_overflows(size, 1)) {
81 if (gentle) {
82 error("Data too large to fit into virtual memory space.");
83 return NULL;
84 } else
85 die("Data too large to fit into virtual memory space.");
87 ret = do_xmalloc(size + 1, gentle);
88 if (ret)
89 ((char*)ret)[size] = 0;
90 return ret;
93 void *xmallocz(size_t size)
95 return do_xmallocz(size, 0);
98 void *xmallocz_gently(size_t size)
100 return do_xmallocz(size, 1);
104 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
105 * "data" to the allocated memory, zero terminates the allocated memory,
106 * and returns a pointer to the allocated memory. If the allocation fails,
107 * the program dies.
109 void *xmemdupz(const void *data, size_t len)
111 return memcpy(xmallocz(len), data, len);
114 char *xstrndup(const char *str, size_t len)
116 char *p = memchr(str, '\0', len);
117 return xmemdupz(str, p ? p - str : len);
120 int xstrncmpz(const char *s, const char *t, size_t len)
122 int res = strncmp(s, t, len);
123 if (res)
124 return res;
125 return s[len] == '\0' ? 0 : 1;
128 void *xrealloc(void *ptr, size_t size)
130 void *ret;
132 if (!size) {
133 free(ptr);
134 return xmalloc(0);
137 memory_limit_check(size, 0);
138 ret = realloc(ptr, size);
139 if (!ret)
140 die("Out of memory, realloc failed");
141 return ret;
144 void *xcalloc(size_t nmemb, size_t size)
146 void *ret;
148 if (unsigned_mult_overflows(nmemb, size))
149 die("data too large to fit into virtual memory space");
151 memory_limit_check(size * nmemb, 0);
152 ret = calloc(nmemb, size);
153 if (!ret && (!nmemb || !size))
154 ret = calloc(1, 1);
155 if (!ret)
156 die("Out of memory, calloc failed");
157 return ret;
160 void xsetenv(const char *name, const char *value, int overwrite)
162 if (setenv(name, value, overwrite))
163 die_errno(_("could not setenv '%s'"), name ? name : "(null)");
167 * xopen() is the same as open(), but it die()s if the open() fails.
169 int xopen(const char *path, int oflag, ...)
171 mode_t mode = 0;
172 va_list ap;
175 * va_arg() will have undefined behavior if the specified type is not
176 * compatible with the argument type. Since integers are promoted to
177 * ints, we fetch the next argument as an int, and then cast it to a
178 * mode_t to avoid undefined behavior.
180 va_start(ap, oflag);
181 if (oflag & O_CREAT)
182 mode = va_arg(ap, int);
183 va_end(ap);
185 for (;;) {
186 int fd = open(path, oflag, mode);
187 if (fd >= 0)
188 return fd;
189 if (errno == EINTR)
190 continue;
192 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
193 die_errno(_("unable to create '%s'"), path);
194 else if ((oflag & O_RDWR) == O_RDWR)
195 die_errno(_("could not open '%s' for reading and writing"), path);
196 else if ((oflag & O_WRONLY) == O_WRONLY)
197 die_errno(_("could not open '%s' for writing"), path);
198 else
199 die_errno(_("could not open '%s' for reading"), path);
203 static int handle_nonblock(int fd, short poll_events, int err)
205 struct pollfd pfd;
207 if (err != EAGAIN && err != EWOULDBLOCK)
208 return 0;
210 pfd.fd = fd;
211 pfd.events = poll_events;
214 * no need to check for errors, here;
215 * a subsequent read/write will detect unrecoverable errors
217 poll(&pfd, 1, -1);
218 return 1;
222 * xread() is the same a read(), but it automatically restarts read()
223 * operations with a recoverable error (EAGAIN and EINTR). xread()
224 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
226 ssize_t xread(int fd, void *buf, size_t len)
228 ssize_t nr;
229 if (len > MAX_IO_SIZE)
230 len = MAX_IO_SIZE;
231 while (1) {
232 nr = read(fd, buf, len);
233 if (nr < 0) {
234 if (errno == EINTR)
235 continue;
236 if (handle_nonblock(fd, POLLIN, errno))
237 continue;
239 return nr;
244 * xwrite() is the same a write(), but it automatically restarts write()
245 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
246 * GUARANTEE that "len" bytes is written even if the operation is successful.
248 ssize_t xwrite(int fd, const void *buf, size_t len)
250 ssize_t nr;
251 if (len > MAX_IO_SIZE)
252 len = MAX_IO_SIZE;
253 while (1) {
254 nr = write(fd, buf, len);
255 if (nr < 0) {
256 if (errno == EINTR)
257 continue;
258 if (handle_nonblock(fd, POLLOUT, errno))
259 continue;
262 return nr;
267 * xpread() is the same as pread(), but it automatically restarts pread()
268 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
269 * NOT GUARANTEE that "len" bytes is read even if the data is available.
271 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
273 ssize_t nr;
274 if (len > MAX_IO_SIZE)
275 len = MAX_IO_SIZE;
276 while (1) {
277 nr = pread(fd, buf, len, offset);
278 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
279 continue;
280 return nr;
284 ssize_t read_in_full(int fd, void *buf, size_t count)
286 char *p = buf;
287 ssize_t total = 0;
289 while (count > 0) {
290 ssize_t loaded = xread(fd, p, count);
291 if (loaded < 0)
292 return -1;
293 if (loaded == 0)
294 return total;
295 count -= loaded;
296 p += loaded;
297 total += loaded;
300 return total;
303 ssize_t write_in_full(int fd, const void *buf, size_t count)
305 const char *p = buf;
306 ssize_t total = 0;
308 while (count > 0) {
309 ssize_t written = xwrite(fd, p, count);
310 if (written < 0)
311 return -1;
312 if (!written) {
313 errno = ENOSPC;
314 return -1;
316 count -= written;
317 p += written;
318 total += written;
321 return total;
324 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
326 char *p = buf;
327 ssize_t total = 0;
329 while (count > 0) {
330 ssize_t loaded = xpread(fd, p, count, offset);
331 if (loaded < 0)
332 return -1;
333 if (loaded == 0)
334 return total;
335 count -= loaded;
336 p += loaded;
337 total += loaded;
338 offset += loaded;
341 return total;
344 int xdup(int fd)
346 int ret = dup(fd);
347 if (ret < 0)
348 die_errno("dup failed");
349 return ret;
353 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
355 FILE *xfopen(const char *path, const char *mode)
357 for (;;) {
358 FILE *fp = fopen(path, mode);
359 if (fp)
360 return fp;
361 if (errno == EINTR)
362 continue;
364 if (*mode && mode[1] == '+')
365 die_errno(_("could not open '%s' for reading and writing"), path);
366 else if (*mode == 'w' || *mode == 'a')
367 die_errno(_("could not open '%s' for writing"), path);
368 else
369 die_errno(_("could not open '%s' for reading"), path);
373 FILE *xfdopen(int fd, const char *mode)
375 FILE *stream = fdopen(fd, mode);
376 if (!stream)
377 die_errno("Out of memory? fdopen failed");
378 return stream;
381 FILE *fopen_for_writing(const char *path)
383 FILE *ret = fopen(path, "w");
385 if (!ret && errno == EPERM) {
386 if (!unlink(path))
387 ret = fopen(path, "w");
388 else
389 errno = EPERM;
391 return ret;
394 static void warn_on_inaccessible(const char *path)
396 warning_errno(_("unable to access '%s'"), path);
399 int warn_on_fopen_errors(const char *path)
401 if (errno != ENOENT && errno != ENOTDIR) {
402 warn_on_inaccessible(path);
403 return -1;
406 return 0;
409 FILE *fopen_or_warn(const char *path, const char *mode)
411 FILE *fp = fopen(path, mode);
413 if (fp)
414 return fp;
416 warn_on_fopen_errors(path);
417 return NULL;
420 int xmkstemp(char *filename_template)
422 int fd;
423 char origtemplate[PATH_MAX];
424 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
426 fd = mkstemp(filename_template);
427 if (fd < 0) {
428 int saved_errno = errno;
429 const char *nonrelative_template;
431 if (strlen(filename_template) != strlen(origtemplate))
432 filename_template = origtemplate;
434 nonrelative_template = absolute_path(filename_template);
435 errno = saved_errno;
436 die_errno("Unable to create temporary file '%s'",
437 nonrelative_template);
439 return fd;
442 /* Adapted from libiberty's mkstemp.c. */
444 #undef TMP_MAX
445 #define TMP_MAX 16384
447 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
449 static const char letters[] =
450 "abcdefghijklmnopqrstuvwxyz"
451 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
452 "0123456789";
453 static const int num_letters = ARRAY_SIZE(letters) - 1;
454 static const char x_pattern[] = "XXXXXX";
455 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
456 char *filename_template;
457 size_t len;
458 int fd, count;
460 len = strlen(pattern);
462 if (len < num_x + suffix_len) {
463 errno = EINVAL;
464 return -1;
467 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
468 errno = EINVAL;
469 return -1;
473 * Replace pattern's XXXXXX characters with randomness.
474 * Try TMP_MAX different filenames.
476 filename_template = &pattern[len - num_x - suffix_len];
477 for (count = 0; count < TMP_MAX; ++count) {
478 int i;
479 uint64_t v;
480 if (csprng_bytes(&v, sizeof(v)) < 0)
481 return error_errno("unable to get random bytes for temporary file");
483 /* Fill in the random bits. */
484 for (i = 0; i < num_x; i++) {
485 filename_template[i] = letters[v % num_letters];
486 v /= num_letters;
489 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
490 if (fd >= 0)
491 return fd;
493 * Fatal error (EPERM, ENOSPC etc).
494 * It doesn't make sense to loop.
496 if (errno != EEXIST)
497 break;
499 /* We return the null string if we can't find a unique file name. */
500 pattern[0] = '\0';
501 return -1;
504 int git_mkstemp_mode(char *pattern, int mode)
506 /* mkstemp is just mkstemps with no suffix */
507 return git_mkstemps_mode(pattern, 0, mode);
510 int xmkstemp_mode(char *filename_template, int mode)
512 int fd;
513 char origtemplate[PATH_MAX];
514 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
516 fd = git_mkstemp_mode(filename_template, mode);
517 if (fd < 0) {
518 int saved_errno = errno;
519 const char *nonrelative_template;
521 if (!filename_template[0])
522 filename_template = origtemplate;
524 nonrelative_template = absolute_path(filename_template);
525 errno = saved_errno;
526 die_errno("Unable to create temporary file '%s'",
527 nonrelative_template);
529 return fd;
533 * Some platforms return EINTR from fsync. Since fsync is invoked in some
534 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
536 static int fsync_loop(int fd)
538 int err;
540 do {
541 err = fsync(fd);
542 } while (err < 0 && errno == EINTR);
543 return err;
546 int git_fsync(int fd, enum fsync_action action)
548 switch (action) {
549 case FSYNC_WRITEOUT_ONLY:
550 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_WRITEOUT_ONLY, 1);
552 #ifdef __APPLE__
554 * On macOS, fsync just causes filesystem cache writeback but
555 * does not flush hardware caches.
557 return fsync_loop(fd);
558 #endif
560 #ifdef HAVE_SYNC_FILE_RANGE
562 * On linux 2.6.17 and above, sync_file_range is the way to
563 * issue a writeback without a hardware flush. An offset of
564 * 0 and size of 0 indicates writeout of the entire file and the
565 * wait flags ensure that all dirty data is written to the disk
566 * (potentially in a disk-side cache) before we continue.
569 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
570 SYNC_FILE_RANGE_WRITE |
571 SYNC_FILE_RANGE_WAIT_AFTER);
572 #endif
574 #ifdef fsync_no_flush
575 return fsync_no_flush(fd);
576 #endif
578 errno = ENOSYS;
579 return -1;
581 case FSYNC_HARDWARE_FLUSH:
582 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_HARDWARE_FLUSH, 1);
585 * On macOS, a special fcntl is required to really flush the
586 * caches within the storage controller. As of this writing,
587 * this is a very expensive operation on Apple SSDs.
589 #ifdef __APPLE__
590 return fcntl(fd, F_FULLFSYNC);
591 #else
592 return fsync_loop(fd);
593 #endif
594 default:
595 BUG("unexpected git_fsync(%d) call", action);
599 static int warn_if_unremovable(const char *op, const char *file, int rc)
601 int err;
602 if (!rc || errno == ENOENT)
603 return 0;
604 err = errno;
605 warning_errno("unable to %s '%s'", op, file);
606 errno = err;
607 return rc;
610 int unlink_or_msg(const char *file, struct strbuf *err)
612 int rc = unlink(file);
614 assert(err);
616 if (!rc || errno == ENOENT)
617 return 0;
619 strbuf_addf(err, "unable to unlink '%s': %s",
620 file, strerror(errno));
621 return -1;
624 int unlink_or_warn(const char *file)
626 return warn_if_unremovable("unlink", file, unlink(file));
629 int rmdir_or_warn(const char *file)
631 return warn_if_unremovable("rmdir", file, rmdir(file));
634 static int access_error_is_ok(int err, unsigned flag)
636 return (is_missing_file_error(err) ||
637 ((flag & ACCESS_EACCES_OK) && err == EACCES));
640 int access_or_warn(const char *path, int mode, unsigned flag)
642 int ret = access(path, mode);
643 if (ret && !access_error_is_ok(errno, flag))
644 warn_on_inaccessible(path);
645 return ret;
648 int access_or_die(const char *path, int mode, unsigned flag)
650 int ret = access(path, mode);
651 if (ret && !access_error_is_ok(errno, flag))
652 die_errno(_("unable to access '%s'"), path);
653 return ret;
656 char *xgetcwd(void)
658 struct strbuf sb = STRBUF_INIT;
659 if (strbuf_getcwd(&sb))
660 die_errno(_("unable to get current working directory"));
661 return strbuf_detach(&sb, NULL);
664 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
666 va_list ap;
667 int len;
669 va_start(ap, fmt);
670 len = vsnprintf(dst, max, fmt, ap);
671 va_end(ap);
673 if (len < 0)
674 BUG("your snprintf is broken");
675 if (len >= max)
676 BUG("attempt to snprintf into too-small buffer");
677 return len;
680 void write_file_buf(const char *path, const char *buf, size_t len)
682 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
683 if (write_in_full(fd, buf, len) < 0)
684 die_errno(_("could not write to '%s'"), path);
685 if (close(fd))
686 die_errno(_("could not close '%s'"), path);
689 void write_file(const char *path, const char *fmt, ...)
691 va_list params;
692 struct strbuf sb = STRBUF_INIT;
694 va_start(params, fmt);
695 strbuf_vaddf(&sb, fmt, params);
696 va_end(params);
698 strbuf_complete_line(&sb);
700 write_file_buf(path, sb.buf, sb.len);
701 strbuf_release(&sb);
704 void sleep_millisec(int millisec)
706 poll(NULL, 0, millisec);
709 int xgethostname(char *buf, size_t len)
712 * If the full hostname doesn't fit in buf, POSIX does not
713 * specify whether the buffer will be null-terminated, so to
714 * be safe, do it ourselves.
716 int ret = gethostname(buf, len);
717 if (!ret)
718 buf[len - 1] = 0;
719 return ret;
722 int is_empty_or_missing_file(const char *filename)
724 struct stat st;
726 if (stat(filename, &st) < 0) {
727 if (errno == ENOENT)
728 return 1;
729 die_errno(_("could not stat %s"), filename);
732 return !st.st_size;
735 int open_nofollow(const char *path, int flags)
737 #ifdef O_NOFOLLOW
738 return open(path, flags | O_NOFOLLOW);
739 #else
740 struct stat st;
741 if (lstat(path, &st) < 0)
742 return -1;
743 if (S_ISLNK(st.st_mode)) {
744 errno = ELOOP;
745 return -1;
747 return open(path, flags);
748 #endif
751 int csprng_bytes(void *buf, size_t len)
753 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
754 /* This function never returns an error. */
755 arc4random_buf(buf, len);
756 return 0;
757 #elif defined(HAVE_GETRANDOM)
758 ssize_t res;
759 char *p = buf;
760 while (len) {
761 res = getrandom(p, len, 0);
762 if (res < 0)
763 return -1;
764 len -= res;
765 p += res;
767 return 0;
768 #elif defined(HAVE_GETENTROPY)
769 int res;
770 char *p = buf;
771 while (len) {
772 /* getentropy has a maximum size of 256 bytes. */
773 size_t chunk = len < 256 ? len : 256;
774 res = getentropy(p, chunk);
775 if (res < 0)
776 return -1;
777 len -= chunk;
778 p += chunk;
780 return 0;
781 #elif defined(HAVE_RTLGENRANDOM)
782 if (!RtlGenRandom(buf, len))
783 return -1;
784 return 0;
785 #elif defined(HAVE_OPENSSL_CSPRNG)
786 int res = RAND_bytes(buf, len);
787 if (res == 1)
788 return 0;
789 if (res == -1)
790 errno = ENOTSUP;
791 else
792 errno = EIO;
793 return -1;
794 #else
795 ssize_t res;
796 char *p = buf;
797 int fd, err;
798 fd = open("/dev/urandom", O_RDONLY);
799 if (fd < 0)
800 return -1;
801 while (len) {
802 res = xread(fd, p, len);
803 if (res < 0) {
804 err = errno;
805 close(fd);
806 errno = err;
807 return -1;
809 len -= res;
810 p += res;
812 close(fd);
813 return 0;
814 #endif
817 uint32_t git_rand(void)
819 uint32_t result;
821 if (csprng_bytes(&result, sizeof(result)) < 0)
822 die(_("unable to get random bytes"));
824 return result;