read-cache.con commit commit: convert register_commit_graft to handle arbitrary repositories (a3b78e8)
   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 "config.h"
   9#include "tempfile.h"
  10#include "lockfile.h"
  11#include "cache-tree.h"
  12#include "refs.h"
  13#include "dir.h"
  14#include "object-store.h"
  15#include "tree.h"
  16#include "commit.h"
  17#include "blob.h"
  18#include "resolve-undo.h"
  19#include "strbuf.h"
  20#include "varint.h"
  21#include "split-index.h"
  22#include "utf8.h"
  23#include "fsmonitor.h"
  24
  25/* Mask for the name length in ce_flags in the on-disk index */
  26
  27#define CE_NAMEMASK  (0x0fff)
  28
  29/* Index extensions.
  30 *
  31 * The first letter should be 'A'..'Z' for extensions that are not
  32 * necessary for a correct operation (i.e. optimization data).
  33 * When new extensions are added that _needs_ to be understood in
  34 * order to correctly interpret the index file, pick character that
  35 * is outside the range, to cause the reader to abort.
  36 */
  37
  38#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
  39#define CACHE_EXT_TREE 0x54524545       /* "TREE" */
  40#define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
  41#define CACHE_EXT_LINK 0x6c696e6b         /* "link" */
  42#define CACHE_EXT_UNTRACKED 0x554E5452    /* "UNTR" */
  43#define CACHE_EXT_FSMONITOR 0x46534D4E    /* "FSMN" */
  44
  45/* changes that can be kept in $GIT_DIR/index (basically all extensions) */
  46#define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
  47                 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
  48                 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
  49
  50struct index_state the_index;
  51static const char *alternate_index_output;
  52
  53static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
  54{
  55        istate->cache[nr] = ce;
  56        add_name_hash(istate, ce);
  57}
  58
  59static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
  60{
  61        struct cache_entry *old = istate->cache[nr];
  62
  63        replace_index_entry_in_base(istate, old, ce);
  64        remove_name_hash(istate, old);
  65        free(old);
  66        ce->ce_flags &= ~CE_HASHED;
  67        set_index_entry(istate, nr, ce);
  68        ce->ce_flags |= CE_UPDATE_IN_BASE;
  69        mark_fsmonitor_invalid(istate, ce);
  70        istate->cache_changed |= CE_ENTRY_CHANGED;
  71}
  72
  73void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
  74{
  75        struct cache_entry *old_entry = istate->cache[nr], *new_entry;
  76        int namelen = strlen(new_name);
  77
  78        new_entry = xmalloc(cache_entry_size(namelen));
  79        copy_cache_entry(new_entry, old_entry);
  80        new_entry->ce_flags &= ~CE_HASHED;
  81        new_entry->ce_namelen = namelen;
  82        new_entry->index = 0;
  83        memcpy(new_entry->name, new_name, namelen + 1);
  84
  85        cache_tree_invalidate_path(istate, old_entry->name);
  86        untracked_cache_remove_from_index(istate, old_entry->name);
  87        remove_index_entry_at(istate, nr);
  88        add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
  89}
  90
  91void fill_stat_data(struct stat_data *sd, struct stat *st)
  92{
  93        sd->sd_ctime.sec = (unsigned int)st->st_ctime;
  94        sd->sd_mtime.sec = (unsigned int)st->st_mtime;
  95        sd->sd_ctime.nsec = ST_CTIME_NSEC(*st);
  96        sd->sd_mtime.nsec = ST_MTIME_NSEC(*st);
  97        sd->sd_dev = st->st_dev;
  98        sd->sd_ino = st->st_ino;
  99        sd->sd_uid = st->st_uid;
 100        sd->sd_gid = st->st_gid;
 101        sd->sd_size = st->st_size;
 102}
 103
 104int match_stat_data(const struct stat_data *sd, struct stat *st)
 105{
 106        int changed = 0;
 107
 108        if (sd->sd_mtime.sec != (unsigned int)st->st_mtime)
 109                changed |= MTIME_CHANGED;
 110        if (trust_ctime && check_stat &&
 111            sd->sd_ctime.sec != (unsigned int)st->st_ctime)
 112                changed |= CTIME_CHANGED;
 113
 114#ifdef USE_NSEC
 115        if (check_stat && sd->sd_mtime.nsec != ST_MTIME_NSEC(*st))
 116                changed |= MTIME_CHANGED;
 117        if (trust_ctime && check_stat &&
 118            sd->sd_ctime.nsec != ST_CTIME_NSEC(*st))
 119                changed |= CTIME_CHANGED;
 120#endif
 121
 122        if (check_stat) {
 123                if (sd->sd_uid != (unsigned int) st->st_uid ||
 124                        sd->sd_gid != (unsigned int) st->st_gid)
 125                        changed |= OWNER_CHANGED;
 126                if (sd->sd_ino != (unsigned int) st->st_ino)
 127                        changed |= INODE_CHANGED;
 128        }
 129
 130#ifdef USE_STDEV
 131        /*
 132         * st_dev breaks on network filesystems where different
 133         * clients will have different views of what "device"
 134         * the filesystem is on
 135         */
 136        if (check_stat && sd->sd_dev != (unsigned int) st->st_dev)
 137                        changed |= INODE_CHANGED;
 138#endif
 139
 140        if (sd->sd_size != (unsigned int) st->st_size)
 141                changed |= DATA_CHANGED;
 142
 143        return changed;
 144}
 145
 146/*
 147 * This only updates the "non-critical" parts of the directory
 148 * cache, ie the parts that aren't tracked by GIT, and only used
 149 * to validate the cache.
 150 */
 151void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
 152{
 153        fill_stat_data(&ce->ce_stat_data, st);
 154
 155        if (assume_unchanged)
 156                ce->ce_flags |= CE_VALID;
 157
 158        if (S_ISREG(st->st_mode)) {
 159                ce_mark_uptodate(ce);
 160                mark_fsmonitor_valid(ce);
 161        }
 162}
 163
 164static int ce_compare_data(const struct cache_entry *ce, struct stat *st)
 165{
 166        int match = -1;
 167        int fd = git_open_cloexec(ce->name, O_RDONLY);
 168
 169        if (fd >= 0) {
 170                struct object_id oid;
 171                if (!index_fd(&oid, fd, st, OBJ_BLOB, ce->name, 0))
 172                        match = oidcmp(&oid, &ce->oid);
 173                /* index_fd() closed the file descriptor already */
 174        }
 175        return match;
 176}
 177
 178static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
 179{
 180        int match = -1;
 181        void *buffer;
 182        unsigned long size;
 183        enum object_type type;
 184        struct strbuf sb = STRBUF_INIT;
 185
 186        if (strbuf_readlink(&sb, ce->name, expected_size))
 187                return -1;
 188
 189        buffer = read_object_file(&ce->oid, &type, &size);
 190        if (buffer) {
 191                if (size == sb.len)
 192                        match = memcmp(buffer, sb.buf, size);
 193                free(buffer);
 194        }
 195        strbuf_release(&sb);
 196        return match;
 197}
 198
 199static int ce_compare_gitlink(const struct cache_entry *ce)
 200{
 201        struct object_id oid;
 202
 203        /*
 204         * We don't actually require that the .git directory
 205         * under GITLINK directory be a valid git directory. It
 206         * might even be missing (in case nobody populated that
 207         * sub-project).
 208         *
 209         * If so, we consider it always to match.
 210         */
 211        if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
 212                return 0;
 213        return oidcmp(&oid, &ce->oid);
 214}
 215
 216static int ce_modified_check_fs(const struct cache_entry *ce, struct stat *st)
 217{
 218        switch (st->st_mode & S_IFMT) {
 219        case S_IFREG:
 220                if (ce_compare_data(ce, st))
 221                        return DATA_CHANGED;
 222                break;
 223        case S_IFLNK:
 224                if (ce_compare_link(ce, xsize_t(st->st_size)))
 225                        return DATA_CHANGED;
 226                break;
 227        case S_IFDIR:
 228                if (S_ISGITLINK(ce->ce_mode))
 229                        return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
 230                /* else fallthrough */
 231        default:
 232                return TYPE_CHANGED;
 233        }
 234        return 0;
 235}
 236
 237static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
 238{
 239        unsigned int changed = 0;
 240
 241        if (ce->ce_flags & CE_REMOVE)
 242                return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
 243
 244        switch (ce->ce_mode & S_IFMT) {
 245        case S_IFREG:
 246                changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
 247                /* We consider only the owner x bit to be relevant for
 248                 * "mode changes"
 249                 */
 250                if (trust_executable_bit &&
 251                    (0100 & (ce->ce_mode ^ st->st_mode)))
 252                        changed |= MODE_CHANGED;
 253                break;
 254        case S_IFLNK:
 255                if (!S_ISLNK(st->st_mode) &&
 256                    (has_symlinks || !S_ISREG(st->st_mode)))
 257                        changed |= TYPE_CHANGED;
 258                break;
 259        case S_IFGITLINK:
 260                /* We ignore most of the st_xxx fields for gitlinks */
 261                if (!S_ISDIR(st->st_mode))
 262                        changed |= TYPE_CHANGED;
 263                else if (ce_compare_gitlink(ce))
 264                        changed |= DATA_CHANGED;
 265                return changed;
 266        default:
 267                die("internal error: ce_mode is %o", ce->ce_mode);
 268        }
 269
 270        changed |= match_stat_data(&ce->ce_stat_data, st);
 271
 272        /* Racily smudged entry? */
 273        if (!ce->ce_stat_data.sd_size) {
 274                if (!is_empty_blob_sha1(ce->oid.hash))
 275                        changed |= DATA_CHANGED;
 276        }
 277
 278        return changed;
 279}
 280
 281static int is_racy_stat(const struct index_state *istate,
 282                        const struct stat_data *sd)
 283{
 284        return (istate->timestamp.sec &&
 285#ifdef USE_NSEC
 286                 /* nanosecond timestamped files can also be racy! */
 287                (istate->timestamp.sec < sd->sd_mtime.sec ||
 288                 (istate->timestamp.sec == sd->sd_mtime.sec &&
 289                  istate->timestamp.nsec <= sd->sd_mtime.nsec))
 290#else
 291                istate->timestamp.sec <= sd->sd_mtime.sec
 292#endif
 293                );
 294}
 295
 296static int is_racy_timestamp(const struct index_state *istate,
 297                             const struct cache_entry *ce)
 298{
 299        return (!S_ISGITLINK(ce->ce_mode) &&
 300                is_racy_stat(istate, &ce->ce_stat_data));
 301}
 302
 303int match_stat_data_racy(const struct index_state *istate,
 304                         const struct stat_data *sd, struct stat *st)
 305{
 306        if (is_racy_stat(istate, sd))
 307                return MTIME_CHANGED;
 308        return match_stat_data(sd, st);
 309}
 310
 311int ie_match_stat(struct index_state *istate,
 312                  const struct cache_entry *ce, struct stat *st,
 313                  unsigned int options)
 314{
 315        unsigned int changed;
 316        int ignore_valid = options & CE_MATCH_IGNORE_VALID;
 317        int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
 318        int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
 319        int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
 320
 321        if (!ignore_fsmonitor)
 322                refresh_fsmonitor(istate);
 323        /*
 324         * If it's marked as always valid in the index, it's
 325         * valid whatever the checked-out copy says.
 326         *
 327         * skip-worktree has the same effect with higher precedence
 328         */
 329        if (!ignore_skip_worktree && ce_skip_worktree(ce))
 330                return 0;
 331        if (!ignore_valid && (ce->ce_flags & CE_VALID))
 332                return 0;
 333        if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
 334                return 0;
 335
 336        /*
 337         * Intent-to-add entries have not been added, so the index entry
 338         * by definition never matches what is in the work tree until it
 339         * actually gets added.
 340         */
 341        if (ce_intent_to_add(ce))
 342                return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
 343
 344        changed = ce_match_stat_basic(ce, st);
 345
 346        /*
 347         * Within 1 second of this sequence:
 348         *      echo xyzzy >file && git-update-index --add file
 349         * running this command:
 350         *      echo frotz >file
 351         * would give a falsely clean cache entry.  The mtime and
 352         * length match the cache, and other stat fields do not change.
 353         *
 354         * We could detect this at update-index time (the cache entry
 355         * being registered/updated records the same time as "now")
 356         * and delay the return from git-update-index, but that would
 357         * effectively mean we can make at most one commit per second,
 358         * which is not acceptable.  Instead, we check cache entries
 359         * whose mtime are the same as the index file timestamp more
 360         * carefully than others.
 361         */
 362        if (!changed && is_racy_timestamp(istate, ce)) {
 363                if (assume_racy_is_modified)
 364                        changed |= DATA_CHANGED;
 365                else
 366                        changed |= ce_modified_check_fs(ce, st);
 367        }
 368
 369        return changed;
 370}
 371
 372int ie_modified(struct index_state *istate,
 373                const struct cache_entry *ce,
 374                struct stat *st, unsigned int options)
 375{
 376        int changed, changed_fs;
 377
 378        changed = ie_match_stat(istate, ce, st, options);
 379        if (!changed)
 380                return 0;
 381        /*
 382         * If the mode or type has changed, there's no point in trying
 383         * to refresh the entry - it's not going to match
 384         */
 385        if (changed & (MODE_CHANGED | TYPE_CHANGED))
 386                return changed;
 387
 388        /*
 389         * Immediately after read-tree or update-index --cacheinfo,
 390         * the length field is zero, as we have never even read the
 391         * lstat(2) information once, and we cannot trust DATA_CHANGED
 392         * returned by ie_match_stat() which in turn was returned by
 393         * ce_match_stat_basic() to signal that the filesize of the
 394         * blob changed.  We have to actually go to the filesystem to
 395         * see if the contents match, and if so, should answer "unchanged".
 396         *
 397         * The logic does not apply to gitlinks, as ce_match_stat_basic()
 398         * already has checked the actual HEAD from the filesystem in the
 399         * subproject.  If ie_match_stat() already said it is different,
 400         * then we know it is.
 401         */
 402        if ((changed & DATA_CHANGED) &&
 403            (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
 404                return changed;
 405
 406        changed_fs = ce_modified_check_fs(ce, st);
 407        if (changed_fs)
 408                return changed | changed_fs;
 409        return 0;
 410}
 411
 412int base_name_compare(const char *name1, int len1, int mode1,
 413                      const char *name2, int len2, int mode2)
 414{
 415        unsigned char c1, c2;
 416        int len = len1 < len2 ? len1 : len2;
 417        int cmp;
 418
 419        cmp = memcmp(name1, name2, len);
 420        if (cmp)
 421                return cmp;
 422        c1 = name1[len];
 423        c2 = name2[len];
 424        if (!c1 && S_ISDIR(mode1))
 425                c1 = '/';
 426        if (!c2 && S_ISDIR(mode2))
 427                c2 = '/';
 428        return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
 429}
 430
 431/*
 432 * df_name_compare() is identical to base_name_compare(), except it
 433 * compares conflicting directory/file entries as equal. Note that
 434 * while a directory name compares as equal to a regular file, they
 435 * then individually compare _differently_ to a filename that has
 436 * a dot after the basename (because '\0' < '.' < '/').
 437 *
 438 * This is used by routines that want to traverse the git namespace
 439 * but then handle conflicting entries together when possible.
 440 */
 441int df_name_compare(const char *name1, int len1, int mode1,
 442                    const char *name2, int len2, int mode2)
 443{
 444        int len = len1 < len2 ? len1 : len2, cmp;
 445        unsigned char c1, c2;
 446
 447        cmp = memcmp(name1, name2, len);
 448        if (cmp)
 449                return cmp;
 450        /* Directories and files compare equal (same length, same name) */
 451        if (len1 == len2)
 452                return 0;
 453        c1 = name1[len];
 454        if (!c1 && S_ISDIR(mode1))
 455                c1 = '/';
 456        c2 = name2[len];
 457        if (!c2 && S_ISDIR(mode2))
 458                c2 = '/';
 459        if (c1 == '/' && !c2)
 460                return 0;
 461        if (c2 == '/' && !c1)
 462                return 0;
 463        return c1 - c2;
 464}
 465
 466int name_compare(const char *name1, size_t len1, const char *name2, size_t len2)
 467{
 468        size_t min_len = (len1 < len2) ? len1 : len2;
 469        int cmp = memcmp(name1, name2, min_len);
 470        if (cmp)
 471                return cmp;
 472        if (len1 < len2)
 473                return -1;
 474        if (len1 > len2)
 475                return 1;
 476        return 0;
 477}
 478
 479int cache_name_stage_compare(const char *name1, int len1, int stage1, const char *name2, int len2, int stage2)
 480{
 481        int cmp;
 482
 483        cmp = name_compare(name1, len1, name2, len2);
 484        if (cmp)
 485                return cmp;
 486
 487        if (stage1 < stage2)
 488                return -1;
 489        if (stage1 > stage2)
 490                return 1;
 491        return 0;
 492}
 493
 494static int index_name_stage_pos(const struct index_state *istate, const char *name, int namelen, int stage)
 495{
 496        int first, last;
 497
 498        first = 0;
 499        last = istate->cache_nr;
 500        while (last > first) {
 501                int next = (last + first) >> 1;
 502                struct cache_entry *ce = istate->cache[next];
 503                int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
 504                if (!cmp)
 505                        return next;
 506                if (cmp < 0) {
 507                        last = next;
 508                        continue;
 509                }
 510                first = next+1;
 511        }
 512        return -first-1;
 513}
 514
 515int index_name_pos(const struct index_state *istate, const char *name, int namelen)
 516{
 517        return index_name_stage_pos(istate, name, namelen, 0);
 518}
 519
 520int remove_index_entry_at(struct index_state *istate, int pos)
 521{
 522        struct cache_entry *ce = istate->cache[pos];
 523
 524        record_resolve_undo(istate, ce);
 525        remove_name_hash(istate, ce);
 526        save_or_free_index_entry(istate, ce);
 527        istate->cache_changed |= CE_ENTRY_REMOVED;
 528        istate->cache_nr--;
 529        if (pos >= istate->cache_nr)
 530                return 0;
 531        MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
 532                   istate->cache_nr - pos);
 533        return 1;
 534}
 535
 536/*
 537 * Remove all cache entries marked for removal, that is where
 538 * CE_REMOVE is set in ce_flags.  This is much more effective than
 539 * calling remove_index_entry_at() for each entry to be removed.
 540 */
 541void remove_marked_cache_entries(struct index_state *istate)
 542{
 543        struct cache_entry **ce_array = istate->cache;
 544        unsigned int i, j;
 545
 546        for (i = j = 0; i < istate->cache_nr; i++) {
 547                if (ce_array[i]->ce_flags & CE_REMOVE) {
 548                        remove_name_hash(istate, ce_array[i]);
 549                        save_or_free_index_entry(istate, ce_array[i]);
 550                }
 551                else
 552                        ce_array[j++] = ce_array[i];
 553        }
 554        if (j == istate->cache_nr)
 555                return;
 556        istate->cache_changed |= CE_ENTRY_REMOVED;
 557        istate->cache_nr = j;
 558}
 559
 560int remove_file_from_index(struct index_state *istate, const char *path)
 561{
 562        int pos = index_name_pos(istate, path, strlen(path));
 563        if (pos < 0)
 564                pos = -pos-1;
 565        cache_tree_invalidate_path(istate, path);
 566        untracked_cache_remove_from_index(istate, path);
 567        while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
 568                remove_index_entry_at(istate, pos);
 569        return 0;
 570}
 571
 572static int compare_name(struct cache_entry *ce, const char *path, int namelen)
 573{
 574        return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
 575}
 576
 577static int index_name_pos_also_unmerged(struct index_state *istate,
 578        const char *path, int namelen)
 579{
 580        int pos = index_name_pos(istate, path, namelen);
 581        struct cache_entry *ce;
 582
 583        if (pos >= 0)
 584                return pos;
 585
 586        /* maybe unmerged? */
 587        pos = -1 - pos;
 588        if (pos >= istate->cache_nr ||
 589                        compare_name((ce = istate->cache[pos]), path, namelen))
 590                return -1;
 591
 592        /* order of preference: stage 2, 1, 3 */
 593        if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
 594                        ce_stage((ce = istate->cache[pos + 1])) == 2 &&
 595                        !compare_name(ce, path, namelen))
 596                pos++;
 597        return pos;
 598}
 599
 600static int different_name(struct cache_entry *ce, struct cache_entry *alias)
 601{
 602        int len = ce_namelen(ce);
 603        return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
 604}
 605
 606/*
 607 * If we add a filename that aliases in the cache, we will use the
 608 * name that we already have - but we don't want to update the same
 609 * alias twice, because that implies that there were actually two
 610 * different files with aliasing names!
 611 *
 612 * So we use the CE_ADDED flag to verify that the alias was an old
 613 * one before we accept it as
 614 */
 615static struct cache_entry *create_alias_ce(struct index_state *istate,
 616                                           struct cache_entry *ce,
 617                                           struct cache_entry *alias)
 618{
 619        int len;
 620        struct cache_entry *new_entry;
 621
 622        if (alias->ce_flags & CE_ADDED)
 623                die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
 624
 625        /* Ok, create the new entry using the name of the existing alias */
 626        len = ce_namelen(alias);
 627        new_entry = xcalloc(1, cache_entry_size(len));
 628        memcpy(new_entry->name, alias->name, len);
 629        copy_cache_entry(new_entry, ce);
 630        save_or_free_index_entry(istate, ce);
 631        return new_entry;
 632}
 633
 634void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
 635{
 636        struct object_id oid;
 637        if (write_object_file("", 0, blob_type, &oid))
 638                die("cannot create an empty blob in the object database");
 639        oidcpy(&ce->oid, &oid);
 640}
 641
 642int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
 643{
 644        int size, namelen, was_same;
 645        mode_t st_mode = st->st_mode;
 646        struct cache_entry *ce, *alias = NULL;
 647        unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
 648        int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
 649        int pretend = flags & ADD_CACHE_PRETEND;
 650        int intent_only = flags & ADD_CACHE_INTENT;
 651        int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
 652                          (intent_only ? ADD_CACHE_NEW_ONLY : 0));
 653        int newflags = HASH_WRITE_OBJECT;
 654
 655        if (flags & HASH_RENORMALIZE)
 656                newflags |= HASH_RENORMALIZE;
 657
 658        if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
 659                return error("%s: can only add regular files, symbolic links or git-directories", path);
 660
 661        namelen = strlen(path);
 662        if (S_ISDIR(st_mode)) {
 663                while (namelen && path[namelen-1] == '/')
 664                        namelen--;
 665        }
 666        size = cache_entry_size(namelen);
 667        ce = xcalloc(1, size);
 668        memcpy(ce->name, path, namelen);
 669        ce->ce_namelen = namelen;
 670        if (!intent_only)
 671                fill_stat_cache_info(ce, st);
 672        else
 673                ce->ce_flags |= CE_INTENT_TO_ADD;
 674
 675
 676        if (trust_executable_bit && has_symlinks) {
 677                ce->ce_mode = create_ce_mode(st_mode);
 678        } else {
 679                /* If there is an existing entry, pick the mode bits and type
 680                 * from it, otherwise assume unexecutable regular file.
 681                 */
 682                struct cache_entry *ent;
 683                int pos = index_name_pos_also_unmerged(istate, path, namelen);
 684
 685                ent = (0 <= pos) ? istate->cache[pos] : NULL;
 686                ce->ce_mode = ce_mode_from_stat(ent, st_mode);
 687        }
 688
 689        /* When core.ignorecase=true, determine if a directory of the same name but differing
 690         * case already exists within the Git repository.  If it does, ensure the directory
 691         * case of the file being added to the repository matches (is folded into) the existing
 692         * entry's directory case.
 693         */
 694        if (ignore_case) {
 695                adjust_dirname_case(istate, ce->name);
 696        }
 697        if (!(flags & HASH_RENORMALIZE)) {
 698                alias = index_file_exists(istate, ce->name,
 699                                          ce_namelen(ce), ignore_case);
 700                if (alias &&
 701                    !ce_stage(alias) &&
 702                    !ie_match_stat(istate, alias, st, ce_option)) {
 703                        /* Nothing changed, really */
 704                        if (!S_ISGITLINK(alias->ce_mode))
 705                                ce_mark_uptodate(alias);
 706                        alias->ce_flags |= CE_ADDED;
 707
 708                        free(ce);
 709                        return 0;
 710                }
 711        }
 712        if (!intent_only) {
 713                if (index_path(&ce->oid, path, st, newflags)) {
 714                        free(ce);
 715                        return error("unable to index file %s", path);
 716                }
 717        } else
 718                set_object_name_for_intent_to_add_entry(ce);
 719
 720        if (ignore_case && alias && different_name(ce, alias))
 721                ce = create_alias_ce(istate, ce, alias);
 722        ce->ce_flags |= CE_ADDED;
 723
 724        /* It was suspected to be racily clean, but it turns out to be Ok */
 725        was_same = (alias &&
 726                    !ce_stage(alias) &&
 727                    !oidcmp(&alias->oid, &ce->oid) &&
 728                    ce->ce_mode == alias->ce_mode);
 729
 730        if (pretend)
 731                free(ce);
 732        else if (add_index_entry(istate, ce, add_option)) {
 733                free(ce);
 734                return error("unable to add %s to index", path);
 735        }
 736        if (verbose && !was_same)
 737                printf("add '%s'\n", path);
 738        return 0;
 739}
 740
 741int add_file_to_index(struct index_state *istate, const char *path, int flags)
 742{
 743        struct stat st;
 744        if (lstat(path, &st))
 745                die_errno("unable to stat '%s'", path);
 746        return add_to_index(istate, path, &st, flags);
 747}
 748
 749struct cache_entry *make_cache_entry(unsigned int mode,
 750                const unsigned char *sha1, const char *path, int stage,
 751                unsigned int refresh_options)
 752{
 753        int size, len;
 754        struct cache_entry *ce, *ret;
 755
 756        if (!verify_path(path)) {
 757                error("Invalid path '%s'", path);
 758                return NULL;
 759        }
 760
 761        len = strlen(path);
 762        size = cache_entry_size(len);
 763        ce = xcalloc(1, size);
 764
 765        hashcpy(ce->oid.hash, sha1);
 766        memcpy(ce->name, path, len);
 767        ce->ce_flags = create_ce_flags(stage);
 768        ce->ce_namelen = len;
 769        ce->ce_mode = create_ce_mode(mode);
 770
 771        ret = refresh_cache_entry(ce, refresh_options);
 772        if (ret != ce)
 773                free(ce);
 774        return ret;
 775}
 776
 777/*
 778 * Chmod an index entry with either +x or -x.
 779 *
 780 * Returns -1 if the chmod for the particular cache entry failed (if it's
 781 * not a regular file), -2 if an invalid flip argument is passed in, 0
 782 * otherwise.
 783 */
 784int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
 785                      char flip)
 786{
 787        if (!S_ISREG(ce->ce_mode))
 788                return -1;
 789        switch (flip) {
 790        case '+':
 791                ce->ce_mode |= 0111;
 792                break;
 793        case '-':
 794                ce->ce_mode &= ~0111;
 795                break;
 796        default:
 797                return -2;
 798        }
 799        cache_tree_invalidate_path(istate, ce->name);
 800        ce->ce_flags |= CE_UPDATE_IN_BASE;
 801        mark_fsmonitor_invalid(istate, ce);
 802        istate->cache_changed |= CE_ENTRY_CHANGED;
 803
 804        return 0;
 805}
 806
 807int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
 808{
 809        int len = ce_namelen(a);
 810        return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
 811}
 812
 813/*
 814 * We fundamentally don't like some paths: we don't want
 815 * dot or dot-dot anywhere, and for obvious reasons don't
 816 * want to recurse into ".git" either.
 817 *
 818 * Also, we don't want double slashes or slashes at the
 819 * end that can make pathnames ambiguous.
 820 */
 821static int verify_dotfile(const char *rest)
 822{
 823        /*
 824         * The first character was '.', but that
 825         * has already been discarded, we now test
 826         * the rest.
 827         */
 828
 829        /* "." is not allowed */
 830        if (*rest == '\0' || is_dir_sep(*rest))
 831                return 0;
 832
 833        switch (*rest) {
 834        /*
 835         * ".git" followed by  NUL or slash is bad. This
 836         * shares the path end test with the ".." case.
 837         */
 838        case 'g':
 839        case 'G':
 840                if (rest[1] != 'i' && rest[1] != 'I')
 841                        break;
 842                if (rest[2] != 't' && rest[2] != 'T')
 843                        break;
 844                rest += 2;
 845        /* fallthrough */
 846        case '.':
 847                if (rest[1] == '\0' || is_dir_sep(rest[1]))
 848                        return 0;
 849        }
 850        return 1;
 851}
 852
 853int verify_path(const char *path)
 854{
 855        char c;
 856
 857        if (has_dos_drive_prefix(path))
 858                return 0;
 859
 860        goto inside;
 861        for (;;) {
 862                if (!c)
 863                        return 1;
 864                if (is_dir_sep(c)) {
 865inside:
 866                        if (protect_hfs && is_hfs_dotgit(path))
 867                                return 0;
 868                        if (protect_ntfs && is_ntfs_dotgit(path))
 869                                return 0;
 870                        c = *path++;
 871                        if ((c == '.' && !verify_dotfile(path)) ||
 872                            is_dir_sep(c) || c == '\0')
 873                                return 0;
 874                }
 875                c = *path++;
 876        }
 877}
 878
 879/*
 880 * Do we have another file that has the beginning components being a
 881 * proper superset of the name we're trying to add?
 882 */
 883static int has_file_name(struct index_state *istate,
 884                         const struct cache_entry *ce, int pos, int ok_to_replace)
 885{
 886        int retval = 0;
 887        int len = ce_namelen(ce);
 888        int stage = ce_stage(ce);
 889        const char *name = ce->name;
 890
 891        while (pos < istate->cache_nr) {
 892                struct cache_entry *p = istate->cache[pos++];
 893
 894                if (len >= ce_namelen(p))
 895                        break;
 896                if (memcmp(name, p->name, len))
 897                        break;
 898                if (ce_stage(p) != stage)
 899                        continue;
 900                if (p->name[len] != '/')
 901                        continue;
 902                if (p->ce_flags & CE_REMOVE)
 903                        continue;
 904                retval = -1;
 905                if (!ok_to_replace)
 906                        break;
 907                remove_index_entry_at(istate, --pos);
 908        }
 909        return retval;
 910}
 911
 912
 913/*
 914 * Like strcmp(), but also return the offset of the first change.
 915 * If strings are equal, return the length.
 916 */
 917int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
 918{
 919        size_t k;
 920
 921        if (!first_change)
 922                return strcmp(s1, s2);
 923
 924        for (k = 0; s1[k] == s2[k]; k++)
 925                if (s1[k] == '\0')
 926                        break;
 927
 928        *first_change = k;
 929        return (unsigned char)s1[k] - (unsigned char)s2[k];
 930}
 931
 932/*
 933 * Do we have another file with a pathname that is a proper
 934 * subset of the name we're trying to add?
 935 *
 936 * That is, is there another file in the index with a path
 937 * that matches a sub-directory in the given entry?
 938 */
 939static int has_dir_name(struct index_state *istate,
 940                        const struct cache_entry *ce, int pos, int ok_to_replace)
 941{
 942        int retval = 0;
 943        int stage = ce_stage(ce);
 944        const char *name = ce->name;
 945        const char *slash = name + ce_namelen(ce);
 946        size_t len_eq_last;
 947        int cmp_last = 0;
 948
 949        /*
 950         * We are frequently called during an iteration on a sorted
 951         * list of pathnames and while building a new index.  Therefore,
 952         * there is a high probability that this entry will eventually
 953         * be appended to the index, rather than inserted in the middle.
 954         * If we can confirm that, we can avoid binary searches on the
 955         * components of the pathname.
 956         *
 957         * Compare the entry's full path with the last path in the index.
 958         */
 959        if (istate->cache_nr > 0) {
 960                cmp_last = strcmp_offset(name,
 961                        istate->cache[istate->cache_nr - 1]->name,
 962                        &len_eq_last);
 963                if (cmp_last > 0) {
 964                        if (len_eq_last == 0) {
 965                                /*
 966                                 * The entry sorts AFTER the last one in the
 967                                 * index and their paths have no common prefix,
 968                                 * so there cannot be a F/D conflict.
 969                                 */
 970                                return retval;
 971                        } else {
 972                                /*
 973                                 * The entry sorts AFTER the last one in the
 974                                 * index, but has a common prefix.  Fall through
 975                                 * to the loop below to disect the entry's path
 976                                 * and see where the difference is.
 977                                 */
 978                        }
 979                } else if (cmp_last == 0) {
 980                        /*
 981                         * The entry exactly matches the last one in the
 982                         * index, but because of multiple stage and CE_REMOVE
 983                         * items, we fall through and let the regular search
 984                         * code handle it.
 985                         */
 986                }
 987        }
 988
 989        for (;;) {
 990                size_t len;
 991
 992                for (;;) {
 993                        if (*--slash == '/')
 994                                break;
 995                        if (slash <= ce->name)
 996                                return retval;
 997                }
 998                len = slash - name;
 999
1000                if (cmp_last > 0) {
1001                        /*
1002                         * (len + 1) is a directory boundary (including
1003                         * the trailing slash).  And since the loop is
1004                         * decrementing "slash", the first iteration is
1005                         * the longest directory prefix; subsequent
1006                         * iterations consider parent directories.
1007                         */
1008
1009                        if (len + 1 <= len_eq_last) {
1010                                /*
1011                                 * The directory prefix (including the trailing
1012                                 * slash) also appears as a prefix in the last
1013                                 * entry, so the remainder cannot collide (because
1014                                 * strcmp said the whole path was greater).
1015                                 *
1016                                 * EQ: last: xxx/A
1017                                 *     this: xxx/B
1018                                 *
1019                                 * LT: last: xxx/file_A
1020                                 *     this: xxx/file_B
1021                                 */
1022                                return retval;
1023                        }
1024
1025                        if (len > len_eq_last) {
1026                                /*
1027                                 * This part of the directory prefix (excluding
1028                                 * the trailing slash) is longer than the known
1029                                 * equal portions, so this sub-directory cannot
1030                                 * collide with a file.
1031                                 *
1032                                 * GT: last: xxxA
1033                                 *     this: xxxB/file
1034                                 */
1035                                return retval;
1036                        }
1037
1038                        if (istate->cache_nr > 0 &&
1039                                ce_namelen(istate->cache[istate->cache_nr - 1]) > len) {
1040                                /*
1041                                 * The directory prefix lines up with part of
1042                                 * a longer file or directory name, but sorts
1043                                 * after it, so this sub-directory cannot
1044                                 * collide with a file.
1045                                 *
1046                                 * last: xxx/yy-file (because '-' sorts before '/')
1047                                 * this: xxx/yy/abc
1048                                 */
1049                                return retval;
1050                        }
1051
1052                        /*
1053                         * This is a possible collision. Fall through and
1054                         * let the regular search code handle it.
1055                         *
1056                         * last: xxx
1057                         * this: xxx/file
1058                         */
1059                }
1060
1061                pos = index_name_stage_pos(istate, name, len, stage);
1062                if (pos >= 0) {
1063                        /*
1064                         * Found one, but not so fast.  This could
1065                         * be a marker that says "I was here, but
1066                         * I am being removed".  Such an entry is
1067                         * not a part of the resulting tree, and
1068                         * it is Ok to have a directory at the same
1069                         * path.
1070                         */
1071                        if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
1072                                retval = -1;
1073                                if (!ok_to_replace)
1074                                        break;
1075                                remove_index_entry_at(istate, pos);
1076                                continue;
1077                        }
1078                }
1079                else
1080                        pos = -pos-1;
1081
1082                /*
1083                 * Trivial optimization: if we find an entry that
1084                 * already matches the sub-directory, then we know
1085                 * we're ok, and we can exit.
1086                 */
1087                while (pos < istate->cache_nr) {
1088                        struct cache_entry *p = istate->cache[pos];
1089                        if ((ce_namelen(p) <= len) ||
1090                            (p->name[len] != '/') ||
1091                            memcmp(p->name, name, len))
1092                                break; /* not our subdirectory */
1093                        if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1094                                /*
1095                                 * p is at the same stage as our entry, and
1096                                 * is a subdirectory of what we are looking
1097                                 * at, so we cannot have conflicts at our
1098                                 * level or anything shorter.
1099                                 */
1100                                return retval;
1101                        pos++;
1102                }
1103        }
1104        return retval;
1105}
1106
1107/* We may be in a situation where we already have path/file and path
1108 * is being added, or we already have path and path/file is being
1109 * added.  Either one would result in a nonsense tree that has path
1110 * twice when git-write-tree tries to write it out.  Prevent it.
1111 *
1112 * If ok-to-replace is specified, we remove the conflicting entries
1113 * from the cache so the caller should recompute the insert position.
1114 * When this happens, we return non-zero.
1115 */
1116static int check_file_directory_conflict(struct index_state *istate,
1117                                         const struct cache_entry *ce,
1118                                         int pos, int ok_to_replace)
1119{
1120        int retval;
1121
1122        /*
1123         * When ce is an "I am going away" entry, we allow it to be added
1124         */
1125        if (ce->ce_flags & CE_REMOVE)
1126                return 0;
1127
1128        /*
1129         * We check if the path is a sub-path of a subsequent pathname
1130         * first, since removing those will not change the position
1131         * in the array.
1132         */
1133        retval = has_file_name(istate, ce, pos, ok_to_replace);
1134
1135        /*
1136         * Then check if the path might have a clashing sub-directory
1137         * before it.
1138         */
1139        return retval + has_dir_name(istate, ce, pos, ok_to_replace);
1140}
1141
1142static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
1143{
1144        int pos;
1145        int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1146        int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
1147        int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
1148        int new_only = option & ADD_CACHE_NEW_ONLY;
1149
1150        if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1151                cache_tree_invalidate_path(istate, ce->name);
1152
1153        /*
1154         * If this entry's path sorts after the last entry in the index,
1155         * we can avoid searching for it.
1156         */
1157        if (istate->cache_nr > 0 &&
1158                strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1159                pos = -istate->cache_nr - 1;
1160        else
1161                pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
1162
1163        /* existing match? Just replace it. */
1164        if (pos >= 0) {
1165                if (!new_only)
1166                        replace_index_entry(istate, pos, ce);
1167                return 0;
1168        }
1169        pos = -pos-1;
1170
1171        if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1172                untracked_cache_add_to_index(istate, ce->name);
1173
1174        /*
1175         * Inserting a merged entry ("stage 0") into the index
1176         * will always replace all non-merged entries..
1177         */
1178        if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1179                while (ce_same_name(istate->cache[pos], ce)) {
1180                        ok_to_add = 1;
1181                        if (!remove_index_entry_at(istate, pos))
1182                                break;
1183                }
1184        }
1185
1186        if (!ok_to_add)
1187                return -1;
1188        if (!verify_path(ce->name))
1189                return error("Invalid path '%s'", ce->name);
1190
1191        if (!skip_df_check &&
1192            check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
1193                if (!ok_to_replace)
1194                        return error("'%s' appears as both a file and as a directory",
1195                                     ce->name);
1196                pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
1197                pos = -pos-1;
1198        }
1199        return pos + 1;
1200}
1201
1202int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1203{
1204        int pos;
1205
1206        if (option & ADD_CACHE_JUST_APPEND)
1207                pos = istate->cache_nr;
1208        else {
1209                int ret;
1210                ret = add_index_entry_with_check(istate, ce, option);
1211                if (ret <= 0)
1212                        return ret;
1213                pos = ret - 1;
1214        }
1215
1216        /* Make sure the array is big enough .. */
1217        ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1218
1219        /* Add it in.. */
1220        istate->cache_nr++;
1221        if (istate->cache_nr > pos + 1)
1222                MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1223                           istate->cache_nr - pos - 1);
1224        set_index_entry(istate, pos, ce);
1225        istate->cache_changed |= CE_ENTRY_ADDED;
1226        return 0;
1227}
1228
1229/*
1230 * "refresh" does not calculate a new sha1 file or bring the
1231 * cache up-to-date for mode/content changes. But what it
1232 * _does_ do is to "re-match" the stat information of a file
1233 * with the cache, so that you can refresh the cache for a
1234 * file that hasn't been changed but where the stat entry is
1235 * out of date.
1236 *
1237 * For example, you'd want to do this after doing a "git-read-tree",
1238 * to link up the stat cache details with the proper files.
1239 */
1240static struct cache_entry *refresh_cache_ent(struct index_state *istate,
1241                                             struct cache_entry *ce,
1242                                             unsigned int options, int *err,
1243                                             int *changed_ret)
1244{
1245        struct stat st;
1246        struct cache_entry *updated;
1247        int changed, size;
1248        int refresh = options & CE_MATCH_REFRESH;
1249        int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1250        int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
1251        int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
1252        int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
1253
1254        if (!refresh || ce_uptodate(ce))
1255                return ce;
1256
1257        if (!ignore_fsmonitor)
1258                refresh_fsmonitor(istate);
1259        /*
1260         * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1261         * that the change to the work tree does not matter and told
1262         * us not to worry.
1263         */
1264        if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1265                ce_mark_uptodate(ce);
1266                return ce;
1267        }
1268        if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1269                ce_mark_uptodate(ce);
1270                return ce;
1271        }
1272        if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
1273                ce_mark_uptodate(ce);
1274                return ce;
1275        }
1276
1277        if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
1278                if (ignore_missing)
1279                        return ce;
1280                if (err)
1281                        *err = ENOENT;
1282                return NULL;
1283        }
1284
1285        if (lstat(ce->name, &st) < 0) {
1286                if (ignore_missing && errno == ENOENT)
1287                        return ce;
1288                if (err)
1289                        *err = errno;
1290                return NULL;
1291        }
1292
1293        changed = ie_match_stat(istate, ce, &st, options);
1294        if (changed_ret)
1295                *changed_ret = changed;
1296        if (!changed) {
1297                /*
1298                 * The path is unchanged.  If we were told to ignore
1299                 * valid bit, then we did the actual stat check and
1300                 * found that the entry is unmodified.  If the entry
1301                 * is not marked VALID, this is the place to mark it
1302                 * valid again, under "assume unchanged" mode.
1303                 */
1304                if (ignore_valid && assume_unchanged &&
1305                    !(ce->ce_flags & CE_VALID))
1306                        ; /* mark this one VALID again */
1307                else {
1308                        /*
1309                         * We do not mark the index itself "modified"
1310                         * because CE_UPTODATE flag is in-core only;
1311                         * we are not going to write this change out.
1312                         */
1313                        if (!S_ISGITLINK(ce->ce_mode)) {
1314                                ce_mark_uptodate(ce);
1315                                mark_fsmonitor_valid(ce);
1316                        }
1317                        return ce;
1318                }
1319        }
1320
1321        if (ie_modified(istate, ce, &st, options)) {
1322                if (err)
1323                        *err = EINVAL;
1324                return NULL;
1325        }
1326
1327        size = ce_size(ce);
1328        updated = xmalloc(size);
1329        copy_cache_entry(updated, ce);
1330        memcpy(updated->name, ce->name, ce->ce_namelen + 1);
1331        fill_stat_cache_info(updated, &st);
1332        /*
1333         * If ignore_valid is not set, we should leave CE_VALID bit
1334         * alone.  Otherwise, paths marked with --no-assume-unchanged
1335         * (i.e. things to be edited) will reacquire CE_VALID bit
1336         * automatically, which is not really what we want.
1337         */
1338        if (!ignore_valid && assume_unchanged &&
1339            !(ce->ce_flags & CE_VALID))
1340                updated->ce_flags &= ~CE_VALID;
1341
1342        /* istate->cache_changed is updated in the caller */
1343        return updated;
1344}
1345
1346static void show_file(const char * fmt, const char * name, int in_porcelain,
1347                      int * first, const char *header_msg)
1348{
1349        if (in_porcelain && *first && header_msg) {
1350                printf("%s\n", header_msg);
1351                *first = 0;
1352        }
1353        printf(fmt, name);
1354}
1355
1356int refresh_index(struct index_state *istate, unsigned int flags,
1357                  const struct pathspec *pathspec,
1358                  char *seen, const char *header_msg)
1359{
1360        int i;
1361        int has_errors = 0;
1362        int really = (flags & REFRESH_REALLY) != 0;
1363        int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1364        int quiet = (flags & REFRESH_QUIET) != 0;
1365        int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1366        int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1367        int first = 1;
1368        int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1369        unsigned int options = (CE_MATCH_REFRESH |
1370                                (really ? CE_MATCH_IGNORE_VALID : 0) |
1371                                (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1372        const char *modified_fmt;
1373        const char *deleted_fmt;
1374        const char *typechange_fmt;
1375        const char *added_fmt;
1376        const char *unmerged_fmt;
1377        uint64_t start = getnanotime();
1378
1379        modified_fmt = (in_porcelain ? "M\t%s\n" : "%s: needs update\n");
1380        deleted_fmt = (in_porcelain ? "D\t%s\n" : "%s: needs update\n");
1381        typechange_fmt = (in_porcelain ? "T\t%s\n" : "%s needs update\n");
1382        added_fmt = (in_porcelain ? "A\t%s\n" : "%s needs update\n");
1383        unmerged_fmt = (in_porcelain ? "U\t%s\n" : "%s: needs merge\n");
1384        for (i = 0; i < istate->cache_nr; i++) {
1385                struct cache_entry *ce, *new_entry;
1386                int cache_errno = 0;
1387                int changed = 0;
1388                int filtered = 0;
1389
1390                ce = istate->cache[i];
1391                if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1392                        continue;
1393
1394                if (pathspec && !ce_path_match(ce, pathspec, seen))
1395                        filtered = 1;
1396
1397                if (ce_stage(ce)) {
1398                        while ((i < istate->cache_nr) &&
1399                               ! strcmp(istate->cache[i]->name, ce->name))
1400                                i++;
1401                        i--;
1402                        if (allow_unmerged)
1403                                continue;
1404                        if (!filtered)
1405                                show_file(unmerged_fmt, ce->name, in_porcelain,
1406                                          &first, header_msg);
1407                        has_errors = 1;
1408                        continue;
1409                }
1410
1411                if (filtered)
1412                        continue;
1413
1414                new_entry = refresh_cache_ent(istate, ce, options, &cache_errno, &changed);
1415                if (new_entry == ce)
1416                        continue;
1417                if (!new_entry) {
1418                        const char *fmt;
1419
1420                        if (really && cache_errno == EINVAL) {
1421                                /* If we are doing --really-refresh that
1422                                 * means the index is not valid anymore.
1423                                 */
1424                                ce->ce_flags &= ~CE_VALID;
1425                                ce->ce_flags |= CE_UPDATE_IN_BASE;
1426                                mark_fsmonitor_invalid(istate, ce);
1427                                istate->cache_changed |= CE_ENTRY_CHANGED;
1428                        }
1429                        if (quiet)
1430                                continue;
1431
1432                        if (cache_errno == ENOENT)
1433                                fmt = deleted_fmt;
1434                        else if (ce_intent_to_add(ce))
1435                                fmt = added_fmt; /* must be before other checks */
1436                        else if (changed & TYPE_CHANGED)
1437                                fmt = typechange_fmt;
1438                        else
1439                                fmt = modified_fmt;
1440                        show_file(fmt,
1441                                  ce->name, in_porcelain, &first, header_msg);
1442                        has_errors = 1;
1443                        continue;
1444                }
1445
1446                replace_index_entry(istate, i, new_entry);
1447        }
1448        trace_performance_since(start, "refresh index");
1449        return has_errors;
1450}
1451
1452struct cache_entry *refresh_cache_entry(struct cache_entry *ce,
1453                                               unsigned int options)
1454{
1455        return refresh_cache_ent(&the_index, ce, options, NULL, NULL);
1456}
1457
1458
1459/*****************************************************************
1460 * Index File I/O
1461 *****************************************************************/
1462
1463#define INDEX_FORMAT_DEFAULT 3
1464
1465static unsigned int get_index_format_default(void)
1466{
1467        char *envversion = getenv("GIT_INDEX_VERSION");
1468        char *endp;
1469        int value;
1470        unsigned int version = INDEX_FORMAT_DEFAULT;
1471
1472        if (!envversion) {
1473                if (!git_config_get_int("index.version", &value))
1474                        version = value;
1475                if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1476                        warning(_("index.version set, but the value is invalid.\n"
1477                                  "Using version %i"), INDEX_FORMAT_DEFAULT);
1478                        return INDEX_FORMAT_DEFAULT;
1479                }
1480                return version;
1481        }
1482
1483        version = strtoul(envversion, &endp, 10);
1484        if (*endp ||
1485            version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1486                warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1487                          "Using version %i"), INDEX_FORMAT_DEFAULT);
1488                version = INDEX_FORMAT_DEFAULT;
1489        }
1490        return version;
1491}
1492
1493/*
1494 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1495 * Again - this is just a (very strong in practice) heuristic that
1496 * the inode hasn't changed.
1497 *
1498 * We save the fields in big-endian order to allow using the
1499 * index file over NFS transparently.
1500 */
1501struct ondisk_cache_entry {
1502        struct cache_time ctime;
1503        struct cache_time mtime;
1504        uint32_t dev;
1505        uint32_t ino;
1506        uint32_t mode;
1507        uint32_t uid;
1508        uint32_t gid;
1509        uint32_t size;
1510        unsigned char sha1[20];
1511        uint16_t flags;
1512        char name[FLEX_ARRAY]; /* more */
1513};
1514
1515/*
1516 * This struct is used when CE_EXTENDED bit is 1
1517 * The struct must match ondisk_cache_entry exactly from
1518 * ctime till flags
1519 */
1520struct ondisk_cache_entry_extended {
1521        struct cache_time ctime;
1522        struct cache_time mtime;
1523        uint32_t dev;
1524        uint32_t ino;
1525        uint32_t mode;
1526        uint32_t uid;
1527        uint32_t gid;
1528        uint32_t size;
1529        unsigned char sha1[20];
1530        uint16_t flags;
1531        uint16_t flags2;
1532        char name[FLEX_ARRAY]; /* more */
1533};
1534
1535/* These are only used for v3 or lower */
1536#define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
1537#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)
1538#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1539#define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)
1540#define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \
1541                            ondisk_cache_entry_extended_size(ce_namelen(ce)) : \
1542                            ondisk_cache_entry_size(ce_namelen(ce)))
1543
1544/* Allow fsck to force verification of the index checksum. */
1545int verify_index_checksum;
1546
1547/* Allow fsck to force verification of the cache entry order. */
1548int verify_ce_order;
1549
1550static int verify_hdr(struct cache_header *hdr, unsigned long size)
1551{
1552        git_hash_ctx c;
1553        unsigned char hash[GIT_MAX_RAWSZ];
1554        int hdr_version;
1555
1556        if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1557                return error("bad signature");
1558        hdr_version = ntohl(hdr->hdr_version);
1559        if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1560                return error("bad index version %d", hdr_version);
1561
1562        if (!verify_index_checksum)
1563                return 0;
1564
1565        the_hash_algo->init_fn(&c);
1566        the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
1567        the_hash_algo->final_fn(hash, &c);
1568        if (hashcmp(hash, (unsigned char *)hdr + size - the_hash_algo->rawsz))
1569                return error("bad index file sha1 signature");
1570        return 0;
1571}
1572
1573static int read_index_extension(struct index_state *istate,
1574                                const char *ext, void *data, unsigned long sz)
1575{
1576        switch (CACHE_EXT(ext)) {
1577        case CACHE_EXT_TREE:
1578                istate->cache_tree = cache_tree_read(data, sz);
1579                break;
1580        case CACHE_EXT_RESOLVE_UNDO:
1581                istate->resolve_undo = resolve_undo_read(data, sz);
1582                break;
1583        case CACHE_EXT_LINK:
1584                if (read_link_extension(istate, data, sz))
1585                        return -1;
1586                break;
1587        case CACHE_EXT_UNTRACKED:
1588                istate->untracked = read_untracked_extension(data, sz);
1589                break;
1590        case CACHE_EXT_FSMONITOR:
1591                read_fsmonitor_extension(istate, data, sz);
1592                break;
1593        default:
1594                if (*ext < 'A' || 'Z' < *ext)
1595                        return error("index uses %.4s extension, which we do not understand",
1596                                     ext);
1597                fprintf(stderr, "ignoring %.4s extension\n", ext);
1598                break;
1599        }
1600        return 0;
1601}
1602
1603int hold_locked_index(struct lock_file *lk, int lock_flags)
1604{
1605        return hold_lock_file_for_update(lk, get_index_file(), lock_flags);
1606}
1607
1608int read_index(struct index_state *istate)
1609{
1610        return read_index_from(istate, get_index_file(), get_git_dir());
1611}
1612
1613static struct cache_entry *cache_entry_from_ondisk(struct ondisk_cache_entry *ondisk,
1614                                                   unsigned int flags,
1615                                                   const char *name,
1616                                                   size_t len)
1617{
1618        struct cache_entry *ce = xmalloc(cache_entry_size(len));
1619
1620        ce->ce_stat_data.sd_ctime.sec = get_be32(&ondisk->ctime.sec);
1621        ce->ce_stat_data.sd_mtime.sec = get_be32(&ondisk->mtime.sec);
1622        ce->ce_stat_data.sd_ctime.nsec = get_be32(&ondisk->ctime.nsec);
1623        ce->ce_stat_data.sd_mtime.nsec = get_be32(&ondisk->mtime.nsec);
1624        ce->ce_stat_data.sd_dev   = get_be32(&ondisk->dev);
1625        ce->ce_stat_data.sd_ino   = get_be32(&ondisk->ino);
1626        ce->ce_mode  = get_be32(&ondisk->mode);
1627        ce->ce_stat_data.sd_uid   = get_be32(&ondisk->uid);
1628        ce->ce_stat_data.sd_gid   = get_be32(&ondisk->gid);
1629        ce->ce_stat_data.sd_size  = get_be32(&ondisk->size);
1630        ce->ce_flags = flags & ~CE_NAMEMASK;
1631        ce->ce_namelen = len;
1632        ce->index = 0;
1633        hashcpy(ce->oid.hash, ondisk->sha1);
1634        memcpy(ce->name, name, len);
1635        ce->name[len] = '\0';
1636        return ce;
1637}
1638
1639/*
1640 * Adjacent cache entries tend to share the leading paths, so it makes
1641 * sense to only store the differences in later entries.  In the v4
1642 * on-disk format of the index, each on-disk cache entry stores the
1643 * number of bytes to be stripped from the end of the previous name,
1644 * and the bytes to append to the result, to come up with its name.
1645 */
1646static unsigned long expand_name_field(struct strbuf *name, const char *cp_)
1647{
1648        const unsigned char *ep, *cp = (const unsigned char *)cp_;
1649        size_t len = decode_varint(&cp);
1650
1651        if (name->len < len)
1652                die("malformed name field in the index");
1653        strbuf_remove(name, name->len - len, len);
1654        for (ep = cp; *ep; ep++)
1655                ; /* find the end */
1656        strbuf_add(name, cp, ep - cp);
1657        return (const char *)ep + 1 - cp_;
1658}
1659
1660static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk,
1661                                            unsigned long *ent_size,
1662                                            struct strbuf *previous_name)
1663{
1664        struct cache_entry *ce;
1665        size_t len;
1666        const char *name;
1667        unsigned int flags;
1668
1669        /* On-disk flags are just 16 bits */
1670        flags = get_be16(&ondisk->flags);
1671        len = flags & CE_NAMEMASK;
1672
1673        if (flags & CE_EXTENDED) {
1674                struct ondisk_cache_entry_extended *ondisk2;
1675                int extended_flags;
1676                ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
1677                extended_flags = get_be16(&ondisk2->flags2) << 16;
1678                /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1679                if (extended_flags & ~CE_EXTENDED_FLAGS)
1680                        die("Unknown index entry format %08x", extended_flags);
1681                flags |= extended_flags;
1682                name = ondisk2->name;
1683        }
1684        else
1685                name = ondisk->name;
1686
1687        if (!previous_name) {
1688                /* v3 and earlier */
1689                if (len == CE_NAMEMASK)
1690                        len = strlen(name);
1691                ce = cache_entry_from_ondisk(ondisk, flags, name, len);
1692
1693                *ent_size = ondisk_ce_size(ce);
1694        } else {
1695                unsigned long consumed;
1696                consumed = expand_name_field(previous_name, name);
1697                ce = cache_entry_from_ondisk(ondisk, flags,
1698                                             previous_name->buf,
1699                                             previous_name->len);
1700
1701                *ent_size = (name - ((char *)ondisk)) + consumed;
1702        }
1703        return ce;
1704}
1705
1706static void check_ce_order(struct index_state *istate)
1707{
1708        unsigned int i;
1709
1710        if (!verify_ce_order)
1711                return;
1712
1713        for (i = 1; i < istate->cache_nr; i++) {
1714                struct cache_entry *ce = istate->cache[i - 1];
1715                struct cache_entry *next_ce = istate->cache[i];
1716                int name_compare = strcmp(ce->name, next_ce->name);
1717
1718                if (0 < name_compare)
1719                        die("unordered stage entries in index");
1720                if (!name_compare) {
1721                        if (!ce_stage(ce))
1722                                die("multiple stage entries for merged file '%s'",
1723                                    ce->name);
1724                        if (ce_stage(ce) > ce_stage(next_ce))
1725                                die("unordered stage entries for '%s'",
1726                                    ce->name);
1727                }
1728        }
1729}
1730
1731static void tweak_untracked_cache(struct index_state *istate)
1732{
1733        switch (git_config_get_untracked_cache()) {
1734        case -1: /* keep: do nothing */
1735                break;
1736        case 0: /* false */
1737                remove_untracked_cache(istate);
1738                break;
1739        case 1: /* true */
1740                add_untracked_cache(istate);
1741                break;
1742        default: /* unknown value: do nothing */
1743                break;
1744        }
1745}
1746
1747static void tweak_split_index(struct index_state *istate)
1748{
1749        switch (git_config_get_split_index()) {
1750        case -1: /* unset: do nothing */
1751                break;
1752        case 0: /* false */
1753                remove_split_index(istate);
1754                break;
1755        case 1: /* true */
1756                add_split_index(istate);
1757                break;
1758        default: /* unknown value: do nothing */
1759                break;
1760        }
1761}
1762
1763static void post_read_index_from(struct index_state *istate)
1764{
1765        check_ce_order(istate);
1766        tweak_untracked_cache(istate);
1767        tweak_split_index(istate);
1768        tweak_fsmonitor(istate);
1769}
1770
1771/* remember to discard_cache() before reading a different cache! */
1772int do_read_index(struct index_state *istate, const char *path, int must_exist)
1773{
1774        int fd, i;
1775        struct stat st;
1776        unsigned long src_offset;
1777        struct cache_header *hdr;
1778        void *mmap;
1779        size_t mmap_size;
1780        struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
1781
1782        if (istate->initialized)
1783                return istate->cache_nr;
1784
1785        istate->timestamp.sec = 0;
1786        istate->timestamp.nsec = 0;
1787        fd = open(path, O_RDONLY);
1788        if (fd < 0) {
1789                if (!must_exist && errno == ENOENT)
1790                        return 0;
1791                die_errno("%s: index file open failed", path);
1792        }
1793
1794        if (fstat(fd, &st))
1795                die_errno("cannot stat the open index");
1796
1797        mmap_size = xsize_t(st.st_size);
1798        if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
1799                die("index file smaller than expected");
1800
1801        mmap = xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
1802        if (mmap == MAP_FAILED)
1803                die_errno("unable to map index file");
1804        close(fd);
1805
1806        hdr = mmap;
1807        if (verify_hdr(hdr, mmap_size) < 0)
1808                goto unmap;
1809
1810        hashcpy(istate->sha1, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
1811        istate->version = ntohl(hdr->hdr_version);
1812        istate->cache_nr = ntohl(hdr->hdr_entries);
1813        istate->cache_alloc = alloc_nr(istate->cache_nr);
1814        istate->cache = xcalloc(istate->cache_alloc, sizeof(*istate->cache));
1815        istate->initialized = 1;
1816
1817        if (istate->version == 4)
1818                previous_name = &previous_name_buf;
1819        else
1820                previous_name = NULL;
1821
1822        src_offset = sizeof(*hdr);
1823        for (i = 0; i < istate->cache_nr; i++) {
1824                struct ondisk_cache_entry *disk_ce;
1825                struct cache_entry *ce;
1826                unsigned long consumed;
1827
1828                disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1829                ce = create_from_disk(disk_ce, &consumed, previous_name);
1830                set_index_entry(istate, i, ce);
1831
1832                src_offset += consumed;
1833        }
1834        strbuf_release(&previous_name_buf);
1835        istate->timestamp.sec = st.st_mtime;
1836        istate->timestamp.nsec = ST_MTIME_NSEC(st);
1837
1838        while (src_offset <= mmap_size - the_hash_algo->rawsz - 8) {
1839                /* After an array of active_nr index entries,
1840                 * there can be arbitrary number of extended
1841                 * sections, each of which is prefixed with
1842                 * extension name (4-byte) and section length
1843                 * in 4-byte network byte order.
1844                 */
1845                uint32_t extsize;
1846                memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1847                extsize = ntohl(extsize);
1848                if (read_index_extension(istate,
1849                                         (const char *) mmap + src_offset,
1850                                         (char *) mmap + src_offset + 8,
1851                                         extsize) < 0)
1852                        goto unmap;
1853                src_offset += 8;
1854                src_offset += extsize;
1855        }
1856        munmap(mmap, mmap_size);
1857        return istate->cache_nr;
1858
1859unmap:
1860        munmap(mmap, mmap_size);
1861        die("index file corrupt");
1862}
1863
1864/*
1865 * Signal that the shared index is used by updating its mtime.
1866 *
1867 * This way, shared index can be removed if they have not been used
1868 * for some time.
1869 */
1870static void freshen_shared_index(const char *shared_index, int warn)
1871{
1872        if (!check_and_freshen_file(shared_index, 1) && warn)
1873                warning("could not freshen shared index '%s'", shared_index);
1874}
1875
1876int read_index_from(struct index_state *istate, const char *path,
1877                    const char *gitdir)
1878{
1879        uint64_t start = getnanotime();
1880        struct split_index *split_index;
1881        int ret;
1882        char *base_sha1_hex;
1883        char *base_path;
1884
1885        /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
1886        if (istate->initialized)
1887                return istate->cache_nr;
1888
1889        ret = do_read_index(istate, path, 0);
1890        trace_performance_since(start, "read cache %s", path);
1891
1892        split_index = istate->split_index;
1893        if (!split_index || is_null_sha1(split_index->base_sha1)) {
1894                post_read_index_from(istate);
1895                return ret;
1896        }
1897
1898        if (split_index->base)
1899                discard_index(split_index->base);
1900        else
1901                split_index->base = xcalloc(1, sizeof(*split_index->base));
1902
1903        base_sha1_hex = sha1_to_hex(split_index->base_sha1);
1904        base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_sha1_hex);
1905        ret = do_read_index(split_index->base, base_path, 1);
1906        if (hashcmp(split_index->base_sha1, split_index->base->sha1))
1907                die("broken index, expect %s in %s, got %s",
1908                    base_sha1_hex, base_path,
1909                    sha1_to_hex(split_index->base->sha1));
1910
1911        freshen_shared_index(base_path, 0);
1912        merge_base_index(istate);
1913        post_read_index_from(istate);
1914        trace_performance_since(start, "read cache %s", base_path);
1915        free(base_path);
1916        return ret;
1917}
1918
1919int is_index_unborn(struct index_state *istate)
1920{
1921        return (!istate->cache_nr && !istate->timestamp.sec);
1922}
1923
1924int discard_index(struct index_state *istate)
1925{
1926        int i;
1927
1928        for (i = 0; i < istate->cache_nr; i++) {
1929                if (istate->cache[i]->index &&
1930                    istate->split_index &&
1931                    istate->split_index->base &&
1932                    istate->cache[i]->index <= istate->split_index->base->cache_nr &&
1933                    istate->cache[i] == istate->split_index->base->cache[istate->cache[i]->index - 1])
1934                        continue;
1935                free(istate->cache[i]);
1936        }
1937        resolve_undo_clear_index(istate);
1938        istate->cache_nr = 0;
1939        istate->cache_changed = 0;
1940        istate->timestamp.sec = 0;
1941        istate->timestamp.nsec = 0;
1942        free_name_hash(istate);
1943        cache_tree_free(&(istate->cache_tree));
1944        istate->initialized = 0;
1945        FREE_AND_NULL(istate->cache);
1946        istate->cache_alloc = 0;
1947        discard_split_index(istate);
1948        free_untracked_cache(istate->untracked);
1949        istate->untracked = NULL;
1950        return 0;
1951}
1952
1953int unmerged_index(const struct index_state *istate)
1954{
1955        int i;
1956        for (i = 0; i < istate->cache_nr; i++) {
1957                if (ce_stage(istate->cache[i]))
1958                        return 1;
1959        }
1960        return 0;
1961}
1962
1963#define WRITE_BUFFER_SIZE 8192
1964static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1965static unsigned long write_buffer_len;
1966
1967static int ce_write_flush(git_hash_ctx *context, int fd)
1968{
1969        unsigned int buffered = write_buffer_len;
1970        if (buffered) {
1971                the_hash_algo->update_fn(context, write_buffer, buffered);
1972                if (write_in_full(fd, write_buffer, buffered) < 0)
1973                        return -1;
1974                write_buffer_len = 0;
1975        }
1976        return 0;
1977}
1978
1979static int ce_write(git_hash_ctx *context, int fd, void *data, unsigned int len)
1980{
1981        while (len) {
1982                unsigned int buffered = write_buffer_len;
1983                unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1984                if (partial > len)
1985                        partial = len;
1986                memcpy(write_buffer + buffered, data, partial);
1987                buffered += partial;
1988                if (buffered == WRITE_BUFFER_SIZE) {
1989                        write_buffer_len = buffered;
1990                        if (ce_write_flush(context, fd))
1991                                return -1;
1992                        buffered = 0;
1993                }
1994                write_buffer_len = buffered;
1995                len -= partial;
1996                data = (char *) data + partial;
1997        }
1998        return 0;
1999}
2000
2001static int write_index_ext_header(git_hash_ctx *context, int fd,
2002                                  unsigned int ext, unsigned int sz)
2003{
2004        ext = htonl(ext);
2005        sz = htonl(sz);
2006        return ((ce_write(context, fd, &ext, 4) < 0) ||
2007                (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
2008}
2009
2010static int ce_flush(git_hash_ctx *context, int fd, unsigned char *hash)
2011{
2012        unsigned int left = write_buffer_len;
2013
2014        if (left) {
2015                write_buffer_len = 0;
2016                the_hash_algo->update_fn(context, write_buffer, left);
2017        }
2018
2019        /* Flush first if not enough space for hash signature */
2020        if (left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {
2021                if (write_in_full(fd, write_buffer, left) < 0)
2022                        return -1;
2023                left = 0;
2024        }
2025
2026        /* Append the hash signature at the end */
2027        the_hash_algo->final_fn(write_buffer + left, context);
2028        hashcpy(hash, write_buffer + left);
2029        left += the_hash_algo->rawsz;
2030        return (write_in_full(fd, write_buffer, left) < 0) ? -1 : 0;
2031}
2032
2033static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
2034{
2035        /*
2036         * The only thing we care about in this function is to smudge the
2037         * falsely clean entry due to touch-update-touch race, so we leave
2038         * everything else as they are.  We are called for entries whose
2039         * ce_stat_data.sd_mtime match the index file mtime.
2040         *
2041         * Note that this actually does not do much for gitlinks, for
2042         * which ce_match_stat_basic() always goes to the actual
2043         * contents.  The caller checks with is_racy_timestamp() which
2044         * always says "no" for gitlinks, so we are not called for them ;-)
2045         */
2046        struct stat st;
2047
2048        if (lstat(ce->name, &st) < 0)
2049                return;
2050        if (ce_match_stat_basic(ce, &st))
2051                return;
2052        if (ce_modified_check_fs(ce, &st)) {
2053                /* This is "racily clean"; smudge it.  Note that this
2054                 * is a tricky code.  At first glance, it may appear
2055                 * that it can break with this sequence:
2056                 *
2057                 * $ echo xyzzy >frotz
2058                 * $ git-update-index --add frotz
2059                 * $ : >frotz
2060                 * $ sleep 3
2061                 * $ echo filfre >nitfol
2062                 * $ git-update-index --add nitfol
2063                 *
2064                 * but it does not.  When the second update-index runs,
2065                 * it notices that the entry "frotz" has the same timestamp
2066                 * as index, and if we were to smudge it by resetting its
2067                 * size to zero here, then the object name recorded
2068                 * in index is the 6-byte file but the cached stat information
2069                 * becomes zero --- which would then match what we would
2070                 * obtain from the filesystem next time we stat("frotz").
2071                 *
2072                 * However, the second update-index, before calling
2073                 * this function, notices that the cached size is 6
2074                 * bytes and what is on the filesystem is an empty
2075                 * file, and never calls us, so the cached size information
2076                 * for "frotz" stays 6 which does not match the filesystem.
2077                 */
2078                ce->ce_stat_data.sd_size = 0;
2079        }
2080}
2081
2082/* Copy miscellaneous fields but not the name */
2083static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
2084                                       struct cache_entry *ce)
2085{
2086        short flags;
2087
2088        ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2089        ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2090        ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2091        ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2092        ondisk->dev  = htonl(ce->ce_stat_data.sd_dev);
2093        ondisk->ino  = htonl(ce->ce_stat_data.sd_ino);
2094        ondisk->mode = htonl(ce->ce_mode);
2095        ondisk->uid  = htonl(ce->ce_stat_data.sd_uid);
2096        ondisk->gid  = htonl(ce->ce_stat_data.sd_gid);
2097        ondisk->size = htonl(ce->ce_stat_data.sd_size);
2098        hashcpy(ondisk->sha1, ce->oid.hash);
2099
2100        flags = ce->ce_flags & ~CE_NAMEMASK;
2101        flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2102        ondisk->flags = htons(flags);
2103        if (ce->ce_flags & CE_EXTENDED) {
2104                struct ondisk_cache_entry_extended *ondisk2;
2105                ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
2106                ondisk2->flags2 = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
2107        }
2108}
2109
2110static int ce_write_entry(git_hash_ctx *c, int fd, struct cache_entry *ce,
2111                          struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
2112{
2113        int size;
2114        int result;
2115        unsigned int saved_namelen;
2116        int stripped_name = 0;
2117        static unsigned char padding[8] = { 0x00 };
2118
2119        if (ce->ce_flags & CE_STRIP_NAME) {
2120                saved_namelen = ce_namelen(ce);
2121                ce->ce_namelen = 0;
2122                stripped_name = 1;
2123        }
2124
2125        if (ce->ce_flags & CE_EXTENDED)
2126                size = offsetof(struct ondisk_cache_entry_extended, name);
2127        else
2128                size = offsetof(struct ondisk_cache_entry, name);
2129
2130        if (!previous_name) {
2131                int len = ce_namelen(ce);
2132                copy_cache_entry_to_ondisk(ondisk, ce);
2133                result = ce_write(c, fd, ondisk, size);
2134                if (!result)
2135                        result = ce_write(c, fd, ce->name, len);
2136                if (!result)
2137                        result = ce_write(c, fd, padding, align_padding_size(size, len));
2138        } else {
2139                int common, to_remove, prefix_size;
2140                unsigned char to_remove_vi[16];
2141                for (common = 0;
2142                     (ce->name[common] &&
2143                      common < previous_name->len &&
2144                      ce->name[common] == previous_name->buf[common]);
2145                     common++)
2146                        ; /* still matching */
2147                to_remove = previous_name->len - common;
2148                prefix_size = encode_varint(to_remove, to_remove_vi);
2149
2150                copy_cache_entry_to_ondisk(ondisk, ce);
2151                result = ce_write(c, fd, ondisk, size);
2152                if (!result)
2153                        result = ce_write(c, fd, to_remove_vi, prefix_size);
2154                if (!result)
2155                        result = ce_write(c, fd, ce->name + common, ce_namelen(ce) - common);
2156                if (!result)
2157                        result = ce_write(c, fd, padding, 1);
2158
2159                strbuf_splice(previous_name, common, to_remove,
2160                              ce->name + common, ce_namelen(ce) - common);
2161        }
2162        if (stripped_name) {
2163                ce->ce_namelen = saved_namelen;
2164                ce->ce_flags &= ~CE_STRIP_NAME;
2165        }
2166
2167        return result;
2168}
2169
2170/*
2171 * This function verifies if index_state has the correct sha1 of the
2172 * index file.  Don't die if we have any other failure, just return 0.
2173 */
2174static int verify_index_from(const struct index_state *istate, const char *path)
2175{
2176        int fd;
2177        ssize_t n;
2178        struct stat st;
2179        unsigned char hash[GIT_MAX_RAWSZ];
2180
2181        if (!istate->initialized)
2182                return 0;
2183
2184        fd = open(path, O_RDONLY);
2185        if (fd < 0)
2186                return 0;
2187
2188        if (fstat(fd, &st))
2189                goto out;
2190
2191        if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2192                goto out;
2193
2194        n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2195        if (n != the_hash_algo->rawsz)
2196                goto out;
2197
2198        if (hashcmp(istate->sha1, hash))
2199                goto out;
2200
2201        close(fd);
2202        return 1;
2203
2204out:
2205        close(fd);
2206        return 0;
2207}
2208
2209static int verify_index(const struct index_state *istate)
2210{
2211        return verify_index_from(istate, get_index_file());
2212}
2213
2214static int has_racy_timestamp(struct index_state *istate)
2215{
2216        int entries = istate->cache_nr;
2217        int i;
2218
2219        for (i = 0; i < entries; i++) {
2220                struct cache_entry *ce = istate->cache[i];
2221                if (is_racy_timestamp(istate, ce))
2222                        return 1;
2223        }
2224        return 0;
2225}
2226
2227void update_index_if_able(struct index_state *istate, struct lock_file *lockfile)
2228{
2229        if ((istate->cache_changed || has_racy_timestamp(istate)) &&
2230            verify_index(istate))
2231                write_locked_index(istate, lockfile, COMMIT_LOCK);
2232        else
2233                rollback_lock_file(lockfile);
2234}
2235
2236/*
2237 * On success, `tempfile` is closed. If it is the temporary file
2238 * of a `struct lock_file`, we will therefore effectively perform
2239 * a 'close_lock_file_gently()`. Since that is an implementation
2240 * detail of lockfiles, callers of `do_write_index()` should not
2241 * rely on it.
2242 */
2243static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
2244                          int strip_extensions)
2245{
2246        uint64_t start = getnanotime();
2247        int newfd = tempfile->fd;
2248        git_hash_ctx c;
2249        struct cache_header hdr;
2250        int i, err = 0, removed, extended, hdr_version;
2251        struct cache_entry **cache = istate->cache;
2252        int entries = istate->cache_nr;
2253        struct stat st;
2254        struct ondisk_cache_entry_extended ondisk;
2255        struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
2256        int drop_cache_tree = istate->drop_cache_tree;
2257
2258        for (i = removed = extended = 0; i < entries; i++) {
2259                if (cache[i]->ce_flags & CE_REMOVE)
2260                        removed++;
2261
2262                /* reduce extended entries if possible */
2263                cache[i]->ce_flags &= ~CE_EXTENDED;
2264                if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2265                        extended++;
2266                        cache[i]->ce_flags |= CE_EXTENDED;
2267                }
2268        }
2269
2270        if (!istate->version) {
2271                istate->version = get_index_format_default();
2272                if (getenv("GIT_TEST_SPLIT_INDEX"))
2273                        init_split_index(istate);
2274        }
2275
2276        /* demote version 3 to version 2 when the latter suffices */
2277        if (istate->version == 3 || istate->version == 2)
2278                istate->version = extended ? 3 : 2;
2279
2280        hdr_version = istate->version;
2281
2282        hdr.hdr_signature = htonl(CACHE_SIGNATURE);
2283        hdr.hdr_version = htonl(hdr_version);
2284        hdr.hdr_entries = htonl(entries - removed);
2285
2286        the_hash_algo->init_fn(&c);
2287        if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
2288                return -1;
2289
2290        previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
2291
2292        for (i = 0; i < entries; i++) {
2293                struct cache_entry *ce = cache[i];
2294                if (ce->ce_flags & CE_REMOVE)
2295                        continue;
2296                if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
2297                        ce_smudge_racily_clean_entry(ce);
2298                if (is_null_oid(&ce->oid)) {
2299                        static const char msg[] = "cache entry has null sha1: %s";
2300                        static int allow = -1;
2301
2302                        if (allow < 0)
2303                                allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
2304                        if (allow)
2305                                warning(msg, ce->name);
2306                        else
2307                                err = error(msg, ce->name);
2308
2309                        drop_cache_tree = 1;
2310                }
2311                if (ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
2312                        err = -1;
2313
2314                if (err)
2315                        break;
2316        }
2317        strbuf_release(&previous_name_buf);
2318
2319        if (err)
2320                return err;
2321
2322        /* Write extension data here */
2323        if (!strip_extensions && istate->split_index) {
2324                struct strbuf sb = STRBUF_INIT;
2325
2326                err = write_link_extension(&sb, istate) < 0 ||
2327                        write_index_ext_header(&c, newfd, CACHE_EXT_LINK,
2328                                               sb.len) < 0 ||
2329                        ce_write(&c, newfd, sb.buf, sb.len) < 0;
2330                strbuf_release(&sb);
2331                if (err)
2332                        return -1;
2333        }
2334        if (!strip_extensions && !drop_cache_tree && istate->cache_tree) {
2335                struct strbuf sb = STRBUF_INIT;
2336
2337                cache_tree_write(&sb, istate->cache_tree);
2338                err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
2339                        || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2340                strbuf_release(&sb);
2341                if (err)
2342                        return -1;
2343        }
2344        if (!strip_extensions && istate->resolve_undo) {
2345                struct strbuf sb = STRBUF_INIT;
2346
2347                resolve_undo_write(&sb, istate->resolve_undo);
2348                err = write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,
2349                                             sb.len) < 0
2350                        || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2351                strbuf_release(&sb);
2352                if (err)
2353                        return -1;
2354        }
2355        if (!strip_extensions && istate->untracked) {
2356                struct strbuf sb = STRBUF_INIT;
2357
2358                write_untracked_extension(&sb, istate->untracked);
2359                err = write_index_ext_header(&c, newfd, CACHE_EXT_UNTRACKED,
2360                                             sb.len) < 0 ||
2361                        ce_write(&c, newfd, sb.buf, sb.len) < 0;
2362                strbuf_release(&sb);
2363                if (err)
2364                        return -1;
2365        }
2366        if (!strip_extensions && istate->fsmonitor_last_update) {
2367                struct strbuf sb = STRBUF_INIT;
2368
2369                write_fsmonitor_extension(&sb, istate);
2370                err = write_index_ext_header(&c, newfd, CACHE_EXT_FSMONITOR, sb.len) < 0
2371                        || ce_write(&c, newfd, sb.buf, sb.len) < 0;
2372                strbuf_release(&sb);
2373                if (err)
2374                        return -1;
2375        }
2376
2377        if (ce_flush(&c, newfd, istate->sha1))
2378                return -1;
2379        if (close_tempfile_gently(tempfile)) {
2380                error(_("could not close '%s'"), tempfile->filename.buf);
2381                return -1;
2382        }
2383        if (stat(tempfile->filename.buf, &st))
2384                return -1;
2385        istate->timestamp.sec = (unsigned int)st.st_mtime;
2386        istate->timestamp.nsec = ST_MTIME_NSEC(st);
2387        trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
2388        return 0;
2389}
2390
2391void set_alternate_index_output(const char *name)
2392{
2393        alternate_index_output = name;
2394}
2395
2396static int commit_locked_index(struct lock_file *lk)
2397{
2398        if (alternate_index_output)
2399                return commit_lock_file_to(lk, alternate_index_output);
2400        else
2401                return commit_lock_file(lk);
2402}
2403
2404static int do_write_locked_index(struct index_state *istate, struct lock_file *lock,
2405                                 unsigned flags)
2406{
2407        int ret = do_write_index(istate, lock->tempfile, 0);
2408        if (ret)
2409                return ret;
2410        if (flags & COMMIT_LOCK)
2411                return commit_locked_index(lock);
2412        return close_lock_file_gently(lock);
2413}
2414
2415static int write_split_index(struct index_state *istate,
2416                             struct lock_file *lock,
2417                             unsigned flags)
2418{
2419        int ret;
2420        prepare_to_write_split_index(istate);
2421        ret = do_write_locked_index(istate, lock, flags);
2422        finish_writing_split_index(istate);
2423        return ret;
2424}
2425
2426static const char *shared_index_expire = "2.weeks.ago";
2427
2428static unsigned long get_shared_index_expire_date(void)
2429{
2430        static unsigned long shared_index_expire_date;
2431        static int shared_index_expire_date_prepared;
2432
2433        if (!shared_index_expire_date_prepared) {
2434                git_config_get_expiry("splitindex.sharedindexexpire",
2435                                      &shared_index_expire);
2436                shared_index_expire_date = approxidate(shared_index_expire);
2437                shared_index_expire_date_prepared = 1;
2438        }
2439
2440        return shared_index_expire_date;
2441}
2442
2443static int should_delete_shared_index(const char *shared_index_path)
2444{
2445        struct stat st;
2446        unsigned long expiration;
2447
2448        /* Check timestamp */
2449        expiration = get_shared_index_expire_date();
2450        if (!expiration)
2451                return 0;
2452        if (stat(shared_index_path, &st))
2453                return error_errno(_("could not stat '%s'"), shared_index_path);
2454        if (st.st_mtime > expiration)
2455                return 0;
2456
2457        return 1;
2458}
2459
2460static int clean_shared_index_files(const char *current_hex)
2461{
2462        struct dirent *de;
2463        DIR *dir = opendir(get_git_dir());
2464
2465        if (!dir)
2466                return error_errno(_("unable to open git dir: %s"), get_git_dir());
2467
2468        while ((de = readdir(dir)) != NULL) {
2469                const char *sha1_hex;
2470                const char *shared_index_path;
2471                if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
2472                        continue;
2473                if (!strcmp(sha1_hex, current_hex))
2474                        continue;
2475                shared_index_path = git_path("%s", de->d_name);
2476                if (should_delete_shared_index(shared_index_path) > 0 &&
2477                    unlink(shared_index_path))
2478                        warning_errno(_("unable to unlink: %s"), shared_index_path);
2479        }
2480        closedir(dir);
2481
2482        return 0;
2483}
2484
2485static int write_shared_index(struct index_state *istate,
2486                              struct tempfile **temp)
2487{
2488        struct split_index *si = istate->split_index;
2489        int ret;
2490
2491        move_cache_to_base_index(istate);
2492        ret = do_write_index(si->base, *temp, 1);
2493        if (ret)
2494                return ret;
2495        ret = adjust_shared_perm(get_tempfile_path(*temp));
2496        if (ret) {
2497                error("cannot fix permission bits on %s", get_tempfile_path(*temp));
2498                return ret;
2499        }
2500        ret = rename_tempfile(temp,
2501                              git_path("sharedindex.%s", sha1_to_hex(si->base->sha1)));
2502        if (!ret) {
2503                hashcpy(si->base_sha1, si->base->sha1);
2504                clean_shared_index_files(sha1_to_hex(si->base->sha1));
2505        }
2506
2507        return ret;
2508}
2509
2510static const int default_max_percent_split_change = 20;
2511
2512static int too_many_not_shared_entries(struct index_state *istate)
2513{
2514        int i, not_shared = 0;
2515        int max_split = git_config_get_max_percent_split_change();
2516
2517        switch (max_split) {
2518        case -1:
2519                /* not or badly configured: use the default value */
2520                max_split = default_max_percent_split_change;
2521                break;
2522        case 0:
2523                return 1; /* 0% means always write a new shared index */
2524        case 100:
2525                return 0; /* 100% means never write a new shared index */
2526        default:
2527                break; /* just use the configured value */
2528        }
2529
2530        /* Count not shared entries */
2531        for (i = 0; i < istate->cache_nr; i++) {
2532                struct cache_entry *ce = istate->cache[i];
2533                if (!ce->index)
2534                        not_shared++;
2535        }
2536
2537        return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
2538}
2539
2540int write_locked_index(struct index_state *istate, struct lock_file *lock,
2541                       unsigned flags)
2542{
2543        int new_shared_index, ret;
2544        struct split_index *si = istate->split_index;
2545
2546        if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
2547                if (flags & COMMIT_LOCK)
2548                        rollback_lock_file(lock);
2549                return 0;
2550        }
2551
2552        if (istate->fsmonitor_last_update)
2553                fill_fsmonitor_bitmap(istate);
2554
2555        if (!si || alternate_index_output ||
2556            (istate->cache_changed & ~EXTMASK)) {
2557                if (si)
2558                        hashclr(si->base_sha1);
2559                ret = do_write_locked_index(istate, lock, flags);
2560                goto out;
2561        }
2562
2563        if (getenv("GIT_TEST_SPLIT_INDEX")) {
2564                int v = si->base_sha1[0];
2565                if ((v & 15) < 6)
2566                        istate->cache_changed |= SPLIT_INDEX_ORDERED;
2567        }
2568        if (too_many_not_shared_entries(istate))
2569                istate->cache_changed |= SPLIT_INDEX_ORDERED;
2570
2571        new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
2572
2573        if (new_shared_index) {
2574                struct tempfile *temp;
2575                int saved_errno;
2576
2577                temp = mks_tempfile(git_path("sharedindex_XXXXXX"));
2578                if (!temp) {
2579                        hashclr(si->base_sha1);
2580                        ret = do_write_locked_index(istate, lock, flags);
2581                        goto out;
2582                }
2583                ret = write_shared_index(istate, &temp);
2584
2585                saved_errno = errno;
2586                if (is_tempfile_active(temp))
2587                        delete_tempfile(&temp);
2588                errno = saved_errno;
2589
2590                if (ret)
2591                        goto out;
2592        }
2593
2594        ret = write_split_index(istate, lock, flags);
2595
2596        /* Freshen the shared index only if the split-index was written */
2597        if (!ret && !new_shared_index) {
2598                const char *shared_index = git_path("sharedindex.%s",
2599                                                    sha1_to_hex(si->base_sha1));
2600                freshen_shared_index(shared_index, 1);
2601        }
2602
2603out:
2604        if (flags & COMMIT_LOCK)
2605                rollback_lock_file(lock);
2606        return ret;
2607}
2608
2609/*
2610 * Read the index file that is potentially unmerged into given
2611 * index_state, dropping any unmerged entries.  Returns true if
2612 * the index is unmerged.  Callers who want to refuse to work
2613 * from an unmerged state can call this and check its return value,
2614 * instead of calling read_cache().
2615 */
2616int read_index_unmerged(struct index_state *istate)
2617{
2618        int i;
2619        int unmerged = 0;
2620
2621        read_index(istate);
2622        for (i = 0; i < istate->cache_nr; i++) {
2623                struct cache_entry *ce = istate->cache[i];
2624                struct cache_entry *new_ce;
2625                int size, len;
2626
2627                if (!ce_stage(ce))
2628                        continue;
2629                unmerged = 1;
2630                len = ce_namelen(ce);
2631                size = cache_entry_size(len);
2632                new_ce = xcalloc(1, size);
2633                memcpy(new_ce->name, ce->name, len);
2634                new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
2635                new_ce->ce_namelen = len;
2636                new_ce->ce_mode = ce->ce_mode;
2637                if (add_index_entry(istate, new_ce, 0))
2638                        return error("%s: cannot drop to stage #0",
2639                                     new_ce->name);
2640        }
2641        return unmerged;
2642}
2643
2644/*
2645 * Returns 1 if the path is an "other" path with respect to
2646 * the index; that is, the path is not mentioned in the index at all,
2647 * either as a file, a directory with some files in the index,
2648 * or as an unmerged entry.
2649 *
2650 * We helpfully remove a trailing "/" from directories so that
2651 * the output of read_directory can be used as-is.
2652 */
2653int index_name_is_other(const struct index_state *istate, const char *name,
2654                int namelen)
2655{
2656        int pos;
2657        if (namelen && name[namelen - 1] == '/')
2658                namelen--;
2659        pos = index_name_pos(istate, name, namelen);
2660        if (0 <= pos)
2661                return 0;       /* exact match */
2662        pos = -pos - 1;
2663        if (pos < istate->cache_nr) {
2664                struct cache_entry *ce = istate->cache[pos];
2665                if (ce_namelen(ce) == namelen &&
2666                    !memcmp(ce->name, name, namelen))
2667                        return 0; /* Yup, this one exists unmerged */
2668        }
2669        return 1;
2670}
2671
2672void *read_blob_data_from_index(const struct index_state *istate,
2673                                const char *path, unsigned long *size)
2674{
2675        int pos, len;
2676        unsigned long sz;
2677        enum object_type type;
2678        void *data;
2679
2680        len = strlen(path);
2681        pos = index_name_pos(istate, path, len);
2682        if (pos < 0) {
2683                /*
2684                 * We might be in the middle of a merge, in which
2685                 * case we would read stage #2 (ours).
2686                 */
2687                int i;
2688                for (i = -pos - 1;
2689                     (pos < 0 && i < istate->cache_nr &&
2690                      !strcmp(istate->cache[i]->name, path));
2691                     i++)
2692                        if (ce_stage(istate->cache[i]) == 2)
2693                                pos = i;
2694        }
2695        if (pos < 0)
2696                return NULL;
2697        data = read_object_file(&istate->cache[pos]->oid, &type, &sz);
2698        if (!data || type != OBJ_BLOB) {
2699                free(data);
2700                return NULL;
2701        }
2702        if (size)
2703                *size = sz;
2704        return data;
2705}
2706
2707void stat_validity_clear(struct stat_validity *sv)
2708{
2709        FREE_AND_NULL(sv->sd);
2710}
2711
2712int stat_validity_check(struct stat_validity *sv, const char *path)
2713{
2714        struct stat st;
2715
2716        if (stat(path, &st) < 0)
2717                return sv->sd == NULL;
2718        if (!sv->sd)
2719                return 0;
2720        return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
2721}
2722
2723void stat_validity_update(struct stat_validity *sv, int fd)
2724{
2725        struct stat st;
2726
2727        if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
2728                stat_validity_clear(sv);
2729        else {
2730                if (!sv->sd)
2731                        sv->sd = xcalloc(1, sizeof(struct stat_data));
2732                fill_stat_data(sv->sd, &st);
2733        }
2734}
2735
2736void move_index_extensions(struct index_state *dst, struct index_state *src)
2737{
2738        dst->untracked = src->untracked;
2739        src->untracked = NULL;
2740}