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#define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945/* "EOIE" */ 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 = !oideq(&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; 258return!oideq(&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) && 771oideq(&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;14801481trace_performance_enter();1482 modified_fmt = (in_porcelain ?"M\t%s\n":"%s: needs update\n");1483 deleted_fmt = (in_porcelain ?"D\t%s\n":"%s: needs update\n");1484 typechange_fmt = (in_porcelain ?"T\t%s\n":"%sneeds update\n");1485 added_fmt = (in_porcelain ?"A\t%s\n":"%sneeds update\n");1486 unmerged_fmt = (in_porcelain ?"U\t%s\n":"%s: needs merge\n");1487for(i =0; i < istate->cache_nr; i++) {1488struct cache_entry *ce, *new_entry;1489int cache_errno =0;1490int changed =0;1491int filtered =0;14921493 ce = istate->cache[i];1494if(ignore_submodules &&S_ISGITLINK(ce->ce_mode))1495continue;14961497if(pathspec && !ce_path_match(&the_index, ce, pathspec, seen))1498 filtered =1;14991500if(ce_stage(ce)) {1501while((i < istate->cache_nr) &&1502!strcmp(istate->cache[i]->name, ce->name))1503 i++;1504 i--;1505if(allow_unmerged)1506continue;1507if(!filtered)1508show_file(unmerged_fmt, ce->name, in_porcelain,1509&first, header_msg);1510 has_errors =1;1511continue;1512}15131514if(filtered)1515continue;15161517 new_entry =refresh_cache_ent(istate, ce, options, &cache_errno, &changed);1518if(new_entry == ce)1519continue;1520if(!new_entry) {1521const char*fmt;15221523if(really && cache_errno == EINVAL) {1524/* If we are doing --really-refresh that1525 * means the index is not valid anymore.1526 */1527 ce->ce_flags &= ~CE_VALID;1528 ce->ce_flags |= CE_UPDATE_IN_BASE;1529mark_fsmonitor_invalid(istate, ce);1530 istate->cache_changed |= CE_ENTRY_CHANGED;1531}1532if(quiet)1533continue;15341535if(cache_errno == ENOENT)1536 fmt = deleted_fmt;1537else if(ce_intent_to_add(ce))1538 fmt = added_fmt;/* must be before other checks */1539else if(changed & TYPE_CHANGED)1540 fmt = typechange_fmt;1541else1542 fmt = modified_fmt;1543show_file(fmt,1544 ce->name, in_porcelain, &first, header_msg);1545 has_errors =1;1546continue;1547}15481549replace_index_entry(istate, i, new_entry);1550}1551trace_performance_leave("refresh index");1552return has_errors;1553}15541555struct cache_entry *refresh_cache_entry(struct index_state *istate,1556struct cache_entry *ce,1557unsigned int options)1558{1559returnrefresh_cache_ent(istate, ce, options, NULL, NULL);1560}156115621563/*****************************************************************1564 * Index File I/O1565 *****************************************************************/15661567#define INDEX_FORMAT_DEFAULT 315681569static unsigned intget_index_format_default(void)1570{1571char*envversion =getenv("GIT_INDEX_VERSION");1572char*endp;1573int value;1574unsigned int version = INDEX_FORMAT_DEFAULT;15751576if(!envversion) {1577if(!git_config_get_int("index.version", &value))1578 version = value;1579if(version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1580warning(_("index.version set, but the value is invalid.\n"1581"Using version%i"), INDEX_FORMAT_DEFAULT);1582return INDEX_FORMAT_DEFAULT;1583}1584return version;1585}15861587 version =strtoul(envversion, &endp,10);1588if(*endp ||1589 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1590warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"1591"Using version%i"), INDEX_FORMAT_DEFAULT);1592 version = INDEX_FORMAT_DEFAULT;1593}1594return version;1595}15961597/*1598 * dev/ino/uid/gid/size are also just tracked to the low 32 bits1599 * Again - this is just a (very strong in practice) heuristic that1600 * the inode hasn't changed.1601 *1602 * We save the fields in big-endian order to allow using the1603 * index file over NFS transparently.1604 */1605struct ondisk_cache_entry {1606struct cache_time ctime;1607struct cache_time mtime;1608uint32_t dev;1609uint32_t ino;1610uint32_t mode;1611uint32_t uid;1612uint32_t gid;1613uint32_t size;1614unsigned char sha1[20];1615uint16_t flags;1616char name[FLEX_ARRAY];/* more */1617};16181619/*1620 * This struct is used when CE_EXTENDED bit is 11621 * The struct must match ondisk_cache_entry exactly from1622 * ctime till flags1623 */1624struct ondisk_cache_entry_extended {1625struct cache_time ctime;1626struct cache_time mtime;1627uint32_t dev;1628uint32_t ino;1629uint32_t mode;1630uint32_t uid;1631uint32_t gid;1632uint32_t size;1633unsigned char sha1[20];1634uint16_t flags;1635uint16_t flags2;1636char name[FLEX_ARRAY];/* more */1637};16381639/* These are only used for v3 or lower */1640#define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)1641#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)1642#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)1643#define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)1644#define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \1645 ondisk_cache_entry_extended_size(ce_namelen(ce)) : \1646 ondisk_cache_entry_size(ce_namelen(ce)))16471648/* Allow fsck to force verification of the index checksum. */1649int verify_index_checksum;16501651/* Allow fsck to force verification of the cache entry order. */1652int verify_ce_order;16531654static intverify_hdr(const struct cache_header *hdr,unsigned long size)1655{1656 git_hash_ctx c;1657unsigned char hash[GIT_MAX_RAWSZ];1658int hdr_version;16591660if(hdr->hdr_signature !=htonl(CACHE_SIGNATURE))1661returnerror("bad signature");1662 hdr_version =ntohl(hdr->hdr_version);1663if(hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)1664returnerror("bad index version%d", hdr_version);16651666if(!verify_index_checksum)1667return0;16681669 the_hash_algo->init_fn(&c);1670 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);1671 the_hash_algo->final_fn(hash, &c);1672if(!hasheq(hash, (unsigned char*)hdr + size - the_hash_algo->rawsz))1673returnerror("bad index file sha1 signature");1674return0;1675}16761677static intread_index_extension(struct index_state *istate,1678const char*ext,const char*data,unsigned long sz)1679{1680switch(CACHE_EXT(ext)) {1681case CACHE_EXT_TREE:1682 istate->cache_tree =cache_tree_read(data, sz);1683break;1684case CACHE_EXT_RESOLVE_UNDO:1685 istate->resolve_undo =resolve_undo_read(data, sz);1686break;1687case CACHE_EXT_LINK:1688if(read_link_extension(istate, data, sz))1689return-1;1690break;1691case CACHE_EXT_UNTRACKED:1692 istate->untracked =read_untracked_extension(data, sz);1693break;1694case CACHE_EXT_FSMONITOR:1695read_fsmonitor_extension(istate, data, sz);1696break;1697case CACHE_EXT_ENDOFINDEXENTRIES:1698/* already handled in do_read_index() */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 *create_from_disk(struct index_state *istate,1721struct ondisk_cache_entry *ondisk,1722unsigned long*ent_size,1723const struct cache_entry *previous_ce)1724{1725struct cache_entry *ce;1726size_t len;1727const char*name;1728unsigned int flags;1729size_t copy_len;1730/*1731 * Adjacent cache entries tend to share the leading paths, so it makes1732 * sense to only store the differences in later entries. In the v41733 * on-disk format of the index, each on-disk cache entry stores the1734 * number of bytes to be stripped from the end of the previous name,1735 * and the bytes to append to the result, to come up with its name.1736 */1737int expand_name_field = istate->version ==4;17381739/* On-disk flags are just 16 bits */1740 flags =get_be16(&ondisk->flags);1741 len = flags & CE_NAMEMASK;17421743if(flags & CE_EXTENDED) {1744struct ondisk_cache_entry_extended *ondisk2;1745int extended_flags;1746 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;1747 extended_flags =get_be16(&ondisk2->flags2) <<16;1748/* We do not yet understand any bit out of CE_EXTENDED_FLAGS */1749if(extended_flags & ~CE_EXTENDED_FLAGS)1750die("Unknown index entry format%08x", extended_flags);1751 flags |= extended_flags;1752 name = ondisk2->name;1753}1754else1755 name = ondisk->name;17561757if(expand_name_field) {1758const unsigned char*cp = (const unsigned char*)name;1759size_t strip_len, previous_len;17601761 previous_len = previous_ce ? previous_ce->ce_namelen :0;1762 strip_len =decode_varint(&cp);1763if(previous_len < strip_len) {1764if(previous_ce)1765die(_("malformed name field in the index, near path '%s'"),1766 previous_ce->name);1767else1768die(_("malformed name field in the index in the first path"));1769}1770 copy_len = previous_len - strip_len;1771 name = (const char*)cp;1772}17731774if(len == CE_NAMEMASK) {1775 len =strlen(name);1776if(expand_name_field)1777 len += copy_len;1778}17791780 ce =mem_pool__ce_alloc(istate->ce_mem_pool, len);17811782 ce->ce_stat_data.sd_ctime.sec =get_be32(&ondisk->ctime.sec);1783 ce->ce_stat_data.sd_mtime.sec =get_be32(&ondisk->mtime.sec);1784 ce->ce_stat_data.sd_ctime.nsec =get_be32(&ondisk->ctime.nsec);1785 ce->ce_stat_data.sd_mtime.nsec =get_be32(&ondisk->mtime.nsec);1786 ce->ce_stat_data.sd_dev =get_be32(&ondisk->dev);1787 ce->ce_stat_data.sd_ino =get_be32(&ondisk->ino);1788 ce->ce_mode =get_be32(&ondisk->mode);1789 ce->ce_stat_data.sd_uid =get_be32(&ondisk->uid);1790 ce->ce_stat_data.sd_gid =get_be32(&ondisk->gid);1791 ce->ce_stat_data.sd_size =get_be32(&ondisk->size);1792 ce->ce_flags = flags & ~CE_NAMEMASK;1793 ce->ce_namelen = len;1794 ce->index =0;1795hashcpy(ce->oid.hash, ondisk->sha1);17961797if(expand_name_field) {1798if(copy_len)1799memcpy(ce->name, previous_ce->name, copy_len);1800memcpy(ce->name + copy_len, name, len +1- copy_len);1801*ent_size = (name - ((char*)ondisk)) + len +1- copy_len;1802}else{1803memcpy(ce->name, name, len +1);1804*ent_size =ondisk_ce_size(ce);1805}1806return ce;1807}18081809static voidcheck_ce_order(struct index_state *istate)1810{1811unsigned int i;18121813if(!verify_ce_order)1814return;18151816for(i =1; i < istate->cache_nr; i++) {1817struct cache_entry *ce = istate->cache[i -1];1818struct cache_entry *next_ce = istate->cache[i];1819int name_compare =strcmp(ce->name, next_ce->name);18201821if(0< name_compare)1822die("unordered stage entries in index");1823if(!name_compare) {1824if(!ce_stage(ce))1825die("multiple stage entries for merged file '%s'",1826 ce->name);1827if(ce_stage(ce) >ce_stage(next_ce))1828die("unordered stage entries for '%s'",1829 ce->name);1830}1831}1832}18331834static voidtweak_untracked_cache(struct index_state *istate)1835{1836switch(git_config_get_untracked_cache()) {1837case-1:/* keep: do nothing */1838break;1839case0:/* false */1840remove_untracked_cache(istate);1841break;1842case1:/* true */1843add_untracked_cache(istate);1844break;1845default:/* unknown value: do nothing */1846break;1847}1848}18491850static voidtweak_split_index(struct index_state *istate)1851{1852switch(git_config_get_split_index()) {1853case-1:/* unset: do nothing */1854break;1855case0:/* false */1856remove_split_index(istate);1857break;1858case1:/* true */1859add_split_index(istate);1860break;1861default:/* unknown value: do nothing */1862break;1863}1864}18651866static voidpost_read_index_from(struct index_state *istate)1867{1868check_ce_order(istate);1869tweak_untracked_cache(istate);1870tweak_split_index(istate);1871tweak_fsmonitor(istate);1872}18731874static size_testimate_cache_size_from_compressed(unsigned int entries)1875{1876return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);1877}18781879static size_testimate_cache_size(size_t ondisk_size,unsigned int entries)1880{1881long per_entry =sizeof(struct cache_entry) -sizeof(struct ondisk_cache_entry);18821883/*1884 * Account for potential alignment differences.1885 */1886 per_entry +=align_padding_size(sizeof(struct cache_entry), -sizeof(struct ondisk_cache_entry));1887return ondisk_size + entries * per_entry;1888}18891890static size_tread_eoie_extension(const char*mmap,size_t mmap_size);1891static voidwrite_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context,size_t offset);18921893/* remember to discard_cache() before reading a different cache! */1894intdo_read_index(struct index_state *istate,const char*path,int must_exist)1895{1896int fd, i;1897struct stat st;1898unsigned long src_offset;1899const struct cache_header *hdr;1900const char*mmap;1901size_t mmap_size;1902const struct cache_entry *previous_ce = NULL;19031904if(istate->initialized)1905return istate->cache_nr;19061907 istate->timestamp.sec =0;1908 istate->timestamp.nsec =0;1909 fd =open(path, O_RDONLY);1910if(fd <0) {1911if(!must_exist && errno == ENOENT)1912return0;1913die_errno("%s: index file open failed", path);1914}19151916if(fstat(fd, &st))1917die_errno("cannot stat the open index");19181919 mmap_size =xsize_t(st.st_size);1920if(mmap_size <sizeof(struct cache_header) + the_hash_algo->rawsz)1921die("index file smaller than expected");19221923 mmap =xmmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd,0);1924if(mmap == MAP_FAILED)1925die_errno("unable to map index file");1926close(fd);19271928 hdr = (const struct cache_header *)mmap;1929if(verify_hdr(hdr, mmap_size) <0)1930goto unmap;19311932hashcpy(istate->oid.hash, (const unsigned char*)hdr + mmap_size - the_hash_algo->rawsz);1933 istate->version =ntohl(hdr->hdr_version);1934 istate->cache_nr =ntohl(hdr->hdr_entries);1935 istate->cache_alloc =alloc_nr(istate->cache_nr);1936 istate->cache =xcalloc(istate->cache_alloc,sizeof(*istate->cache));1937 istate->initialized =1;19381939if(istate->version ==4) {1940mem_pool_init(&istate->ce_mem_pool,1941estimate_cache_size_from_compressed(istate->cache_nr));1942}else{1943mem_pool_init(&istate->ce_mem_pool,1944estimate_cache_size(mmap_size, istate->cache_nr));1945}19461947 src_offset =sizeof(*hdr);1948for(i =0; i < istate->cache_nr; i++) {1949struct ondisk_cache_entry *disk_ce;1950struct cache_entry *ce;1951unsigned long consumed;19521953 disk_ce = (struct ondisk_cache_entry *)(mmap + src_offset);1954 ce =create_from_disk(istate, disk_ce, &consumed, previous_ce);1955set_index_entry(istate, i, ce);19561957 src_offset += consumed;1958 previous_ce = ce;1959}1960 istate->timestamp.sec = st.st_mtime;1961 istate->timestamp.nsec =ST_MTIME_NSEC(st);19621963while(src_offset <= mmap_size - the_hash_algo->rawsz -8) {1964/* After an array of active_nr index entries,1965 * there can be arbitrary number of extended1966 * sections, each of which is prefixed with1967 * extension name (4-byte) and section length1968 * in 4-byte network byte order.1969 */1970uint32_t extsize;1971 extsize =get_be32(mmap + src_offset +4);1972if(read_index_extension(istate,1973 mmap + src_offset,1974 mmap + src_offset +8,1975 extsize) <0)1976goto unmap;1977 src_offset +=8;1978 src_offset += extsize;1979}1980munmap((void*)mmap, mmap_size);1981return istate->cache_nr;19821983unmap:1984munmap((void*)mmap, mmap_size);1985die("index file corrupt");1986}19871988/*1989 * Signal that the shared index is used by updating its mtime.1990 *1991 * This way, shared index can be removed if they have not been used1992 * for some time.1993 */1994static voidfreshen_shared_index(const char*shared_index,int warn)1995{1996if(!check_and_freshen_file(shared_index,1) && warn)1997warning("could not freshen shared index '%s'", shared_index);1998}19992000intread_index_from(struct index_state *istate,const char*path,2001const char*gitdir)2002{2003struct split_index *split_index;2004int ret;2005char*base_oid_hex;2006char*base_path;20072008/* istate->initialized covers both .git/index and .git/sharedindex.xxx */2009if(istate->initialized)2010return istate->cache_nr;20112012trace_performance_enter();2013 ret =do_read_index(istate, path,0);2014trace_performance_leave("read cache%s", path);20152016 split_index = istate->split_index;2017if(!split_index ||is_null_oid(&split_index->base_oid)) {2018post_read_index_from(istate);2019return ret;2020}20212022trace_performance_enter();2023if(split_index->base)2024discard_index(split_index->base);2025else2026 split_index->base =xcalloc(1,sizeof(*split_index->base));20272028 base_oid_hex =oid_to_hex(&split_index->base_oid);2029 base_path =xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);2030 ret =do_read_index(split_index->base, base_path,1);2031if(!oideq(&split_index->base_oid, &split_index->base->oid))2032die("broken index, expect%sin%s, got%s",2033 base_oid_hex, base_path,2034oid_to_hex(&split_index->base->oid));20352036freshen_shared_index(base_path,0);2037merge_base_index(istate);2038post_read_index_from(istate);2039free(base_path);2040trace_performance_leave("read cache%s", base_path);2041return ret;2042}20432044intis_index_unborn(struct index_state *istate)2045{2046return(!istate->cache_nr && !istate->timestamp.sec);2047}20482049intdiscard_index(struct index_state *istate)2050{2051/*2052 * Cache entries in istate->cache[] should have been allocated2053 * from the memory pool associated with this index, or from an2054 * associated split_index. There is no need to free individual2055 * cache entries. validate_cache_entries can detect when this2056 * assertion does not hold.2057 */2058validate_cache_entries(istate);20592060resolve_undo_clear_index(istate);2061 istate->cache_nr =0;2062 istate->cache_changed =0;2063 istate->timestamp.sec =0;2064 istate->timestamp.nsec =0;2065free_name_hash(istate);2066cache_tree_free(&(istate->cache_tree));2067 istate->initialized =0;2068FREE_AND_NULL(istate->cache);2069 istate->cache_alloc =0;2070discard_split_index(istate);2071free_untracked_cache(istate->untracked);2072 istate->untracked = NULL;20732074if(istate->ce_mem_pool) {2075mem_pool_discard(istate->ce_mem_pool,should_validate_cache_entries());2076 istate->ce_mem_pool = NULL;2077}20782079return0;2080}20812082/*2083 * Validate the cache entries of this index.2084 * All cache entries associated with this index2085 * should have been allocated by the memory pool2086 * associated with this index, or by a referenced2087 * split index.2088 */2089voidvalidate_cache_entries(const struct index_state *istate)2090{2091int i;20922093if(!should_validate_cache_entries() ||!istate || !istate->initialized)2094return;20952096for(i =0; i < istate->cache_nr; i++) {2097if(!istate) {2098die("internal error: cache entry is not allocated from expected memory pool");2099}else if(!istate->ce_mem_pool ||2100!mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {2101if(!istate->split_index ||2102!istate->split_index->base ||2103!istate->split_index->base->ce_mem_pool ||2104!mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {2105die("internal error: cache entry is not allocated from expected memory pool");2106}2107}2108}21092110if(istate->split_index)2111validate_cache_entries(istate->split_index->base);2112}21132114intunmerged_index(const struct index_state *istate)2115{2116int i;2117for(i =0; i < istate->cache_nr; i++) {2118if(ce_stage(istate->cache[i]))2119return1;2120}2121return0;2122}21232124intindex_has_changes(const struct index_state *istate,2125struct tree *tree,2126struct strbuf *sb)2127{2128struct object_id cmp;2129int i;21302131if(istate != &the_index) {2132BUG("index_has_changes cannot yet accept istate != &the_index; do_diff_cache needs updating first.");2133}2134if(tree)2135 cmp = tree->object.oid;2136if(tree || !get_oid_tree("HEAD", &cmp)) {2137struct diff_options opt;21382139diff_setup(&opt);2140 opt.flags.exit_with_status =1;2141if(!sb)2142 opt.flags.quick =1;2143do_diff_cache(&cmp, &opt);2144diffcore_std(&opt);2145for(i =0; sb && i < diff_queued_diff.nr; i++) {2146if(i)2147strbuf_addch(sb,' ');2148strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);2149}2150diff_flush(&opt);2151return opt.flags.has_changes !=0;2152}else{2153for(i =0; sb && i < istate->cache_nr; i++) {2154if(i)2155strbuf_addch(sb,' ');2156strbuf_addstr(sb, istate->cache[i]->name);2157}2158return!!istate->cache_nr;2159}2160}21612162#define WRITE_BUFFER_SIZE 81922163static unsigned char write_buffer[WRITE_BUFFER_SIZE];2164static unsigned long write_buffer_len;21652166static intce_write_flush(git_hash_ctx *context,int fd)2167{2168unsigned int buffered = write_buffer_len;2169if(buffered) {2170 the_hash_algo->update_fn(context, write_buffer, buffered);2171if(write_in_full(fd, write_buffer, buffered) <0)2172return-1;2173 write_buffer_len =0;2174}2175return0;2176}21772178static intce_write(git_hash_ctx *context,int fd,void*data,unsigned int len)2179{2180while(len) {2181unsigned int buffered = write_buffer_len;2182unsigned int partial = WRITE_BUFFER_SIZE - buffered;2183if(partial > len)2184 partial = len;2185memcpy(write_buffer + buffered, data, partial);2186 buffered += partial;2187if(buffered == WRITE_BUFFER_SIZE) {2188 write_buffer_len = buffered;2189if(ce_write_flush(context, fd))2190return-1;2191 buffered =0;2192}2193 write_buffer_len = buffered;2194 len -= partial;2195 data = (char*) data + partial;2196}2197return0;2198}21992200static intwrite_index_ext_header(git_hash_ctx *context, git_hash_ctx *eoie_context,2201int fd,unsigned int ext,unsigned int sz)2202{2203 ext =htonl(ext);2204 sz =htonl(sz);2205if(eoie_context) {2206 the_hash_algo->update_fn(eoie_context, &ext,4);2207 the_hash_algo->update_fn(eoie_context, &sz,4);2208}2209return((ce_write(context, fd, &ext,4) <0) ||2210(ce_write(context, fd, &sz,4) <0)) ? -1:0;2211}22122213static intce_flush(git_hash_ctx *context,int fd,unsigned char*hash)2214{2215unsigned int left = write_buffer_len;22162217if(left) {2218 write_buffer_len =0;2219 the_hash_algo->update_fn(context, write_buffer, left);2220}22212222/* Flush first if not enough space for hash signature */2223if(left + the_hash_algo->rawsz > WRITE_BUFFER_SIZE) {2224if(write_in_full(fd, write_buffer, left) <0)2225return-1;2226 left =0;2227}22282229/* Append the hash signature at the end */2230 the_hash_algo->final_fn(write_buffer + left, context);2231hashcpy(hash, write_buffer + left);2232 left += the_hash_algo->rawsz;2233return(write_in_full(fd, write_buffer, left) <0) ? -1:0;2234}22352236static voidce_smudge_racily_clean_entry(struct cache_entry *ce)2237{2238/*2239 * The only thing we care about in this function is to smudge the2240 * falsely clean entry due to touch-update-touch race, so we leave2241 * everything else as they are. We are called for entries whose2242 * ce_stat_data.sd_mtime match the index file mtime.2243 *2244 * Note that this actually does not do much for gitlinks, for2245 * which ce_match_stat_basic() always goes to the actual2246 * contents. The caller checks with is_racy_timestamp() which2247 * always says "no" for gitlinks, so we are not called for them ;-)2248 */2249struct stat st;22502251if(lstat(ce->name, &st) <0)2252return;2253if(ce_match_stat_basic(ce, &st))2254return;2255if(ce_modified_check_fs(ce, &st)) {2256/* This is "racily clean"; smudge it. Note that this2257 * is a tricky code. At first glance, it may appear2258 * that it can break with this sequence:2259 *2260 * $ echo xyzzy >frotz2261 * $ git-update-index --add frotz2262 * $ : >frotz2263 * $ sleep 32264 * $ echo filfre >nitfol2265 * $ git-update-index --add nitfol2266 *2267 * but it does not. When the second update-index runs,2268 * it notices that the entry "frotz" has the same timestamp2269 * as index, and if we were to smudge it by resetting its2270 * size to zero here, then the object name recorded2271 * in index is the 6-byte file but the cached stat information2272 * becomes zero --- which would then match what we would2273 * obtain from the filesystem next time we stat("frotz").2274 *2275 * However, the second update-index, before calling2276 * this function, notices that the cached size is 62277 * bytes and what is on the filesystem is an empty2278 * file, and never calls us, so the cached size information2279 * for "frotz" stays 6 which does not match the filesystem.2280 */2281 ce->ce_stat_data.sd_size =0;2282}2283}22842285/* Copy miscellaneous fields but not the name */2286static voidcopy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,2287struct cache_entry *ce)2288{2289short flags;22902291 ondisk->ctime.sec =htonl(ce->ce_stat_data.sd_ctime.sec);2292 ondisk->mtime.sec =htonl(ce->ce_stat_data.sd_mtime.sec);2293 ondisk->ctime.nsec =htonl(ce->ce_stat_data.sd_ctime.nsec);2294 ondisk->mtime.nsec =htonl(ce->ce_stat_data.sd_mtime.nsec);2295 ondisk->dev =htonl(ce->ce_stat_data.sd_dev);2296 ondisk->ino =htonl(ce->ce_stat_data.sd_ino);2297 ondisk->mode =htonl(ce->ce_mode);2298 ondisk->uid =htonl(ce->ce_stat_data.sd_uid);2299 ondisk->gid =htonl(ce->ce_stat_data.sd_gid);2300 ondisk->size =htonl(ce->ce_stat_data.sd_size);2301hashcpy(ondisk->sha1, ce->oid.hash);23022303 flags = ce->ce_flags & ~CE_NAMEMASK;2304 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK :ce_namelen(ce));2305 ondisk->flags =htons(flags);2306if(ce->ce_flags & CE_EXTENDED) {2307struct ondisk_cache_entry_extended *ondisk2;2308 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;2309 ondisk2->flags2 =htons((ce->ce_flags & CE_EXTENDED_FLAGS) >>16);2310}2311}23122313static intce_write_entry(git_hash_ctx *c,int fd,struct cache_entry *ce,2314struct strbuf *previous_name,struct ondisk_cache_entry *ondisk)2315{2316int size;2317int result;2318unsigned int saved_namelen;2319int stripped_name =0;2320static unsigned char padding[8] = {0x00};23212322if(ce->ce_flags & CE_STRIP_NAME) {2323 saved_namelen =ce_namelen(ce);2324 ce->ce_namelen =0;2325 stripped_name =1;2326}23272328if(ce->ce_flags & CE_EXTENDED)2329 size =offsetof(struct ondisk_cache_entry_extended, name);2330else2331 size =offsetof(struct ondisk_cache_entry, name);23322333if(!previous_name) {2334int len =ce_namelen(ce);2335copy_cache_entry_to_ondisk(ondisk, ce);2336 result =ce_write(c, fd, ondisk, size);2337if(!result)2338 result =ce_write(c, fd, ce->name, len);2339if(!result)2340 result =ce_write(c, fd, padding,align_padding_size(size, len));2341}else{2342int common, to_remove, prefix_size;2343unsigned char to_remove_vi[16];2344for(common =0;2345(ce->name[common] &&2346 common < previous_name->len &&2347 ce->name[common] == previous_name->buf[common]);2348 common++)2349;/* still matching */2350 to_remove = previous_name->len - common;2351 prefix_size =encode_varint(to_remove, to_remove_vi);23522353copy_cache_entry_to_ondisk(ondisk, ce);2354 result =ce_write(c, fd, ondisk, size);2355if(!result)2356 result =ce_write(c, fd, to_remove_vi, prefix_size);2357if(!result)2358 result =ce_write(c, fd, ce->name + common,ce_namelen(ce) - common);2359if(!result)2360 result =ce_write(c, fd, padding,1);23612362strbuf_splice(previous_name, common, to_remove,2363 ce->name + common,ce_namelen(ce) - common);2364}2365if(stripped_name) {2366 ce->ce_namelen = saved_namelen;2367 ce->ce_flags &= ~CE_STRIP_NAME;2368}23692370return result;2371}23722373/*2374 * This function verifies if index_state has the correct sha1 of the2375 * index file. Don't die if we have any other failure, just return 0.2376 */2377static intverify_index_from(const struct index_state *istate,const char*path)2378{2379int fd;2380 ssize_t n;2381struct stat st;2382unsigned char hash[GIT_MAX_RAWSZ];23832384if(!istate->initialized)2385return0;23862387 fd =open(path, O_RDONLY);2388if(fd <0)2389return0;23902391if(fstat(fd, &st))2392goto out;23932394if(st.st_size <sizeof(struct cache_header) + the_hash_algo->rawsz)2395goto out;23962397 n =pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);2398if(n != the_hash_algo->rawsz)2399goto out;24002401if(!hasheq(istate->oid.hash, hash))2402goto out;24032404close(fd);2405return1;24062407out:2408close(fd);2409return0;2410}24112412static intverify_index(const struct index_state *istate)2413{2414returnverify_index_from(istate,get_index_file());2415}24162417static inthas_racy_timestamp(struct index_state *istate)2418{2419int entries = istate->cache_nr;2420int i;24212422for(i =0; i < entries; i++) {2423struct cache_entry *ce = istate->cache[i];2424if(is_racy_timestamp(istate, ce))2425return1;2426}2427return0;2428}24292430voidupdate_index_if_able(struct index_state *istate,struct lock_file *lockfile)2431{2432if((istate->cache_changed ||has_racy_timestamp(istate)) &&2433verify_index(istate))2434write_locked_index(istate, lockfile, COMMIT_LOCK);2435else2436rollback_lock_file(lockfile);2437}24382439/*2440 * On success, `tempfile` is closed. If it is the temporary file2441 * of a `struct lock_file`, we will therefore effectively perform2442 * a 'close_lock_file_gently()`. Since that is an implementation2443 * detail of lockfiles, callers of `do_write_index()` should not2444 * rely on it.2445 */2446static intdo_write_index(struct index_state *istate,struct tempfile *tempfile,2447int strip_extensions)2448{2449uint64_t start =getnanotime();2450int newfd = tempfile->fd;2451 git_hash_ctx c, eoie_c;2452struct cache_header hdr;2453int i, err =0, removed, extended, hdr_version;2454struct cache_entry **cache = istate->cache;2455int entries = istate->cache_nr;2456struct stat st;2457struct ondisk_cache_entry_extended ondisk;2458struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;2459int drop_cache_tree = istate->drop_cache_tree;2460 off_t offset;24612462for(i = removed = extended =0; i < entries; i++) {2463if(cache[i]->ce_flags & CE_REMOVE)2464 removed++;24652466/* reduce extended entries if possible */2467 cache[i]->ce_flags &= ~CE_EXTENDED;2468if(cache[i]->ce_flags & CE_EXTENDED_FLAGS) {2469 extended++;2470 cache[i]->ce_flags |= CE_EXTENDED;2471}2472}24732474if(!istate->version) {2475 istate->version =get_index_format_default();2476if(git_env_bool("GIT_TEST_SPLIT_INDEX",0))2477init_split_index(istate);2478}24792480/* demote version 3 to version 2 when the latter suffices */2481if(istate->version ==3|| istate->version ==2)2482 istate->version = extended ?3:2;24832484 hdr_version = istate->version;24852486 hdr.hdr_signature =htonl(CACHE_SIGNATURE);2487 hdr.hdr_version =htonl(hdr_version);2488 hdr.hdr_entries =htonl(entries - removed);24892490 the_hash_algo->init_fn(&c);2491if(ce_write(&c, newfd, &hdr,sizeof(hdr)) <0)2492return-1;24932494 offset =lseek(newfd,0, SEEK_CUR);2495if(offset <0)2496return-1;2497 offset += write_buffer_len;2498 previous_name = (hdr_version ==4) ? &previous_name_buf : NULL;24992500for(i =0; i < entries; i++) {2501struct cache_entry *ce = cache[i];2502if(ce->ce_flags & CE_REMOVE)2503continue;2504if(!ce_uptodate(ce) &&is_racy_timestamp(istate, ce))2505ce_smudge_racily_clean_entry(ce);2506if(is_null_oid(&ce->oid)) {2507static const char msg[] ="cache entry has null sha1:%s";2508static int allow = -1;25092510if(allow <0)2511 allow =git_env_bool("GIT_ALLOW_NULL_SHA1",0);2512if(allow)2513warning(msg, ce->name);2514else2515 err =error(msg, ce->name);25162517 drop_cache_tree =1;2518}2519if(ce_write_entry(&c, newfd, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) <0)2520 err = -1;25212522if(err)2523break;2524}2525strbuf_release(&previous_name_buf);25262527if(err)2528return err;25292530/* Write extension data here */2531 offset =lseek(newfd,0, SEEK_CUR);2532if(offset <0)2533return-1;2534 offset += write_buffer_len;2535 the_hash_algo->init_fn(&eoie_c);25362537if(!strip_extensions && istate->split_index) {2538struct strbuf sb = STRBUF_INIT;25392540 err =write_link_extension(&sb, istate) <0||2541write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_LINK,2542 sb.len) <0||2543ce_write(&c, newfd, sb.buf, sb.len) <0;2544strbuf_release(&sb);2545if(err)2546return-1;2547}2548if(!strip_extensions && !drop_cache_tree && istate->cache_tree) {2549struct strbuf sb = STRBUF_INIT;25502551cache_tree_write(&sb, istate->cache_tree);2552 err =write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_TREE, sb.len) <02553||ce_write(&c, newfd, sb.buf, sb.len) <0;2554strbuf_release(&sb);2555if(err)2556return-1;2557}2558if(!strip_extensions && istate->resolve_undo) {2559struct strbuf sb = STRBUF_INIT;25602561resolve_undo_write(&sb, istate->resolve_undo);2562 err =write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_RESOLVE_UNDO,2563 sb.len) <02564||ce_write(&c, newfd, sb.buf, sb.len) <0;2565strbuf_release(&sb);2566if(err)2567return-1;2568}2569if(!strip_extensions && istate->untracked) {2570struct strbuf sb = STRBUF_INIT;25712572write_untracked_extension(&sb, istate->untracked);2573 err =write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_UNTRACKED,2574 sb.len) <0||2575ce_write(&c, newfd, sb.buf, sb.len) <0;2576strbuf_release(&sb);2577if(err)2578return-1;2579}2580if(!strip_extensions && istate->fsmonitor_last_update) {2581struct strbuf sb = STRBUF_INIT;25822583write_fsmonitor_extension(&sb, istate);2584 err =write_index_ext_header(&c, &eoie_c, newfd, CACHE_EXT_FSMONITOR, sb.len) <02585||ce_write(&c, newfd, sb.buf, sb.len) <0;2586strbuf_release(&sb);2587if(err)2588return-1;2589}25902591/*2592 * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA12593 * so that it can be found and processed before all the index entries are2594 * read. Write it out regardless of the strip_extensions parameter as we need it2595 * when loading the shared index.2596 */2597if(offset) {2598struct strbuf sb = STRBUF_INIT;25992600write_eoie_extension(&sb, &eoie_c, offset);2601 err =write_index_ext_header(&c, NULL, newfd, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) <02602||ce_write(&c, newfd, sb.buf, sb.len) <0;2603strbuf_release(&sb);2604if(err)2605return-1;2606}26072608if(ce_flush(&c, newfd, istate->oid.hash))2609return-1;2610if(close_tempfile_gently(tempfile)) {2611error(_("could not close '%s'"), tempfile->filename.buf);2612return-1;2613}2614if(stat(tempfile->filename.buf, &st))2615return-1;2616 istate->timestamp.sec = (unsigned int)st.st_mtime;2617 istate->timestamp.nsec =ST_MTIME_NSEC(st);2618trace_performance_since(start,"write index, changed mask =%x", istate->cache_changed);2619return0;2620}26212622voidset_alternate_index_output(const char*name)2623{2624 alternate_index_output = name;2625}26262627static intcommit_locked_index(struct lock_file *lk)2628{2629if(alternate_index_output)2630returncommit_lock_file_to(lk, alternate_index_output);2631else2632returncommit_lock_file(lk);2633}26342635static intdo_write_locked_index(struct index_state *istate,struct lock_file *lock,2636unsigned flags)2637{2638int ret =do_write_index(istate, lock->tempfile,0);2639if(ret)2640return ret;2641if(flags & COMMIT_LOCK)2642returncommit_locked_index(lock);2643returnclose_lock_file_gently(lock);2644}26452646static intwrite_split_index(struct index_state *istate,2647struct lock_file *lock,2648unsigned flags)2649{2650int ret;2651prepare_to_write_split_index(istate);2652 ret =do_write_locked_index(istate, lock, flags);2653finish_writing_split_index(istate);2654return ret;2655}26562657static const char*shared_index_expire ="2.weeks.ago";26582659static unsigned longget_shared_index_expire_date(void)2660{2661static unsigned long shared_index_expire_date;2662static int shared_index_expire_date_prepared;26632664if(!shared_index_expire_date_prepared) {2665git_config_get_expiry("splitindex.sharedindexexpire",2666&shared_index_expire);2667 shared_index_expire_date =approxidate(shared_index_expire);2668 shared_index_expire_date_prepared =1;2669}26702671return shared_index_expire_date;2672}26732674static intshould_delete_shared_index(const char*shared_index_path)2675{2676struct stat st;2677unsigned long expiration;26782679/* Check timestamp */2680 expiration =get_shared_index_expire_date();2681if(!expiration)2682return0;2683if(stat(shared_index_path, &st))2684returnerror_errno(_("could not stat '%s'"), shared_index_path);2685if(st.st_mtime > expiration)2686return0;26872688return1;2689}26902691static intclean_shared_index_files(const char*current_hex)2692{2693struct dirent *de;2694DIR*dir =opendir(get_git_dir());26952696if(!dir)2697returnerror_errno(_("unable to open git dir:%s"),get_git_dir());26982699while((de =readdir(dir)) != NULL) {2700const char*sha1_hex;2701const char*shared_index_path;2702if(!skip_prefix(de->d_name,"sharedindex.", &sha1_hex))2703continue;2704if(!strcmp(sha1_hex, current_hex))2705continue;2706 shared_index_path =git_path("%s", de->d_name);2707if(should_delete_shared_index(shared_index_path) >0&&2708unlink(shared_index_path))2709warning_errno(_("unable to unlink:%s"), shared_index_path);2710}2711closedir(dir);27122713return0;2714}27152716static intwrite_shared_index(struct index_state *istate,2717struct tempfile **temp)2718{2719struct split_index *si = istate->split_index;2720int ret;27212722move_cache_to_base_index(istate);2723 ret =do_write_index(si->base, *temp,1);2724if(ret)2725return ret;2726 ret =adjust_shared_perm(get_tempfile_path(*temp));2727if(ret) {2728error("cannot fix permission bits on%s",get_tempfile_path(*temp));2729return ret;2730}2731 ret =rename_tempfile(temp,2732git_path("sharedindex.%s",oid_to_hex(&si->base->oid)));2733if(!ret) {2734oidcpy(&si->base_oid, &si->base->oid);2735clean_shared_index_files(oid_to_hex(&si->base->oid));2736}27372738return ret;2739}27402741static const int default_max_percent_split_change =20;27422743static inttoo_many_not_shared_entries(struct index_state *istate)2744{2745int i, not_shared =0;2746int max_split =git_config_get_max_percent_split_change();27472748switch(max_split) {2749case-1:2750/* not or badly configured: use the default value */2751 max_split = default_max_percent_split_change;2752break;2753case0:2754return1;/* 0% means always write a new shared index */2755case100:2756return0;/* 100% means never write a new shared index */2757default:2758break;/* just use the configured value */2759}27602761/* Count not shared entries */2762for(i =0; i < istate->cache_nr; i++) {2763struct cache_entry *ce = istate->cache[i];2764if(!ce->index)2765 not_shared++;2766}27672768return(int64_t)istate->cache_nr * max_split < (int64_t)not_shared *100;2769}27702771intwrite_locked_index(struct index_state *istate,struct lock_file *lock,2772unsigned flags)2773{2774int new_shared_index, ret;2775struct split_index *si = istate->split_index;27762777if(git_env_bool("GIT_TEST_CHECK_CACHE_TREE",0))2778cache_tree_verify(istate);27792780if((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {2781if(flags & COMMIT_LOCK)2782rollback_lock_file(lock);2783return0;2784}27852786if(istate->fsmonitor_last_update)2787fill_fsmonitor_bitmap(istate);27882789if(!si || alternate_index_output ||2790(istate->cache_changed & ~EXTMASK)) {2791if(si)2792oidclr(&si->base_oid);2793 ret =do_write_locked_index(istate, lock, flags);2794goto out;2795}27962797if(git_env_bool("GIT_TEST_SPLIT_INDEX",0)) {2798int v = si->base_oid.hash[0];2799if((v &15) <6)2800 istate->cache_changed |= SPLIT_INDEX_ORDERED;2801}2802if(too_many_not_shared_entries(istate))2803 istate->cache_changed |= SPLIT_INDEX_ORDERED;28042805 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;28062807if(new_shared_index) {2808struct tempfile *temp;2809int saved_errno;28102811 temp =mks_tempfile(git_path("sharedindex_XXXXXX"));2812if(!temp) {2813oidclr(&si->base_oid);2814 ret =do_write_locked_index(istate, lock, flags);2815goto out;2816}2817 ret =write_shared_index(istate, &temp);28182819 saved_errno = errno;2820if(is_tempfile_active(temp))2821delete_tempfile(&temp);2822 errno = saved_errno;28232824if(ret)2825goto out;2826}28272828 ret =write_split_index(istate, lock, flags);28292830/* Freshen the shared index only if the split-index was written */2831if(!ret && !new_shared_index) {2832const char*shared_index =git_path("sharedindex.%s",2833oid_to_hex(&si->base_oid));2834freshen_shared_index(shared_index,1);2835}28362837out:2838if(flags & COMMIT_LOCK)2839rollback_lock_file(lock);2840return ret;2841}28422843/*2844 * Read the index file that is potentially unmerged into given2845 * index_state, dropping any unmerged entries to stage #0 (potentially2846 * resulting in a path appearing as both a file and a directory in the2847 * index; the caller is responsible to clear out the extra entries2848 * before writing the index to a tree). Returns true if the index is2849 * unmerged. Callers who want to refuse to work from an unmerged2850 * state can call this and check its return value, instead of calling2851 * read_cache().2852 */2853intread_index_unmerged(struct index_state *istate)2854{2855int i;2856int unmerged =0;28572858read_index(istate);2859for(i =0; i < istate->cache_nr; i++) {2860struct cache_entry *ce = istate->cache[i];2861struct cache_entry *new_ce;2862int len;28632864if(!ce_stage(ce))2865continue;2866 unmerged =1;2867 len =ce_namelen(ce);2868 new_ce =make_empty_cache_entry(istate, len);2869memcpy(new_ce->name, ce->name, len);2870 new_ce->ce_flags =create_ce_flags(0) | CE_CONFLICTED;2871 new_ce->ce_namelen = len;2872 new_ce->ce_mode = ce->ce_mode;2873if(add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))2874returnerror("%s: cannot drop to stage #0",2875 new_ce->name);2876}2877return unmerged;2878}28792880/*2881 * Returns 1 if the path is an "other" path with respect to2882 * the index; that is, the path is not mentioned in the index at all,2883 * either as a file, a directory with some files in the index,2884 * or as an unmerged entry.2885 *2886 * We helpfully remove a trailing "/" from directories so that2887 * the output of read_directory can be used as-is.2888 */2889intindex_name_is_other(const struct index_state *istate,const char*name,2890int namelen)2891{2892int pos;2893if(namelen && name[namelen -1] =='/')2894 namelen--;2895 pos =index_name_pos(istate, name, namelen);2896if(0<= pos)2897return0;/* exact match */2898 pos = -pos -1;2899if(pos < istate->cache_nr) {2900struct cache_entry *ce = istate->cache[pos];2901if(ce_namelen(ce) == namelen &&2902!memcmp(ce->name, name, namelen))2903return0;/* Yup, this one exists unmerged */2904}2905return1;2906}29072908void*read_blob_data_from_index(const struct index_state *istate,2909const char*path,unsigned long*size)2910{2911int pos, len;2912unsigned long sz;2913enum object_type type;2914void*data;29152916 len =strlen(path);2917 pos =index_name_pos(istate, path, len);2918if(pos <0) {2919/*2920 * We might be in the middle of a merge, in which2921 * case we would read stage #2 (ours).2922 */2923int i;2924for(i = -pos -1;2925(pos <0&& i < istate->cache_nr &&2926!strcmp(istate->cache[i]->name, path));2927 i++)2928if(ce_stage(istate->cache[i]) ==2)2929 pos = i;2930}2931if(pos <0)2932return NULL;2933 data =read_object_file(&istate->cache[pos]->oid, &type, &sz);2934if(!data || type != OBJ_BLOB) {2935free(data);2936return NULL;2937}2938if(size)2939*size = sz;2940return data;2941}29422943voidstat_validity_clear(struct stat_validity *sv)2944{2945FREE_AND_NULL(sv->sd);2946}29472948intstat_validity_check(struct stat_validity *sv,const char*path)2949{2950struct stat st;29512952if(stat(path, &st) <0)2953return sv->sd == NULL;2954if(!sv->sd)2955return0;2956returnS_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);2957}29582959voidstat_validity_update(struct stat_validity *sv,int fd)2960{2961struct stat st;29622963if(fstat(fd, &st) <0|| !S_ISREG(st.st_mode))2964stat_validity_clear(sv);2965else{2966if(!sv->sd)2967 sv->sd =xcalloc(1,sizeof(struct stat_data));2968fill_stat_data(sv->sd, &st);2969}2970}29712972voidmove_index_extensions(struct index_state *dst,struct index_state *src)2973{2974 dst->untracked = src->untracked;2975 src->untracked = NULL;2976 dst->cache_tree = src->cache_tree;2977 src->cache_tree = NULL;2978}29792980struct cache_entry *dup_cache_entry(const struct cache_entry *ce,2981struct index_state *istate)2982{2983unsigned int size =ce_size(ce);2984int mem_pool_allocated;2985struct cache_entry *new_entry =make_empty_cache_entry(istate,ce_namelen(ce));2986 mem_pool_allocated = new_entry->mem_pool_allocated;29872988memcpy(new_entry, ce, size);2989 new_entry->mem_pool_allocated = mem_pool_allocated;2990return new_entry;2991}29922993voiddiscard_cache_entry(struct cache_entry *ce)2994{2995if(ce &&should_validate_cache_entries())2996memset(ce,0xCD,cache_entry_size(ce->ce_namelen));29972998if(ce && ce->mem_pool_allocated)2999return;30003001free(ce);3002}30033004intshould_validate_cache_entries(void)3005{3006static int validate_index_cache_entries = -1;30073008if(validate_index_cache_entries <0) {3009if(getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))3010 validate_index_cache_entries =1;3011else3012 validate_index_cache_entries =0;3013}30143015return validate_index_cache_entries;3016}30173018#define EOIE_SIZE (4 + GIT_SHA1_RAWSZ)/* <4-byte offset> + <20-byte hash> */3019#define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE)/* <4-byte signature> + <4-byte length> + EOIE_SIZE */30203021static size_tread_eoie_extension(const char*mmap,size_t mmap_size)3022{3023/*3024 * The end of index entries (EOIE) extension is guaranteed to be last3025 * so that it can be found by scanning backwards from the EOF.3026 *3027 * "EOIE"3028 * <4-byte length>3029 * <4-byte offset>3030 * <20-byte hash>3031 */3032const char*index, *eoie;3033uint32_t extsize;3034size_t offset, src_offset;3035unsigned char hash[GIT_MAX_RAWSZ];3036 git_hash_ctx c;30373038/* ensure we have an index big enough to contain an EOIE extension */3039if(mmap_size <sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)3040return0;30413042/* validate the extension signature */3043 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;3044if(CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)3045return0;3046 index +=sizeof(uint32_t);30473048/* validate the extension size */3049 extsize =get_be32(index);3050if(extsize != EOIE_SIZE)3051return0;3052 index +=sizeof(uint32_t);30533054/*3055 * Validate the offset we're going to look for the first extension3056 * signature is after the index header and before the eoie extension.3057 */3058 offset =get_be32(index);3059if(mmap + offset < mmap +sizeof(struct cache_header))3060return0;3061if(mmap + offset >= eoie)3062return0;3063 index +=sizeof(uint32_t);30643065/*3066 * The hash is computed over extension types and their sizes (but not3067 * their contents). E.g. if we have "TREE" extension that is N-bytes3068 * long, "REUC" extension that is M-bytes long, followed by "EOIE",3069 * then the hash would be:3070 *3071 * SHA-1("TREE" + <binary representation of N> +3072 * "REUC" + <binary representation of M>)3073 */3074 src_offset = offset;3075 the_hash_algo->init_fn(&c);3076while(src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {3077/* After an array of active_nr index entries,3078 * there can be arbitrary number of extended3079 * sections, each of which is prefixed with3080 * extension name (4-byte) and section length3081 * in 4-byte network byte order.3082 */3083uint32_t extsize;3084memcpy(&extsize, mmap + src_offset +4,4);3085 extsize =ntohl(extsize);30863087/* verify the extension size isn't so large it will wrap around */3088if(src_offset +8+ extsize < src_offset)3089return0;30903091 the_hash_algo->update_fn(&c, mmap + src_offset,8);30923093 src_offset +=8;3094 src_offset += extsize;3095}3096 the_hash_algo->final_fn(hash, &c);3097if(!hasheq(hash, (const unsigned char*)index))3098return0;30993100/* Validate that the extension offsets returned us back to the eoie extension. */3101if(src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)3102return0;31033104return offset;3105}31063107static voidwrite_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context,size_t offset)3108{3109uint32_t buffer;3110unsigned char hash[GIT_MAX_RAWSZ];31113112/* offset */3113put_be32(&buffer, offset);3114strbuf_add(sb, &buffer,sizeof(uint32_t));31153116/* hash */3117 the_hash_algo->final_fn(hash, eoie_context);3118strbuf_add(sb, hash, the_hash_algo->rawsz);3119}