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"cache-tree.h" 9#include"refs.h" 10#include"dir.h" 11#include"tree.h" 12#include"commit.h" 13#include"blob.h" 14#include"resolve-undo.h" 15#include"strbuf.h" 16#include"varint.h" 17#include"split-index.h" 18 19static struct cache_entry *refresh_cache_entry(struct cache_entry *ce, 20unsigned int options); 21 22/* Mask for the name length in ce_flags in the on-disk index */ 23 24#define CE_NAMEMASK (0x0fff) 25 26/* Index extensions. 27 * 28 * The first letter should be 'A'..'Z' for extensions that are not 29 * necessary for a correct operation (i.e. optimization data). 30 * When new extensions are added that _needs_ to be understood in 31 * order to correctly interpret the index file, pick character that 32 * is outside the range, to cause the reader to abort. 33 */ 34 35#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) ) 36#define CACHE_EXT_TREE 0x54524545/* "TREE" */ 37#define CACHE_EXT_RESOLVE_UNDO 0x52455543/* "REUC" */ 38#define CACHE_EXT_LINK 0x6c696e6b/* "link" */ 39 40/* changes that can be kept in $GIT_DIR/index (basically all extensions) */ 41#define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED) 42 43struct index_state the_index; 44static const char*alternate_index_output; 45 46static voidset_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 47{ 48 istate->cache[nr] = ce; 49add_name_hash(istate, ce); 50} 51 52static voidreplace_index_entry(struct index_state *istate,int nr,struct cache_entry *ce) 53{ 54struct cache_entry *old = istate->cache[nr]; 55 56remove_name_hash(istate, old); 57free(old); 58set_index_entry(istate, nr, ce); 59 istate->cache_changed |= CE_ENTRY_CHANGED; 60} 61 62voidrename_index_entry_at(struct index_state *istate,int nr,const char*new_name) 63{ 64struct cache_entry *old = istate->cache[nr], *new; 65int namelen =strlen(new_name); 66 67new=xmalloc(cache_entry_size(namelen)); 68copy_cache_entry(new, old); 69new->ce_flags &= ~CE_HASHED; 70new->ce_namelen = namelen; 71new->index =0; 72memcpy(new->name, new_name, namelen +1); 73 74cache_tree_invalidate_path(istate, old->name); 75remove_index_entry_at(istate, nr); 76add_index_entry(istate,new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE); 77} 78 79voidfill_stat_data(struct stat_data *sd,struct stat *st) 80{ 81 sd->sd_ctime.sec = (unsigned int)st->st_ctime; 82 sd->sd_mtime.sec = (unsigned int)st->st_mtime; 83 sd->sd_ctime.nsec =ST_CTIME_NSEC(*st); 84 sd->sd_mtime.nsec =ST_MTIME_NSEC(*st); 85 sd->sd_dev = st->st_dev; 86 sd->sd_ino = st->st_ino; 87 sd->sd_uid = st->st_uid; 88 sd->sd_gid = st->st_gid; 89 sd->sd_size = st->st_size; 90} 91 92intmatch_stat_data(const struct stat_data *sd,struct stat *st) 93{ 94int changed =0; 95 96if(sd->sd_mtime.sec != (unsigned int)st->st_mtime) 97 changed |= MTIME_CHANGED; 98if(trust_ctime && check_stat && 99 sd->sd_ctime.sec != (unsigned int)st->st_ctime) 100 changed |= CTIME_CHANGED; 101 102#ifdef USE_NSEC 103if(check_stat && sd->sd_mtime.nsec !=ST_MTIME_NSEC(*st)) 104 changed |= MTIME_CHANGED; 105if(trust_ctime && check_stat && 106 sd->sd_ctime.nsec !=ST_CTIME_NSEC(*st)) 107 changed |= CTIME_CHANGED; 108#endif 109 110if(check_stat) { 111if(sd->sd_uid != (unsigned int) st->st_uid || 112 sd->sd_gid != (unsigned int) st->st_gid) 113 changed |= OWNER_CHANGED; 114if(sd->sd_ino != (unsigned int) st->st_ino) 115 changed |= INODE_CHANGED; 116} 117 118#ifdef USE_STDEV 119/* 120 * st_dev breaks on network filesystems where different 121 * clients will have different views of what "device" 122 * the filesystem is on 123 */ 124if(check_stat && sd->sd_dev != (unsigned int) st->st_dev) 125 changed |= INODE_CHANGED; 126#endif 127 128if(sd->sd_size != (unsigned int) st->st_size) 129 changed |= DATA_CHANGED; 130 131return changed; 132} 133 134/* 135 * This only updates the "non-critical" parts of the directory 136 * cache, ie the parts that aren't tracked by GIT, and only used 137 * to validate the cache. 138 */ 139voidfill_stat_cache_info(struct cache_entry *ce,struct stat *st) 140{ 141fill_stat_data(&ce->ce_stat_data, st); 142 143if(assume_unchanged) 144 ce->ce_flags |= CE_VALID; 145 146if(S_ISREG(st->st_mode)) 147ce_mark_uptodate(ce); 148} 149 150static intce_compare_data(const struct cache_entry *ce,struct stat *st) 151{ 152int match = -1; 153int fd =open(ce->name, O_RDONLY); 154 155if(fd >=0) { 156unsigned char sha1[20]; 157if(!index_fd(sha1, fd, st, OBJ_BLOB, ce->name,0)) 158 match =hashcmp(sha1, ce->sha1); 159/* index_fd() closed the file descriptor already */ 160} 161return match; 162} 163 164static intce_compare_link(const struct cache_entry *ce,size_t expected_size) 165{ 166int match = -1; 167void*buffer; 168unsigned long size; 169enum object_type type; 170struct strbuf sb = STRBUF_INIT; 171 172if(strbuf_readlink(&sb, ce->name, expected_size)) 173return-1; 174 175 buffer =read_sha1_file(ce->sha1, &type, &size); 176if(buffer) { 177if(size == sb.len) 178 match =memcmp(buffer, sb.buf, size); 179free(buffer); 180} 181strbuf_release(&sb); 182return match; 183} 184 185static intce_compare_gitlink(const struct cache_entry *ce) 186{ 187unsigned char sha1[20]; 188 189/* 190 * We don't actually require that the .git directory 191 * under GITLINK directory be a valid git directory. It 192 * might even be missing (in case nobody populated that 193 * sub-project). 194 * 195 * If so, we consider it always to match. 196 */ 197if(resolve_gitlink_ref(ce->name,"HEAD", sha1) <0) 198return0; 199returnhashcmp(sha1, ce->sha1); 200} 201 202static intce_modified_check_fs(const struct cache_entry *ce,struct stat *st) 203{ 204switch(st->st_mode & S_IFMT) { 205case S_IFREG: 206if(ce_compare_data(ce, st)) 207return DATA_CHANGED; 208break; 209case S_IFLNK: 210if(ce_compare_link(ce,xsize_t(st->st_size))) 211return DATA_CHANGED; 212break; 213case S_IFDIR: 214if(S_ISGITLINK(ce->ce_mode)) 215returnce_compare_gitlink(ce) ? DATA_CHANGED :0; 216default: 217return TYPE_CHANGED; 218} 219return0; 220} 221 222static intce_match_stat_basic(const struct cache_entry *ce,struct stat *st) 223{ 224unsigned int changed =0; 225 226if(ce->ce_flags & CE_REMOVE) 227return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED; 228 229switch(ce->ce_mode & S_IFMT) { 230case S_IFREG: 231 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED :0; 232/* We consider only the owner x bit to be relevant for 233 * "mode changes" 234 */ 235if(trust_executable_bit && 236(0100& (ce->ce_mode ^ st->st_mode))) 237 changed |= MODE_CHANGED; 238break; 239case S_IFLNK: 240if(!S_ISLNK(st->st_mode) && 241(has_symlinks || !S_ISREG(st->st_mode))) 242 changed |= TYPE_CHANGED; 243break; 244case S_IFGITLINK: 245/* We ignore most of the st_xxx fields for gitlinks */ 246if(!S_ISDIR(st->st_mode)) 247 changed |= TYPE_CHANGED; 248else if(ce_compare_gitlink(ce)) 249 changed |= DATA_CHANGED; 250return changed; 251default: 252die("internal error: ce_mode is%o", ce->ce_mode); 253} 254 255 changed |=match_stat_data(&ce->ce_stat_data, st); 256 257/* Racily smudged entry? */ 258if(!ce->ce_stat_data.sd_size) { 259if(!is_empty_blob_sha1(ce->sha1)) 260 changed |= DATA_CHANGED; 261} 262 263return changed; 264} 265 266static intis_racy_timestamp(const struct index_state *istate, 267const struct cache_entry *ce) 268{ 269return(!S_ISGITLINK(ce->ce_mode) && 270 istate->timestamp.sec && 271#ifdef USE_NSEC 272/* nanosecond timestamped files can also be racy! */ 273(istate->timestamp.sec < ce->ce_stat_data.sd_mtime.sec || 274(istate->timestamp.sec == ce->ce_stat_data.sd_mtime.sec && 275 istate->timestamp.nsec <= ce->ce_stat_data.sd_mtime.nsec)) 276#else 277 istate->timestamp.sec <= ce->ce_stat_data.sd_mtime.sec 278#endif 279); 280} 281 282intie_match_stat(const struct index_state *istate, 283const struct cache_entry *ce,struct stat *st, 284unsigned int options) 285{ 286unsigned int changed; 287int ignore_valid = options & CE_MATCH_IGNORE_VALID; 288int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE; 289int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY; 290 291/* 292 * If it's marked as always valid in the index, it's 293 * valid whatever the checked-out copy says. 294 * 295 * skip-worktree has the same effect with higher precedence 296 */ 297if(!ignore_skip_worktree &&ce_skip_worktree(ce)) 298return0; 299if(!ignore_valid && (ce->ce_flags & CE_VALID)) 300return0; 301 302/* 303 * Intent-to-add entries have not been added, so the index entry 304 * by definition never matches what is in the work tree until it 305 * actually gets added. 306 */ 307if(ce->ce_flags & CE_INTENT_TO_ADD) 308return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED; 309 310 changed =ce_match_stat_basic(ce, st); 311 312/* 313 * Within 1 second of this sequence: 314 * echo xyzzy >file && git-update-index --add file 315 * running this command: 316 * echo frotz >file 317 * would give a falsely clean cache entry. The mtime and 318 * length match the cache, and other stat fields do not change. 319 * 320 * We could detect this at update-index time (the cache entry 321 * being registered/updated records the same time as "now") 322 * and delay the return from git-update-index, but that would 323 * effectively mean we can make at most one commit per second, 324 * which is not acceptable. Instead, we check cache entries 325 * whose mtime are the same as the index file timestamp more 326 * carefully than others. 327 */ 328if(!changed &&is_racy_timestamp(istate, ce)) { 329if(assume_racy_is_modified) 330 changed |= DATA_CHANGED; 331else 332 changed |=ce_modified_check_fs(ce, st); 333} 334 335return changed; 336} 337 338intie_modified(const struct index_state *istate, 339const struct cache_entry *ce, 340struct stat *st,unsigned int options) 341{ 342int changed, changed_fs; 343 344 changed =ie_match_stat(istate, ce, st, options); 345if(!changed) 346return0; 347/* 348 * If the mode or type has changed, there's no point in trying 349 * to refresh the entry - it's not going to match 350 */ 351if(changed & (MODE_CHANGED | TYPE_CHANGED)) 352return changed; 353 354/* 355 * Immediately after read-tree or update-index --cacheinfo, 356 * the length field is zero, as we have never even read the 357 * lstat(2) information once, and we cannot trust DATA_CHANGED 358 * returned by ie_match_stat() which in turn was returned by 359 * ce_match_stat_basic() to signal that the filesize of the 360 * blob changed. We have to actually go to the filesystem to 361 * see if the contents match, and if so, should answer "unchanged". 362 * 363 * The logic does not apply to gitlinks, as ce_match_stat_basic() 364 * already has checked the actual HEAD from the filesystem in the 365 * subproject. If ie_match_stat() already said it is different, 366 * then we know it is. 367 */ 368if((changed & DATA_CHANGED) && 369(S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size !=0)) 370return changed; 371 372 changed_fs =ce_modified_check_fs(ce, st); 373if(changed_fs) 374return changed | changed_fs; 375return0; 376} 377 378intbase_name_compare(const char*name1,int len1,int mode1, 379const char*name2,int len2,int mode2) 380{ 381unsigned char c1, c2; 382int len = len1 < len2 ? len1 : len2; 383int cmp; 384 385 cmp =memcmp(name1, name2, len); 386if(cmp) 387return cmp; 388 c1 = name1[len]; 389 c2 = name2[len]; 390if(!c1 &&S_ISDIR(mode1)) 391 c1 ='/'; 392if(!c2 &&S_ISDIR(mode2)) 393 c2 ='/'; 394return(c1 < c2) ? -1: (c1 > c2) ?1:0; 395} 396 397/* 398 * df_name_compare() is identical to base_name_compare(), except it 399 * compares conflicting directory/file entries as equal. Note that 400 * while a directory name compares as equal to a regular file, they 401 * then individually compare _differently_ to a filename that has 402 * a dot after the basename (because '\0' < '.' < '/'). 403 * 404 * This is used by routines that want to traverse the git namespace 405 * but then handle conflicting entries together when possible. 406 */ 407intdf_name_compare(const char*name1,int len1,int mode1, 408const char*name2,int len2,int mode2) 409{ 410int len = len1 < len2 ? len1 : len2, cmp; 411unsigned char c1, c2; 412 413 cmp =memcmp(name1, name2, len); 414if(cmp) 415return cmp; 416/* Directories and files compare equal (same length, same name) */ 417if(len1 == len2) 418return0; 419 c1 = name1[len]; 420if(!c1 &&S_ISDIR(mode1)) 421 c1 ='/'; 422 c2 = name2[len]; 423if(!c2 &&S_ISDIR(mode2)) 424 c2 ='/'; 425if(c1 =='/'&& !c2) 426return0; 427if(c2 =='/'&& !c1) 428return0; 429return c1 - c2; 430} 431 432intcache_name_stage_compare(const char*name1,int len1,int stage1,const char*name2,int len2,int stage2) 433{ 434int len = len1 < len2 ? len1 : len2; 435int cmp; 436 437 cmp =memcmp(name1, name2, len); 438if(cmp) 439return cmp; 440if(len1 < len2) 441return-1; 442if(len1 > len2) 443return1; 444 445if(stage1 < stage2) 446return-1; 447if(stage1 > stage2) 448return1; 449return0; 450} 451 452intcache_name_compare(const char*name1,int len1,const char*name2,int len2) 453{ 454returncache_name_stage_compare(name1, len1,0, name2, len2,0); 455} 456 457static intindex_name_stage_pos(const struct index_state *istate,const char*name,int namelen,int stage) 458{ 459int first, last; 460 461 first =0; 462 last = istate->cache_nr; 463while(last > first) { 464int next = (last + first) >>1; 465struct cache_entry *ce = istate->cache[next]; 466int cmp =cache_name_stage_compare(name, namelen, stage, ce->name,ce_namelen(ce),ce_stage(ce)); 467if(!cmp) 468return next; 469if(cmp <0) { 470 last = next; 471continue; 472} 473 first = next+1; 474} 475return-first-1; 476} 477 478intindex_name_pos(const struct index_state *istate,const char*name,int namelen) 479{ 480returnindex_name_stage_pos(istate, name, namelen,0); 481} 482 483/* Remove entry, return true if there are more entries to go.. */ 484intremove_index_entry_at(struct index_state *istate,int pos) 485{ 486struct cache_entry *ce = istate->cache[pos]; 487 488record_resolve_undo(istate, ce); 489remove_name_hash(istate, ce); 490free(ce); 491 istate->cache_changed |= CE_ENTRY_REMOVED; 492 istate->cache_nr--; 493if(pos >= istate->cache_nr) 494return0; 495memmove(istate->cache + pos, 496 istate->cache + pos +1, 497(istate->cache_nr - pos) *sizeof(struct cache_entry *)); 498return1; 499} 500 501/* 502 * Remove all cache entries marked for removal, that is where 503 * CE_REMOVE is set in ce_flags. This is much more effective than 504 * calling remove_index_entry_at() for each entry to be removed. 505 */ 506voidremove_marked_cache_entries(struct index_state *istate) 507{ 508struct cache_entry **ce_array = istate->cache; 509unsigned int i, j; 510 511for(i = j =0; i < istate->cache_nr; i++) { 512if(ce_array[i]->ce_flags & CE_REMOVE) { 513remove_name_hash(istate, ce_array[i]); 514free(ce_array[i]); 515} 516else 517 ce_array[j++] = ce_array[i]; 518} 519if(j == istate->cache_nr) 520return; 521 istate->cache_changed |= CE_ENTRY_REMOVED; 522 istate->cache_nr = j; 523} 524 525intremove_file_from_index(struct index_state *istate,const char*path) 526{ 527int pos =index_name_pos(istate, path,strlen(path)); 528if(pos <0) 529 pos = -pos-1; 530cache_tree_invalidate_path(istate, path); 531while(pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path)) 532remove_index_entry_at(istate, pos); 533return0; 534} 535 536static intcompare_name(struct cache_entry *ce,const char*path,int namelen) 537{ 538return namelen !=ce_namelen(ce) ||memcmp(path, ce->name, namelen); 539} 540 541static intindex_name_pos_also_unmerged(struct index_state *istate, 542const char*path,int namelen) 543{ 544int pos =index_name_pos(istate, path, namelen); 545struct cache_entry *ce; 546 547if(pos >=0) 548return pos; 549 550/* maybe unmerged? */ 551 pos = -1- pos; 552if(pos >= istate->cache_nr || 553compare_name((ce = istate->cache[pos]), path, namelen)) 554return-1; 555 556/* order of preference: stage 2, 1, 3 */ 557if(ce_stage(ce) ==1&& pos +1< istate->cache_nr && 558ce_stage((ce = istate->cache[pos +1])) ==2&& 559!compare_name(ce, path, namelen)) 560 pos++; 561return pos; 562} 563 564static intdifferent_name(struct cache_entry *ce,struct cache_entry *alias) 565{ 566int len =ce_namelen(ce); 567returnce_namelen(alias) != len ||memcmp(ce->name, alias->name, len); 568} 569 570/* 571 * If we add a filename that aliases in the cache, we will use the 572 * name that we already have - but we don't want to update the same 573 * alias twice, because that implies that there were actually two 574 * different files with aliasing names! 575 * 576 * So we use the CE_ADDED flag to verify that the alias was an old 577 * one before we accept it as 578 */ 579static struct cache_entry *create_alias_ce(struct cache_entry *ce,struct cache_entry *alias) 580{ 581int len; 582struct cache_entry *new; 583 584if(alias->ce_flags & CE_ADDED) 585die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name); 586 587/* Ok, create the new entry using the name of the existing alias */ 588 len =ce_namelen(alias); 589new=xcalloc(1,cache_entry_size(len)); 590memcpy(new->name, alias->name, len); 591copy_cache_entry(new, ce); 592free(ce); 593return new; 594} 595 596voidset_object_name_for_intent_to_add_entry(struct cache_entry *ce) 597{ 598unsigned char sha1[20]; 599if(write_sha1_file("",0, blob_type, sha1)) 600die("cannot create an empty blob in the object database"); 601hashcpy(ce->sha1, sha1); 602} 603 604intadd_to_index(struct index_state *istate,const char*path,struct stat *st,int flags) 605{ 606int size, namelen, was_same; 607 mode_t st_mode = st->st_mode; 608struct cache_entry *ce, *alias; 609unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY; 610int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND); 611int pretend = flags & ADD_CACHE_PRETEND; 612int intent_only = flags & ADD_CACHE_INTENT; 613int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE| 614(intent_only ? ADD_CACHE_NEW_ONLY :0)); 615 616if(!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode)) 617returnerror("%s: can only add regular files, symbolic links or git-directories", path); 618 619 namelen =strlen(path); 620if(S_ISDIR(st_mode)) { 621while(namelen && path[namelen-1] =='/') 622 namelen--; 623} 624 size =cache_entry_size(namelen); 625 ce =xcalloc(1, size); 626memcpy(ce->name, path, namelen); 627 ce->ce_namelen = namelen; 628if(!intent_only) 629fill_stat_cache_info(ce, st); 630else 631 ce->ce_flags |= CE_INTENT_TO_ADD; 632 633if(trust_executable_bit && has_symlinks) 634 ce->ce_mode =create_ce_mode(st_mode); 635else{ 636/* If there is an existing entry, pick the mode bits and type 637 * from it, otherwise assume unexecutable regular file. 638 */ 639struct cache_entry *ent; 640int pos =index_name_pos_also_unmerged(istate, path, namelen); 641 642 ent = (0<= pos) ? istate->cache[pos] : NULL; 643 ce->ce_mode =ce_mode_from_stat(ent, st_mode); 644} 645 646/* When core.ignorecase=true, determine if a directory of the same name but differing 647 * case already exists within the Git repository. If it does, ensure the directory 648 * case of the file being added to the repository matches (is folded into) the existing 649 * entry's directory case. 650 */ 651if(ignore_case) { 652const char*startPtr = ce->name; 653const char*ptr = startPtr; 654while(*ptr) { 655while(*ptr && *ptr !='/') 656++ptr; 657if(*ptr =='/') { 658struct cache_entry *foundce; 659++ptr; 660 foundce =index_dir_exists(istate, ce->name, ptr - ce->name -1); 661if(foundce) { 662memcpy((void*)startPtr, foundce->name + (startPtr - ce->name), ptr - startPtr); 663 startPtr = ptr; 664} 665} 666} 667} 668 669 alias =index_file_exists(istate, ce->name,ce_namelen(ce), ignore_case); 670if(alias && !ce_stage(alias) && !ie_match_stat(istate, alias, st, ce_option)) { 671/* Nothing changed, really */ 672free(ce); 673if(!S_ISGITLINK(alias->ce_mode)) 674ce_mark_uptodate(alias); 675 alias->ce_flags |= CE_ADDED; 676return0; 677} 678if(!intent_only) { 679if(index_path(ce->sha1, path, st, HASH_WRITE_OBJECT)) 680returnerror("unable to index file%s", path); 681}else 682set_object_name_for_intent_to_add_entry(ce); 683 684if(ignore_case && alias &&different_name(ce, alias)) 685 ce =create_alias_ce(ce, alias); 686 ce->ce_flags |= CE_ADDED; 687 688/* It was suspected to be racily clean, but it turns out to be Ok */ 689 was_same = (alias && 690!ce_stage(alias) && 691!hashcmp(alias->sha1, ce->sha1) && 692 ce->ce_mode == alias->ce_mode); 693 694if(pretend) 695; 696else if(add_index_entry(istate, ce, add_option)) 697returnerror("unable to add%sto index",path); 698if(verbose && !was_same) 699printf("add '%s'\n", path); 700return0; 701} 702 703intadd_file_to_index(struct index_state *istate,const char*path,int flags) 704{ 705struct stat st; 706if(lstat(path, &st)) 707die_errno("unable to stat '%s'", path); 708returnadd_to_index(istate, path, &st, flags); 709} 710 711struct cache_entry *make_cache_entry(unsigned int mode, 712const unsigned char*sha1,const char*path,int stage, 713unsigned int refresh_options) 714{ 715int size, len; 716struct cache_entry *ce; 717 718if(!verify_path(path)) { 719error("Invalid path '%s'", path); 720return NULL; 721} 722 723 len =strlen(path); 724 size =cache_entry_size(len); 725 ce =xcalloc(1, size); 726 727hashcpy(ce->sha1, sha1); 728memcpy(ce->name, path, len); 729 ce->ce_flags =create_ce_flags(stage); 730 ce->ce_namelen = len; 731 ce->ce_mode =create_ce_mode(mode); 732 733returnrefresh_cache_entry(ce, refresh_options); 734} 735 736intce_same_name(const struct cache_entry *a,const struct cache_entry *b) 737{ 738int len =ce_namelen(a); 739returnce_namelen(b) == len && !memcmp(a->name, b->name, len); 740} 741 742/* 743 * We fundamentally don't like some paths: we don't want 744 * dot or dot-dot anywhere, and for obvious reasons don't 745 * want to recurse into ".git" either. 746 * 747 * Also, we don't want double slashes or slashes at the 748 * end that can make pathnames ambiguous. 749 */ 750static intverify_dotfile(const char*rest) 751{ 752/* 753 * The first character was '.', but that 754 * has already been discarded, we now test 755 * the rest. 756 */ 757 758/* "." is not allowed */ 759if(*rest =='\0'||is_dir_sep(*rest)) 760return0; 761 762switch(*rest) { 763/* 764 * ".git" followed by NUL or slash is bad. This 765 * shares the path end test with the ".." case. 766 */ 767case'g': 768if(rest[1] !='i') 769break; 770if(rest[2] !='t') 771break; 772 rest +=2; 773/* fallthrough */ 774case'.': 775if(rest[1] =='\0'||is_dir_sep(rest[1])) 776return0; 777} 778return1; 779} 780 781intverify_path(const char*path) 782{ 783char c; 784 785if(has_dos_drive_prefix(path)) 786return0; 787 788goto inside; 789for(;;) { 790if(!c) 791return1; 792if(is_dir_sep(c)) { 793inside: 794 c = *path++; 795if((c =='.'&& !verify_dotfile(path)) || 796is_dir_sep(c) || c =='\0') 797return0; 798} 799 c = *path++; 800} 801} 802 803/* 804 * Do we have another file that has the beginning components being a 805 * proper superset of the name we're trying to add? 806 */ 807static inthas_file_name(struct index_state *istate, 808const struct cache_entry *ce,int pos,int ok_to_replace) 809{ 810int retval =0; 811int len =ce_namelen(ce); 812int stage =ce_stage(ce); 813const char*name = ce->name; 814 815while(pos < istate->cache_nr) { 816struct cache_entry *p = istate->cache[pos++]; 817 818if(len >=ce_namelen(p)) 819break; 820if(memcmp(name, p->name, len)) 821break; 822if(ce_stage(p) != stage) 823continue; 824if(p->name[len] !='/') 825continue; 826if(p->ce_flags & CE_REMOVE) 827continue; 828 retval = -1; 829if(!ok_to_replace) 830break; 831remove_index_entry_at(istate, --pos); 832} 833return retval; 834} 835 836/* 837 * Do we have another file with a pathname that is a proper 838 * subset of the name we're trying to add? 839 */ 840static inthas_dir_name(struct index_state *istate, 841const struct cache_entry *ce,int pos,int ok_to_replace) 842{ 843int retval =0; 844int stage =ce_stage(ce); 845const char*name = ce->name; 846const char*slash = name +ce_namelen(ce); 847 848for(;;) { 849int len; 850 851for(;;) { 852if(*--slash =='/') 853break; 854if(slash <= ce->name) 855return retval; 856} 857 len = slash - name; 858 859 pos =index_name_stage_pos(istate, name, len, stage); 860if(pos >=0) { 861/* 862 * Found one, but not so fast. This could 863 * be a marker that says "I was here, but 864 * I am being removed". Such an entry is 865 * not a part of the resulting tree, and 866 * it is Ok to have a directory at the same 867 * path. 868 */ 869if(!(istate->cache[pos]->ce_flags & CE_REMOVE)) { 870 retval = -1; 871if(!ok_to_replace) 872break; 873remove_index_entry_at(istate, pos); 874continue; 875} 876} 877else 878 pos = -pos-1; 879 880/* 881 * Trivial optimization: if we find an entry that 882 * already matches the sub-directory, then we know 883 * we're ok, and we can exit. 884 */ 885while(pos < istate->cache_nr) { 886struct cache_entry *p = istate->cache[pos]; 887if((ce_namelen(p) <= len) || 888(p->name[len] !='/') || 889memcmp(p->name, name, len)) 890break;/* not our subdirectory */ 891if(ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE)) 892/* 893 * p is at the same stage as our entry, and 894 * is a subdirectory of what we are looking 895 * at, so we cannot have conflicts at our 896 * level or anything shorter. 897 */ 898return retval; 899 pos++; 900} 901} 902return retval; 903} 904 905/* We may be in a situation where we already have path/file and path 906 * is being added, or we already have path and path/file is being 907 * added. Either one would result in a nonsense tree that has path 908 * twice when git-write-tree tries to write it out. Prevent it. 909 * 910 * If ok-to-replace is specified, we remove the conflicting entries 911 * from the cache so the caller should recompute the insert position. 912 * When this happens, we return non-zero. 913 */ 914static intcheck_file_directory_conflict(struct index_state *istate, 915const struct cache_entry *ce, 916int pos,int ok_to_replace) 917{ 918int retval; 919 920/* 921 * When ce is an "I am going away" entry, we allow it to be added 922 */ 923if(ce->ce_flags & CE_REMOVE) 924return0; 925 926/* 927 * We check if the path is a sub-path of a subsequent pathname 928 * first, since removing those will not change the position 929 * in the array. 930 */ 931 retval =has_file_name(istate, ce, pos, ok_to_replace); 932 933/* 934 * Then check if the path might have a clashing sub-directory 935 * before it. 936 */ 937return retval +has_dir_name(istate, ce, pos, ok_to_replace); 938} 939 940static intadd_index_entry_with_check(struct index_state *istate,struct cache_entry *ce,int option) 941{ 942int pos; 943int ok_to_add = option & ADD_CACHE_OK_TO_ADD; 944int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE; 945int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK; 946int new_only = option & ADD_CACHE_NEW_ONLY; 947 948cache_tree_invalidate_path(istate, ce->name); 949 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce)); 950 951/* existing match? Just replace it. */ 952if(pos >=0) { 953if(!new_only) 954replace_index_entry(istate, pos, ce); 955return0; 956} 957 pos = -pos-1; 958 959/* 960 * Inserting a merged entry ("stage 0") into the index 961 * will always replace all non-merged entries.. 962 */ 963if(pos < istate->cache_nr &&ce_stage(ce) ==0) { 964while(ce_same_name(istate->cache[pos], ce)) { 965 ok_to_add =1; 966if(!remove_index_entry_at(istate, pos)) 967break; 968} 969} 970 971if(!ok_to_add) 972return-1; 973if(!verify_path(ce->name)) 974returnerror("Invalid path '%s'", ce->name); 975 976if(!skip_df_check && 977check_file_directory_conflict(istate, ce, pos, ok_to_replace)) { 978if(!ok_to_replace) 979returnerror("'%s' appears as both a file and as a directory", 980 ce->name); 981 pos =index_name_stage_pos(istate, ce->name,ce_namelen(ce),ce_stage(ce)); 982 pos = -pos-1; 983} 984return pos +1; 985} 986 987intadd_index_entry(struct index_state *istate,struct cache_entry *ce,int option) 988{ 989int pos; 990 991if(option & ADD_CACHE_JUST_APPEND) 992 pos = istate->cache_nr; 993else{ 994int ret; 995 ret =add_index_entry_with_check(istate, ce, option); 996if(ret <=0) 997return ret; 998 pos = ret -1; 999}10001001/* Make sure the array is big enough .. */1002ALLOC_GROW(istate->cache, istate->cache_nr +1, istate->cache_alloc);10031004/* Add it in.. */1005 istate->cache_nr++;1006if(istate->cache_nr > pos +1)1007memmove(istate->cache + pos +1,1008 istate->cache + pos,1009(istate->cache_nr - pos -1) *sizeof(ce));1010set_index_entry(istate, pos, ce);1011 istate->cache_changed |= CE_ENTRY_ADDED;1012return0;1013}10141015/*1016 * "refresh" does not calculate a new sha1 file or bring the1017 * cache up-to-date for mode/content changes. But what it1018 * _does_ do is to "re-match" the stat information of a file1019 * with the cache, so that you can refresh the cache for a1020 * file that hasn't been changed but where the stat entry is1021 * out of date.1022 *1023 * For example, you'd want to do this after doing a "git-read-tree",1024 * to link up the stat cache details with the proper files.1025 */1026static struct cache_entry *refresh_cache_ent(struct index_state *istate,1027struct cache_entry *ce,1028unsigned int options,int*err,1029int*changed_ret)1030{1031struct stat st;1032struct cache_entry *updated;1033int changed, size;1034int refresh = options & CE_MATCH_REFRESH;1035int ignore_valid = options & CE_MATCH_IGNORE_VALID;1036int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;1037int ignore_missing = options & CE_MATCH_IGNORE_MISSING;10381039if(!refresh ||ce_uptodate(ce))1040return ce;10411042/*1043 * CE_VALID or CE_SKIP_WORKTREE means the user promised us1044 * that the change to the work tree does not matter and told1045 * us not to worry.1046 */1047if(!ignore_skip_worktree &&ce_skip_worktree(ce)) {1048ce_mark_uptodate(ce);1049return ce;1050}1051if(!ignore_valid && (ce->ce_flags & CE_VALID)) {1052ce_mark_uptodate(ce);1053return ce;1054}10551056if(lstat(ce->name, &st) <0) {1057if(ignore_missing && errno == ENOENT)1058return ce;1059if(err)1060*err = errno;1061return NULL;1062}10631064 changed =ie_match_stat(istate, ce, &st, options);1065if(changed_ret)1066*changed_ret = changed;1067if(!changed) {1068/*1069 * The path is unchanged. If we were told to ignore1070 * valid bit, then we did the actual stat check and1071 * found that the entry is unmodified. If the entry1072 * is not marked VALID, this is the place to mark it1073 * valid again, under "assume unchanged" mode.1074 */1075if(ignore_valid && assume_unchanged &&1076!(ce->ce_flags & CE_VALID))1077;/* mark this one VALID again */1078else{1079/*1080 * We do not mark the index itself "modified"1081 * because CE_UPTODATE flag is in-core only;1082 * we are not going to write this change out.1083 */1084if(!S_ISGITLINK(ce->ce_mode))1085ce_mark_uptodate(ce);1086return ce;1087}1088}10891090if(ie_modified(istate, ce, &st, options)) {1091if(err)1092*err = EINVAL;1093return NULL;1094}10951096 size =ce_size(ce);1097 updated =xmalloc(size);1098memcpy(updated, ce, size);1099fill_stat_cache_info(updated, &st);1100/*1101 * If ignore_valid is not set, we should leave CE_VALID bit1102 * alone. Otherwise, paths marked with --no-assume-unchanged1103 * (i.e. things to be edited) will reacquire CE_VALID bit1104 * automatically, which is not really what we want.1105 */1106if(!ignore_valid && assume_unchanged &&1107!(ce->ce_flags & CE_VALID))1108 updated->ce_flags &= ~CE_VALID;11091110/* istate->cache_changed is updated in the caller */1111return updated;1112}11131114static voidshow_file(const char* fmt,const char* name,int in_porcelain,1115int* first,const char*header_msg)1116{1117if(in_porcelain && *first && header_msg) {1118printf("%s\n", header_msg);1119*first =0;1120}1121printf(fmt, name);1122}11231124intrefresh_index(struct index_state *istate,unsigned int flags,1125const struct pathspec *pathspec,1126char*seen,const char*header_msg)1127{1128int i;1129int has_errors =0;1130int really = (flags & REFRESH_REALLY) !=0;1131int allow_unmerged = (flags & REFRESH_UNMERGED) !=0;1132int quiet = (flags & REFRESH_QUIET) !=0;1133int not_new = (flags & REFRESH_IGNORE_MISSING) !=0;1134int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) !=0;1135int first =1;1136int in_porcelain = (flags & REFRESH_IN_PORCELAIN);1137unsigned int options = (CE_MATCH_REFRESH |1138(really ? CE_MATCH_IGNORE_VALID :0) |1139(not_new ? CE_MATCH_IGNORE_MISSING :0));1140const char*modified_fmt;1141const char*deleted_fmt;1142const char*typechange_fmt;1143const char*added_fmt;1144const char*unmerged_fmt;11451146 modified_fmt = (in_porcelain ?"M\t%s\n":"%s: needs update\n");1147 deleted_fmt = (in_porcelain ?"D\t%s\n":"%s: needs update\n");1148 typechange_fmt = (in_porcelain ?"T\t%s\n":"%sneeds update\n");1149 added_fmt = (in_porcelain ?"A\t%s\n":"%sneeds update\n");1150 unmerged_fmt = (in_porcelain ?"U\t%s\n":"%s: needs merge\n");1151for(i =0; i < istate->cache_nr; i++) {1152struct cache_entry *ce, *new;1153int cache_errno =0;1154int changed =0;1155int filtered =0;11561157 ce = istate->cache[i];1158if(ignore_submodules &&S_ISGITLINK(ce->ce_mode))1159continue;11601161if(pathspec && !ce_path_match(ce, pathspec, seen))1162 filtered =1;11631164if(ce_stage(ce)) {1165while((i < istate->cache_nr) &&1166!strcmp(istate->cache[i]->name, ce->name))1167 i++;1168 i--;1169if(allow_unmerged)1170continue;1171if(!filtered)1172show_file(unmerged_fmt, ce->name, in_porcelain,1173&first, header_msg);1174 has_errors =1;1175continue;1176}11771178if(filtered)1179continue;11801181new=refresh_cache_ent(istate, ce, options, &cache_errno, &changed);1182if(new== ce)1183continue;1184if(!new) {1185const char*fmt;11861187if(really && cache_errno == EINVAL) {1188/* If we are doing --really-refresh that1189 * means the index is not valid anymore.1190 */1191 ce->ce_flags &= ~CE_VALID;1192 istate->cache_changed |= CE_ENTRY_CHANGED;1193}1194if(quiet)1195continue;11961197if(cache_errno == ENOENT)1198 fmt = deleted_fmt;1199else if(ce->ce_flags & CE_INTENT_TO_ADD)1200 fmt = added_fmt;/* must be before other checks */1201else if(changed & TYPE_CHANGED)1202 fmt = typechange_fmt;1203else1204 fmt = modified_fmt;1205show_file(fmt,1206 ce->name, in_porcelain, &first, header_msg);1207 has_errors =1;1208continue;1209}12101211replace_index_entry(istate, i,new);1212}1213return has_errors;1214}12151216static struct cache_entry *refresh_cache_entry(struct cache_entry *ce,1217unsigned int options)1218{1219returnrefresh_cache_ent(&the_index, ce, options, NULL, NULL);1220}122112221223/*****************************************************************1224 * Index File I/O1225 *****************************************************************/12261227#define INDEX_FORMAT_DEFAULT 312281229static intindex_format_config(const char*var,const char*value,void*cb)1230{1231unsigned int*version = cb;1232if(!strcmp(var,"index.version")) {1233*version =git_config_int(var, value);1234return0;1235}1236return1;1237}12381239static unsigned intget_index_format_default(void)1240{1241char*envversion =getenv("GIT_INDEX_VERSION");1242char*endp;1243unsigned int version = INDEX_FORMAT_DEFAULT;12441245if(!envversion) {1246git_config(index_format_config, &version);1247if(version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1248warning(_("index.version set, but the value is invalid.\n"1249"Using version%i"), INDEX_FORMAT_DEFAULT);1250return INDEX_FORMAT_DEFAULT;1251}1252return version;1253}12541255 version =strtoul(envversion, &endp,10);1256if(*endp ||1257 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {1258warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"1259"Using version%i"), INDEX_FORMAT_DEFAULT);1260 version = INDEX_FORMAT_DEFAULT;1261}1262return version;1263}12641265/*1266 * dev/ino/uid/gid/size are also just tracked to the low 32 bits1267 * Again - this is just a (very strong in practice) heuristic that1268 * the inode hasn't changed.1269 *1270 * We save the fields in big-endian order to allow using the1271 * index file over NFS transparently.1272 */1273struct ondisk_cache_entry {1274struct cache_time ctime;1275struct cache_time mtime;1276uint32_t dev;1277uint32_t ino;1278uint32_t mode;1279uint32_t uid;1280uint32_t gid;1281uint32_t size;1282unsigned char sha1[20];1283uint16_t flags;1284char name[FLEX_ARRAY];/* more */1285};12861287/*1288 * This struct is used when CE_EXTENDED bit is 11289 * The struct must match ondisk_cache_entry exactly from1290 * ctime till flags1291 */1292struct ondisk_cache_entry_extended {1293struct cache_time ctime;1294struct cache_time mtime;1295uint32_t dev;1296uint32_t ino;1297uint32_t mode;1298uint32_t uid;1299uint32_t gid;1300uint32_t size;1301unsigned char sha1[20];1302uint16_t flags;1303uint16_t flags2;1304char name[FLEX_ARRAY];/* more */1305};13061307/* These are only used for v3 or lower */1308#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)1309#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)1310#define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)1311#define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \1312 ondisk_cache_entry_extended_size(ce_namelen(ce)) : \1313 ondisk_cache_entry_size(ce_namelen(ce)))13141315static intverify_hdr(struct cache_header *hdr,unsigned long size)1316{1317 git_SHA_CTX c;1318unsigned char sha1[20];1319int hdr_version;13201321if(hdr->hdr_signature !=htonl(CACHE_SIGNATURE))1322returnerror("bad signature");1323 hdr_version =ntohl(hdr->hdr_version);1324if(hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)1325returnerror("bad index version%d", hdr_version);1326git_SHA1_Init(&c);1327git_SHA1_Update(&c, hdr, size -20);1328git_SHA1_Final(sha1, &c);1329if(hashcmp(sha1, (unsigned char*)hdr + size -20))1330returnerror("bad index file sha1 signature");1331return0;1332}13331334static intread_index_extension(struct index_state *istate,1335const char*ext,void*data,unsigned long sz)1336{1337switch(CACHE_EXT(ext)) {1338case CACHE_EXT_TREE:1339 istate->cache_tree =cache_tree_read(data, sz);1340break;1341case CACHE_EXT_RESOLVE_UNDO:1342 istate->resolve_undo =resolve_undo_read(data, sz);1343break;1344case CACHE_EXT_LINK:1345if(read_link_extension(istate, data, sz))1346return-1;1347break;1348default:1349if(*ext <'A'||'Z'< *ext)1350returnerror("index uses %.4s extension, which we do not understand",1351 ext);1352fprintf(stderr,"ignoring %.4s extension\n", ext);1353break;1354}1355return0;1356}13571358intread_index(struct index_state *istate)1359{1360returnread_index_from(istate,get_index_file());1361}13621363static struct cache_entry *cache_entry_from_ondisk(struct ondisk_cache_entry *ondisk,1364unsigned int flags,1365const char*name,1366size_t len)1367{1368struct cache_entry *ce =xmalloc(cache_entry_size(len));13691370 ce->ce_stat_data.sd_ctime.sec =get_be32(&ondisk->ctime.sec);1371 ce->ce_stat_data.sd_mtime.sec =get_be32(&ondisk->mtime.sec);1372 ce->ce_stat_data.sd_ctime.nsec =get_be32(&ondisk->ctime.nsec);1373 ce->ce_stat_data.sd_mtime.nsec =get_be32(&ondisk->mtime.nsec);1374 ce->ce_stat_data.sd_dev =get_be32(&ondisk->dev);1375 ce->ce_stat_data.sd_ino =get_be32(&ondisk->ino);1376 ce->ce_mode =get_be32(&ondisk->mode);1377 ce->ce_stat_data.sd_uid =get_be32(&ondisk->uid);1378 ce->ce_stat_data.sd_gid =get_be32(&ondisk->gid);1379 ce->ce_stat_data.sd_size =get_be32(&ondisk->size);1380 ce->ce_flags = flags & ~CE_NAMEMASK;1381 ce->ce_namelen = len;1382 ce->index =0;1383hashcpy(ce->sha1, ondisk->sha1);1384memcpy(ce->name, name, len);1385 ce->name[len] ='\0';1386return ce;1387}13881389/*1390 * Adjacent cache entries tend to share the leading paths, so it makes1391 * sense to only store the differences in later entries. In the v41392 * on-disk format of the index, each on-disk cache entry stores the1393 * number of bytes to be stripped from the end of the previous name,1394 * and the bytes to append to the result, to come up with its name.1395 */1396static unsigned longexpand_name_field(struct strbuf *name,const char*cp_)1397{1398const unsigned char*ep, *cp = (const unsigned char*)cp_;1399size_t len =decode_varint(&cp);14001401if(name->len < len)1402die("malformed name field in the index");1403strbuf_remove(name, name->len - len, len);1404for(ep = cp; *ep; ep++)1405;/* find the end */1406strbuf_add(name, cp, ep - cp);1407return(const char*)ep +1- cp_;1408}14091410static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk,1411unsigned long*ent_size,1412struct strbuf *previous_name)1413{1414struct cache_entry *ce;1415size_t len;1416const char*name;1417unsigned int flags;14181419/* On-disk flags are just 16 bits */1420 flags =get_be16(&ondisk->flags);1421 len = flags & CE_NAMEMASK;14221423if(flags & CE_EXTENDED) {1424struct ondisk_cache_entry_extended *ondisk2;1425int extended_flags;1426 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;1427 extended_flags =get_be16(&ondisk2->flags2) <<16;1428/* We do not yet understand any bit out of CE_EXTENDED_FLAGS */1429if(extended_flags & ~CE_EXTENDED_FLAGS)1430die("Unknown index entry format%08x", extended_flags);1431 flags |= extended_flags;1432 name = ondisk2->name;1433}1434else1435 name = ondisk->name;14361437if(!previous_name) {1438/* v3 and earlier */1439if(len == CE_NAMEMASK)1440 len =strlen(name);1441 ce =cache_entry_from_ondisk(ondisk, flags, name, len);14421443*ent_size =ondisk_ce_size(ce);1444}else{1445unsigned long consumed;1446 consumed =expand_name_field(previous_name, name);1447 ce =cache_entry_from_ondisk(ondisk, flags,1448 previous_name->buf,1449 previous_name->len);14501451*ent_size = (name - ((char*)ondisk)) + consumed;1452}1453return ce;1454}14551456/* remember to discard_cache() before reading a different cache! */1457static intdo_read_index(struct index_state *istate,const char*path,1458int must_exist)1459{1460int fd, i;1461struct stat st;1462unsigned long src_offset;1463struct cache_header *hdr;1464void*mmap;1465size_t mmap_size;1466struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;14671468if(istate->initialized)1469return istate->cache_nr;14701471 istate->timestamp.sec =0;1472 istate->timestamp.nsec =0;1473 fd =open(path, O_RDONLY);1474if(fd <0) {1475if(!must_exist && errno == ENOENT)1476return0;1477die_errno("%s: index file open failed", path);1478}14791480if(fstat(fd, &st))1481die_errno("cannot stat the open index");14821483 mmap_size =xsize_t(st.st_size);1484if(mmap_size <sizeof(struct cache_header) +20)1485die("index file smaller than expected");14861487 mmap =xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd,0);1488if(mmap == MAP_FAILED)1489die_errno("unable to map index file");1490close(fd);14911492 hdr = mmap;1493if(verify_hdr(hdr, mmap_size) <0)1494goto unmap;14951496hashcpy(istate->sha1, (const unsigned char*)hdr + mmap_size -20);1497 istate->version =ntohl(hdr->hdr_version);1498 istate->cache_nr =ntohl(hdr->hdr_entries);1499 istate->cache_alloc =alloc_nr(istate->cache_nr);1500 istate->cache =xcalloc(istate->cache_alloc,sizeof(*istate->cache));1501 istate->initialized =1;15021503if(istate->version ==4)1504 previous_name = &previous_name_buf;1505else1506 previous_name = NULL;15071508 src_offset =sizeof(*hdr);1509for(i =0; i < istate->cache_nr; i++) {1510struct ondisk_cache_entry *disk_ce;1511struct cache_entry *ce;1512unsigned long consumed;15131514 disk_ce = (struct ondisk_cache_entry *)((char*)mmap + src_offset);1515 ce =create_from_disk(disk_ce, &consumed, previous_name);1516set_index_entry(istate, i, ce);15171518 src_offset += consumed;1519}1520strbuf_release(&previous_name_buf);1521 istate->timestamp.sec = st.st_mtime;1522 istate->timestamp.nsec =ST_MTIME_NSEC(st);15231524while(src_offset <= mmap_size -20-8) {1525/* After an array of active_nr index entries,1526 * there can be arbitrary number of extended1527 * sections, each of which is prefixed with1528 * extension name (4-byte) and section length1529 * in 4-byte network byte order.1530 */1531uint32_t extsize;1532memcpy(&extsize, (char*)mmap + src_offset +4,4);1533 extsize =ntohl(extsize);1534if(read_index_extension(istate,1535(const char*) mmap + src_offset,1536(char*) mmap + src_offset +8,1537 extsize) <0)1538goto unmap;1539 src_offset +=8;1540 src_offset += extsize;1541}1542munmap(mmap, mmap_size);1543return istate->cache_nr;15441545unmap:1546munmap(mmap, mmap_size);1547die("index file corrupt");1548}15491550intread_index_from(struct index_state *istate,const char*path)1551{1552struct split_index *split_index;1553int ret;15541555/* istate->initialized covers both .git/index and .git/sharedindex.xxx */1556if(istate->initialized)1557return istate->cache_nr;15581559 ret =do_read_index(istate, path,0);1560 split_index = istate->split_index;1561if(!split_index)1562return ret;15631564if(is_null_sha1(split_index->base_sha1))1565return ret;1566if(istate->cache_nr)1567die("index in split-index mode must contain no entries");15681569if(split_index->base)1570discard_index(split_index->base);1571else1572 split_index->base =xcalloc(1,sizeof(*split_index->base));1573 ret =do_read_index(split_index->base,1574git_path("sharedindex.%s",1575sha1_to_hex(split_index->base_sha1)),1);1576if(hashcmp(split_index->base_sha1, split_index->base->sha1))1577die("broken index, expect%sin%s, got%s",1578sha1_to_hex(split_index->base_sha1),1579git_path("sharedindex.%s",1580sha1_to_hex(split_index->base_sha1)),1581sha1_to_hex(split_index->base->sha1));1582merge_base_index(istate);1583return ret;1584}15851586intis_index_unborn(struct index_state *istate)1587{1588return(!istate->cache_nr && !istate->timestamp.sec);1589}15901591intdiscard_index(struct index_state *istate)1592{1593int i;15941595for(i =0; i < istate->cache_nr; i++) {1596if(istate->cache[i]->index &&1597 istate->split_index &&1598 istate->split_index->base &&1599 istate->cache[i]->index <= istate->split_index->base->cache_nr &&1600 istate->cache[i] == istate->split_index->base->cache[istate->cache[i]->index -1])1601continue;1602free(istate->cache[i]);1603}1604resolve_undo_clear_index(istate);1605 istate->cache_nr =0;1606 istate->cache_changed =0;1607 istate->timestamp.sec =0;1608 istate->timestamp.nsec =0;1609free_name_hash(istate);1610cache_tree_free(&(istate->cache_tree));1611 istate->initialized =0;1612free(istate->cache);1613 istate->cache = NULL;1614 istate->cache_alloc =0;1615discard_split_index(istate);1616return0;1617}16181619intunmerged_index(const struct index_state *istate)1620{1621int i;1622for(i =0; i < istate->cache_nr; i++) {1623if(ce_stage(istate->cache[i]))1624return1;1625}1626return0;1627}16281629#define WRITE_BUFFER_SIZE 81921630static unsigned char write_buffer[WRITE_BUFFER_SIZE];1631static unsigned long write_buffer_len;16321633static intce_write_flush(git_SHA_CTX *context,int fd)1634{1635unsigned int buffered = write_buffer_len;1636if(buffered) {1637git_SHA1_Update(context, write_buffer, buffered);1638if(write_in_full(fd, write_buffer, buffered) != buffered)1639return-1;1640 write_buffer_len =0;1641}1642return0;1643}16441645static intce_write(git_SHA_CTX *context,int fd,void*data,unsigned int len)1646{1647while(len) {1648unsigned int buffered = write_buffer_len;1649unsigned int partial = WRITE_BUFFER_SIZE - buffered;1650if(partial > len)1651 partial = len;1652memcpy(write_buffer + buffered, data, partial);1653 buffered += partial;1654if(buffered == WRITE_BUFFER_SIZE) {1655 write_buffer_len = buffered;1656if(ce_write_flush(context, fd))1657return-1;1658 buffered =0;1659}1660 write_buffer_len = buffered;1661 len -= partial;1662 data = (char*) data + partial;1663}1664return0;1665}16661667static intwrite_index_ext_header(git_SHA_CTX *context,int fd,1668unsigned int ext,unsigned int sz)1669{1670 ext =htonl(ext);1671 sz =htonl(sz);1672return((ce_write(context, fd, &ext,4) <0) ||1673(ce_write(context, fd, &sz,4) <0)) ? -1:0;1674}16751676static intce_flush(git_SHA_CTX *context,int fd,unsigned char*sha1)1677{1678unsigned int left = write_buffer_len;16791680if(left) {1681 write_buffer_len =0;1682git_SHA1_Update(context, write_buffer, left);1683}16841685/* Flush first if not enough space for SHA1 signature */1686if(left +20> WRITE_BUFFER_SIZE) {1687if(write_in_full(fd, write_buffer, left) != left)1688return-1;1689 left =0;1690}16911692/* Append the SHA1 signature at the end */1693git_SHA1_Final(write_buffer + left, context);1694hashcpy(sha1, write_buffer + left);1695 left +=20;1696return(write_in_full(fd, write_buffer, left) != left) ? -1:0;1697}16981699static voidce_smudge_racily_clean_entry(struct cache_entry *ce)1700{1701/*1702 * The only thing we care about in this function is to smudge the1703 * falsely clean entry due to touch-update-touch race, so we leave1704 * everything else as they are. We are called for entries whose1705 * ce_stat_data.sd_mtime match the index file mtime.1706 *1707 * Note that this actually does not do much for gitlinks, for1708 * which ce_match_stat_basic() always goes to the actual1709 * contents. The caller checks with is_racy_timestamp() which1710 * always says "no" for gitlinks, so we are not called for them ;-)1711 */1712struct stat st;17131714if(lstat(ce->name, &st) <0)1715return;1716if(ce_match_stat_basic(ce, &st))1717return;1718if(ce_modified_check_fs(ce, &st)) {1719/* This is "racily clean"; smudge it. Note that this1720 * is a tricky code. At first glance, it may appear1721 * that it can break with this sequence:1722 *1723 * $ echo xyzzy >frotz1724 * $ git-update-index --add frotz1725 * $ : >frotz1726 * $ sleep 31727 * $ echo filfre >nitfol1728 * $ git-update-index --add nitfol1729 *1730 * but it does not. When the second update-index runs,1731 * it notices that the entry "frotz" has the same timestamp1732 * as index, and if we were to smudge it by resetting its1733 * size to zero here, then the object name recorded1734 * in index is the 6-byte file but the cached stat information1735 * becomes zero --- which would then match what we would1736 * obtain from the filesystem next time we stat("frotz").1737 *1738 * However, the second update-index, before calling1739 * this function, notices that the cached size is 61740 * bytes and what is on the filesystem is an empty1741 * file, and never calls us, so the cached size information1742 * for "frotz" stays 6 which does not match the filesystem.1743 */1744 ce->ce_stat_data.sd_size =0;1745}1746}17471748/* Copy miscellaneous fields but not the name */1749static char*copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,1750struct cache_entry *ce)1751{1752short flags;17531754 ondisk->ctime.sec =htonl(ce->ce_stat_data.sd_ctime.sec);1755 ondisk->mtime.sec =htonl(ce->ce_stat_data.sd_mtime.sec);1756 ondisk->ctime.nsec =htonl(ce->ce_stat_data.sd_ctime.nsec);1757 ondisk->mtime.nsec =htonl(ce->ce_stat_data.sd_mtime.nsec);1758 ondisk->dev =htonl(ce->ce_stat_data.sd_dev);1759 ondisk->ino =htonl(ce->ce_stat_data.sd_ino);1760 ondisk->mode =htonl(ce->ce_mode);1761 ondisk->uid =htonl(ce->ce_stat_data.sd_uid);1762 ondisk->gid =htonl(ce->ce_stat_data.sd_gid);1763 ondisk->size =htonl(ce->ce_stat_data.sd_size);1764hashcpy(ondisk->sha1, ce->sha1);17651766 flags = ce->ce_flags & ~CE_NAMEMASK;1767 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK :ce_namelen(ce));1768 ondisk->flags =htons(flags);1769if(ce->ce_flags & CE_EXTENDED) {1770struct ondisk_cache_entry_extended *ondisk2;1771 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;1772 ondisk2->flags2 =htons((ce->ce_flags & CE_EXTENDED_FLAGS) >>16);1773return ondisk2->name;1774}1775else{1776return ondisk->name;1777}1778}17791780static intce_write_entry(git_SHA_CTX *c,int fd,struct cache_entry *ce,1781struct strbuf *previous_name)1782{1783int size;1784struct ondisk_cache_entry *ondisk;1785char*name;1786int result;17871788if(!previous_name) {1789 size =ondisk_ce_size(ce);1790 ondisk =xcalloc(1, size);1791 name =copy_cache_entry_to_ondisk(ondisk, ce);1792memcpy(name, ce->name,ce_namelen(ce));1793}else{1794int common, to_remove, prefix_size;1795unsigned char to_remove_vi[16];1796for(common =0;1797(ce->name[common] &&1798 common < previous_name->len &&1799 ce->name[common] == previous_name->buf[common]);1800 common++)1801;/* still matching */1802 to_remove = previous_name->len - common;1803 prefix_size =encode_varint(to_remove, to_remove_vi);18041805if(ce->ce_flags & CE_EXTENDED)1806 size =offsetof(struct ondisk_cache_entry_extended, name);1807else1808 size =offsetof(struct ondisk_cache_entry, name);1809 size += prefix_size + (ce_namelen(ce) - common +1);18101811 ondisk =xcalloc(1, size);1812 name =copy_cache_entry_to_ondisk(ondisk, ce);1813memcpy(name, to_remove_vi, prefix_size);1814memcpy(name + prefix_size, ce->name + common,ce_namelen(ce) - common);18151816strbuf_splice(previous_name, common, to_remove,1817 ce->name + common,ce_namelen(ce) - common);1818}18191820 result =ce_write(c, fd, ondisk, size);1821free(ondisk);1822return result;1823}18241825static inthas_racy_timestamp(struct index_state *istate)1826{1827int entries = istate->cache_nr;1828int i;18291830for(i =0; i < entries; i++) {1831struct cache_entry *ce = istate->cache[i];1832if(is_racy_timestamp(istate, ce))1833return1;1834}1835return0;1836}18371838/*1839 * Opportunistically update the index but do not complain if we can't1840 */1841voidupdate_index_if_able(struct index_state *istate,struct lock_file *lockfile)1842{1843if((istate->cache_changed ||has_racy_timestamp(istate)) &&1844write_locked_index(istate, lockfile, COMMIT_LOCK))1845rollback_lock_file(lockfile);1846}18471848static intdo_write_index(struct index_state *istate,int newfd)1849{1850 git_SHA_CTX c;1851struct cache_header hdr;1852int i, err, removed, extended, hdr_version;1853struct cache_entry **cache = istate->cache;1854int entries = istate->cache_nr;1855struct stat st;1856struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;18571858for(i = removed = extended =0; i < entries; i++) {1859if(cache[i]->ce_flags & CE_REMOVE)1860 removed++;18611862/* reduce extended entries if possible */1863 cache[i]->ce_flags &= ~CE_EXTENDED;1864if(cache[i]->ce_flags & CE_EXTENDED_FLAGS) {1865 extended++;1866 cache[i]->ce_flags |= CE_EXTENDED;1867}1868}18691870if(!istate->version)1871 istate->version =get_index_format_default();18721873/* demote version 3 to version 2 when the latter suffices */1874if(istate->version ==3|| istate->version ==2)1875 istate->version = extended ?3:2;18761877 hdr_version = istate->version;18781879 hdr.hdr_signature =htonl(CACHE_SIGNATURE);1880 hdr.hdr_version =htonl(hdr_version);1881 hdr.hdr_entries =htonl(entries - removed);18821883git_SHA1_Init(&c);1884if(ce_write(&c, newfd, &hdr,sizeof(hdr)) <0)1885return-1;18861887 previous_name = (hdr_version ==4) ? &previous_name_buf : NULL;1888for(i =0; i < entries; i++) {1889struct cache_entry *ce = cache[i];1890if(ce->ce_flags & CE_REMOVE)1891continue;1892if(!ce_uptodate(ce) &&is_racy_timestamp(istate, ce))1893ce_smudge_racily_clean_entry(ce);1894if(is_null_sha1(ce->sha1)) {1895static const char msg[] ="cache entry has null sha1:%s";1896static int allow = -1;18971898if(allow <0)1899 allow =git_env_bool("GIT_ALLOW_NULL_SHA1",0);1900if(allow)1901warning(msg, ce->name);1902else1903returnerror(msg, ce->name);1904}1905if(ce_write_entry(&c, newfd, ce, previous_name) <0)1906return-1;1907}1908strbuf_release(&previous_name_buf);19091910/* Write extension data here */1911if(istate->split_index) {1912struct strbuf sb = STRBUF_INIT;19131914 err =write_link_extension(&sb, istate) <0||1915write_index_ext_header(&c, newfd, CACHE_EXT_LINK,1916 sb.len) <0||1917ce_write(&c, newfd, sb.buf, sb.len) <0;1918strbuf_release(&sb);1919if(err)1920return-1;1921}1922if(istate->cache_tree) {1923struct strbuf sb = STRBUF_INIT;19241925cache_tree_write(&sb, istate->cache_tree);1926 err =write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) <01927||ce_write(&c, newfd, sb.buf, sb.len) <0;1928strbuf_release(&sb);1929if(err)1930return-1;1931}1932if(istate->resolve_undo) {1933struct strbuf sb = STRBUF_INIT;19341935resolve_undo_write(&sb, istate->resolve_undo);1936 err =write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,1937 sb.len) <01938||ce_write(&c, newfd, sb.buf, sb.len) <0;1939strbuf_release(&sb);1940if(err)1941return-1;1942}19431944if(ce_flush(&c, newfd, istate->sha1) ||fstat(newfd, &st))1945return-1;1946 istate->timestamp.sec = (unsigned int)st.st_mtime;1947 istate->timestamp.nsec =ST_MTIME_NSEC(st);1948return0;1949}19501951voidset_alternate_index_output(const char*name)1952{1953 alternate_index_output = name;1954}19551956static intcommit_locked_index(struct lock_file *lk)1957{1958if(alternate_index_output) {1959if(lk->fd >=0&&close_lock_file(lk))1960return-1;1961if(rename(lk->filename, alternate_index_output))1962return-1;1963 lk->filename[0] =0;1964return0;1965}else{1966returncommit_lock_file(lk);1967}1968}19691970static intdo_write_locked_index(struct index_state *istate,struct lock_file *lock,1971unsigned flags)1972{1973int ret =do_write_index(istate, lock->fd);1974if(ret)1975return ret;1976assert((flags & (COMMIT_LOCK | CLOSE_LOCK)) !=1977(COMMIT_LOCK | CLOSE_LOCK));1978if(flags & COMMIT_LOCK)1979returncommit_locked_index(lock);1980else if(flags & CLOSE_LOCK)1981returnclose_lock_file(lock);1982else1983return ret;1984}19851986static intwrite_split_index(struct index_state *istate,1987struct lock_file *lock,1988unsigned flags)1989{1990int ret;1991prepare_to_write_split_index(istate);1992 ret =do_write_locked_index(istate, lock, flags);1993finish_writing_split_index(istate);1994return ret;1995}19961997intwrite_locked_index(struct index_state *istate,struct lock_file *lock,1998unsigned flags)1999{2000struct split_index *si = istate->split_index;20012002if(!si || (istate->cache_changed & ~EXTMASK)) {2003if(si)2004hashclr(si->base_sha1);2005returndo_write_locked_index(istate, lock, flags);2006}20072008returnwrite_split_index(istate, lock, flags);2009}20102011/*2012 * Read the index file that is potentially unmerged into given2013 * index_state, dropping any unmerged entries. Returns true if2014 * the index is unmerged. Callers who want to refuse to work2015 * from an unmerged state can call this and check its return value,2016 * instead of calling read_cache().2017 */2018intread_index_unmerged(struct index_state *istate)2019{2020int i;2021int unmerged =0;20222023read_index(istate);2024for(i =0; i < istate->cache_nr; i++) {2025struct cache_entry *ce = istate->cache[i];2026struct cache_entry *new_ce;2027int size, len;20282029if(!ce_stage(ce))2030continue;2031 unmerged =1;2032 len =ce_namelen(ce);2033 size =cache_entry_size(len);2034 new_ce =xcalloc(1, size);2035memcpy(new_ce->name, ce->name, len);2036 new_ce->ce_flags =create_ce_flags(0) | CE_CONFLICTED;2037 new_ce->ce_namelen = len;2038 new_ce->ce_mode = ce->ce_mode;2039if(add_index_entry(istate, new_ce,0))2040returnerror("%s: cannot drop to stage #0",2041 new_ce->name);2042 i =index_name_pos(istate, new_ce->name, len);2043}2044return unmerged;2045}20462047/*2048 * Returns 1 if the path is an "other" path with respect to2049 * the index; that is, the path is not mentioned in the index at all,2050 * either as a file, a directory with some files in the index,2051 * or as an unmerged entry.2052 *2053 * We helpfully remove a trailing "/" from directories so that2054 * the output of read_directory can be used as-is.2055 */2056intindex_name_is_other(const struct index_state *istate,const char*name,2057int namelen)2058{2059int pos;2060if(namelen && name[namelen -1] =='/')2061 namelen--;2062 pos =index_name_pos(istate, name, namelen);2063if(0<= pos)2064return0;/* exact match */2065 pos = -pos -1;2066if(pos < istate->cache_nr) {2067struct cache_entry *ce = istate->cache[pos];2068if(ce_namelen(ce) == namelen &&2069!memcmp(ce->name, name, namelen))2070return0;/* Yup, this one exists unmerged */2071}2072return1;2073}20742075void*read_blob_data_from_index(struct index_state *istate,const char*path,unsigned long*size)2076{2077int pos, len;2078unsigned long sz;2079enum object_type type;2080void*data;20812082 len =strlen(path);2083 pos =index_name_pos(istate, path, len);2084if(pos <0) {2085/*2086 * We might be in the middle of a merge, in which2087 * case we would read stage #2 (ours).2088 */2089int i;2090for(i = -pos -1;2091(pos <0&& i < istate->cache_nr &&2092!strcmp(istate->cache[i]->name, path));2093 i++)2094if(ce_stage(istate->cache[i]) ==2)2095 pos = i;2096}2097if(pos <0)2098return NULL;2099 data =read_sha1_file(istate->cache[pos]->sha1, &type, &sz);2100if(!data || type != OBJ_BLOB) {2101free(data);2102return NULL;2103}2104if(size)2105*size = sz;2106return data;2107}21082109voidstat_validity_clear(struct stat_validity *sv)2110{2111free(sv->sd);2112 sv->sd = NULL;2113}21142115intstat_validity_check(struct stat_validity *sv,const char*path)2116{2117struct stat st;21182119if(stat(path, &st) <0)2120return sv->sd == NULL;2121if(!sv->sd)2122return0;2123returnS_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);2124}21252126voidstat_validity_update(struct stat_validity *sv,int fd)2127{2128struct stat st;21292130if(fstat(fd, &st) <0|| !S_ISREG(st.st_mode))2131stat_validity_clear(sv);2132else{2133if(!sv->sd)2134 sv->sd =xcalloc(1,sizeof(struct stat_data));2135fill_stat_data(sv->sd, &st);2136}2137}