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 =oidcmp(&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; 259returnoidcmp(&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) && 774!oidcmp(&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;1483uint64_t start =getnanotime();14841485 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_since(start,"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(hashcmp(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{2009uint64_t start =getnanotime();2010struct split_index *split_index;2011int ret;2012char*base_oid_hex;2013char*base_path;20142015/* istate->initialized covers both .git/index and .git/sharedindex.xxx */2016if(istate->initialized)2017return istate->cache_nr;20182019 ret =do_read_index(istate, path,0);2020trace_performance_since(start,"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}20272028if(split_index->base)2029discard_index(split_index->base);2030else2031 split_index->base =xcalloc(1,sizeof(*split_index->base));20322033 base_oid_hex =oid_to_hex(&split_index->base_oid);2034 base_path =xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);2035 ret =do_read_index(split_index->base, base_path,1);2036if(oidcmp(&split_index->base_oid, &split_index->base->oid))2037die("broken index, expect%sin%s, got%s",2038 base_oid_hex, base_path,2039oid_to_hex(&split_index->base->oid));20402041freshen_shared_index(base_path,0);2042merge_base_index(istate);2043post_read_index_from(istate);2044trace_performance_since(start,"read cache%s", base_path);2045free(base_path);2046return ret;2047}20482049intis_index_unborn(struct index_state *istate)2050{2051return(!istate->cache_nr && !istate->timestamp.sec);2052}20532054intdiscard_index(struct index_state *istate)2055{2056/*2057 * Cache entries in istate->cache[] should have been allocated2058 * from the memory pool associated with this index, or from an2059 * associated split_index. There is no need to free individual2060 * cache entries. validate_cache_entries can detect when this2061 * assertion does not hold.2062 */2063validate_cache_entries(istate);20642065resolve_undo_clear_index(istate);2066 istate->cache_nr =0;2067 istate->cache_changed =0;2068 istate->timestamp.sec =0;2069 istate->timestamp.nsec =0;2070free_name_hash(istate);2071cache_tree_free(&(istate->cache_tree));2072 istate->initialized =0;2073FREE_AND_NULL(istate->cache);2074 istate->cache_alloc =0;2075discard_split_index(istate);2076free_untracked_cache(istate->untracked);2077 istate->untracked = NULL;20782079if(istate->ce_mem_pool) {2080mem_pool_discard(istate->ce_mem_pool,should_validate_cache_entries());2081 istate->ce_mem_pool = NULL;2082}20832084return0;2085}20862087/*2088 * Validate the cache entries of this index.2089 * All cache entries associated with this index2090 * should have been allocated by the memory pool2091 * associated with this index, or by a referenced2092 * split index.2093 */2094voidvalidate_cache_entries(const struct index_state *istate)2095{2096int i;20972098if(!should_validate_cache_entries() ||!istate || !istate->initialized)2099return;21002101for(i =0; i < istate->cache_nr; i++) {2102if(!istate) {2103die("internal error: cache entry is not allocated from expected memory pool");2104}else if(!istate->ce_mem_pool ||2105!mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {2106if(!istate->split_index ||2107!istate->split_index->base ||2108!istate->split_index->base->ce_mem_pool ||2109!mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {2110die("internal error: cache entry is not allocated from expected memory pool");2111}2112}2113}21142115if(istate->split_index)2116validate_cache_entries(istate->split_index->base);2117}21182119intunmerged_index(const struct index_state *istate)2120{2121int i;2122for(i =0; i < istate->cache_nr; i++) {2123if(ce_stage(istate->cache[i]))2124return1;2125}2126return0;2127}21282129intindex_has_changes(struct index_state *istate,2130struct tree *tree,2131struct strbuf *sb)2132{2133struct object_id cmp;2134int i;21352136if(istate != &the_index) {2137BUG("index_has_changes cannot yet accept istate != &the_index; do_diff_cache needs updating first.");2138}2139if(tree)2140 cmp = tree->object.oid;2141if(tree || !get_oid_tree("HEAD", &cmp)) {2142struct diff_options opt;21432144repo_diff_setup(the_repository, &opt);2145 opt.flags.exit_with_status =1;2146if(!sb)2147 opt.flags.quick =1;2148do_diff_cache(&cmp, &opt);2149diffcore_std(&opt);2150for(i =0; sb && i < diff_queued_diff.nr; i++) {2151if(i)2152strbuf_addch(sb,' ');2153strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);2154}2155diff_flush(&opt);2156return opt.flags.has_changes !=0;2157}else{2158for(i =0; sb && i < istate->cache_nr; i++) {2159if(i)2160strbuf_addch(sb,' ');2161strbuf_addstr(sb, istate->cache[i]->name);2162}2163return!!istate->cache_nr;2164}2165}21662167#define WRITE_BUFFER_SIZE 81922168static unsigned char write_buffer[WRITE_BUFFER_SIZE];2169static unsigned long write_buffer_len;21702171static intce_write_flush(git_hash_ctx *context,int fd)2172{2173unsigned int buffered = write_buffer_len;2174if(buffered) {2175 the_hash_algo->update_fn(context, write_buffer, buffered);2176if(write_in_full(fd, write_buffer, buffered) <0)2177return-1;2178 write_buffer_len =0;2179}2180return0;2181}21822183static intce_write(git_hash_ctx *context,int fd,void*data,unsigned int len)2184{2185while(len) {2186unsigned int buffered = write_buffer_len;2187unsigned int partial = WRITE_BUFFER_SIZE - buffered;2188if(partial > len)2189 partial = len;2190memcpy(write_buffer + buffered, data, partial);2191 buffered += partial;2192if(buffered == WRITE_BUFFER_SIZE) {2193 write_buffer_len = buffered;2194if(ce_write_flush(context, fd))2195return-1;2196 buffered =0;2197}2198 write_buffer_len = buffered;2199 len -= partial;2200 data = (char*) data + partial;2201}2202return0;2203}22042205static intwrite_index_ext_header(git_hash_ctx *context,int fd,2206unsigned int ext,unsigned int sz)2207{2208 ext =htonl(ext);2209 sz =htonl(sz);2210return((ce_write(context, fd, &ext,4) <0) ||2211(ce_write(context, fd, &sz,4) <0)) ? -1:0;2212}22132214static intce_flush(git_hash_ctx *context,int fd,unsigned char*hash)2215{2216unsigned int left = write_buffer_len;22172218if(left) {2219 write_buffer_len =0;2220 the_hash_algo->update_fn(context, write_buffer, left);2221}22222223/* Flush first if not enough space for hash signature */2224if(left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {2225if(write_in_full(fd, write_buffer, left) <0)2226return-1;2227 left =0;2228}22292230/* Append the hash signature at the end */2231 the_hash_algo->final_fn(write_buffer + left, context);2232hashcpy(hash, write_buffer + left);2233 left += the_hash_algo->rawsz;2234return(write_in_full(fd, write_buffer, left) <0) ? -1:0;2235}22362237static voidce_smudge_racily_clean_entry(struct index_state *istate,2238struct cache_entry *ce)2239{2240/*2241 * The only thing we care about in this function is to smudge the2242 * falsely clean entry due to touch-update-touch race, so we leave2243 * everything else as they are. We are called for entries whose2244 * ce_stat_data.sd_mtime match the index file mtime.2245 *2246 * Note that this actually does not do much for gitlinks, for2247 * which ce_match_stat_basic() always goes to the actual2248 * contents. The caller checks with is_racy_timestamp() which2249 * always says "no" for gitlinks, so we are not called for them ;-)2250 */2251struct stat st;22522253if(lstat(ce->name, &st) <0)2254return;2255if(ce_match_stat_basic(ce, &st))2256return;2257if(ce_modified_check_fs(istate, ce, &st)) {2258/* This is "racily clean"; smudge it. Note that this2259 * is a tricky code. At first glance, it may appear2260 * that it can break with this sequence:2261 *2262 * $ echo xyzzy >frotz2263 * $ git-update-index --add frotz2264 * $ : >frotz2265 * $ sleep 32266 * $ echo filfre >nitfol2267 * $ git-update-index --add nitfol2268 *2269 * but it does not. When the second update-index runs,2270 * it notices that the entry "frotz" has the same timestamp2271 * as index, and if we were to smudge it by resetting its2272 * size to zero here, then the object name recorded2273 * in index is the 6-byte file but the cached stat information2274 * becomes zero --- which would then match what we would2275 * obtain from the filesystem next time we stat("frotz").2276 *2277 * However, the second update-index, before calling2278 * this function, notices that the cached size is 62279 * bytes and what is on the filesystem is an empty2280 * file, and never calls us, so the cached size information2281 * for "frotz" stays 6 which does not match the filesystem.2282 */2283 ce->ce_stat_data.sd_size =0;2284}2285}22862287/* Copy miscellaneous fields but not the name */2288static voidcopy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,2289struct cache_entry *ce)2290{2291short flags;22922293 ondisk->ctime.sec =htonl(ce->ce_stat_data.sd_ctime.sec);2294 ondisk->mtime.sec =htonl(ce->ce_stat_data.sd_mtime.sec);2295 ondisk->ctime.nsec =htonl(ce->ce_stat_data.sd_ctime.nsec);2296 ondisk->mtime.nsec =htonl(ce->ce_stat_data.sd_mtime.nsec);2297 ondisk->dev =htonl(ce->ce_stat_data.sd_dev);2298 ondisk->ino =htonl(ce->ce_stat_data.sd_ino);2299 ondisk->mode =htonl(ce->ce_mode);2300 ondisk->uid =htonl(ce->ce_stat_data.sd_uid);2301 ondisk->gid =htonl(ce->ce_stat_data.sd_gid);2302 ondisk->size =htonl(ce->ce_stat_data.sd_size);2303hashcpy(ondisk->sha1, ce->oid.hash);23042305 flags = ce->ce_flags & ~CE_NAMEMASK;2306 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK :ce_namelen(ce));2307 ondisk->flags =htons(flags);2308if(ce->ce_flags & CE_EXTENDED) {2309struct ondisk_cache_entry_extended *ondisk2;2310 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;2311 ondisk2->flags2 =htons((ce->ce_flags & CE_EXTENDED_FLAGS) >>16);2312}2313}23142315static intce_write_entry(git_hash_ctx *c,int fd,struct cache_entry *ce,2316struct strbuf *previous_name,struct ondisk_cache_entry *ondisk)2317{2318int size;2319int result;2320unsigned int saved_namelen;2321int stripped_name =0;2322static unsigned char padding[8] = {0x00};23232324if(ce->ce_flags & CE_STRIP_NAME) {2325 saved_namelen =ce_namelen(ce);2326 ce->ce_namelen =0;2327 stripped_name =1;2328}23292330if(ce->ce_flags & CE_EXTENDED)2331 size =offsetof(struct ondisk_cache_entry_extended, name);2332else2333 size =offsetof(struct ondisk_cache_entry, name);23342335if(!previous_name) {2336int len =ce_namelen(ce);2337copy_cache_entry_to_ondisk(ondisk, ce);2338 result =ce_write(c, fd, ondisk, size);2339if(!result)2340 result =ce_write(c, fd, ce->name, len);2341if(!result)2342 result =ce_write(c, fd, padding,align_padding_size(size, len));2343}else{2344int common, to_remove, prefix_size;2345unsigned char to_remove_vi[16];2346for(common =0;2347(ce->name[common] &&2348 common < previous_name->len &&2349 ce->name[common] == previous_name->buf[common]);2350 common++)2351;/* still matching */2352 to_remove = previous_name->len - common;2353 prefix_size =encode_varint(to_remove, to_remove_vi);23542355copy_cache_entry_to_ondisk(ondisk, ce);2356 result =ce_write(c, fd, ondisk, size);2357if(!result)2358 result =ce_write(c, fd, to_remove_vi, prefix_size);2359if(!result)2360 result =ce_write(c, fd, ce->name + common,ce_namelen(ce) - common);2361if(!result)2362 result =ce_write(c, fd, padding,1);23632364strbuf_splice(previous_name, common, to_remove,2365 ce->name + common,ce_namelen(ce) - common);2366}2367if(stripped_name) {2368 ce->ce_namelen = saved_namelen;2369 ce->ce_flags &= ~CE_STRIP_NAME;2370}23712372return result;2373}23742375/*2376 * This function verifies if index_state has the correct sha1 of the2377 * index file. Don't die if we have any other failure, just return 0.2378 */2379static intverify_index_from(const struct index_state *istate,const char*path)2380{2381int fd;2382 ssize_t n;2383struct stat st;2384unsigned char hash[GIT_MAX_RAWSZ];23852386if(!istate->initialized)2387return0;23882389 fd =open(path, O_RDONLY);2390if(fd <0)2391return0;23922393if(fstat(fd, &st))2394goto out;23952396if(st.st_size <sizeof(struct cache_header) + the_hash_algo->rawsz)2397goto out;23982399 n =pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);2400if(n != the_hash_algo->rawsz)2401goto out;24022403if(hashcmp(istate->oid.hash, hash))2404goto out;24052406close(fd);2407return1;24082409out:2410close(fd);2411return0;2412}24132414static intverify_index(const struct index_state *istate)2415{2416returnverify_index_from(istate,get_index_file());2417}24182419static inthas_racy_timestamp(struct index_state *istate)2420{2421int entries = istate->cache_nr;2422int i;24232424for(i =0; i < entries; i++) {2425struct cache_entry *ce = istate->cache[i];2426if(is_racy_timestamp(istate, ce))2427return1;2428}2429return0;2430}24312432voidupdate_index_if_able(struct index_state *istate,struct lock_file *lockfile)2433{2434if((istate->cache_changed ||has_racy_timestamp(istate)) &&2435verify_index(istate))2436write_locked_index(istate, lockfile, COMMIT_LOCK);2437else2438rollback_lock_file(lockfile);2439}24402441/*2442 * On success, `tempfile` is closed. If it is the temporary file2443 * of a `struct lock_file`, we will therefore effectively perform2444 * a 'close_lock_file_gently()`. Since that is an implementation2445 * detail of lockfiles, callers of `do_write_index()` should not2446 * rely on it.2447 */2448static intdo_write_index(struct index_state *istate,struct tempfile *tempfile,2449int strip_extensions)2450{2451uint64_t start =getnanotime();2452int newfd = tempfile->fd;2453 git_hash_ctx c;2454struct cache_header hdr;2455int i, err =0, removed, extended, hdr_version;2456struct cache_entry **cache = istate->cache;2457int entries = istate->cache_nr;2458struct stat st;2459struct ondisk_cache_entry_extended ondisk;2460struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;2461int drop_cache_tree = istate->drop_cache_tree;24622463for(i = removed = extended =0; i < entries; i++) {2464if(cache[i]->ce_flags & CE_REMOVE)2465 removed++;24662467/* reduce extended entries if possible */2468 cache[i]->ce_flags &= ~CE_EXTENDED;2469if(cache[i]->ce_flags & CE_EXTENDED_FLAGS) {2470 extended++;2471 cache[i]->ce_flags |= CE_EXTENDED;2472}2473}24742475if(!istate->version) {2476 istate->version =get_index_format_default();2477if(git_env_bool("GIT_TEST_SPLIT_INDEX",0))2478init_split_index(istate);2479}24802481/* demote version 3 to version 2 when the latter suffices */2482if(istate->version ==3|| istate->version ==2)2483 istate->version = extended ?3:2;24842485 hdr_version = istate->version;24862487 hdr.hdr_signature =htonl(CACHE_SIGNATURE);2488 hdr.hdr_version =htonl(hdr_version);2489 hdr.hdr_entries =htonl(entries - removed);24902491 the_hash_algo->init_fn(&c);2492if(ce_write(&c, newfd, &hdr,sizeof(hdr)) <0)2493return-1;24942495 previous_name = (hdr_version ==4) ? &previous_name_buf : NULL;24962497for(i =0; i < entries; i++) {2498struct cache_entry *ce = cache[i];2499if(ce->ce_flags & CE_REMOVE)2500continue;2501if(!ce_uptodate(ce) &&is_racy_timestamp(istate, ce))2502ce_smudge_racily_clean_entry(istate, ce);2503if(is_null_oid(&ce->oid)) {2504static const char msg[] ="cache entry has null sha1:%s";2505static int allow = -1;25062507if(allow <0)2508 allow =git_env_bool("GIT_ALLOW_NULL_SHA1",0);2509if(allow)2510warning(msg, ce->name);2511else2512 err =error(msg, ce->name);25132514 drop_cache_tree =1;2515}2516if(ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) <0)2517 err = -1;25182519if(err)2520break;2521}2522strbuf_release(&previous_name_buf);25232524if(err)2525return err;25262527/* Write extension data here */2528if(!strip_extensions && istate->split_index) {2529struct strbuf sb = STRBUF_INIT;25302531 err =write_link_extension(&sb, istate) <0||2532write_index_ext_header(&c, newfd, CACHE_EXT_LINK,2533 sb.len) <0||2534ce_write(&c, newfd, sb.buf, sb.len) <0;2535strbuf_release(&sb);2536if(err)2537return-1;2538}2539if(!strip_extensions && !drop_cache_tree && istate->cache_tree) {2540struct strbuf sb = STRBUF_INIT;25412542cache_tree_write(&sb, istate->cache_tree);2543 err =write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) <02544||ce_write(&c, newfd, sb.buf, sb.len) <0;2545strbuf_release(&sb);2546if(err)2547return-1;2548}2549if(!strip_extensions && istate->resolve_undo) {2550struct strbuf sb = STRBUF_INIT;25512552resolve_undo_write(&sb, istate->resolve_undo);2553 err =write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,2554 sb.len) <02555||ce_write(&c, newfd, sb.buf, sb.len) <0;2556strbuf_release(&sb);2557if(err)2558return-1;2559}2560if(!strip_extensions && istate->untracked) {2561struct strbuf sb = STRBUF_INIT;25622563write_untracked_extension(&sb, istate->untracked);2564 err =write_index_ext_header(&c, newfd, CACHE_EXT_UNTRACKED,2565 sb.len) <0||2566ce_write(&c, newfd, sb.buf, sb.len) <0;2567strbuf_release(&sb);2568if(err)2569return-1;2570}2571if(!strip_extensions && istate->fsmonitor_last_update) {2572struct strbuf sb = STRBUF_INIT;25732574write_fsmonitor_extension(&sb, istate);2575 err =write_index_ext_header(&c, newfd, CACHE_EXT_FSMONITOR, sb.len) <02576||ce_write(&c, newfd, sb.buf, sb.len) <0;2577strbuf_release(&sb);2578if(err)2579return-1;2580}25812582if(ce_flush(&c, newfd, istate->oid.hash))2583return-1;2584if(close_tempfile_gently(tempfile)) {2585error(_("could not close '%s'"), tempfile->filename.buf);2586return-1;2587}2588if(stat(tempfile->filename.buf, &st))2589return-1;2590 istate->timestamp.sec = (unsigned int)st.st_mtime;2591 istate->timestamp.nsec =ST_MTIME_NSEC(st);2592trace_performance_since(start,"write index, changed mask =%x", istate->cache_changed);2593return0;2594}25952596voidset_alternate_index_output(const char*name)2597{2598 alternate_index_output = name;2599}26002601static intcommit_locked_index(struct lock_file *lk)2602{2603if(alternate_index_output)2604returncommit_lock_file_to(lk, alternate_index_output);2605else2606returncommit_lock_file(lk);2607}26082609static intdo_write_locked_index(struct index_state *istate,struct lock_file *lock,2610unsigned flags)2611{2612int ret =do_write_index(istate, lock->tempfile,0);2613if(ret)2614return ret;2615if(flags & COMMIT_LOCK)2616returncommit_locked_index(lock);2617returnclose_lock_file_gently(lock);2618}26192620static intwrite_split_index(struct index_state *istate,2621struct lock_file *lock,2622unsigned flags)2623{2624int ret;2625prepare_to_write_split_index(istate);2626 ret =do_write_locked_index(istate, lock, flags);2627finish_writing_split_index(istate);2628return ret;2629}26302631static const char*shared_index_expire ="2.weeks.ago";26322633static unsigned longget_shared_index_expire_date(void)2634{2635static unsigned long shared_index_expire_date;2636static int shared_index_expire_date_prepared;26372638if(!shared_index_expire_date_prepared) {2639git_config_get_expiry("splitindex.sharedindexexpire",2640&shared_index_expire);2641 shared_index_expire_date =approxidate(shared_index_expire);2642 shared_index_expire_date_prepared =1;2643}26442645return shared_index_expire_date;2646}26472648static intshould_delete_shared_index(const char*shared_index_path)2649{2650struct stat st;2651unsigned long expiration;26522653/* Check timestamp */2654 expiration =get_shared_index_expire_date();2655if(!expiration)2656return0;2657if(stat(shared_index_path, &st))2658returnerror_errno(_("could not stat '%s'"), shared_index_path);2659if(st.st_mtime > expiration)2660return0;26612662return1;2663}26642665static intclean_shared_index_files(const char*current_hex)2666{2667struct dirent *de;2668DIR*dir =opendir(get_git_dir());26692670if(!dir)2671returnerror_errno(_("unable to open git dir:%s"),get_git_dir());26722673while((de =readdir(dir)) != NULL) {2674const char*sha1_hex;2675const char*shared_index_path;2676if(!skip_prefix(de->d_name,"sharedindex.", &sha1_hex))2677continue;2678if(!strcmp(sha1_hex, current_hex))2679continue;2680 shared_index_path =git_path("%s", de->d_name);2681if(should_delete_shared_index(shared_index_path) >0&&2682unlink(shared_index_path))2683warning_errno(_("unable to unlink:%s"), shared_index_path);2684}2685closedir(dir);26862687return0;2688}26892690static intwrite_shared_index(struct index_state *istate,2691struct tempfile **temp)2692{2693struct split_index *si = istate->split_index;2694int ret;26952696move_cache_to_base_index(istate);2697 ret =do_write_index(si->base, *temp,1);2698if(ret)2699return ret;2700 ret =adjust_shared_perm(get_tempfile_path(*temp));2701if(ret) {2702error("cannot fix permission bits on%s",get_tempfile_path(*temp));2703return ret;2704}2705 ret =rename_tempfile(temp,2706git_path("sharedindex.%s",oid_to_hex(&si->base->oid)));2707if(!ret) {2708oidcpy(&si->base_oid, &si->base->oid);2709clean_shared_index_files(oid_to_hex(&si->base->oid));2710}27112712return ret;2713}27142715static const int default_max_percent_split_change =20;27162717static inttoo_many_not_shared_entries(struct index_state *istate)2718{2719int i, not_shared =0;2720int max_split =git_config_get_max_percent_split_change();27212722switch(max_split) {2723case-1:2724/* not or badly configured: use the default value */2725 max_split = default_max_percent_split_change;2726break;2727case0:2728return1;/* 0% means always write a new shared index */2729case100:2730return0;/* 100% means never write a new shared index */2731default:2732break;/* just use the configured value */2733}27342735/* Count not shared entries */2736for(i =0; i < istate->cache_nr; i++) {2737struct cache_entry *ce = istate->cache[i];2738if(!ce->index)2739 not_shared++;2740}27412742return(int64_t)istate->cache_nr * max_split < (int64_t)not_shared *100;2743}27442745intwrite_locked_index(struct index_state *istate,struct lock_file *lock,2746unsigned flags)2747{2748int new_shared_index, ret;2749struct split_index *si = istate->split_index;27502751if((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {2752if(flags & COMMIT_LOCK)2753rollback_lock_file(lock);2754return0;2755}27562757if(istate->fsmonitor_last_update)2758fill_fsmonitor_bitmap(istate);27592760if(!si || alternate_index_output ||2761(istate->cache_changed & ~EXTMASK)) {2762if(si)2763oidclr(&si->base_oid);2764 ret =do_write_locked_index(istate, lock, flags);2765goto out;2766}27672768if(git_env_bool("GIT_TEST_SPLIT_INDEX",0)) {2769int v = si->base_oid.hash[0];2770if((v &15) <6)2771 istate->cache_changed |= SPLIT_INDEX_ORDERED;2772}2773if(too_many_not_shared_entries(istate))2774 istate->cache_changed |= SPLIT_INDEX_ORDERED;27752776 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;27772778if(new_shared_index) {2779struct tempfile *temp;2780int saved_errno;27812782 temp =mks_tempfile(git_path("sharedindex_XXXXXX"));2783if(!temp) {2784oidclr(&si->base_oid);2785 ret =do_write_locked_index(istate, lock, flags);2786goto out;2787}2788 ret =write_shared_index(istate, &temp);27892790 saved_errno = errno;2791if(is_tempfile_active(temp))2792delete_tempfile(&temp);2793 errno = saved_errno;27942795if(ret)2796goto out;2797}27982799 ret =write_split_index(istate, lock, flags);28002801/* Freshen the shared index only if the split-index was written */2802if(!ret && !new_shared_index) {2803const char*shared_index =git_path("sharedindex.%s",2804oid_to_hex(&si->base_oid));2805freshen_shared_index(shared_index,1);2806}28072808out:2809if(flags & COMMIT_LOCK)2810rollback_lock_file(lock);2811return ret;2812}28132814/*2815 * Read the index file that is potentially unmerged into given2816 * index_state, dropping any unmerged entries to stage #0 (potentially2817 * resulting in a path appearing as both a file and a directory in the2818 * index; the caller is responsible to clear out the extra entries2819 * before writing the index to a tree). Returns true if the index is2820 * unmerged. Callers who want to refuse to work from an unmerged2821 * state can call this and check its return value, instead of calling2822 * read_cache().2823 */2824intread_index_unmerged(struct index_state *istate)2825{2826int i;2827int unmerged =0;28282829read_index(istate);2830for(i =0; i < istate->cache_nr; i++) {2831struct cache_entry *ce = istate->cache[i];2832struct cache_entry *new_ce;2833int len;28342835if(!ce_stage(ce))2836continue;2837 unmerged =1;2838 len =ce_namelen(ce);2839 new_ce =make_empty_cache_entry(istate, len);2840memcpy(new_ce->name, ce->name, len);2841 new_ce->ce_flags =create_ce_flags(0) | CE_CONFLICTED;2842 new_ce->ce_namelen = len;2843 new_ce->ce_mode = ce->ce_mode;2844if(add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))2845returnerror("%s: cannot drop to stage #0",2846 new_ce->name);2847}2848return unmerged;2849}28502851/*2852 * Returns 1 if the path is an "other" path with respect to2853 * the index; that is, the path is not mentioned in the index at all,2854 * either as a file, a directory with some files in the index,2855 * or as an unmerged entry.2856 *2857 * We helpfully remove a trailing "/" from directories so that2858 * the output of read_directory can be used as-is.2859 */2860intindex_name_is_other(const struct index_state *istate,const char*name,2861int namelen)2862{2863int pos;2864if(namelen && name[namelen -1] =='/')2865 namelen--;2866 pos =index_name_pos(istate, name, namelen);2867if(0<= pos)2868return0;/* exact match */2869 pos = -pos -1;2870if(pos < istate->cache_nr) {2871struct cache_entry *ce = istate->cache[pos];2872if(ce_namelen(ce) == namelen &&2873!memcmp(ce->name, name, namelen))2874return0;/* Yup, this one exists unmerged */2875}2876return1;2877}28782879void*read_blob_data_from_index(const struct index_state *istate,2880const char*path,unsigned long*size)2881{2882int pos, len;2883unsigned long sz;2884enum object_type type;2885void*data;28862887 len =strlen(path);2888 pos =index_name_pos(istate, path, len);2889if(pos <0) {2890/*2891 * We might be in the middle of a merge, in which2892 * case we would read stage #2 (ours).2893 */2894int i;2895for(i = -pos -1;2896(pos <0&& i < istate->cache_nr &&2897!strcmp(istate->cache[i]->name, path));2898 i++)2899if(ce_stage(istate->cache[i]) ==2)2900 pos = i;2901}2902if(pos <0)2903return NULL;2904 data =read_object_file(&istate->cache[pos]->oid, &type, &sz);2905if(!data || type != OBJ_BLOB) {2906free(data);2907return NULL;2908}2909if(size)2910*size = sz;2911return data;2912}29132914voidstat_validity_clear(struct stat_validity *sv)2915{2916FREE_AND_NULL(sv->sd);2917}29182919intstat_validity_check(struct stat_validity *sv,const char*path)2920{2921struct stat st;29222923if(stat(path, &st) <0)2924return sv->sd == NULL;2925if(!sv->sd)2926return0;2927returnS_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);2928}29292930voidstat_validity_update(struct stat_validity *sv,int fd)2931{2932struct stat st;29332934if(fstat(fd, &st) <0|| !S_ISREG(st.st_mode))2935stat_validity_clear(sv);2936else{2937if(!sv->sd)2938 sv->sd =xcalloc(1,sizeof(struct stat_data));2939fill_stat_data(sv->sd, &st);2940}2941}29422943voidmove_index_extensions(struct index_state *dst,struct index_state *src)2944{2945 dst->untracked = src->untracked;2946 src->untracked = NULL;2947}29482949struct cache_entry *dup_cache_entry(const struct cache_entry *ce,2950struct index_state *istate)2951{2952unsigned int size =ce_size(ce);2953int mem_pool_allocated;2954struct cache_entry *new_entry =make_empty_cache_entry(istate,ce_namelen(ce));2955 mem_pool_allocated = new_entry->mem_pool_allocated;29562957memcpy(new_entry, ce, size);2958 new_entry->mem_pool_allocated = mem_pool_allocated;2959return new_entry;2960}29612962voiddiscard_cache_entry(struct cache_entry *ce)2963{2964if(ce &&should_validate_cache_entries())2965memset(ce,0xCD,cache_entry_size(ce->ce_namelen));29662967if(ce && ce->mem_pool_allocated)2968return;29692970free(ce);2971}29722973intshould_validate_cache_entries(void)2974{2975static int validate_index_cache_entries = -1;29762977if(validate_index_cache_entries <0) {2978if(getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))2979 validate_index_cache_entries =1;2980else2981 validate_index_cache_entries =0;2982}29832984return validate_index_cache_entries;2985}