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