2 * Various trivial helper wrappers around standard functions
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
14 #undef SystemFunction036
17 static int memory_limit_check(size_t size
, int gentle
)
19 static size_t limit
= 0;
21 limit
= git_env_ulong("GIT_ALLOC_LIMIT", 0);
27 error("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
28 (uintmax_t)size
, (uintmax_t)limit
);
31 die("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
32 (uintmax_t)size
, (uintmax_t)limit
);
37 char *xstrdup(const char *str
)
39 char *ret
= strdup(str
);
41 die("Out of memory, strdup failed");
45 static void *do_xmalloc(size_t size
, int gentle
)
49 if (memory_limit_check(size
, gentle
))
56 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
59 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
65 memset(ret
, 0xA5, size
);
70 void *xmalloc(size_t size
)
72 return do_xmalloc(size
, 0);
75 static void *do_xmallocz(size_t size
, int gentle
)
78 if (unsigned_add_overflows(size
, 1)) {
80 error("Data too large to fit into virtual memory space.");
83 die("Data too large to fit into virtual memory space.");
85 ret
= do_xmalloc(size
+ 1, gentle
);
87 ((char*)ret
)[size
] = 0;
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,
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
);
123 return s
[len
] == '\0' ? 0 : 1;
126 void *xrealloc(void *ptr
, size_t size
)
135 memory_limit_check(size
, 0);
136 ret
= realloc(ptr
, size
);
138 die("Out of memory, realloc failed");
142 void *xcalloc(size_t nmemb
, size_t size
)
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
))
154 die("Out of memory, calloc failed");
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
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
182 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
187 * xopen() is the same as open(), but it die()s if the open() fails.
189 int xopen(const char *path
, int oflag
, ...)
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.
202 mode
= va_arg(ap
, int);
206 int fd
= open(path
, oflag
, mode
);
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
);
219 die_errno(_("could not open '%s' for reading"), path
);
223 static int handle_nonblock(int fd
, short poll_events
, int err
)
227 if (err
!= EAGAIN
&& err
!= EWOULDBLOCK
)
231 pfd
.events
= poll_events
;
234 * no need to check for errors, here;
235 * a subsequent read/write will detect unrecoverable errors
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
)
249 if (len
> MAX_IO_SIZE
)
252 nr
= read(fd
, buf
, len
);
256 if (handle_nonblock(fd
, POLLIN
, errno
))
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
)
271 if (len
> MAX_IO_SIZE
)
274 nr
= write(fd
, buf
, len
);
278 if (handle_nonblock(fd
, POLLOUT
, errno
))
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
)
294 if (len
> MAX_IO_SIZE
)
297 nr
= pread(fd
, buf
, len
, offset
);
298 if ((nr
< 0) && (errno
== EAGAIN
|| errno
== EINTR
))
304 ssize_t
read_in_full(int fd
, void *buf
, size_t count
)
310 ssize_t loaded
= xread(fd
, p
, count
);
323 ssize_t
write_in_full(int fd
, const void *buf
, size_t count
)
329 ssize_t written
= xwrite(fd
, p
, count
);
344 ssize_t
pread_in_full(int fd
, void *buf
, size_t count
, off_t offset
)
350 ssize_t loaded
= xpread(fd
, p
, count
, offset
);
368 die_errno("dup failed");
373 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
375 FILE *xfopen(const char *path
, const char *mode
)
378 FILE *fp
= fopen(path
, mode
);
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
);
389 die_errno(_("could not open '%s' for reading"), path
);
393 FILE *xfdopen(int fd
, const char *mode
)
395 FILE *stream
= fdopen(fd
, mode
);
397 die_errno("Out of memory? fdopen failed");
401 FILE *fopen_for_writing(const char *path
)
403 FILE *ret
= fopen(path
, "w");
405 if (!ret
&& errno
== EPERM
) {
407 ret
= fopen(path
, "w");
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
);
429 FILE *fopen_or_warn(const char *path
, const char *mode
)
431 FILE *fp
= fopen(path
, mode
);
436 warn_on_fopen_errors(path
);
440 int xmkstemp(char *filename_template
)
443 char origtemplate
[PATH_MAX
];
444 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
446 fd
= mkstemp(filename_template
);
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
);
456 die_errno("Unable to create temporary file '%s'",
457 nonrelative_template
);
462 /* Adapted from libiberty's mkstemp.c. */
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"
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
;
480 len
= strlen(pattern
);
482 if (len
< num_x
+ suffix_len
) {
487 if (strncmp(&pattern
[len
- num_x
- suffix_len
], x_pattern
, num_x
)) {
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
) {
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
];
509 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, mode
);
513 * Fatal error (EPERM, ENOSPC etc).
514 * It doesn't make sense to loop.
519 /* We return the null string if we can't find a unique file name. */
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
)
533 char origtemplate
[PATH_MAX
];
534 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
536 fd
= git_mkstemp_mode(filename_template
, mode
);
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
);
546 die_errno("Unable to create temporary file '%s'",
547 nonrelative_template
);
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
)
562 } while (err
< 0 && errno
== EINTR
);
566 int git_fsync(int fd
, enum fsync_action action
)
569 case FSYNC_WRITEOUT_ONLY
:
570 count_fsync_writeout_only
+= 1;
574 * On macOS, fsync just causes filesystem cache writeback but
575 * does not flush hardware caches.
577 return fsync_loop(fd
);
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
);
594 #ifdef fsync_no_flush
595 return fsync_no_flush(fd
);
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.
610 return fcntl(fd
, F_FULLFSYNC
);
612 return fsync_loop(fd
);
615 BUG("unexpected git_fsync(%d) call", action
);
619 static void log_trace_fsync_if(const char *key
, intmax_t 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
)
634 if (!rc
|| errno
== ENOENT
)
637 warning_errno("unable to %s '%s'", op
, file
);
642 int unlink_or_msg(const char *file
, struct strbuf
*err
)
644 int rc
= unlink(file
);
648 if (!rc
|| errno
== ENOENT
)
651 strbuf_addf(err
, "unable to unlink '%s': %s",
652 file
, strerror(errno
));
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
);
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
);
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
, ...)
707 len
= vsnprintf(dst
, max
, fmt
, ap
);
711 BUG("your snprintf is broken");
713 BUG("attempt to snprintf into too-small buffer");
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
);
723 die_errno(_("could not close '%s'"), path
);
726 void write_file(const char *path
, const char *fmt
, ...)
729 struct strbuf sb
= STRBUF_INIT
;
731 va_start(params
, fmt
);
732 strbuf_vaddf(&sb
, fmt
, params
);
735 strbuf_complete_line(&sb
);
737 write_file_buf(path
, sb
.buf
, sb
.len
);
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
);
759 int is_empty_or_missing_file(const char *filename
)
763 if (stat(filename
, &st
) < 0) {
766 die_errno(_("could not stat %s"), filename
);
772 int open_nofollow(const char *path
, int flags
)
775 return open(path
, flags
| O_NOFOLLOW
);
778 if (lstat(path
, &st
) < 0)
780 if (S_ISLNK(st
.st_mode
)) {
784 return open(path
, flags
);
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
);
794 #elif defined(HAVE_GETRANDOM)
798 res
= getrandom(p
, len
, 0);
805 #elif defined(HAVE_GETENTROPY)
809 /* getentropy has a maximum size of 256 bytes. */
810 size_t chunk
= len
< 256 ? len
: 256;
811 res
= getentropy(p
, chunk
);
818 #elif defined(HAVE_RTLGENRANDOM)
819 if (!RtlGenRandom(buf
, len
))
822 #elif defined(HAVE_OPENSSL_CSPRNG)
823 int res
= RAND_bytes(buf
, len
);
835 fd
= open("/dev/urandom", O_RDONLY
);
839 res
= xread(fd
, p
, len
);