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