1/* 2 * GIT - The information manager from hell 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 */ 6#define NO_THE_INDEX_COMPATIBILITY_MACROS 7#include"cache.h" 8#include"config.h" 9#include"tempfile.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"refs.h" 13#include"dir.h" 14#include"object-store.h" 15#include"tree.h" 16#include"commit.h" 17#include"blob.h" 18#include"resolve-undo.h" 19#include"strbuf.h" 20#include"varint.h" 21#include"split-index.h" 22#include"utf8.h" 23#include"fsmonitor.h" 24 25/* Mask for the name length in ce_flags in the on-disk index */ 26 27#define CE_NAMEMASK (0x0fff) 28 29/* Index extensions. 30 * 31 * The first letter should be 'A'..'Z' for extensions that are not 32 * necessary for a correct operation (i.e. optimization data). 33 * When new extensions are added that _needs_ to be understood in 34 * order to correctly interpret the index file, pick character that 35 * is outside the range, to cause the reader to abort. 36 */ 37 38#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) ) 39#define CACHE_EXT_TREE 0x54524545/* "TREE" */ 40#define CACHE_EXT_RESOLVE_UNDO 0x52455543/* "REUC" */ 41#define CACHE_EXT_LINK 0x6c696e6b/* "link" */ 42#define CACHE_EXT_UNTRACKED 0x554E5452/* "UNTR" */ 43#define CACHE_EXT_FSMONITOR 0x46534D4E/* "FSMN" */ 44 45/* changes that can be kept in $GIT_DIR/index (basically all extensions) */ 46#define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \ 47 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \ 48 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED) 49 50struct index_state the_index; 51static const char*alternate_index_output; 52 53static voidset_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 54{ 55 istate->cache[nr] = ce; 56add_name_hash(istate, ce); 57} 58 59static voidreplace_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 60{ 61struct cache_entry *old = istate->cache[nr]; 62 63replace_index_entry_in_base(istate, old, ce); 64remove_name_hash(istate, old); 65free(old); 66 ce->ce_flags &= ~CE_HASHED; 67set_index_entry(istate, nr, ce); 68 ce->ce_flags |= CE_UPDATE_IN_BASE; 69mark_fsmonitor_invalid(istate, ce); 70 istate->cache_changed |= CE_ENTRY_CHANGED; 71} 72 73voidrename_index_entry_at(struct index_state *istate,int nr,const char*new_name) 74{ 75struct cache_entry *old_entry = istate->cache[nr], *new_entry; 76int namelen =strlen(new_name); 77 78 new_entry =xmalloc(cache_entry_size(namelen)); 79copy_cache_entry(new_entry, old_entry); 80 new_entry->ce_flags &= ~CE_HASHED; 81 new_entry->ce_namelen = namelen; 82 new_entry->index =0; 83memcpy(new_entry->name, new_name, namelen +1); 84 85cache_tree_invalidate_path(istate, old_entry->name); 86untracked_cache_remove_from_index(istate, old_entry->name); 87remove_index_entry_at(istate, nr); 88add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE); 89} 90 91voidfill_stat_data(struct stat_data *sd,struct stat *st) 92{ 93 sd->sd_ctime.sec = (unsigned int)st->st_ctime; 94 sd->sd_mtime.sec = (unsigned int)st->st_mtime; 95 sd->sd_ctime.nsec =ST_CTIME_NSEC(*st); 96 sd->sd_mtime.nsec =ST_MTIME_NSEC(*st); 97 sd->sd_dev = st->st_dev; 98 sd->sd_ino = st->st_ino; 99 sd->sd_uid = st->st_uid; 100 sd->sd_gid = st->st_gid; 101 sd->sd_size = st->st_size; 102} 103 104intmatch_stat_data(const struct stat_data *sd,struct stat *st) 105{ 106int changed =0; 107 108if(sd->sd_mtime.sec != (unsigned int)st->st_mtime) 109 changed |= MTIME_CHANGED; 110if(trust_ctime && check_stat && 111 sd->sd_ctime.sec != (unsigned int)st->st_ctime) 112 changed |= CTIME_CHANGED; 113 114#ifdef USE_NSEC 115if(check_stat && sd->sd_mtime.nsec !=ST_MTIME_NSEC(*st)) 116 changed |= MTIME_CHANGED; 117if(trust_ctime && check_stat && 118 sd->sd_ctime.nsec !=ST_CTIME_NSEC(*st)) 119 changed |= CTIME_CHANGED; 120#endif 121 122if(check_stat) { 123if(sd->sd_uid != (unsigned int) st->st_uid || 124 sd->sd_gid != (unsigned int) st->st_gid) 125 changed |= OWNER_CHANGED; 126if(sd->sd_ino != (unsigned int) st->st_ino) 127 changed |= INODE_CHANGED; 128} 129 130#ifdef USE_STDEV 131/* 132 * st_dev breaks on network filesystems where different 133 * clients will have different views of what "device" 134 * the filesystem is on 135 */ 136if(check_stat && sd->sd_dev != (unsigned int) st->st_dev) 137 changed |= INODE_CHANGED; 138#endif 139 140if(sd->sd_size != (unsigned int) st->st_size) 141 changed |= DATA_CHANGED; 142 143return changed; 144} 145 146/* 147 * This only updates the "non-critical" parts of the directory 148 * cache, ie the parts that aren't tracked by GIT, and only used 149 * to validate the cache. 150 */ 151voidfill_stat_cache_info(struct cache_entry *ce,struct stat *st) 152{ 153fill_stat_data(&ce->ce_stat_data, st); 154 155if(assume_unchanged) 156 ce->ce_flags |= CE_VALID; 157 158if(S_ISREG(st->st_mode)) { 159ce_mark_uptodate(ce); 160mark_fsmonitor_valid(ce); 161} 162} 163 164static intce_compare_data(const struct cache_entry *ce,struct stat *st) 165{ 166int match = -1; 167int fd =git_open_cloexec(ce->name, O_RDONLY); 168 169if(fd >=0) { 170struct object_id oid; 171if(!index_fd(&oid, fd, st, OBJ_BLOB, ce->name,0)) 172 match =oidcmp(&oid, &ce->oid); 173/* index_fd() closed the file descriptor already */ 174} 175return match; 176} 177 178static intce_compare_link(const struct cache_entry *ce,size_t expected_size) 179{ 180int match = -1; 181void*buffer; 182unsigned long size; 183enum object_type type; 184struct strbuf sb = STRBUF_INIT; 185 186if(strbuf_readlink(&sb, ce->name, expected_size)) 187return-1; 188 189 buffer =read_object_file(&ce->oid, &type, &size); 190if(buffer) { 191if(size == sb.len) 192 match =memcmp(buffer, sb.buf, size); 193free(buffer); 194} 195strbuf_release(&sb); 196return match; 197} 198 199static intce_compare_gitlink(const struct cache_entry *ce) 200{ 201struct object_id oid; 202 203/* 204 * We don't actually require that the .git directory 205 * under GITLINK directory be a valid git directory. It 206 * might even be missing (in case nobody populated that 207 * sub-project). 208 * 209 * If so, we consider it always to match. 210 */ 211if(resolve_gitlink_ref(ce->name,"HEAD", &oid) <0) 212return0; 213returnoidcmp(&oid, &ce->oid); 214} 215 216static intce_modified_check_fs(const struct cache_entry *ce,struct stat *st) 217{ 218switch(st->st_mode & S_IFMT) { 219case S_IFREG: 220if(ce_compare_data(ce, st)) 221return DATA_CHANGED; 222break; 223case S_IFLNK: 224if(ce_compare_link(ce,xsize_t(st->st_size))) 225return DATA_CHANGED; 226break; 227case S_IFDIR: 228if(S_ISGITLINK(ce->ce_mode)) 229returnce_compare_gitlink(ce) ? DATA_CHANGED :0; 230/* else fallthrough */ 231default: 232return TYPE_CHANGED; 233} 234return0; 235} 236 237static intce_match_stat_basic(const struct cache_entry *ce,struct stat *st) 238{ 239unsigned int changed =0; 240 241if(ce->ce_flags & CE_REMOVE) 242return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED; 243 244switch(ce->ce_mode & S_IFMT) { 245case S_IFREG: 246 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED :0; 247/* We consider only the owner x bit to be relevant for 248 * "mode changes" 249 */ 250if(trust_executable_bit && 251(0100& (ce->ce_mode ^ st->st_mode))) 252 changed |= MODE_CHANGED; 253break; 254case S_IFLNK: 255if(!S_ISLNK(st->st_mode) && 256(has_symlinks || !S_ISREG(st->st_mode))) 257 changed |= TYPE_CHANGED; 258break; 259case S_IFGITLINK: 260/* We ignore most of the st_xxx fields for gitlinks */ 261if(!S_ISDIR(st->st_mode)) 262 changed |= TYPE_CHANGED; 263else if(ce_compare_gitlink(ce)) 264 changed |= DATA_CHANGED; 265return changed; 266default: 267die("internal error: ce_mode is%o", ce->ce_mode); 268} 269 270 changed |=match_stat_data(&ce->ce_stat_data, st); 271 272/* Racily smudged entry? */ 273if(!ce->ce_stat_data.sd_size) { 274if(!is_empty_blob_sha1(ce->oid.hash)) 275 changed |= DATA_CHANGED; 276} 277 278return changed; 279} 280 281static intis_racy_stat(const struct index_state *istate, 282const struct stat_data *sd) 283{ 284return(istate->timestamp.sec && 285#ifdef USE_NSEC 286/* nanosecond timestamped files can also be racy! */ 287(istate->timestamp.sec < sd->sd_mtime.sec || 288(istate->timestamp.sec == sd->sd_mtime.sec && 289 istate->timestamp.nsec <= sd->sd_mtime.nsec)) 290#else 291 istate->timestamp.sec <= sd->sd_mtime.sec 292#endif 293); 294} 295 296static intis_racy_timestamp(const struct index_state *istate, 297const struct cache_entry *ce) 298{ 299return(!S_ISGITLINK(ce->ce_mode) && 300is_racy_stat(istate, &ce->ce_stat_data)); 301} 302 303intmatch_stat_data_racy(const struct index_state *istate, 304const struct stat_data *sd,struct stat *st) 305{ 306if(is_racy_stat(istate, sd)) 307return MTIME_CHANGED; 308returnmatch_stat_data(sd, st); 309} 310 311intie_match_stat(struct index_state *istate, 312const struct cache_entry *ce,struct stat *st, 313unsigned int options) 314{ 315unsigned int changed; 316int ignore_valid = options & CE_MATCH_IGNORE_VALID; 317int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE; 318int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY; 319int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR; 320 321if(!ignore_fsmonitor) 322refresh_fsmonitor(istate); 323/* 324 * If it's marked as always valid in the index, it's 325 * valid whatever the checked-out copy says. 326 * 327 * skip-worktree has the same effect with higher precedence 328 */ 329if(!ignore_skip_worktree &&ce_skip_worktree(ce)) 330return0; 331if(!ignore_valid && (ce->ce_flags & CE_VALID)) 332return0; 333if(!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) 334return0; 335 336/* 337 * Intent-to-add entries have not been added, so the index entry 338 * by definition never matches what is in the work tree until it 339 * actually gets added. 340 */ 341if(ce_intent_to_add(ce)) 342return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED; 343 344 changed =ce_match_stat_basic(ce, st); 345 346/* 347 * Within 1 second of this sequence: 348 * echo xyzzy >file && git-update-index --add file 349 * running this command: 350 * echo frotz >file 351 * would give a falsely clean cache entry. The mtime and 352 * length match the cache, and other stat fields do not change. 353 * 354 * We could detect this at update-index time (the cache entry 355 * being registered/updated records the same time as "now") 356 * and delay the return from git-update-index, but that would 357 * effectively mean we can make at most one commit per second, 358 * which is not acceptable. Instead, we check cache entries 359 * whose mtime are the same as the index file timestamp more 360 * carefully than others. 361 */ 362if(!changed &&is_racy_timestamp(istate, ce)) { 363if(assume_racy_is_modified) 364 changed |= DATA_CHANGED; 365else 366 changed |=ce_modified_check_fs(ce, st); 367} 368 369return changed; 370} 371 372intie_modified(struct index_state *istate, 373const struct cache_entry *ce, 374struct stat *st,unsigned int options) 375{ 376int changed, changed_fs; 377 378 changed =ie_match_stat(istate, ce, st, options); 379if(!changed) 380return0; 381/* 382 * If the mode or type has changed, there's no point in trying 383 * to refresh the entry - it's not going to match 384 */ 385if(changed & (MODE_CHANGED | TYPE_CHANGED)) 386return changed; 387 388/* 389 * Immediately after read-tree or update-index --cacheinfo, 390 * the length field is zero, as we have never even read the 391 * lstat(2) information once, and we cannot trust DATA_CHANGED 392 * returned by ie_match_stat() which in turn was returned by 393 * ce_match_stat_basic() to signal that the filesize of the 394 * blob changed. We have to actually go to the filesystem to 395 * see if the contents match, and if so, should answer "unchanged". 396 * 397 * The logic does not apply to gitlinks, as ce_match_stat_basic() 398 * already has checked the actual HEAD from the filesystem in the 399 * subproject. If ie_match_stat() already said it is different, 400 * then we know it is. 401 */ 402if((changed & DATA_CHANGED) && 403(S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size !=0)) 404return changed; 405 406 changed_fs =ce_modified_check_fs(ce, st); 407if(changed_fs) 408return changed | changed_fs; 409return0; 410} 411 412intbase_name_compare(const char*name1,int len1,int mode1, 413const char*name2,int len2,int mode2) 414{ 415unsigned char c1, c2; 416int len = len1 < len2 ? len1 : len2; 417int cmp; 418 419 cmp =memcmp(name1, name2, len); 420if(cmp) 421return cmp; 422 c1 = name1[len]; 423 c2 = name2[len]; 424if(!c1 &&S_ISDIR(mode1)) 425 c1 ='/'; 426if(!c2 &&S_ISDIR(mode2)) 427 c2 ='/'; 428return(c1 < c2) ? -1: (c1 > c2) ?1:0; 429} 430 431/* 432 * df_name_compare() is identical to base_name_compare(), except it 433 * compares conflicting directory/file entries as equal. Note that 434 * while a directory name compares as equal to a regular file, they 435 * then individually compare _differently_ to a filename that has 436 * a dot after the basename (because '\0' < '.' < '/'). 437 * 438 * This is used by routines that want to traverse the git namespace 439 * but then handle conflicting entries together when possible. 440 */ 441intdf_name_compare(const char*name1,int len1,int mode1, 442const char*name2,int len2,int mode2) 443{ 444int len = len1 < len2 ? len1 : len2, cmp; 445unsigned char c1, c2; 446 447 cmp =memcmp(name1, name2, len); 448if(cmp) 449return cmp; 450/* Directories and files compare equal (same length, same name) */ 451if(len1 == len2) 452return0; 453 c1 = name1[len]; 454if(!c1 &&S_ISDIR(mode1)) 455 c1 ='/'; 456 c2 = name2[len]; 457if(!c2 &&S_ISDIR(mode2)) 458 c2 ='/'; 459if(c1 =='/'&& !c2) 460return0; 461if(c2 =='/'&& !c1) 462return0; 463return c1 - c2; 464} 465 466intname_compare(const char*name1,size_t len1,const char*name2,size_t len2) 467{ 468size_t min_len = (len1 < len2) ? len1 : len2; 469int cmp =memcmp(name1, name2, min_len); 470if(cmp) 471return cmp; 472if(len1 < len2) 473return-1; 474if(len1 > len2) 475return1; 476return0; 477} 478 479intcache_name_stage_compare(const char*name1,int len1,int stage1,const char*name2,int len2,int stage2) 480{ 481int cmp; 482 483 cmp =name_compare(name1, len1, name2, len2); 484if(cmp) 485return cmp; 486 487if(stage1 < stage2) 488return-1; 489if(stage1 > stage2) 490return1; 491return0; 492} 493 494static intindex_name_stage_pos(const struct index_state *istate,const char*name,int namelen,int stage) 495{ 496int first, last; 497 498 first =0; 499 last = istate->cache_nr; 500while(last > first) { 501int next = (last + first) >>1; 502struct cache_entry *ce = istate->cache[next]; 503int cmp =cache_name_stage_compare(name, namelen, stage, ce->name,ce_namelen(ce),ce_stage(ce)); 504if(!cmp) 505return next; 506if(cmp <0) { 507 last = next; 508continue; 509} 510 first = next+1; 511} 512return-first-1; 513} 514 515intindex_name_pos(const struct index_state *istate,const char*name,int namelen) 516{ 517returnindex_name_stage_pos(istate, name, namelen,0); 518} 519 520intremove_index_entry_at(struct index_state *istate,int pos) 521{ 522struct cache_entry *ce = istate->cache[pos]; 523 524record_resolve_undo(istate, ce); 525remove_name_hash(istate, ce); 526save_or_free_index_entry(istate, ce); 527 istate->cache_changed |= CE_ENTRY_REMOVED; 528 istate->cache_nr--; 529if(pos >= istate->cache_nr) 530return0; 531MOVE_ARRAY(istate->cache + pos, istate->cache + pos +1, 532 istate->cache_nr - pos); 533return1; 534} 535 536/* 537 * Remove all cache entries marked for removal, that is where 538 * CE_REMOVE is set in ce_flags. This is much more effective than 539 * calling remove_index_entry_at() for each entry to be removed. 540 */ 541voidremove_marked_cache_entries(struct index_state *istate) 542{ 543struct cache_entry **ce_array = istate->cache; 544unsigned int i, j; 545 546for(i = j =0; i < istate->cache_nr; i++) { 547if(ce_array[i]->ce_flags & CE_REMOVE) { 548remove_name_hash(istate, ce_array[i]); 549save_or_free_index_entry(istate, ce_array[i]); 550} 551else 552 ce_array[j++] = ce_array[i]; 553} 554if(j == istate->cache_nr) 555return; 556 istate->cache_changed |= CE_ENTRY_REMOVED; 557 istate->cache_nr = j; 558} 559 560intremove_file_from_index(struct index_state *istate,const char*path) 561{ 562int pos =index_name_pos(istate, path,strlen(path)); 563if(pos <0) 564 pos = -pos-1; 565cache_tree_invalidate_path(istate, path); 566untracked_cache_remove_from_index(istate, path); 567while(pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path)) 568remove_index_entry_at(istate, pos); 569return0; 570} 571 572static intcompare_name(struct cache_entry *ce,const char*path,int namelen) 573{ 574return namelen !=ce_namelen(ce) ||memcmp(path, ce->name, namelen); 575} 576 577static intindex_name_pos_also_unmerged(struct index_state *istate, 578const char*path,int namelen) 579{ 580int pos =index_name_pos(istate, path, namelen); 581struct cache_entry *ce; 582 583if(pos >=0) 584return pos; 585 586/* maybe unmerged? */ 587 pos = -1- pos; 588if(pos >= istate->cache_nr || 589compare_name((ce = istate->cache[pos]), path, namelen)) 590return-1; 591 592/* order of preference: stage 2, 1, 3 */ 593if(ce_stage(ce) ==1&& pos +1< istate->cache_nr && 594ce_stage((ce = istate->cache[pos +1])) ==2&& 595!compare_name(ce, path, namelen)) 596 pos++; 597return pos; 598} 599 600static intdifferent_name(struct cache_entry *ce,struct cache_entry *alias) 601{ 602int len =ce_namelen(ce); 603returnce_namelen(alias) != len ||memcmp(ce->name, alias->name, len); 604} 605 606/* 607 * If we add a filename that aliases in the cache, we will use the 608 * name that we already have - but we don't want to update the same 609 * alias twice, because that implies that there were actually two 610 * different files with aliasing names! 611 * 612 * So we use the CE_ADDED flag to verify that the alias was an old 613 * one before we accept it as 614 */ 615static struct cache_entry *create_alias_ce(struct index_state *istate, 616struct cache_entry *ce, 617struct cache_entry *alias) 618{ 619int len; 620struct cache_entry *new_entry; 621 622if(alias->ce_flags & CE_ADDED) 623die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name); 624 625/* Ok, create the new entry using the name of the existing alias */ 626 len =ce_namelen(alias); 627 new_entry =xcalloc(1,cache_entry_size(len)); 628memcpy(new_entry->name, alias->name, len); 629copy_cache_entry(new_entry, ce); 630save_or_free_index_entry(istate, ce); 631return new_entry; 632} 633 634voidset_object_name_for_intent_to_add_entry(struct cache_entry *ce) 635{ 636struct object_id oid; 637if(write_object_file("",0, blob_type, &oid)) 638die("cannot create an empty blob in the object database"); 639oidcpy(&ce->oid, &oid); 640} 641 642intadd_to_index(struct index_state *istate,const char*path,struct stat *st,int flags) 643{ 644int size, namelen, was_same; 645 mode_t st_mode = st->st_mode; 646struct cache_entry *ce, *alias = NULL; 647unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY; 648int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND); 649int pretend = flags & ADD_CACHE_PRETEND; 650int intent_only = flags & ADD_CACHE_INTENT; 651int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE| 652(intent_only ? ADD_CACHE_NEW_ONLY :0)); 653int newflags = HASH_WRITE_OBJECT; 654 655if(flags & HASH_RENORMALIZE) 656 newflags |= HASH_RENORMALIZE; 657 658if(!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode)) 659returnerror("%s: can only add regular files, symbolic links or git-directories", path); 660 661 namelen =strlen(path); 662if(S_ISDIR(st_mode)) { 663while(namelen && path[namelen-1] =='/') 664 namelen--; 665} 666 size =cache_entry_size(namelen); 667 ce =xcalloc(1, size); 668memcpy(ce->name, path, namelen); 669 ce->ce_namelen = namelen; 670if(!intent_only) 671fill_stat_cache_info(ce, st); 672else 673 ce->ce_flags |= CE_INTENT_TO_ADD; 674 675 676if(trust_executable_bit && has_symlinks) { 677 ce->ce_mode =create_ce_mode(st_mode); 678}else{ 679/* If there is an existing entry, pick the mode bits and type 680 * from it, otherwise assume unexecutable regular file. 681 */ 682struct cache_entry *ent; 683int pos =index_name_pos_also_unmerged(istate, path, namelen); 684 685 ent = (0<= pos) ? istate->cache[pos] : NULL; 686 ce->ce_mode =ce_mode_from_stat(ent, st_mode); 687} 688 689/* When core.ignorecase=true, determine if a directory of the same name but differing 690 * case already exists within the Git repository. If it does, ensure the directory 691 * case of the file being added to the repository matches (is folded into) the existing 692 * entry's directory case. 693 */ 694if(ignore_case) { 695adjust_dirname_case(istate, ce->name); 696} 697if(!(flags & HASH_RENORMALIZE)) { 698 alias =index_file_exists(istate, ce->name, 699ce_namelen(ce), ignore_case); 700if(alias && 701!ce_stage(alias) && 702!ie_match_stat(istate, alias, st, ce_option)) { 703/* Nothing changed, really */ 704if(!S_ISGITLINK(alias->ce_mode)) 705ce_mark_uptodate(alias); 706 alias->ce_flags |= CE_ADDED; 707 708free(ce); 709return0; 710} 711} 712if(!intent_only) { 713if(index_path(&ce->oid, path, st, newflags)) { 714free(ce); 715returnerror("unable to index file%s", path); 716} 717}else 718set_object_name_for_intent_to_add_entry(ce); 719 720if(ignore_case && alias &&different_name(ce, alias)) 721 ce =create_alias_ce(istate, ce, alias); 722 ce->ce_flags |= CE_ADDED; 723 724/* It was suspected to be racily clean, but it turns out to be Ok */ 725 was_same = (alias && 726!ce_stage(alias) && 727!oidcmp(&alias->oid, &ce->oid) && 728 ce->ce_mode == alias->ce_mode); 729 730if(pretend) 731free(ce); 732else if(add_index_entry(istate, ce, add_option)) { 733free(ce); 734returnerror("unable to add%sto index", path); 735} 736if(verbose && !was_same) 737printf("add '%s'\n", path); 738return0; 739} 740 741intadd_file_to_index(struct index_state *istate,const char*path,int flags) 742{ 743struct stat st; 744if(lstat(path, &st)) 745die_errno("unable to stat '%s'", path); 746returnadd_to_index(istate, path, &st, flags); 747} 748 749struct cache_entry *make_cache_entry(unsigned int mode, 750const unsigned char*sha1,const char*path,int stage, 751unsigned int refresh_options) 752{ 753int size, len; 754struct cache_entry *ce, *ret; 755 756if(!verify_path(path)) { 757error("Invalid path '%s'", path); 758return NULL; 759} 760 761 len =strlen(path); 762 size =cache_entry_size(len); 763 ce =xcalloc(1, size); 764 765hashcpy(ce->oid.hash, sha1); 766memcpy(ce->name, path, len); 767 ce->ce_flags =create_ce_flags(stage); 768 ce->ce_namelen = len; 769 ce->ce_mode =create_ce_mode(mode); 770 771 ret =refresh_cache_entry(ce, refresh_options); 772if(ret != ce) 773free(ce); 774return ret; 775} 776 777/* 778 * Chmod an index entry with either +x or -x. 779 * 780 * Returns -1 if the chmod for the particular cache entry failed (if it's 781 * not a regular file), -2 if an invalid flip argument is passed in, 0 782 * otherwise. 783 */ 784intchmod_index_entry(struct index_state *istate,struct cache_entry *ce, 785char flip) 786{ 787if(!S_ISREG(ce->ce_mode)) 788return-1; 789switch(flip) { 790case'+': 791 ce->ce_mode |=0111; 792break; 793case'-': 794 ce->ce_mode &= ~0111; 795break; 796default: 797return-2; 798} 799cache_tree_invalidate_path(istate, ce->name); 800 ce->ce_flags |= CE_UPDATE_IN_BASE; 801mark_fsmonitor_invalid(istate, ce); 802 istate->cache_changed |= CE_ENTRY_CHANGED; 803 804return0; 805} 806 807intce_same_name(const struct cache_entry *a,const struct cache_entry *b) 808{ 809int len =ce_namelen(a); 810returnce_namelen(b) == len && !memcmp(a->name, b->name, len); 811} 812 813/* 814 * We fundamentally don't like some paths: we don't want 815 * dot or dot-dot anywhere, and for obvious reasons don't 816 * want to recurse into ".git" either. 817 * 818 * Also, we don't want double slashes or slashes at the 819 * end that can make pathnames ambiguous. 820 */ 821static intverify_dotfile(const char*rest) 822{ 823/* 824 * The first character was '.', but that 825 * has already been discarded, we now test 826 * the rest. 827 */ 828 829/* "." is not allowed */ 830if(*rest =='\0'||is_dir_sep(*rest)) 831return0; 832 833switch(*rest) { 834/* 835 * ".git" followed by NUL or slash is bad. This 836 * shares the path end test with the ".." case. 837 */ 838case'g': 839case'G': 840if(rest[1] !='i'&& rest[1] !='I') 841break; 842if(rest[2] !='t'&& rest[2] !='T') 843break; 844 rest +=2; 845/* fallthrough */ 846case'.': 847if(rest[1] =='\0'||is_dir_sep(rest[1])) 848return0; 849} 850return1; 851} 852 853intverify_path(const char*path) 854{ 855char c; 856 857if(has_dos_drive_prefix(path)) 858return0; 859 860goto inside; 861for(;;) { 862if(!c) 863return1; 864if(is_dir_sep(c)) { 865inside: 866if(protect_hfs &&is_hfs_dotgit(path)) 867return0; 868if(protect_ntfs &&is_ntfs_dotgit(path)) 869return0; 870 c = *path++; 871if((c =='.'&& !verify_dotfile(path)) || 872is_dir_sep(c) || c =='\0') 873return0; 874} 875 c = *path++; 876} 877} 878 879/* 880 * Do we have another file that has the beginning components being a 881 * proper superset of the name we're trying to add? 882 */ 883static inthas_file_name(struct index_state *istate, 884const struct cache_entry *ce,int pos,int ok_to_replace) 885{ 886int retval =0; 887int len =ce_namelen(ce); 888int stage =ce_stage(ce); 889const char*name = ce->name; 890 891while(pos < istate->cache_nr) { 892struct cache_entry *p = istate->cache[pos++]; 893 894if(len >=ce_namelen(p)) 895break; 896if(memcmp(name, p->name, len)) 897break; 898if(ce_stage(p) != stage) 899continue; 900if(p->name[len] !='/') 901continue; 902if(p->ce_flags & CE_REMOVE) 903continue; 904 retval = -1; 905if(!ok_to_replace) 906break; 907remove_index_entry_at(istate, --pos); 908} 909return retval; 910} 911 912 913/* 914 * Like strcmp(), but also return the offset of the first change. 915 * If strings are equal, return the length. 916 */ 917intstrcmp_offset(const char*s1,const char*s2,size_t*first_change) 918{ 919size_t k; 920 921if(!first_change) 922returnstrcmp(s1, s2); 923 924for(k =0; s1[k] == s2[k]; k++) 925if(s1[k] =='\0') 926break; 927 928*first_change = k; 929return(unsigned char)s1[k] - (unsigned char)s2[k]; 930} 931 932/* 933 * Do we have another file with a pathname that is a proper 934 * subset of the name we're trying to add? 935 * 936 * That is, is there another file in the index with a path 937 * that matches a sub-directory in the given entry? 938 */ 939static inthas_dir_name(struct index_state *istate, 940const struct cache_entry *ce,int pos,int ok_to_replace) 941{ 942int retval =0; 943int stage =ce_stage(ce); 944const char*name = ce->name; 945const char*slash = name +ce_namelen(ce); 946size_t len_eq_last; 947int cmp_last =0; 948 949/* 950 * We are frequently called during an iteration on a sorted 951 * list of pathnames and while building a new index. Therefore, 952 * there is a high probability that this entry will eventually 953 * be appended to the index, rather than inserted in the middle. 954 * If we can confirm that, we can avoid binary searches on the 955 * components of the pathname. 956 * 957 * Compare the entry's full path with the last path in the index. 958 */ 959if(istate->cache_nr >0) { 960 cmp_last =strcmp_offset(name, 961 istate->cache[istate->cache_nr -1]->name, 962&len_eq_last); 963if(cmp_last >0) { 964if(len_eq_last ==0) { 965/* 966 * The entry sorts AFTER the last one in the 967 * index and their paths have no common prefix, 968 * so there cannot be a F/D conflict. 969 */ 970return retval; 971}else{ 972/* 973 * The entry sorts AFTER the last one in the 974 * index, but has a common prefix. Fall through 975 * to the loop below to disect the entry's path 976 * and see where the difference is. 977 */ 978} 979}else if(cmp_last ==0) { 980/* 981 * The entry exactly matches the last one in the 982 * index, but because of multiple stage and CE_REMOVE 983 * items, we fall through and let the regular search 984 * code handle it. 985 */ 986} 987} 988 989for(;;) { 990size_t len; 991 992for(;;) { 993if(*--slash =='/') 994break; 995if(slash <= ce->name) 996return retval; 997} 998 len = slash - name; 9991000if(cmp_last >0) {1001/*1002 * (len + 1) is a directory boundary (including1003 * the trailing slash). And since the loop is1004 * decrementing "slash", the first iteration is1005 * the longest directory prefix; subsequent1006 * iterations consider parent directories.1007 */10081009if(len +1<= len_eq_last) {1010/*1011 * The directory prefix (including the trailing1012 * slash) also appears as a prefix in the last1013 * entry, so the remainder cannot collide (because1014 * strcmp said the whole path was greater).1015 *1016 * EQ: last: xxx/A1017 * this: xxx/B1018 *1019 * LT: last: xxx/file_A1020 * this: xxx/file_B1021 */1022return retval;1023}10241025if(len > len_eq_last) {1026/*1027 * This part of the directory prefix (excluding1028 * the trailing slash) is longer than the known1029 * equal portions, so this sub-directory cannot1030 * collide with a file.1031 *1032 * GT: last: xxxA1033 * this: xxxB/file1034 */1035return retval;1036}10371038if(istate->cache_nr >0&&1039ce_namelen(istate->cache[istate->cache_nr -1]) > len) {1040/*1041 * The directory prefix lines up with part of1042 * a longer file or directory name, but sorts1043 * after it, so this sub-directory cannot1044 * collide with a file.1045 *1046 * last: xxx/yy-file (because '-' sorts before '/')1047 * this: xxx/yy/abc1048 */1049return retval;1050}10511052/*1053 * This is a possible collision. Fall through and1054 * let the regular search code handle it.1055 *1056 * last: xxx1057 * this: xxx/file1058 */1059}10601061 pos =index_name_stage_pos(istate, name, len, stage);1062if(pos >=0) {1063/*1064 * Found one, but not so fast. This could1065 * be a marker that says "I was here, but1066 * I am being removed". Such an entry is1067 * not a part of the resulting tree, and1068 * it is Ok to have a directory at the same1069 * path.1070 */1071if(!(istate->cache[pos]->ce_flags & CE_REMOVE)) {1072 retval = -1;1073if(!ok_to_replace)1074break;1075remove_index_entry_at(istate, pos);1076continue;1077}1078}1079else1080 pos = -pos-1;10811082/*1083 * Trivial optimization: if we find an entry that1084 * already matches the sub-directory, then we know1085 * we're ok, and we can exit.1086 */1087while(pos < istate->cache_nr) {1088struct cache_entry *p = istate->cache[pos];1089if((ce_namelen(p) <= len) ||1090(p->name[len] !='/') ||1091memcmp(p->name, name, len))1092break;/* not our subdirectory */1093if(ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))1094/*1095 * p is at the same stage as our entry, and1096 * is a subdirectory of what we are looking1097 * at, so we cannot have conflicts at our1098 * level or anything shorter.1099 */1100return retval;1101 pos++;1102}1103}1104return retval;1105}11061107/* We may be in a situation where we already have path/file and path1108 * is being added, or we already have path and path/file is being1109 * added. Either one would result in a nonsense tree that has path1110 * twice when git-write-tree tries to write it out. Prevent it.1111 *1112 * If ok-to-replace is specified, we remove the conflicting entries1113 * from the cache so the caller should recompute the insert position.1114 * When this happens, we return non-zero.1115 */1116static intcheck_file_directory_conflict(struct index_state *istate,1117const struct cache_entry *ce,1118int pos,int ok_to_replace)1119{1120int retval;11211122/*1123 * When ce is an "I am going away" entry, we allow it to be added1124 */1125if(ce->ce_flags & CE_REMOVE)1126return0;11271128/*1129 * We check if the path is a sub-path of a subsequent pathname1130 * first, since removing those will not change the position1131 * in the array.1132 */1133 retval =has_file_name(istate, ce, pos, ok_to_replace);11341135/*1136 * Then check if the path might have a clashing sub-directory1137 * before it.1138 */1139return retval +has_dir_name(istate, ce, pos, ok_to_replace);1140}11411142static intadd_index_entry_with_check(struct index_state *istate,struct cache_entry *ce,int option)1143{1144int pos;1145int ok_to_add = option & ADD_CACHE_OK_TO_ADD;1146int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;1147int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;1148int new_only = option & ADD_CACHE_NEW_ONLY;11491150if(!(option & ADD_CACHE_KEEP_CACHE_TREE))1151cache_tree_invalidate_path(istate, ce->name);11521153/*1154 * If this entry's path sorts after the last entry in the index,1155 * we can avoid searching for it.1156 */1157if(istate->cache_nr >0&&1158strcmp(ce->name, istate->cache[istate->cache_nr -1]->name) >0)1159 pos = -istate->cache_nr -1;1160else1161 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce));11621163/* existing match? Just replace it. */1164if(pos >=0) {1165if(!new_only)1166replace_index_entry(istate, pos, ce);1167return0;1168}1169 pos = -pos-1;11701171if(!(option & ADD_CACHE_KEEP_CACHE_TREE))1172untracked_cache_add_to_index(istate, ce->name);11731174/*1175 * Inserting a merged entry ("stage 0") into the index1176 * will always replace all non-merged entries..1177 */1178if(pos < istate->cache_nr &&ce_stage(ce) ==0) {1179while(ce_same_name(istate->cache[pos], ce)) {1180 ok_to_add =1;1181if(!remove_index_entry_at(istate, pos))1182break;1183}1184}11851186if(!ok_to_add)1187return-1;1188if(!verify_path(ce->name))1189returnerror("Invalid path '%s'", ce->name);11901191if(!skip_df_check &&1192check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {1193if(!ok_to_replace)1194returnerror("'%s' appears as both a file and as a directory",1195 ce->name);1196 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce));1197 pos = -pos-1;1198}1199return pos +1;1200}12011202intadd_index_entry(struct index_state *istate,struct cache_entry *ce,int option)1203{1204int pos;12051206if(option & ADD_CACHE_JUST_APPEND)1207 pos = istate->cache_nr;1208else{1209int ret;1210 ret =add_index_entry_with_check(istate, ce, option);1211if(ret <=0)1212return ret;1213 pos = ret -1;1214}12151216/* Make sure the array is big enough .. */1217ALLOC_GROW(istate->cache, istate->cache_nr +1, istate->cache_alloc);12181219/* Add it in.. */1220 istate->cache_nr++;1221if(istate->cache_nr > pos +1)1222MOVE_ARRAY(istate->cache + pos +1, istate->cache + pos,1223 istate->cache_nr - pos -1);1224set_index_entry(istate, pos, ce);1225 istate->cache_changed |= CE_ENTRY_ADDED;1226return0;1227}12281229/*1230 * "refresh" does not calculate a new sha1 file or bring the1231 * cache up-to-date for mode/content changes. But what it1232 * _does_ do is to "re-match" the stat information of a file1233 * with the cache, so that you can refresh the cache for a1234 * file that hasn't been changed but where the stat entry is1235 * out of date.1236 *1237 * For example, you'd want to do this after doing a "git-read-tree",1238 * to link up the stat cache details with the proper files.1239 */1240static struct cache_entry *refresh_cache_ent(struct index_state *istate,1241struct cache_entry *ce,1242unsigned int options,int*err,1243int*changed_ret)1244{1245struct stat st;1246struct cache_entry *updated;1247int changed, size;1248int refresh = options & CE_MATCH_REFRESH;1249int ignore_valid = options & CE_MATCH_IGNORE_VALID;1250int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;1251int ignore_missing = options & CE_MATCH_IGNORE_MISSING;1252int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;12531254if(!refresh ||ce_uptodate(ce))1255return ce;12561257if(!ignore_fsmonitor)1258refresh_fsmonitor(istate);1259/*1260 * CE_VALID or CE_SKIP_WORKTREE means the user promised us1261 * that the change to the work tree does not matter and told1262 * us not to worry.1263 */1264if(!ignore_skip_worktree &&ce_skip_worktree(ce)) {1265ce_mark_uptodate(ce);1266return ce;1267}1268if(!ignore_valid && (ce->ce_flags & CE_VALID)) {1269ce_mark_uptodate(ce);1270return ce;1271}1272if(!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {1273ce_mark_uptodate(ce);1274return ce;1275}12761277if(has_symlink_leading_path(ce->name,ce_namelen(ce))) {1278if(ignore_missing)1279return ce;1280if(err)1281*err = ENOENT;1282return NULL;1283}12841285if(lstat(ce->name, &st) <0) {1286if(ignore_missing && errno == ENOENT)1287return ce;1288if(err)1289*err = errno;1290return NULL;1291}12921293 changed =ie_match_stat(istate, ce, &st, options);1294if(changed_ret)1295*changed_ret = changed;1296if(!changed) {1297/*1298 * The path is unchanged. If we were told to ignore1299 * valid bit, then we did the actual stat check and1300 * found that the entry is unmodified. If the entry1301 * is not marked VALID, this is the place to mark it1302 * valid again, under "assume unchanged" mode.1303 */1304if(ignore_valid && assume_unchanged &&1305!(ce->ce_flags & CE_VALID))1306;/* mark this one VALID again */1307else{1308/*1309 * We do not mark the index itself "modified"1310 * because CE_UPTODATE flag is in-core only;1311 * we are not going to write this change out.1312 */1313if(!S_ISGITLINK(ce->ce_mode)) {1314ce_mark_uptodate(ce);1315mark_fsmonitor_valid(ce);1316}1317return ce;1318}1319}13201321if(ie_modified(istate, ce, &st, options)) {1322if(err)1323*err = EINVAL;1324return NULL;1325}13261327 size =ce_size(ce);1328 updated =xmalloc(size);1329copy_cache_entry(updated, ce);1330memcpy(updated->name, ce->name, ce->ce_namelen +1);1331fill_stat_cache_info(updated, &st);1332/*1333 * If ignore_valid is not set, we should leave CE_VALID bit1334 * alone. Otherwise, paths marked with --no-assume-unchanged1335 * (i.e. things to be edited) will reacquire CE_VALID bit1336 * automatically, which is not really what we want.1337 */1338if(!ignore_valid && assume_unchanged &&1339!(ce->ce_flags & CE_VALID))1340 updated->ce_flags &= ~CE_VALID;13411342/* istate->cache_changed is updated in the caller */1343return updated;1344}13451346static voidshow_file(const char* fmt,const char* name,int in_porcelain,1347int* first,const char*header_msg)1348{1349if(in_porcelain && *first && header_msg) {1350printf("%s\n", header_msg);1351*first =0;1352}1353printf(fmt, name);1354}13551356intrefresh_index(struct index_state *istate,unsigned int flags,1357const struct pathspec *pathspec,1358char*seen,const char*header_msg)1359{1360int i;1361int has_errors =0;1362int really = (flags & REFRESH_REALLY) !=0;1363int allow_unmerged = (flags & REFRESH_UNMERGED) !=0;1364int quiet = (flags & REFRESH_QUIET) !=0;1365int not_new = (flags & REFRESH_IGNORE_MISSING) !=0;1366int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) !=0;1367int first =1;1368int in_porcelain = (flags & REFRESH_IN_PORCELAIN);1369unsigned int options = (CE_MATCH_REFRESH |1370(really ? CE_MATCH_IGNORE_VALID :0) |1371(not_new ? CE_MATCH_IGNORE_MISSING :0));1372const char*modified_fmt;1373const char*deleted_fmt;1374const char*typechange_fmt;1375const char*added_fmt;1376const char*unmerged_fmt;1377uint64_t start =getnanotime();13781379 modified_fmt = (in_porcelain ?"M\t%s\n":"%s: needs update\n");1380 deleted_fmt = (in_porcelain ?"D\t%s\n":"%s: needs update\n");1381 typechange_fmt = (in_porcelain ?"T\t%s\n":"%sneeds update\n");1382 added_fmt = (in_porcelain ?"A\t%s\n":"%sneeds update\n");1383 unmerged_fmt = (in_porcelain ?"U\t%s\n":"%s: needs merge\n");1384for(i =0; i < istate->cache_nr; i++) {1385struct cache_entry *ce, *new_entry;1386int cache_errno =0;1387int changed =0;1388int filtered =0;13891390 ce = istate->cache[i];1391if(ignore_submodules &&S_ISGITLINK(ce->ce_mode))1392continue;13931394if(pathspec && !ce_path_match(ce, pathspec, seen))1395 filtered =1;13961397if(ce_stage(ce)) {1398while((i < istate->cache_nr) &&1399!strcmp(istate->cache[i]->name, ce->name))1400 i++;1401 i--;1402if(allow_unmerged)1403continue;1404if(!filtered)1405show_file(unmerged_fmt, ce->name, in_porcelain,1406&first, header_msg);1407 has_errors =1;1408continue;1409}14101411if(filtered)1412continue;14131414 new_entry =refresh_cache_ent(istate, ce, options, &cache_errno, &changed);1415if(new_entry == ce)1416continue;1417if(!new_entry) {1418const char*fmt;14191420if(really && cache_errno == EINVAL) {1421/* If we are doing --really-refresh that1422 * means the index is not valid anymore.1423 */1424 ce->ce_flags &= ~CE_VALID;1425 ce->ce_flags |= CE_UPDATE_IN_BASE;1426mark_fsmonitor_invalid(istate, ce);1427 istate->cache_changed |= CE_ENTRY_CHANGED;1428}1429if(quiet)1430continue;14311432if(cache_errno == ENOENT)1433 fmt = deleted_fmt;1434else if(ce_intent_to_add(ce))1435 fmt = added_fmt;/* must be before other checks */1436else if(changed & TYPE_CHANGED)1437 fmt = typechange_fmt;1438else1439 fmt = modified_fmt;1440show_file(fmt,1441 ce->name, in_porcelain, &first, header_msg);1442 has_errors =1;1443continue;1444}14451446replace_index_entry(istate, i, new_entry);1447}1448trace_performance_since(start,"refresh index");1449return has_errors;1450}14511452struct cache_entry *refresh_cache_entry(struct cache_entry *ce,1453unsigned int options)1454{1455returnrefresh_cache_ent(&the_index, ce, options, NULL, NULL);1456}145714581459/*****************************************************************1460 * Index File I/O1461 *****************************************************************/14621463#define INDEX_FORMAT_DEFAULT 314641465static unsigned intget_index_format_default(void)1466{1467char*envversion =getenv("GIT_INDEX_VERSION");1468char*endp;1469int value;1470unsigned int version = INDEX_FORMAT_DEFAULT;14711472if(!envversion) {1473if(!git_config_get_int("index.version", &value))1474 version = value;1475if(version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1476warning(_("index.version set, but the value is invalid.\n"1477"Using version%i"), INDEX_FORMAT_DEFAULT);1478return INDEX_FORMAT_DEFAULT;1479}1480return version;1481}14821483 version =strtoul(envversion, &endp,10);1484if(*endp ||1485 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1486warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"1487"Using version%i"), INDEX_FORMAT_DEFAULT);1488 version = INDEX_FORMAT_DEFAULT;1489}1490return version;1491}14921493/*1494 * dev/ino/uid/gid/size are also just tracked to the low 32 bits1495 * Again - this is just a (very strong in practice) heuristic that1496 * the inode hasn't changed.1497 *1498 * We save the fields in big-endian order to allow using the1499 * index file over NFS transparently.1500 */1501struct ondisk_cache_entry {1502struct cache_time ctime;1503struct cache_time mtime;1504uint32_t dev;1505uint32_t ino;1506uint32_t mode;1507uint32_t uid;1508uint32_t gid;1509uint32_t size;1510unsigned char sha1[20];1511uint16_t flags;1512char name[FLEX_ARRAY];/* more */1513};15141515/*1516 * This struct is used when CE_EXTENDED bit is 11517 * The struct must match ondisk_cache_entry exactly from1518 * ctime till flags1519 */1520struct ondisk_cache_entry_extended {1521struct cache_time ctime;1522struct cache_time mtime;1523uint32_t dev;1524uint32_t ino;1525uint32_t mode;1526uint32_t uid;1527uint32_t gid;1528uint32_t size;1529unsigned char sha1[20];1530uint16_t flags;1531uint16_t flags2;1532char name[FLEX_ARRAY];/* more */1533};15341535/* These are only used for v3 or lower */1536#define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)1537#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)1538#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)1539#define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)1540#define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \1541 ondisk_cache_entry_extended_size(ce_namelen(ce)) : \1542 ondisk_cache_entry_size(ce_namelen(ce)))15431544/* Allow fsck to force verification of the index checksum. */1545int verify_index_checksum;15461547/* Allow fsck to force verification of the cache entry order. */1548int verify_ce_order;15491550static intverify_hdr(struct cache_header *hdr,unsigned long size)1551{1552 git_hash_ctx c;1553unsigned char hash[GIT_MAX_RAWSZ];1554int hdr_version;15551556if(hdr->hdr_signature !=htonl(CACHE_SIGNATURE))1557returnerror("bad signature");1558 hdr_version =ntohl(hdr->hdr_version);1559if(hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)1560returnerror("bad index version%d", hdr_version);15611562if(!verify_index_checksum)1563return0;15641565 the_hash_algo->init_fn(&c);1566 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);1567 the_hash_algo->final_fn(hash, &c);1568if(hashcmp(hash, (unsigned char*)hdr + size - the_hash_algo->rawsz))1569returnerror("bad index file sha1 signature");1570return0;1571}15721573static intread_index_extension(struct index_state *istate,1574const char*ext,void*data,unsigned long sz)1575{1576switch(CACHE_EXT(ext)) {1577case CACHE_EXT_TREE:1578 istate->cache_tree =cache_tree_read(data, sz);1579break;1580case CACHE_EXT_RESOLVE_UNDO:1581 istate->resolve_undo =resolve_undo_read(data, sz);1582break;1583case CACHE_EXT_LINK:1584if(read_link_extension(istate, data, sz))1585return-1;1586break;1587case CACHE_EXT_UNTRACKED:1588 istate->untracked =read_untracked_extension(data, sz);1589break;1590case CACHE_EXT_FSMONITOR:1591read_fsmonitor_extension(istate, data, sz);1592break;1593default:1594if(*ext <'A'||'Z'< *ext)1595returnerror("index uses %.4s extension, which we do not understand",1596 ext);1597fprintf(stderr,"ignoring %.4s extension\n", ext);1598break;1599}1600return0;1601}16021603inthold_locked_index(struct lock_file *lk,int lock_flags)1604{1605returnhold_lock_file_for_update(lk,get_index_file(), lock_flags);1606}16071608intread_index(struct index_state *istate)1609{1610returnread_index_from(istate,get_index_file(),get_git_dir());1611}16121613static struct cache_entry *cache_entry_from_ondisk(struct ondisk_cache_entry *ondisk,1614unsigned int flags,1615const char*name,1616size_t len)1617{1618struct cache_entry *ce =xmalloc(cache_entry_size(len));16191620 ce->ce_stat_data.sd_ctime.sec =get_be32(&ondisk->ctime.sec);1621 ce->ce_stat_data.sd_mtime.sec =get_be32(&ondisk->mtime.sec);1622 ce->ce_stat_data.sd_ctime.nsec =get_be32(&ondisk->ctime.nsec);1623 ce->ce_stat_data.sd_mtime.nsec =get_be32(&ondisk->mtime.nsec);1624 ce->ce_stat_data.sd_dev =get_be32(&ondisk->dev);1625 ce->ce_stat_data.sd_ino =get_be32(&ondisk->ino);1626 ce->ce_mode =get_be32(&ondisk->mode);1627 ce->ce_stat_data.sd_uid =get_be32(&ondisk->uid);1628 ce->ce_stat_data.sd_gid =get_be32(&ondisk->gid);1629 ce->ce_stat_data.sd_size =get_be32(&ondisk->size);1630 ce->ce_flags = flags & ~CE_NAMEMASK;1631 ce->ce_namelen = len;1632 ce->index =0;1633hashcpy(ce->oid.hash, ondisk->sha1);1634memcpy(ce->name, name, len);1635 ce->name[len] ='\0';1636return ce;1637}16381639/*1640 * Adjacent cache entries tend to share the leading paths, so it makes1641 * sense to only store the differences in later entries. In the v41642 * on-disk format of the index, each on-disk cache entry stores the1643 * number of bytes to be stripped from the end of the previous name,1644 * and the bytes to append to the result, to come up with its name.1645 */1646static unsigned longexpand_name_field(struct strbuf *name,const char*cp_)1647{1648const unsigned char*ep, *cp = (const unsigned char*)cp_;1649size_t len =decode_varint(&cp);16501651if(name->len < len)1652die("malformed name field in the index");1653strbuf_remove(name, name->len - len, len);1654for(ep = cp; *ep; ep++)1655;/* find the end */1656strbuf_add(name, cp, ep - cp);1657return(const char*)ep +1- cp_;1658}16591660static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk,1661unsigned long*ent_size,1662struct strbuf *previous_name)1663{1664struct cache_entry *ce;1665size_t len;1666const char*name;1667unsigned int flags;16681669/* On-disk flags are just 16 bits */1670 flags =get_be16(&ondisk->flags);1671 len = flags & CE_NAMEMASK;16721673if(flags & CE_EXTENDED) {1674struct ondisk_cache_entry_extended *ondisk2;1675int extended_flags;1676 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;1677 extended_flags =get_be16(&ondisk2->flags2) <<16;1678/* We do not yet understand any bit out of CE_EXTENDED_FLAGS */1679if(extended_flags & ~CE_EXTENDED_FLAGS)1680die("Unknown index entry format%08x", extended_flags);1681 flags |= extended_flags;1682 name = ondisk2->name;1683}1684else1685 name = ondisk->name;16861687if(!previous_name) {1688/* v3 and earlier */1689if(len == CE_NAMEMASK)1690 len =strlen(name);1691 ce =cache_entry_from_ondisk(ondisk, flags, name, len);16921693*ent_size =ondisk_ce_size(ce);1694}else{1695unsigned long consumed;1696 consumed =expand_name_field(previous_name, name);1697 ce =cache_entry_from_ondisk(ondisk, flags,1698 previous_name->buf,1699 previous_name->len);17001701*ent_size = (name - ((char*)ondisk)) + consumed;1702}1703return ce;1704}17051706static voidcheck_ce_order(struct index_state *istate)1707{1708unsigned int i;17091710if(!verify_ce_order)1711return;17121713for(i =1; i < istate->cache_nr; i++) {1714struct cache_entry *ce = istate->cache[i -1];1715struct cache_entry *next_ce = istate->cache[i];1716int name_compare =strcmp(ce->name, next_ce->name);17171718if(0< name_compare)1719die("unordered stage entries in index");1720if(!name_compare) {1721if(!ce_stage(ce))1722die("multiple stage entries for merged file '%s'",1723 ce->name);1724if(ce_stage(ce) >ce_stage(next_ce))1725die("unordered stage entries for '%s'",1726 ce->name);1727}1728}1729}17301731static voidtweak_untracked_cache(struct index_state *istate)1732{1733switch(git_config_get_untracked_cache()) {1734case-1:/* keep: do nothing */1735break;1736case0:/* false */1737remove_untracked_cache(istate);1738break;1739case1:/* true */1740add_untracked_cache(istate);1741break;1742default:/* unknown value: do nothing */1743break;1744}1745}17461747static voidtweak_split_index(struct index_state *istate)1748{1749switch(git_config_get_split_index()) {1750case-1:/* unset: do nothing */1751break;1752case0:/* false */1753remove_split_index(istate);1754break;1755case1:/* true */1756add_split_index(istate);1757break;1758default:/* unknown value: do nothing */1759break;1760}1761}17621763static voidpost_read_index_from(struct index_state *istate)1764{1765check_ce_order(istate);1766tweak_untracked_cache(istate);1767tweak_split_index(istate);1768tweak_fsmonitor(istate);1769}17701771/* remember to discard_cache() before reading a different cache! */1772intdo_read_index(struct index_state *istate,const char*path,int must_exist)1773{1774int fd, i;1775struct stat st;1776unsigned long src_offset;1777struct cache_header *hdr;1778void*mmap;1779size_t mmap_size;1780struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;17811782if(istate->initialized)1783return istate->cache_nr;17841785 istate->timestamp.sec =0;1786 istate->timestamp.nsec =0;1787 fd =open(path, O_RDONLY);1788if(fd <0) {1789if(!must_exist && errno == ENOENT)1790return0;1791die_errno("%s: index file open failed", path);1792}17931794if(fstat(fd, &st))1795die_errno("cannot stat the open index");17961797 mmap_size =xsize_t(st.st_size);1798if(mmap_size <sizeof(struct cache_header) + the_hash_algo->rawsz)1799die("index file smaller than expected");18001801 mmap =xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd,0);1802if(mmap == MAP_FAILED)1803die_errno("unable to map index file");1804close(fd);18051806 hdr = mmap;1807if(verify_hdr(hdr, mmap_size) <0)1808goto unmap;18091810hashcpy(istate->sha1, (const unsigned char*)hdr + mmap_size - the_hash_algo->rawsz);1811 istate->version =ntohl(hdr->hdr_version);1812 istate->cache_nr =ntohl(hdr->hdr_entries);1813 istate->cache_alloc =alloc_nr(istate->cache_nr);1814 istate->cache =xcalloc(istate->cache_alloc,sizeof(*istate->cache));1815 istate->initialized =1;18161817if(istate->version ==4)1818 previous_name = &previous_name_buf;1819else1820 previous_name = NULL;18211822 src_offset =sizeof(*hdr);1823for(i =0; i < istate->cache_nr; i++) {1824struct ondisk_cache_entry *disk_ce;1825struct cache_entry *ce;1826unsigned long consumed;18271828 disk_ce = (struct ondisk_cache_entry *)((char*)mmap + src_offset);1829 ce =create_from_disk(disk_ce, &consumed, previous_name);1830set_index_entry(istate, i, ce);18311832 src_offset += consumed;1833}1834strbuf_release(&previous_name_buf);1835 istate->timestamp.sec = st.st_mtime;1836 istate->timestamp.nsec =ST_MTIME_NSEC(st);18371838while(src_offset <= mmap_size - the_hash_algo->rawsz -8) {1839/* After an array of active_nr index entries,1840 * there can be arbitrary number of extended1841 * sections, each of which is prefixed with1842 * extension name (4-byte) and section length1843 * in 4-byte network byte order.1844 */1845uint32_t extsize;1846memcpy(&extsize, (char*)mmap + src_offset +4,4);1847 extsize =ntohl(extsize);1848if(read_index_extension(istate,1849(const char*) mmap + src_offset,1850(char*) mmap + src_offset +8,1851 extsize) <0)1852goto unmap;1853 src_offset +=8;1854 src_offset += extsize;1855}1856munmap(mmap, mmap_size);1857return istate->cache_nr;18581859unmap:1860munmap(mmap, mmap_size);1861die("index file corrupt");1862}18631864/*1865 * Signal that the shared index is used by updating its mtime.1866 *1867 * This way, shared index can be removed if they have not been used1868 * for some time.1869 */1870static voidfreshen_shared_index(const char*shared_index,int warn)1871{1872if(!check_and_freshen_file(shared_index,1) && warn)1873warning("could not freshen shared index '%s'", shared_index);1874}18751876intread_index_from(struct index_state *istate,const char*path,1877const char*gitdir)1878{1879uint64_t start =getnanotime();1880struct split_index *split_index;1881int ret;1882char*base_sha1_hex;1883char*base_path;18841885/* istate->initialized covers both .git/index and .git/sharedindex.xxx */1886if(istate->initialized)1887return istate->cache_nr;18881889 ret =do_read_index(istate, path,0);1890trace_performance_since(start,"read cache%s", path);18911892 split_index = istate->split_index;1893if(!split_index ||is_null_sha1(split_index->base_sha1)) {1894post_read_index_from(istate);1895return ret;1896}18971898if(split_index->base)1899discard_index(split_index->base);1900else1901 split_index->base =xcalloc(1,sizeof(*split_index->base));19021903 base_sha1_hex =sha1_to_hex(split_index->base_sha1);1904 base_path =xstrfmt("%s/sharedindex.%s", gitdir, base_sha1_hex);1905 ret =do_read_index(split_index->base, base_path,1);1906if(hashcmp(split_index->base_sha1, split_index->base->sha1))1907die("broken index, expect%sin%s, got%s",1908 base_sha1_hex, base_path,1909sha1_to_hex(split_index->base->sha1));19101911freshen_shared_index(base_path,0);1912merge_base_index(istate);1913post_read_index_from(istate);1914trace_performance_since(start,"read cache%s", base_path);1915free(base_path);1916return ret;1917}19181919intis_index_unborn(struct index_state *istate)1920{1921return(!istate->cache_nr && !istate->timestamp.sec);1922}19231924intdiscard_index(struct index_state *istate)1925{1926int i;19271928for(i =0; i < istate->cache_nr; i++) {1929if(istate->cache[i]->index &&1930 istate->split_index &&1931 istate->split_index->base &&1932 istate->cache[i]->index <= istate->split_index->base->cache_nr &&1933 istate->cache[i] == istate->split_index->base->cache[istate->cache[i]->index -1])1934continue;1935free(istate->cache[i]);1936}1937resolve_undo_clear_index(istate);1938 istate->cache_nr =0;1939 istate->cache_changed =0;1940 istate->timestamp.sec =0;1941 istate->timestamp.nsec =0;1942free_name_hash(istate);1943cache_tree_free(&(istate->cache_tree));1944 istate->initialized =0;1945FREE_AND_NULL(istate->cache);1946 istate->cache_alloc =0;1947discard_split_index(istate);1948free_untracked_cache(istate->untracked);1949 istate->untracked = NULL;1950return0;1951}19521953intunmerged_index(const struct index_state *istate)1954{1955int i;1956for(i =0; i < istate->cache_nr; i++) {1957if(ce_stage(istate->cache[i]))1958return1;1959}1960return0;1961}19621963#define WRITE_BUFFER_SIZE 81921964static unsigned char write_buffer[WRITE_BUFFER_SIZE];1965static unsigned long write_buffer_len;19661967static intce_write_flush(git_hash_ctx *context,int fd)1968{1969unsigned int buffered = write_buffer_len;1970if(buffered) {1971 the_hash_algo->update_fn(context, write_buffer, buffered);1972if(write_in_full(fd, write_buffer, buffered) <0)1973return-1;1974 write_buffer_len =0;1975}1976return0;1977}19781979static intce_write(git_hash_ctx *context,int fd,void*data,unsigned int len)1980{1981while(len) {1982unsigned int buffered = write_buffer_len;1983unsigned int partial = WRITE_BUFFER_SIZE - buffered;1984if(partial > len)1985 partial = len;1986memcpy(write_buffer + buffered, data, partial);1987 buffered += partial;1988if(buffered == WRITE_BUFFER_SIZE) {1989 write_buffer_len = buffered;1990if(ce_write_flush(context, fd))1991return-1;1992 buffered =0;1993}1994 write_buffer_len = buffered;1995 len -= partial;1996 data = (char*) data + partial;1997}1998return0;1999}20002001static intwrite_index_ext_header(git_hash_ctx *context,int fd,2002unsigned int ext,unsigned int sz)2003{2004 ext =htonl(ext);2005 sz =htonl(sz);2006return((ce_write(context, fd, &ext,4) <0) ||2007(ce_write(context, fd, &sz,4) <0)) ? -1:0;2008}20092010static intce_flush(git_hash_ctx *context,int fd,unsigned char*hash)2011{2012unsigned int left = write_buffer_len;20132014if(left) {2015 write_buffer_len =0;2016 the_hash_algo->update_fn(context, write_buffer, left);2017}20182019/* Flush first if not enough space for hash signature */2020if(left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {2021if(write_in_full(fd, write_buffer, left) <0)2022return-1;2023 left =0;2024}20252026/* Append the hash signature at the end */2027 the_hash_algo->final_fn(write_buffer + left, context);2028hashcpy(hash, write_buffer + left);2029 left += the_hash_algo->rawsz;2030return(write_in_full(fd, write_buffer, left) <0) ? -1:0;2031}20322033static voidce_smudge_racily_clean_entry(struct cache_entry *ce)2034{2035/*2036 * The only thing we care about in this function is to smudge the2037 * falsely clean entry due to touch-update-touch race, so we leave2038 * everything else as they are. We are called for entries whose2039 * ce_stat_data.sd_mtime match the index file mtime.2040 *2041 * Note that this actually does not do much for gitlinks, for2042 * which ce_match_stat_basic() always goes to the actual2043 * contents. The caller checks with is_racy_timestamp() which2044 * always says "no" for gitlinks, so we are not called for them ;-)2045 */2046struct stat st;20472048if(lstat(ce->name, &st) <0)2049return;2050if(ce_match_stat_basic(ce, &st))2051return;2052if(ce_modified_check_fs(ce, &st)) {2053/* This is "racily clean"; smudge it. Note that this2054 * is a tricky code. At first glance, it may appear2055 * that it can break with this sequence:2056 *2057 * $ echo xyzzy >frotz2058 * $ git-update-index --add frotz2059 * $ : >frotz2060 * $ sleep 32061 * $ echo filfre >nitfol2062 * $ git-update-index --add nitfol2063 *2064 * but it does not. When the second update-index runs,2065 * it notices that the entry "frotz" has the same timestamp2066 * as index, and if we were to smudge it by resetting its2067 * size to zero here, then the object name recorded2068 * in index is the 6-byte file but the cached stat information2069 * becomes zero --- which would then match what we would2070 * obtain from the filesystem next time we stat("frotz").2071 *2072 * However, the second update-index, before calling2073 * this function, notices that the cached size is 62074 * bytes and what is on the filesystem is an empty2075 * file, and never calls us, so the cached size information2076 * for "frotz" stays 6 which does not match the filesystem.2077 */2078 ce->ce_stat_data.sd_size =0;2079}2080}20812082/* Copy miscellaneous fields but not the name */2083static voidcopy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,2084struct cache_entry *ce)2085{2086short flags;20872088 ondisk->ctime.sec =htonl(ce->ce_stat_data.sd_ctime.sec);2089 ondisk->mtime.sec =htonl(ce->ce_stat_data.sd_mtime.sec);2090 ondisk->ctime.nsec =htonl(ce->ce_stat_data.sd_ctime.nsec);2091 ondisk->mtime.nsec =htonl(ce->ce_stat_data.sd_mtime.nsec);2092 ondisk->dev =htonl(ce->ce_stat_data.sd_dev);2093 ondisk->ino =htonl(ce->ce_stat_data.sd_ino);2094 ondisk->mode =htonl(ce->ce_mode);2095 ondisk->uid =htonl(ce->ce_stat_data.sd_uid);2096 ondisk->gid =htonl(ce->ce_stat_data.sd_gid);2097 ondisk->size =htonl(ce->ce_stat_data.sd_size);2098hashcpy(ondisk->sha1, ce->oid.hash);20992100 flags = ce->ce_flags & ~CE_NAMEMASK;2101 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK :ce_namelen(ce));2102 ondisk->flags =htons(flags);2103if(ce->ce_flags & CE_EXTENDED) {2104struct ondisk_cache_entry_extended *ondisk2;2105 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;2106 ondisk2->flags2 =htons((ce->ce_flags & CE_EXTENDED_FLAGS) >>16);2107}2108}21092110static intce_write_entry(git_hash_ctx *c,int fd,struct cache_entry *ce,2111struct strbuf *previous_name,struct ondisk_cache_entry *ondisk)2112{2113int size;2114int result;2115unsigned int saved_namelen;2116int stripped_name =0;2117static unsigned char padding[8] = {0x00};21182119if(ce->ce_flags & CE_STRIP_NAME) {2120 saved_namelen =ce_namelen(ce);2121 ce->ce_namelen =0;2122 stripped_name =1;2123}21242125if(ce->ce_flags & CE_EXTENDED)2126 size =offsetof(struct ondisk_cache_entry_extended, name);2127else2128 size =offsetof(struct ondisk_cache_entry, name);21292130if(!previous_name) {2131int len =ce_namelen(ce);2132copy_cache_entry_to_ondisk(ondisk, ce);2133 result =ce_write(c, fd, ondisk, size);2134if(!result)2135 result =ce_write(c, fd, ce->name, len);2136if(!result)2137 result =ce_write(c, fd, padding,align_padding_size(size, len));2138}else{2139int common, to_remove, prefix_size;2140unsigned char to_remove_vi[16];2141for(common =0;2142(ce->name[common] &&2143 common < previous_name->len &&2144 ce->name[common] == previous_name->buf[common]);2145 common++)2146;/* still matching */2147 to_remove = previous_name->len - common;2148 prefix_size =encode_varint(to_remove, to_remove_vi);21492150copy_cache_entry_to_ondisk(ondisk, ce);2151 result =ce_write(c, fd, ondisk, size);2152if(!result)2153 result =ce_write(c, fd, to_remove_vi, prefix_size);2154if(!result)2155 result =ce_write(c, fd, ce->name + common,ce_namelen(ce) - common);2156if(!result)2157 result =ce_write(c, fd, padding,1);21582159strbuf_splice(previous_name, common, to_remove,2160 ce->name + common,ce_namelen(ce) - common);2161}2162if(stripped_name) {2163 ce->ce_namelen = saved_namelen;2164 ce->ce_flags &= ~CE_STRIP_NAME;2165}21662167return result;2168}21692170/*2171 * This function verifies if index_state has the correct sha1 of the2172 * index file. Don't die if we have any other failure, just return 0.2173 */2174static intverify_index_from(const struct index_state *istate,const char*path)2175{2176int fd;2177 ssize_t n;2178struct stat st;2179unsigned char hash[GIT_MAX_RAWSZ];21802181if(!istate->initialized)2182return0;21832184 fd =open(path, O_RDONLY);2185if(fd <0)2186return0;21872188if(fstat(fd, &st))2189goto out;21902191if(st.st_size <sizeof(struct cache_header) + the_hash_algo->rawsz)2192goto out;21932194 n =pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);2195if(n != the_hash_algo->rawsz)2196goto out;21972198if(hashcmp(istate->sha1, hash))2199goto out;22002201close(fd);2202return1;22032204out:2205close(fd);2206return0;2207}22082209static intverify_index(const struct index_state *istate)2210{2211returnverify_index_from(istate,get_index_file());2212}22132214static inthas_racy_timestamp(struct index_state *istate)2215{2216int entries = istate->cache_nr;2217int i;22182219for(i =0; i < entries; i++) {2220struct cache_entry *ce = istate->cache[i];2221if(is_racy_timestamp(istate, ce))2222return1;2223}2224return0;2225}22262227voidupdate_index_if_able(struct index_state *istate,struct lock_file *lockfile)2228{2229if((istate->cache_changed ||has_racy_timestamp(istate)) &&2230verify_index(istate))2231write_locked_index(istate, lockfile, COMMIT_LOCK);2232else2233rollback_lock_file(lockfile);2234}22352236/*2237 * On success, `tempfile` is closed. If it is the temporary file2238 * of a `struct lock_file`, we will therefore effectively perform2239 * a 'close_lock_file_gently()`. Since that is an implementation2240 * detail of lockfiles, callers of `do_write_index()` should not2241 * rely on it.2242 */2243static intdo_write_index(struct index_state *istate,struct tempfile *tempfile,2244int strip_extensions)2245{2246uint64_t start =getnanotime();2247int newfd = tempfile->fd;2248 git_hash_ctx c;2249struct cache_header hdr;2250int i, err =0, removed, extended, hdr_version;2251struct cache_entry **cache = istate->cache;2252int entries = istate->cache_nr;2253struct stat st;2254struct ondisk_cache_entry_extended ondisk;2255struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;2256int drop_cache_tree = istate->drop_cache_tree;22572258for(i = removed = extended =0; i < entries; i++) {2259if(cache[i]->ce_flags & CE_REMOVE)2260 removed++;22612262/* reduce extended entries if possible */2263 cache[i]->ce_flags &= ~CE_EXTENDED;2264if(cache[i]->ce_flags & CE_EXTENDED_FLAGS) {2265 extended++;2266 cache[i]->ce_flags |= CE_EXTENDED;2267}2268}22692270if(!istate->version) {2271 istate->version =get_index_format_default();2272if(getenv("GIT_TEST_SPLIT_INDEX"))2273init_split_index(istate);2274}22752276/* demote version 3 to version 2 when the latter suffices */2277if(istate->version ==3|| istate->version ==2)2278 istate->version = extended ?3:2;22792280 hdr_version = istate->version;22812282 hdr.hdr_signature =htonl(CACHE_SIGNATURE);2283 hdr.hdr_version =htonl(hdr_version);2284 hdr.hdr_entries =htonl(entries - removed);22852286 the_hash_algo->init_fn(&c);2287if(ce_write(&c, newfd, &hdr,sizeof(hdr)) <0)2288return-1;22892290 previous_name = (hdr_version ==4) ? &previous_name_buf : NULL;22912292for(i =0; i < entries; i++) {2293struct cache_entry *ce = cache[i];2294if(ce->ce_flags & CE_REMOVE)2295continue;2296if(!ce_uptodate(ce) &&is_racy_timestamp(istate, ce))2297ce_smudge_racily_clean_entry(ce);2298if(is_null_oid(&ce->oid)) {2299static const char msg[] ="cache entry has null sha1:%s";2300static int allow = -1;23012302if(allow <0)2303 allow =git_env_bool("GIT_ALLOW_NULL_SHA1",0);2304if(allow)2305warning(msg, ce->name);2306else2307 err =error(msg, ce->name);23082309 drop_cache_tree =1;2310}2311if(ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) <0)2312 err = -1;23132314if(err)2315break;2316}2317strbuf_release(&previous_name_buf);23182319if(err)2320return err;23212322/* Write extension data here */2323if(!strip_extensions && istate->split_index) {2324struct strbuf sb = STRBUF_INIT;23252326 err =write_link_extension(&sb, istate) <0||2327write_index_ext_header(&c, newfd, CACHE_EXT_LINK,2328 sb.len) <0||2329ce_write(&c, newfd, sb.buf, sb.len) <0;2330strbuf_release(&sb);2331if(err)2332return-1;2333}2334if(!strip_extensions && !drop_cache_tree && istate->cache_tree) {2335struct strbuf sb = STRBUF_INIT;23362337cache_tree_write(&sb, istate->cache_tree);2338 err =write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) <02339||ce_write(&c, newfd, sb.buf, sb.len) <0;2340strbuf_release(&sb);2341if(err)2342return-1;2343}2344if(!strip_extensions && istate->resolve_undo) {2345struct strbuf sb = STRBUF_INIT;23462347resolve_undo_write(&sb, istate->resolve_undo);2348 err =write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,2349 sb.len) <02350||ce_write(&c, newfd, sb.buf, sb.len) <0;2351strbuf_release(&sb);2352if(err)2353return-1;2354}2355if(!strip_extensions && istate->untracked) {2356struct strbuf sb = STRBUF_INIT;23572358write_untracked_extension(&sb, istate->untracked);2359 err =write_index_ext_header(&c, newfd, CACHE_EXT_UNTRACKED,2360 sb.len) <0||2361ce_write(&c, newfd, sb.buf, sb.len) <0;2362strbuf_release(&sb);2363if(err)2364return-1;2365}2366if(!strip_extensions && istate->fsmonitor_last_update) {2367struct strbuf sb = STRBUF_INIT;23682369write_fsmonitor_extension(&sb, istate);2370 err =write_index_ext_header(&c, newfd, CACHE_EXT_FSMONITOR, sb.len) <02371||ce_write(&c, newfd, sb.buf, sb.len) <0;2372strbuf_release(&sb);2373if(err)2374return-1;2375}23762377if(ce_flush(&c, newfd, istate->sha1))2378return-1;2379if(close_tempfile_gently(tempfile)) {2380error(_("could not close '%s'"), tempfile->filename.buf);2381return-1;2382}2383if(stat(tempfile->filename.buf, &st))2384return-1;2385 istate->timestamp.sec = (unsigned int)st.st_mtime;2386 istate->timestamp.nsec =ST_MTIME_NSEC(st);2387trace_performance_since(start,"write index, changed mask =%x", istate->cache_changed);2388return0;2389}23902391voidset_alternate_index_output(const char*name)2392{2393 alternate_index_output = name;2394}23952396static intcommit_locked_index(struct lock_file *lk)2397{2398if(alternate_index_output)2399returncommit_lock_file_to(lk, alternate_index_output);2400else2401returncommit_lock_file(lk);2402}24032404static intdo_write_locked_index(struct index_state *istate,struct lock_file *lock,2405unsigned flags)2406{2407int ret =do_write_index(istate, lock->tempfile,0);2408if(ret)2409return ret;2410if(flags & COMMIT_LOCK)2411returncommit_locked_index(lock);2412returnclose_lock_file_gently(lock);2413}24142415static intwrite_split_index(struct index_state *istate,2416struct lock_file *lock,2417unsigned flags)2418{2419int ret;2420prepare_to_write_split_index(istate);2421 ret =do_write_locked_index(istate, lock, flags);2422finish_writing_split_index(istate);2423return ret;2424}24252426static const char*shared_index_expire ="2.weeks.ago";24272428static unsigned longget_shared_index_expire_date(void)2429{2430static unsigned long shared_index_expire_date;2431static int shared_index_expire_date_prepared;24322433if(!shared_index_expire_date_prepared) {2434git_config_get_expiry("splitindex.sharedindexexpire",2435&shared_index_expire);2436 shared_index_expire_date =approxidate(shared_index_expire);2437 shared_index_expire_date_prepared =1;2438}24392440return shared_index_expire_date;2441}24422443static intshould_delete_shared_index(const char*shared_index_path)2444{2445struct stat st;2446unsigned long expiration;24472448/* Check timestamp */2449 expiration =get_shared_index_expire_date();2450if(!expiration)2451return0;2452if(stat(shared_index_path, &st))2453returnerror_errno(_("could not stat '%s'"), shared_index_path);2454if(st.st_mtime > expiration)2455return0;24562457return1;2458}24592460static intclean_shared_index_files(const char*current_hex)2461{2462struct dirent *de;2463DIR*dir =opendir(get_git_dir());24642465if(!dir)2466returnerror_errno(_("unable to open git dir:%s"),get_git_dir());24672468while((de =readdir(dir)) != NULL) {2469const char*sha1_hex;2470const char*shared_index_path;2471if(!skip_prefix(de->d_name,"sharedindex.", &sha1_hex))2472continue;2473if(!strcmp(sha1_hex, current_hex))2474continue;2475 shared_index_path =git_path("%s", de->d_name);2476if(should_delete_shared_index(shared_index_path) >0&&2477unlink(shared_index_path))2478warning_errno(_("unable to unlink:%s"), shared_index_path);2479}2480closedir(dir);24812482return0;2483}24842485static intwrite_shared_index(struct index_state *istate,2486struct tempfile **temp)2487{2488struct split_index *si = istate->split_index;2489int ret;24902491move_cache_to_base_index(istate);2492 ret =do_write_index(si->base, *temp,1);2493if(ret)2494return ret;2495 ret =adjust_shared_perm(get_tempfile_path(*temp));2496if(ret) {2497error("cannot fix permission bits on%s",get_tempfile_path(*temp));2498return ret;2499}2500 ret =rename_tempfile(temp,2501git_path("sharedindex.%s",sha1_to_hex(si->base->sha1)));2502if(!ret) {2503hashcpy(si->base_sha1, si->base->sha1);2504clean_shared_index_files(sha1_to_hex(si->base->sha1));2505}25062507return ret;2508}25092510static const int default_max_percent_split_change =20;25112512static inttoo_many_not_shared_entries(struct index_state *istate)2513{2514int i, not_shared =0;2515int max_split =git_config_get_max_percent_split_change();25162517switch(max_split) {2518case-1:2519/* not or badly configured: use the default value */2520 max_split = default_max_percent_split_change;2521break;2522case0:2523return1;/* 0% means always write a new shared index */2524case100:2525return0;/* 100% means never write a new shared index */2526default:2527break;/* just use the configured value */2528}25292530/* Count not shared entries */2531for(i =0; i < istate->cache_nr; i++) {2532struct cache_entry *ce = istate->cache[i];2533if(!ce->index)2534 not_shared++;2535}25362537return(int64_t)istate->cache_nr * max_split < (int64_t)not_shared *100;2538}25392540intwrite_locked_index(struct index_state *istate,struct lock_file *lock,2541unsigned flags)2542{2543int new_shared_index, ret;2544struct split_index *si = istate->split_index;25452546if((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {2547if(flags & COMMIT_LOCK)2548rollback_lock_file(lock);2549return0;2550}25512552if(istate->fsmonitor_last_update)2553fill_fsmonitor_bitmap(istate);25542555if(!si || alternate_index_output ||2556(istate->cache_changed & ~EXTMASK)) {2557if(si)2558hashclr(si->base_sha1);2559 ret =do_write_locked_index(istate, lock, flags);2560goto out;2561}25622563if(getenv("GIT_TEST_SPLIT_INDEX")) {2564int v = si->base_sha1[0];2565if((v &15) <6)2566 istate->cache_changed |= SPLIT_INDEX_ORDERED;2567}2568if(too_many_not_shared_entries(istate))2569 istate->cache_changed |= SPLIT_INDEX_ORDERED;25702571 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;25722573if(new_shared_index) {2574struct tempfile *temp;2575int saved_errno;25762577 temp =mks_tempfile(git_path("sharedindex_XXXXXX"));2578if(!temp) {2579hashclr(si->base_sha1);2580 ret =do_write_locked_index(istate, lock, flags);2581goto out;2582}2583 ret =write_shared_index(istate, &temp);25842585 saved_errno = errno;2586if(is_tempfile_active(temp))2587delete_tempfile(&temp);2588 errno = saved_errno;25892590if(ret)2591goto out;2592}25932594 ret =write_split_index(istate, lock, flags);25952596/* Freshen the shared index only if the split-index was written */2597if(!ret && !new_shared_index) {2598const char*shared_index =git_path("sharedindex.%s",2599sha1_to_hex(si->base_sha1));2600freshen_shared_index(shared_index,1);2601}26022603out:2604if(flags & COMMIT_LOCK)2605rollback_lock_file(lock);2606return ret;2607}26082609/*2610 * Read the index file that is potentially unmerged into given2611 * index_state, dropping any unmerged entries. Returns true if2612 * the index is unmerged. Callers who want to refuse to work2613 * from an unmerged state can call this and check its return value,2614 * instead of calling read_cache().2615 */2616intread_index_unmerged(struct index_state *istate)2617{2618int i;2619int unmerged =0;26202621read_index(istate);2622for(i =0; i < istate->cache_nr; i++) {2623struct cache_entry *ce = istate->cache[i];2624struct cache_entry *new_ce;2625int size, len;26262627if(!ce_stage(ce))2628continue;2629 unmerged =1;2630 len =ce_namelen(ce);2631 size =cache_entry_size(len);2632 new_ce =xcalloc(1, size);2633memcpy(new_ce->name, ce->name, len);2634 new_ce->ce_flags =create_ce_flags(0) | CE_CONFLICTED;2635 new_ce->ce_namelen = len;2636 new_ce->ce_mode = ce->ce_mode;2637if(add_index_entry(istate, new_ce,0))2638returnerror("%s: cannot drop to stage #0",2639 new_ce->name);2640}2641return unmerged;2642}26432644/*2645 * Returns 1 if the path is an "other" path with respect to2646 * the index; that is, the path is not mentioned in the index at all,2647 * either as a file, a directory with some files in the index,2648 * or as an unmerged entry.2649 *2650 * We helpfully remove a trailing "/" from directories so that2651 * the output of read_directory can be used as-is.2652 */2653intindex_name_is_other(const struct index_state *istate,const char*name,2654int namelen)2655{2656int pos;2657if(namelen && name[namelen -1] =='/')2658 namelen--;2659 pos =index_name_pos(istate, name, namelen);2660if(0<= pos)2661return0;/* exact match */2662 pos = -pos -1;2663if(pos < istate->cache_nr) {2664struct cache_entry *ce = istate->cache[pos];2665if(ce_namelen(ce) == namelen &&2666!memcmp(ce->name, name, namelen))2667return0;/* Yup, this one exists unmerged */2668}2669return1;2670}26712672void*read_blob_data_from_index(const struct index_state *istate,2673const char*path,unsigned long*size)2674{2675int pos, len;2676unsigned long sz;2677enum object_type type;2678void*data;26792680 len =strlen(path);2681 pos =index_name_pos(istate, path, len);2682if(pos <0) {2683/*2684 * We might be in the middle of a merge, in which2685 * case we would read stage #2 (ours).2686 */2687int i;2688for(i = -pos -1;2689(pos <0&& i < istate->cache_nr &&2690!strcmp(istate->cache[i]->name, path));2691 i++)2692if(ce_stage(istate->cache[i]) ==2)2693 pos = i;2694}2695if(pos <0)2696return NULL;2697 data =read_object_file(&istate->cache[pos]->oid, &type, &sz);2698if(!data || type != OBJ_BLOB) {2699free(data);2700return NULL;2701}2702if(size)2703*size = sz;2704return data;2705}27062707voidstat_validity_clear(struct stat_validity *sv)2708{2709FREE_AND_NULL(sv->sd);2710}27112712intstat_validity_check(struct stat_validity *sv,const char*path)2713{2714struct stat st;27152716if(stat(path, &st) <0)2717return sv->sd == NULL;2718if(!sv->sd)2719return0;2720returnS_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);2721}27222723voidstat_validity_update(struct stat_validity *sv,int fd)2724{2725struct stat st;27262727if(fstat(fd, &st) <0|| !S_ISREG(st.st_mode))2728stat_validity_clear(sv);2729else{2730if(!sv->sd)2731 sv->sd =xcalloc(1,sizeof(struct stat_data));2732fill_stat_data(sv->sd, &st);2733}2734}27352736voidmove_index_extensions(struct index_state *dst,struct index_state *src)2737{2738 dst->untracked = src->untracked;2739 src->untracked = NULL;2740}