Documentation/technical: describe bitmap lookup table extension
[git/debian.git] / wrapper.c
blobcfe79bd081ff75837b626f1db7e3960e6dc4e5e4
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 static void log_trace_fsync_if(const char *key, intmax_t value)
621 if (value)
622 trace2_data_intmax("fsync", the_repository, key, value);
625 void trace_git_fsync_stats(void)
627 log_trace_fsync_if("fsync/writeout-only", count_fsync_writeout_only);
628 log_trace_fsync_if("fsync/hardware-flush", count_fsync_hardware_flush);
631 static int warn_if_unremovable(const char *op, const char *file, int rc)
633 int err;
634 if (!rc || errno == ENOENT)
635 return 0;
636 err = errno;
637 warning_errno("unable to %s '%s'", op, file);
638 errno = err;
639 return rc;
642 int unlink_or_msg(const char *file, struct strbuf *err)
644 int rc = unlink(file);
646 assert(err);
648 if (!rc || errno == ENOENT)
649 return 0;
651 strbuf_addf(err, "unable to unlink '%s': %s",
652 file, strerror(errno));
653 return -1;
656 int unlink_or_warn(const char *file)
658 return warn_if_unremovable("unlink", file, unlink(file));
661 int rmdir_or_warn(const char *file)
663 return warn_if_unremovable("rmdir", file, rmdir(file));
666 int remove_or_warn(unsigned int mode, const char *file)
668 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
671 static int access_error_is_ok(int err, unsigned flag)
673 return (is_missing_file_error(err) ||
674 ((flag & ACCESS_EACCES_OK) && err == EACCES));
677 int access_or_warn(const char *path, int mode, unsigned flag)
679 int ret = access(path, mode);
680 if (ret && !access_error_is_ok(errno, flag))
681 warn_on_inaccessible(path);
682 return ret;
685 int access_or_die(const char *path, int mode, unsigned flag)
687 int ret = access(path, mode);
688 if (ret && !access_error_is_ok(errno, flag))
689 die_errno(_("unable to access '%s'"), path);
690 return ret;
693 char *xgetcwd(void)
695 struct strbuf sb = STRBUF_INIT;
696 if (strbuf_getcwd(&sb))
697 die_errno(_("unable to get current working directory"));
698 return strbuf_detach(&sb, NULL);
701 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
703 va_list ap;
704 int len;
706 va_start(ap, fmt);
707 len = vsnprintf(dst, max, fmt, ap);
708 va_end(ap);
710 if (len < 0)
711 BUG("your snprintf is broken");
712 if (len >= max)
713 BUG("attempt to snprintf into too-small buffer");
714 return len;
717 void write_file_buf(const char *path, const char *buf, size_t len)
719 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
720 if (write_in_full(fd, buf, len) < 0)
721 die_errno(_("could not write to '%s'"), path);
722 if (close(fd))
723 die_errno(_("could not close '%s'"), path);
726 void write_file(const char *path, const char *fmt, ...)
728 va_list params;
729 struct strbuf sb = STRBUF_INIT;
731 va_start(params, fmt);
732 strbuf_vaddf(&sb, fmt, params);
733 va_end(params);
735 strbuf_complete_line(&sb);
737 write_file_buf(path, sb.buf, sb.len);
738 strbuf_release(&sb);
741 void sleep_millisec(int millisec)
743 poll(NULL, 0, millisec);
746 int xgethostname(char *buf, size_t len)
749 * If the full hostname doesn't fit in buf, POSIX does not
750 * specify whether the buffer will be null-terminated, so to
751 * be safe, do it ourselves.
753 int ret = gethostname(buf, len);
754 if (!ret)
755 buf[len - 1] = 0;
756 return ret;
759 int is_empty_or_missing_file(const char *filename)
761 struct stat st;
763 if (stat(filename, &st) < 0) {
764 if (errno == ENOENT)
765 return 1;
766 die_errno(_("could not stat %s"), filename);
769 return !st.st_size;
772 int open_nofollow(const char *path, int flags)
774 #ifdef O_NOFOLLOW
775 return open(path, flags | O_NOFOLLOW);
776 #else
777 struct stat st;
778 if (lstat(path, &st) < 0)
779 return -1;
780 if (S_ISLNK(st.st_mode)) {
781 errno = ELOOP;
782 return -1;
784 return open(path, flags);
785 #endif
788 int csprng_bytes(void *buf, size_t len)
790 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
791 /* This function never returns an error. */
792 arc4random_buf(buf, len);
793 return 0;
794 #elif defined(HAVE_GETRANDOM)
795 ssize_t res;
796 char *p = buf;
797 while (len) {
798 res = getrandom(p, len, 0);
799 if (res < 0)
800 return -1;
801 len -= res;
802 p += res;
804 return 0;
805 #elif defined(HAVE_GETENTROPY)
806 int res;
807 char *p = buf;
808 while (len) {
809 /* getentropy has a maximum size of 256 bytes. */
810 size_t chunk = len < 256 ? len : 256;
811 res = getentropy(p, chunk);
812 if (res < 0)
813 return -1;
814 len -= chunk;
815 p += chunk;
817 return 0;
818 #elif defined(HAVE_RTLGENRANDOM)
819 if (!RtlGenRandom(buf, len))
820 return -1;
821 return 0;
822 #elif defined(HAVE_OPENSSL_CSPRNG)
823 int res = RAND_bytes(buf, len);
824 if (res == 1)
825 return 0;
826 if (res == -1)
827 errno = ENOTSUP;
828 else
829 errno = EIO;
830 return -1;
831 #else
832 ssize_t res;
833 char *p = buf;
834 int fd, err;
835 fd = open("/dev/urandom", O_RDONLY);
836 if (fd < 0)
837 return -1;
838 while (len) {
839 res = xread(fd, p, len);
840 if (res < 0) {
841 err = errno;
842 close(fd);
843 errno = err;
844 return -1;
846 len -= res;
847 p += res;
849 close(fd);
850 return 0;
851 #endif