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