Makefile + hash.h: remove PPC_SHA1 implementation
[git/debian.git] / wrapper.c
blob299d6489a6b0a148b57fa6c8a11f9245e1dfd0dd
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 * xopen() is the same as open(), but it die()s if the open() fails.
167 int xopen(const char *path, int oflag, ...)
169 mode_t mode = 0;
170 va_list ap;
173 * va_arg() will have undefined behavior if the specified type is not
174 * compatible with the argument type. Since integers are promoted to
175 * ints, we fetch the next argument as an int, and then cast it to a
176 * mode_t to avoid undefined behavior.
178 va_start(ap, oflag);
179 if (oflag & O_CREAT)
180 mode = va_arg(ap, int);
181 va_end(ap);
183 for (;;) {
184 int fd = open(path, oflag, mode);
185 if (fd >= 0)
186 return fd;
187 if (errno == EINTR)
188 continue;
190 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
191 die_errno(_("unable to create '%s'"), path);
192 else if ((oflag & O_RDWR) == O_RDWR)
193 die_errno(_("could not open '%s' for reading and writing"), path);
194 else if ((oflag & O_WRONLY) == O_WRONLY)
195 die_errno(_("could not open '%s' for writing"), path);
196 else
197 die_errno(_("could not open '%s' for reading"), path);
201 static int handle_nonblock(int fd, short poll_events, int err)
203 struct pollfd pfd;
205 if (err != EAGAIN && err != EWOULDBLOCK)
206 return 0;
208 pfd.fd = fd;
209 pfd.events = poll_events;
212 * no need to check for errors, here;
213 * a subsequent read/write will detect unrecoverable errors
215 poll(&pfd, 1, -1);
216 return 1;
220 * xread() is the same a read(), but it automatically restarts read()
221 * operations with a recoverable error (EAGAIN and EINTR). xread()
222 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
224 ssize_t xread(int fd, void *buf, size_t len)
226 ssize_t nr;
227 if (len > MAX_IO_SIZE)
228 len = MAX_IO_SIZE;
229 while (1) {
230 nr = read(fd, buf, len);
231 if (nr < 0) {
232 if (errno == EINTR)
233 continue;
234 if (handle_nonblock(fd, POLLIN, errno))
235 continue;
237 return nr;
242 * xwrite() is the same a write(), but it automatically restarts write()
243 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
244 * GUARANTEE that "len" bytes is written even if the operation is successful.
246 ssize_t xwrite(int fd, const 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 = write(fd, buf, len);
253 if (nr < 0) {
254 if (errno == EINTR)
255 continue;
256 if (handle_nonblock(fd, POLLOUT, errno))
257 continue;
260 return nr;
265 * xpread() is the same as pread(), but it automatically restarts pread()
266 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
267 * NOT GUARANTEE that "len" bytes is read even if the data is available.
269 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
271 ssize_t nr;
272 if (len > MAX_IO_SIZE)
273 len = MAX_IO_SIZE;
274 while (1) {
275 nr = pread(fd, buf, len, offset);
276 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
277 continue;
278 return nr;
282 ssize_t read_in_full(int fd, void *buf, size_t count)
284 char *p = buf;
285 ssize_t total = 0;
287 while (count > 0) {
288 ssize_t loaded = xread(fd, p, count);
289 if (loaded < 0)
290 return -1;
291 if (loaded == 0)
292 return total;
293 count -= loaded;
294 p += loaded;
295 total += loaded;
298 return total;
301 ssize_t write_in_full(int fd, const void *buf, size_t count)
303 const char *p = buf;
304 ssize_t total = 0;
306 while (count > 0) {
307 ssize_t written = xwrite(fd, p, count);
308 if (written < 0)
309 return -1;
310 if (!written) {
311 errno = ENOSPC;
312 return -1;
314 count -= written;
315 p += written;
316 total += written;
319 return total;
322 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
324 char *p = buf;
325 ssize_t total = 0;
327 while (count > 0) {
328 ssize_t loaded = xpread(fd, p, count, offset);
329 if (loaded < 0)
330 return -1;
331 if (loaded == 0)
332 return total;
333 count -= loaded;
334 p += loaded;
335 total += loaded;
336 offset += loaded;
339 return total;
342 int xdup(int fd)
344 int ret = dup(fd);
345 if (ret < 0)
346 die_errno("dup failed");
347 return ret;
351 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
353 FILE *xfopen(const char *path, const char *mode)
355 for (;;) {
356 FILE *fp = fopen(path, mode);
357 if (fp)
358 return fp;
359 if (errno == EINTR)
360 continue;
362 if (*mode && mode[1] == '+')
363 die_errno(_("could not open '%s' for reading and writing"), path);
364 else if (*mode == 'w' || *mode == 'a')
365 die_errno(_("could not open '%s' for writing"), path);
366 else
367 die_errno(_("could not open '%s' for reading"), path);
371 FILE *xfdopen(int fd, const char *mode)
373 FILE *stream = fdopen(fd, mode);
374 if (!stream)
375 die_errno("Out of memory? fdopen failed");
376 return stream;
379 FILE *fopen_for_writing(const char *path)
381 FILE *ret = fopen(path, "w");
383 if (!ret && errno == EPERM) {
384 if (!unlink(path))
385 ret = fopen(path, "w");
386 else
387 errno = EPERM;
389 return ret;
392 static void warn_on_inaccessible(const char *path)
394 warning_errno(_("unable to access '%s'"), path);
397 int warn_on_fopen_errors(const char *path)
399 if (errno != ENOENT && errno != ENOTDIR) {
400 warn_on_inaccessible(path);
401 return -1;
404 return 0;
407 FILE *fopen_or_warn(const char *path, const char *mode)
409 FILE *fp = fopen(path, mode);
411 if (fp)
412 return fp;
414 warn_on_fopen_errors(path);
415 return NULL;
418 int xmkstemp(char *filename_template)
420 int fd;
421 char origtemplate[PATH_MAX];
422 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
424 fd = mkstemp(filename_template);
425 if (fd < 0) {
426 int saved_errno = errno;
427 const char *nonrelative_template;
429 if (strlen(filename_template) != strlen(origtemplate))
430 filename_template = origtemplate;
432 nonrelative_template = absolute_path(filename_template);
433 errno = saved_errno;
434 die_errno("Unable to create temporary file '%s'",
435 nonrelative_template);
437 return fd;
440 /* Adapted from libiberty's mkstemp.c. */
442 #undef TMP_MAX
443 #define TMP_MAX 16384
445 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
447 static const char letters[] =
448 "abcdefghijklmnopqrstuvwxyz"
449 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
450 "0123456789";
451 static const int num_letters = ARRAY_SIZE(letters) - 1;
452 static const char x_pattern[] = "XXXXXX";
453 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
454 char *filename_template;
455 size_t len;
456 int fd, count;
458 len = strlen(pattern);
460 if (len < num_x + suffix_len) {
461 errno = EINVAL;
462 return -1;
465 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
466 errno = EINVAL;
467 return -1;
471 * Replace pattern's XXXXXX characters with randomness.
472 * Try TMP_MAX different filenames.
474 filename_template = &pattern[len - num_x - suffix_len];
475 for (count = 0; count < TMP_MAX; ++count) {
476 int i;
477 uint64_t v;
478 if (csprng_bytes(&v, sizeof(v)) < 0)
479 return error_errno("unable to get random bytes for temporary file");
481 /* Fill in the random bits. */
482 for (i = 0; i < num_x; i++) {
483 filename_template[i] = letters[v % num_letters];
484 v /= num_letters;
487 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
488 if (fd >= 0)
489 return fd;
491 * Fatal error (EPERM, ENOSPC etc).
492 * It doesn't make sense to loop.
494 if (errno != EEXIST)
495 break;
497 /* We return the null string if we can't find a unique file name. */
498 pattern[0] = '\0';
499 return -1;
502 int git_mkstemp_mode(char *pattern, int mode)
504 /* mkstemp is just mkstemps with no suffix */
505 return git_mkstemps_mode(pattern, 0, mode);
508 int xmkstemp_mode(char *filename_template, int mode)
510 int fd;
511 char origtemplate[PATH_MAX];
512 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
514 fd = git_mkstemp_mode(filename_template, mode);
515 if (fd < 0) {
516 int saved_errno = errno;
517 const char *nonrelative_template;
519 if (!filename_template[0])
520 filename_template = origtemplate;
522 nonrelative_template = absolute_path(filename_template);
523 errno = saved_errno;
524 die_errno("Unable to create temporary file '%s'",
525 nonrelative_template);
527 return fd;
531 * Some platforms return EINTR from fsync. Since fsync is invoked in some
532 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
534 static int fsync_loop(int fd)
536 int err;
538 do {
539 err = fsync(fd);
540 } while (err < 0 && errno == EINTR);
541 return err;
544 int git_fsync(int fd, enum fsync_action action)
546 switch (action) {
547 case FSYNC_WRITEOUT_ONLY:
548 count_fsync_writeout_only += 1;
550 #ifdef __APPLE__
552 * On macOS, fsync just causes filesystem cache writeback but
553 * does not flush hardware caches.
555 return fsync_loop(fd);
556 #endif
558 #ifdef HAVE_SYNC_FILE_RANGE
560 * On linux 2.6.17 and above, sync_file_range is the way to
561 * issue a writeback without a hardware flush. An offset of
562 * 0 and size of 0 indicates writeout of the entire file and the
563 * wait flags ensure that all dirty data is written to the disk
564 * (potentially in a disk-side cache) before we continue.
567 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
568 SYNC_FILE_RANGE_WRITE |
569 SYNC_FILE_RANGE_WAIT_AFTER);
570 #endif
572 #ifdef fsync_no_flush
573 return fsync_no_flush(fd);
574 #endif
576 errno = ENOSYS;
577 return -1;
579 case FSYNC_HARDWARE_FLUSH:
580 count_fsync_hardware_flush += 1;
583 * On macOS, a special fcntl is required to really flush the
584 * caches within the storage controller. As of this writing,
585 * this is a very expensive operation on Apple SSDs.
587 #ifdef __APPLE__
588 return fcntl(fd, F_FULLFSYNC);
589 #else
590 return fsync_loop(fd);
591 #endif
592 default:
593 BUG("unexpected git_fsync(%d) call", action);
597 static void log_trace_fsync_if(const char *key, intmax_t value)
599 if (value)
600 trace2_data_intmax("fsync", the_repository, key, value);
603 void trace_git_fsync_stats(void)
605 log_trace_fsync_if("fsync/writeout-only", count_fsync_writeout_only);
606 log_trace_fsync_if("fsync/hardware-flush", count_fsync_hardware_flush);
609 static int warn_if_unremovable(const char *op, const char *file, int rc)
611 int err;
612 if (!rc || errno == ENOENT)
613 return 0;
614 err = errno;
615 warning_errno("unable to %s '%s'", op, file);
616 errno = err;
617 return rc;
620 int unlink_or_msg(const char *file, struct strbuf *err)
622 int rc = unlink(file);
624 assert(err);
626 if (!rc || errno == ENOENT)
627 return 0;
629 strbuf_addf(err, "unable to unlink '%s': %s",
630 file, strerror(errno));
631 return -1;
634 int unlink_or_warn(const char *file)
636 return warn_if_unremovable("unlink", file, unlink(file));
639 int rmdir_or_warn(const char *file)
641 return warn_if_unremovable("rmdir", file, rmdir(file));
644 int remove_or_warn(unsigned int mode, const char *file)
646 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
649 static int access_error_is_ok(int err, unsigned flag)
651 return (is_missing_file_error(err) ||
652 ((flag & ACCESS_EACCES_OK) && err == EACCES));
655 int access_or_warn(const char *path, int mode, unsigned flag)
657 int ret = access(path, mode);
658 if (ret && !access_error_is_ok(errno, flag))
659 warn_on_inaccessible(path);
660 return ret;
663 int access_or_die(const char *path, int mode, unsigned flag)
665 int ret = access(path, mode);
666 if (ret && !access_error_is_ok(errno, flag))
667 die_errno(_("unable to access '%s'"), path);
668 return ret;
671 char *xgetcwd(void)
673 struct strbuf sb = STRBUF_INIT;
674 if (strbuf_getcwd(&sb))
675 die_errno(_("unable to get current working directory"));
676 return strbuf_detach(&sb, NULL);
679 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
681 va_list ap;
682 int len;
684 va_start(ap, fmt);
685 len = vsnprintf(dst, max, fmt, ap);
686 va_end(ap);
688 if (len < 0)
689 BUG("your snprintf is broken");
690 if (len >= max)
691 BUG("attempt to snprintf into too-small buffer");
692 return len;
695 void write_file_buf(const char *path, const char *buf, size_t len)
697 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
698 if (write_in_full(fd, buf, len) < 0)
699 die_errno(_("could not write to '%s'"), path);
700 if (close(fd))
701 die_errno(_("could not close '%s'"), path);
704 void write_file(const char *path, const char *fmt, ...)
706 va_list params;
707 struct strbuf sb = STRBUF_INIT;
709 va_start(params, fmt);
710 strbuf_vaddf(&sb, fmt, params);
711 va_end(params);
713 strbuf_complete_line(&sb);
715 write_file_buf(path, sb.buf, sb.len);
716 strbuf_release(&sb);
719 void sleep_millisec(int millisec)
721 poll(NULL, 0, millisec);
724 int xgethostname(char *buf, size_t len)
727 * If the full hostname doesn't fit in buf, POSIX does not
728 * specify whether the buffer will be null-terminated, so to
729 * be safe, do it ourselves.
731 int ret = gethostname(buf, len);
732 if (!ret)
733 buf[len - 1] = 0;
734 return ret;
737 int is_empty_or_missing_file(const char *filename)
739 struct stat st;
741 if (stat(filename, &st) < 0) {
742 if (errno == ENOENT)
743 return 1;
744 die_errno(_("could not stat %s"), filename);
747 return !st.st_size;
750 int open_nofollow(const char *path, int flags)
752 #ifdef O_NOFOLLOW
753 return open(path, flags | O_NOFOLLOW);
754 #else
755 struct stat st;
756 if (lstat(path, &st) < 0)
757 return -1;
758 if (S_ISLNK(st.st_mode)) {
759 errno = ELOOP;
760 return -1;
762 return open(path, flags);
763 #endif
766 int csprng_bytes(void *buf, size_t len)
768 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
769 /* This function never returns an error. */
770 arc4random_buf(buf, len);
771 return 0;
772 #elif defined(HAVE_GETRANDOM)
773 ssize_t res;
774 char *p = buf;
775 while (len) {
776 res = getrandom(p, len, 0);
777 if (res < 0)
778 return -1;
779 len -= res;
780 p += res;
782 return 0;
783 #elif defined(HAVE_GETENTROPY)
784 int res;
785 char *p = buf;
786 while (len) {
787 /* getentropy has a maximum size of 256 bytes. */
788 size_t chunk = len < 256 ? len : 256;
789 res = getentropy(p, chunk);
790 if (res < 0)
791 return -1;
792 len -= chunk;
793 p += chunk;
795 return 0;
796 #elif defined(HAVE_RTLGENRANDOM)
797 if (!RtlGenRandom(buf, len))
798 return -1;
799 return 0;
800 #elif defined(HAVE_OPENSSL_CSPRNG)
801 int res = RAND_bytes(buf, len);
802 if (res == 1)
803 return 0;
804 if (res == -1)
805 errno = ENOTSUP;
806 else
807 errno = EIO;
808 return -1;
809 #else
810 ssize_t res;
811 char *p = buf;
812 int fd, err;
813 fd = open("/dev/urandom", O_RDONLY);
814 if (fd < 0)
815 return -1;
816 while (len) {
817 res = xread(fd, p, len);
818 if (res < 0) {
819 err = errno;
820 close(fd);
821 errno = err;
822 return -1;
824 len -= res;
825 p += res;
827 close(fd);
828 return 0;
829 #endif