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