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 * xopen() is the same as open(), but it die()s if the open() fails.
167 int xopen(const char *path
, int oflag
, ...)
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.
180 mode
= va_arg(ap
, int);
184 int fd
= open(path
, oflag
, mode
);
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
);
197 die_errno(_("could not open '%s' for reading"), path
);
201 static int handle_nonblock(int fd
, short poll_events
, int err
)
205 if (err
!= EAGAIN
&& err
!= EWOULDBLOCK
)
209 pfd
.events
= poll_events
;
212 * no need to check for errors, here;
213 * a subsequent read/write will detect unrecoverable errors
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
)
227 if (len
> MAX_IO_SIZE
)
230 nr
= read(fd
, buf
, len
);
234 if (handle_nonblock(fd
, POLLIN
, errno
))
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
)
249 if (len
> MAX_IO_SIZE
)
252 nr
= write(fd
, buf
, len
);
256 if (handle_nonblock(fd
, POLLOUT
, errno
))
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
)
272 if (len
> MAX_IO_SIZE
)
275 nr
= pread(fd
, buf
, len
, offset
);
276 if ((nr
< 0) && (errno
== EAGAIN
|| errno
== EINTR
))
282 ssize_t
read_in_full(int fd
, void *buf
, size_t count
)
288 ssize_t loaded
= xread(fd
, p
, count
);
301 ssize_t
write_in_full(int fd
, const void *buf
, size_t count
)
307 ssize_t written
= xwrite(fd
, p
, count
);
322 ssize_t
pread_in_full(int fd
, void *buf
, size_t count
, off_t offset
)
328 ssize_t loaded
= xpread(fd
, p
, count
, offset
);
346 die_errno("dup failed");
351 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
353 FILE *xfopen(const char *path
, const char *mode
)
356 FILE *fp
= fopen(path
, mode
);
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
);
367 die_errno(_("could not open '%s' for reading"), path
);
371 FILE *xfdopen(int fd
, const char *mode
)
373 FILE *stream
= fdopen(fd
, mode
);
375 die_errno("Out of memory? fdopen failed");
379 FILE *fopen_for_writing(const char *path
)
381 FILE *ret
= fopen(path
, "w");
383 if (!ret
&& errno
== EPERM
) {
385 ret
= fopen(path
, "w");
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
);
407 FILE *fopen_or_warn(const char *path
, const char *mode
)
409 FILE *fp
= fopen(path
, mode
);
414 warn_on_fopen_errors(path
);
418 int xmkstemp(char *filename_template
)
421 char origtemplate
[PATH_MAX
];
422 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
424 fd
= mkstemp(filename_template
);
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
);
434 die_errno("Unable to create temporary file '%s'",
435 nonrelative_template
);
440 /* Adapted from libiberty's mkstemp.c. */
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"
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
;
458 len
= strlen(pattern
);
460 if (len
< num_x
+ suffix_len
) {
465 if (strncmp(&pattern
[len
- num_x
- suffix_len
], x_pattern
, num_x
)) {
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
) {
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
];
487 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, mode
);
491 * Fatal error (EPERM, ENOSPC etc).
492 * It doesn't make sense to loop.
497 /* We return the null string if we can't find a unique file name. */
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
)
511 char origtemplate
[PATH_MAX
];
512 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
514 fd
= git_mkstemp_mode(filename_template
, mode
);
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
);
524 die_errno("Unable to create temporary file '%s'",
525 nonrelative_template
);
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
)
540 } while (err
< 0 && errno
== EINTR
);
544 int git_fsync(int fd
, enum fsync_action action
)
547 case FSYNC_WRITEOUT_ONLY
:
548 count_fsync_writeout_only
+= 1;
552 * On macOS, fsync just causes filesystem cache writeback but
553 * does not flush hardware caches.
555 return fsync_loop(fd
);
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
);
572 #ifdef fsync_no_flush
573 return fsync_no_flush(fd
);
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.
588 return fcntl(fd
, F_FULLFSYNC
);
590 return fsync_loop(fd
);
593 BUG("unexpected git_fsync(%d) call", action
);
597 static void log_trace_fsync_if(const char *key
, intmax_t 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
)
612 if (!rc
|| errno
== ENOENT
)
615 warning_errno("unable to %s '%s'", op
, file
);
620 int unlink_or_msg(const char *file
, struct strbuf
*err
)
622 int rc
= unlink(file
);
626 if (!rc
|| errno
== ENOENT
)
629 strbuf_addf(err
, "unable to unlink '%s': %s",
630 file
, strerror(errno
));
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
);
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
);
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
, ...)
685 len
= vsnprintf(dst
, max
, fmt
, ap
);
689 BUG("your snprintf is broken");
691 BUG("attempt to snprintf into too-small buffer");
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
);
701 die_errno(_("could not close '%s'"), path
);
704 void write_file(const char *path
, const char *fmt
, ...)
707 struct strbuf sb
= STRBUF_INIT
;
709 va_start(params
, fmt
);
710 strbuf_vaddf(&sb
, fmt
, params
);
713 strbuf_complete_line(&sb
);
715 write_file_buf(path
, sb
.buf
, sb
.len
);
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
);
737 int is_empty_or_missing_file(const char *filename
)
741 if (stat(filename
, &st
) < 0) {
744 die_errno(_("could not stat %s"), filename
);
750 int open_nofollow(const char *path
, int flags
)
753 return open(path
, flags
| O_NOFOLLOW
);
756 if (lstat(path
, &st
) < 0)
758 if (S_ISLNK(st
.st_mode
)) {
762 return open(path
, flags
);
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
);
772 #elif defined(HAVE_GETRANDOM)
776 res
= getrandom(p
, len
, 0);
783 #elif defined(HAVE_GETENTROPY)
787 /* getentropy has a maximum size of 256 bytes. */
788 size_t chunk
= len
< 256 ? len
: 256;
789 res
= getentropy(p
, chunk
);
796 #elif defined(HAVE_RTLGENRANDOM)
797 if (!RtlGenRandom(buf
, len
))
800 #elif defined(HAVE_OPENSSL_CSPRNG)
801 int res
= RAND_bytes(buf
, len
);
813 fd
= open("/dev/urandom", O_RDONLY
);
817 res
= xread(fd
, p
, len
);