read-cache.con commit Documentation/git-commit.txt: correct bad list formatting. (f9935bf)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#define NO_THE_INDEX_COMPATIBILITY_MACROS
   7#include "cache.h"
   8#include "cache-tree.h"
   9#include "refs.h"
  10
  11/* Index extensions.
  12 *
  13 * The first letter should be 'A'..'Z' for extensions that are not
  14 * necessary for a correct operation (i.e. optimization data).
  15 * When new extensions are added that _needs_ to be understood in
  16 * order to correctly interpret the index file, pick character that
  17 * is outside the range, to cause the reader to abort.
  18 */
  19
  20#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
  21#define CACHE_EXT_TREE 0x54524545       /* "TREE" */
  22
  23struct index_state the_index;
  24
  25/*
  26 * This only updates the "non-critical" parts of the directory
  27 * cache, ie the parts that aren't tracked by GIT, and only used
  28 * to validate the cache.
  29 */
  30void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
  31{
  32        ce->ce_ctime.sec = htonl(st->st_ctime);
  33        ce->ce_mtime.sec = htonl(st->st_mtime);
  34#ifdef USE_NSEC
  35        ce->ce_ctime.nsec = htonl(st->st_ctim.tv_nsec);
  36        ce->ce_mtime.nsec = htonl(st->st_mtim.tv_nsec);
  37#endif
  38        ce->ce_dev = htonl(st->st_dev);
  39        ce->ce_ino = htonl(st->st_ino);
  40        ce->ce_uid = htonl(st->st_uid);
  41        ce->ce_gid = htonl(st->st_gid);
  42        ce->ce_size = htonl(st->st_size);
  43
  44        if (assume_unchanged)
  45                ce->ce_flags |= htons(CE_VALID);
  46}
  47
  48static int ce_compare_data(struct cache_entry *ce, struct stat *st)
  49{
  50        int match = -1;
  51        int fd = open(ce->name, O_RDONLY);
  52
  53        if (fd >= 0) {
  54                unsigned char sha1[20];
  55                if (!index_fd(sha1, fd, st, 0, OBJ_BLOB, ce->name))
  56                        match = hashcmp(sha1, ce->sha1);
  57                /* index_fd() closed the file descriptor already */
  58        }
  59        return match;
  60}
  61
  62static int ce_compare_link(struct cache_entry *ce, size_t expected_size)
  63{
  64        int match = -1;
  65        char *target;
  66        void *buffer;
  67        unsigned long size;
  68        enum object_type type;
  69        int len;
  70
  71        target = xmalloc(expected_size);
  72        len = readlink(ce->name, target, expected_size);
  73        if (len != expected_size) {
  74                free(target);
  75                return -1;
  76        }
  77        buffer = read_sha1_file(ce->sha1, &type, &size);
  78        if (!buffer) {
  79                free(target);
  80                return -1;
  81        }
  82        if (size == expected_size)
  83                match = memcmp(buffer, target, size);
  84        free(buffer);
  85        free(target);
  86        return match;
  87}
  88
  89static int ce_compare_gitlink(struct cache_entry *ce)
  90{
  91        unsigned char sha1[20];
  92
  93        /*
  94         * We don't actually require that the .git directory
  95         * under GITLINK directory be a valid git directory. It
  96         * might even be missing (in case nobody populated that
  97         * sub-project).
  98         *
  99         * If so, we consider it always to match.
 100         */
 101        if (resolve_gitlink_ref(ce->name, "HEAD", sha1) < 0)
 102                return 0;
 103        return hashcmp(sha1, ce->sha1);
 104}
 105
 106static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
 107{
 108        switch (st->st_mode & S_IFMT) {
 109        case S_IFREG:
 110                if (ce_compare_data(ce, st))
 111                        return DATA_CHANGED;
 112                break;
 113        case S_IFLNK:
 114                if (ce_compare_link(ce, xsize_t(st->st_size)))
 115                        return DATA_CHANGED;
 116                break;
 117        case S_IFDIR:
 118                if (S_ISGITLINK(ntohl(ce->ce_mode)))
 119                        return 0;
 120        default:
 121                return TYPE_CHANGED;
 122        }
 123        return 0;
 124}
 125
 126static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
 127{
 128        unsigned int changed = 0;
 129
 130        switch (ntohl(ce->ce_mode) & S_IFMT) {
 131        case S_IFREG:
 132                changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
 133                /* We consider only the owner x bit to be relevant for
 134                 * "mode changes"
 135                 */
 136                if (trust_executable_bit &&
 137                    (0100 & (ntohl(ce->ce_mode) ^ st->st_mode)))
 138                        changed |= MODE_CHANGED;
 139                break;
 140        case S_IFLNK:
 141                if (!S_ISLNK(st->st_mode) &&
 142                    (has_symlinks || !S_ISREG(st->st_mode)))
 143                        changed |= TYPE_CHANGED;
 144                break;
 145        case S_IFGITLINK:
 146                if (!S_ISDIR(st->st_mode))
 147                        changed |= TYPE_CHANGED;
 148                else if (ce_compare_gitlink(ce))
 149                        changed |= DATA_CHANGED;
 150                return changed;
 151        default:
 152                die("internal error: ce_mode is %o", ntohl(ce->ce_mode));
 153        }
 154        if (ce->ce_mtime.sec != htonl(st->st_mtime))
 155                changed |= MTIME_CHANGED;
 156        if (ce->ce_ctime.sec != htonl(st->st_ctime))
 157                changed |= CTIME_CHANGED;
 158
 159#ifdef USE_NSEC
 160        /*
 161         * nsec seems unreliable - not all filesystems support it, so
 162         * as long as it is in the inode cache you get right nsec
 163         * but after it gets flushed, you get zero nsec.
 164         */
 165        if (ce->ce_mtime.nsec != htonl(st->st_mtim.tv_nsec))
 166                changed |= MTIME_CHANGED;
 167        if (ce->ce_ctime.nsec != htonl(st->st_ctim.tv_nsec))
 168                changed |= CTIME_CHANGED;
 169#endif
 170
 171        if (ce->ce_uid != htonl(st->st_uid) ||
 172            ce->ce_gid != htonl(st->st_gid))
 173                changed |= OWNER_CHANGED;
 174        if (ce->ce_ino != htonl(st->st_ino))
 175                changed |= INODE_CHANGED;
 176
 177#ifdef USE_STDEV
 178        /*
 179         * st_dev breaks on network filesystems where different
 180         * clients will have different views of what "device"
 181         * the filesystem is on
 182         */
 183        if (ce->ce_dev != htonl(st->st_dev))
 184                changed |= INODE_CHANGED;
 185#endif
 186
 187        if (ce->ce_size != htonl(st->st_size))
 188                changed |= DATA_CHANGED;
 189
 190        return changed;
 191}
 192
 193int ie_match_stat(struct index_state *istate,
 194                  struct cache_entry *ce, struct stat *st, int options)
 195{
 196        unsigned int changed;
 197        int ignore_valid = options & 01;
 198        int assume_racy_is_modified = options & 02;
 199
 200        /*
 201         * If it's marked as always valid in the index, it's
 202         * valid whatever the checked-out copy says.
 203         */
 204        if (!ignore_valid && (ce->ce_flags & htons(CE_VALID)))
 205                return 0;
 206
 207        changed = ce_match_stat_basic(ce, st);
 208
 209        /*
 210         * Within 1 second of this sequence:
 211         *      echo xyzzy >file && git-update-index --add file
 212         * running this command:
 213         *      echo frotz >file
 214         * would give a falsely clean cache entry.  The mtime and
 215         * length match the cache, and other stat fields do not change.
 216         *
 217         * We could detect this at update-index time (the cache entry
 218         * being registered/updated records the same time as "now")
 219         * and delay the return from git-update-index, but that would
 220         * effectively mean we can make at most one commit per second,
 221         * which is not acceptable.  Instead, we check cache entries
 222         * whose mtime are the same as the index file timestamp more
 223         * carefully than others.
 224         */
 225        if (!changed &&
 226            istate->timestamp &&
 227            istate->timestamp <= ntohl(ce->ce_mtime.sec)) {
 228                if (assume_racy_is_modified)
 229                        changed |= DATA_CHANGED;
 230                else
 231                        changed |= ce_modified_check_fs(ce, st);
 232        }
 233
 234        return changed;
 235}
 236
 237int ie_modified(struct index_state *istate,
 238                struct cache_entry *ce, struct stat *st, int really)
 239{
 240        int changed, changed_fs;
 241        changed = ie_match_stat(istate, ce, st, really);
 242        if (!changed)
 243                return 0;
 244        /*
 245         * If the mode or type has changed, there's no point in trying
 246         * to refresh the entry - it's not going to match
 247         */
 248        if (changed & (MODE_CHANGED | TYPE_CHANGED))
 249                return changed;
 250
 251        /* Immediately after read-tree or update-index --cacheinfo,
 252         * the length field is zero.  For other cases the ce_size
 253         * should match the SHA1 recorded in the index entry.
 254         */
 255        if ((changed & DATA_CHANGED) && ce->ce_size != htonl(0))
 256                return changed;
 257
 258        changed_fs = ce_modified_check_fs(ce, st);
 259        if (changed_fs)
 260                return changed | changed_fs;
 261        return 0;
 262}
 263
 264int base_name_compare(const char *name1, int len1, int mode1,
 265                      const char *name2, int len2, int mode2)
 266{
 267        unsigned char c1, c2;
 268        int len = len1 < len2 ? len1 : len2;
 269        int cmp;
 270
 271        cmp = memcmp(name1, name2, len);
 272        if (cmp)
 273                return cmp;
 274        c1 = name1[len];
 275        c2 = name2[len];
 276        if (!c1 && S_ISDIR(mode1))
 277                c1 = '/';
 278        if (!c2 && S_ISDIR(mode2))
 279                c2 = '/';
 280        return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
 281}
 282
 283int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
 284{
 285        int len1 = flags1 & CE_NAMEMASK;
 286        int len2 = flags2 & CE_NAMEMASK;
 287        int len = len1 < len2 ? len1 : len2;
 288        int cmp;
 289
 290        cmp = memcmp(name1, name2, len);
 291        if (cmp)
 292                return cmp;
 293        if (len1 < len2)
 294                return -1;
 295        if (len1 > len2)
 296                return 1;
 297
 298        /* Compare stages  */
 299        flags1 &= CE_STAGEMASK;
 300        flags2 &= CE_STAGEMASK;
 301
 302        if (flags1 < flags2)
 303                return -1;
 304        if (flags1 > flags2)
 305                return 1;
 306        return 0;
 307}
 308
 309int index_name_pos(struct index_state *istate, const char *name, int namelen)
 310{
 311        int first, last;
 312
 313        first = 0;
 314        last = istate->cache_nr;
 315        while (last > first) {
 316                int next = (last + first) >> 1;
 317                struct cache_entry *ce = istate->cache[next];
 318                int cmp = cache_name_compare(name, namelen, ce->name, ntohs(ce->ce_flags));
 319                if (!cmp)
 320                        return next;
 321                if (cmp < 0) {
 322                        last = next;
 323                        continue;
 324                }
 325                first = next+1;
 326        }
 327        return -first-1;
 328}
 329
 330/* Remove entry, return true if there are more entries to go.. */
 331int remove_index_entry_at(struct index_state *istate, int pos)
 332{
 333        istate->cache_changed = 1;
 334        istate->cache_nr--;
 335        if (pos >= istate->cache_nr)
 336                return 0;
 337        memmove(istate->cache + pos,
 338                istate->cache + pos + 1,
 339                (istate->cache_nr - pos) * sizeof(struct cache_entry *));
 340        return 1;
 341}
 342
 343int remove_file_from_index(struct index_state *istate, const char *path)
 344{
 345        int pos = index_name_pos(istate, path, strlen(path));
 346        if (pos < 0)
 347                pos = -pos-1;
 348        while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
 349                remove_index_entry_at(istate, pos);
 350        return 0;
 351}
 352
 353static int compare_name(struct cache_entry *ce, const char *path, int namelen)
 354{
 355        return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
 356}
 357
 358static int index_name_pos_also_unmerged(struct index_state *istate,
 359        const char *path, int namelen)
 360{
 361        int pos = index_name_pos(istate, path, namelen);
 362        struct cache_entry *ce;
 363
 364        if (pos >= 0)
 365                return pos;
 366
 367        /* maybe unmerged? */
 368        pos = -1 - pos;
 369        if (pos >= istate->cache_nr ||
 370                        compare_name((ce = istate->cache[pos]), path, namelen))
 371                return -1;
 372
 373        /* order of preference: stage 2, 1, 3 */
 374        if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
 375                        ce_stage((ce = istate->cache[pos + 1])) == 2 &&
 376                        !compare_name(ce, path, namelen))
 377                pos++;
 378        return pos;
 379}
 380
 381int add_file_to_index(struct index_state *istate, const char *path, int verbose)
 382{
 383        int size, namelen, pos;
 384        struct stat st;
 385        struct cache_entry *ce;
 386
 387        if (lstat(path, &st))
 388                die("%s: unable to stat (%s)", path, strerror(errno));
 389
 390        if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode) && !S_ISDIR(st.st_mode))
 391                die("%s: can only add regular files, symbolic links or git-directories", path);
 392
 393        namelen = strlen(path);
 394        if (S_ISDIR(st.st_mode)) {
 395                while (namelen && path[namelen-1] == '/')
 396                        namelen--;
 397        }
 398        size = cache_entry_size(namelen);
 399        ce = xcalloc(1, size);
 400        memcpy(ce->name, path, namelen);
 401        ce->ce_flags = htons(namelen);
 402        fill_stat_cache_info(ce, &st);
 403
 404        if (trust_executable_bit && has_symlinks)
 405                ce->ce_mode = create_ce_mode(st.st_mode);
 406        else {
 407                /* If there is an existing entry, pick the mode bits and type
 408                 * from it, otherwise assume unexecutable regular file.
 409                 */
 410                struct cache_entry *ent;
 411                int pos = index_name_pos_also_unmerged(istate, path, namelen);
 412
 413                ent = (0 <= pos) ? istate->cache[pos] : NULL;
 414                ce->ce_mode = ce_mode_from_stat(ent, st.st_mode);
 415        }
 416
 417        pos = index_name_pos(istate, ce->name, namelen);
 418        if (0 <= pos &&
 419            !ce_stage(istate->cache[pos]) &&
 420            !ie_modified(istate, istate->cache[pos], &st, 1)) {
 421                /* Nothing changed, really */
 422                free(ce);
 423                return 0;
 424        }
 425
 426        if (index_path(ce->sha1, path, &st, 1))
 427                die("unable to index file %s", path);
 428        if (add_index_entry(istate, ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE))
 429                die("unable to add %s to index",path);
 430        if (verbose)
 431                printf("add '%s'\n", path);
 432        cache_tree_invalidate_path(istate->cache_tree, path);
 433        return 0;
 434}
 435
 436int ce_same_name(struct cache_entry *a, struct cache_entry *b)
 437{
 438        int len = ce_namelen(a);
 439        return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
 440}
 441
 442int ce_path_match(const struct cache_entry *ce, const char **pathspec)
 443{
 444        const char *match, *name;
 445        int len;
 446
 447        if (!pathspec)
 448                return 1;
 449
 450        len = ce_namelen(ce);
 451        name = ce->name;
 452        while ((match = *pathspec++) != NULL) {
 453                int matchlen = strlen(match);
 454                if (matchlen > len)
 455                        continue;
 456                if (memcmp(name, match, matchlen))
 457                        continue;
 458                if (matchlen && name[matchlen-1] == '/')
 459                        return 1;
 460                if (name[matchlen] == '/' || !name[matchlen])
 461                        return 1;
 462                if (!matchlen)
 463                        return 1;
 464        }
 465        return 0;
 466}
 467
 468/*
 469 * We fundamentally don't like some paths: we don't want
 470 * dot or dot-dot anywhere, and for obvious reasons don't
 471 * want to recurse into ".git" either.
 472 *
 473 * Also, we don't want double slashes or slashes at the
 474 * end that can make pathnames ambiguous.
 475 */
 476static int verify_dotfile(const char *rest)
 477{
 478        /*
 479         * The first character was '.', but that
 480         * has already been discarded, we now test
 481         * the rest.
 482         */
 483        switch (*rest) {
 484        /* "." is not allowed */
 485        case '\0': case '/':
 486                return 0;
 487
 488        /*
 489         * ".git" followed by  NUL or slash is bad. This
 490         * shares the path end test with the ".." case.
 491         */
 492        case 'g':
 493                if (rest[1] != 'i')
 494                        break;
 495                if (rest[2] != 't')
 496                        break;
 497                rest += 2;
 498        /* fallthrough */
 499        case '.':
 500                if (rest[1] == '\0' || rest[1] == '/')
 501                        return 0;
 502        }
 503        return 1;
 504}
 505
 506int verify_path(const char *path)
 507{
 508        char c;
 509
 510        goto inside;
 511        for (;;) {
 512                if (!c)
 513                        return 1;
 514                if (c == '/') {
 515inside:
 516                        c = *path++;
 517                        switch (c) {
 518                        default:
 519                                continue;
 520                        case '/': case '\0':
 521                                break;
 522                        case '.':
 523                                if (verify_dotfile(path))
 524                                        continue;
 525                        }
 526                        return 0;
 527                }
 528                c = *path++;
 529        }
 530}
 531
 532/*
 533 * Do we have another file that has the beginning components being a
 534 * proper superset of the name we're trying to add?
 535 */
 536static int has_file_name(struct index_state *istate,
 537                         const struct cache_entry *ce, int pos, int ok_to_replace)
 538{
 539        int retval = 0;
 540        int len = ce_namelen(ce);
 541        int stage = ce_stage(ce);
 542        const char *name = ce->name;
 543
 544        while (pos < istate->cache_nr) {
 545                struct cache_entry *p = istate->cache[pos++];
 546
 547                if (len >= ce_namelen(p))
 548                        break;
 549                if (memcmp(name, p->name, len))
 550                        break;
 551                if (ce_stage(p) != stage)
 552                        continue;
 553                if (p->name[len] != '/')
 554                        continue;
 555                if (!ce_stage(p) && !p->ce_mode)
 556                        continue;
 557                retval = -1;
 558                if (!ok_to_replace)
 559                        break;
 560                remove_index_entry_at(istate, --pos);
 561        }
 562        return retval;
 563}
 564
 565/*
 566 * Do we have another file with a pathname that is a proper
 567 * subset of the name we're trying to add?
 568 */
 569static int has_dir_name(struct index_state *istate,
 570                        const struct cache_entry *ce, int pos, int ok_to_replace)
 571{
 572        int retval = 0;
 573        int stage = ce_stage(ce);
 574        const char *name = ce->name;
 575        const char *slash = name + ce_namelen(ce);
 576
 577        for (;;) {
 578                int len;
 579
 580                for (;;) {
 581                        if (*--slash == '/')
 582                                break;
 583                        if (slash <= ce->name)
 584                                return retval;
 585                }
 586                len = slash - name;
 587
 588                pos = index_name_pos(istate, name, ntohs(create_ce_flags(len, stage)));
 589                if (pos >= 0) {
 590                        /*
 591                         * Found one, but not so fast.  This could
 592                         * be a marker that says "I was here, but
 593                         * I am being removed".  Such an entry is
 594                         * not a part of the resulting tree, and
 595                         * it is Ok to have a directory at the same
 596                         * path.
 597                         */
 598                        if (stage || istate->cache[pos]->ce_mode) {
 599                                retval = -1;
 600                                if (!ok_to_replace)
 601                                        break;
 602                                remove_index_entry_at(istate, pos);
 603                                continue;
 604                        }
 605                }
 606                else
 607                        pos = -pos-1;
 608
 609                /*
 610                 * Trivial optimization: if we find an entry that
 611                 * already matches the sub-directory, then we know
 612                 * we're ok, and we can exit.
 613                 */
 614                while (pos < istate->cache_nr) {
 615                        struct cache_entry *p = istate->cache[pos];
 616                        if ((ce_namelen(p) <= len) ||
 617                            (p->name[len] != '/') ||
 618                            memcmp(p->name, name, len))
 619                                break; /* not our subdirectory */
 620                        if (ce_stage(p) == stage && (stage || p->ce_mode))
 621                                /* p is at the same stage as our entry, and
 622                                 * is a subdirectory of what we are looking
 623                                 * at, so we cannot have conflicts at our
 624                                 * level or anything shorter.
 625                                 */
 626                                return retval;
 627                        pos++;
 628                }
 629        }
 630        return retval;
 631}
 632
 633/* We may be in a situation where we already have path/file and path
 634 * is being added, or we already have path and path/file is being
 635 * added.  Either one would result in a nonsense tree that has path
 636 * twice when git-write-tree tries to write it out.  Prevent it.
 637 *
 638 * If ok-to-replace is specified, we remove the conflicting entries
 639 * from the cache so the caller should recompute the insert position.
 640 * When this happens, we return non-zero.
 641 */
 642static int check_file_directory_conflict(struct index_state *istate,
 643                                         const struct cache_entry *ce,
 644                                         int pos, int ok_to_replace)
 645{
 646        int retval;
 647
 648        /*
 649         * When ce is an "I am going away" entry, we allow it to be added
 650         */
 651        if (!ce_stage(ce) && !ce->ce_mode)
 652                return 0;
 653
 654        /*
 655         * We check if the path is a sub-path of a subsequent pathname
 656         * first, since removing those will not change the position
 657         * in the array.
 658         */
 659        retval = has_file_name(istate, ce, pos, ok_to_replace);
 660
 661        /*
 662         * Then check if the path might have a clashing sub-directory
 663         * before it.
 664         */
 665        return retval + has_dir_name(istate, ce, pos, ok_to_replace);
 666}
 667
 668int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
 669{
 670        int pos;
 671        int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
 672        int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
 673        int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
 674
 675        pos = index_name_pos(istate, ce->name, ntohs(ce->ce_flags));
 676
 677        /* existing match? Just replace it. */
 678        if (pos >= 0) {
 679                istate->cache_changed = 1;
 680                istate->cache[pos] = ce;
 681                return 0;
 682        }
 683        pos = -pos-1;
 684
 685        /*
 686         * Inserting a merged entry ("stage 0") into the index
 687         * will always replace all non-merged entries..
 688         */
 689        if (pos < istate->cache_nr && ce_stage(ce) == 0) {
 690                while (ce_same_name(istate->cache[pos], ce)) {
 691                        ok_to_add = 1;
 692                        if (!remove_index_entry_at(istate, pos))
 693                                break;
 694                }
 695        }
 696
 697        if (!ok_to_add)
 698                return -1;
 699        if (!verify_path(ce->name))
 700                return -1;
 701
 702        if (!skip_df_check &&
 703            check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
 704                if (!ok_to_replace)
 705                        return error("'%s' appears as both a file and as a directory",
 706                                     ce->name);
 707                pos = index_name_pos(istate, ce->name, ntohs(ce->ce_flags));
 708                pos = -pos-1;
 709        }
 710
 711        /* Make sure the array is big enough .. */
 712        if (istate->cache_nr == istate->cache_alloc) {
 713                istate->cache_alloc = alloc_nr(istate->cache_alloc);
 714                istate->cache = xrealloc(istate->cache,
 715                                        istate->cache_alloc * sizeof(struct cache_entry *));
 716        }
 717
 718        /* Add it in.. */
 719        istate->cache_nr++;
 720        if (istate->cache_nr > pos)
 721                memmove(istate->cache + pos + 1,
 722                        istate->cache + pos,
 723                        (istate->cache_nr - pos - 1) * sizeof(ce));
 724        istate->cache[pos] = ce;
 725        istate->cache_changed = 1;
 726        return 0;
 727}
 728
 729/*
 730 * "refresh" does not calculate a new sha1 file or bring the
 731 * cache up-to-date for mode/content changes. But what it
 732 * _does_ do is to "re-match" the stat information of a file
 733 * with the cache, so that you can refresh the cache for a
 734 * file that hasn't been changed but where the stat entry is
 735 * out of date.
 736 *
 737 * For example, you'd want to do this after doing a "git-read-tree",
 738 * to link up the stat cache details with the proper files.
 739 */
 740static struct cache_entry *refresh_cache_ent(struct index_state *istate,
 741                                             struct cache_entry *ce, int really, int *err)
 742{
 743        struct stat st;
 744        struct cache_entry *updated;
 745        int changed, size;
 746
 747        if (lstat(ce->name, &st) < 0) {
 748                if (err)
 749                        *err = errno;
 750                return NULL;
 751        }
 752
 753        changed = ie_match_stat(istate, ce, &st, really);
 754        if (!changed) {
 755                if (really && assume_unchanged &&
 756                    !(ce->ce_flags & htons(CE_VALID)))
 757                        ; /* mark this one VALID again */
 758                else
 759                        return ce;
 760        }
 761
 762        if (ie_modified(istate, ce, &st, really)) {
 763                if (err)
 764                        *err = EINVAL;
 765                return NULL;
 766        }
 767
 768        size = ce_size(ce);
 769        updated = xmalloc(size);
 770        memcpy(updated, ce, size);
 771        fill_stat_cache_info(updated, &st);
 772
 773        /* In this case, if really is not set, we should leave
 774         * CE_VALID bit alone.  Otherwise, paths marked with
 775         * --no-assume-unchanged (i.e. things to be edited) will
 776         * reacquire CE_VALID bit automatically, which is not
 777         * really what we want.
 778         */
 779        if (!really && assume_unchanged && !(ce->ce_flags & htons(CE_VALID)))
 780                updated->ce_flags &= ~htons(CE_VALID);
 781
 782        return updated;
 783}
 784
 785int refresh_index(struct index_state *istate, unsigned int flags)
 786{
 787        int i;
 788        int has_errors = 0;
 789        int really = (flags & REFRESH_REALLY) != 0;
 790        int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
 791        int quiet = (flags & REFRESH_QUIET) != 0;
 792        int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
 793
 794        for (i = 0; i < istate->cache_nr; i++) {
 795                struct cache_entry *ce, *new;
 796                int cache_errno = 0;
 797
 798                ce = istate->cache[i];
 799                if (ce_stage(ce)) {
 800                        while ((i < istate->cache_nr) &&
 801                               ! strcmp(istate->cache[i]->name, ce->name))
 802                                i++;
 803                        i--;
 804                        if (allow_unmerged)
 805                                continue;
 806                        printf("%s: needs merge\n", ce->name);
 807                        has_errors = 1;
 808                        continue;
 809                }
 810
 811                new = refresh_cache_ent(istate, ce, really, &cache_errno);
 812                if (new == ce)
 813                        continue;
 814                if (!new) {
 815                        if (not_new && cache_errno == ENOENT)
 816                                continue;
 817                        if (really && cache_errno == EINVAL) {
 818                                /* If we are doing --really-refresh that
 819                                 * means the index is not valid anymore.
 820                                 */
 821                                ce->ce_flags &= ~htons(CE_VALID);
 822                                istate->cache_changed = 1;
 823                        }
 824                        if (quiet)
 825                                continue;
 826                        printf("%s: needs update\n", ce->name);
 827                        has_errors = 1;
 828                        continue;
 829                }
 830                istate->cache_changed = 1;
 831                /* You can NOT just free istate->cache[i] here, since it
 832                 * might not be necessarily malloc()ed but can also come
 833                 * from mmap(). */
 834                istate->cache[i] = new;
 835        }
 836        return has_errors;
 837}
 838
 839struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
 840{
 841        return refresh_cache_ent(&the_index, ce, really, NULL);
 842}
 843
 844static int verify_hdr(struct cache_header *hdr, unsigned long size)
 845{
 846        SHA_CTX c;
 847        unsigned char sha1[20];
 848
 849        if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
 850                return error("bad signature");
 851        if (hdr->hdr_version != htonl(2))
 852                return error("bad index version");
 853        SHA1_Init(&c);
 854        SHA1_Update(&c, hdr, size - 20);
 855        SHA1_Final(sha1, &c);
 856        if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
 857                return error("bad index file sha1 signature");
 858        return 0;
 859}
 860
 861static int read_index_extension(struct index_state *istate,
 862                                const char *ext, void *data, unsigned long sz)
 863{
 864        switch (CACHE_EXT(ext)) {
 865        case CACHE_EXT_TREE:
 866                istate->cache_tree = cache_tree_read(data, sz);
 867                break;
 868        default:
 869                if (*ext < 'A' || 'Z' < *ext)
 870                        return error("index uses %.4s extension, which we do not understand",
 871                                     ext);
 872                fprintf(stderr, "ignoring %.4s extension\n", ext);
 873                break;
 874        }
 875        return 0;
 876}
 877
 878int read_index(struct index_state *istate)
 879{
 880        return read_index_from(istate, get_index_file());
 881}
 882
 883/* remember to discard_cache() before reading a different cache! */
 884int read_index_from(struct index_state *istate, const char *path)
 885{
 886        int fd, i;
 887        struct stat st;
 888        unsigned long offset;
 889        struct cache_header *hdr;
 890
 891        errno = EBUSY;
 892        if (istate->mmap)
 893                return istate->cache_nr;
 894
 895        errno = ENOENT;
 896        istate->timestamp = 0;
 897        fd = open(path, O_RDONLY);
 898        if (fd < 0) {
 899                if (errno == ENOENT)
 900                        return 0;
 901                die("index file open failed (%s)", strerror(errno));
 902        }
 903
 904        if (fstat(fd, &st))
 905                die("cannot stat the open index (%s)", strerror(errno));
 906
 907        errno = EINVAL;
 908        istate->mmap_size = xsize_t(st.st_size);
 909        if (istate->mmap_size < sizeof(struct cache_header) + 20)
 910                die("index file smaller than expected");
 911
 912        istate->mmap = xmmap(NULL, istate->mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
 913        close(fd);
 914
 915        hdr = istate->mmap;
 916        if (verify_hdr(hdr, istate->mmap_size) < 0)
 917                goto unmap;
 918
 919        istate->cache_nr = ntohl(hdr->hdr_entries);
 920        istate->cache_alloc = alloc_nr(istate->cache_nr);
 921        istate->cache = xcalloc(istate->cache_alloc, sizeof(struct cache_entry *));
 922
 923        offset = sizeof(*hdr);
 924        for (i = 0; i < istate->cache_nr; i++) {
 925                struct cache_entry *ce;
 926
 927                ce = (struct cache_entry *)((char *)(istate->mmap) + offset);
 928                offset = offset + ce_size(ce);
 929                istate->cache[i] = ce;
 930        }
 931        istate->timestamp = st.st_mtime;
 932        while (offset <= istate->mmap_size - 20 - 8) {
 933                /* After an array of active_nr index entries,
 934                 * there can be arbitrary number of extended
 935                 * sections, each of which is prefixed with
 936                 * extension name (4-byte) and section length
 937                 * in 4-byte network byte order.
 938                 */
 939                unsigned long extsize;
 940                memcpy(&extsize, (char *)(istate->mmap) + offset + 4, 4);
 941                extsize = ntohl(extsize);
 942                if (read_index_extension(istate,
 943                                         ((const char *) (istate->mmap)) + offset,
 944                                         (char *) (istate->mmap) + offset + 8,
 945                                         extsize) < 0)
 946                        goto unmap;
 947                offset += 8;
 948                offset += extsize;
 949        }
 950        return istate->cache_nr;
 951
 952unmap:
 953        munmap(istate->mmap, istate->mmap_size);
 954        errno = EINVAL;
 955        die("index file corrupt");
 956}
 957
 958int discard_index(struct index_state *istate)
 959{
 960        int ret;
 961
 962        istate->cache_nr = 0;
 963        istate->cache_changed = 0;
 964        istate->timestamp = 0;
 965        cache_tree_free(&(istate->cache_tree));
 966        if (istate->mmap == NULL)
 967                return 0;
 968        ret = munmap(istate->mmap, istate->mmap_size);
 969        istate->mmap = NULL;
 970        istate->mmap_size = 0;
 971
 972        /* no need to throw away allocated active_cache */
 973        return ret;
 974}
 975
 976#define WRITE_BUFFER_SIZE 8192
 977static unsigned char write_buffer[WRITE_BUFFER_SIZE];
 978static unsigned long write_buffer_len;
 979
 980static int ce_write_flush(SHA_CTX *context, int fd)
 981{
 982        unsigned int buffered = write_buffer_len;
 983        if (buffered) {
 984                SHA1_Update(context, write_buffer, buffered);
 985                if (write_in_full(fd, write_buffer, buffered) != buffered)
 986                        return -1;
 987                write_buffer_len = 0;
 988        }
 989        return 0;
 990}
 991
 992static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
 993{
 994        while (len) {
 995                unsigned int buffered = write_buffer_len;
 996                unsigned int partial = WRITE_BUFFER_SIZE - buffered;
 997                if (partial > len)
 998                        partial = len;
 999                memcpy(write_buffer + buffered, data, partial);
1000                buffered += partial;
1001                if (buffered == WRITE_BUFFER_SIZE) {
1002                        write_buffer_len = buffered;
1003                        if (ce_write_flush(context, fd))
1004                                return -1;
1005                        buffered = 0;
1006                }
1007                write_buffer_len = buffered;
1008                len -= partial;
1009                data = (char *) data + partial;
1010        }
1011        return 0;
1012}
1013
1014static int write_index_ext_header(SHA_CTX *context, int fd,
1015                                  unsigned int ext, unsigned int sz)
1016{
1017        ext = htonl(ext);
1018        sz = htonl(sz);
1019        return ((ce_write(context, fd, &ext, 4) < 0) ||
1020                (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1021}
1022
1023static int ce_flush(SHA_CTX *context, int fd)
1024{
1025        unsigned int left = write_buffer_len;
1026
1027        if (left) {
1028                write_buffer_len = 0;
1029                SHA1_Update(context, write_buffer, left);
1030        }
1031
1032        /* Flush first if not enough space for SHA1 signature */
1033        if (left + 20 > WRITE_BUFFER_SIZE) {
1034                if (write_in_full(fd, write_buffer, left) != left)
1035                        return -1;
1036                left = 0;
1037        }
1038
1039        /* Append the SHA1 signature at the end */
1040        SHA1_Final(write_buffer + left, context);
1041        left += 20;
1042        return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1043}
1044
1045static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1046{
1047        /*
1048         * The only thing we care about in this function is to smudge the
1049         * falsely clean entry due to touch-update-touch race, so we leave
1050         * everything else as they are.  We are called for entries whose
1051         * ce_mtime match the index file mtime.
1052         */
1053        struct stat st;
1054
1055        if (lstat(ce->name, &st) < 0)
1056                return;
1057        if (ce_match_stat_basic(ce, &st))
1058                return;
1059        if (ce_modified_check_fs(ce, &st)) {
1060                /* This is "racily clean"; smudge it.  Note that this
1061                 * is a tricky code.  At first glance, it may appear
1062                 * that it can break with this sequence:
1063                 *
1064                 * $ echo xyzzy >frotz
1065                 * $ git-update-index --add frotz
1066                 * $ : >frotz
1067                 * $ sleep 3
1068                 * $ echo filfre >nitfol
1069                 * $ git-update-index --add nitfol
1070                 *
1071                 * but it does not.  When the second update-index runs,
1072                 * it notices that the entry "frotz" has the same timestamp
1073                 * as index, and if we were to smudge it by resetting its
1074                 * size to zero here, then the object name recorded
1075                 * in index is the 6-byte file but the cached stat information
1076                 * becomes zero --- which would then match what we would
1077                 * obtain from the filesystem next time we stat("frotz").
1078                 *
1079                 * However, the second update-index, before calling
1080                 * this function, notices that the cached size is 6
1081                 * bytes and what is on the filesystem is an empty
1082                 * file, and never calls us, so the cached size information
1083                 * for "frotz" stays 6 which does not match the filesystem.
1084                 */
1085                ce->ce_size = htonl(0);
1086        }
1087}
1088
1089int write_index(struct index_state *istate, int newfd)
1090{
1091        SHA_CTX c;
1092        struct cache_header hdr;
1093        int i, removed;
1094        struct cache_entry **cache = istate->cache;
1095        int entries = istate->cache_nr;
1096
1097        for (i = removed = 0; i < entries; i++)
1098                if (!cache[i]->ce_mode)
1099                        removed++;
1100
1101        hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1102        hdr.hdr_version = htonl(2);
1103        hdr.hdr_entries = htonl(entries - removed);
1104
1105        SHA1_Init(&c);
1106        if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1107                return -1;
1108
1109        for (i = 0; i < entries; i++) {
1110                struct cache_entry *ce = cache[i];
1111                if (!ce->ce_mode)
1112                        continue;
1113                if (istate->timestamp &&
1114                    istate->timestamp <= ntohl(ce->ce_mtime.sec))
1115                        ce_smudge_racily_clean_entry(ce);
1116                if (ce_write(&c, newfd, ce, ce_size(ce)) < 0)
1117                        return -1;
1118        }
1119
1120        /* Write extension data here */
1121        if (istate->cache_tree) {
1122                unsigned long sz;
1123                void *data = cache_tree_write(istate->cache_tree, &sz);
1124                if (data &&
1125                    !write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sz) &&
1126                    !ce_write(&c, newfd, data, sz))
1127                        free(data);
1128                else {
1129                        free(data);
1130                        return -1;
1131                }
1132        }
1133        return ce_flush(&c, newfd);
1134}