wrapper.con commit xread/xwrite: clip MAX_IO_SIZE to SSIZE_MAX (a983e6a)
   1/*
   2 * Various trivial helper wrappers around standard functions
   3 */
   4#include "cache.h"
   5
   6static void do_nothing(size_t size)
   7{
   8}
   9
  10static void (*try_to_free_routine)(size_t size) = do_nothing;
  11
  12static void memory_limit_check(size_t size)
  13{
  14        static int limit = -1;
  15        if (limit == -1) {
  16                const char *env = getenv("GIT_ALLOC_LIMIT");
  17                limit = env ? atoi(env) * 1024 : 0;
  18        }
  19        if (limit && size > limit)
  20                die("attempting to allocate %"PRIuMAX" over limit %d",
  21                    (intmax_t)size, limit);
  22}
  23
  24try_to_free_t set_try_to_free_routine(try_to_free_t routine)
  25{
  26        try_to_free_t old = try_to_free_routine;
  27        if (!routine)
  28                routine = do_nothing;
  29        try_to_free_routine = routine;
  30        return old;
  31}
  32
  33char *xstrdup(const char *str)
  34{
  35        char *ret = strdup(str);
  36        if (!ret) {
  37                try_to_free_routine(strlen(str) + 1);
  38                ret = strdup(str);
  39                if (!ret)
  40                        die("Out of memory, strdup failed");
  41        }
  42        return ret;
  43}
  44
  45void *xmalloc(size_t size)
  46{
  47        void *ret;
  48
  49        memory_limit_check(size);
  50        ret = malloc(size);
  51        if (!ret && !size)
  52                ret = malloc(1);
  53        if (!ret) {
  54                try_to_free_routine(size);
  55                ret = malloc(size);
  56                if (!ret && !size)
  57                        ret = malloc(1);
  58                if (!ret)
  59                        die("Out of memory, malloc failed (tried to allocate %lu bytes)",
  60                            (unsigned long)size);
  61        }
  62#ifdef XMALLOC_POISON
  63        memset(ret, 0xA5, size);
  64#endif
  65        return ret;
  66}
  67
  68void *xmallocz(size_t size)
  69{
  70        void *ret;
  71        if (unsigned_add_overflows(size, 1))
  72                die("Data too large to fit into virtual memory space.");
  73        ret = xmalloc(size + 1);
  74        ((char*)ret)[size] = 0;
  75        return ret;
  76}
  77
  78/*
  79 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
  80 * "data" to the allocated memory, zero terminates the allocated memory,
  81 * and returns a pointer to the allocated memory. If the allocation fails,
  82 * the program dies.
  83 */
  84void *xmemdupz(const void *data, size_t len)
  85{
  86        return memcpy(xmallocz(len), data, len);
  87}
  88
  89char *xstrndup(const char *str, size_t len)
  90{
  91        char *p = memchr(str, '\0', len);
  92        return xmemdupz(str, p ? p - str : len);
  93}
  94
  95void *xrealloc(void *ptr, size_t size)
  96{
  97        void *ret;
  98
  99        memory_limit_check(size);
 100        ret = realloc(ptr, size);
 101        if (!ret && !size)
 102                ret = realloc(ptr, 1);
 103        if (!ret) {
 104                try_to_free_routine(size);
 105                ret = realloc(ptr, size);
 106                if (!ret && !size)
 107                        ret = realloc(ptr, 1);
 108                if (!ret)
 109                        die("Out of memory, realloc failed");
 110        }
 111        return ret;
 112}
 113
 114void *xcalloc(size_t nmemb, size_t size)
 115{
 116        void *ret;
 117
 118        memory_limit_check(size * nmemb);
 119        ret = calloc(nmemb, size);
 120        if (!ret && (!nmemb || !size))
 121                ret = calloc(1, 1);
 122        if (!ret) {
 123                try_to_free_routine(nmemb * size);
 124                ret = calloc(nmemb, size);
 125                if (!ret && (!nmemb || !size))
 126                        ret = calloc(1, 1);
 127                if (!ret)
 128                        die("Out of memory, calloc failed");
 129        }
 130        return ret;
 131}
 132
 133/*
 134 * Limit size of IO chunks, because huge chunks only cause pain.  OS X
 135 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
 136 * the absense of bugs, large chunks can result in bad latencies when
 137 * you decide to kill the process.
 138 *
 139 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
 140 * that is smaller than that, clip it to SSIZE_MAX, as a call to
 141 * read(2) or write(2) larger than that is allowed to fail.  As the last
 142 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
 143 * to override this, if the definition of SSIZE_MAX given by the platform
 144 * is broken.
 145 */
 146#ifndef MAX_IO_SIZE
 147# define MAX_IO_SIZE_DEFAULT (8*1024*1024)
 148# if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
 149#  define MAX_IO_SIZE SSIZE_MAX
 150# else
 151#  define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
 152# endif
 153#endif
 154
 155/*
 156 * xread() is the same a read(), but it automatically restarts read()
 157 * operations with a recoverable error (EAGAIN and EINTR). xread()
 158 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
 159 */
 160ssize_t xread(int fd, void *buf, size_t len)
 161{
 162        ssize_t nr;
 163        if (len > MAX_IO_SIZE)
 164            len = MAX_IO_SIZE;
 165        while (1) {
 166                nr = read(fd, buf, len);
 167                if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
 168                        continue;
 169                return nr;
 170        }
 171}
 172
 173/*
 174 * xwrite() is the same a write(), but it automatically restarts write()
 175 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
 176 * GUARANTEE that "len" bytes is written even if the operation is successful.
 177 */
 178ssize_t xwrite(int fd, const void *buf, size_t len)
 179{
 180        ssize_t nr;
 181        if (len > MAX_IO_SIZE)
 182            len = MAX_IO_SIZE;
 183        while (1) {
 184                nr = write(fd, buf, len);
 185                if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
 186                        continue;
 187                return nr;
 188        }
 189}
 190
 191ssize_t read_in_full(int fd, void *buf, size_t count)
 192{
 193        char *p = buf;
 194        ssize_t total = 0;
 195
 196        while (count > 0) {
 197                ssize_t loaded = xread(fd, p, count);
 198                if (loaded < 0)
 199                        return -1;
 200                if (loaded == 0)
 201                        return total;
 202                count -= loaded;
 203                p += loaded;
 204                total += loaded;
 205        }
 206
 207        return total;
 208}
 209
 210ssize_t write_in_full(int fd, const void *buf, size_t count)
 211{
 212        const char *p = buf;
 213        ssize_t total = 0;
 214
 215        while (count > 0) {
 216                ssize_t written = xwrite(fd, p, count);
 217                if (written < 0)
 218                        return -1;
 219                if (!written) {
 220                        errno = ENOSPC;
 221                        return -1;
 222                }
 223                count -= written;
 224                p += written;
 225                total += written;
 226        }
 227
 228        return total;
 229}
 230
 231int xdup(int fd)
 232{
 233        int ret = dup(fd);
 234        if (ret < 0)
 235                die_errno("dup failed");
 236        return ret;
 237}
 238
 239FILE *xfdopen(int fd, const char *mode)
 240{
 241        FILE *stream = fdopen(fd, mode);
 242        if (stream == NULL)
 243                die_errno("Out of memory? fdopen failed");
 244        return stream;
 245}
 246
 247int xmkstemp(char *template)
 248{
 249        int fd;
 250        char origtemplate[PATH_MAX];
 251        strlcpy(origtemplate, template, sizeof(origtemplate));
 252
 253        fd = mkstemp(template);
 254        if (fd < 0) {
 255                int saved_errno = errno;
 256                const char *nonrelative_template;
 257
 258                if (strlen(template) != strlen(origtemplate))
 259                        template = origtemplate;
 260
 261                nonrelative_template = absolute_path(template);
 262                errno = saved_errno;
 263                die_errno("Unable to create temporary file '%s'",
 264                        nonrelative_template);
 265        }
 266        return fd;
 267}
 268
 269/* git_mkstemp() - create tmp file honoring TMPDIR variable */
 270int git_mkstemp(char *path, size_t len, const char *template)
 271{
 272        const char *tmp;
 273        size_t n;
 274
 275        tmp = getenv("TMPDIR");
 276        if (!tmp)
 277                tmp = "/tmp";
 278        n = snprintf(path, len, "%s/%s", tmp, template);
 279        if (len <= n) {
 280                errno = ENAMETOOLONG;
 281                return -1;
 282        }
 283        return mkstemp(path);
 284}
 285
 286/* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
 287int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
 288{
 289        const char *tmp;
 290        size_t n;
 291
 292        tmp = getenv("TMPDIR");
 293        if (!tmp)
 294                tmp = "/tmp";
 295        n = snprintf(path, len, "%s/%s", tmp, template);
 296        if (len <= n) {
 297                errno = ENAMETOOLONG;
 298                return -1;
 299        }
 300        return mkstemps(path, suffix_len);
 301}
 302
 303/* Adapted from libiberty's mkstemp.c. */
 304
 305#undef TMP_MAX
 306#define TMP_MAX 16384
 307
 308int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
 309{
 310        static const char letters[] =
 311                "abcdefghijklmnopqrstuvwxyz"
 312                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 313                "0123456789";
 314        static const int num_letters = 62;
 315        uint64_t value;
 316        struct timeval tv;
 317        char *template;
 318        size_t len;
 319        int fd, count;
 320
 321        len = strlen(pattern);
 322
 323        if (len < 6 + suffix_len) {
 324                errno = EINVAL;
 325                return -1;
 326        }
 327
 328        if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
 329                errno = EINVAL;
 330                return -1;
 331        }
 332
 333        /*
 334         * Replace pattern's XXXXXX characters with randomness.
 335         * Try TMP_MAX different filenames.
 336         */
 337        gettimeofday(&tv, NULL);
 338        value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
 339        template = &pattern[len - 6 - suffix_len];
 340        for (count = 0; count < TMP_MAX; ++count) {
 341                uint64_t v = value;
 342                /* Fill in the random bits. */
 343                template[0] = letters[v % num_letters]; v /= num_letters;
 344                template[1] = letters[v % num_letters]; v /= num_letters;
 345                template[2] = letters[v % num_letters]; v /= num_letters;
 346                template[3] = letters[v % num_letters]; v /= num_letters;
 347                template[4] = letters[v % num_letters]; v /= num_letters;
 348                template[5] = letters[v % num_letters]; v /= num_letters;
 349
 350                fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
 351                if (fd >= 0)
 352                        return fd;
 353                /*
 354                 * Fatal error (EPERM, ENOSPC etc).
 355                 * It doesn't make sense to loop.
 356                 */
 357                if (errno != EEXIST)
 358                        break;
 359                /*
 360                 * This is a random value.  It is only necessary that
 361                 * the next TMP_MAX values generated by adding 7777 to
 362                 * VALUE are different with (module 2^32).
 363                 */
 364                value += 7777;
 365        }
 366        /* We return the null string if we can't find a unique file name.  */
 367        pattern[0] = '\0';
 368        return -1;
 369}
 370
 371int git_mkstemp_mode(char *pattern, int mode)
 372{
 373        /* mkstemp is just mkstemps with no suffix */
 374        return git_mkstemps_mode(pattern, 0, mode);
 375}
 376
 377int gitmkstemps(char *pattern, int suffix_len)
 378{
 379        return git_mkstemps_mode(pattern, suffix_len, 0600);
 380}
 381
 382int xmkstemp_mode(char *template, int mode)
 383{
 384        int fd;
 385        char origtemplate[PATH_MAX];
 386        strlcpy(origtemplate, template, sizeof(origtemplate));
 387
 388        fd = git_mkstemp_mode(template, mode);
 389        if (fd < 0) {
 390                int saved_errno = errno;
 391                const char *nonrelative_template;
 392
 393                if (!template[0])
 394                        template = origtemplate;
 395
 396                nonrelative_template = absolute_path(template);
 397                errno = saved_errno;
 398                die_errno("Unable to create temporary file '%s'",
 399                        nonrelative_template);
 400        }
 401        return fd;
 402}
 403
 404static int warn_if_unremovable(const char *op, const char *file, int rc)
 405{
 406        if (rc < 0) {
 407                int err = errno;
 408                if (ENOENT != err) {
 409                        warning("unable to %s %s: %s",
 410                                op, file, strerror(errno));
 411                        errno = err;
 412                }
 413        }
 414        return rc;
 415}
 416
 417int unlink_or_warn(const char *file)
 418{
 419        return warn_if_unremovable("unlink", file, unlink(file));
 420}
 421
 422int rmdir_or_warn(const char *file)
 423{
 424        return warn_if_unremovable("rmdir", file, rmdir(file));
 425}
 426
 427int remove_or_warn(unsigned int mode, const char *file)
 428{
 429        return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
 430}
 431
 432void warn_on_inaccessible(const char *path)
 433{
 434        warning(_("unable to access '%s': %s"), path, strerror(errno));
 435}
 436
 437static int access_error_is_ok(int err, unsigned flag)
 438{
 439        return err == ENOENT || err == ENOTDIR ||
 440                ((flag & ACCESS_EACCES_OK) && err == EACCES);
 441}
 442
 443int access_or_warn(const char *path, int mode, unsigned flag)
 444{
 445        int ret = access(path, mode);
 446        if (ret && !access_error_is_ok(errno, flag))
 447                warn_on_inaccessible(path);
 448        return ret;
 449}
 450
 451int access_or_die(const char *path, int mode, unsigned flag)
 452{
 453        int ret = access(path, mode);
 454        if (ret && !access_error_is_ok(errno, flag))
 455                die_errno(_("unable to access '%s'"), path);
 456        return ret;
 457}
 458
 459struct passwd *xgetpwuid_self(void)
 460{
 461        struct passwd *pw;
 462
 463        errno = 0;
 464        pw = getpwuid(getuid());
 465        if (!pw)
 466                die(_("unable to look up current user in the passwd file: %s"),
 467                    errno ? strerror(errno) : _("no such user"));
 468        return pw;
 469}