2 * Various trivial helper wrappers around standard functions
7 static void do_nothing(size_t size)
11 static void (*try_to_free_routine)(size_t size) = do_nothing;
13 static int memory_limit_check(size_t size, int gentle)
15 static size_t limit = 0;
17 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
23 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
24 (uintmax_t)size, (uintmax_t)limit);
27 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
28 (uintmax_t)size, (uintmax_t)limit);
33 try_to_free_t set_try_to_free_routine(try_to_free_t routine)
35 try_to_free_t old = try_to_free_routine;
38 try_to_free_routine = routine;
42 char *xstrdup(const char *str)
44 char *ret = strdup(str);
46 try_to_free_routine(strlen(str) + 1);
49 die("Out of memory, strdup failed");
54 static void *do_xmalloc(size_t size, int gentle)
58 if (memory_limit_check(size, gentle))
64 try_to_free_routine(size);
70 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
73 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
80 memset(ret, 0xA5, size);
85 void *xmalloc(size_t size)
87 return do_xmalloc(size, 0);
90 static void *do_xmallocz(size_t size, int gentle)
93 if (unsigned_add_overflows(size, 1)) {
95 error("Data too large to fit into virtual memory space.");
98 die("Data too large to fit into virtual memory space.");
100 ret = do_xmalloc(size + 1, gentle);
102 ((char*)ret)[size] = 0;
106 void *xmallocz(size_t size)
108 return do_xmallocz(size, 0);
111 void *xmallocz_gently(size_t size)
113 return do_xmallocz(size, 1);
117 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
118 * "data" to the allocated memory, zero terminates the allocated memory,
119 * and returns a pointer to the allocated memory. If the allocation fails,
122 void *xmemdupz(const void *data, size_t len)
124 return memcpy(xmallocz(len), data, len);
127 char *xstrndup(const char *str, size_t len)
129 char *p = memchr(str, '\0', len);
130 return xmemdupz(str, p ? p - str : len);
133 void *xrealloc(void *ptr, size_t size)
137 memory_limit_check(size, 0);
138 ret = realloc(ptr, size);
140 ret = realloc(ptr, 1);
142 try_to_free_routine(size);
143 ret = realloc(ptr, size);
145 ret = realloc(ptr, 1);
147 die("Out of memory, realloc failed");
152 void *xcalloc(size_t nmemb, size_t size)
156 if (unsigned_mult_overflows(nmemb, size))
157 die("data too large to fit into virtual memory space");
159 memory_limit_check(size * nmemb, 0);
160 ret = calloc(nmemb, size);
161 if (!ret && (!nmemb || !size))
164 try_to_free_routine(nmemb * size);
165 ret = calloc(nmemb, size);
166 if (!ret && (!nmemb || !size))
169 die("Out of memory, calloc failed");
175 * Limit size of IO chunks, because huge chunks only cause pain. OS X
176 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
177 * the absence of bugs, large chunks can result in bad latencies when
178 * you decide to kill the process.
180 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
181 * that is smaller than that, clip it to SSIZE_MAX, as a call to
182 * read(2) or write(2) larger than that is allowed to fail. As the last
183 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
184 * to override this, if the definition of SSIZE_MAX given by the platform
188 # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
189 # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
190 # define MAX_IO_SIZE SSIZE_MAX
192 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
197 * xopen() is the same as open(), but it die()s if the open() fails.
199 int xopen(const char *path, int oflag, ...)
205 * va_arg() will have undefined behavior if the specified type is not
206 * compatible with the argument type. Since integers are promoted to
207 * ints, we fetch the next argument as an int, and then cast it to a
208 * mode_t to avoid undefined behavior.
212 mode = va_arg(ap, int);
216 int fd = open(path, oflag, mode);
222 if ((oflag & O_RDWR) == O_RDWR)
223 die_errno(_("could not open '%s' for reading and writing"), path);
224 else if ((oflag & O_WRONLY) == O_WRONLY)
225 die_errno(_("could not open '%s' for writing"), path);
227 die_errno(_("could not open '%s' for reading"), path);
231 static int handle_nonblock(int fd, short poll_events, int err)
235 if (err != EAGAIN && err != EWOULDBLOCK)
239 pfd.events = poll_events;
242 * no need to check for errors, here;
243 * a subsequent read/write will detect unrecoverable errors
250 * xread() is the same a read(), but it automatically restarts read()
251 * operations with a recoverable error (EAGAIN and EINTR). xread()
252 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
254 ssize_t xread(int fd, void *buf, size_t len)
257 if (len > MAX_IO_SIZE)
260 nr = read(fd, buf, len);
264 if (handle_nonblock(fd, POLLIN, errno))
272 * xwrite() is the same a write(), but it automatically restarts write()
273 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
274 * GUARANTEE that "len" bytes is written even if the operation is successful.
276 ssize_t xwrite(int fd, const void *buf, size_t len)
279 if (len > MAX_IO_SIZE)
282 nr = write(fd, buf, len);
286 if (handle_nonblock(fd, POLLOUT, errno))
295 * xpread() is the same as pread(), but it automatically restarts pread()
296 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
297 * NOT GUARANTEE that "len" bytes is read even if the data is available.
299 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
302 if (len > MAX_IO_SIZE)
305 nr = pread(fd, buf, len, offset);
306 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
312 ssize_t read_in_full(int fd, void *buf, size_t count)
318 ssize_t loaded = xread(fd, p, count);
331 ssize_t write_in_full(int fd, const void *buf, size_t count)
337 ssize_t written = xwrite(fd, p, count);
352 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
358 ssize_t loaded = xpread(fd, p, count, offset);
376 die_errno("dup failed");
381 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
383 FILE *xfopen(const char *path, const char *mode)
386 FILE *fp = fopen(path, mode);
392 if (*mode && mode[1] == '+')
393 die_errno(_("could not open '%s' for reading and writing"), path);
394 else if (*mode == 'w' || *mode == 'a')
395 die_errno(_("could not open '%s' for writing"), path);
397 die_errno(_("could not open '%s' for reading"), path);
401 FILE *xfdopen(int fd, const char *mode)
403 FILE *stream = fdopen(fd, mode);
405 die_errno("Out of memory? fdopen failed");
409 FILE *fopen_for_writing(const char *path)
411 FILE *ret = fopen(path, "w");
413 if (!ret && errno == EPERM) {
415 ret = fopen(path, "w");
422 int xmkstemp(char *template)
425 char origtemplate[PATH_MAX];
426 strlcpy(origtemplate, template, sizeof(origtemplate));
428 fd = mkstemp(template);
430 int saved_errno = errno;
431 const char *nonrelative_template;
433 if (strlen(template) != strlen(origtemplate))
434 template = origtemplate;
436 nonrelative_template = absolute_path(template);
438 die_errno("Unable to create temporary file '%s'",
439 nonrelative_template);
444 /* Adapted from libiberty's mkstemp.c. */
447 #define TMP_MAX 16384
449 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
451 static const char letters[] =
452 "abcdefghijklmnopqrstuvwxyz"
453 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
455 static const int num_letters = 62;
462 len = strlen(pattern);
464 if (len < 6 + suffix_len) {
469 if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
475 * Replace pattern's XXXXXX characters with randomness.
476 * Try TMP_MAX different filenames.
478 gettimeofday(&tv, NULL);
479 value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
480 template = &pattern[len - 6 - suffix_len];
481 for (count = 0; count < TMP_MAX; ++count) {
483 /* Fill in the random bits. */
484 template[0] = letters[v % num_letters]; v /= num_letters;
485 template[1] = letters[v % num_letters]; v /= num_letters;
486 template[2] = letters[v % num_letters]; v /= num_letters;
487 template[3] = letters[v % num_letters]; v /= num_letters;
488 template[4] = letters[v % num_letters]; v /= num_letters;
489 template[5] = letters[v % num_letters]; v /= num_letters;
491 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
495 * Fatal error (EPERM, ENOSPC etc).
496 * It doesn't make sense to loop.
501 * This is a random value. It is only necessary that
502 * the next TMP_MAX values generated by adding 7777 to
503 * VALUE are different with (module 2^32).
507 /* We return the null string if we can't find a unique file name. */
512 int git_mkstemp_mode(char *pattern, int mode)
514 /* mkstemp is just mkstemps with no suffix */
515 return git_mkstemps_mode(pattern, 0, mode);
518 int xmkstemp_mode(char *template, int mode)
521 char origtemplate[PATH_MAX];
522 strlcpy(origtemplate, template, sizeof(origtemplate));
524 fd = git_mkstemp_mode(template, mode);
526 int saved_errno = errno;
527 const char *nonrelative_template;
530 template = origtemplate;
532 nonrelative_template = absolute_path(template);
534 die_errno("Unable to create temporary file '%s'",
535 nonrelative_template);
540 static int warn_if_unremovable(const char *op, const char *file, int rc)
543 if (!rc || errno == ENOENT)
546 warning_errno("unable to %s %s", op, file);
551 int unlink_or_msg(const char *file, struct strbuf *err)
553 int rc = unlink(file);
557 if (!rc || errno == ENOENT)
560 strbuf_addf(err, "unable to unlink %s: %s",
561 file, strerror(errno));
565 int unlink_or_warn(const char *file)
567 return warn_if_unremovable("unlink", file, unlink(file));
570 int rmdir_or_warn(const char *file)
572 return warn_if_unremovable("rmdir", file, rmdir(file));
575 int remove_or_warn(unsigned int mode, const char *file)
577 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
580 void warn_on_inaccessible(const char *path)
582 warning_errno(_("unable to access '%s'"), path);
585 static int access_error_is_ok(int err, unsigned flag)
587 return err == ENOENT || err == ENOTDIR ||
588 ((flag & ACCESS_EACCES_OK) && err == EACCES);
591 int access_or_warn(const char *path, int mode, unsigned flag)
593 int ret = access(path, mode);
594 if (ret && !access_error_is_ok(errno, flag))
595 warn_on_inaccessible(path);
599 int access_or_die(const char *path, int mode, unsigned flag)
601 int ret = access(path, mode);
602 if (ret && !access_error_is_ok(errno, flag))
603 die_errno(_("unable to access '%s'"), path);
609 struct strbuf sb = STRBUF_INIT;
610 if (strbuf_getcwd(&sb))
611 die_errno(_("unable to get current working directory"));
612 return strbuf_detach(&sb, NULL);
615 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
621 len = vsnprintf(dst, max, fmt, ap);
625 die("BUG: your snprintf is broken");
627 die("BUG: attempt to snprintf into too-small buffer");
631 void write_file_buf(const char *path, const char *buf, size_t len)
633 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
634 if (write_in_full(fd, buf, len) != len)
635 die_errno(_("could not write to %s"), path);
637 die_errno(_("could not close %s"), path);
640 void write_file(const char *path, const char *fmt, ...)
643 struct strbuf sb = STRBUF_INIT;
645 va_start(params, fmt);
646 strbuf_vaddf(&sb, fmt, params);
649 strbuf_complete_line(&sb);
651 write_file_buf(path, sb.buf, sb.len);
655 void sleep_millisec(int millisec)
657 poll(NULL, 0, millisec);
660 int xgethostname(char *buf, size_t len)
663 * If the full hostname doesn't fit in buf, POSIX does not
664 * specify whether the buffer will be null-terminated, so to
665 * be safe, do it ourselves.
667 int ret = gethostname(buf, len);