2 * Various trivial helper wrappers around standard functions
7 #ifdef HAVE_RTLGENRANDOM
8 /* This is required to get access to RtlGenRandom. */
9 #define SystemFunction036 NTAPI SystemFunction036
11 #undef SystemFunction036
14 static int memory_limit_check(size_t size
, int gentle
)
16 static size_t limit
= 0;
18 limit
= git_env_ulong("GIT_ALLOC_LIMIT", 0);
24 error("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
25 (uintmax_t)size
, (uintmax_t)limit
);
28 die("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
29 (uintmax_t)size
, (uintmax_t)limit
);
34 char *xstrdup(const char *str
)
36 char *ret
= strdup(str
);
38 die("Out of memory, strdup failed");
42 static void *do_xmalloc(size_t size
, int gentle
)
46 if (memory_limit_check(size
, gentle
))
53 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
56 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
62 memset(ret
, 0xA5, size
);
67 void *xmalloc(size_t size
)
69 return do_xmalloc(size
, 0);
72 static void *do_xmallocz(size_t size
, int gentle
)
75 if (unsigned_add_overflows(size
, 1)) {
77 error("Data too large to fit into virtual memory space.");
80 die("Data too large to fit into virtual memory space.");
82 ret
= do_xmalloc(size
+ 1, gentle
);
84 ((char*)ret
)[size
] = 0;
88 void *xmallocz(size_t size
)
90 return do_xmallocz(size
, 0);
93 void *xmallocz_gently(size_t size
)
95 return do_xmallocz(size
, 1);
99 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
100 * "data" to the allocated memory, zero terminates the allocated memory,
101 * and returns a pointer to the allocated memory. If the allocation fails,
104 void *xmemdupz(const void *data
, size_t len
)
106 return memcpy(xmallocz(len
), data
, len
);
109 char *xstrndup(const char *str
, size_t len
)
111 char *p
= memchr(str
, '\0', len
);
112 return xmemdupz(str
, p
? p
- str
: len
);
115 int xstrncmpz(const char *s
, const char *t
, size_t len
)
117 int res
= strncmp(s
, t
, len
);
120 return s
[len
] == '\0' ? 0 : 1;
123 void *xrealloc(void *ptr
, size_t size
)
132 memory_limit_check(size
, 0);
133 ret
= realloc(ptr
, size
);
135 die("Out of memory, realloc failed");
139 void *xcalloc(size_t nmemb
, size_t size
)
143 if (unsigned_mult_overflows(nmemb
, size
))
144 die("data too large to fit into virtual memory space");
146 memory_limit_check(size
* nmemb
, 0);
147 ret
= calloc(nmemb
, size
);
148 if (!ret
&& (!nmemb
|| !size
))
151 die("Out of memory, calloc failed");
155 void xsetenv(const char *name
, const char *value
, int overwrite
)
157 if (setenv(name
, value
, overwrite
))
158 die_errno(_("could not setenv '%s'"), name
? name
: "(null)");
162 * Limit size of IO chunks, because huge chunks only cause pain. OS X
163 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
164 * the absence of bugs, large chunks can result in bad latencies when
165 * you decide to kill the process.
167 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
168 * that is smaller than that, clip it to SSIZE_MAX, as a call to
169 * read(2) or write(2) larger than that is allowed to fail. As the last
170 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
171 * to override this, if the definition of SSIZE_MAX given by the platform
175 # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
176 # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
177 # define MAX_IO_SIZE SSIZE_MAX
179 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
184 * xopen() is the same as open(), but it die()s if the open() fails.
186 int xopen(const char *path
, int oflag
, ...)
192 * va_arg() will have undefined behavior if the specified type is not
193 * compatible with the argument type. Since integers are promoted to
194 * ints, we fetch the next argument as an int, and then cast it to a
195 * mode_t to avoid undefined behavior.
199 mode
= va_arg(ap
, int);
203 int fd
= open(path
, oflag
, mode
);
209 if ((oflag
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
))
210 die_errno(_("unable to create '%s'"), path
);
211 else if ((oflag
& O_RDWR
) == O_RDWR
)
212 die_errno(_("could not open '%s' for reading and writing"), path
);
213 else if ((oflag
& O_WRONLY
) == O_WRONLY
)
214 die_errno(_("could not open '%s' for writing"), path
);
216 die_errno(_("could not open '%s' for reading"), path
);
220 static int handle_nonblock(int fd
, short poll_events
, int err
)
224 if (err
!= EAGAIN
&& err
!= EWOULDBLOCK
)
228 pfd
.events
= poll_events
;
231 * no need to check for errors, here;
232 * a subsequent read/write will detect unrecoverable errors
239 * xread() is the same a read(), but it automatically restarts read()
240 * operations with a recoverable error (EAGAIN and EINTR). xread()
241 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
243 ssize_t
xread(int fd
, void *buf
, size_t len
)
246 if (len
> MAX_IO_SIZE
)
249 nr
= read(fd
, buf
, len
);
253 if (handle_nonblock(fd
, POLLIN
, errno
))
261 * xwrite() is the same a write(), but it automatically restarts write()
262 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
263 * GUARANTEE that "len" bytes is written even if the operation is successful.
265 ssize_t
xwrite(int fd
, const void *buf
, size_t len
)
268 if (len
> MAX_IO_SIZE
)
271 nr
= write(fd
, buf
, len
);
275 if (handle_nonblock(fd
, POLLOUT
, errno
))
284 * xpread() is the same as pread(), but it automatically restarts pread()
285 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
286 * NOT GUARANTEE that "len" bytes is read even if the data is available.
288 ssize_t
xpread(int fd
, void *buf
, size_t len
, off_t offset
)
291 if (len
> MAX_IO_SIZE
)
294 nr
= pread(fd
, buf
, len
, offset
);
295 if ((nr
< 0) && (errno
== EAGAIN
|| errno
== EINTR
))
301 ssize_t
read_in_full(int fd
, void *buf
, size_t count
)
307 ssize_t loaded
= xread(fd
, p
, count
);
320 ssize_t
write_in_full(int fd
, const void *buf
, size_t count
)
326 ssize_t written
= xwrite(fd
, p
, count
);
341 ssize_t
pread_in_full(int fd
, void *buf
, size_t count
, off_t offset
)
347 ssize_t loaded
= xpread(fd
, p
, count
, offset
);
365 die_errno("dup failed");
370 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
372 FILE *xfopen(const char *path
, const char *mode
)
375 FILE *fp
= fopen(path
, mode
);
381 if (*mode
&& mode
[1] == '+')
382 die_errno(_("could not open '%s' for reading and writing"), path
);
383 else if (*mode
== 'w' || *mode
== 'a')
384 die_errno(_("could not open '%s' for writing"), path
);
386 die_errno(_("could not open '%s' for reading"), path
);
390 FILE *xfdopen(int fd
, const char *mode
)
392 FILE *stream
= fdopen(fd
, mode
);
394 die_errno("Out of memory? fdopen failed");
398 FILE *fopen_for_writing(const char *path
)
400 FILE *ret
= fopen(path
, "w");
402 if (!ret
&& errno
== EPERM
) {
404 ret
= fopen(path
, "w");
411 static void warn_on_inaccessible(const char *path
)
413 warning_errno(_("unable to access '%s'"), path
);
416 int warn_on_fopen_errors(const char *path
)
418 if (errno
!= ENOENT
&& errno
!= ENOTDIR
) {
419 warn_on_inaccessible(path
);
426 FILE *fopen_or_warn(const char *path
, const char *mode
)
428 FILE *fp
= fopen(path
, mode
);
433 warn_on_fopen_errors(path
);
437 int xmkstemp(char *filename_template
)
440 char origtemplate
[PATH_MAX
];
441 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
443 fd
= mkstemp(filename_template
);
445 int saved_errno
= errno
;
446 const char *nonrelative_template
;
448 if (strlen(filename_template
) != strlen(origtemplate
))
449 filename_template
= origtemplate
;
451 nonrelative_template
= absolute_path(filename_template
);
453 die_errno("Unable to create temporary file '%s'",
454 nonrelative_template
);
459 /* Adapted from libiberty's mkstemp.c. */
462 #define TMP_MAX 16384
464 int git_mkstemps_mode(char *pattern
, int suffix_len
, int mode
)
466 static const char letters
[] =
467 "abcdefghijklmnopqrstuvwxyz"
468 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
470 static const int num_letters
= ARRAY_SIZE(letters
) - 1;
471 static const char x_pattern
[] = "XXXXXX";
472 static const int num_x
= ARRAY_SIZE(x_pattern
) - 1;
473 char *filename_template
;
477 len
= strlen(pattern
);
479 if (len
< num_x
+ suffix_len
) {
484 if (strncmp(&pattern
[len
- num_x
- suffix_len
], x_pattern
, num_x
)) {
490 * Replace pattern's XXXXXX characters with randomness.
491 * Try TMP_MAX different filenames.
493 filename_template
= &pattern
[len
- num_x
- suffix_len
];
494 for (count
= 0; count
< TMP_MAX
; ++count
) {
497 if (csprng_bytes(&v
, sizeof(v
)) < 0)
498 return error_errno("unable to get random bytes for temporary file");
500 /* Fill in the random bits. */
501 for (i
= 0; i
< num_x
; i
++) {
502 filename_template
[i
] = letters
[v
% num_letters
];
506 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, mode
);
510 * Fatal error (EPERM, ENOSPC etc).
511 * It doesn't make sense to loop.
516 /* We return the null string if we can't find a unique file name. */
521 int git_mkstemp_mode(char *pattern
, int mode
)
523 /* mkstemp is just mkstemps with no suffix */
524 return git_mkstemps_mode(pattern
, 0, mode
);
527 int xmkstemp_mode(char *filename_template
, int mode
)
530 char origtemplate
[PATH_MAX
];
531 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
533 fd
= git_mkstemp_mode(filename_template
, mode
);
535 int saved_errno
= errno
;
536 const char *nonrelative_template
;
538 if (!filename_template
[0])
539 filename_template
= origtemplate
;
541 nonrelative_template
= absolute_path(filename_template
);
543 die_errno("Unable to create temporary file '%s'",
544 nonrelative_template
);
550 * Some platforms return EINTR from fsync. Since fsync is invoked in some
551 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
553 static int fsync_loop(int fd
)
559 } while (err
< 0 && errno
== EINTR
);
563 int git_fsync(int fd
, enum fsync_action action
)
566 case FSYNC_WRITEOUT_ONLY
:
570 * On macOS, fsync just causes filesystem cache writeback but
571 * does not flush hardware caches.
573 return fsync_loop(fd
);
576 #ifdef HAVE_SYNC_FILE_RANGE
578 * On linux 2.6.17 and above, sync_file_range is the way to
579 * issue a writeback without a hardware flush. An offset of
580 * 0 and size of 0 indicates writeout of the entire file and the
581 * wait flags ensure that all dirty data is written to the disk
582 * (potentially in a disk-side cache) before we continue.
585 return sync_file_range(fd
, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE
|
586 SYNC_FILE_RANGE_WRITE
|
587 SYNC_FILE_RANGE_WAIT_AFTER
);
590 #ifdef fsync_no_flush
591 return fsync_no_flush(fd
);
597 case FSYNC_HARDWARE_FLUSH
:
599 * On macOS, a special fcntl is required to really flush the
600 * caches within the storage controller. As of this writing,
601 * this is a very expensive operation on Apple SSDs.
604 return fcntl(fd
, F_FULLFSYNC
);
606 return fsync_loop(fd
);
609 BUG("unexpected git_fsync(%d) call", action
);
613 static int warn_if_unremovable(const char *op
, const char *file
, int rc
)
616 if (!rc
|| errno
== ENOENT
)
619 warning_errno("unable to %s '%s'", op
, file
);
624 int unlink_or_msg(const char *file
, struct strbuf
*err
)
626 int rc
= unlink(file
);
630 if (!rc
|| errno
== ENOENT
)
633 strbuf_addf(err
, "unable to unlink '%s': %s",
634 file
, strerror(errno
));
638 int unlink_or_warn(const char *file
)
640 return warn_if_unremovable("unlink", file
, unlink(file
));
643 int rmdir_or_warn(const char *file
)
645 return warn_if_unremovable("rmdir", file
, rmdir(file
));
648 int remove_or_warn(unsigned int mode
, const char *file
)
650 return S_ISGITLINK(mode
) ? rmdir_or_warn(file
) : unlink_or_warn(file
);
653 static int access_error_is_ok(int err
, unsigned flag
)
655 return (is_missing_file_error(err
) ||
656 ((flag
& ACCESS_EACCES_OK
) && err
== EACCES
));
659 int access_or_warn(const char *path
, int mode
, unsigned flag
)
661 int ret
= access(path
, mode
);
662 if (ret
&& !access_error_is_ok(errno
, flag
))
663 warn_on_inaccessible(path
);
667 int access_or_die(const char *path
, int mode
, unsigned flag
)
669 int ret
= access(path
, mode
);
670 if (ret
&& !access_error_is_ok(errno
, flag
))
671 die_errno(_("unable to access '%s'"), path
);
677 struct strbuf sb
= STRBUF_INIT
;
678 if (strbuf_getcwd(&sb
))
679 die_errno(_("unable to get current working directory"));
680 return strbuf_detach(&sb
, NULL
);
683 int xsnprintf(char *dst
, size_t max
, const char *fmt
, ...)
689 len
= vsnprintf(dst
, max
, fmt
, ap
);
693 BUG("your snprintf is broken");
695 BUG("attempt to snprintf into too-small buffer");
699 void write_file_buf(const char *path
, const char *buf
, size_t len
)
701 int fd
= xopen(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
702 if (write_in_full(fd
, buf
, len
) < 0)
703 die_errno(_("could not write to '%s'"), path
);
705 die_errno(_("could not close '%s'"), path
);
708 void write_file(const char *path
, const char *fmt
, ...)
711 struct strbuf sb
= STRBUF_INIT
;
713 va_start(params
, fmt
);
714 strbuf_vaddf(&sb
, fmt
, params
);
717 strbuf_complete_line(&sb
);
719 write_file_buf(path
, sb
.buf
, sb
.len
);
723 void sleep_millisec(int millisec
)
725 poll(NULL
, 0, millisec
);
728 int xgethostname(char *buf
, size_t len
)
731 * If the full hostname doesn't fit in buf, POSIX does not
732 * specify whether the buffer will be null-terminated, so to
733 * be safe, do it ourselves.
735 int ret
= gethostname(buf
, len
);
741 int is_empty_or_missing_file(const char *filename
)
745 if (stat(filename
, &st
) < 0) {
748 die_errno(_("could not stat %s"), filename
);
754 int open_nofollow(const char *path
, int flags
)
757 return open(path
, flags
| O_NOFOLLOW
);
760 if (lstat(path
, &st
) < 0)
762 if (S_ISLNK(st
.st_mode
)) {
766 return open(path
, flags
);
770 int csprng_bytes(void *buf
, size_t len
)
772 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
773 /* This function never returns an error. */
774 arc4random_buf(buf
, len
);
776 #elif defined(HAVE_GETRANDOM)
780 res
= getrandom(p
, len
, 0);
787 #elif defined(HAVE_GETENTROPY)
791 /* getentropy has a maximum size of 256 bytes. */
792 size_t chunk
= len
< 256 ? len
: 256;
793 res
= getentropy(p
, chunk
);
800 #elif defined(HAVE_RTLGENRANDOM)
801 if (!RtlGenRandom(buf
, len
))
804 #elif defined(HAVE_OPENSSL_CSPRNG)
805 int res
= RAND_bytes(buf
, len
);
817 fd
= open("/dev/urandom", O_RDONLY
);
821 res
= xread(fd
, p
, len
);