branch: fix a leak in setup_tracking
[alt-git.git] / wrapper.c
blob67f5f5dbe199f8362cad205a19f968687cb2906b
1 /*
2 * Various trivial helper wrappers around standard functions
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "config.h"
7 #include "gettext.h"
8 #include "object.h"
9 #include "repository.h"
10 #include "strbuf.h"
11 #include "trace2.h"
12 #include "wrapper.h"
14 static intmax_t count_fsync_writeout_only;
15 static intmax_t count_fsync_hardware_flush;
17 #ifdef HAVE_RTLGENRANDOM
18 /* This is required to get access to RtlGenRandom. */
19 #define SystemFunction036 NTAPI SystemFunction036
20 #include <NTSecAPI.h>
21 #undef SystemFunction036
22 #endif
24 static int memory_limit_check(size_t size, int gentle)
26 static size_t limit = 0;
27 if (!limit) {
28 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
29 if (!limit)
30 limit = SIZE_MAX;
32 if (size > limit) {
33 if (gentle) {
34 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
35 (uintmax_t)size, (uintmax_t)limit);
36 return -1;
37 } else
38 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
39 (uintmax_t)size, (uintmax_t)limit);
41 return 0;
44 char *xstrdup(const char *str)
46 char *ret = strdup(str);
47 if (!ret)
48 die("Out of memory, strdup failed");
49 return ret;
52 static void *do_xmalloc(size_t size, int gentle)
54 void *ret;
56 if (memory_limit_check(size, gentle))
57 return NULL;
58 ret = malloc(size);
59 if (!ret && !size)
60 ret = malloc(1);
61 if (!ret) {
62 if (!gentle)
63 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
64 (unsigned long)size);
65 else {
66 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
67 (unsigned long)size);
68 return NULL;
71 #ifdef XMALLOC_POISON
72 memset(ret, 0xA5, size);
73 #endif
74 return ret;
77 void *xmalloc(size_t size)
79 return do_xmalloc(size, 0);
82 static void *do_xmallocz(size_t size, int gentle)
84 void *ret;
85 if (unsigned_add_overflows(size, 1)) {
86 if (gentle) {
87 error("Data too large to fit into virtual memory space.");
88 return NULL;
89 } else
90 die("Data too large to fit into virtual memory space.");
92 ret = do_xmalloc(size + 1, gentle);
93 if (ret)
94 ((char*)ret)[size] = 0;
95 return ret;
98 void *xmallocz(size_t size)
100 return do_xmallocz(size, 0);
103 void *xmallocz_gently(size_t size)
105 return do_xmallocz(size, 1);
109 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
110 * "data" to the allocated memory, zero terminates the allocated memory,
111 * and returns a pointer to the allocated memory. If the allocation fails,
112 * the program dies.
114 void *xmemdupz(const void *data, size_t len)
116 return memcpy(xmallocz(len), data, len);
119 char *xstrndup(const char *str, size_t len)
121 char *p = memchr(str, '\0', len);
122 return xmemdupz(str, p ? p - str : len);
125 int xstrncmpz(const char *s, const char *t, size_t len)
127 int res = strncmp(s, t, len);
128 if (res)
129 return res;
130 return s[len] == '\0' ? 0 : 1;
133 void *xrealloc(void *ptr, size_t size)
135 void *ret;
137 if (!size) {
138 free(ptr);
139 return xmalloc(0);
142 memory_limit_check(size, 0);
143 ret = realloc(ptr, size);
144 if (!ret)
145 die("Out of memory, realloc failed");
146 return ret;
149 void *xcalloc(size_t nmemb, size_t size)
151 void *ret;
153 if (unsigned_mult_overflows(nmemb, size))
154 die("data too large to fit into virtual memory space");
156 memory_limit_check(size * nmemb, 0);
157 ret = calloc(nmemb, size);
158 if (!ret && (!nmemb || !size))
159 ret = calloc(1, 1);
160 if (!ret)
161 die("Out of memory, calloc failed");
162 return ret;
165 void xsetenv(const char *name, const char *value, int overwrite)
167 if (setenv(name, value, overwrite))
168 die_errno(_("could not setenv '%s'"), name ? name : "(null)");
172 * xopen() is the same as open(), but it die()s if the open() fails.
174 int xopen(const char *path, int oflag, ...)
176 mode_t mode = 0;
177 va_list ap;
180 * va_arg() will have undefined behavior if the specified type is not
181 * compatible with the argument type. Since integers are promoted to
182 * ints, we fetch the next argument as an int, and then cast it to a
183 * mode_t to avoid undefined behavior.
185 va_start(ap, oflag);
186 if (oflag & O_CREAT)
187 mode = va_arg(ap, int);
188 va_end(ap);
190 for (;;) {
191 int fd = open(path, oflag, mode);
192 if (fd >= 0)
193 return fd;
194 if (errno == EINTR)
195 continue;
197 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
198 die_errno(_("unable to create '%s'"), path);
199 else if ((oflag & O_RDWR) == O_RDWR)
200 die_errno(_("could not open '%s' for reading and writing"), path);
201 else if ((oflag & O_WRONLY) == O_WRONLY)
202 die_errno(_("could not open '%s' for writing"), path);
203 else
204 die_errno(_("could not open '%s' for reading"), path);
208 static int handle_nonblock(int fd, short poll_events, int err)
210 struct pollfd pfd;
212 if (err != EAGAIN && err != EWOULDBLOCK)
213 return 0;
215 pfd.fd = fd;
216 pfd.events = poll_events;
219 * no need to check for errors, here;
220 * a subsequent read/write will detect unrecoverable errors
222 poll(&pfd, 1, -1);
223 return 1;
227 * xread() is the same a read(), but it automatically restarts read()
228 * operations with a recoverable error (EAGAIN and EINTR). xread()
229 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
231 ssize_t xread(int fd, void *buf, size_t len)
233 ssize_t nr;
234 if (len > MAX_IO_SIZE)
235 len = MAX_IO_SIZE;
236 while (1) {
237 nr = read(fd, buf, len);
238 if (nr < 0) {
239 if (errno == EINTR)
240 continue;
241 if (handle_nonblock(fd, POLLIN, errno))
242 continue;
244 return nr;
249 * xwrite() is the same a write(), but it automatically restarts write()
250 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
251 * GUARANTEE that "len" bytes is written even if the operation is successful.
253 ssize_t xwrite(int fd, const void *buf, size_t len)
255 ssize_t nr;
256 if (len > MAX_IO_SIZE)
257 len = MAX_IO_SIZE;
258 while (1) {
259 nr = write(fd, buf, len);
260 if (nr < 0) {
261 if (errno == EINTR)
262 continue;
263 if (handle_nonblock(fd, POLLOUT, errno))
264 continue;
267 return nr;
272 * xpread() is the same as pread(), but it automatically restarts pread()
273 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
274 * NOT GUARANTEE that "len" bytes is read even if the data is available.
276 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
278 ssize_t nr;
279 if (len > MAX_IO_SIZE)
280 len = MAX_IO_SIZE;
281 while (1) {
282 nr = pread(fd, buf, len, offset);
283 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
284 continue;
285 return nr;
289 ssize_t read_in_full(int fd, void *buf, size_t count)
291 char *p = buf;
292 ssize_t total = 0;
294 while (count > 0) {
295 ssize_t loaded = xread(fd, p, count);
296 if (loaded < 0)
297 return -1;
298 if (loaded == 0)
299 return total;
300 count -= loaded;
301 p += loaded;
302 total += loaded;
305 return total;
308 ssize_t write_in_full(int fd, const void *buf, size_t count)
310 const char *p = buf;
311 ssize_t total = 0;
313 while (count > 0) {
314 ssize_t written = xwrite(fd, p, count);
315 if (written < 0)
316 return -1;
317 if (!written) {
318 errno = ENOSPC;
319 return -1;
321 count -= written;
322 p += written;
323 total += written;
326 return total;
329 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
331 char *p = buf;
332 ssize_t total = 0;
334 while (count > 0) {
335 ssize_t loaded = xpread(fd, p, count, offset);
336 if (loaded < 0)
337 return -1;
338 if (loaded == 0)
339 return total;
340 count -= loaded;
341 p += loaded;
342 total += loaded;
343 offset += loaded;
346 return total;
349 int xdup(int fd)
351 int ret = dup(fd);
352 if (ret < 0)
353 die_errno("dup failed");
354 return ret;
358 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
360 FILE *xfopen(const char *path, const char *mode)
362 for (;;) {
363 FILE *fp = fopen(path, mode);
364 if (fp)
365 return fp;
366 if (errno == EINTR)
367 continue;
369 if (*mode && mode[1] == '+')
370 die_errno(_("could not open '%s' for reading and writing"), path);
371 else if (*mode == 'w' || *mode == 'a')
372 die_errno(_("could not open '%s' for writing"), path);
373 else
374 die_errno(_("could not open '%s' for reading"), path);
378 FILE *xfdopen(int fd, const char *mode)
380 FILE *stream = fdopen(fd, mode);
381 if (!stream)
382 die_errno("Out of memory? fdopen failed");
383 return stream;
386 FILE *fopen_for_writing(const char *path)
388 FILE *ret = fopen(path, "w");
390 if (!ret && errno == EPERM) {
391 if (!unlink(path))
392 ret = fopen(path, "w");
393 else
394 errno = EPERM;
396 return ret;
399 static void warn_on_inaccessible(const char *path)
401 warning_errno(_("unable to access '%s'"), path);
404 int warn_on_fopen_errors(const char *path)
406 if (errno != ENOENT && errno != ENOTDIR) {
407 warn_on_inaccessible(path);
408 return -1;
411 return 0;
414 FILE *fopen_or_warn(const char *path, const char *mode)
416 FILE *fp = fopen(path, mode);
418 if (fp)
419 return fp;
421 warn_on_fopen_errors(path);
422 return NULL;
425 int xmkstemp(char *filename_template)
427 int fd;
428 char origtemplate[PATH_MAX];
429 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
431 fd = mkstemp(filename_template);
432 if (fd < 0) {
433 int saved_errno = errno;
434 const char *nonrelative_template;
436 if (strlen(filename_template) != strlen(origtemplate))
437 filename_template = origtemplate;
439 nonrelative_template = absolute_path(filename_template);
440 errno = saved_errno;
441 die_errno("Unable to create temporary file '%s'",
442 nonrelative_template);
444 return fd;
447 /* Adapted from libiberty's mkstemp.c. */
449 #undef TMP_MAX
450 #define TMP_MAX 16384
452 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
454 static const char letters[] =
455 "abcdefghijklmnopqrstuvwxyz"
456 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
457 "0123456789";
458 static const int num_letters = ARRAY_SIZE(letters) - 1;
459 static const char x_pattern[] = "XXXXXX";
460 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
461 char *filename_template;
462 size_t len;
463 int fd, count;
465 len = strlen(pattern);
467 if (len < num_x + suffix_len) {
468 errno = EINVAL;
469 return -1;
472 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
473 errno = EINVAL;
474 return -1;
478 * Replace pattern's XXXXXX characters with randomness.
479 * Try TMP_MAX different filenames.
481 filename_template = &pattern[len - num_x - suffix_len];
482 for (count = 0; count < TMP_MAX; ++count) {
483 int i;
484 uint64_t v;
485 if (csprng_bytes(&v, sizeof(v)) < 0)
486 return error_errno("unable to get random bytes for temporary file");
488 /* Fill in the random bits. */
489 for (i = 0; i < num_x; i++) {
490 filename_template[i] = letters[v % num_letters];
491 v /= num_letters;
494 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
495 if (fd >= 0)
496 return fd;
498 * Fatal error (EPERM, ENOSPC etc).
499 * It doesn't make sense to loop.
501 if (errno != EEXIST)
502 break;
504 /* We return the null string if we can't find a unique file name. */
505 pattern[0] = '\0';
506 return -1;
509 int git_mkstemp_mode(char *pattern, int mode)
511 /* mkstemp is just mkstemps with no suffix */
512 return git_mkstemps_mode(pattern, 0, mode);
515 int xmkstemp_mode(char *filename_template, int mode)
517 int fd;
518 char origtemplate[PATH_MAX];
519 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
521 fd = git_mkstemp_mode(filename_template, mode);
522 if (fd < 0) {
523 int saved_errno = errno;
524 const char *nonrelative_template;
526 if (!filename_template[0])
527 filename_template = origtemplate;
529 nonrelative_template = absolute_path(filename_template);
530 errno = saved_errno;
531 die_errno("Unable to create temporary file '%s'",
532 nonrelative_template);
534 return fd;
538 * Some platforms return EINTR from fsync. Since fsync is invoked in some
539 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
541 static int fsync_loop(int fd)
543 int err;
545 do {
546 err = fsync(fd);
547 } while (err < 0 && errno == EINTR);
548 return err;
551 int git_fsync(int fd, enum fsync_action action)
553 switch (action) {
554 case FSYNC_WRITEOUT_ONLY:
555 count_fsync_writeout_only += 1;
557 #ifdef __APPLE__
559 * On macOS, fsync just causes filesystem cache writeback but
560 * does not flush hardware caches.
562 return fsync_loop(fd);
563 #endif
565 #ifdef HAVE_SYNC_FILE_RANGE
567 * On linux 2.6.17 and above, sync_file_range is the way to
568 * issue a writeback without a hardware flush. An offset of
569 * 0 and size of 0 indicates writeout of the entire file and the
570 * wait flags ensure that all dirty data is written to the disk
571 * (potentially in a disk-side cache) before we continue.
574 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
575 SYNC_FILE_RANGE_WRITE |
576 SYNC_FILE_RANGE_WAIT_AFTER);
577 #endif
579 #ifdef fsync_no_flush
580 return fsync_no_flush(fd);
581 #endif
583 errno = ENOSYS;
584 return -1;
586 case FSYNC_HARDWARE_FLUSH:
587 count_fsync_hardware_flush += 1;
590 * On macOS, a special fcntl is required to really flush the
591 * caches within the storage controller. As of this writing,
592 * this is a very expensive operation on Apple SSDs.
594 #ifdef __APPLE__
595 return fcntl(fd, F_FULLFSYNC);
596 #else
597 return fsync_loop(fd);
598 #endif
599 default:
600 BUG("unexpected git_fsync(%d) call", action);
604 static void log_trace_fsync_if(const char *key, intmax_t value)
606 if (value)
607 trace2_data_intmax("fsync", the_repository, key, value);
610 void trace_git_fsync_stats(void)
612 log_trace_fsync_if("fsync/writeout-only", count_fsync_writeout_only);
613 log_trace_fsync_if("fsync/hardware-flush", count_fsync_hardware_flush);
616 static int warn_if_unremovable(const char *op, const char *file, int rc)
618 int err;
619 if (!rc || errno == ENOENT)
620 return 0;
621 err = errno;
622 warning_errno("unable to %s '%s'", op, file);
623 errno = err;
624 return rc;
627 int unlink_or_msg(const char *file, struct strbuf *err)
629 int rc = unlink(file);
631 assert(err);
633 if (!rc || errno == ENOENT)
634 return 0;
636 strbuf_addf(err, "unable to unlink '%s': %s",
637 file, strerror(errno));
638 return -1;
641 int unlink_or_warn(const char *file)
643 return warn_if_unremovable("unlink", file, unlink(file));
646 int rmdir_or_warn(const char *file)
648 return warn_if_unremovable("rmdir", file, rmdir(file));
651 int remove_or_warn(unsigned int mode, const char *file)
653 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
656 static int access_error_is_ok(int err, unsigned flag)
658 return (is_missing_file_error(err) ||
659 ((flag & ACCESS_EACCES_OK) && err == EACCES));
662 int access_or_warn(const char *path, int mode, unsigned flag)
664 int ret = access(path, mode);
665 if (ret && !access_error_is_ok(errno, flag))
666 warn_on_inaccessible(path);
667 return ret;
670 int access_or_die(const char *path, int mode, unsigned flag)
672 int ret = access(path, mode);
673 if (ret && !access_error_is_ok(errno, flag))
674 die_errno(_("unable to access '%s'"), path);
675 return ret;
678 char *xgetcwd(void)
680 struct strbuf sb = STRBUF_INIT;
681 if (strbuf_getcwd(&sb))
682 die_errno(_("unable to get current working directory"));
683 return strbuf_detach(&sb, NULL);
686 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
688 va_list ap;
689 int len;
691 va_start(ap, fmt);
692 len = vsnprintf(dst, max, fmt, ap);
693 va_end(ap);
695 if (len < 0)
696 BUG("your snprintf is broken");
697 if (len >= max)
698 BUG("attempt to snprintf into too-small buffer");
699 return len;
702 void write_file_buf(const char *path, const char *buf, size_t len)
704 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
705 if (write_in_full(fd, buf, len) < 0)
706 die_errno(_("could not write to '%s'"), path);
707 if (close(fd))
708 die_errno(_("could not close '%s'"), path);
711 void write_file(const char *path, const char *fmt, ...)
713 va_list params;
714 struct strbuf sb = STRBUF_INIT;
716 va_start(params, fmt);
717 strbuf_vaddf(&sb, fmt, params);
718 va_end(params);
720 strbuf_complete_line(&sb);
722 write_file_buf(path, sb.buf, sb.len);
723 strbuf_release(&sb);
726 void sleep_millisec(int millisec)
728 poll(NULL, 0, millisec);
731 int xgethostname(char *buf, size_t len)
734 * If the full hostname doesn't fit in buf, POSIX does not
735 * specify whether the buffer will be null-terminated, so to
736 * be safe, do it ourselves.
738 int ret = gethostname(buf, len);
739 if (!ret)
740 buf[len - 1] = 0;
741 return ret;
744 int is_empty_or_missing_file(const char *filename)
746 struct stat st;
748 if (stat(filename, &st) < 0) {
749 if (errno == ENOENT)
750 return 1;
751 die_errno(_("could not stat %s"), filename);
754 return !st.st_size;
757 int open_nofollow(const char *path, int flags)
759 #ifdef O_NOFOLLOW
760 return open(path, flags | O_NOFOLLOW);
761 #else
762 struct stat st;
763 if (lstat(path, &st) < 0)
764 return -1;
765 if (S_ISLNK(st.st_mode)) {
766 errno = ELOOP;
767 return -1;
769 return open(path, flags);
770 #endif
773 int csprng_bytes(void *buf, size_t len)
775 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
776 /* This function never returns an error. */
777 arc4random_buf(buf, len);
778 return 0;
779 #elif defined(HAVE_GETRANDOM)
780 ssize_t res;
781 char *p = buf;
782 while (len) {
783 res = getrandom(p, len, 0);
784 if (res < 0)
785 return -1;
786 len -= res;
787 p += res;
789 return 0;
790 #elif defined(HAVE_GETENTROPY)
791 int res;
792 char *p = buf;
793 while (len) {
794 /* getentropy has a maximum size of 256 bytes. */
795 size_t chunk = len < 256 ? len : 256;
796 res = getentropy(p, chunk);
797 if (res < 0)
798 return -1;
799 len -= chunk;
800 p += chunk;
802 return 0;
803 #elif defined(HAVE_RTLGENRANDOM)
804 if (!RtlGenRandom(buf, len))
805 return -1;
806 return 0;
807 #elif defined(HAVE_OPENSSL_CSPRNG)
808 int res = RAND_bytes(buf, len);
809 if (res == 1)
810 return 0;
811 if (res == -1)
812 errno = ENOTSUP;
813 else
814 errno = EIO;
815 return -1;
816 #else
817 ssize_t res;
818 char *p = buf;
819 int fd, err;
820 fd = open("/dev/urandom", O_RDONLY);
821 if (fd < 0)
822 return -1;
823 while (len) {
824 res = xread(fd, p, len);
825 if (res < 0) {
826 err = errno;
827 close(fd);
828 errno = err;
829 return -1;
831 len -= res;
832 p += res;
834 close(fd);
835 return 0;
836 #endif