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#include"progress.h" 27 28/* Mask for the name length in ce_flags in the on-disk index */ 29 30#define CE_NAMEMASK (0x0fff) 31 32/* Index extensions. 33 * 34 * The first letter should be 'A'..'Z' for extensions that are not 35 * necessary for a correct operation (i.e. optimization data). 36 * When new extensions are added that _needs_ to be understood in 37 * order to correctly interpret the index file, pick character that 38 * is outside the range, to cause the reader to abort. 39 */ 40 41#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) ) 42#define CACHE_EXT_TREE 0x54524545/* "TREE" */ 43#define CACHE_EXT_RESOLVE_UNDO 0x52455543/* "REUC" */ 44#define CACHE_EXT_LINK 0x6c696e6b/* "link" */ 45#define CACHE_EXT_UNTRACKED 0x554E5452/* "UNTR" */ 46#define CACHE_EXT_FSMONITOR 0x46534D4E/* "FSMN" */ 47 48/* changes that can be kept in $GIT_DIR/index (basically all extensions) */ 49#define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \ 50 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \ 51 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED) 52 53 54/* 55 * This is an estimate of the pathname length in the index. We use 56 * this for V4 index files to guess the un-deltafied size of the index 57 * in memory because of pathname deltafication. This is not required 58 * for V2/V3 index formats because their pathnames are not compressed. 59 * If the initial amount of memory set aside is not sufficient, the 60 * mem pool will allocate extra memory. 61 */ 62#define CACHE_ENTRY_PATH_LENGTH 80 63 64staticinlinestruct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool,size_t len) 65{ 66struct cache_entry *ce; 67 ce =mem_pool_alloc(mem_pool,cache_entry_size(len)); 68 ce->mem_pool_allocated =1; 69return ce; 70} 71 72staticinlinestruct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool,size_t len) 73{ 74struct cache_entry * ce; 75 ce =mem_pool_calloc(mem_pool,1,cache_entry_size(len)); 76 ce->mem_pool_allocated =1; 77return ce; 78} 79 80static struct mem_pool *find_mem_pool(struct index_state *istate) 81{ 82struct mem_pool **pool_ptr; 83 84if(istate->split_index && istate->split_index->base) 85 pool_ptr = &istate->split_index->base->ce_mem_pool; 86else 87 pool_ptr = &istate->ce_mem_pool; 88 89if(!*pool_ptr) 90mem_pool_init(pool_ptr,0); 91 92return*pool_ptr; 93} 94 95struct index_state the_index; 96static const char*alternate_index_output; 97 98static voidset_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 99{ 100 istate->cache[nr] = ce; 101add_name_hash(istate, ce); 102} 103 104static voidreplace_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 105{ 106struct cache_entry *old = istate->cache[nr]; 107 108replace_index_entry_in_base(istate, old, ce); 109remove_name_hash(istate, old); 110discard_cache_entry(old); 111 ce->ce_flags &= ~CE_HASHED; 112set_index_entry(istate, nr, ce); 113 ce->ce_flags |= CE_UPDATE_IN_BASE; 114mark_fsmonitor_invalid(istate, ce); 115 istate->cache_changed |= CE_ENTRY_CHANGED; 116} 117 118voidrename_index_entry_at(struct index_state *istate,int nr,const char*new_name) 119{ 120struct cache_entry *old_entry = istate->cache[nr], *new_entry; 121int namelen =strlen(new_name); 122 123 new_entry =make_empty_cache_entry(istate, namelen); 124copy_cache_entry(new_entry, old_entry); 125 new_entry->ce_flags &= ~CE_HASHED; 126 new_entry->ce_namelen = namelen; 127 new_entry->index =0; 128memcpy(new_entry->name, new_name, namelen +1); 129 130cache_tree_invalidate_path(istate, old_entry->name); 131untracked_cache_remove_from_index(istate, old_entry->name); 132remove_index_entry_at(istate, nr); 133add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE); 134} 135 136voidfill_stat_data(struct stat_data *sd,struct stat *st) 137{ 138 sd->sd_ctime.sec = (unsigned int)st->st_ctime; 139 sd->sd_mtime.sec = (unsigned int)st->st_mtime; 140 sd->sd_ctime.nsec =ST_CTIME_NSEC(*st); 141 sd->sd_mtime.nsec =ST_MTIME_NSEC(*st); 142 sd->sd_dev = st->st_dev; 143 sd->sd_ino = st->st_ino; 144 sd->sd_uid = st->st_uid; 145 sd->sd_gid = st->st_gid; 146 sd->sd_size = st->st_size; 147} 148 149intmatch_stat_data(const struct stat_data *sd,struct stat *st) 150{ 151int changed =0; 152 153if(sd->sd_mtime.sec != (unsigned int)st->st_mtime) 154 changed |= MTIME_CHANGED; 155if(trust_ctime && check_stat && 156 sd->sd_ctime.sec != (unsigned int)st->st_ctime) 157 changed |= CTIME_CHANGED; 158 159#ifdef USE_NSEC 160if(check_stat && sd->sd_mtime.nsec !=ST_MTIME_NSEC(*st)) 161 changed |= MTIME_CHANGED; 162if(trust_ctime && check_stat && 163 sd->sd_ctime.nsec !=ST_CTIME_NSEC(*st)) 164 changed |= CTIME_CHANGED; 165#endif 166 167if(check_stat) { 168if(sd->sd_uid != (unsigned int) st->st_uid || 169 sd->sd_gid != (unsigned int) st->st_gid) 170 changed |= OWNER_CHANGED; 171if(sd->sd_ino != (unsigned int) st->st_ino) 172 changed |= INODE_CHANGED; 173} 174 175#ifdef USE_STDEV 176/* 177 * st_dev breaks on network filesystems where different 178 * clients will have different views of what "device" 179 * the filesystem is on 180 */ 181if(check_stat && sd->sd_dev != (unsigned int) st->st_dev) 182 changed |= INODE_CHANGED; 183#endif 184 185if(sd->sd_size != (unsigned int) st->st_size) 186 changed |= DATA_CHANGED; 187 188return changed; 189} 190 191/* 192 * This only updates the "non-critical" parts of the directory 193 * cache, ie the parts that aren't tracked by GIT, and only used 194 * to validate the cache. 195 */ 196voidfill_stat_cache_info(struct cache_entry *ce,struct stat *st) 197{ 198fill_stat_data(&ce->ce_stat_data, st); 199 200if(assume_unchanged) 201 ce->ce_flags |= CE_VALID; 202 203if(S_ISREG(st->st_mode)) { 204ce_mark_uptodate(ce); 205mark_fsmonitor_valid(ce); 206} 207} 208 209static intce_compare_data(const struct cache_entry *ce,struct stat *st) 210{ 211int match = -1; 212int fd =git_open_cloexec(ce->name, O_RDONLY); 213 214if(fd >=0) { 215struct object_id oid; 216if(!index_fd(&oid, fd, st, OBJ_BLOB, ce->name,0)) 217 match =oidcmp(&oid, &ce->oid); 218/* index_fd() closed the file descriptor already */ 219} 220return match; 221} 222 223static intce_compare_link(const struct cache_entry *ce,size_t expected_size) 224{ 225int match = -1; 226void*buffer; 227unsigned long size; 228enum object_type type; 229struct strbuf sb = STRBUF_INIT; 230 231if(strbuf_readlink(&sb, ce->name, expected_size)) 232return-1; 233 234 buffer =read_object_file(&ce->oid, &type, &size); 235if(buffer) { 236if(size == sb.len) 237 match =memcmp(buffer, sb.buf, size); 238free(buffer); 239} 240strbuf_release(&sb); 241return match; 242} 243 244static intce_compare_gitlink(const struct cache_entry *ce) 245{ 246struct object_id oid; 247 248/* 249 * We don't actually require that the .git directory 250 * under GITLINK directory be a valid git directory. It 251 * might even be missing (in case nobody populated that 252 * sub-project). 253 * 254 * If so, we consider it always to match. 255 */ 256if(resolve_gitlink_ref(ce->name,"HEAD", &oid) <0) 257return0; 258returnoidcmp(&oid, &ce->oid); 259} 260 261static intce_modified_check_fs(const struct cache_entry *ce,struct stat *st) 262{ 263switch(st->st_mode & S_IFMT) { 264case S_IFREG: 265if(ce_compare_data(ce, st)) 266return DATA_CHANGED; 267break; 268case S_IFLNK: 269if(ce_compare_link(ce,xsize_t(st->st_size))) 270return DATA_CHANGED; 271break; 272case S_IFDIR: 273if(S_ISGITLINK(ce->ce_mode)) 274returnce_compare_gitlink(ce) ? DATA_CHANGED :0; 275/* else fallthrough */ 276default: 277return TYPE_CHANGED; 278} 279return0; 280} 281 282static intce_match_stat_basic(const struct cache_entry *ce,struct stat *st) 283{ 284unsigned int changed =0; 285 286if(ce->ce_flags & CE_REMOVE) 287return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED; 288 289switch(ce->ce_mode & S_IFMT) { 290case S_IFREG: 291 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED :0; 292/* We consider only the owner x bit to be relevant for 293 * "mode changes" 294 */ 295if(trust_executable_bit && 296(0100& (ce->ce_mode ^ st->st_mode))) 297 changed |= MODE_CHANGED; 298break; 299case S_IFLNK: 300if(!S_ISLNK(st->st_mode) && 301(has_symlinks || !S_ISREG(st->st_mode))) 302 changed |= TYPE_CHANGED; 303break; 304case S_IFGITLINK: 305/* We ignore most of the st_xxx fields for gitlinks */ 306if(!S_ISDIR(st->st_mode)) 307 changed |= TYPE_CHANGED; 308else if(ce_compare_gitlink(ce)) 309 changed |= DATA_CHANGED; 310return changed; 311default: 312die("internal error: ce_mode is%o", ce->ce_mode); 313} 314 315 changed |=match_stat_data(&ce->ce_stat_data, st); 316 317/* Racily smudged entry? */ 318if(!ce->ce_stat_data.sd_size) { 319if(!is_empty_blob_sha1(ce->oid.hash)) 320 changed |= DATA_CHANGED; 321} 322 323return changed; 324} 325 326static intis_racy_stat(const struct index_state *istate, 327const struct stat_data *sd) 328{ 329return(istate->timestamp.sec && 330#ifdef USE_NSEC 331/* nanosecond timestamped files can also be racy! */ 332(istate->timestamp.sec < sd->sd_mtime.sec || 333(istate->timestamp.sec == sd->sd_mtime.sec && 334 istate->timestamp.nsec <= sd->sd_mtime.nsec)) 335#else 336 istate->timestamp.sec <= sd->sd_mtime.sec 337#endif 338); 339} 340 341static intis_racy_timestamp(const struct index_state *istate, 342const struct cache_entry *ce) 343{ 344return(!S_ISGITLINK(ce->ce_mode) && 345is_racy_stat(istate, &ce->ce_stat_data)); 346} 347 348intmatch_stat_data_racy(const struct index_state *istate, 349const struct stat_data *sd,struct stat *st) 350{ 351if(is_racy_stat(istate, sd)) 352return MTIME_CHANGED; 353returnmatch_stat_data(sd, st); 354} 355 356intie_match_stat(struct index_state *istate, 357const struct cache_entry *ce,struct stat *st, 358unsigned int options) 359{ 360unsigned int changed; 361int ignore_valid = options & CE_MATCH_IGNORE_VALID; 362int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE; 363int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY; 364int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR; 365 366if(!ignore_fsmonitor) 367refresh_fsmonitor(istate); 368/* 369 * If it's marked as always valid in the index, it's 370 * valid whatever the checked-out copy says. 371 * 372 * skip-worktree has the same effect with higher precedence 373 */ 374if(!ignore_skip_worktree &&ce_skip_worktree(ce)) 375return0; 376if(!ignore_valid && (ce->ce_flags & CE_VALID)) 377return0; 378if(!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) 379return0; 380 381/* 382 * Intent-to-add entries have not been added, so the index entry 383 * by definition never matches what is in the work tree until it 384 * actually gets added. 385 */ 386if(ce_intent_to_add(ce)) 387return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED; 388 389 changed =ce_match_stat_basic(ce, st); 390 391/* 392 * Within 1 second of this sequence: 393 * echo xyzzy >file && git-update-index --add file 394 * running this command: 395 * echo frotz >file 396 * would give a falsely clean cache entry. The mtime and 397 * length match the cache, and other stat fields do not change. 398 * 399 * We could detect this at update-index time (the cache entry 400 * being registered/updated records the same time as "now") 401 * and delay the return from git-update-index, but that would 402 * effectively mean we can make at most one commit per second, 403 * which is not acceptable. Instead, we check cache entries 404 * whose mtime are the same as the index file timestamp more 405 * carefully than others. 406 */ 407if(!changed &&is_racy_timestamp(istate, ce)) { 408if(assume_racy_is_modified) 409 changed |= DATA_CHANGED; 410else 411 changed |=ce_modified_check_fs(ce, st); 412} 413 414return changed; 415} 416 417intie_modified(struct index_state *istate, 418const struct cache_entry *ce, 419struct stat *st,unsigned int options) 420{ 421int changed, changed_fs; 422 423 changed =ie_match_stat(istate, ce, st, options); 424if(!changed) 425return0; 426/* 427 * If the mode or type has changed, there's no point in trying 428 * to refresh the entry - it's not going to match 429 */ 430if(changed & (MODE_CHANGED | TYPE_CHANGED)) 431return changed; 432 433/* 434 * Immediately after read-tree or update-index --cacheinfo, 435 * the length field is zero, as we have never even read the 436 * lstat(2) information once, and we cannot trust DATA_CHANGED 437 * returned by ie_match_stat() which in turn was returned by 438 * ce_match_stat_basic() to signal that the filesize of the 439 * blob changed. We have to actually go to the filesystem to 440 * see if the contents match, and if so, should answer "unchanged". 441 * 442 * The logic does not apply to gitlinks, as ce_match_stat_basic() 443 * already has checked the actual HEAD from the filesystem in the 444 * subproject. If ie_match_stat() already said it is different, 445 * then we know it is. 446 */ 447if((changed & DATA_CHANGED) && 448(S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size !=0)) 449return changed; 450 451 changed_fs =ce_modified_check_fs(ce, st); 452if(changed_fs) 453return changed | changed_fs; 454return0; 455} 456 457intbase_name_compare(const char*name1,int len1,int mode1, 458const char*name2,int len2,int mode2) 459{ 460unsigned char c1, c2; 461int len = len1 < len2 ? len1 : len2; 462int cmp; 463 464 cmp =memcmp(name1, name2, len); 465if(cmp) 466return cmp; 467 c1 = name1[len]; 468 c2 = name2[len]; 469if(!c1 &&S_ISDIR(mode1)) 470 c1 ='/'; 471if(!c2 &&S_ISDIR(mode2)) 472 c2 ='/'; 473return(c1 < c2) ? -1: (c1 > c2) ?1:0; 474} 475 476/* 477 * df_name_compare() is identical to base_name_compare(), except it 478 * compares conflicting directory/file entries as equal. Note that 479 * while a directory name compares as equal to a regular file, they 480 * then individually compare _differently_ to a filename that has 481 * a dot after the basename (because '\0' < '.' < '/'). 482 * 483 * This is used by routines that want to traverse the git namespace 484 * but then handle conflicting entries together when possible. 485 */ 486intdf_name_compare(const char*name1,int len1,int mode1, 487const char*name2,int len2,int mode2) 488{ 489int len = len1 < len2 ? len1 : len2, cmp; 490unsigned char c1, c2; 491 492 cmp =memcmp(name1, name2, len); 493if(cmp) 494return cmp; 495/* Directories and files compare equal (same length, same name) */ 496if(len1 == len2) 497return0; 498 c1 = name1[len]; 499if(!c1 &&S_ISDIR(mode1)) 500 c1 ='/'; 501 c2 = name2[len]; 502if(!c2 &&S_ISDIR(mode2)) 503 c2 ='/'; 504if(c1 =='/'&& !c2) 505return0; 506if(c2 =='/'&& !c1) 507return0; 508return c1 - c2; 509} 510 511intname_compare(const char*name1,size_t len1,const char*name2,size_t len2) 512{ 513size_t min_len = (len1 < len2) ? len1 : len2; 514int cmp =memcmp(name1, name2, min_len); 515if(cmp) 516return cmp; 517if(len1 < len2) 518return-1; 519if(len1 > len2) 520return1; 521return0; 522} 523 524intcache_name_stage_compare(const char*name1,int len1,int stage1,const char*name2,int len2,int stage2) 525{ 526int cmp; 527 528 cmp =name_compare(name1, len1, name2, len2); 529if(cmp) 530return cmp; 531 532if(stage1 < stage2) 533return-1; 534if(stage1 > stage2) 535return1; 536return0; 537} 538 539static intindex_name_stage_pos(const struct index_state *istate,const char*name,int namelen,int stage) 540{ 541int first, last; 542 543 first =0; 544 last = istate->cache_nr; 545while(last > first) { 546int next = (last + first) >>1; 547struct cache_entry *ce = istate->cache[next]; 548int cmp =cache_name_stage_compare(name, namelen, stage, ce->name,ce_namelen(ce),ce_stage(ce)); 549if(!cmp) 550return next; 551if(cmp <0) { 552 last = next; 553continue; 554} 555 first = next+1; 556} 557return-first-1; 558} 559 560intindex_name_pos(const struct index_state *istate,const char*name,int namelen) 561{ 562returnindex_name_stage_pos(istate, name, namelen,0); 563} 564 565intremove_index_entry_at(struct index_state *istate,int pos) 566{ 567struct cache_entry *ce = istate->cache[pos]; 568 569record_resolve_undo(istate, ce); 570remove_name_hash(istate, ce); 571save_or_free_index_entry(istate, ce); 572 istate->cache_changed |= CE_ENTRY_REMOVED; 573 istate->cache_nr--; 574if(pos >= istate->cache_nr) 575return0; 576MOVE_ARRAY(istate->cache + pos, istate->cache + pos +1, 577 istate->cache_nr - pos); 578return1; 579} 580 581/* 582 * Remove all cache entries marked for removal, that is where 583 * CE_REMOVE is set in ce_flags. This is much more effective than 584 * calling remove_index_entry_at() for each entry to be removed. 585 */ 586voidremove_marked_cache_entries(struct index_state *istate) 587{ 588struct cache_entry **ce_array = istate->cache; 589unsigned int i, j; 590 591for(i = j =0; i < istate->cache_nr; i++) { 592if(ce_array[i]->ce_flags & CE_REMOVE) { 593remove_name_hash(istate, ce_array[i]); 594save_or_free_index_entry(istate, ce_array[i]); 595} 596else 597 ce_array[j++] = ce_array[i]; 598} 599if(j == istate->cache_nr) 600return; 601 istate->cache_changed |= CE_ENTRY_REMOVED; 602 istate->cache_nr = j; 603} 604 605intremove_file_from_index(struct index_state *istate,const char*path) 606{ 607int pos =index_name_pos(istate, path,strlen(path)); 608if(pos <0) 609 pos = -pos-1; 610cache_tree_invalidate_path(istate, path); 611untracked_cache_remove_from_index(istate, path); 612while(pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path)) 613remove_index_entry_at(istate, pos); 614return0; 615} 616 617static intcompare_name(struct cache_entry *ce,const char*path,int namelen) 618{ 619return namelen !=ce_namelen(ce) ||memcmp(path, ce->name, namelen); 620} 621 622static intindex_name_pos_also_unmerged(struct index_state *istate, 623const char*path,int namelen) 624{ 625int pos =index_name_pos(istate, path, namelen); 626struct cache_entry *ce; 627 628if(pos >=0) 629return pos; 630 631/* maybe unmerged? */ 632 pos = -1- pos; 633if(pos >= istate->cache_nr || 634compare_name((ce = istate->cache[pos]), path, namelen)) 635return-1; 636 637/* order of preference: stage 2, 1, 3 */ 638if(ce_stage(ce) ==1&& pos +1< istate->cache_nr && 639ce_stage((ce = istate->cache[pos +1])) ==2&& 640!compare_name(ce, path, namelen)) 641 pos++; 642return pos; 643} 644 645static intdifferent_name(struct cache_entry *ce,struct cache_entry *alias) 646{ 647int len =ce_namelen(ce); 648returnce_namelen(alias) != len ||memcmp(ce->name, alias->name, len); 649} 650 651/* 652 * If we add a filename that aliases in the cache, we will use the 653 * name that we already have - but we don't want to update the same 654 * alias twice, because that implies that there were actually two 655 * different files with aliasing names! 656 * 657 * So we use the CE_ADDED flag to verify that the alias was an old 658 * one before we accept it as 659 */ 660static struct cache_entry *create_alias_ce(struct index_state *istate, 661struct cache_entry *ce, 662struct cache_entry *alias) 663{ 664int len; 665struct cache_entry *new_entry; 666 667if(alias->ce_flags & CE_ADDED) 668die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name); 669 670/* Ok, create the new entry using the name of the existing alias */ 671 len =ce_namelen(alias); 672 new_entry =make_empty_cache_entry(istate, len); 673memcpy(new_entry->name, alias->name, len); 674copy_cache_entry(new_entry, ce); 675save_or_free_index_entry(istate, ce); 676return new_entry; 677} 678 679voidset_object_name_for_intent_to_add_entry(struct cache_entry *ce) 680{ 681struct object_id oid; 682if(write_object_file("",0, blob_type, &oid)) 683die("cannot create an empty blob in the object database"); 684oidcpy(&ce->oid, &oid); 685} 686 687intadd_to_index(struct index_state *istate,const char*path,struct stat *st,int flags) 688{ 689int namelen, was_same; 690 mode_t st_mode = st->st_mode; 691struct cache_entry *ce, *alias = NULL; 692unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY; 693int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND); 694int pretend = flags & ADD_CACHE_PRETEND; 695int intent_only = flags & ADD_CACHE_INTENT; 696int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE| 697(intent_only ? ADD_CACHE_NEW_ONLY :0)); 698int newflags = HASH_WRITE_OBJECT; 699 700if(flags & HASH_RENORMALIZE) 701 newflags |= HASH_RENORMALIZE; 702 703if(!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode)) 704returnerror("%s: can only add regular files, symbolic links or git-directories", path); 705 706 namelen =strlen(path); 707if(S_ISDIR(st_mode)) { 708while(namelen && path[namelen-1] =='/') 709 namelen--; 710} 711 ce =make_empty_cache_entry(istate, namelen); 712memcpy(ce->name, path, namelen); 713 ce->ce_namelen = namelen; 714if(!intent_only) 715fill_stat_cache_info(ce, st); 716else 717 ce->ce_flags |= CE_INTENT_TO_ADD; 718 719 720if(trust_executable_bit && has_symlinks) { 721 ce->ce_mode =create_ce_mode(st_mode); 722}else{ 723/* If there is an existing entry, pick the mode bits and type 724 * from it, otherwise assume unexecutable regular file. 725 */ 726struct cache_entry *ent; 727int pos =index_name_pos_also_unmerged(istate, path, namelen); 728 729 ent = (0<= pos) ? istate->cache[pos] : NULL; 730 ce->ce_mode =ce_mode_from_stat(ent, st_mode); 731} 732 733/* When core.ignorecase=true, determine if a directory of the same name but differing 734 * case already exists within the Git repository. If it does, ensure the directory 735 * case of the file being added to the repository matches (is folded into) the existing 736 * entry's directory case. 737 */ 738if(ignore_case) { 739adjust_dirname_case(istate, ce->name); 740} 741if(!(flags & HASH_RENORMALIZE)) { 742 alias =index_file_exists(istate, ce->name, 743ce_namelen(ce), ignore_case); 744if(alias && 745!ce_stage(alias) && 746!ie_match_stat(istate, alias, st, ce_option)) { 747/* Nothing changed, really */ 748if(!S_ISGITLINK(alias->ce_mode)) 749ce_mark_uptodate(alias); 750 alias->ce_flags |= CE_ADDED; 751 752discard_cache_entry(ce); 753return0; 754} 755} 756if(!intent_only) { 757if(index_path(&ce->oid, path, st, newflags)) { 758discard_cache_entry(ce); 759returnerror("unable to index file%s", path); 760} 761}else 762set_object_name_for_intent_to_add_entry(ce); 763 764if(ignore_case && alias &&different_name(ce, alias)) 765 ce =create_alias_ce(istate, ce, alias); 766 ce->ce_flags |= CE_ADDED; 767 768/* It was suspected to be racily clean, but it turns out to be Ok */ 769 was_same = (alias && 770!ce_stage(alias) && 771!oidcmp(&alias->oid, &ce->oid) && 772 ce->ce_mode == alias->ce_mode); 773 774if(pretend) 775discard_cache_entry(ce); 776else if(add_index_entry(istate, ce, add_option)) { 777discard_cache_entry(ce); 778returnerror("unable to add%sto index", path); 779} 780if(verbose && !was_same) 781printf("add '%s'\n", path); 782return0; 783} 784 785intadd_file_to_index(struct index_state *istate,const char*path,int flags) 786{ 787struct stat st; 788if(lstat(path, &st)) 789die_errno("unable to stat '%s'", path); 790returnadd_to_index(istate, path, &st, flags); 791} 792 793struct cache_entry *make_empty_cache_entry(struct index_state *istate,size_t len) 794{ 795returnmem_pool__ce_calloc(find_mem_pool(istate), len); 796} 797 798struct cache_entry *make_empty_transient_cache_entry(size_t len) 799{ 800returnxcalloc(1,cache_entry_size(len)); 801} 802 803struct cache_entry *make_cache_entry(struct index_state *istate, 804unsigned int mode, 805const struct object_id *oid, 806const char*path, 807int stage, 808unsigned int refresh_options) 809{ 810struct cache_entry *ce, *ret; 811int len; 812 813if(!verify_path(path, mode)) { 814error("Invalid path '%s'", path); 815return NULL; 816} 817 818 len =strlen(path); 819 ce =make_empty_cache_entry(istate, len); 820 821oidcpy(&ce->oid, oid); 822memcpy(ce->name, path, len); 823 ce->ce_flags =create_ce_flags(stage); 824 ce->ce_namelen = len; 825 ce->ce_mode =create_ce_mode(mode); 826 827 ret =refresh_cache_entry(&the_index, ce, refresh_options); 828if(ret != ce) 829discard_cache_entry(ce); 830return ret; 831} 832 833struct cache_entry *make_transient_cache_entry(unsigned int mode,const struct object_id *oid, 834const char*path,int stage) 835{ 836struct cache_entry *ce; 837int len; 838 839if(!verify_path(path, mode)) { 840error("Invalid path '%s'", path); 841return NULL; 842} 843 844 len =strlen(path); 845 ce =make_empty_transient_cache_entry(len); 846 847oidcpy(&ce->oid, oid); 848memcpy(ce->name, path, len); 849 ce->ce_flags =create_ce_flags(stage); 850 ce->ce_namelen = len; 851 ce->ce_mode =create_ce_mode(mode); 852 853return ce; 854} 855 856/* 857 * Chmod an index entry with either +x or -x. 858 * 859 * Returns -1 if the chmod for the particular cache entry failed (if it's 860 * not a regular file), -2 if an invalid flip argument is passed in, 0 861 * otherwise. 862 */ 863intchmod_index_entry(struct index_state *istate,struct cache_entry *ce, 864char flip) 865{ 866if(!S_ISREG(ce->ce_mode)) 867return-1; 868switch(flip) { 869case'+': 870 ce->ce_mode |=0111; 871break; 872case'-': 873 ce->ce_mode &= ~0111; 874break; 875default: 876return-2; 877} 878cache_tree_invalidate_path(istate, ce->name); 879 ce->ce_flags |= CE_UPDATE_IN_BASE; 880mark_fsmonitor_invalid(istate, ce); 881 istate->cache_changed |= CE_ENTRY_CHANGED; 882 883return0; 884} 885 886intce_same_name(const struct cache_entry *a,const struct cache_entry *b) 887{ 888int len =ce_namelen(a); 889returnce_namelen(b) == len && !memcmp(a->name, b->name, len); 890} 891 892/* 893 * We fundamentally don't like some paths: we don't want 894 * dot or dot-dot anywhere, and for obvious reasons don't 895 * want to recurse into ".git" either. 896 * 897 * Also, we don't want double slashes or slashes at the 898 * end that can make pathnames ambiguous. 899 */ 900static intverify_dotfile(const char*rest,unsigned mode) 901{ 902/* 903 * The first character was '.', but that 904 * has already been discarded, we now test 905 * the rest. 906 */ 907 908/* "." is not allowed */ 909if(*rest =='\0'||is_dir_sep(*rest)) 910return0; 911 912switch(*rest) { 913/* 914 * ".git" followed by NUL or slash is bad. Note that we match 915 * case-insensitively here, even if ignore_case is not set. 916 * This outlaws ".GIT" everywhere out of an abundance of caution, 917 * since there's really no good reason to allow it. 918 * 919 * Once we've seen ".git", we can also find ".gitmodules", etc (also 920 * case-insensitively). 921 */ 922case'g': 923case'G': 924if(rest[1] !='i'&& rest[1] !='I') 925break; 926if(rest[2] !='t'&& rest[2] !='T') 927break; 928if(rest[3] =='\0'||is_dir_sep(rest[3])) 929return0; 930if(S_ISLNK(mode)) { 931 rest +=3; 932if(skip_iprefix(rest,"modules", &rest) && 933(*rest =='\0'||is_dir_sep(*rest))) 934return0; 935} 936break; 937case'.': 938if(rest[1] =='\0'||is_dir_sep(rest[1])) 939return0; 940} 941return1; 942} 943 944intverify_path(const char*path,unsigned mode) 945{ 946char c; 947 948if(has_dos_drive_prefix(path)) 949return0; 950 951goto inside; 952for(;;) { 953if(!c) 954return1; 955if(is_dir_sep(c)) { 956inside: 957if(protect_hfs) { 958if(is_hfs_dotgit(path)) 959return0; 960if(S_ISLNK(mode)) { 961if(is_hfs_dotgitmodules(path)) 962return0; 963} 964} 965if(protect_ntfs) { 966if(is_ntfs_dotgit(path)) 967return0; 968if(S_ISLNK(mode)) { 969if(is_ntfs_dotgitmodules(path)) 970return0; 971} 972} 973 974 c = *path++; 975if((c =='.'&& !verify_dotfile(path, mode)) || 976is_dir_sep(c) || c =='\0') 977return0; 978} 979 c = *path++; 980} 981} 982 983/* 984 * Do we have another file that has the beginning components being a 985 * proper superset of the name we're trying to add? 986 */ 987static inthas_file_name(struct index_state *istate, 988const struct cache_entry *ce,int pos,int ok_to_replace) 989{ 990int retval =0; 991int len =ce_namelen(ce); 992int stage =ce_stage(ce); 993const char*name = ce->name; 994 995while(pos < istate->cache_nr) { 996struct cache_entry *p = istate->cache[pos++]; 997 998if(len >=ce_namelen(p)) 999break;1000if(memcmp(name, p->name, len))1001break;1002if(ce_stage(p) != stage)1003continue;1004if(p->name[len] !='/')1005continue;1006if(p->ce_flags & CE_REMOVE)1007continue;1008 retval = -1;1009if(!ok_to_replace)1010break;1011remove_index_entry_at(istate, --pos);1012}1013return retval;1014}101510161017/*1018 * Like strcmp(), but also return the offset of the first change.1019 * If strings are equal, return the length.1020 */1021intstrcmp_offset(const char*s1,const char*s2,size_t*first_change)1022{1023size_t k;10241025if(!first_change)1026returnstrcmp(s1, s2);10271028for(k =0; s1[k] == s2[k]; k++)1029if(s1[k] =='\0')1030break;10311032*first_change = k;1033return(unsigned char)s1[k] - (unsigned char)s2[k];1034}10351036/*1037 * Do we have another file with a pathname that is a proper1038 * subset of the name we're trying to add?1039 *1040 * That is, is there another file in the index with a path1041 * that matches a sub-directory in the given entry?1042 */1043static inthas_dir_name(struct index_state *istate,1044const struct cache_entry *ce,int pos,int ok_to_replace)1045{1046int retval =0;1047int stage =ce_stage(ce);1048const char*name = ce->name;1049const char*slash = name +ce_namelen(ce);1050size_t len_eq_last;1051int cmp_last =0;10521053/*1054 * We are frequently called during an iteration on a sorted1055 * list of pathnames and while building a new index. Therefore,1056 * there is a high probability that this entry will eventually1057 * be appended to the index, rather than inserted in the middle.1058 * If we can confirm that, we can avoid binary searches on the1059 * components of the pathname.1060 *1061 * Compare the entry's full path with the last path in the index.1062 */1063if(istate->cache_nr >0) {1064 cmp_last =strcmp_offset(name,1065 istate->cache[istate->cache_nr -1]->name,1066&len_eq_last);1067if(cmp_last >0) {1068if(len_eq_last ==0) {1069/*1070 * The entry sorts AFTER the last one in the1071 * index and their paths have no common prefix,1072 * so there cannot be a F/D conflict.1073 */1074return retval;1075}else{1076/*1077 * The entry sorts AFTER the last one in the1078 * index, but has a common prefix. Fall through1079 * to the loop below to disect the entry's path1080 * and see where the difference is.1081 */1082}1083}else if(cmp_last ==0) {1084/*1085 * The entry exactly matches the last one in the1086 * index, but because of multiple stage and CE_REMOVE1087 * items, we fall through and let the regular search1088 * code handle it.1089 */1090}1091}10921093for(;;) {1094size_t len;10951096for(;;) {1097if(*--slash =='/')1098break;1099if(slash <= ce->name)1100return retval;1101}1102 len = slash - name;11031104if(cmp_last >0) {1105/*1106 * (len + 1) is a directory boundary (including1107 * the trailing slash). And since the loop is1108 * decrementing "slash", the first iteration is1109 * the longest directory prefix; subsequent1110 * iterations consider parent directories.1111 */11121113if(len +1<= len_eq_last) {1114/*1115 * The directory prefix (including the trailing1116 * slash) also appears as a prefix in the last1117 * entry, so the remainder cannot collide (because1118 * strcmp said the whole path was greater).1119 *1120 * EQ: last: xxx/A1121 * this: xxx/B1122 *1123 * LT: last: xxx/file_A1124 * this: xxx/file_B1125 */1126return retval;1127}11281129if(len > len_eq_last) {1130/*1131 * This part of the directory prefix (excluding1132 * the trailing slash) is longer than the known1133 * equal portions, so this sub-directory cannot1134 * collide with a file.1135 *1136 * GT: last: xxxA1137 * this: xxxB/file1138 */1139return retval;1140}11411142if(istate->cache_nr >0&&1143ce_namelen(istate->cache[istate->cache_nr -1]) > len) {1144/*1145 * The directory prefix lines up with part of1146 * a longer file or directory name, but sorts1147 * after it, so this sub-directory cannot1148 * collide with a file.1149 *1150 * last: xxx/yy-file (because '-' sorts before '/')1151 * this: xxx/yy/abc1152 */1153return retval;1154}11551156/*1157 * This is a possible collision. Fall through and1158 * let the regular search code handle it.1159 *1160 * last: xxx1161 * this: xxx/file1162 */1163}11641165 pos =index_name_stage_pos(istate, name, len, stage);1166if(pos >=0) {1167/*1168 * Found one, but not so fast. This could1169 * be a marker that says "I was here, but1170 * I am being removed". Such an entry is1171 * not a part of the resulting tree, and1172 * it is Ok to have a directory at the same1173 * path.1174 */1175if(!(istate->cache[pos]->ce_flags & CE_REMOVE)) {1176 retval = -1;1177if(!ok_to_replace)1178break;1179remove_index_entry_at(istate, pos);1180continue;1181}1182}1183else1184 pos = -pos-1;11851186/*1187 * Trivial optimization: if we find an entry that1188 * already matches the sub-directory, then we know1189 * we're ok, and we can exit.1190 */1191while(pos < istate->cache_nr) {1192struct cache_entry *p = istate->cache[pos];1193if((ce_namelen(p) <= len) ||1194(p->name[len] !='/') ||1195memcmp(p->name, name, len))1196break;/* not our subdirectory */1197if(ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))1198/*1199 * p is at the same stage as our entry, and1200 * is a subdirectory of what we are looking1201 * at, so we cannot have conflicts at our1202 * level or anything shorter.1203 */1204return retval;1205 pos++;1206}1207}1208return retval;1209}12101211/* We may be in a situation where we already have path/file and path1212 * is being added, or we already have path and path/file is being1213 * added. Either one would result in a nonsense tree that has path1214 * twice when git-write-tree tries to write it out. Prevent it.1215 *1216 * If ok-to-replace is specified, we remove the conflicting entries1217 * from the cache so the caller should recompute the insert position.1218 * When this happens, we return non-zero.1219 */1220static intcheck_file_directory_conflict(struct index_state *istate,1221const struct cache_entry *ce,1222int pos,int ok_to_replace)1223{1224int retval;12251226/*1227 * When ce is an "I am going away" entry, we allow it to be added1228 */1229if(ce->ce_flags & CE_REMOVE)1230return0;12311232/*1233 * We check if the path is a sub-path of a subsequent pathname1234 * first, since removing those will not change the position1235 * in the array.1236 */1237 retval =has_file_name(istate, ce, pos, ok_to_replace);12381239/*1240 * Then check if the path might have a clashing sub-directory1241 * before it.1242 */1243return retval +has_dir_name(istate, ce, pos, ok_to_replace);1244}12451246static intadd_index_entry_with_check(struct index_state *istate,struct cache_entry *ce,int option)1247{1248int pos;1249int ok_to_add = option & ADD_CACHE_OK_TO_ADD;1250int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;1251int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;1252int new_only = option & ADD_CACHE_NEW_ONLY;12531254if(!(option & ADD_CACHE_KEEP_CACHE_TREE))1255cache_tree_invalidate_path(istate, ce->name);12561257/*1258 * If this entry's path sorts after the last entry in the index,1259 * we can avoid searching for it.1260 */1261if(istate->cache_nr >0&&1262strcmp(ce->name, istate->cache[istate->cache_nr -1]->name) >0)1263 pos = -istate->cache_nr -1;1264else1265 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce));12661267/* existing match? Just replace it. */1268if(pos >=0) {1269if(!new_only)1270replace_index_entry(istate, pos, ce);1271return0;1272}1273 pos = -pos-1;12741275if(!(option & ADD_CACHE_KEEP_CACHE_TREE))1276untracked_cache_add_to_index(istate, ce->name);12771278/*1279 * Inserting a merged entry ("stage 0") into the index1280 * will always replace all non-merged entries..1281 */1282if(pos < istate->cache_nr &&ce_stage(ce) ==0) {1283while(ce_same_name(istate->cache[pos], ce)) {1284 ok_to_add =1;1285if(!remove_index_entry_at(istate, pos))1286break;1287}1288}12891290if(!ok_to_add)1291return-1;1292if(!verify_path(ce->name, ce->ce_mode))1293returnerror("Invalid path '%s'", ce->name);12941295if(!skip_df_check &&1296check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {1297if(!ok_to_replace)1298returnerror("'%s' appears as both a file and as a directory",1299 ce->name);1300 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce));1301 pos = -pos-1;1302}1303return pos +1;1304}13051306intadd_index_entry(struct index_state *istate,struct cache_entry *ce,int option)1307{1308int pos;13091310if(option & ADD_CACHE_JUST_APPEND)1311 pos = istate->cache_nr;1312else{1313int ret;1314 ret =add_index_entry_with_check(istate, ce, option);1315if(ret <=0)1316return ret;1317 pos = ret -1;1318}13191320/* Make sure the array is big enough .. */1321ALLOC_GROW(istate->cache, istate->cache_nr +1, istate->cache_alloc);13221323/* Add it in.. */1324 istate->cache_nr++;1325if(istate->cache_nr > pos +1)1326MOVE_ARRAY(istate->cache + pos +1, istate->cache + pos,1327 istate->cache_nr - pos -1);1328set_index_entry(istate, pos, ce);1329 istate->cache_changed |= CE_ENTRY_ADDED;1330return0;1331}13321333/*1334 * "refresh" does not calculate a new sha1 file or bring the1335 * cache up-to-date for mode/content changes. But what it1336 * _does_ do is to "re-match" the stat information of a file1337 * with the cache, so that you can refresh the cache for a1338 * file that hasn't been changed but where the stat entry is1339 * out of date.1340 *1341 * For example, you'd want to do this after doing a "git-read-tree",1342 * to link up the stat cache details with the proper files.1343 */1344static struct cache_entry *refresh_cache_ent(struct index_state *istate,1345struct cache_entry *ce,1346unsigned int options,int*err,1347int*changed_ret)1348{1349struct stat st;1350struct cache_entry *updated;1351int changed;1352int refresh = options & CE_MATCH_REFRESH;1353int ignore_valid = options & CE_MATCH_IGNORE_VALID;1354int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;1355int ignore_missing = options & CE_MATCH_IGNORE_MISSING;1356int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;13571358if(!refresh ||ce_uptodate(ce))1359return ce;13601361if(!ignore_fsmonitor)1362refresh_fsmonitor(istate);1363/*1364 * CE_VALID or CE_SKIP_WORKTREE means the user promised us1365 * that the change to the work tree does not matter and told1366 * us not to worry.1367 */1368if(!ignore_skip_worktree &&ce_skip_worktree(ce)) {1369ce_mark_uptodate(ce);1370return ce;1371}1372if(!ignore_valid && (ce->ce_flags & CE_VALID)) {1373ce_mark_uptodate(ce);1374return ce;1375}1376if(!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {1377ce_mark_uptodate(ce);1378return ce;1379}13801381if(has_symlink_leading_path(ce->name,ce_namelen(ce))) {1382if(ignore_missing)1383return ce;1384if(err)1385*err = ENOENT;1386return NULL;1387}13881389if(lstat(ce->name, &st) <0) {1390if(ignore_missing && errno == ENOENT)1391return ce;1392if(err)1393*err = errno;1394return NULL;1395}13961397 changed =ie_match_stat(istate, ce, &st, options);1398if(changed_ret)1399*changed_ret = changed;1400if(!changed) {1401/*1402 * The path is unchanged. If we were told to ignore1403 * valid bit, then we did the actual stat check and1404 * found that the entry is unmodified. If the entry1405 * is not marked VALID, this is the place to mark it1406 * valid again, under "assume unchanged" mode.1407 */1408if(ignore_valid && assume_unchanged &&1409!(ce->ce_flags & CE_VALID))1410;/* mark this one VALID again */1411else{1412/*1413 * We do not mark the index itself "modified"1414 * because CE_UPTODATE flag is in-core only;1415 * we are not going to write this change out.1416 */1417if(!S_ISGITLINK(ce->ce_mode)) {1418ce_mark_uptodate(ce);1419mark_fsmonitor_valid(ce);1420}1421return ce;1422}1423}14241425if(ie_modified(istate, ce, &st, options)) {1426if(err)1427*err = EINVAL;1428return NULL;1429}14301431 updated =make_empty_cache_entry(istate,ce_namelen(ce));1432copy_cache_entry(updated, ce);1433memcpy(updated->name, ce->name, ce->ce_namelen +1);1434fill_stat_cache_info(updated, &st);1435/*1436 * If ignore_valid is not set, we should leave CE_VALID bit1437 * alone. Otherwise, paths marked with --no-assume-unchanged1438 * (i.e. things to be edited) will reacquire CE_VALID bit1439 * automatically, which is not really what we want.1440 */1441if(!ignore_valid && assume_unchanged &&1442!(ce->ce_flags & CE_VALID))1443 updated->ce_flags &= ~CE_VALID;14441445/* istate->cache_changed is updated in the caller */1446return updated;1447}14481449static voidshow_file(const char* fmt,const char* name,int in_porcelain,1450int* first,const char*header_msg)1451{1452if(in_porcelain && *first && header_msg) {1453printf("%s\n", header_msg);1454*first =0;1455}1456printf(fmt, name);1457}14581459intrefresh_index(struct index_state *istate,unsigned int flags,1460const struct pathspec *pathspec,1461char*seen,const char*header_msg)1462{1463int i;1464int has_errors =0;1465int really = (flags & REFRESH_REALLY) !=0;1466int allow_unmerged = (flags & REFRESH_UNMERGED) !=0;1467int quiet = (flags & REFRESH_QUIET) !=0;1468int not_new = (flags & REFRESH_IGNORE_MISSING) !=0;1469int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) !=0;1470int first =1;1471int in_porcelain = (flags & REFRESH_IN_PORCELAIN);1472unsigned int options = (CE_MATCH_REFRESH |1473(really ? CE_MATCH_IGNORE_VALID :0) |1474(not_new ? CE_MATCH_IGNORE_MISSING :0));1475const char*modified_fmt;1476const char*deleted_fmt;1477const char*typechange_fmt;1478const char*added_fmt;1479const char*unmerged_fmt;1480uint64_t start =getnanotime();1481struct progress *progress = NULL;14821483if(flags & REFRESH_PROGRESS &&isatty(2))1484 progress =start_delayed_progress(_("Refresh index"),1485 istate->cache_nr);14861487 modified_fmt = (in_porcelain ?"M\t%s\n":"%s: needs update\n");1488 deleted_fmt = (in_porcelain ?"D\t%s\n":"%s: needs update\n");1489 typechange_fmt = (in_porcelain ?"T\t%s\n":"%sneeds update\n");1490 added_fmt = (in_porcelain ?"A\t%s\n":"%sneeds update\n");1491 unmerged_fmt = (in_porcelain ?"U\t%s\n":"%s: needs merge\n");1492for(i =0; i < istate->cache_nr; i++) {1493struct cache_entry *ce, *new_entry;1494int cache_errno =0;1495int changed =0;1496int filtered =0;14971498 ce = istate->cache[i];1499if(ignore_submodules &&S_ISGITLINK(ce->ce_mode))1500continue;15011502if(pathspec && !ce_path_match(&the_index, ce, pathspec, seen))1503 filtered =1;15041505if(ce_stage(ce)) {1506while((i < istate->cache_nr) &&1507!strcmp(istate->cache[i]->name, ce->name))1508 i++;1509 i--;1510if(allow_unmerged)1511continue;1512if(!filtered)1513show_file(unmerged_fmt, ce->name, in_porcelain,1514&first, header_msg);1515 has_errors =1;1516continue;1517}15181519if(filtered)1520continue;15211522 new_entry =refresh_cache_ent(istate, ce, options, &cache_errno, &changed);1523if(new_entry == ce)1524continue;1525if(progress)1526display_progress(progress, i);1527if(!new_entry) {1528const char*fmt;15291530if(really && cache_errno == EINVAL) {1531/* If we are doing --really-refresh that1532 * means the index is not valid anymore.1533 */1534 ce->ce_flags &= ~CE_VALID;1535 ce->ce_flags |= CE_UPDATE_IN_BASE;1536mark_fsmonitor_invalid(istate, ce);1537 istate->cache_changed |= CE_ENTRY_CHANGED;1538}1539if(quiet)1540continue;15411542if(cache_errno == ENOENT)1543 fmt = deleted_fmt;1544else if(ce_intent_to_add(ce))1545 fmt = added_fmt;/* must be before other checks */1546else if(changed & TYPE_CHANGED)1547 fmt = typechange_fmt;1548else1549 fmt = modified_fmt;1550show_file(fmt,1551 ce->name, in_porcelain, &first, header_msg);1552 has_errors =1;1553continue;1554}15551556replace_index_entry(istate, i, new_entry);1557}1558if(progress) {1559display_progress(progress, istate->cache_nr);1560stop_progress(&progress);1561}1562trace_performance_since(start,"refresh index");1563return has_errors;1564}15651566struct cache_entry *refresh_cache_entry(struct index_state *istate,1567struct cache_entry *ce,1568unsigned int options)1569{1570returnrefresh_cache_ent(istate, ce, options, NULL, NULL);1571}157215731574/*****************************************************************1575 * Index File I/O1576 *****************************************************************/15771578#define INDEX_FORMAT_DEFAULT 315791580static unsigned intget_index_format_default(void)1581{1582char*envversion =getenv("GIT_INDEX_VERSION");1583char*endp;1584int value;1585unsigned int version = INDEX_FORMAT_DEFAULT;15861587if(!envversion) {1588if(!git_config_get_int("index.version", &value))1589 version = value;1590if(version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1591warning(_("index.version set, but the value is invalid.\n"1592"Using version%i"), INDEX_FORMAT_DEFAULT);1593return INDEX_FORMAT_DEFAULT;1594}1595return version;1596}15971598 version =strtoul(envversion, &endp,10);1599if(*endp ||1600 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1601warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"1602"Using version%i"), INDEX_FORMAT_DEFAULT);1603 version = INDEX_FORMAT_DEFAULT;1604}1605return version;1606}16071608/*1609 * dev/ino/uid/gid/size are also just tracked to the low 32 bits1610 * Again - this is just a (very strong in practice) heuristic that1611 * the inode hasn't changed.1612 *1613 * We save the fields in big-endian order to allow using the1614 * index file over NFS transparently.1615 */1616struct ondisk_cache_entry {1617struct cache_time ctime;1618struct cache_time mtime;1619uint32_t dev;1620uint32_t ino;1621uint32_t mode;1622uint32_t uid;1623uint32_t gid;1624uint32_t size;1625unsigned char sha1[20];1626uint16_t flags;1627char name[FLEX_ARRAY];/* more */1628};16291630/*1631 * This struct is used when CE_EXTENDED bit is 11632 * The struct must match ondisk_cache_entry exactly from1633 * ctime till flags1634 */1635struct ondisk_cache_entry_extended {1636struct cache_time ctime;1637struct cache_time mtime;1638uint32_t dev;1639uint32_t ino;1640uint32_t mode;1641uint32_t uid;1642uint32_t gid;1643uint32_t size;1644unsigned char sha1[20];1645uint16_t flags;1646uint16_t flags2;1647char name[FLEX_ARRAY];/* more */1648};16491650/* These are only used for v3 or lower */1651#define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)1652#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)1653#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)1654#define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)1655#define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \1656 ondisk_cache_entry_extended_size(ce_namelen(ce)) : \1657 ondisk_cache_entry_size(ce_namelen(ce)))16581659/* Allow fsck to force verification of the index checksum. */1660int verify_index_checksum;16611662/* Allow fsck to force verification of the cache entry order. */1663int verify_ce_order;16641665static intverify_hdr(struct cache_header *hdr,unsigned long size)1666{1667 git_hash_ctx c;1668unsigned char hash[GIT_MAX_RAWSZ];1669int hdr_version;16701671if(hdr->hdr_signature !=htonl(CACHE_SIGNATURE))1672returnerror("bad signature");1673 hdr_version =ntohl(hdr->hdr_version);1674if(hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)1675returnerror("bad index version%d", hdr_version);16761677if(!verify_index_checksum)1678return0;16791680 the_hash_algo->init_fn(&c);1681 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);1682 the_hash_algo->final_fn(hash, &c);1683if(hashcmp(hash, (unsigned char*)hdr + size - the_hash_algo->rawsz))1684returnerror("bad index file sha1 signature");1685return0;1686}16871688static intread_index_extension(struct index_state *istate,1689const char*ext,void*data,unsigned long sz)1690{1691switch(CACHE_EXT(ext)) {1692case CACHE_EXT_TREE:1693 istate->cache_tree =cache_tree_read(data, sz);1694break;1695case CACHE_EXT_RESOLVE_UNDO:1696 istate->resolve_undo =resolve_undo_read(data, sz);1697break;1698case CACHE_EXT_LINK:1699if(read_link_extension(istate, data, sz))1700return-1;1701break;1702case CACHE_EXT_UNTRACKED:1703 istate->untracked =read_untracked_extension(data, sz);1704break;1705case CACHE_EXT_FSMONITOR:1706read_fsmonitor_extension(istate, data, sz);1707break;1708default:1709if(*ext <'A'||'Z'< *ext)1710returnerror("index uses %.4s extension, which we do not understand",1711 ext);1712fprintf(stderr,"ignoring %.4s extension\n", ext);1713break;1714}1715return0;1716}17171718inthold_locked_index(struct lock_file *lk,int lock_flags)1719{1720returnhold_lock_file_for_update(lk,get_index_file(), lock_flags);1721}17221723intread_index(struct index_state *istate)1724{1725returnread_index_from(istate,get_index_file(),get_git_dir());1726}17271728static struct cache_entry *cache_entry_from_ondisk(struct mem_pool *mem_pool,1729struct ondisk_cache_entry *ondisk,1730unsigned int flags,1731const char*name,1732size_t len)1733{1734struct cache_entry *ce =mem_pool__ce_alloc(mem_pool, len);17351736 ce->ce_stat_data.sd_ctime.sec =get_be32(&ondisk->ctime.sec);1737 ce->ce_stat_data.sd_mtime.sec =get_be32(&ondisk->mtime.sec);1738 ce->ce_stat_data.sd_ctime.nsec =get_be32(&ondisk->ctime.nsec);1739 ce->ce_stat_data.sd_mtime.nsec =get_be32(&ondisk->mtime.nsec);1740 ce->ce_stat_data.sd_dev =get_be32(&ondisk->dev);1741 ce->ce_stat_data.sd_ino =get_be32(&ondisk->ino);1742 ce->ce_mode =get_be32(&ondisk->mode);1743 ce->ce_stat_data.sd_uid =get_be32(&ondisk->uid);1744 ce->ce_stat_data.sd_gid =get_be32(&ondisk->gid);1745 ce->ce_stat_data.sd_size =get_be32(&ondisk->size);1746 ce->ce_flags = flags & ~CE_NAMEMASK;1747 ce->ce_namelen = len;1748 ce->index =0;1749hashcpy(ce->oid.hash, ondisk->sha1);1750memcpy(ce->name, name, len);1751 ce->name[len] ='\0';1752return ce;1753}17541755/*1756 * Adjacent cache entries tend to share the leading paths, so it makes1757 * sense to only store the differences in later entries. In the v41758 * on-disk format of the index, each on-disk cache entry stores the1759 * number of bytes to be stripped from the end of the previous name,1760 * and the bytes to append to the result, to come up with its name.1761 */1762static unsigned longexpand_name_field(struct strbuf *name,const char*cp_)1763{1764const unsigned char*ep, *cp = (const unsigned char*)cp_;1765size_t len =decode_varint(&cp);17661767if(name->len < len)1768die("malformed name field in the index");1769strbuf_remove(name, name->len - len, len);1770for(ep = cp; *ep; ep++)1771;/* find the end */1772strbuf_add(name, cp, ep - cp);1773return(const char*)ep +1- cp_;1774}17751776static struct cache_entry *create_from_disk(struct mem_pool *mem_pool,1777struct ondisk_cache_entry *ondisk,1778unsigned long*ent_size,1779struct strbuf *previous_name)1780{1781struct cache_entry *ce;1782size_t len;1783const char*name;1784unsigned int flags;17851786/* On-disk flags are just 16 bits */1787 flags =get_be16(&ondisk->flags);1788 len = flags & CE_NAMEMASK;17891790if(flags & CE_EXTENDED) {1791struct ondisk_cache_entry_extended *ondisk2;1792int extended_flags;1793 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;1794 extended_flags =get_be16(&ondisk2->flags2) <<16;1795/* We do not yet understand any bit out of CE_EXTENDED_FLAGS */1796if(extended_flags & ~CE_EXTENDED_FLAGS)1797die("Unknown index entry format%08x", extended_flags);1798 flags |= extended_flags;1799 name = ondisk2->name;1800}1801else1802 name = ondisk->name;18031804if(!previous_name) {1805/* v3 and earlier */1806if(len == CE_NAMEMASK)1807 len =strlen(name);1808 ce =cache_entry_from_ondisk(mem_pool, ondisk, flags, name, len);18091810*ent_size =ondisk_ce_size(ce);1811}else{1812unsigned long consumed;1813 consumed =expand_name_field(previous_name, name);1814 ce =cache_entry_from_ondisk(mem_pool, ondisk, flags,1815 previous_name->buf,1816 previous_name->len);18171818*ent_size = (name - ((char*)ondisk)) + consumed;1819}1820return ce;1821}18221823static voidcheck_ce_order(struct index_state *istate)1824{1825unsigned int i;18261827if(!verify_ce_order)1828return;18291830for(i =1; i < istate->cache_nr; i++) {1831struct cache_entry *ce = istate->cache[i -1];1832struct cache_entry *next_ce = istate->cache[i];1833int name_compare =strcmp(ce->name, next_ce->name);18341835if(0< name_compare)1836die("unordered stage entries in index");1837if(!name_compare) {1838if(!ce_stage(ce))1839die("multiple stage entries for merged file '%s'",1840 ce->name);1841if(ce_stage(ce) >ce_stage(next_ce))1842die("unordered stage entries for '%s'",1843 ce->name);1844}1845}1846}18471848static voidtweak_untracked_cache(struct index_state *istate)1849{1850switch(git_config_get_untracked_cache()) {1851case-1:/* keep: do nothing */1852break;1853case0:/* false */1854remove_untracked_cache(istate);1855break;1856case1:/* true */1857add_untracked_cache(istate);1858break;1859default:/* unknown value: do nothing */1860break;1861}1862}18631864static voidtweak_split_index(struct index_state *istate)1865{1866switch(git_config_get_split_index()) {1867case-1:/* unset: do nothing */1868break;1869case0:/* false */1870remove_split_index(istate);1871break;1872case1:/* true */1873add_split_index(istate);1874break;1875default:/* unknown value: do nothing */1876break;1877}1878}18791880static voidpost_read_index_from(struct index_state *istate)1881{1882check_ce_order(istate);1883tweak_untracked_cache(istate);1884tweak_split_index(istate);1885tweak_fsmonitor(istate);1886}18871888static size_testimate_cache_size_from_compressed(unsigned int entries)1889{1890return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);1891}18921893static size_testimate_cache_size(size_t ondisk_size,unsigned int entries)1894{1895long per_entry =sizeof(struct cache_entry) -sizeof(struct ondisk_cache_entry);18961897/*1898 * Account for potential alignment differences.1899 */1900 per_entry +=align_padding_size(sizeof(struct cache_entry), -sizeof(struct ondisk_cache_entry));1901return ondisk_size + entries * per_entry;1902}19031904/* remember to discard_cache() before reading a different cache! */1905intdo_read_index(struct index_state *istate,const char*path,int must_exist)1906{1907int fd, i;1908struct stat st;1909unsigned long src_offset;1910struct cache_header *hdr;1911void*mmap;1912size_t mmap_size;1913struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;19141915if(istate->initialized)1916return istate->cache_nr;19171918 istate->timestamp.sec =0;1919 istate->timestamp.nsec =0;1920 fd =open(path, O_RDONLY);1921if(fd <0) {1922if(!must_exist && errno == ENOENT)1923return0;1924die_errno("%s: index file open failed", path);1925}19261927if(fstat(fd, &st))1928die_errno("cannot stat the open index");19291930 mmap_size =xsize_t(st.st_size);1931if(mmap_size <sizeof(struct cache_header) + the_hash_algo->rawsz)1932die("index file smaller than expected");19331934 mmap =xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd,0);1935if(mmap == MAP_FAILED)1936die_errno("unable to map index file");1937close(fd);19381939 hdr = mmap;1940if(verify_hdr(hdr, mmap_size) <0)1941goto unmap;19421943hashcpy(istate->oid.hash, (const unsigned char*)hdr + mmap_size - the_hash_algo->rawsz);1944 istate->version =ntohl(hdr->hdr_version);1945 istate->cache_nr =ntohl(hdr->hdr_entries);1946 istate->cache_alloc =alloc_nr(istate->cache_nr);1947 istate->cache =xcalloc(istate->cache_alloc,sizeof(*istate->cache));1948 istate->initialized =1;19491950if(istate->version ==4) {1951 previous_name = &previous_name_buf;1952mem_pool_init(&istate->ce_mem_pool,1953estimate_cache_size_from_compressed(istate->cache_nr));1954}else{1955 previous_name = NULL;1956mem_pool_init(&istate->ce_mem_pool,1957estimate_cache_size(mmap_size, istate->cache_nr));1958}19591960 src_offset =sizeof(*hdr);1961for(i =0; i < istate->cache_nr; i++) {1962struct ondisk_cache_entry *disk_ce;1963struct cache_entry *ce;1964unsigned long consumed;19651966 disk_ce = (struct ondisk_cache_entry *)((char*)mmap + src_offset);1967 ce =create_from_disk(istate->ce_mem_pool, disk_ce, &consumed, previous_name);1968set_index_entry(istate, i, ce);19691970 src_offset += consumed;1971}1972strbuf_release(&previous_name_buf);1973 istate->timestamp.sec = st.st_mtime;1974 istate->timestamp.nsec =ST_MTIME_NSEC(st);19751976while(src_offset <= mmap_size - the_hash_algo->rawsz -8) {1977/* After an array of active_nr index entries,1978 * there can be arbitrary number of extended1979 * sections, each of which is prefixed with1980 * extension name (4-byte) and section length1981 * in 4-byte network byte order.1982 */1983uint32_t extsize;1984memcpy(&extsize, (char*)mmap + src_offset +4,4);1985 extsize =ntohl(extsize);1986if(read_index_extension(istate,1987(const char*) mmap + src_offset,1988(char*) mmap + src_offset +8,1989 extsize) <0)1990goto unmap;1991 src_offset +=8;1992 src_offset += extsize;1993}1994munmap(mmap, mmap_size);1995return istate->cache_nr;19961997unmap:1998munmap(mmap, mmap_size);1999die("index file corrupt");2000}20012002/*2003 * Signal that the shared index is used by updating its mtime.2004 *2005 * This way, shared index can be removed if they have not been used2006 * for some time.2007 */2008static voidfreshen_shared_index(const char*shared_index,int warn)2009{2010if(!check_and_freshen_file(shared_index,1) && warn)2011warning("could not freshen shared index '%s'", shared_index);2012}20132014intread_index_from(struct index_state *istate,const char*path,2015const char*gitdir)2016{2017uint64_t start =getnanotime();2018struct split_index *split_index;2019int ret;2020char*base_oid_hex;2021char*base_path;20222023/* istate->initialized covers both .git/index and .git/sharedindex.xxx */2024if(istate->initialized)2025return istate->cache_nr;20262027 ret =do_read_index(istate, path,0);2028trace_performance_since(start,"read cache%s", path);20292030 split_index = istate->split_index;2031if(!split_index ||is_null_oid(&split_index->base_oid)) {2032post_read_index_from(istate);2033return ret;2034}20352036if(split_index->base)2037discard_index(split_index->base);2038else2039 split_index->base =xcalloc(1,sizeof(*split_index->base));20402041 base_oid_hex =oid_to_hex(&split_index->base_oid);2042 base_path =xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);2043 ret =do_read_index(split_index->base, base_path,1);2044if(oidcmp(&split_index->base_oid, &split_index->base->oid))2045die("broken index, expect%sin%s, got%s",2046 base_oid_hex, base_path,2047oid_to_hex(&split_index->base->oid));20482049freshen_shared_index(base_path,0);2050merge_base_index(istate);2051post_read_index_from(istate);2052trace_performance_since(start,"read cache%s", base_path);2053free(base_path);2054return ret;2055}20562057intis_index_unborn(struct index_state *istate)2058{2059return(!istate->cache_nr && !istate->timestamp.sec);2060}20612062intdiscard_index(struct index_state *istate)2063{2064/*2065 * Cache entries in istate->cache[] should have been allocated2066 * from the memory pool associated with this index, or from an2067 * associated split_index. There is no need to free individual2068 * cache entries. validate_cache_entries can detect when this2069 * assertion does not hold.2070 */2071validate_cache_entries(istate);20722073resolve_undo_clear_index(istate);2074 istate->cache_nr =0;2075 istate->cache_changed =0;2076 istate->timestamp.sec =0;2077 istate->timestamp.nsec =0;2078free_name_hash(istate);2079cache_tree_free(&(istate->cache_tree));2080 istate->initialized =0;2081FREE_AND_NULL(istate->cache);2082 istate->cache_alloc =0;2083discard_split_index(istate);2084free_untracked_cache(istate->untracked);2085 istate->untracked = NULL;20862087if(istate->ce_mem_pool) {2088mem_pool_discard(istate->ce_mem_pool,should_validate_cache_entries());2089 istate->ce_mem_pool = NULL;2090}20912092return0;2093}20942095/*2096 * Validate the cache entries of this index.2097 * All cache entries associated with this index2098 * should have been allocated by the memory pool2099 * associated with this index, or by a referenced2100 * split index.2101 */2102voidvalidate_cache_entries(const struct index_state *istate)2103{2104int i;21052106if(!should_validate_cache_entries() ||!istate || !istate->initialized)2107return;21082109for(i =0; i < istate->cache_nr; i++) {2110if(!istate) {2111die("internal error: cache entry is not allocated from expected memory pool");2112}else if(!istate->ce_mem_pool ||2113!mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {2114if(!istate->split_index ||2115!istate->split_index->base ||2116!istate->split_index->base->ce_mem_pool ||2117!mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {2118die("internal error: cache entry is not allocated from expected memory pool");2119}2120}2121}21222123if(istate->split_index)2124validate_cache_entries(istate->split_index->base);2125}21262127intunmerged_index(const struct index_state *istate)2128{2129int i;2130for(i =0; i < istate->cache_nr; i++) {2131if(ce_stage(istate->cache[i]))2132return1;2133}2134return0;2135}21362137intindex_has_changes(const struct index_state *istate,2138struct tree *tree,2139struct strbuf *sb)2140{2141struct object_id cmp;2142int i;21432144if(istate != &the_index) {2145BUG("index_has_changes cannot yet accept istate != &the_index; do_diff_cache needs updating first.");2146}2147if(tree)2148 cmp = tree->object.oid;2149if(tree || !get_oid_tree("HEAD", &cmp)) {2150struct diff_options opt;21512152diff_setup(&opt);2153 opt.flags.exit_with_status =1;2154if(!sb)2155 opt.flags.quick =1;2156do_diff_cache(&cmp, &opt);2157diffcore_std(&opt);2158for(i =0; sb && i < diff_queued_diff.nr; i++) {2159if(i)2160strbuf_addch(sb,' ');2161strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);2162}2163diff_flush(&opt);2164return opt.flags.has_changes !=0;2165}else{2166for(i =0; sb && i < istate->cache_nr; i++) {2167if(i)2168strbuf_addch(sb,' ');2169strbuf_addstr(sb, istate->cache[i]->name);2170}2171return!!istate->cache_nr;2172}2173}21742175#define WRITE_BUFFER_SIZE 81922176static unsigned char write_buffer[WRITE_BUFFER_SIZE];2177static unsigned long write_buffer_len;21782179static intce_write_flush(git_hash_ctx *context,int fd)2180{2181unsigned int buffered = write_buffer_len;2182if(buffered) {2183 the_hash_algo->update_fn(context, write_buffer, buffered);2184if(write_in_full(fd, write_buffer, buffered) <0)2185return-1;2186 write_buffer_len =0;2187}2188return0;2189}21902191static intce_write(git_hash_ctx *context,int fd,void*data,unsigned int len)2192{2193while(len) {2194unsigned int buffered = write_buffer_len;2195unsigned int partial = WRITE_BUFFER_SIZE - buffered;2196if(partial > len)2197 partial = len;2198memcpy(write_buffer + buffered, data, partial);2199 buffered += partial;2200if(buffered == WRITE_BUFFER_SIZE) {2201 write_buffer_len = buffered;2202if(ce_write_flush(context, fd))2203return-1;2204 buffered =0;2205}2206 write_buffer_len = buffered;2207 len -= partial;2208 data = (char*) data + partial;2209}2210return0;2211}22122213static intwrite_index_ext_header(git_hash_ctx *context,int fd,2214unsigned int ext,unsigned int sz)2215{2216 ext =htonl(ext);2217 sz =htonl(sz);2218return((ce_write(context, fd, &ext,4) <0) ||2219(ce_write(context, fd, &sz,4) <0)) ? -1:0;2220}22212222static intce_flush(git_hash_ctx *context,int fd,unsigned char*hash)2223{2224unsigned int left = write_buffer_len;22252226if(left) {2227 write_buffer_len =0;2228 the_hash_algo->update_fn(context, write_buffer, left);2229}22302231/* Flush first if not enough space for hash signature */2232if(left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {2233if(write_in_full(fd, write_buffer, left) <0)2234return-1;2235 left =0;2236}22372238/* Append the hash signature at the end */2239 the_hash_algo->final_fn(write_buffer + left, context);2240hashcpy(hash, write_buffer + left);2241 left += the_hash_algo->rawsz;2242return(write_in_full(fd, write_buffer, left) <0) ? -1:0;2243}22442245static voidce_smudge_racily_clean_entry(struct cache_entry *ce)2246{2247/*2248 * The only thing we care about in this function is to smudge the2249 * falsely clean entry due to touch-update-touch race, so we leave2250 * everything else as they are. We are called for entries whose2251 * ce_stat_data.sd_mtime match the index file mtime.2252 *2253 * Note that this actually does not do much for gitlinks, for2254 * which ce_match_stat_basic() always goes to the actual2255 * contents. The caller checks with is_racy_timestamp() which2256 * always says "no" for gitlinks, so we are not called for them ;-)2257 */2258struct stat st;22592260if(lstat(ce->name, &st) <0)2261return;2262if(ce_match_stat_basic(ce, &st))2263return;2264if(ce_modified_check_fs(ce, &st)) {2265/* This is "racily clean"; smudge it. Note that this2266 * is a tricky code. At first glance, it may appear2267 * that it can break with this sequence:2268 *2269 * $ echo xyzzy >frotz2270 * $ git-update-index --add frotz2271 * $ : >frotz2272 * $ sleep 32273 * $ echo filfre >nitfol2274 * $ git-update-index --add nitfol2275 *2276 * but it does not. When the second update-index runs,2277 * it notices that the entry "frotz" has the same timestamp2278 * as index, and if we were to smudge it by resetting its2279 * size to zero here, then the object name recorded2280 * in index is the 6-byte file but the cached stat information2281 * becomes zero --- which would then match what we would2282 * obtain from the filesystem next time we stat("frotz").2283 *2284 * However, the second update-index, before calling2285 * this function, notices that the cached size is 62286 * bytes and what is on the filesystem is an empty2287 * file, and never calls us, so the cached size information2288 * for "frotz" stays 6 which does not match the filesystem.2289 */2290 ce->ce_stat_data.sd_size =0;2291}2292}22932294/* Copy miscellaneous fields but not the name */2295static voidcopy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,2296struct cache_entry *ce)2297{2298short flags;22992300 ondisk->ctime.sec =htonl(ce->ce_stat_data.sd_ctime.sec);2301 ondisk->mtime.sec =htonl(ce->ce_stat_data.sd_mtime.sec);2302 ondisk->ctime.nsec =htonl(ce->ce_stat_data.sd_ctime.nsec);2303 ondisk->mtime.nsec =htonl(ce->ce_stat_data.sd_mtime.nsec);2304 ondisk->dev =htonl(ce->ce_stat_data.sd_dev);2305 ondisk->ino =htonl(ce->ce_stat_data.sd_ino);2306 ondisk->mode =htonl(ce->ce_mode);2307 ondisk->uid =htonl(ce->ce_stat_data.sd_uid);2308 ondisk->gid =htonl(ce->ce_stat_data.sd_gid);2309 ondisk->size =htonl(ce->ce_stat_data.sd_size);2310hashcpy(ondisk->sha1, ce->oid.hash);23112312 flags = ce->ce_flags & ~CE_NAMEMASK;2313 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK :ce_namelen(ce));2314 ondisk->flags =htons(flags);2315if(ce->ce_flags & CE_EXTENDED) {2316struct ondisk_cache_entry_extended *ondisk2;2317 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;2318 ondisk2->flags2 =htons((ce->ce_flags & CE_EXTENDED_FLAGS) >>16);2319}2320}23212322static intce_write_entry(git_hash_ctx *c,int fd,struct cache_entry *ce,2323struct strbuf *previous_name,struct ondisk_cache_entry *ondisk)2324{2325int size;2326int result;2327unsigned int saved_namelen;2328int stripped_name =0;2329static unsigned char padding[8] = {0x00};23302331if(ce->ce_flags & CE_STRIP_NAME) {2332 saved_namelen =ce_namelen(ce);2333 ce->ce_namelen =0;2334 stripped_name =1;2335}23362337if(ce->ce_flags & CE_EXTENDED)2338 size =offsetof(struct ondisk_cache_entry_extended, name);2339else2340 size =offsetof(struct ondisk_cache_entry, name);23412342if(!previous_name) {2343int len =ce_namelen(ce);2344copy_cache_entry_to_ondisk(ondisk, ce);2345 result =ce_write(c, fd, ondisk, size);2346if(!result)2347 result =ce_write(c, fd, ce->name, len);2348if(!result)2349 result =ce_write(c, fd, padding,align_padding_size(size, len));2350}else{2351int common, to_remove, prefix_size;2352unsigned char to_remove_vi[16];2353for(common =0;2354(ce->name[common] &&2355 common < previous_name->len &&2356 ce->name[common] == previous_name->buf[common]);2357 common++)2358;/* still matching */2359 to_remove = previous_name->len - common;2360 prefix_size =encode_varint(to_remove, to_remove_vi);23612362copy_cache_entry_to_ondisk(ondisk, ce);2363 result =ce_write(c, fd, ondisk, size);2364if(!result)2365 result =ce_write(c, fd, to_remove_vi, prefix_size);2366if(!result)2367 result =ce_write(c, fd, ce->name + common,ce_namelen(ce) - common);2368if(!result)2369 result =ce_write(c, fd, padding,1);23702371strbuf_splice(previous_name, common, to_remove,2372 ce->name + common,ce_namelen(ce) - common);2373}2374if(stripped_name) {2375 ce->ce_namelen = saved_namelen;2376 ce->ce_flags &= ~CE_STRIP_NAME;2377}23782379return result;2380}23812382/*2383 * This function verifies if index_state has the correct sha1 of the2384 * index file. Don't die if we have any other failure, just return 0.2385 */2386static intverify_index_from(const struct index_state *istate,const char*path)2387{2388int fd;2389 ssize_t n;2390struct stat st;2391unsigned char hash[GIT_MAX_RAWSZ];23922393if(!istate->initialized)2394return0;23952396 fd =open(path, O_RDONLY);2397if(fd <0)2398return0;23992400if(fstat(fd, &st))2401goto out;24022403if(st.st_size <sizeof(struct cache_header) + the_hash_algo->rawsz)2404goto out;24052406 n =pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);2407if(n != the_hash_algo->rawsz)2408goto out;24092410if(hashcmp(istate->oid.hash, hash))2411goto out;24122413close(fd);2414return1;24152416out:2417close(fd);2418return0;2419}24202421static intverify_index(const struct index_state *istate)2422{2423returnverify_index_from(istate,get_index_file());2424}24252426static inthas_racy_timestamp(struct index_state *istate)2427{2428int entries = istate->cache_nr;2429int i;24302431for(i =0; i < entries; i++) {2432struct cache_entry *ce = istate->cache[i];2433if(is_racy_timestamp(istate, ce))2434return1;2435}2436return0;2437}24382439voidupdate_index_if_able(struct index_state *istate,struct lock_file *lockfile)2440{2441if((istate->cache_changed ||has_racy_timestamp(istate)) &&2442verify_index(istate))2443write_locked_index(istate, lockfile, COMMIT_LOCK);2444else2445rollback_lock_file(lockfile);2446}24472448/*2449 * On success, `tempfile` is closed. If it is the temporary file2450 * of a `struct lock_file`, we will therefore effectively perform2451 * a 'close_lock_file_gently()`. Since that is an implementation2452 * detail of lockfiles, callers of `do_write_index()` should not2453 * rely on it.2454 */2455static intdo_write_index(struct index_state *istate,struct tempfile *tempfile,2456int strip_extensions)2457{2458uint64_t start =getnanotime();2459int newfd = tempfile->fd;2460 git_hash_ctx c;2461struct cache_header hdr;2462int i, err =0, removed, extended, hdr_version;2463struct cache_entry **cache = istate->cache;2464int entries = istate->cache_nr;2465struct stat st;2466struct ondisk_cache_entry_extended ondisk;2467struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;2468int drop_cache_tree = istate->drop_cache_tree;24692470for(i = removed = extended =0; i < entries; i++) {2471if(cache[i]->ce_flags & CE_REMOVE)2472 removed++;24732474/* reduce extended entries if possible */2475 cache[i]->ce_flags &= ~CE_EXTENDED;2476if(cache[i]->ce_flags & CE_EXTENDED_FLAGS) {2477 extended++;2478 cache[i]->ce_flags |= CE_EXTENDED;2479}2480}24812482if(!istate->version) {2483 istate->version =get_index_format_default();2484if(git_env_bool("GIT_TEST_SPLIT_INDEX",0))2485init_split_index(istate);2486}24872488/* demote version 3 to version 2 when the latter suffices */2489if(istate->version ==3|| istate->version ==2)2490 istate->version = extended ?3:2;24912492 hdr_version = istate->version;24932494 hdr.hdr_signature =htonl(CACHE_SIGNATURE);2495 hdr.hdr_version =htonl(hdr_version);2496 hdr.hdr_entries =htonl(entries - removed);24972498 the_hash_algo->init_fn(&c);2499if(ce_write(&c, newfd, &hdr,sizeof(hdr)) <0)2500return-1;25012502 previous_name = (hdr_version ==4) ? &previous_name_buf : NULL;25032504for(i =0; i < entries; i++) {2505struct cache_entry *ce = cache[i];2506if(ce->ce_flags & CE_REMOVE)2507continue;2508if(!ce_uptodate(ce) &&is_racy_timestamp(istate, ce))2509ce_smudge_racily_clean_entry(ce);2510if(is_null_oid(&ce->oid)) {2511static const char msg[] ="cache entry has null sha1:%s";2512static int allow = -1;25132514if(allow <0)2515 allow =git_env_bool("GIT_ALLOW_NULL_SHA1",0);2516if(allow)2517warning(msg, ce->name);2518else2519 err =error(msg, ce->name);25202521 drop_cache_tree =1;2522}2523if(ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) <0)2524 err = -1;25252526if(err)2527break;2528}2529strbuf_release(&previous_name_buf);25302531if(err)2532return err;25332534/* Write extension data here */2535if(!strip_extensions && istate->split_index) {2536struct strbuf sb = STRBUF_INIT;25372538 err =write_link_extension(&sb, istate) <0||2539write_index_ext_header(&c, newfd, CACHE_EXT_LINK,2540 sb.len) <0||2541ce_write(&c, newfd, sb.buf, sb.len) <0;2542strbuf_release(&sb);2543if(err)2544return-1;2545}2546if(!strip_extensions && !drop_cache_tree && istate->cache_tree) {2547struct strbuf sb = STRBUF_INIT;25482549cache_tree_write(&sb, istate->cache_tree);2550 err =write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) <02551||ce_write(&c, newfd, sb.buf, sb.len) <0;2552strbuf_release(&sb);2553if(err)2554return-1;2555}2556if(!strip_extensions && istate->resolve_undo) {2557struct strbuf sb = STRBUF_INIT;25582559resolve_undo_write(&sb, istate->resolve_undo);2560 err =write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,2561 sb.len) <02562||ce_write(&c, newfd, sb.buf, sb.len) <0;2563strbuf_release(&sb);2564if(err)2565return-1;2566}2567if(!strip_extensions && istate->untracked) {2568struct strbuf sb = STRBUF_INIT;25692570write_untracked_extension(&sb, istate->untracked);2571 err =write_index_ext_header(&c, newfd, CACHE_EXT_UNTRACKED,2572 sb.len) <0||2573ce_write(&c, newfd, sb.buf, sb.len) <0;2574strbuf_release(&sb);2575if(err)2576return-1;2577}2578if(!strip_extensions && istate->fsmonitor_last_update) {2579struct strbuf sb = STRBUF_INIT;25802581write_fsmonitor_extension(&sb, istate);2582 err =write_index_ext_header(&c, newfd, CACHE_EXT_FSMONITOR, sb.len) <02583||ce_write(&c, newfd, sb.buf, sb.len) <0;2584strbuf_release(&sb);2585if(err)2586return-1;2587}25882589if(ce_flush(&c, newfd, istate->oid.hash))2590return-1;2591if(close_tempfile_gently(tempfile)) {2592error(_("could not close '%s'"), tempfile->filename.buf);2593return-1;2594}2595if(stat(tempfile->filename.buf, &st))2596return-1;2597 istate->timestamp.sec = (unsigned int)st.st_mtime;2598 istate->timestamp.nsec =ST_MTIME_NSEC(st);2599trace_performance_since(start,"write index, changed mask =%x", istate->cache_changed);2600return0;2601}26022603voidset_alternate_index_output(const char*name)2604{2605 alternate_index_output = name;2606}26072608static intcommit_locked_index(struct lock_file *lk)2609{2610if(alternate_index_output)2611returncommit_lock_file_to(lk, alternate_index_output);2612else2613returncommit_lock_file(lk);2614}26152616static intdo_write_locked_index(struct index_state *istate,struct lock_file *lock,2617unsigned flags)2618{2619int ret =do_write_index(istate, lock->tempfile,0);2620if(ret)2621return ret;2622if(flags & COMMIT_LOCK)2623returncommit_locked_index(lock);2624returnclose_lock_file_gently(lock);2625}26262627static intwrite_split_index(struct index_state *istate,2628struct lock_file *lock,2629unsigned flags)2630{2631int ret;2632prepare_to_write_split_index(istate);2633 ret =do_write_locked_index(istate, lock, flags);2634finish_writing_split_index(istate);2635return ret;2636}26372638static const char*shared_index_expire ="2.weeks.ago";26392640static unsigned longget_shared_index_expire_date(void)2641{2642static unsigned long shared_index_expire_date;2643static int shared_index_expire_date_prepared;26442645if(!shared_index_expire_date_prepared) {2646git_config_get_expiry("splitindex.sharedindexexpire",2647&shared_index_expire);2648 shared_index_expire_date =approxidate(shared_index_expire);2649 shared_index_expire_date_prepared =1;2650}26512652return shared_index_expire_date;2653}26542655static intshould_delete_shared_index(const char*shared_index_path)2656{2657struct stat st;2658unsigned long expiration;26592660/* Check timestamp */2661 expiration =get_shared_index_expire_date();2662if(!expiration)2663return0;2664if(stat(shared_index_path, &st))2665returnerror_errno(_("could not stat '%s'"), shared_index_path);2666if(st.st_mtime > expiration)2667return0;26682669return1;2670}26712672static intclean_shared_index_files(const char*current_hex)2673{2674struct dirent *de;2675DIR*dir =opendir(get_git_dir());26762677if(!dir)2678returnerror_errno(_("unable to open git dir:%s"),get_git_dir());26792680while((de =readdir(dir)) != NULL) {2681const char*sha1_hex;2682const char*shared_index_path;2683if(!skip_prefix(de->d_name,"sharedindex.", &sha1_hex))2684continue;2685if(!strcmp(sha1_hex, current_hex))2686continue;2687 shared_index_path =git_path("%s", de->d_name);2688if(should_delete_shared_index(shared_index_path) >0&&2689unlink(shared_index_path))2690warning_errno(_("unable to unlink:%s"), shared_index_path);2691}2692closedir(dir);26932694return0;2695}26962697static intwrite_shared_index(struct index_state *istate,2698struct tempfile **temp)2699{2700struct split_index *si = istate->split_index;2701int ret;27022703move_cache_to_base_index(istate);2704 ret =do_write_index(si->base, *temp,1);2705if(ret)2706return ret;2707 ret =adjust_shared_perm(get_tempfile_path(*temp));2708if(ret) {2709error("cannot fix permission bits on%s",get_tempfile_path(*temp));2710return ret;2711}2712 ret =rename_tempfile(temp,2713git_path("sharedindex.%s",oid_to_hex(&si->base->oid)));2714if(!ret) {2715oidcpy(&si->base_oid, &si->base->oid);2716clean_shared_index_files(oid_to_hex(&si->base->oid));2717}27182719return ret;2720}27212722static const int default_max_percent_split_change =20;27232724static inttoo_many_not_shared_entries(struct index_state *istate)2725{2726int i, not_shared =0;2727int max_split =git_config_get_max_percent_split_change();27282729switch(max_split) {2730case-1:2731/* not or badly configured: use the default value */2732 max_split = default_max_percent_split_change;2733break;2734case0:2735return1;/* 0% means always write a new shared index */2736case100:2737return0;/* 100% means never write a new shared index */2738default:2739break;/* just use the configured value */2740}27412742/* Count not shared entries */2743for(i =0; i < istate->cache_nr; i++) {2744struct cache_entry *ce = istate->cache[i];2745if(!ce->index)2746 not_shared++;2747}27482749return(int64_t)istate->cache_nr * max_split < (int64_t)not_shared *100;2750}27512752intwrite_locked_index(struct index_state *istate,struct lock_file *lock,2753unsigned flags)2754{2755int new_shared_index, ret;2756struct split_index *si = istate->split_index;27572758if((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {2759if(flags & COMMIT_LOCK)2760rollback_lock_file(lock);2761return0;2762}27632764if(istate->fsmonitor_last_update)2765fill_fsmonitor_bitmap(istate);27662767if(!si || alternate_index_output ||2768(istate->cache_changed & ~EXTMASK)) {2769if(si)2770oidclr(&si->base_oid);2771 ret =do_write_locked_index(istate, lock, flags);2772goto out;2773}27742775if(git_env_bool("GIT_TEST_SPLIT_INDEX",0)) {2776int v = si->base_oid.hash[0];2777if((v &15) <6)2778 istate->cache_changed |= SPLIT_INDEX_ORDERED;2779}2780if(too_many_not_shared_entries(istate))2781 istate->cache_changed |= SPLIT_INDEX_ORDERED;27822783 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;27842785if(new_shared_index) {2786struct tempfile *temp;2787int saved_errno;27882789 temp =mks_tempfile(git_path("sharedindex_XXXXXX"));2790if(!temp) {2791oidclr(&si->base_oid);2792 ret =do_write_locked_index(istate, lock, flags);2793goto out;2794}2795 ret =write_shared_index(istate, &temp);27962797 saved_errno = errno;2798if(is_tempfile_active(temp))2799delete_tempfile(&temp);2800 errno = saved_errno;28012802if(ret)2803goto out;2804}28052806 ret =write_split_index(istate, lock, flags);28072808/* Freshen the shared index only if the split-index was written */2809if(!ret && !new_shared_index) {2810const char*shared_index =git_path("sharedindex.%s",2811oid_to_hex(&si->base_oid));2812freshen_shared_index(shared_index,1);2813}28142815out:2816if(flags & COMMIT_LOCK)2817rollback_lock_file(lock);2818return ret;2819}28202821/*2822 * Read the index file that is potentially unmerged into given2823 * index_state, dropping any unmerged entries to stage #0 (potentially2824 * resulting in a path appearing as both a file and a directory in the2825 * index; the caller is responsible to clear out the extra entries2826 * before writing the index to a tree). Returns true if the index is2827 * unmerged. Callers who want to refuse to work from an unmerged2828 * state can call this and check its return value, instead of calling2829 * read_cache().2830 */2831intread_index_unmerged(struct index_state *istate)2832{2833int i;2834int unmerged =0;28352836read_index(istate);2837for(i =0; i < istate->cache_nr; i++) {2838struct cache_entry *ce = istate->cache[i];2839struct cache_entry *new_ce;2840int len;28412842if(!ce_stage(ce))2843continue;2844 unmerged =1;2845 len =ce_namelen(ce);2846 new_ce =make_empty_cache_entry(istate, len);2847memcpy(new_ce->name, ce->name, len);2848 new_ce->ce_flags =create_ce_flags(0) | CE_CONFLICTED;2849 new_ce->ce_namelen = len;2850 new_ce->ce_mode = ce->ce_mode;2851if(add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))2852returnerror("%s: cannot drop to stage #0",2853 new_ce->name);2854}2855return unmerged;2856}28572858/*2859 * Returns 1 if the path is an "other" path with respect to2860 * the index; that is, the path is not mentioned in the index at all,2861 * either as a file, a directory with some files in the index,2862 * or as an unmerged entry.2863 *2864 * We helpfully remove a trailing "/" from directories so that2865 * the output of read_directory can be used as-is.2866 */2867intindex_name_is_other(const struct index_state *istate,const char*name,2868int namelen)2869{2870int pos;2871if(namelen && name[namelen -1] =='/')2872 namelen--;2873 pos =index_name_pos(istate, name, namelen);2874if(0<= pos)2875return0;/* exact match */2876 pos = -pos -1;2877if(pos < istate->cache_nr) {2878struct cache_entry *ce = istate->cache[pos];2879if(ce_namelen(ce) == namelen &&2880!memcmp(ce->name, name, namelen))2881return0;/* Yup, this one exists unmerged */2882}2883return1;2884}28852886void*read_blob_data_from_index(const struct index_state *istate,2887const char*path,unsigned long*size)2888{2889int pos, len;2890unsigned long sz;2891enum object_type type;2892void*data;28932894 len =strlen(path);2895 pos =index_name_pos(istate, path, len);2896if(pos <0) {2897/*2898 * We might be in the middle of a merge, in which2899 * case we would read stage #2 (ours).2900 */2901int i;2902for(i = -pos -1;2903(pos <0&& i < istate->cache_nr &&2904!strcmp(istate->cache[i]->name, path));2905 i++)2906if(ce_stage(istate->cache[i]) ==2)2907 pos = i;2908}2909if(pos <0)2910return NULL;2911 data =read_object_file(&istate->cache[pos]->oid, &type, &sz);2912if(!data || type != OBJ_BLOB) {2913free(data);2914return NULL;2915}2916if(size)2917*size = sz;2918return data;2919}29202921voidstat_validity_clear(struct stat_validity *sv)2922{2923FREE_AND_NULL(sv->sd);2924}29252926intstat_validity_check(struct stat_validity *sv,const char*path)2927{2928struct stat st;29292930if(stat(path, &st) <0)2931return sv->sd == NULL;2932if(!sv->sd)2933return0;2934returnS_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);2935}29362937voidstat_validity_update(struct stat_validity *sv,int fd)2938{2939struct stat st;29402941if(fstat(fd, &st) <0|| !S_ISREG(st.st_mode))2942stat_validity_clear(sv);2943else{2944if(!sv->sd)2945 sv->sd =xcalloc(1,sizeof(struct stat_data));2946fill_stat_data(sv->sd, &st);2947}2948}29492950voidmove_index_extensions(struct index_state *dst,struct index_state *src)2951{2952 dst->untracked = src->untracked;2953 src->untracked = NULL;2954}29552956struct cache_entry *dup_cache_entry(const struct cache_entry *ce,2957struct index_state *istate)2958{2959unsigned int size =ce_size(ce);2960int mem_pool_allocated;2961struct cache_entry *new_entry =make_empty_cache_entry(istate,ce_namelen(ce));2962 mem_pool_allocated = new_entry->mem_pool_allocated;29632964memcpy(new_entry, ce, size);2965 new_entry->mem_pool_allocated = mem_pool_allocated;2966return new_entry;2967}29682969voiddiscard_cache_entry(struct cache_entry *ce)2970{2971if(ce &&should_validate_cache_entries())2972memset(ce,0xCD,cache_entry_size(ce->ce_namelen));29732974if(ce && ce->mem_pool_allocated)2975return;29762977free(ce);2978}29792980intshould_validate_cache_entries(void)2981{2982static int validate_index_cache_entries = -1;29832984if(validate_index_cache_entries <0) {2985if(getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))2986 validate_index_cache_entries =1;2987else2988 validate_index_cache_entries =0;2989}29902991return validate_index_cache_entries;2992}