2 * Various trivial helper wrappers around standard functions
4 #include "git-compat-util.h"
9 #include "repository.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
21 #undef SystemFunction036
24 static int memory_limit_check(size_t size
, int gentle
)
26 static size_t limit
= 0;
28 limit
= git_env_ulong("GIT_ALLOC_LIMIT", 0);
34 error("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
35 (uintmax_t)size
, (uintmax_t)limit
);
38 die("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
39 (uintmax_t)size
, (uintmax_t)limit
);
44 char *xstrdup(const char *str
)
46 char *ret
= strdup(str
);
48 die("Out of memory, strdup failed");
52 static void *do_xmalloc(size_t size
, int gentle
)
56 if (memory_limit_check(size
, gentle
))
63 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
66 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
72 memset(ret
, 0xA5, size
);
77 void *xmalloc(size_t size
)
79 return do_xmalloc(size
, 0);
82 static void *do_xmallocz(size_t size
, int gentle
)
85 if (unsigned_add_overflows(size
, 1)) {
87 error("Data too large to fit into virtual memory space.");
90 die("Data too large to fit into virtual memory space.");
92 ret
= do_xmalloc(size
+ 1, gentle
);
94 ((char*)ret
)[size
] = 0;
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,
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
);
130 return s
[len
] == '\0' ? 0 : 1;
133 void *xrealloc(void *ptr
, size_t size
)
142 memory_limit_check(size
, 0);
143 ret
= realloc(ptr
, size
);
145 die("Out of memory, realloc failed");
149 void *xcalloc(size_t nmemb
, size_t size
)
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
))
161 die("Out of memory, calloc failed");
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
, ...)
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.
187 mode
= va_arg(ap
, int);
191 int fd
= open(path
, oflag
, mode
);
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
);
204 die_errno(_("could not open '%s' for reading"), path
);
208 static int handle_nonblock(int fd
, short poll_events
, int err
)
212 if (err
!= EAGAIN
&& err
!= EWOULDBLOCK
)
216 pfd
.events
= poll_events
;
219 * no need to check for errors, here;
220 * a subsequent read/write will detect unrecoverable errors
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
)
234 if (len
> MAX_IO_SIZE
)
237 nr
= read(fd
, buf
, len
);
241 if (handle_nonblock(fd
, POLLIN
, errno
))
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
)
256 if (len
> MAX_IO_SIZE
)
259 nr
= write(fd
, buf
, len
);
263 if (handle_nonblock(fd
, POLLOUT
, errno
))
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
)
279 if (len
> MAX_IO_SIZE
)
282 nr
= pread(fd
, buf
, len
, offset
);
283 if ((nr
< 0) && (errno
== EAGAIN
|| errno
== EINTR
))
289 ssize_t
read_in_full(int fd
, void *buf
, size_t count
)
295 ssize_t loaded
= xread(fd
, p
, count
);
308 ssize_t
write_in_full(int fd
, const void *buf
, size_t count
)
314 ssize_t written
= xwrite(fd
, p
, count
);
329 ssize_t
pread_in_full(int fd
, void *buf
, size_t count
, off_t offset
)
335 ssize_t loaded
= xpread(fd
, p
, count
, offset
);
353 die_errno("dup failed");
358 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
360 FILE *xfopen(const char *path
, const char *mode
)
363 FILE *fp
= fopen(path
, mode
);
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
);
374 die_errno(_("could not open '%s' for reading"), path
);
378 FILE *xfdopen(int fd
, const char *mode
)
380 FILE *stream
= fdopen(fd
, mode
);
382 die_errno("Out of memory? fdopen failed");
386 FILE *fopen_for_writing(const char *path
)
388 FILE *ret
= fopen(path
, "w");
390 if (!ret
&& errno
== EPERM
) {
392 ret
= fopen(path
, "w");
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
);
414 FILE *fopen_or_warn(const char *path
, const char *mode
)
416 FILE *fp
= fopen(path
, mode
);
421 warn_on_fopen_errors(path
);
425 int xmkstemp(char *filename_template
)
428 char origtemplate
[PATH_MAX
];
429 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
431 fd
= mkstemp(filename_template
);
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
);
441 die_errno("Unable to create temporary file '%s'",
442 nonrelative_template
);
447 /* Adapted from libiberty's mkstemp.c. */
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"
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
;
465 len
= strlen(pattern
);
467 if (len
< num_x
+ suffix_len
) {
472 if (strncmp(&pattern
[len
- num_x
- suffix_len
], x_pattern
, num_x
)) {
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
) {
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
];
494 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, mode
);
498 * Fatal error (EPERM, ENOSPC etc).
499 * It doesn't make sense to loop.
504 /* We return the null string if we can't find a unique file name. */
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
)
518 char origtemplate
[PATH_MAX
];
519 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
521 fd
= git_mkstemp_mode(filename_template
, mode
);
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
);
531 die_errno("Unable to create temporary file '%s'",
532 nonrelative_template
);
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
)
547 } while (err
< 0 && errno
== EINTR
);
551 int git_fsync(int fd
, enum fsync_action action
)
554 case FSYNC_WRITEOUT_ONLY
:
555 count_fsync_writeout_only
+= 1;
559 * On macOS, fsync just causes filesystem cache writeback but
560 * does not flush hardware caches.
562 return fsync_loop(fd
);
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
);
579 #ifdef fsync_no_flush
580 return fsync_no_flush(fd
);
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.
595 return fcntl(fd
, F_FULLFSYNC
);
597 return fsync_loop(fd
);
600 BUG("unexpected git_fsync(%d) call", action
);
604 static void log_trace_fsync_if(const char *key
, intmax_t 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
)
619 if (!rc
|| errno
== ENOENT
)
622 warning_errno("unable to %s '%s'", op
, file
);
627 int unlink_or_msg(const char *file
, struct strbuf
*err
)
629 int rc
= unlink(file
);
633 if (!rc
|| errno
== ENOENT
)
636 strbuf_addf(err
, "unable to unlink '%s': %s",
637 file
, strerror(errno
));
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
);
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
);
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
, ...)
692 len
= vsnprintf(dst
, max
, fmt
, ap
);
696 BUG("your snprintf is broken");
698 BUG("attempt to snprintf into too-small buffer");
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
);
708 die_errno(_("could not close '%s'"), path
);
711 void write_file(const char *path
, const char *fmt
, ...)
714 struct strbuf sb
= STRBUF_INIT
;
716 va_start(params
, fmt
);
717 strbuf_vaddf(&sb
, fmt
, params
);
720 strbuf_complete_line(&sb
);
722 write_file_buf(path
, sb
.buf
, sb
.len
);
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
);
744 int is_empty_or_missing_file(const char *filename
)
748 if (stat(filename
, &st
) < 0) {
751 die_errno(_("could not stat %s"), filename
);
757 int open_nofollow(const char *path
, int flags
)
760 return open(path
, flags
| O_NOFOLLOW
);
763 if (lstat(path
, &st
) < 0)
765 if (S_ISLNK(st
.st_mode
)) {
769 return open(path
, flags
);
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
);
779 #elif defined(HAVE_GETRANDOM)
783 res
= getrandom(p
, len
, 0);
790 #elif defined(HAVE_GETENTROPY)
794 /* getentropy has a maximum size of 256 bytes. */
795 size_t chunk
= len
< 256 ? len
: 256;
796 res
= getentropy(p
, chunk
);
803 #elif defined(HAVE_RTLGENRANDOM)
804 if (!RtlGenRandom(buf
, len
))
807 #elif defined(HAVE_OPENSSL_CSPRNG)
808 int res
= RAND_bytes(buf
, len
);
820 fd
= open("/dev/urandom", O_RDONLY
);
824 res
= xread(fd
, p
, len
);