read-cache.con commit git-format-patch --start-number <n> (fa0f02d)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#include "cache.h"
   7
   8struct cache_entry **active_cache = NULL;
   9static time_t index_file_timestamp;
  10unsigned int active_nr = 0, active_alloc = 0, active_cache_changed = 0;
  11
  12/*
  13 * This only updates the "non-critical" parts of the directory
  14 * cache, ie the parts that aren't tracked by GIT, and only used
  15 * to validate the cache.
  16 */
  17void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
  18{
  19        ce->ce_ctime.sec = htonl(st->st_ctime);
  20        ce->ce_mtime.sec = htonl(st->st_mtime);
  21#ifdef USE_NSEC
  22        ce->ce_ctime.nsec = htonl(st->st_ctim.tv_nsec);
  23        ce->ce_mtime.nsec = htonl(st->st_mtim.tv_nsec);
  24#endif
  25        ce->ce_dev = htonl(st->st_dev);
  26        ce->ce_ino = htonl(st->st_ino);
  27        ce->ce_uid = htonl(st->st_uid);
  28        ce->ce_gid = htonl(st->st_gid);
  29        ce->ce_size = htonl(st->st_size);
  30
  31        if (assume_unchanged)
  32                ce->ce_flags |= htons(CE_VALID);
  33}
  34
  35static int ce_compare_data(struct cache_entry *ce, struct stat *st)
  36{
  37        int match = -1;
  38        int fd = open(ce->name, O_RDONLY);
  39
  40        if (fd >= 0) {
  41                unsigned char sha1[20];
  42                if (!index_fd(sha1, fd, st, 0, NULL))
  43                        match = memcmp(sha1, ce->sha1, 20);
  44                close(fd);
  45        }
  46        return match;
  47}
  48
  49static int ce_compare_link(struct cache_entry *ce, unsigned long expected_size)
  50{
  51        int match = -1;
  52        char *target;
  53        void *buffer;
  54        unsigned long size;
  55        char type[10];
  56        int len;
  57
  58        target = xmalloc(expected_size);
  59        len = readlink(ce->name, target, expected_size);
  60        if (len != expected_size) {
  61                free(target);
  62                return -1;
  63        }
  64        buffer = read_sha1_file(ce->sha1, type, &size);
  65        if (!buffer) {
  66                free(target);
  67                return -1;
  68        }
  69        if (size == expected_size)
  70                match = memcmp(buffer, target, size);
  71        free(buffer);
  72        free(target);
  73        return match;
  74}
  75
  76static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
  77{
  78        switch (st->st_mode & S_IFMT) {
  79        case S_IFREG:
  80                if (ce_compare_data(ce, st))
  81                        return DATA_CHANGED;
  82                break;
  83        case S_IFLNK:
  84                if (ce_compare_link(ce, st->st_size))
  85                        return DATA_CHANGED;
  86                break;
  87        default:
  88                return TYPE_CHANGED;
  89        }
  90        return 0;
  91}
  92
  93static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
  94{
  95        unsigned int changed = 0;
  96
  97        switch (ntohl(ce->ce_mode) & S_IFMT) {
  98        case S_IFREG:
  99                changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
 100                /* We consider only the owner x bit to be relevant for
 101                 * "mode changes"
 102                 */
 103                if (trust_executable_bit &&
 104                    (0100 & (ntohl(ce->ce_mode) ^ st->st_mode)))
 105                        changed |= MODE_CHANGED;
 106                break;
 107        case S_IFLNK:
 108                changed |= !S_ISLNK(st->st_mode) ? TYPE_CHANGED : 0;
 109                break;
 110        default:
 111                die("internal error: ce_mode is %o", ntohl(ce->ce_mode));
 112        }
 113        if (ce->ce_mtime.sec != htonl(st->st_mtime))
 114                changed |= MTIME_CHANGED;
 115        if (ce->ce_ctime.sec != htonl(st->st_ctime))
 116                changed |= CTIME_CHANGED;
 117
 118#ifdef USE_NSEC
 119        /*
 120         * nsec seems unreliable - not all filesystems support it, so
 121         * as long as it is in the inode cache you get right nsec
 122         * but after it gets flushed, you get zero nsec.
 123         */
 124        if (ce->ce_mtime.nsec != htonl(st->st_mtim.tv_nsec))
 125                changed |= MTIME_CHANGED;
 126        if (ce->ce_ctime.nsec != htonl(st->st_ctim.tv_nsec))
 127                changed |= CTIME_CHANGED;
 128#endif  
 129
 130        if (ce->ce_uid != htonl(st->st_uid) ||
 131            ce->ce_gid != htonl(st->st_gid))
 132                changed |= OWNER_CHANGED;
 133        if (ce->ce_ino != htonl(st->st_ino))
 134                changed |= INODE_CHANGED;
 135
 136#ifdef USE_STDEV
 137        /*
 138         * st_dev breaks on network filesystems where different
 139         * clients will have different views of what "device"
 140         * the filesystem is on
 141         */
 142        if (ce->ce_dev != htonl(st->st_dev))
 143                changed |= INODE_CHANGED;
 144#endif
 145
 146        if (ce->ce_size != htonl(st->st_size))
 147                changed |= DATA_CHANGED;
 148
 149        return changed;
 150}
 151
 152int ce_match_stat(struct cache_entry *ce, struct stat *st, int ignore_valid)
 153{
 154        unsigned int changed;
 155
 156        /*
 157         * If it's marked as always valid in the index, it's
 158         * valid whatever the checked-out copy says.
 159         */
 160        if (!ignore_valid && (ce->ce_flags & htons(CE_VALID)))
 161                return 0;
 162
 163        changed = ce_match_stat_basic(ce, st);
 164
 165        /*
 166         * Within 1 second of this sequence:
 167         *      echo xyzzy >file && git-update-index --add file
 168         * running this command:
 169         *      echo frotz >file
 170         * would give a falsely clean cache entry.  The mtime and
 171         * length match the cache, and other stat fields do not change.
 172         *
 173         * We could detect this at update-index time (the cache entry
 174         * being registered/updated records the same time as "now")
 175         * and delay the return from git-update-index, but that would
 176         * effectively mean we can make at most one commit per second,
 177         * which is not acceptable.  Instead, we check cache entries
 178         * whose mtime are the same as the index file timestamp more
 179         * carefully than others.
 180         */
 181        if (!changed &&
 182            index_file_timestamp &&
 183            index_file_timestamp <= ntohl(ce->ce_mtime.sec))
 184                changed |= ce_modified_check_fs(ce, st);
 185
 186        return changed;
 187}
 188
 189int ce_modified(struct cache_entry *ce, struct stat *st, int really)
 190{
 191        int changed, changed_fs;
 192        changed = ce_match_stat(ce, st, really);
 193        if (!changed)
 194                return 0;
 195        /*
 196         * If the mode or type has changed, there's no point in trying
 197         * to refresh the entry - it's not going to match
 198         */
 199        if (changed & (MODE_CHANGED | TYPE_CHANGED))
 200                return changed;
 201
 202        /* Immediately after read-tree or update-index --cacheinfo,
 203         * the length field is zero.  For other cases the ce_size
 204         * should match the SHA1 recorded in the index entry.
 205         */
 206        if ((changed & DATA_CHANGED) && ce->ce_size != htonl(0))
 207                return changed;
 208
 209        changed_fs = ce_modified_check_fs(ce, st);
 210        if (changed_fs)
 211                return changed | changed_fs;
 212        return 0;
 213}
 214
 215int base_name_compare(const char *name1, int len1, int mode1,
 216                      const char *name2, int len2, int mode2)
 217{
 218        unsigned char c1, c2;
 219        int len = len1 < len2 ? len1 : len2;
 220        int cmp;
 221
 222        cmp = memcmp(name1, name2, len);
 223        if (cmp)
 224                return cmp;
 225        c1 = name1[len];
 226        c2 = name2[len];
 227        if (!c1 && S_ISDIR(mode1))
 228                c1 = '/';
 229        if (!c2 && S_ISDIR(mode2))
 230                c2 = '/';
 231        return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
 232}
 233
 234int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
 235{
 236        int len1 = flags1 & CE_NAMEMASK;
 237        int len2 = flags2 & CE_NAMEMASK;
 238        int len = len1 < len2 ? len1 : len2;
 239        int cmp;
 240
 241        cmp = memcmp(name1, name2, len);
 242        if (cmp)
 243                return cmp;
 244        if (len1 < len2)
 245                return -1;
 246        if (len1 > len2)
 247                return 1;
 248
 249        /* Compare stages  */
 250        flags1 &= CE_STAGEMASK;
 251        flags2 &= CE_STAGEMASK;
 252
 253        if (flags1 < flags2)
 254                return -1;
 255        if (flags1 > flags2)
 256                return 1;
 257        return 0;
 258}
 259
 260int cache_name_pos(const char *name, int namelen)
 261{
 262        int first, last;
 263
 264        first = 0;
 265        last = active_nr;
 266        while (last > first) {
 267                int next = (last + first) >> 1;
 268                struct cache_entry *ce = active_cache[next];
 269                int cmp = cache_name_compare(name, namelen, ce->name, ntohs(ce->ce_flags));
 270                if (!cmp)
 271                        return next;
 272                if (cmp < 0) {
 273                        last = next;
 274                        continue;
 275                }
 276                first = next+1;
 277        }
 278        return -first-1;
 279}
 280
 281/* Remove entry, return true if there are more entries to go.. */
 282int remove_cache_entry_at(int pos)
 283{
 284        active_cache_changed = 1;
 285        active_nr--;
 286        if (pos >= active_nr)
 287                return 0;
 288        memmove(active_cache + pos, active_cache + pos + 1, (active_nr - pos) * sizeof(struct cache_entry *));
 289        return 1;
 290}
 291
 292int remove_file_from_cache(const char *path)
 293{
 294        int pos = cache_name_pos(path, strlen(path));
 295        if (pos < 0)
 296                pos = -pos-1;
 297        while (pos < active_nr && !strcmp(active_cache[pos]->name, path))
 298                remove_cache_entry_at(pos);
 299        return 0;
 300}
 301
 302int ce_same_name(struct cache_entry *a, struct cache_entry *b)
 303{
 304        int len = ce_namelen(a);
 305        return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
 306}
 307
 308int ce_path_match(const struct cache_entry *ce, const char **pathspec)
 309{
 310        const char *match, *name;
 311        int len;
 312
 313        if (!pathspec)
 314                return 1;
 315
 316        len = ce_namelen(ce);
 317        name = ce->name;
 318        while ((match = *pathspec++) != NULL) {
 319                int matchlen = strlen(match);
 320                if (matchlen > len)
 321                        continue;
 322                if (memcmp(name, match, matchlen))
 323                        continue;
 324                if (matchlen && name[matchlen-1] == '/')
 325                        return 1;
 326                if (name[matchlen] == '/' || !name[matchlen])
 327                        return 1;
 328                if (!matchlen)
 329                        return 1;
 330        }
 331        return 0;
 332}
 333
 334/*
 335 * We fundamentally don't like some paths: we don't want
 336 * dot or dot-dot anywhere, and for obvious reasons don't
 337 * want to recurse into ".git" either.
 338 *
 339 * Also, we don't want double slashes or slashes at the
 340 * end that can make pathnames ambiguous.
 341 */
 342static int verify_dotfile(const char *rest)
 343{
 344        /*
 345         * The first character was '.', but that
 346         * has already been discarded, we now test
 347         * the rest.
 348         */
 349        switch (*rest) {
 350        /* "." is not allowed */
 351        case '\0': case '/':
 352                return 0;
 353
 354        /*
 355         * ".git" followed by  NUL or slash is bad. This
 356         * shares the path end test with the ".." case.
 357         */
 358        case 'g':
 359                if (rest[1] != 'i')
 360                        break;
 361                if (rest[2] != 't')
 362                        break;
 363                rest += 2;
 364        /* fallthrough */
 365        case '.':
 366                if (rest[1] == '\0' || rest[1] == '/')
 367                        return 0;
 368        }
 369        return 1;
 370}
 371
 372int verify_path(const char *path)
 373{
 374        char c;
 375
 376        goto inside;
 377        for (;;) {
 378                if (!c)
 379                        return 1;
 380                if (c == '/') {
 381inside:
 382                        c = *path++;
 383                        switch (c) {
 384                        default:
 385                                continue;
 386                        case '/': case '\0':
 387                                break;
 388                        case '.':
 389                                if (verify_dotfile(path))
 390                                        continue;
 391                        }
 392                        return 0;
 393                }
 394                c = *path++;
 395        }
 396}
 397
 398/*
 399 * Do we have another file that has the beginning components being a
 400 * proper superset of the name we're trying to add?
 401 */
 402static int has_file_name(const struct cache_entry *ce, int pos, int ok_to_replace)
 403{
 404        int retval = 0;
 405        int len = ce_namelen(ce);
 406        int stage = ce_stage(ce);
 407        const char *name = ce->name;
 408
 409        while (pos < active_nr) {
 410                struct cache_entry *p = active_cache[pos++];
 411
 412                if (len >= ce_namelen(p))
 413                        break;
 414                if (memcmp(name, p->name, len))
 415                        break;
 416                if (ce_stage(p) != stage)
 417                        continue;
 418                if (p->name[len] != '/')
 419                        continue;
 420                retval = -1;
 421                if (!ok_to_replace)
 422                        break;
 423                remove_cache_entry_at(--pos);
 424        }
 425        return retval;
 426}
 427
 428/*
 429 * Do we have another file with a pathname that is a proper
 430 * subset of the name we're trying to add?
 431 */
 432static int has_dir_name(const struct cache_entry *ce, int pos, int ok_to_replace)
 433{
 434        int retval = 0;
 435        int stage = ce_stage(ce);
 436        const char *name = ce->name;
 437        const char *slash = name + ce_namelen(ce);
 438
 439        for (;;) {
 440                int len;
 441
 442                for (;;) {
 443                        if (*--slash == '/')
 444                                break;
 445                        if (slash <= ce->name)
 446                                return retval;
 447                }
 448                len = slash - name;
 449
 450                pos = cache_name_pos(name, ntohs(create_ce_flags(len, stage)));
 451                if (pos >= 0) {
 452                        retval = -1;
 453                        if (ok_to_replace)
 454                                break;
 455                        remove_cache_entry_at(pos);
 456                        continue;
 457                }
 458
 459                /*
 460                 * Trivial optimization: if we find an entry that
 461                 * already matches the sub-directory, then we know
 462                 * we're ok, and we can exit.
 463                 */
 464                pos = -pos-1;
 465                while (pos < active_nr) {
 466                        struct cache_entry *p = active_cache[pos];
 467                        if ((ce_namelen(p) <= len) ||
 468                            (p->name[len] != '/') ||
 469                            memcmp(p->name, name, len))
 470                                break; /* not our subdirectory */
 471                        if (ce_stage(p) == stage)
 472                                /* p is at the same stage as our entry, and
 473                                 * is a subdirectory of what we are looking
 474                                 * at, so we cannot have conflicts at our
 475                                 * level or anything shorter.
 476                                 */
 477                                return retval;
 478                        pos++;
 479                }
 480        }
 481        return retval;
 482}
 483
 484/* We may be in a situation where we already have path/file and path
 485 * is being added, or we already have path and path/file is being
 486 * added.  Either one would result in a nonsense tree that has path
 487 * twice when git-write-tree tries to write it out.  Prevent it.
 488 * 
 489 * If ok-to-replace is specified, we remove the conflicting entries
 490 * from the cache so the caller should recompute the insert position.
 491 * When this happens, we return non-zero.
 492 */
 493static int check_file_directory_conflict(const struct cache_entry *ce, int pos, int ok_to_replace)
 494{
 495        /*
 496         * We check if the path is a sub-path of a subsequent pathname
 497         * first, since removing those will not change the position
 498         * in the array
 499         */
 500        int retval = has_file_name(ce, pos, ok_to_replace);
 501        /*
 502         * Then check if the path might have a clashing sub-directory
 503         * before it.
 504         */
 505        return retval + has_dir_name(ce, pos, ok_to_replace);
 506}
 507
 508int add_cache_entry(struct cache_entry *ce, int option)
 509{
 510        int pos;
 511        int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
 512        int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
 513        int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
 514
 515        pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
 516
 517        /* existing match? Just replace it. */
 518        if (pos >= 0) {
 519                active_cache_changed = 1;
 520                active_cache[pos] = ce;
 521                return 0;
 522        }
 523        pos = -pos-1;
 524
 525        /*
 526         * Inserting a merged entry ("stage 0") into the index
 527         * will always replace all non-merged entries..
 528         */
 529        if (pos < active_nr && ce_stage(ce) == 0) {
 530                while (ce_same_name(active_cache[pos], ce)) {
 531                        ok_to_add = 1;
 532                        if (!remove_cache_entry_at(pos))
 533                                break;
 534                }
 535        }
 536
 537        if (!ok_to_add)
 538                return -1;
 539        if (!verify_path(ce->name))
 540                return -1;
 541
 542        if (!skip_df_check &&
 543            check_file_directory_conflict(ce, pos, ok_to_replace)) {
 544                if (!ok_to_replace)
 545                        return -1;
 546                pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
 547                pos = -pos-1;
 548        }
 549
 550        /* Make sure the array is big enough .. */
 551        if (active_nr == active_alloc) {
 552                active_alloc = alloc_nr(active_alloc);
 553                active_cache = xrealloc(active_cache, active_alloc * sizeof(struct cache_entry *));
 554        }
 555
 556        /* Add it in.. */
 557        active_nr++;
 558        if (active_nr > pos)
 559                memmove(active_cache + pos + 1, active_cache + pos, (active_nr - pos - 1) * sizeof(ce));
 560        active_cache[pos] = ce;
 561        active_cache_changed = 1;
 562        return 0;
 563}
 564
 565/* Three functions to allow overloaded pointer return; see linux/err.h */
 566static inline void *ERR_PTR(long error)
 567{
 568        return (void *) error;
 569}
 570
 571static inline long PTR_ERR(const void *ptr)
 572{
 573        return (long) ptr;
 574}
 575
 576static inline long IS_ERR(const void *ptr)
 577{
 578        return (unsigned long)ptr > (unsigned long)-1000L;
 579}
 580
 581/*
 582 * "refresh" does not calculate a new sha1 file or bring the
 583 * cache up-to-date for mode/content changes. But what it
 584 * _does_ do is to "re-match" the stat information of a file
 585 * with the cache, so that you can refresh the cache for a
 586 * file that hasn't been changed but where the stat entry is
 587 * out of date.
 588 *
 589 * For example, you'd want to do this after doing a "git-read-tree",
 590 * to link up the stat cache details with the proper files.
 591 */
 592static struct cache_entry *refresh_entry(struct cache_entry *ce, int really)
 593{
 594        struct stat st;
 595        struct cache_entry *updated;
 596        int changed, size;
 597
 598        if (lstat(ce->name, &st) < 0)
 599                return ERR_PTR(-errno);
 600
 601        changed = ce_match_stat(ce, &st, really);
 602        if (!changed) {
 603                if (really && assume_unchanged &&
 604                    !(ce->ce_flags & htons(CE_VALID)))
 605                        ; /* mark this one VALID again */
 606                else
 607                        return NULL;
 608        }
 609
 610        if (ce_modified(ce, &st, really))
 611                return ERR_PTR(-EINVAL);
 612
 613        size = ce_size(ce);
 614        updated = xmalloc(size);
 615        memcpy(updated, ce, size);
 616        fill_stat_cache_info(updated, &st);
 617
 618        /* In this case, if really is not set, we should leave
 619         * CE_VALID bit alone.  Otherwise, paths marked with
 620         * --no-assume-unchanged (i.e. things to be edited) will
 621         * reacquire CE_VALID bit automatically, which is not
 622         * really what we want.
 623         */
 624        if (!really && assume_unchanged && !(ce->ce_flags & htons(CE_VALID)))
 625                updated->ce_flags &= ~htons(CE_VALID);
 626
 627        return updated;
 628}
 629
 630int refresh_cache(unsigned int flags)
 631{
 632        int i;
 633        int has_errors = 0;
 634        int really = (flags & REFRESH_REALLY) != 0;
 635        int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
 636        int quiet = (flags & REFRESH_QUIET) != 0;
 637        int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
 638
 639        for (i = 0; i < active_nr; i++) {
 640                struct cache_entry *ce, *new;
 641                ce = active_cache[i];
 642                if (ce_stage(ce)) {
 643                        while ((i < active_nr) &&
 644                               ! strcmp(active_cache[i]->name, ce->name))
 645                                i++;
 646                        i--;
 647                        if (allow_unmerged)
 648                                continue;
 649                        printf("%s: needs merge\n", ce->name);
 650                        has_errors = 1;
 651                        continue;
 652                }
 653
 654                new = refresh_entry(ce, really);
 655                if (!new)
 656                        continue;
 657                if (IS_ERR(new)) {
 658                        if (not_new && PTR_ERR(new) == -ENOENT)
 659                                continue;
 660                        if (really && PTR_ERR(new) == -EINVAL) {
 661                                /* If we are doing --really-refresh that
 662                                 * means the index is not valid anymore.
 663                                 */
 664                                ce->ce_flags &= ~htons(CE_VALID);
 665                                active_cache_changed = 1;
 666                        }
 667                        if (quiet)
 668                                continue;
 669                        printf("%s: needs update\n", ce->name);
 670                        has_errors = 1;
 671                        continue;
 672                }
 673                active_cache_changed = 1;
 674                /* You can NOT just free active_cache[i] here, since it
 675                 * might not be necessarily malloc()ed but can also come
 676                 * from mmap(). */
 677                active_cache[i] = new;
 678        }
 679        return has_errors;
 680}
 681
 682static int verify_hdr(struct cache_header *hdr, unsigned long size)
 683{
 684        SHA_CTX c;
 685        unsigned char sha1[20];
 686
 687        if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
 688                return error("bad signature");
 689        if (hdr->hdr_version != htonl(2))
 690                return error("bad index version");
 691        SHA1_Init(&c);
 692        SHA1_Update(&c, hdr, size - 20);
 693        SHA1_Final(sha1, &c);
 694        if (memcmp(sha1, (void *)hdr + size - 20, 20))
 695                return error("bad index file sha1 signature");
 696        return 0;
 697}
 698
 699int read_cache(void)
 700{
 701        int fd, i;
 702        struct stat st;
 703        unsigned long size, offset;
 704        void *map;
 705        struct cache_header *hdr;
 706
 707        errno = EBUSY;
 708        if (active_cache)
 709                return active_nr;
 710
 711        errno = ENOENT;
 712        index_file_timestamp = 0;
 713        fd = open(get_index_file(), O_RDONLY);
 714        if (fd < 0) {
 715                if (errno == ENOENT)
 716                        return 0;
 717                die("index file open failed (%s)", strerror(errno));
 718        }
 719
 720        size = 0; // avoid gcc warning
 721        map = MAP_FAILED;
 722        if (!fstat(fd, &st)) {
 723                size = st.st_size;
 724                errno = EINVAL;
 725                if (size >= sizeof(struct cache_header) + 20)
 726                        map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
 727        }
 728        close(fd);
 729        if (map == MAP_FAILED)
 730                die("index file mmap failed (%s)", strerror(errno));
 731
 732        hdr = map;
 733        if (verify_hdr(hdr, size) < 0)
 734                goto unmap;
 735
 736        active_nr = ntohl(hdr->hdr_entries);
 737        active_alloc = alloc_nr(active_nr);
 738        active_cache = xcalloc(active_alloc, sizeof(struct cache_entry *));
 739
 740        offset = sizeof(*hdr);
 741        for (i = 0; i < active_nr; i++) {
 742                struct cache_entry *ce = map + offset;
 743                offset = offset + ce_size(ce);
 744                active_cache[i] = ce;
 745        }
 746        index_file_timestamp = st.st_mtime;
 747        return active_nr;
 748
 749unmap:
 750        munmap(map, size);
 751        errno = EINVAL;
 752        die("index file corrupt");
 753}
 754
 755#define WRITE_BUFFER_SIZE 8192
 756static unsigned char write_buffer[WRITE_BUFFER_SIZE];
 757static unsigned long write_buffer_len;
 758
 759static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
 760{
 761        while (len) {
 762                unsigned int buffered = write_buffer_len;
 763                unsigned int partial = WRITE_BUFFER_SIZE - buffered;
 764                if (partial > len)
 765                        partial = len;
 766                memcpy(write_buffer + buffered, data, partial);
 767                buffered += partial;
 768                if (buffered == WRITE_BUFFER_SIZE) {
 769                        SHA1_Update(context, write_buffer, WRITE_BUFFER_SIZE);
 770                        if (write(fd, write_buffer, WRITE_BUFFER_SIZE) != WRITE_BUFFER_SIZE)
 771                                return -1;
 772                        buffered = 0;
 773                }
 774                write_buffer_len = buffered;
 775                len -= partial;
 776                data += partial;
 777        }
 778        return 0;
 779}
 780
 781static int ce_flush(SHA_CTX *context, int fd)
 782{
 783        unsigned int left = write_buffer_len;
 784
 785        if (left) {
 786                write_buffer_len = 0;
 787                SHA1_Update(context, write_buffer, left);
 788        }
 789
 790        /* Flush first if not enough space for SHA1 signature */
 791        if (left + 20 > WRITE_BUFFER_SIZE) {
 792                if (write(fd, write_buffer, left) != left)
 793                        return -1;
 794                left = 0;
 795        }
 796
 797        /* Append the SHA1 signature at the end */
 798        SHA1_Final(write_buffer + left, context);
 799        left += 20;
 800        if (write(fd, write_buffer, left) != left)
 801                return -1;
 802        return 0;
 803}
 804
 805static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
 806{
 807        /*
 808         * The only thing we care about in this function is to smudge the
 809         * falsely clean entry due to touch-update-touch race, so we leave
 810         * everything else as they are.  We are called for entries whose
 811         * ce_mtime match the index file mtime.
 812         */
 813        struct stat st;
 814
 815        if (lstat(ce->name, &st) < 0)
 816                return;
 817        if (ce_match_stat_basic(ce, &st))
 818                return;
 819        if (ce_modified_check_fs(ce, &st)) {
 820                /* This is "racily clean"; smudge it.  Note that this
 821                 * is a tricky code.  At first glance, it may appear
 822                 * that it can break with this sequence:
 823                 *
 824                 * $ echo xyzzy >frotz
 825                 * $ git-update-index --add frotz
 826                 * $ : >frotz
 827                 * $ sleep 3
 828                 * $ echo filfre >nitfol
 829                 * $ git-update-index --add nitfol
 830                 *
 831                 * but it does not.  Whe the second update-index runs,
 832                 * it notices that the entry "frotz" has the same timestamp
 833                 * as index, and if we were to smudge it by resetting its
 834                 * size to zero here, then the object name recorded
 835                 * in index is the 6-byte file but the cached stat information
 836                 * becomes zero --- which would then match what we would
 837                 * obtain from the filesystem next time we stat("frotz"). 
 838                 *
 839                 * However, the second update-index, before calling
 840                 * this function, notices that the cached size is 6
 841                 * bytes and what is on the filesystem is an empty
 842                 * file, and never calls us, so the cached size information
 843                 * for "frotz" stays 6 which does not match the filesystem.
 844                 */
 845                ce->ce_size = htonl(0);
 846        }
 847}
 848
 849int write_cache(int newfd, struct cache_entry **cache, int entries)
 850{
 851        SHA_CTX c;
 852        struct cache_header hdr;
 853        int i, removed;
 854
 855        for (i = removed = 0; i < entries; i++)
 856                if (!cache[i]->ce_mode)
 857                        removed++;
 858
 859        hdr.hdr_signature = htonl(CACHE_SIGNATURE);
 860        hdr.hdr_version = htonl(2);
 861        hdr.hdr_entries = htonl(entries - removed);
 862
 863        SHA1_Init(&c);
 864        if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
 865                return -1;
 866
 867        for (i = 0; i < entries; i++) {
 868                struct cache_entry *ce = cache[i];
 869                if (!ce->ce_mode)
 870                        continue;
 871                if (index_file_timestamp &&
 872                    index_file_timestamp <= ntohl(ce->ce_mtime.sec))
 873                        ce_smudge_racily_clean_entry(ce);
 874                if (ce_write(&c, newfd, ce, ce_size(ce)) < 0)
 875                        return -1;
 876        }
 877        return ce_flush(&c, newfd);
 878}