2 * Various trivial helper wrappers around standard functions
4 #include "git-compat-util.h"
8 #include "repository.h"
12 #ifdef HAVE_RTLGENRANDOM
13 /* This is required to get access to RtlGenRandom. */
14 #define SystemFunction036 NTAPI SystemFunction036
16 #undef SystemFunction036
19 static int memory_limit_check(size_t size
, int gentle
)
21 static size_t limit
= 0;
23 limit
= git_env_ulong("GIT_ALLOC_LIMIT", 0);
29 error("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
30 (uintmax_t)size
, (uintmax_t)limit
);
33 die("attempting to allocate %"PRIuMAX
" over limit %"PRIuMAX
,
34 (uintmax_t)size
, (uintmax_t)limit
);
39 char *xstrdup(const char *str
)
41 char *ret
= strdup(str
);
43 die("Out of memory, strdup failed");
47 static void *do_xmalloc(size_t size
, int gentle
)
51 if (memory_limit_check(size
, gentle
))
58 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
61 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
67 memset(ret
, 0xA5, size
);
72 void *xmalloc(size_t size
)
74 return do_xmalloc(size
, 0);
77 static void *do_xmallocz(size_t size
, int gentle
)
80 if (unsigned_add_overflows(size
, 1)) {
82 error("Data too large to fit into virtual memory space.");
85 die("Data too large to fit into virtual memory space.");
87 ret
= do_xmalloc(size
+ 1, gentle
);
89 ((char*)ret
)[size
] = 0;
93 void *xmallocz(size_t size
)
95 return do_xmallocz(size
, 0);
98 void *xmallocz_gently(size_t size
)
100 return do_xmallocz(size
, 1);
104 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
105 * "data" to the allocated memory, zero terminates the allocated memory,
106 * and returns a pointer to the allocated memory. If the allocation fails,
109 void *xmemdupz(const void *data
, size_t len
)
111 return memcpy(xmallocz(len
), data
, len
);
114 char *xstrndup(const char *str
, size_t len
)
116 char *p
= memchr(str
, '\0', len
);
117 return xmemdupz(str
, p
? p
- str
: len
);
120 int xstrncmpz(const char *s
, const char *t
, size_t len
)
122 int res
= strncmp(s
, t
, len
);
125 return s
[len
] == '\0' ? 0 : 1;
128 void *xrealloc(void *ptr
, size_t size
)
137 memory_limit_check(size
, 0);
138 ret
= realloc(ptr
, size
);
140 die("Out of memory, realloc failed");
144 void *xcalloc(size_t nmemb
, size_t size
)
148 if (unsigned_mult_overflows(nmemb
, size
))
149 die("data too large to fit into virtual memory space");
151 memory_limit_check(size
* nmemb
, 0);
152 ret
= calloc(nmemb
, size
);
153 if (!ret
&& (!nmemb
|| !size
))
156 die("Out of memory, calloc failed");
160 void xsetenv(const char *name
, const char *value
, int overwrite
)
162 if (setenv(name
, value
, overwrite
))
163 die_errno(_("could not setenv '%s'"), name
? name
: "(null)");
167 * xopen() is the same as open(), but it die()s if the open() fails.
169 int xopen(const char *path
, int oflag
, ...)
175 * va_arg() will have undefined behavior if the specified type is not
176 * compatible with the argument type. Since integers are promoted to
177 * ints, we fetch the next argument as an int, and then cast it to a
178 * mode_t to avoid undefined behavior.
182 mode
= va_arg(ap
, int);
186 int fd
= open(path
, oflag
, mode
);
192 if ((oflag
& (O_CREAT
| O_EXCL
)) == (O_CREAT
| O_EXCL
))
193 die_errno(_("unable to create '%s'"), path
);
194 else if ((oflag
& O_RDWR
) == O_RDWR
)
195 die_errno(_("could not open '%s' for reading and writing"), path
);
196 else if ((oflag
& O_WRONLY
) == O_WRONLY
)
197 die_errno(_("could not open '%s' for writing"), path
);
199 die_errno(_("could not open '%s' for reading"), path
);
203 static int handle_nonblock(int fd
, short poll_events
, int err
)
207 if (err
!= EAGAIN
&& err
!= EWOULDBLOCK
)
211 pfd
.events
= poll_events
;
214 * no need to check for errors, here;
215 * a subsequent read/write will detect unrecoverable errors
222 * xread() is the same a read(), but it automatically restarts read()
223 * operations with a recoverable error (EAGAIN and EINTR). xread()
224 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
226 ssize_t
xread(int fd
, void *buf
, size_t len
)
229 if (len
> MAX_IO_SIZE
)
232 nr
= read(fd
, buf
, len
);
236 if (handle_nonblock(fd
, POLLIN
, errno
))
244 * xwrite() is the same a write(), but it automatically restarts write()
245 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
246 * GUARANTEE that "len" bytes is written even if the operation is successful.
248 ssize_t
xwrite(int fd
, const void *buf
, size_t len
)
251 if (len
> MAX_IO_SIZE
)
254 nr
= write(fd
, buf
, len
);
258 if (handle_nonblock(fd
, POLLOUT
, errno
))
267 * xpread() is the same as pread(), but it automatically restarts pread()
268 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
269 * NOT GUARANTEE that "len" bytes is read even if the data is available.
271 ssize_t
xpread(int fd
, void *buf
, size_t len
, off_t offset
)
274 if (len
> MAX_IO_SIZE
)
277 nr
= pread(fd
, buf
, len
, offset
);
278 if ((nr
< 0) && (errno
== EAGAIN
|| errno
== EINTR
))
284 ssize_t
read_in_full(int fd
, void *buf
, size_t count
)
290 ssize_t loaded
= xread(fd
, p
, count
);
303 ssize_t
write_in_full(int fd
, const void *buf
, size_t count
)
309 ssize_t written
= xwrite(fd
, p
, count
);
324 ssize_t
pread_in_full(int fd
, void *buf
, size_t count
, off_t offset
)
330 ssize_t loaded
= xpread(fd
, p
, count
, offset
);
348 die_errno("dup failed");
353 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
355 FILE *xfopen(const char *path
, const char *mode
)
358 FILE *fp
= fopen(path
, mode
);
364 if (*mode
&& mode
[1] == '+')
365 die_errno(_("could not open '%s' for reading and writing"), path
);
366 else if (*mode
== 'w' || *mode
== 'a')
367 die_errno(_("could not open '%s' for writing"), path
);
369 die_errno(_("could not open '%s' for reading"), path
);
373 FILE *xfdopen(int fd
, const char *mode
)
375 FILE *stream
= fdopen(fd
, mode
);
377 die_errno("Out of memory? fdopen failed");
381 FILE *fopen_for_writing(const char *path
)
383 FILE *ret
= fopen(path
, "w");
385 if (!ret
&& errno
== EPERM
) {
387 ret
= fopen(path
, "w");
394 static void warn_on_inaccessible(const char *path
)
396 warning_errno(_("unable to access '%s'"), path
);
399 int warn_on_fopen_errors(const char *path
)
401 if (errno
!= ENOENT
&& errno
!= ENOTDIR
) {
402 warn_on_inaccessible(path
);
409 FILE *fopen_or_warn(const char *path
, const char *mode
)
411 FILE *fp
= fopen(path
, mode
);
416 warn_on_fopen_errors(path
);
420 int xmkstemp(char *filename_template
)
423 char origtemplate
[PATH_MAX
];
424 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
426 fd
= mkstemp(filename_template
);
428 int saved_errno
= errno
;
429 const char *nonrelative_template
;
431 if (strlen(filename_template
) != strlen(origtemplate
))
432 filename_template
= origtemplate
;
434 nonrelative_template
= absolute_path(filename_template
);
436 die_errno("Unable to create temporary file '%s'",
437 nonrelative_template
);
442 /* Adapted from libiberty's mkstemp.c. */
445 #define TMP_MAX 16384
447 int git_mkstemps_mode(char *pattern
, int suffix_len
, int mode
)
449 static const char letters
[] =
450 "abcdefghijklmnopqrstuvwxyz"
451 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
453 static const int num_letters
= ARRAY_SIZE(letters
) - 1;
454 static const char x_pattern
[] = "XXXXXX";
455 static const int num_x
= ARRAY_SIZE(x_pattern
) - 1;
456 char *filename_template
;
460 len
= strlen(pattern
);
462 if (len
< num_x
+ suffix_len
) {
467 if (strncmp(&pattern
[len
- num_x
- suffix_len
], x_pattern
, num_x
)) {
473 * Replace pattern's XXXXXX characters with randomness.
474 * Try TMP_MAX different filenames.
476 filename_template
= &pattern
[len
- num_x
- suffix_len
];
477 for (count
= 0; count
< TMP_MAX
; ++count
) {
480 if (csprng_bytes(&v
, sizeof(v
)) < 0)
481 return error_errno("unable to get random bytes for temporary file");
483 /* Fill in the random bits. */
484 for (i
= 0; i
< num_x
; i
++) {
485 filename_template
[i
] = letters
[v
% num_letters
];
489 fd
= open(pattern
, O_CREAT
| O_EXCL
| O_RDWR
, mode
);
493 * Fatal error (EPERM, ENOSPC etc).
494 * It doesn't make sense to loop.
499 /* We return the null string if we can't find a unique file name. */
504 int git_mkstemp_mode(char *pattern
, int mode
)
506 /* mkstemp is just mkstemps with no suffix */
507 return git_mkstemps_mode(pattern
, 0, mode
);
510 int xmkstemp_mode(char *filename_template
, int mode
)
513 char origtemplate
[PATH_MAX
];
514 strlcpy(origtemplate
, filename_template
, sizeof(origtemplate
));
516 fd
= git_mkstemp_mode(filename_template
, mode
);
518 int saved_errno
= errno
;
519 const char *nonrelative_template
;
521 if (!filename_template
[0])
522 filename_template
= origtemplate
;
524 nonrelative_template
= absolute_path(filename_template
);
526 die_errno("Unable to create temporary file '%s'",
527 nonrelative_template
);
533 * Some platforms return EINTR from fsync. Since fsync is invoked in some
534 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
536 static int fsync_loop(int fd
)
542 } while (err
< 0 && errno
== EINTR
);
546 int git_fsync(int fd
, enum fsync_action action
)
549 case FSYNC_WRITEOUT_ONLY
:
550 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_WRITEOUT_ONLY
, 1);
554 * On macOS, fsync just causes filesystem cache writeback but
555 * does not flush hardware caches.
557 return fsync_loop(fd
);
560 #ifdef HAVE_SYNC_FILE_RANGE
562 * On linux 2.6.17 and above, sync_file_range is the way to
563 * issue a writeback without a hardware flush. An offset of
564 * 0 and size of 0 indicates writeout of the entire file and the
565 * wait flags ensure that all dirty data is written to the disk
566 * (potentially in a disk-side cache) before we continue.
569 return sync_file_range(fd
, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE
|
570 SYNC_FILE_RANGE_WRITE
|
571 SYNC_FILE_RANGE_WAIT_AFTER
);
574 #ifdef fsync_no_flush
575 return fsync_no_flush(fd
);
581 case FSYNC_HARDWARE_FLUSH
:
582 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_HARDWARE_FLUSH
, 1);
585 * On macOS, a special fcntl is required to really flush the
586 * caches within the storage controller. As of this writing,
587 * this is a very expensive operation on Apple SSDs.
590 return fcntl(fd
, F_FULLFSYNC
);
592 return fsync_loop(fd
);
595 BUG("unexpected git_fsync(%d) call", action
);
599 static int warn_if_unremovable(const char *op
, const char *file
, int rc
)
602 if (!rc
|| errno
== ENOENT
)
605 warning_errno("unable to %s '%s'", op
, file
);
610 int unlink_or_msg(const char *file
, struct strbuf
*err
)
612 int rc
= unlink(file
);
616 if (!rc
|| errno
== ENOENT
)
619 strbuf_addf(err
, "unable to unlink '%s': %s",
620 file
, strerror(errno
));
624 int unlink_or_warn(const char *file
)
626 return warn_if_unremovable("unlink", file
, unlink(file
));
629 int rmdir_or_warn(const char *file
)
631 return warn_if_unremovable("rmdir", file
, rmdir(file
));
634 static int access_error_is_ok(int err
, unsigned flag
)
636 return (is_missing_file_error(err
) ||
637 ((flag
& ACCESS_EACCES_OK
) && err
== EACCES
));
640 int access_or_warn(const char *path
, int mode
, unsigned flag
)
642 int ret
= access(path
, mode
);
643 if (ret
&& !access_error_is_ok(errno
, flag
))
644 warn_on_inaccessible(path
);
648 int access_or_die(const char *path
, int mode
, unsigned flag
)
650 int ret
= access(path
, mode
);
651 if (ret
&& !access_error_is_ok(errno
, flag
))
652 die_errno(_("unable to access '%s'"), path
);
658 struct strbuf sb
= STRBUF_INIT
;
659 if (strbuf_getcwd(&sb
))
660 die_errno(_("unable to get current working directory"));
661 return strbuf_detach(&sb
, NULL
);
664 int xsnprintf(char *dst
, size_t max
, const char *fmt
, ...)
670 len
= vsnprintf(dst
, max
, fmt
, ap
);
674 BUG("your snprintf is broken");
676 BUG("attempt to snprintf into too-small buffer");
680 void write_file_buf(const char *path
, const char *buf
, size_t len
)
682 int fd
= xopen(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0666);
683 if (write_in_full(fd
, buf
, len
) < 0)
684 die_errno(_("could not write to '%s'"), path
);
686 die_errno(_("could not close '%s'"), path
);
689 void write_file(const char *path
, const char *fmt
, ...)
692 struct strbuf sb
= STRBUF_INIT
;
694 va_start(params
, fmt
);
695 strbuf_vaddf(&sb
, fmt
, params
);
698 strbuf_complete_line(&sb
);
700 write_file_buf(path
, sb
.buf
, sb
.len
);
704 void sleep_millisec(int millisec
)
706 poll(NULL
, 0, millisec
);
709 int xgethostname(char *buf
, size_t len
)
712 * If the full hostname doesn't fit in buf, POSIX does not
713 * specify whether the buffer will be null-terminated, so to
714 * be safe, do it ourselves.
716 int ret
= gethostname(buf
, len
);
722 int is_empty_or_missing_file(const char *filename
)
726 if (stat(filename
, &st
) < 0) {
729 die_errno(_("could not stat %s"), filename
);
735 int open_nofollow(const char *path
, int flags
)
738 return open(path
, flags
| O_NOFOLLOW
);
741 if (lstat(path
, &st
) < 0)
743 if (S_ISLNK(st
.st_mode
)) {
747 return open(path
, flags
);
751 int csprng_bytes(void *buf
, size_t len
)
753 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
754 /* This function never returns an error. */
755 arc4random_buf(buf
, len
);
757 #elif defined(HAVE_GETRANDOM)
761 res
= getrandom(p
, len
, 0);
768 #elif defined(HAVE_GETENTROPY)
772 /* getentropy has a maximum size of 256 bytes. */
773 size_t chunk
= len
< 256 ? len
: 256;
774 res
= getentropy(p
, chunk
);
781 #elif defined(HAVE_RTLGENRANDOM)
782 if (!RtlGenRandom(buf
, len
))
785 #elif defined(HAVE_OPENSSL_CSPRNG)
786 int res
= RAND_bytes(buf
, len
);
798 fd
= open("/dev/urandom", O_RDONLY
);
802 res
= xread(fd
, p
, len
);
817 uint32_t git_rand(void)
821 if (csprng_bytes(&result
, sizeof(result
)) < 0)
822 die(_("unable to get random bytes"));