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 63staticinlinestruct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool,size_t len) 64{ 65struct cache_entry *ce; 66 ce =mem_pool_alloc(mem_pool,cache_entry_size(len)); 67 ce->mem_pool_allocated =1; 68return ce; 69} 70 71staticinlinestruct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool,size_t len) 72{ 73struct cache_entry * ce; 74 ce =mem_pool_calloc(mem_pool,1,cache_entry_size(len)); 75 ce->mem_pool_allocated =1; 76return ce; 77} 78 79static struct mem_pool *find_mem_pool(struct index_state *istate) 80{ 81struct mem_pool **pool_ptr; 82 83if(istate->split_index && istate->split_index->base) 84 pool_ptr = &istate->split_index->base->ce_mem_pool; 85else 86 pool_ptr = &istate->ce_mem_pool; 87 88if(!*pool_ptr) 89mem_pool_init(pool_ptr,0); 90 91return*pool_ptr; 92} 93 94struct index_state the_index; 95static const char*alternate_index_output; 96 97static voidset_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 98{ 99 istate->cache[nr] = ce; 100add_name_hash(istate, ce); 101} 102 103static voidreplace_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 104{ 105struct cache_entry *old = istate->cache[nr]; 106 107replace_index_entry_in_base(istate, old, ce); 108remove_name_hash(istate, old); 109discard_cache_entry(old); 110 ce->ce_flags &= ~CE_HASHED; 111set_index_entry(istate, nr, ce); 112 ce->ce_flags |= CE_UPDATE_IN_BASE; 113mark_fsmonitor_invalid(istate, ce); 114 istate->cache_changed |= CE_ENTRY_CHANGED; 115} 116 117voidrename_index_entry_at(struct index_state *istate,int nr,const char*new_name) 118{ 119struct cache_entry *old_entry = istate->cache[nr], *new_entry; 120int namelen =strlen(new_name); 121 122 new_entry =make_empty_cache_entry(istate, namelen); 123copy_cache_entry(new_entry, old_entry); 124 new_entry->ce_flags &= ~CE_HASHED; 125 new_entry->ce_namelen = namelen; 126 new_entry->index =0; 127memcpy(new_entry->name, new_name, namelen +1); 128 129cache_tree_invalidate_path(istate, old_entry->name); 130untracked_cache_remove_from_index(istate, old_entry->name); 131remove_index_entry_at(istate, nr); 132add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE); 133} 134 135voidfill_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 148intmatch_stat_data(const struct stat_data *sd,struct stat *st) 149{ 150int changed =0; 151 152if(sd->sd_mtime.sec != (unsigned int)st->st_mtime) 153 changed |= MTIME_CHANGED; 154if(trust_ctime && check_stat && 155 sd->sd_ctime.sec != (unsigned int)st->st_ctime) 156 changed |= CTIME_CHANGED; 157 158#ifdef USE_NSEC 159if(check_stat && sd->sd_mtime.nsec !=ST_MTIME_NSEC(*st)) 160 changed |= MTIME_CHANGED; 161if(trust_ctime && check_stat && 162 sd->sd_ctime.nsec !=ST_CTIME_NSEC(*st)) 163 changed |= CTIME_CHANGED; 164#endif 165 166if(check_stat) { 167if(sd->sd_uid != (unsigned int) st->st_uid || 168 sd->sd_gid != (unsigned int) st->st_gid) 169 changed |= OWNER_CHANGED; 170if(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 */ 180if(check_stat && sd->sd_dev != (unsigned int) st->st_dev) 181 changed |= INODE_CHANGED; 182#endif 183 184if(sd->sd_size != (unsigned int) st->st_size) 185 changed |= DATA_CHANGED; 186 187return 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 */ 195voidfill_stat_cache_info(struct cache_entry *ce,struct stat *st) 196{ 197fill_stat_data(&ce->ce_stat_data, st); 198 199if(assume_unchanged) 200 ce->ce_flags |= CE_VALID; 201 202if(S_ISREG(st->st_mode)) { 203ce_mark_uptodate(ce); 204mark_fsmonitor_valid(ce); 205} 206} 207 208static intce_compare_data(struct index_state *istate, 209const struct cache_entry *ce, 210struct stat *st) 211{ 212int match = -1; 213int fd =git_open_cloexec(ce->name, O_RDONLY); 214 215if(fd >=0) { 216struct object_id oid; 217if(!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} 221return match; 222} 223 224static intce_compare_link(const struct cache_entry *ce,size_t expected_size) 225{ 226int match = -1; 227void*buffer; 228unsigned long size; 229enum object_type type; 230struct strbuf sb = STRBUF_INIT; 231 232if(strbuf_readlink(&sb, ce->name, expected_size)) 233return-1; 234 235 buffer =read_object_file(&ce->oid, &type, &size); 236if(buffer) { 237if(size == sb.len) 238 match =memcmp(buffer, sb.buf, size); 239free(buffer); 240} 241strbuf_release(&sb); 242return match; 243} 244 245static intce_compare_gitlink(const struct cache_entry *ce) 246{ 247struct 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 */ 257if(resolve_gitlink_ref(ce->name,"HEAD", &oid) <0) 258return0; 259return!oideq(&oid, &ce->oid); 260} 261 262static intce_modified_check_fs(struct index_state *istate, 263const struct cache_entry *ce, 264struct stat *st) 265{ 266switch(st->st_mode & S_IFMT) { 267case S_IFREG: 268if(ce_compare_data(istate, ce, st)) 269return DATA_CHANGED; 270break; 271case S_IFLNK: 272if(ce_compare_link(ce,xsize_t(st->st_size))) 273return DATA_CHANGED; 274break; 275case S_IFDIR: 276if(S_ISGITLINK(ce->ce_mode)) 277returnce_compare_gitlink(ce) ? DATA_CHANGED :0; 278/* else fallthrough */ 279default: 280return TYPE_CHANGED; 281} 282return0; 283} 284 285static intce_match_stat_basic(const struct cache_entry *ce,struct stat *st) 286{ 287unsigned int changed =0; 288 289if(ce->ce_flags & CE_REMOVE) 290return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED; 291 292switch(ce->ce_mode & S_IFMT) { 293case 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 */ 298if(trust_executable_bit && 299(0100& (ce->ce_mode ^ st->st_mode))) 300 changed |= MODE_CHANGED; 301break; 302case S_IFLNK: 303if(!S_ISLNK(st->st_mode) && 304(has_symlinks || !S_ISREG(st->st_mode))) 305 changed |= TYPE_CHANGED; 306break; 307case S_IFGITLINK: 308/* We ignore most of the st_xxx fields for gitlinks */ 309if(!S_ISDIR(st->st_mode)) 310 changed |= TYPE_CHANGED; 311else if(ce_compare_gitlink(ce)) 312 changed |= DATA_CHANGED; 313return changed; 314default: 315die("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? */ 321if(!ce->ce_stat_data.sd_size) { 322if(!is_empty_blob_sha1(ce->oid.hash)) 323 changed |= DATA_CHANGED; 324} 325 326return changed; 327} 328 329static intis_racy_stat(const struct index_state *istate, 330const struct stat_data *sd) 331{ 332return(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 intis_racy_timestamp(const struct index_state *istate, 345const struct cache_entry *ce) 346{ 347return(!S_ISGITLINK(ce->ce_mode) && 348is_racy_stat(istate, &ce->ce_stat_data)); 349} 350 351intmatch_stat_data_racy(const struct index_state *istate, 352const struct stat_data *sd,struct stat *st) 353{ 354if(is_racy_stat(istate, sd)) 355return MTIME_CHANGED; 356returnmatch_stat_data(sd, st); 357} 358 359intie_match_stat(struct index_state *istate, 360const struct cache_entry *ce,struct stat *st, 361unsigned int options) 362{ 363unsigned int changed; 364int ignore_valid = options & CE_MATCH_IGNORE_VALID; 365int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE; 366int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY; 367int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR; 368 369if(!ignore_fsmonitor) 370refresh_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 */ 377if(!ignore_skip_worktree &&ce_skip_worktree(ce)) 378return0; 379if(!ignore_valid && (ce->ce_flags & CE_VALID)) 380return0; 381if(!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) 382return0; 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 */ 389if(ce_intent_to_add(ce)) 390return 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 */ 410if(!changed &&is_racy_timestamp(istate, ce)) { 411if(assume_racy_is_modified) 412 changed |= DATA_CHANGED; 413else 414 changed |=ce_modified_check_fs(istate, ce, st); 415} 416 417return changed; 418} 419 420intie_modified(struct index_state *istate, 421const struct cache_entry *ce, 422struct stat *st,unsigned int options) 423{ 424int changed, changed_fs; 425 426 changed =ie_match_stat(istate, ce, st, options); 427if(!changed) 428return0; 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 */ 433if(changed & (MODE_CHANGED | TYPE_CHANGED)) 434return 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 */ 450if((changed & DATA_CHANGED) && 451(S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size !=0)) 452return changed; 453 454 changed_fs =ce_modified_check_fs(istate, ce, st); 455if(changed_fs) 456return changed | changed_fs; 457return0; 458} 459 460intbase_name_compare(const char*name1,int len1,int mode1, 461const char*name2,int len2,int mode2) 462{ 463unsigned char c1, c2; 464int len = len1 < len2 ? len1 : len2; 465int cmp; 466 467 cmp =memcmp(name1, name2, len); 468if(cmp) 469return cmp; 470 c1 = name1[len]; 471 c2 = name2[len]; 472if(!c1 &&S_ISDIR(mode1)) 473 c1 ='/'; 474if(!c2 &&S_ISDIR(mode2)) 475 c2 ='/'; 476return(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 */ 489intdf_name_compare(const char*name1,int len1,int mode1, 490const char*name2,int len2,int mode2) 491{ 492int len = len1 < len2 ? len1 : len2, cmp; 493unsigned char c1, c2; 494 495 cmp =memcmp(name1, name2, len); 496if(cmp) 497return cmp; 498/* Directories and files compare equal (same length, same name) */ 499if(len1 == len2) 500return0; 501 c1 = name1[len]; 502if(!c1 &&S_ISDIR(mode1)) 503 c1 ='/'; 504 c2 = name2[len]; 505if(!c2 &&S_ISDIR(mode2)) 506 c2 ='/'; 507if(c1 =='/'&& !c2) 508return0; 509if(c2 =='/'&& !c1) 510return0; 511return c1 - c2; 512} 513 514intname_compare(const char*name1,size_t len1,const char*name2,size_t len2) 515{ 516size_t min_len = (len1 < len2) ? len1 : len2; 517int cmp =memcmp(name1, name2, min_len); 518if(cmp) 519return cmp; 520if(len1 < len2) 521return-1; 522if(len1 > len2) 523return1; 524return0; 525} 526 527intcache_name_stage_compare(const char*name1,int len1,int stage1,const char*name2,int len2,int stage2) 528{ 529int cmp; 530 531 cmp =name_compare(name1, len1, name2, len2); 532if(cmp) 533return cmp; 534 535if(stage1 < stage2) 536return-1; 537if(stage1 > stage2) 538return1; 539return0; 540} 541 542static intindex_name_stage_pos(const struct index_state *istate,const char*name,int namelen,int stage) 543{ 544int first, last; 545 546 first =0; 547 last = istate->cache_nr; 548while(last > first) { 549int next = (last + first) >>1; 550struct cache_entry *ce = istate->cache[next]; 551int cmp =cache_name_stage_compare(name, namelen, stage, ce->name,ce_namelen(ce),ce_stage(ce)); 552if(!cmp) 553return next; 554if(cmp <0) { 555 last = next; 556continue; 557} 558 first = next+1; 559} 560return-first-1; 561} 562 563intindex_name_pos(const struct index_state *istate,const char*name,int namelen) 564{ 565returnindex_name_stage_pos(istate, name, namelen,0); 566} 567 568intremove_index_entry_at(struct index_state *istate,int pos) 569{ 570struct cache_entry *ce = istate->cache[pos]; 571 572record_resolve_undo(istate, ce); 573remove_name_hash(istate, ce); 574save_or_free_index_entry(istate, ce); 575 istate->cache_changed |= CE_ENTRY_REMOVED; 576 istate->cache_nr--; 577if(pos >= istate->cache_nr) 578return0; 579MOVE_ARRAY(istate->cache + pos, istate->cache + pos +1, 580 istate->cache_nr - pos); 581return1; 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 */ 589voidremove_marked_cache_entries(struct index_state *istate) 590{ 591struct cache_entry **ce_array = istate->cache; 592unsigned int i, j; 593 594for(i = j =0; i < istate->cache_nr; i++) { 595if(ce_array[i]->ce_flags & CE_REMOVE) { 596remove_name_hash(istate, ce_array[i]); 597save_or_free_index_entry(istate, ce_array[i]); 598} 599else 600 ce_array[j++] = ce_array[i]; 601} 602if(j == istate->cache_nr) 603return; 604 istate->cache_changed |= CE_ENTRY_REMOVED; 605 istate->cache_nr = j; 606} 607 608intremove_file_from_index(struct index_state *istate,const char*path) 609{ 610int pos =index_name_pos(istate, path,strlen(path)); 611if(pos <0) 612 pos = -pos-1; 613cache_tree_invalidate_path(istate, path); 614untracked_cache_remove_from_index(istate, path); 615while(pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path)) 616remove_index_entry_at(istate, pos); 617return0; 618} 619 620static intcompare_name(struct cache_entry *ce,const char*path,int namelen) 621{ 622return namelen !=ce_namelen(ce) ||memcmp(path, ce->name, namelen); 623} 624 625static intindex_name_pos_also_unmerged(struct index_state *istate, 626const char*path,int namelen) 627{ 628int pos =index_name_pos(istate, path, namelen); 629struct cache_entry *ce; 630 631if(pos >=0) 632return pos; 633 634/* maybe unmerged? */ 635 pos = -1- pos; 636if(pos >= istate->cache_nr || 637compare_name((ce = istate->cache[pos]), path, namelen)) 638return-1; 639 640/* order of preference: stage 2, 1, 3 */ 641if(ce_stage(ce) ==1&& pos +1< istate->cache_nr && 642ce_stage((ce = istate->cache[pos +1])) ==2&& 643!compare_name(ce, path, namelen)) 644 pos++; 645return pos; 646} 647 648static intdifferent_name(struct cache_entry *ce,struct cache_entry *alias) 649{ 650int len =ce_namelen(ce); 651returnce_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, 664struct cache_entry *ce, 665struct cache_entry *alias) 666{ 667int len; 668struct cache_entry *new_entry; 669 670if(alias->ce_flags & CE_ADDED) 671die("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); 676memcpy(new_entry->name, alias->name, len); 677copy_cache_entry(new_entry, ce); 678save_or_free_index_entry(istate, ce); 679return new_entry; 680} 681 682voidset_object_name_for_intent_to_add_entry(struct cache_entry *ce) 683{ 684struct object_id oid; 685if(write_object_file("",0, blob_type, &oid)) 686die("cannot create an empty blob in the object database"); 687oidcpy(&ce->oid, &oid); 688} 689 690intadd_to_index(struct index_state *istate,const char*path,struct stat *st,int flags) 691{ 692int namelen, was_same; 693 mode_t st_mode = st->st_mode; 694struct cache_entry *ce, *alias = NULL; 695unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY; 696int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND); 697int pretend = flags & ADD_CACHE_PRETEND; 698int intent_only = flags & ADD_CACHE_INTENT; 699int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE| 700(intent_only ? ADD_CACHE_NEW_ONLY :0)); 701int newflags = HASH_WRITE_OBJECT; 702 703if(flags & HASH_RENORMALIZE) 704 newflags |= HASH_RENORMALIZE; 705 706if(!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode)) 707returnerror("%s: can only add regular files, symbolic links or git-directories", path); 708 709 namelen =strlen(path); 710if(S_ISDIR(st_mode)) { 711while(namelen && path[namelen-1] =='/') 712 namelen--; 713} 714 ce =make_empty_cache_entry(istate, namelen); 715memcpy(ce->name, path, namelen); 716 ce->ce_namelen = namelen; 717if(!intent_only) 718fill_stat_cache_info(ce, st); 719else 720 ce->ce_flags |= CE_INTENT_TO_ADD; 721 722 723if(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 */ 729struct cache_entry *ent; 730int 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 */ 741if(ignore_case) { 742adjust_dirname_case(istate, ce->name); 743} 744if(!(flags & HASH_RENORMALIZE)) { 745 alias =index_file_exists(istate, ce->name, 746ce_namelen(ce), ignore_case); 747if(alias && 748!ce_stage(alias) && 749!ie_match_stat(istate, alias, st, ce_option)) { 750/* Nothing changed, really */ 751if(!S_ISGITLINK(alias->ce_mode)) 752ce_mark_uptodate(alias); 753 alias->ce_flags |= CE_ADDED; 754 755discard_cache_entry(ce); 756return0; 757} 758} 759if(!intent_only) { 760if(index_path(istate, &ce->oid, path, st, newflags)) { 761discard_cache_entry(ce); 762returnerror("unable to index file%s", path); 763} 764}else 765set_object_name_for_intent_to_add_entry(ce); 766 767if(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) && 774oideq(&alias->oid, &ce->oid) && 775 ce->ce_mode == alias->ce_mode); 776 777if(pretend) 778discard_cache_entry(ce); 779else if(add_index_entry(istate, ce, add_option)) { 780discard_cache_entry(ce); 781returnerror("unable to add%sto index", path); 782} 783if(verbose && !was_same) 784printf("add '%s'\n", path); 785return0; 786} 787 788intadd_file_to_index(struct index_state *istate,const char*path,int flags) 789{ 790struct stat st; 791if(lstat(path, &st)) 792die_errno("unable to stat '%s'", path); 793returnadd_to_index(istate, path, &st, flags); 794} 795 796struct cache_entry *make_empty_cache_entry(struct index_state *istate,size_t len) 797{ 798returnmem_pool__ce_calloc(find_mem_pool(istate), len); 799} 800 801struct cache_entry *make_empty_transient_cache_entry(size_t len) 802{ 803returnxcalloc(1,cache_entry_size(len)); 804} 805 806struct cache_entry *make_cache_entry(struct index_state *istate, 807unsigned int mode, 808const struct object_id *oid, 809const char*path, 810int stage, 811unsigned int refresh_options) 812{ 813struct cache_entry *ce, *ret; 814int len; 815 816if(!verify_path(path, mode)) { 817error("Invalid path '%s'", path); 818return NULL; 819} 820 821 len =strlen(path); 822 ce =make_empty_cache_entry(istate, len); 823 824oidcpy(&ce->oid, oid); 825memcpy(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); 831if(ret != ce) 832discard_cache_entry(ce); 833return ret; 834} 835 836struct cache_entry *make_transient_cache_entry(unsigned int mode,const struct object_id *oid, 837const char*path,int stage) 838{ 839struct cache_entry *ce; 840int len; 841 842if(!verify_path(path, mode)) { 843error("Invalid path '%s'", path); 844return NULL; 845} 846 847 len =strlen(path); 848 ce =make_empty_transient_cache_entry(len); 849 850oidcpy(&ce->oid, oid); 851memcpy(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 856return 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 */ 866intchmod_index_entry(struct index_state *istate,struct cache_entry *ce, 867char flip) 868{ 869if(!S_ISREG(ce->ce_mode)) 870return-1; 871switch(flip) { 872case'+': 873 ce->ce_mode |=0111; 874break; 875case'-': 876 ce->ce_mode &= ~0111; 877break; 878default: 879return-2; 880} 881cache_tree_invalidate_path(istate, ce->name); 882 ce->ce_flags |= CE_UPDATE_IN_BASE; 883mark_fsmonitor_invalid(istate, ce); 884 istate->cache_changed |= CE_ENTRY_CHANGED; 885 886return0; 887} 888 889intce_same_name(const struct cache_entry *a,const struct cache_entry *b) 890{ 891int len =ce_namelen(a); 892returnce_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 intverify_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 */ 912if(*rest =='\0'||is_dir_sep(*rest)) 913return0; 914 915switch(*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 */ 925case'g': 926case'G': 927if(rest[1] !='i'&& rest[1] !='I') 928break; 929if(rest[2] !='t'&& rest[2] !='T') 930break; 931if(rest[3] =='\0'||is_dir_sep(rest[3])) 932return0; 933if(S_ISLNK(mode)) { 934 rest +=3; 935if(skip_iprefix(rest,"modules", &rest) && 936(*rest =='\0'||is_dir_sep(*rest))) 937return0; 938} 939break; 940case'.': 941if(rest[1] =='\0'||is_dir_sep(rest[1])) 942return0; 943} 944return1; 945} 946 947intverify_path(const char*path,unsigned mode) 948{ 949char c; 950 951if(has_dos_drive_prefix(path)) 952return0; 953 954goto inside; 955for(;;) { 956if(!c) 957return1; 958if(is_dir_sep(c)) { 959inside: 960if(protect_hfs) { 961if(is_hfs_dotgit(path)) 962return0; 963if(S_ISLNK(mode)) { 964if(is_hfs_dotgitmodules(path)) 965return0; 966} 967} 968if(protect_ntfs) { 969if(is_ntfs_dotgit(path)) 970return0; 971if(S_ISLNK(mode)) { 972if(is_ntfs_dotgitmodules(path)) 973return0; 974} 975} 976 977 c = *path++; 978if((c =='.'&& !verify_dotfile(path, mode)) || 979is_dir_sep(c) || c =='\0') 980return0; 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 inthas_file_name(struct index_state *istate, 991const struct cache_entry *ce,int pos,int ok_to_replace) 992{ 993int retval =0; 994int len =ce_namelen(ce); 995int stage =ce_stage(ce); 996const char*name = ce->name; 997 998while(pos < istate->cache_nr) { 999struct cache_entry *p = istate->cache[pos++];10001001if(len >=ce_namelen(p))1002break;1003if(memcmp(name, p->name, len))1004break;1005if(ce_stage(p) != stage)1006continue;1007if(p->name[len] !='/')1008continue;1009if(p->ce_flags & CE_REMOVE)1010continue;1011 retval = -1;1012if(!ok_to_replace)1013break;1014remove_index_entry_at(istate, --pos);1015}1016return retval;1017}101810191020/*1021 * Like strcmp(), but also return the offset of the first change.1022 * If strings are equal, return the length.1023 */1024intstrcmp_offset(const char*s1,const char*s2,size_t*first_change)1025{1026size_t k;10271028if(!first_change)1029returnstrcmp(s1, s2);10301031for(k =0; s1[k] == s2[k]; k++)1032if(s1[k] =='\0')1033break;10341035*first_change = k;1036return(unsigned char)s1[k] - (unsigned char)s2[k];1037}10381039/*1040 * Do we have another file with a pathname that is a proper1041 * subset of the name we're trying to add?1042 *1043 * That is, is there another file in the index with a path1044 * that matches a sub-directory in the given entry?1045 */1046static inthas_dir_name(struct index_state *istate,1047const struct cache_entry *ce,int pos,int ok_to_replace)1048{1049int retval =0;1050int stage =ce_stage(ce);1051const char*name = ce->name;1052const char*slash = name +ce_namelen(ce);1053size_t len_eq_last;1054int cmp_last =0;10551056/*1057 * We are frequently called during an iteration on a sorted1058 * list of pathnames and while building a new index. Therefore,1059 * there is a high probability that this entry will eventually1060 * be appended to the index, rather than inserted in the middle.1061 * If we can confirm that, we can avoid binary searches on the1062 * components of the pathname.1063 *1064 * Compare the entry's full path with the last path in the index.1065 */1066if(istate->cache_nr >0) {1067 cmp_last =strcmp_offset(name,1068 istate->cache[istate->cache_nr -1]->name,1069&len_eq_last);1070if(cmp_last >0) {1071if(len_eq_last ==0) {1072/*1073 * The entry sorts AFTER the last one in the1074 * index and their paths have no common prefix,1075 * so there cannot be a F/D conflict.1076 */1077return retval;1078}else{1079/*1080 * The entry sorts AFTER the last one in the1081 * index, but has a common prefix. Fall through1082 * to the loop below to disect the entry's path1083 * and see where the difference is.1084 */1085}1086}else if(cmp_last ==0) {1087/*1088 * The entry exactly matches the last one in the1089 * index, but because of multiple stage and CE_REMOVE1090 * items, we fall through and let the regular search1091 * code handle it.1092 */1093}1094}10951096for(;;) {1097size_t len;10981099for(;;) {1100if(*--slash =='/')1101break;1102if(slash <= ce->name)1103return retval;1104}1105 len = slash - name;11061107if(cmp_last >0) {1108/*1109 * (len + 1) is a directory boundary (including1110 * the trailing slash). And since the loop is1111 * decrementing "slash", the first iteration is1112 * the longest directory prefix; subsequent1113 * iterations consider parent directories.1114 */11151116if(len +1<= len_eq_last) {1117/*1118 * The directory prefix (including the trailing1119 * slash) also appears as a prefix in the last1120 * entry, so the remainder cannot collide (because1121 * strcmp said the whole path was greater).1122 *1123 * EQ: last: xxx/A1124 * this: xxx/B1125 *1126 * LT: last: xxx/file_A1127 * this: xxx/file_B1128 */1129return retval;1130}11311132if(len > len_eq_last) {1133/*1134 * This part of the directory prefix (excluding1135 * the trailing slash) is longer than the known1136 * equal portions, so this sub-directory cannot1137 * collide with a file.1138 *1139 * GT: last: xxxA1140 * this: xxxB/file1141 */1142return retval;1143}11441145if(istate->cache_nr >0&&1146ce_namelen(istate->cache[istate->cache_nr -1]) > len) {1147/*1148 * The directory prefix lines up with part of1149 * a longer file or directory name, but sorts1150 * after it, so this sub-directory cannot1151 * collide with a file.1152 *1153 * last: xxx/yy-file (because '-' sorts before '/')1154 * this: xxx/yy/abc1155 */1156return retval;1157}11581159/*1160 * This is a possible collision. Fall through and1161 * let the regular search code handle it.1162 *1163 * last: xxx1164 * this: xxx/file1165 */1166}11671168 pos =index_name_stage_pos(istate, name, len, stage);1169if(pos >=0) {1170/*1171 * Found one, but not so fast. This could1172 * be a marker that says "I was here, but1173 * I am being removed". Such an entry is1174 * not a part of the resulting tree, and1175 * it is Ok to have a directory at the same1176 * path.1177 */1178if(!(istate->cache[pos]->ce_flags & CE_REMOVE)) {1179 retval = -1;1180if(!ok_to_replace)1181break;1182remove_index_entry_at(istate, pos);1183continue;1184}1185}1186else1187 pos = -pos-1;11881189/*1190 * Trivial optimization: if we find an entry that1191 * already matches the sub-directory, then we know1192 * we're ok, and we can exit.1193 */1194while(pos < istate->cache_nr) {1195struct cache_entry *p = istate->cache[pos];1196if((ce_namelen(p) <= len) ||1197(p->name[len] !='/') ||1198memcmp(p->name, name, len))1199break;/* not our subdirectory */1200if(ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))1201/*1202 * p is at the same stage as our entry, and1203 * is a subdirectory of what we are looking1204 * at, so we cannot have conflicts at our1205 * level or anything shorter.1206 */1207return retval;1208 pos++;1209}1210}1211return retval;1212}12131214/* We may be in a situation where we already have path/file and path1215 * is being added, or we already have path and path/file is being1216 * added. Either one would result in a nonsense tree that has path1217 * twice when git-write-tree tries to write it out. Prevent it.1218 *1219 * If ok-to-replace is specified, we remove the conflicting entries1220 * from the cache so the caller should recompute the insert position.1221 * When this happens, we return non-zero.1222 */1223static intcheck_file_directory_conflict(struct index_state *istate,1224const struct cache_entry *ce,1225int pos,int ok_to_replace)1226{1227int retval;12281229/*1230 * When ce is an "I am going away" entry, we allow it to be added1231 */1232if(ce->ce_flags & CE_REMOVE)1233return0;12341235/*1236 * We check if the path is a sub-path of a subsequent pathname1237 * first, since removing those will not change the position1238 * in the array.1239 */1240 retval =has_file_name(istate, ce, pos, ok_to_replace);12411242/*1243 * Then check if the path might have a clashing sub-directory1244 * before it.1245 */1246return retval +has_dir_name(istate, ce, pos, ok_to_replace);1247}12481249static intadd_index_entry_with_check(struct index_state *istate,struct cache_entry *ce,int option)1250{1251int pos;1252int ok_to_add = option & ADD_CACHE_OK_TO_ADD;1253int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;1254int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;1255int new_only = option & ADD_CACHE_NEW_ONLY;12561257if(!(option & ADD_CACHE_KEEP_CACHE_TREE))1258cache_tree_invalidate_path(istate, ce->name);12591260/*1261 * If this entry's path sorts after the last entry in the index,1262 * we can avoid searching for it.1263 */1264if(istate->cache_nr >0&&1265strcmp(ce->name, istate->cache[istate->cache_nr -1]->name) >0)1266 pos = -istate->cache_nr -1;1267else1268 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce));12691270/* existing match? Just replace it. */1271if(pos >=0) {1272if(!new_only)1273replace_index_entry(istate, pos, ce);1274return0;1275}1276 pos = -pos-1;12771278if(!(option & ADD_CACHE_KEEP_CACHE_TREE))1279untracked_cache_add_to_index(istate, ce->name);12801281/*1282 * Inserting a merged entry ("stage 0") into the index1283 * will always replace all non-merged entries..1284 */1285if(pos < istate->cache_nr &&ce_stage(ce) ==0) {1286while(ce_same_name(istate->cache[pos], ce)) {1287 ok_to_add =1;1288if(!remove_index_entry_at(istate, pos))1289break;1290}1291}12921293if(!ok_to_add)1294return-1;1295if(!verify_path(ce->name, ce->ce_mode))1296returnerror("Invalid path '%s'", ce->name);12971298if(!skip_df_check &&1299check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {1300if(!ok_to_replace)1301returnerror("'%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}1306return pos +1;1307}13081309intadd_index_entry(struct index_state *istate,struct cache_entry *ce,int option)1310{1311int pos;13121313if(option & ADD_CACHE_JUST_APPEND)1314 pos = istate->cache_nr;1315else{1316int ret;1317 ret =add_index_entry_with_check(istate, ce, option);1318if(ret <=0)1319return ret;1320 pos = ret -1;1321}13221323/* Make sure the array is big enough .. */1324ALLOC_GROW(istate->cache, istate->cache_nr +1, istate->cache_alloc);13251326/* Add it in.. */1327 istate->cache_nr++;1328if(istate->cache_nr > pos +1)1329MOVE_ARRAY(istate->cache + pos +1, istate->cache + pos,1330 istate->cache_nr - pos -1);1331set_index_entry(istate, pos, ce);1332 istate->cache_changed |= CE_ENTRY_ADDED;1333return0;1334}13351336/*1337 * "refresh" does not calculate a new sha1 file or bring the1338 * cache up-to-date for mode/content changes. But what it1339 * _does_ do is to "re-match" the stat information of a file1340 * with the cache, so that you can refresh the cache for a1341 * file that hasn't been changed but where the stat entry is1342 * 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,1348struct cache_entry *ce,1349unsigned int options,int*err,1350int*changed_ret)1351{1352struct stat st;1353struct cache_entry *updated;1354int changed;1355int refresh = options & CE_MATCH_REFRESH;1356int ignore_valid = options & CE_MATCH_IGNORE_VALID;1357int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;1358int ignore_missing = options & CE_MATCH_IGNORE_MISSING;1359int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;13601361if(!refresh ||ce_uptodate(ce))1362return ce;13631364if(!ignore_fsmonitor)1365refresh_fsmonitor(istate);1366/*1367 * CE_VALID or CE_SKIP_WORKTREE means the user promised us1368 * that the change to the work tree does not matter and told1369 * us not to worry.1370 */1371if(!ignore_skip_worktree &&ce_skip_worktree(ce)) {1372ce_mark_uptodate(ce);1373return ce;1374}1375if(!ignore_valid && (ce->ce_flags & CE_VALID)) {1376ce_mark_uptodate(ce);1377return ce;1378}1379if(!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {1380ce_mark_uptodate(ce);1381return ce;1382}13831384if(has_symlink_leading_path(ce->name,ce_namelen(ce))) {1385if(ignore_missing)1386return ce;1387if(err)1388*err = ENOENT;1389return NULL;1390}13911392if(lstat(ce->name, &st) <0) {1393if(ignore_missing && errno == ENOENT)1394return ce;1395if(err)1396*err = errno;1397return NULL;1398}13991400 changed =ie_match_stat(istate, ce, &st, options);1401if(changed_ret)1402*changed_ret = changed;1403if(!changed) {1404/*1405 * The path is unchanged. If we were told to ignore1406 * valid bit, then we did the actual stat check and1407 * found that the entry is unmodified. If the entry1408 * is not marked VALID, this is the place to mark it1409 * valid again, under "assume unchanged" mode.1410 */1411if(ignore_valid && assume_unchanged &&1412!(ce->ce_flags & CE_VALID))1413;/* mark this one VALID again */1414else{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 */1420if(!S_ISGITLINK(ce->ce_mode)) {1421ce_mark_uptodate(ce);1422mark_fsmonitor_valid(ce);1423}1424return ce;1425}1426}14271428if(ie_modified(istate, ce, &st, options)) {1429if(err)1430*err = EINVAL;1431return NULL;1432}14331434 updated =make_empty_cache_entry(istate,ce_namelen(ce));1435copy_cache_entry(updated, ce);1436memcpy(updated->name, ce->name, ce->ce_namelen +1);1437fill_stat_cache_info(updated, &st);1438/*1439 * If ignore_valid is not set, we should leave CE_VALID bit1440 * alone. Otherwise, paths marked with --no-assume-unchanged1441 * (i.e. things to be edited) will reacquire CE_VALID bit1442 * automatically, which is not really what we want.1443 */1444if(!ignore_valid && assume_unchanged &&1445!(ce->ce_flags & CE_VALID))1446 updated->ce_flags &= ~CE_VALID;14471448/* istate->cache_changed is updated in the caller */1449return updated;1450}14511452static voidshow_file(const char* fmt,const char* name,int in_porcelain,1453int* first,const char*header_msg)1454{1455if(in_porcelain && *first && header_msg) {1456printf("%s\n", header_msg);1457*first =0;1458}1459printf(fmt, name);1460}14611462intrefresh_index(struct index_state *istate,unsigned int flags,1463const struct pathspec *pathspec,1464char*seen,const char*header_msg)1465{1466int i;1467int has_errors =0;1468int really = (flags & REFRESH_REALLY) !=0;1469int allow_unmerged = (flags & REFRESH_UNMERGED) !=0;1470int quiet = (flags & REFRESH_QUIET) !=0;1471int not_new = (flags & REFRESH_IGNORE_MISSING) !=0;1472int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) !=0;1473int first =1;1474int in_porcelain = (flags & REFRESH_IN_PORCELAIN);1475unsigned int options = (CE_MATCH_REFRESH |1476(really ? CE_MATCH_IGNORE_VALID :0) |1477(not_new ? CE_MATCH_IGNORE_MISSING :0));1478const char*modified_fmt;1479const char*deleted_fmt;1480const char*typechange_fmt;1481const char*added_fmt;1482const char*unmerged_fmt;14831484trace_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":"%sneeds update\n");1488 added_fmt = (in_porcelain ?"A\t%s\n":"%sneeds update\n");1489 unmerged_fmt = (in_porcelain ?"U\t%s\n":"%s: needs merge\n");1490for(i =0; i < istate->cache_nr; i++) {1491struct cache_entry *ce, *new_entry;1492int cache_errno =0;1493int changed =0;1494int filtered =0;14951496 ce = istate->cache[i];1497if(ignore_submodules &&S_ISGITLINK(ce->ce_mode))1498continue;14991500if(pathspec && !ce_path_match(istate, ce, pathspec, seen))1501 filtered =1;15021503if(ce_stage(ce)) {1504while((i < istate->cache_nr) &&1505!strcmp(istate->cache[i]->name, ce->name))1506 i++;1507 i--;1508if(allow_unmerged)1509continue;1510if(!filtered)1511show_file(unmerged_fmt, ce->name, in_porcelain,1512&first, header_msg);1513 has_errors =1;1514continue;1515}15161517if(filtered)1518continue;15191520 new_entry =refresh_cache_ent(istate, ce, options, &cache_errno, &changed);1521if(new_entry == ce)1522continue;1523if(!new_entry) {1524const char*fmt;15251526if(really && cache_errno == EINVAL) {1527/* If we are doing --really-refresh that1528 * means the index is not valid anymore.1529 */1530 ce->ce_flags &= ~CE_VALID;1531 ce->ce_flags |= CE_UPDATE_IN_BASE;1532mark_fsmonitor_invalid(istate, ce);1533 istate->cache_changed |= CE_ENTRY_CHANGED;1534}1535if(quiet)1536continue;15371538if(cache_errno == ENOENT)1539 fmt = deleted_fmt;1540else if(ce_intent_to_add(ce))1541 fmt = added_fmt;/* must be before other checks */1542else if(changed & TYPE_CHANGED)1543 fmt = typechange_fmt;1544else1545 fmt = modified_fmt;1546show_file(fmt,1547 ce->name, in_porcelain, &first, header_msg);1548 has_errors =1;1549continue;1550}15511552replace_index_entry(istate, i, new_entry);1553}1554trace_performance_leave("refresh index");1555return has_errors;1556}15571558struct cache_entry *refresh_cache_entry(struct index_state *istate,1559struct cache_entry *ce,1560unsigned int options)1561{1562returnrefresh_cache_ent(istate, ce, options, NULL, NULL);1563}156415651566/*****************************************************************1567 * Index File I/O1568 *****************************************************************/15691570#define INDEX_FORMAT_DEFAULT 315711572static unsigned intget_index_format_default(void)1573{1574char*envversion =getenv("GIT_INDEX_VERSION");1575char*endp;1576int value;1577unsigned int version = INDEX_FORMAT_DEFAULT;15781579if(!envversion) {1580if(!git_config_get_int("index.version", &value))1581 version = value;1582if(version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1583warning(_("index.version set, but the value is invalid.\n"1584"Using version%i"), INDEX_FORMAT_DEFAULT);1585return INDEX_FORMAT_DEFAULT;1586}1587return version;1588}15891590 version =strtoul(envversion, &endp,10);1591if(*endp ||1592 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1593warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"1594"Using version%i"), INDEX_FORMAT_DEFAULT);1595 version = INDEX_FORMAT_DEFAULT;1596}1597return version;1598}15991600/*1601 * dev/ino/uid/gid/size are also just tracked to the low 32 bits1602 * Again - this is just a (very strong in practice) heuristic that1603 * the inode hasn't changed.1604 *1605 * We save the fields in big-endian order to allow using the1606 * index file over NFS transparently.1607 */1608struct ondisk_cache_entry {1609struct cache_time ctime;1610struct cache_time mtime;1611uint32_t dev;1612uint32_t ino;1613uint32_t mode;1614uint32_t uid;1615uint32_t gid;1616uint32_t size;1617unsigned char sha1[20];1618uint16_t flags;1619char name[FLEX_ARRAY];/* more */1620};16211622/*1623 * This struct is used when CE_EXTENDED bit is 11624 * The struct must match ondisk_cache_entry exactly from1625 * ctime till flags1626 */1627struct ondisk_cache_entry_extended {1628struct cache_time ctime;1629struct cache_time mtime;1630uint32_t dev;1631uint32_t ino;1632uint32_t mode;1633uint32_t uid;1634uint32_t gid;1635uint32_t size;1636unsigned char sha1[20];1637uint16_t flags;1638uint16_t flags2;1639char name[FLEX_ARRAY];/* more */1640};16411642/* 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)))16501651/* Allow fsck to force verification of the index checksum. */1652int verify_index_checksum;16531654/* Allow fsck to force verification of the cache entry order. */1655int verify_ce_order;16561657static intverify_hdr(struct cache_header *hdr,unsigned long size)1658{1659 git_hash_ctx c;1660unsigned char hash[GIT_MAX_RAWSZ];1661int hdr_version;16621663if(hdr->hdr_signature !=htonl(CACHE_SIGNATURE))1664returnerror("bad signature");1665 hdr_version =ntohl(hdr->hdr_version);1666if(hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)1667returnerror("bad index version%d", hdr_version);16681669if(!verify_index_checksum)1670return0;16711672 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);1675if(!hasheq(hash, (unsigned char*)hdr + size - the_hash_algo->rawsz))1676returnerror("bad index file sha1 signature");1677return0;1678}16791680static intread_index_extension(struct index_state *istate,1681const char*ext,void*data,unsigned long sz)1682{1683switch(CACHE_EXT(ext)) {1684case CACHE_EXT_TREE:1685 istate->cache_tree =cache_tree_read(data, sz);1686break;1687case CACHE_EXT_RESOLVE_UNDO:1688 istate->resolve_undo =resolve_undo_read(data, sz);1689break;1690case CACHE_EXT_LINK:1691if(read_link_extension(istate, data, sz))1692return-1;1693break;1694case CACHE_EXT_UNTRACKED:1695 istate->untracked =read_untracked_extension(data, sz);1696break;1697case CACHE_EXT_FSMONITOR:1698read_fsmonitor_extension(istate, data, sz);1699break;1700default:1701if(*ext <'A'||'Z'< *ext)1702returnerror("index uses %.4s extension, which we do not understand",1703 ext);1704fprintf(stderr,"ignoring %.4s extension\n", ext);1705break;1706}1707return0;1708}17091710inthold_locked_index(struct lock_file *lk,int lock_flags)1711{1712returnhold_lock_file_for_update(lk,get_index_file(), lock_flags);1713}17141715intread_index(struct index_state *istate)1716{1717returnread_index_from(istate,get_index_file(),get_git_dir());1718}17191720static struct cache_entry *cache_entry_from_ondisk(struct mem_pool *mem_pool,1721struct ondisk_cache_entry *ondisk,1722unsigned int flags,1723const char*name,1724size_t len)1725{1726struct cache_entry *ce =mem_pool__ce_alloc(mem_pool, len);17271728 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;1741hashcpy(ce->oid.hash, ondisk->sha1);1742memcpy(ce->name, name, len);1743 ce->name[len] ='\0';1744return ce;1745}17461747/*1748 * Adjacent cache entries tend to share the leading paths, so it makes1749 * sense to only store the differences in later entries. In the v41750 * on-disk format of the index, each on-disk cache entry stores the1751 * 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 longexpand_name_field(struct strbuf *name,const char*cp_)1755{1756const unsigned char*ep, *cp = (const unsigned char*)cp_;1757size_t len =decode_varint(&cp);17581759if(name->len < len)1760die("malformed name field in the index");1761strbuf_remove(name, name->len - len, len);1762for(ep = cp; *ep; ep++)1763;/* find the end */1764strbuf_add(name, cp, ep - cp);1765return(const char*)ep +1- cp_;1766}17671768static struct cache_entry *create_from_disk(struct mem_pool *mem_pool,1769struct ondisk_cache_entry *ondisk,1770unsigned long*ent_size,1771struct strbuf *previous_name)1772{1773struct cache_entry *ce;1774size_t len;1775const char*name;1776unsigned int flags;17771778/* On-disk flags are just 16 bits */1779 flags =get_be16(&ondisk->flags);1780 len = flags & CE_NAMEMASK;17811782if(flags & CE_EXTENDED) {1783struct ondisk_cache_entry_extended *ondisk2;1784int 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 */1788if(extended_flags & ~CE_EXTENDED_FLAGS)1789die("Unknown index entry format%08x", extended_flags);1790 flags |= extended_flags;1791 name = ondisk2->name;1792}1793else1794 name = ondisk->name;17951796if(!previous_name) {1797/* v3 and earlier */1798if(len == CE_NAMEMASK)1799 len =strlen(name);1800 ce =cache_entry_from_ondisk(mem_pool, ondisk, flags, name, len);18011802*ent_size =ondisk_ce_size(ce);1803}else{1804unsigned 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);18091810*ent_size = (name - ((char*)ondisk)) + consumed;1811}1812return ce;1813}18141815static voidcheck_ce_order(struct index_state *istate)1816{1817unsigned int i;18181819if(!verify_ce_order)1820return;18211822for(i =1; i < istate->cache_nr; i++) {1823struct cache_entry *ce = istate->cache[i -1];1824struct cache_entry *next_ce = istate->cache[i];1825int name_compare =strcmp(ce->name, next_ce->name);18261827if(0< name_compare)1828die("unordered stage entries in index");1829if(!name_compare) {1830if(!ce_stage(ce))1831die("multiple stage entries for merged file '%s'",1832 ce->name);1833if(ce_stage(ce) >ce_stage(next_ce))1834die("unordered stage entries for '%s'",1835 ce->name);1836}1837}1838}18391840static voidtweak_untracked_cache(struct index_state *istate)1841{1842switch(git_config_get_untracked_cache()) {1843case-1:/* keep: do nothing */1844break;1845case0:/* false */1846remove_untracked_cache(istate);1847break;1848case1:/* true */1849add_untracked_cache(istate);1850break;1851default:/* unknown value: do nothing */1852break;1853}1854}18551856static voidtweak_split_index(struct index_state *istate)1857{1858switch(git_config_get_split_index()) {1859case-1:/* unset: do nothing */1860break;1861case0:/* false */1862remove_split_index(istate);1863break;1864case1:/* true */1865add_split_index(istate);1866break;1867default:/* unknown value: do nothing */1868break;1869}1870}18711872static voidpost_read_index_from(struct index_state *istate)1873{1874check_ce_order(istate);1875tweak_untracked_cache(istate);1876tweak_split_index(istate);1877tweak_fsmonitor(istate);1878}18791880static size_testimate_cache_size_from_compressed(unsigned int entries)1881{1882return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);1883}18841885static size_testimate_cache_size(size_t ondisk_size,unsigned int entries)1886{1887long per_entry =sizeof(struct cache_entry) -sizeof(struct ondisk_cache_entry);18881889/*1890 * Account for potential alignment differences.1891 */1892 per_entry +=align_padding_size(sizeof(struct cache_entry), -sizeof(struct ondisk_cache_entry));1893return ondisk_size + entries * per_entry;1894}18951896/* remember to discard_cache() before reading a different cache! */1897intdo_read_index(struct index_state *istate,const char*path,int must_exist)1898{1899int fd, i;1900struct stat st;1901unsigned long src_offset;1902struct cache_header *hdr;1903void*mmap;1904size_t mmap_size;1905struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;19061907if(istate->initialized)1908return istate->cache_nr;19091910 istate->timestamp.sec =0;1911 istate->timestamp.nsec =0;1912 fd =open(path, O_RDONLY);1913if(fd <0) {1914if(!must_exist && errno == ENOENT)1915return0;1916die_errno("%s: index file open failed", path);1917}19181919if(fstat(fd, &st))1920die_errno("cannot stat the open index");19211922 mmap_size =xsize_t(st.st_size);1923if(mmap_size <sizeof(struct cache_header) + the_hash_algo->rawsz)1924die("index file smaller than expected");19251926 mmap =xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd,0);1927if(mmap == MAP_FAILED)1928die_errno("unable to map index file");1929close(fd);19301931 hdr = mmap;1932if(verify_hdr(hdr, mmap_size) <0)1933goto unmap;19341935hashcpy(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;19411942if(istate->version ==4) {1943 previous_name = &previous_name_buf;1944mem_pool_init(&istate->ce_mem_pool,1945estimate_cache_size_from_compressed(istate->cache_nr));1946}else{1947 previous_name = NULL;1948mem_pool_init(&istate->ce_mem_pool,1949estimate_cache_size(mmap_size, istate->cache_nr));1950}19511952 src_offset =sizeof(*hdr);1953for(i =0; i < istate->cache_nr; i++) {1954struct ondisk_cache_entry *disk_ce;1955struct cache_entry *ce;1956unsigned long consumed;19571958 disk_ce = (struct ondisk_cache_entry *)((char*)mmap + src_offset);1959 ce =create_from_disk(istate->ce_mem_pool, disk_ce, &consumed, previous_name);1960set_index_entry(istate, i, ce);19611962 src_offset += consumed;1963}1964strbuf_release(&previous_name_buf);1965 istate->timestamp.sec = st.st_mtime;1966 istate->timestamp.nsec =ST_MTIME_NSEC(st);19671968while(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 extended1971 * sections, each of which is prefixed with1972 * extension name (4-byte) and section length1973 * in 4-byte network byte order.1974 */1975uint32_t extsize;1976memcpy(&extsize, (char*)mmap + src_offset +4,4);1977 extsize =ntohl(extsize);1978if(read_index_extension(istate,1979(const char*) mmap + src_offset,1980(char*) mmap + src_offset +8,1981 extsize) <0)1982goto unmap;1983 src_offset +=8;1984 src_offset += extsize;1985}1986munmap(mmap, mmap_size);1987return istate->cache_nr;19881989unmap:1990munmap(mmap, mmap_size);1991die("index file corrupt");1992}19931994/*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 used1998 * for some time.1999 */2000static voidfreshen_shared_index(const char*shared_index,int warn)2001{2002if(!check_and_freshen_file(shared_index,1) && warn)2003warning("could not freshen shared index '%s'", shared_index);2004}20052006intread_index_from(struct index_state *istate,const char*path,2007const char*gitdir)2008{2009struct split_index *split_index;2010int ret;2011char*base_oid_hex;2012char*base_path;20132014/* istate->initialized covers both .git/index and .git/sharedindex.xxx */2015if(istate->initialized)2016return istate->cache_nr;20172018trace_performance_enter();2019 ret =do_read_index(istate, path,0);2020trace_performance_leave("read cache%s", path);20212022 split_index = istate->split_index;2023if(!split_index ||is_null_oid(&split_index->base_oid)) {2024post_read_index_from(istate);2025return ret;2026}20272028trace_performance_enter();2029if(split_index->base)2030discard_index(split_index->base);2031else2032 split_index->base =xcalloc(1,sizeof(*split_index->base));20332034 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);2037if(!oideq(&split_index->base_oid, &split_index->base->oid))2038die("broken index, expect%sin%s, got%s",2039 base_oid_hex, base_path,2040oid_to_hex(&split_index->base->oid));20412042freshen_shared_index(base_path,0);2043merge_base_index(istate);2044post_read_index_from(istate);2045free(base_path);2046trace_performance_leave("read cache%s", base_path);2047return ret;2048}20492050intis_index_unborn(struct index_state *istate)2051{2052return(!istate->cache_nr && !istate->timestamp.sec);2053}20542055intdiscard_index(struct index_state *istate)2056{2057/*2058 * Cache entries in istate->cache[] should have been allocated2059 * from the memory pool associated with this index, or from an2060 * associated split_index. There is no need to free individual2061 * cache entries. validate_cache_entries can detect when this2062 * assertion does not hold.2063 */2064validate_cache_entries(istate);20652066resolve_undo_clear_index(istate);2067 istate->cache_nr =0;2068 istate->cache_changed =0;2069 istate->timestamp.sec =0;2070 istate->timestamp.nsec =0;2071free_name_hash(istate);2072cache_tree_free(&(istate->cache_tree));2073 istate->initialized =0;2074FREE_AND_NULL(istate->cache);2075 istate->cache_alloc =0;2076discard_split_index(istate);2077free_untracked_cache(istate->untracked);2078 istate->untracked = NULL;20792080if(istate->ce_mem_pool) {2081mem_pool_discard(istate->ce_mem_pool,should_validate_cache_entries());2082 istate->ce_mem_pool = NULL;2083}20842085return0;2086}20872088/*2089 * Validate the cache entries of this index.2090 * All cache entries associated with this index2091 * should have been allocated by the memory pool2092 * associated with this index, or by a referenced2093 * split index.2094 */2095voidvalidate_cache_entries(const struct index_state *istate)2096{2097int i;20982099if(!should_validate_cache_entries() ||!istate || !istate->initialized)2100return;21012102for(i =0; i < istate->cache_nr; i++) {2103if(!istate) {2104die("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])) {2107if(!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])) {2111die("internal error: cache entry is not allocated from expected memory pool");2112}2113}2114}21152116if(istate->split_index)2117validate_cache_entries(istate->split_index->base);2118}21192120intunmerged_index(const struct index_state *istate)2121{2122int i;2123for(i =0; i < istate->cache_nr; i++) {2124if(ce_stage(istate->cache[i]))2125return1;2126}2127return0;2128}21292130intindex_has_changes(struct index_state *istate,2131struct tree *tree,2132struct strbuf *sb)2133{2134struct object_id cmp;2135int i;21362137if(istate != &the_index) {2138BUG("index_has_changes cannot yet accept istate != &the_index; do_diff_cache needs updating first.");2139}2140if(tree)2141 cmp = tree->object.oid;2142if(tree || !get_oid_tree("HEAD", &cmp)) {2143struct diff_options opt;21442145repo_diff_setup(the_repository, &opt);2146 opt.flags.exit_with_status =1;2147if(!sb)2148 opt.flags.quick =1;2149do_diff_cache(&cmp, &opt);2150diffcore_std(&opt);2151for(i =0; sb && i < diff_queued_diff.nr; i++) {2152if(i)2153strbuf_addch(sb,' ');2154strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);2155}2156diff_flush(&opt);2157return opt.flags.has_changes !=0;2158}else{2159for(i =0; sb && i < istate->cache_nr; i++) {2160if(i)2161strbuf_addch(sb,' ');2162strbuf_addstr(sb, istate->cache[i]->name);2163}2164return!!istate->cache_nr;2165}2166}21672168#define WRITE_BUFFER_SIZE 81922169static unsigned char write_buffer[WRITE_BUFFER_SIZE];2170static unsigned long write_buffer_len;21712172static intce_write_flush(git_hash_ctx *context,int fd)2173{2174unsigned int buffered = write_buffer_len;2175if(buffered) {2176 the_hash_algo->update_fn(context, write_buffer, buffered);2177if(write_in_full(fd, write_buffer, buffered) <0)2178return-1;2179 write_buffer_len =0;2180}2181return0;2182}21832184static intce_write(git_hash_ctx *context,int fd,void*data,unsigned int len)2185{2186while(len) {2187unsigned int buffered = write_buffer_len;2188unsigned int partial = WRITE_BUFFER_SIZE - buffered;2189if(partial > len)2190 partial = len;2191memcpy(write_buffer + buffered, data, partial);2192 buffered += partial;2193if(buffered == WRITE_BUFFER_SIZE) {2194 write_buffer_len = buffered;2195if(ce_write_flush(context, fd))2196return-1;2197 buffered =0;2198}2199 write_buffer_len = buffered;2200 len -= partial;2201 data = (char*) data + partial;2202}2203return0;2204}22052206static intwrite_index_ext_header(git_hash_ctx *context,int fd,2207unsigned int ext,unsigned int sz)2208{2209 ext =htonl(ext);2210 sz =htonl(sz);2211return((ce_write(context, fd, &ext,4) <0) ||2212(ce_write(context, fd, &sz,4) <0)) ? -1:0;2213}22142215static intce_flush(git_hash_ctx *context,int fd,unsigned char*hash)2216{2217unsigned int left = write_buffer_len;22182219if(left) {2220 write_buffer_len =0;2221 the_hash_algo->update_fn(context, write_buffer, left);2222}22232224/* Flush first if not enough space for hash signature */2225if(left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {2226if(write_in_full(fd, write_buffer, left) <0)2227return-1;2228 left =0;2229}22302231/* Append the hash signature at the end */2232 the_hash_algo->final_fn(write_buffer + left, context);2233hashcpy(hash, write_buffer + left);2234 left += the_hash_algo->rawsz;2235return(write_in_full(fd, write_buffer, left) <0) ? -1:0;2236}22372238static voidce_smudge_racily_clean_entry(struct index_state *istate,2239struct cache_entry *ce)2240{2241/*2242 * The only thing we care about in this function is to smudge the2243 * falsely clean entry due to touch-update-touch race, so we leave2244 * everything else as they are. We are called for entries whose2245 * ce_stat_data.sd_mtime match the index file mtime.2246 *2247 * Note that this actually does not do much for gitlinks, for2248 * which ce_match_stat_basic() always goes to the actual2249 * contents. The caller checks with is_racy_timestamp() which2250 * always says "no" for gitlinks, so we are not called for them ;-)2251 */2252struct stat st;22532254if(lstat(ce->name, &st) <0)2255return;2256if(ce_match_stat_basic(ce, &st))2257return;2258if(ce_modified_check_fs(istate, ce, &st)) {2259/* This is "racily clean"; smudge it. Note that this2260 * is a tricky code. At first glance, it may appear2261 * that it can break with this sequence:2262 *2263 * $ echo xyzzy >frotz2264 * $ git-update-index --add frotz2265 * $ : >frotz2266 * $ sleep 32267 * $ echo filfre >nitfol2268 * $ git-update-index --add nitfol2269 *2270 * but it does not. When the second update-index runs,2271 * it notices that the entry "frotz" has the same timestamp2272 * as index, and if we were to smudge it by resetting its2273 * size to zero here, then the object name recorded2274 * in index is the 6-byte file but the cached stat information2275 * becomes zero --- which would then match what we would2276 * obtain from the filesystem next time we stat("frotz").2277 *2278 * However, the second update-index, before calling2279 * this function, notices that the cached size is 62280 * bytes and what is on the filesystem is an empty2281 * file, and never calls us, so the cached size information2282 * for "frotz" stays 6 which does not match the filesystem.2283 */2284 ce->ce_stat_data.sd_size =0;2285}2286}22872288/* Copy miscellaneous fields but not the name */2289static voidcopy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,2290struct cache_entry *ce)2291{2292short flags;22932294 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);2304hashcpy(ondisk->sha1, ce->oid.hash);23052306 flags = ce->ce_flags & ~CE_NAMEMASK;2307 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK :ce_namelen(ce));2308 ondisk->flags =htons(flags);2309if(ce->ce_flags & CE_EXTENDED) {2310struct 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}23152316static intce_write_entry(git_hash_ctx *c,int fd,struct cache_entry *ce,2317struct strbuf *previous_name,struct ondisk_cache_entry *ondisk)2318{2319int size;2320int result;2321unsigned int saved_namelen;2322int stripped_name =0;2323static unsigned char padding[8] = {0x00};23242325if(ce->ce_flags & CE_STRIP_NAME) {2326 saved_namelen =ce_namelen(ce);2327 ce->ce_namelen =0;2328 stripped_name =1;2329}23302331if(ce->ce_flags & CE_EXTENDED)2332 size =offsetof(struct ondisk_cache_entry_extended, name);2333else2334 size =offsetof(struct ondisk_cache_entry, name);23352336if(!previous_name) {2337int len =ce_namelen(ce);2338copy_cache_entry_to_ondisk(ondisk, ce);2339 result =ce_write(c, fd, ondisk, size);2340if(!result)2341 result =ce_write(c, fd, ce->name, len);2342if(!result)2343 result =ce_write(c, fd, padding,align_padding_size(size, len));2344}else{2345int common, to_remove, prefix_size;2346unsigned char to_remove_vi[16];2347for(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);23552356copy_cache_entry_to_ondisk(ondisk, ce);2357 result =ce_write(c, fd, ondisk, size);2358if(!result)2359 result =ce_write(c, fd, to_remove_vi, prefix_size);2360if(!result)2361 result =ce_write(c, fd, ce->name + common,ce_namelen(ce) - common);2362if(!result)2363 result =ce_write(c, fd, padding,1);23642365strbuf_splice(previous_name, common, to_remove,2366 ce->name + common,ce_namelen(ce) - common);2367}2368if(stripped_name) {2369 ce->ce_namelen = saved_namelen;2370 ce->ce_flags &= ~CE_STRIP_NAME;2371}23722373return result;2374}23752376/*2377 * This function verifies if index_state has the correct sha1 of the2378 * index file. Don't die if we have any other failure, just return 0.2379 */2380static intverify_index_from(const struct index_state *istate,const char*path)2381{2382int fd;2383 ssize_t n;2384struct stat st;2385unsigned char hash[GIT_MAX_RAWSZ];23862387if(!istate->initialized)2388return0;23892390 fd =open(path, O_RDONLY);2391if(fd <0)2392return0;23932394if(fstat(fd, &st))2395goto out;23962397if(st.st_size <sizeof(struct cache_header) + the_hash_algo->rawsz)2398goto out;23992400 n =pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);2401if(n != the_hash_algo->rawsz)2402goto out;24032404if(!hasheq(istate->oid.hash, hash))2405goto out;24062407close(fd);2408return1;24092410out:2411close(fd);2412return0;2413}24142415static intverify_index(const struct index_state *istate)2416{2417returnverify_index_from(istate,get_index_file());2418}24192420static inthas_racy_timestamp(struct index_state *istate)2421{2422int entries = istate->cache_nr;2423int i;24242425for(i =0; i < entries; i++) {2426struct cache_entry *ce = istate->cache[i];2427if(is_racy_timestamp(istate, ce))2428return1;2429}2430return0;2431}24322433voidupdate_index_if_able(struct index_state *istate,struct lock_file *lockfile)2434{2435if((istate->cache_changed ||has_racy_timestamp(istate)) &&2436verify_index(istate))2437write_locked_index(istate, lockfile, COMMIT_LOCK);2438else2439rollback_lock_file(lockfile);2440}24412442/*2443 * On success, `tempfile` is closed. If it is the temporary file2444 * of a `struct lock_file`, we will therefore effectively perform2445 * a 'close_lock_file_gently()`. Since that is an implementation2446 * detail of lockfiles, callers of `do_write_index()` should not2447 * rely on it.2448 */2449static intdo_write_index(struct index_state *istate,struct tempfile *tempfile,2450int strip_extensions)2451{2452uint64_t start =getnanotime();2453int newfd = tempfile->fd;2454 git_hash_ctx c;2455struct cache_header hdr;2456int i, err =0, removed, extended, hdr_version;2457struct cache_entry **cache = istate->cache;2458int entries = istate->cache_nr;2459struct stat st;2460struct ondisk_cache_entry_extended ondisk;2461struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;2462int drop_cache_tree = istate->drop_cache_tree;24632464for(i = removed = extended =0; i < entries; i++) {2465if(cache[i]->ce_flags & CE_REMOVE)2466 removed++;24672468/* reduce extended entries if possible */2469 cache[i]->ce_flags &= ~CE_EXTENDED;2470if(cache[i]->ce_flags & CE_EXTENDED_FLAGS) {2471 extended++;2472 cache[i]->ce_flags |= CE_EXTENDED;2473}2474}24752476if(!istate->version) {2477 istate->version =get_index_format_default();2478if(git_env_bool("GIT_TEST_SPLIT_INDEX",0))2479init_split_index(istate);2480}24812482/* demote version 3 to version 2 when the latter suffices */2483if(istate->version ==3|| istate->version ==2)2484 istate->version = extended ?3:2;24852486 hdr_version = istate->version;24872488 hdr.hdr_signature =htonl(CACHE_SIGNATURE);2489 hdr.hdr_version =htonl(hdr_version);2490 hdr.hdr_entries =htonl(entries - removed);24912492 the_hash_algo->init_fn(&c);2493if(ce_write(&c, newfd, &hdr,sizeof(hdr)) <0)2494return-1;24952496 previous_name = (hdr_version ==4) ? &previous_name_buf : NULL;24972498for(i =0; i < entries; i++) {2499struct cache_entry *ce = cache[i];2500if(ce->ce_flags & CE_REMOVE)2501continue;2502if(!ce_uptodate(ce) &&is_racy_timestamp(istate, ce))2503ce_smudge_racily_clean_entry(istate, ce);2504if(is_null_oid(&ce->oid)) {2505static const char msg[] ="cache entry has null sha1:%s";2506static int allow = -1;25072508if(allow <0)2509 allow =git_env_bool("GIT_ALLOW_NULL_SHA1",0);2510if(allow)2511warning(msg, ce->name);2512else2513 err =error(msg, ce->name);25142515 drop_cache_tree =1;2516}2517if(ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) <0)2518 err = -1;25192520if(err)2521break;2522}2523strbuf_release(&previous_name_buf);25242525if(err)2526return err;25272528/* Write extension data here */2529if(!strip_extensions && istate->split_index) {2530struct strbuf sb = STRBUF_INIT;25312532 err =write_link_extension(&sb, istate) <0||2533write_index_ext_header(&c, newfd, CACHE_EXT_LINK,2534 sb.len) <0||2535ce_write(&c, newfd, sb.buf, sb.len) <0;2536strbuf_release(&sb);2537if(err)2538return-1;2539}2540if(!strip_extensions && !drop_cache_tree && istate->cache_tree) {2541struct strbuf sb = STRBUF_INIT;25422543cache_tree_write(&sb, istate->cache_tree);2544 err =write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) <02545||ce_write(&c, newfd, sb.buf, sb.len) <0;2546strbuf_release(&sb);2547if(err)2548return-1;2549}2550if(!strip_extensions && istate->resolve_undo) {2551struct strbuf sb = STRBUF_INIT;25522553resolve_undo_write(&sb, istate->resolve_undo);2554 err =write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,2555 sb.len) <02556||ce_write(&c, newfd, sb.buf, sb.len) <0;2557strbuf_release(&sb);2558if(err)2559return-1;2560}2561if(!strip_extensions && istate->untracked) {2562struct strbuf sb = STRBUF_INIT;25632564write_untracked_extension(&sb, istate->untracked);2565 err =write_index_ext_header(&c, newfd, CACHE_EXT_UNTRACKED,2566 sb.len) <0||2567ce_write(&c, newfd, sb.buf, sb.len) <0;2568strbuf_release(&sb);2569if(err)2570return-1;2571}2572if(!strip_extensions && istate->fsmonitor_last_update) {2573struct strbuf sb = STRBUF_INIT;25742575write_fsmonitor_extension(&sb, istate);2576 err =write_index_ext_header(&c, newfd, CACHE_EXT_FSMONITOR, sb.len) <02577||ce_write(&c, newfd, sb.buf, sb.len) <0;2578strbuf_release(&sb);2579if(err)2580return-1;2581}25822583if(ce_flush(&c, newfd, istate->oid.hash))2584return-1;2585if(close_tempfile_gently(tempfile)) {2586error(_("could not close '%s'"), tempfile->filename.buf);2587return-1;2588}2589if(stat(tempfile->filename.buf, &st))2590return-1;2591 istate->timestamp.sec = (unsigned int)st.st_mtime;2592 istate->timestamp.nsec =ST_MTIME_NSEC(st);2593trace_performance_since(start,"write index, changed mask =%x", istate->cache_changed);2594return0;2595}25962597voidset_alternate_index_output(const char*name)2598{2599 alternate_index_output = name;2600}26012602static intcommit_locked_index(struct lock_file *lk)2603{2604if(alternate_index_output)2605returncommit_lock_file_to(lk, alternate_index_output);2606else2607returncommit_lock_file(lk);2608}26092610static intdo_write_locked_index(struct index_state *istate,struct lock_file *lock,2611unsigned flags)2612{2613int ret =do_write_index(istate, lock->tempfile,0);2614if(ret)2615return ret;2616if(flags & COMMIT_LOCK)2617returncommit_locked_index(lock);2618returnclose_lock_file_gently(lock);2619}26202621static intwrite_split_index(struct index_state *istate,2622struct lock_file *lock,2623unsigned flags)2624{2625int ret;2626prepare_to_write_split_index(istate);2627 ret =do_write_locked_index(istate, lock, flags);2628finish_writing_split_index(istate);2629return ret;2630}26312632static const char*shared_index_expire ="2.weeks.ago";26332634static unsigned longget_shared_index_expire_date(void)2635{2636static unsigned long shared_index_expire_date;2637static int shared_index_expire_date_prepared;26382639if(!shared_index_expire_date_prepared) {2640git_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}26452646return shared_index_expire_date;2647}26482649static intshould_delete_shared_index(const char*shared_index_path)2650{2651struct stat st;2652unsigned long expiration;26532654/* Check timestamp */2655 expiration =get_shared_index_expire_date();2656if(!expiration)2657return0;2658if(stat(shared_index_path, &st))2659returnerror_errno(_("could not stat '%s'"), shared_index_path);2660if(st.st_mtime > expiration)2661return0;26622663return1;2664}26652666static intclean_shared_index_files(const char*current_hex)2667{2668struct dirent *de;2669DIR*dir =opendir(get_git_dir());26702671if(!dir)2672returnerror_errno(_("unable to open git dir:%s"),get_git_dir());26732674while((de =readdir(dir)) != NULL) {2675const char*sha1_hex;2676const char*shared_index_path;2677if(!skip_prefix(de->d_name,"sharedindex.", &sha1_hex))2678continue;2679if(!strcmp(sha1_hex, current_hex))2680continue;2681 shared_index_path =git_path("%s", de->d_name);2682if(should_delete_shared_index(shared_index_path) >0&&2683unlink(shared_index_path))2684warning_errno(_("unable to unlink:%s"), shared_index_path);2685}2686closedir(dir);26872688return0;2689}26902691static intwrite_shared_index(struct index_state *istate,2692struct tempfile **temp)2693{2694struct split_index *si = istate->split_index;2695int ret;26962697move_cache_to_base_index(istate);2698 ret =do_write_index(si->base, *temp,1);2699if(ret)2700return ret;2701 ret =adjust_shared_perm(get_tempfile_path(*temp));2702if(ret) {2703error("cannot fix permission bits on%s",get_tempfile_path(*temp));2704return ret;2705}2706 ret =rename_tempfile(temp,2707git_path("sharedindex.%s",oid_to_hex(&si->base->oid)));2708if(!ret) {2709oidcpy(&si->base_oid, &si->base->oid);2710clean_shared_index_files(oid_to_hex(&si->base->oid));2711}27122713return ret;2714}27152716static const int default_max_percent_split_change =20;27172718static inttoo_many_not_shared_entries(struct index_state *istate)2719{2720int i, not_shared =0;2721int max_split =git_config_get_max_percent_split_change();27222723switch(max_split) {2724case-1:2725/* not or badly configured: use the default value */2726 max_split = default_max_percent_split_change;2727break;2728case0:2729return1;/* 0% means always write a new shared index */2730case100:2731return0;/* 100% means never write a new shared index */2732default:2733break;/* just use the configured value */2734}27352736/* Count not shared entries */2737for(i =0; i < istate->cache_nr; i++) {2738struct cache_entry *ce = istate->cache[i];2739if(!ce->index)2740 not_shared++;2741}27422743return(int64_t)istate->cache_nr * max_split < (int64_t)not_shared *100;2744}27452746intwrite_locked_index(struct index_state *istate,struct lock_file *lock,2747unsigned flags)2748{2749int new_shared_index, ret;2750struct split_index *si = istate->split_index;27512752if(git_env_bool("GIT_TEST_CHECK_CACHE_TREE",0))2753cache_tree_verify(istate);27542755if((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {2756if(flags & COMMIT_LOCK)2757rollback_lock_file(lock);2758return0;2759}27602761if(istate->fsmonitor_last_update)2762fill_fsmonitor_bitmap(istate);27632764if(!si || alternate_index_output ||2765(istate->cache_changed & ~EXTMASK)) {2766if(si)2767oidclr(&si->base_oid);2768 ret =do_write_locked_index(istate, lock, flags);2769goto out;2770}27712772if(git_env_bool("GIT_TEST_SPLIT_INDEX",0)) {2773int v = si->base_oid.hash[0];2774if((v &15) <6)2775 istate->cache_changed |= SPLIT_INDEX_ORDERED;2776}2777if(too_many_not_shared_entries(istate))2778 istate->cache_changed |= SPLIT_INDEX_ORDERED;27792780 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;27812782if(new_shared_index) {2783struct tempfile *temp;2784int saved_errno;27852786 temp =mks_tempfile(git_path("sharedindex_XXXXXX"));2787if(!temp) {2788oidclr(&si->base_oid);2789 ret =do_write_locked_index(istate, lock, flags);2790goto out;2791}2792 ret =write_shared_index(istate, &temp);27932794 saved_errno = errno;2795if(is_tempfile_active(temp))2796delete_tempfile(&temp);2797 errno = saved_errno;27982799if(ret)2800goto out;2801}28022803 ret =write_split_index(istate, lock, flags);28042805/* Freshen the shared index only if the split-index was written */2806if(!ret && !new_shared_index) {2807const char*shared_index =git_path("sharedindex.%s",2808oid_to_hex(&si->base_oid));2809freshen_shared_index(shared_index,1);2810}28112812out:2813if(flags & COMMIT_LOCK)2814rollback_lock_file(lock);2815return ret;2816}28172818/*2819 * Read the index file that is potentially unmerged into given2820 * index_state, dropping any unmerged entries to stage #0 (potentially2821 * resulting in a path appearing as both a file and a directory in the2822 * index; the caller is responsible to clear out the extra entries2823 * before writing the index to a tree). Returns true if the index is2824 * unmerged. Callers who want to refuse to work from an unmerged2825 * state can call this and check its return value, instead of calling2826 * read_cache().2827 */2828intread_index_unmerged(struct index_state *istate)2829{2830int i;2831int unmerged =0;28322833read_index(istate);2834for(i =0; i < istate->cache_nr; i++) {2835struct cache_entry *ce = istate->cache[i];2836struct cache_entry *new_ce;2837int len;28382839if(!ce_stage(ce))2840continue;2841 unmerged =1;2842 len =ce_namelen(ce);2843 new_ce =make_empty_cache_entry(istate, len);2844memcpy(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;2848if(add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))2849returnerror("%s: cannot drop to stage #0",2850 new_ce->name);2851}2852return unmerged;2853}28542855/*2856 * Returns 1 if the path is an "other" path with respect to2857 * 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 that2862 * the output of read_directory can be used as-is.2863 */2864intindex_name_is_other(const struct index_state *istate,const char*name,2865int namelen)2866{2867int pos;2868if(namelen && name[namelen -1] =='/')2869 namelen--;2870 pos =index_name_pos(istate, name, namelen);2871if(0<= pos)2872return0;/* exact match */2873 pos = -pos -1;2874if(pos < istate->cache_nr) {2875struct cache_entry *ce = istate->cache[pos];2876if(ce_namelen(ce) == namelen &&2877!memcmp(ce->name, name, namelen))2878return0;/* Yup, this one exists unmerged */2879}2880return1;2881}28822883void*read_blob_data_from_index(const struct index_state *istate,2884const char*path,unsigned long*size)2885{2886int pos, len;2887unsigned long sz;2888enum object_type type;2889void*data;28902891 len =strlen(path);2892 pos =index_name_pos(istate, path, len);2893if(pos <0) {2894/*2895 * We might be in the middle of a merge, in which2896 * case we would read stage #2 (ours).2897 */2898int i;2899for(i = -pos -1;2900(pos <0&& i < istate->cache_nr &&2901!strcmp(istate->cache[i]->name, path));2902 i++)2903if(ce_stage(istate->cache[i]) ==2)2904 pos = i;2905}2906if(pos <0)2907return NULL;2908 data =read_object_file(&istate->cache[pos]->oid, &type, &sz);2909if(!data || type != OBJ_BLOB) {2910free(data);2911return NULL;2912}2913if(size)2914*size = sz;2915return data;2916}29172918voidstat_validity_clear(struct stat_validity *sv)2919{2920FREE_AND_NULL(sv->sd);2921}29222923intstat_validity_check(struct stat_validity *sv,const char*path)2924{2925struct stat st;29262927if(stat(path, &st) <0)2928return sv->sd == NULL;2929if(!sv->sd)2930return0;2931returnS_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);2932}29332934voidstat_validity_update(struct stat_validity *sv,int fd)2935{2936struct stat st;29372938if(fstat(fd, &st) <0|| !S_ISREG(st.st_mode))2939stat_validity_clear(sv);2940else{2941if(!sv->sd)2942 sv->sd =xcalloc(1,sizeof(struct stat_data));2943fill_stat_data(sv->sd, &st);2944}2945}29462947voidmove_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}29542955struct cache_entry *dup_cache_entry(const struct cache_entry *ce,2956struct index_state *istate)2957{2958unsigned int size =ce_size(ce);2959int mem_pool_allocated;2960struct cache_entry *new_entry =make_empty_cache_entry(istate,ce_namelen(ce));2961 mem_pool_allocated = new_entry->mem_pool_allocated;29622963memcpy(new_entry, ce, size);2964 new_entry->mem_pool_allocated = mem_pool_allocated;2965return new_entry;2966}29672968voiddiscard_cache_entry(struct cache_entry *ce)2969{2970if(ce &&should_validate_cache_entries())2971memset(ce,0xCD,cache_entry_size(ce->ce_namelen));29722973if(ce && ce->mem_pool_allocated)2974return;29752976free(ce);2977}29782979intshould_validate_cache_entries(void)2980{2981static int validate_index_cache_entries = -1;29822983if(validate_index_cache_entries <0) {2984if(getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))2985 validate_index_cache_entries =1;2986else2987 validate_index_cache_entries =0;2988}29892990return validate_index_cache_entries;2991}