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