1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9struct ref_lock { 10char*ref_name; 11char*orig_ref_name; 12struct lock_file *lk; 13struct object_id old_oid; 14}; 15 16/* 17 * How to handle various characters in refnames: 18 * 0: An acceptable character for refs 19 * 1: End-of-component 20 * 2: ., look for a preceding . to reject .. in refs 21 * 3: {, look for a preceding @ to reject @{ in refs 22 * 4: A bad character: ASCII control characters, and 23 * ":", "?", "[", "\", "^", "~", SP, or TAB 24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,5,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag in ref_update::flags when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Used as a flag in ref_update::flags when the reference should be 51 * updated to new_sha1. 52 */ 53#define REF_HAVE_NEW 0x08 54 55/* 56 * Used as a flag in ref_update::flags when old_sha1 should be 57 * checked. 58 */ 59#define REF_HAVE_OLD 0x10 60 61/* 62 * Used as a flag in ref_update::flags when the lockfile needs to be 63 * committed. 64 */ 65#define REF_NEEDS_COMMIT 0x20 66 67/* 68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a 69 * value to ref_update::flags 70 */ 71 72/* 73 * Try to read one refname component from the front of refname. 74 * Return the length of the component found, or -1 if the component is 75 * not legal. It is legal if it is something reasonable to have under 76 * ".git/refs/"; We do not like it if: 77 * 78 * - any path component of it begins with ".", or 79 * - it has double dots "..", or 80 * - it has ASCII control characters, or 81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 83 * - it ends with a "/", or 84 * - it ends with ".lock", or 85 * - it contains a "@{" portion 86 */ 87static intcheck_refname_component(const char*refname,int*flags) 88{ 89const char*cp; 90char last ='\0'; 91 92for(cp = refname; ; cp++) { 93int ch = *cp &255; 94unsigned char disp = refname_disposition[ch]; 95switch(disp) { 96case1: 97goto out; 98case2: 99if(last =='.') 100return-1;/* Refname contains "..". */ 101break; 102case3: 103if(last =='@') 104return-1;/* Refname contains "@{". */ 105break; 106case4: 107return-1; 108case5: 109if(!(*flags & REFNAME_REFSPEC_PATTERN)) 110return-1;/* refspec can't be a pattern */ 111 112/* 113 * Unset the pattern flag so that we only accept 114 * a single asterisk for one side of refspec. 115 */ 116*flags &= ~ REFNAME_REFSPEC_PATTERN; 117break; 118} 119 last = ch; 120} 121out: 122if(cp == refname) 123return0;/* Component has zero length. */ 124if(refname[0] =='.') 125return-1;/* Component starts with '.'. */ 126if(cp - refname >= LOCK_SUFFIX_LEN && 127!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 128return-1;/* Refname ends with ".lock". */ 129return cp - refname; 130} 131 132intcheck_refname_format(const char*refname,int flags) 133{ 134int component_len, component_count =0; 135 136if(!strcmp(refname,"@")) 137/* Refname is a single character '@'. */ 138return-1; 139 140while(1) { 141/* We are at the start of a path component. */ 142 component_len =check_refname_component(refname, &flags); 143if(component_len <=0) 144return-1; 145 146 component_count++; 147if(refname[component_len] =='\0') 148break; 149/* Skip to next component. */ 150 refname += component_len +1; 151} 152 153if(refname[component_len -1] =='.') 154return-1;/* Refname ends with '.'. */ 155if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 156return-1;/* Refname has only one component. */ 157return0; 158} 159 160struct ref_entry; 161 162/* 163 * Information used (along with the information in ref_entry) to 164 * describe a single cached reference. This data structure only 165 * occurs embedded in a union in struct ref_entry, and only when 166 * (ref_entry->flag & REF_DIR) is zero. 167 */ 168struct ref_value { 169/* 170 * The name of the object to which this reference resolves 171 * (which may be a tag object). If REF_ISBROKEN, this is 172 * null. If REF_ISSYMREF, then this is the name of the object 173 * referred to by the last reference in the symlink chain. 174 */ 175struct object_id oid; 176 177/* 178 * If REF_KNOWS_PEELED, then this field holds the peeled value 179 * of this reference, or null if the reference is known not to 180 * be peelable. See the documentation for peel_ref() for an 181 * exact definition of "peelable". 182 */ 183struct object_id peeled; 184}; 185 186struct ref_cache; 187 188/* 189 * Information used (along with the information in ref_entry) to 190 * describe a level in the hierarchy of references. This data 191 * structure only occurs embedded in a union in struct ref_entry, and 192 * only when (ref_entry.flag & REF_DIR) is set. In that case, 193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 194 * in the directory have already been read: 195 * 196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 197 * or packed references, already read. 198 * 199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 200 * references that hasn't been read yet (nor has any of its 201 * subdirectories). 202 * 203 * Entries within a directory are stored within a growable array of 204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 205 * sorted are sorted by their component name in strcmp() order and the 206 * remaining entries are unsorted. 207 * 208 * Loose references are read lazily, one directory at a time. When a 209 * directory of loose references is read, then all of the references 210 * in that directory are stored, and REF_INCOMPLETE stubs are created 211 * for any subdirectories, but the subdirectories themselves are not 212 * read. The reading is triggered by get_ref_dir(). 213 */ 214struct ref_dir { 215int nr, alloc; 216 217/* 218 * Entries with index 0 <= i < sorted are sorted by name. New 219 * entries are appended to the list unsorted, and are sorted 220 * only when required; thus we avoid the need to sort the list 221 * after the addition of every reference. 222 */ 223int sorted; 224 225/* A pointer to the ref_cache that contains this ref_dir. */ 226struct ref_cache *ref_cache; 227 228struct ref_entry **entries; 229}; 230 231/* 232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 234 * public values; see refs.h. 235 */ 236 237/* 238 * The field ref_entry->u.value.peeled of this value entry contains 239 * the correct peeled value for the reference, which might be 240 * null_sha1 if the reference is not a tag or if it is broken. 241 */ 242#define REF_KNOWS_PEELED 0x10 243 244/* ref_entry represents a directory of references */ 245#define REF_DIR 0x20 246 247/* 248 * Entry has not yet been read from disk (used only for REF_DIR 249 * entries representing loose references) 250 */ 251#define REF_INCOMPLETE 0x40 252 253/* 254 * A ref_entry represents either a reference or a "subdirectory" of 255 * references. 256 * 257 * Each directory in the reference namespace is represented by a 258 * ref_entry with (flags & REF_DIR) set and containing a subdir member 259 * that holds the entries in that directory that have been read so 260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 262 * used for loose reference directories. 263 * 264 * References are represented by a ref_entry with (flags & REF_DIR) 265 * unset and a value member that describes the reference's value. The 266 * flag member is at the ref_entry level, but it is also needed to 267 * interpret the contents of the value field (in other words, a 268 * ref_value object is not very much use without the enclosing 269 * ref_entry). 270 * 271 * Reference names cannot end with slash and directories' names are 272 * always stored with a trailing slash (except for the top-level 273 * directory, which is always denoted by ""). This has two nice 274 * consequences: (1) when the entries in each subdir are sorted 275 * lexicographically by name (as they usually are), the references in 276 * a whole tree can be generated in lexicographic order by traversing 277 * the tree in left-to-right, depth-first order; (2) the names of 278 * references and subdirectories cannot conflict, and therefore the 279 * presence of an empty subdirectory does not block the creation of a 280 * similarly-named reference. (The fact that reference names with the 281 * same leading components can conflict *with each other* is a 282 * separate issue that is regulated by verify_refname_available().) 283 * 284 * Please note that the name field contains the fully-qualified 285 * reference (or subdirectory) name. Space could be saved by only 286 * storing the relative names. But that would require the full names 287 * to be generated on the fly when iterating in do_for_each_ref(), and 288 * would break callback functions, who have always been able to assume 289 * that the name strings that they are passed will not be freed during 290 * the iteration. 291 */ 292struct ref_entry { 293unsigned char flag;/* ISSYMREF? ISPACKED? */ 294union{ 295struct ref_value value;/* if not (flags&REF_DIR) */ 296struct ref_dir subdir;/* if (flags&REF_DIR) */ 297} u; 298/* 299 * The full name of the reference (e.g., "refs/heads/master") 300 * or the full name of the directory with a trailing slash 301 * (e.g., "refs/heads/"): 302 */ 303char name[FLEX_ARRAY]; 304}; 305 306static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 307 308static struct ref_dir *get_ref_dir(struct ref_entry *entry) 309{ 310struct ref_dir *dir; 311assert(entry->flag & REF_DIR); 312 dir = &entry->u.subdir; 313if(entry->flag & REF_INCOMPLETE) { 314read_loose_refs(entry->name, dir); 315 entry->flag &= ~REF_INCOMPLETE; 316} 317return dir; 318} 319 320/* 321 * Check if a refname is safe. 322 * For refs that start with "refs/" we consider it safe as long they do 323 * not try to resolve to outside of refs/. 324 * 325 * For all other refs we only consider them safe iff they only contain 326 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 327 * "config"). 328 */ 329static intrefname_is_safe(const char*refname) 330{ 331if(starts_with(refname,"refs/")) { 332char*buf; 333int result; 334 335 buf =xmalloc(strlen(refname) +1); 336/* 337 * Does the refname try to escape refs/? 338 * For example: refs/foo/../bar is safe but refs/foo/../../bar 339 * is not. 340 */ 341 result = !normalize_path_copy(buf, refname +strlen("refs/")); 342free(buf); 343return result; 344} 345while(*refname) { 346if(!isupper(*refname) && *refname !='_') 347return0; 348 refname++; 349} 350return1; 351} 352 353static struct ref_entry *create_ref_entry(const char*refname, 354const unsigned char*sha1,int flag, 355int check_name) 356{ 357int len; 358struct ref_entry *ref; 359 360if(check_name && 361check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 362die("Reference has invalid format: '%s'", refname); 363 len =strlen(refname) +1; 364 ref =xmalloc(sizeof(struct ref_entry) + len); 365hashcpy(ref->u.value.oid.hash, sha1); 366oidclr(&ref->u.value.peeled); 367memcpy(ref->name, refname, len); 368 ref->flag = flag; 369return ref; 370} 371 372static voidclear_ref_dir(struct ref_dir *dir); 373 374static voidfree_ref_entry(struct ref_entry *entry) 375{ 376if(entry->flag & REF_DIR) { 377/* 378 * Do not use get_ref_dir() here, as that might 379 * trigger the reading of loose refs. 380 */ 381clear_ref_dir(&entry->u.subdir); 382} 383free(entry); 384} 385 386/* 387 * Add a ref_entry to the end of dir (unsorted). Entry is always 388 * stored directly in dir; no recursion into subdirectories is 389 * done. 390 */ 391static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 392{ 393ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 394 dir->entries[dir->nr++] = entry; 395/* optimize for the case that entries are added in order */ 396if(dir->nr ==1|| 397(dir->nr == dir->sorted +1&& 398strcmp(dir->entries[dir->nr -2]->name, 399 dir->entries[dir->nr -1]->name) <0)) 400 dir->sorted = dir->nr; 401} 402 403/* 404 * Clear and free all entries in dir, recursively. 405 */ 406static voidclear_ref_dir(struct ref_dir *dir) 407{ 408int i; 409for(i =0; i < dir->nr; i++) 410free_ref_entry(dir->entries[i]); 411free(dir->entries); 412 dir->sorted = dir->nr = dir->alloc =0; 413 dir->entries = NULL; 414} 415 416/* 417 * Create a struct ref_entry object for the specified dirname. 418 * dirname is the name of the directory with a trailing slash (e.g., 419 * "refs/heads/") or "" for the top-level directory. 420 */ 421static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 422const char*dirname,size_t len, 423int incomplete) 424{ 425struct ref_entry *direntry; 426 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 427memcpy(direntry->name, dirname, len); 428 direntry->name[len] ='\0'; 429 direntry->u.subdir.ref_cache = ref_cache; 430 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 431return direntry; 432} 433 434static intref_entry_cmp(const void*a,const void*b) 435{ 436struct ref_entry *one = *(struct ref_entry **)a; 437struct ref_entry *two = *(struct ref_entry **)b; 438returnstrcmp(one->name, two->name); 439} 440 441static voidsort_ref_dir(struct ref_dir *dir); 442 443struct string_slice { 444size_t len; 445const char*str; 446}; 447 448static intref_entry_cmp_sslice(const void*key_,const void*ent_) 449{ 450const struct string_slice *key = key_; 451const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 452int cmp =strncmp(key->str, ent->name, key->len); 453if(cmp) 454return cmp; 455return'\0'- (unsigned char)ent->name[key->len]; 456} 457 458/* 459 * Return the index of the entry with the given refname from the 460 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 461 * no such entry is found. dir must already be complete. 462 */ 463static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 464{ 465struct ref_entry **r; 466struct string_slice key; 467 468if(refname == NULL || !dir->nr) 469return-1; 470 471sort_ref_dir(dir); 472 key.len = len; 473 key.str = refname; 474 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 475 ref_entry_cmp_sslice); 476 477if(r == NULL) 478return-1; 479 480return r - dir->entries; 481} 482 483/* 484 * Search for a directory entry directly within dir (without 485 * recursing). Sort dir if necessary. subdirname must be a directory 486 * name (i.e., end in '/'). If mkdir is set, then create the 487 * directory if it is missing; otherwise, return NULL if the desired 488 * directory cannot be found. dir must already be complete. 489 */ 490static struct ref_dir *search_for_subdir(struct ref_dir *dir, 491const char*subdirname,size_t len, 492int mkdir) 493{ 494int entry_index =search_ref_dir(dir, subdirname, len); 495struct ref_entry *entry; 496if(entry_index == -1) { 497if(!mkdir) 498return NULL; 499/* 500 * Since dir is complete, the absence of a subdir 501 * means that the subdir really doesn't exist; 502 * therefore, create an empty record for it but mark 503 * the record complete. 504 */ 505 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 506add_entry_to_dir(dir, entry); 507}else{ 508 entry = dir->entries[entry_index]; 509} 510returnget_ref_dir(entry); 511} 512 513/* 514 * If refname is a reference name, find the ref_dir within the dir 515 * tree that should hold refname. If refname is a directory name 516 * (i.e., ends in '/'), then return that ref_dir itself. dir must 517 * represent the top-level directory and must already be complete. 518 * Sort ref_dirs and recurse into subdirectories as necessary. If 519 * mkdir is set, then create any missing directories; otherwise, 520 * return NULL if the desired directory cannot be found. 521 */ 522static struct ref_dir *find_containing_dir(struct ref_dir *dir, 523const char*refname,int mkdir) 524{ 525const char*slash; 526for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 527size_t dirnamelen = slash - refname +1; 528struct ref_dir *subdir; 529 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 530if(!subdir) { 531 dir = NULL; 532break; 533} 534 dir = subdir; 535} 536 537return dir; 538} 539 540/* 541 * Find the value entry with the given name in dir, sorting ref_dirs 542 * and recursing into subdirectories as necessary. If the name is not 543 * found or it corresponds to a directory entry, return NULL. 544 */ 545static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 546{ 547int entry_index; 548struct ref_entry *entry; 549 dir =find_containing_dir(dir, refname,0); 550if(!dir) 551return NULL; 552 entry_index =search_ref_dir(dir, refname,strlen(refname)); 553if(entry_index == -1) 554return NULL; 555 entry = dir->entries[entry_index]; 556return(entry->flag & REF_DIR) ? NULL : entry; 557} 558 559/* 560 * Remove the entry with the given name from dir, recursing into 561 * subdirectories as necessary. If refname is the name of a directory 562 * (i.e., ends with '/'), then remove the directory and its contents. 563 * If the removal was successful, return the number of entries 564 * remaining in the directory entry that contained the deleted entry. 565 * If the name was not found, return -1. Please note that this 566 * function only deletes the entry from the cache; it does not delete 567 * it from the filesystem or ensure that other cache entries (which 568 * might be symbolic references to the removed entry) are updated. 569 * Nor does it remove any containing dir entries that might be made 570 * empty by the removal. dir must represent the top-level directory 571 * and must already be complete. 572 */ 573static intremove_entry(struct ref_dir *dir,const char*refname) 574{ 575int refname_len =strlen(refname); 576int entry_index; 577struct ref_entry *entry; 578int is_dir = refname[refname_len -1] =='/'; 579if(is_dir) { 580/* 581 * refname represents a reference directory. Remove 582 * the trailing slash; otherwise we will get the 583 * directory *representing* refname rather than the 584 * one *containing* it. 585 */ 586char*dirname =xmemdupz(refname, refname_len -1); 587 dir =find_containing_dir(dir, dirname,0); 588free(dirname); 589}else{ 590 dir =find_containing_dir(dir, refname,0); 591} 592if(!dir) 593return-1; 594 entry_index =search_ref_dir(dir, refname, refname_len); 595if(entry_index == -1) 596return-1; 597 entry = dir->entries[entry_index]; 598 599memmove(&dir->entries[entry_index], 600&dir->entries[entry_index +1], 601(dir->nr - entry_index -1) *sizeof(*dir->entries) 602); 603 dir->nr--; 604if(dir->sorted > entry_index) 605 dir->sorted--; 606free_ref_entry(entry); 607return dir->nr; 608} 609 610/* 611 * Add a ref_entry to the ref_dir (unsorted), recursing into 612 * subdirectories as necessary. dir must represent the top-level 613 * directory. Return 0 on success. 614 */ 615static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 616{ 617 dir =find_containing_dir(dir, ref->name,1); 618if(!dir) 619return-1; 620add_entry_to_dir(dir, ref); 621return0; 622} 623 624/* 625 * Emit a warning and return true iff ref1 and ref2 have the same name 626 * and the same sha1. Die if they have the same name but different 627 * sha1s. 628 */ 629static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 630{ 631if(strcmp(ref1->name, ref2->name)) 632return0; 633 634/* Duplicate name; make sure that they don't conflict: */ 635 636if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 637/* This is impossible by construction */ 638die("Reference directory conflict:%s", ref1->name); 639 640if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 641die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 642 643warning("Duplicated ref:%s", ref1->name); 644return1; 645} 646 647/* 648 * Sort the entries in dir non-recursively (if they are not already 649 * sorted) and remove any duplicate entries. 650 */ 651static voidsort_ref_dir(struct ref_dir *dir) 652{ 653int i, j; 654struct ref_entry *last = NULL; 655 656/* 657 * This check also prevents passing a zero-length array to qsort(), 658 * which is a problem on some platforms. 659 */ 660if(dir->sorted == dir->nr) 661return; 662 663qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 664 665/* Remove any duplicates: */ 666for(i =0, j =0; j < dir->nr; j++) { 667struct ref_entry *entry = dir->entries[j]; 668if(last &&is_dup_ref(last, entry)) 669free_ref_entry(entry); 670else 671 last = dir->entries[i++] = entry; 672} 673 dir->sorted = dir->nr = i; 674} 675 676/* Include broken references in a do_for_each_ref*() iteration: */ 677#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 678 679/* 680 * Return true iff the reference described by entry can be resolved to 681 * an object in the database. Emit a warning if the referred-to 682 * object does not exist. 683 */ 684static intref_resolves_to_object(struct ref_entry *entry) 685{ 686if(entry->flag & REF_ISBROKEN) 687return0; 688if(!has_sha1_file(entry->u.value.oid.hash)) { 689error("%sdoes not point to a valid object!", entry->name); 690return0; 691} 692return1; 693} 694 695/* 696 * current_ref is a performance hack: when iterating over references 697 * using the for_each_ref*() functions, current_ref is set to the 698 * current reference's entry before calling the callback function. If 699 * the callback function calls peel_ref(), then peel_ref() first 700 * checks whether the reference to be peeled is the current reference 701 * (it usually is) and if so, returns that reference's peeled version 702 * if it is available. This avoids a refname lookup in a common case. 703 */ 704static struct ref_entry *current_ref; 705 706typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 707 708struct ref_entry_cb { 709const char*base; 710int trim; 711int flags; 712 each_ref_fn *fn; 713void*cb_data; 714}; 715 716/* 717 * Handle one reference in a do_for_each_ref*()-style iteration, 718 * calling an each_ref_fn for each entry. 719 */ 720static intdo_one_ref(struct ref_entry *entry,void*cb_data) 721{ 722struct ref_entry_cb *data = cb_data; 723struct ref_entry *old_current_ref; 724int retval; 725 726if(!starts_with(entry->name, data->base)) 727return0; 728 729if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 730!ref_resolves_to_object(entry)) 731return0; 732 733/* Store the old value, in case this is a recursive call: */ 734 old_current_ref = current_ref; 735 current_ref = entry; 736 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 737 entry->flag, data->cb_data); 738 current_ref = old_current_ref; 739return retval; 740} 741 742/* 743 * Call fn for each reference in dir that has index in the range 744 * offset <= index < dir->nr. Recurse into subdirectories that are in 745 * that index range, sorting them before iterating. This function 746 * does not sort dir itself; it should be sorted beforehand. fn is 747 * called for all references, including broken ones. 748 */ 749static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 750 each_ref_entry_fn fn,void*cb_data) 751{ 752int i; 753assert(dir->sorted == dir->nr); 754for(i = offset; i < dir->nr; i++) { 755struct ref_entry *entry = dir->entries[i]; 756int retval; 757if(entry->flag & REF_DIR) { 758struct ref_dir *subdir =get_ref_dir(entry); 759sort_ref_dir(subdir); 760 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 761}else{ 762 retval =fn(entry, cb_data); 763} 764if(retval) 765return retval; 766} 767return0; 768} 769 770/* 771 * Call fn for each reference in the union of dir1 and dir2, in order 772 * by refname. Recurse into subdirectories. If a value entry appears 773 * in both dir1 and dir2, then only process the version that is in 774 * dir2. The input dirs must already be sorted, but subdirs will be 775 * sorted as needed. fn is called for all references, including 776 * broken ones. 777 */ 778static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 779struct ref_dir *dir2, 780 each_ref_entry_fn fn,void*cb_data) 781{ 782int retval; 783int i1 =0, i2 =0; 784 785assert(dir1->sorted == dir1->nr); 786assert(dir2->sorted == dir2->nr); 787while(1) { 788struct ref_entry *e1, *e2; 789int cmp; 790if(i1 == dir1->nr) { 791returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 792} 793if(i2 == dir2->nr) { 794returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 795} 796 e1 = dir1->entries[i1]; 797 e2 = dir2->entries[i2]; 798 cmp =strcmp(e1->name, e2->name); 799if(cmp ==0) { 800if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 801/* Both are directories; descend them in parallel. */ 802struct ref_dir *subdir1 =get_ref_dir(e1); 803struct ref_dir *subdir2 =get_ref_dir(e2); 804sort_ref_dir(subdir1); 805sort_ref_dir(subdir2); 806 retval =do_for_each_entry_in_dirs( 807 subdir1, subdir2, fn, cb_data); 808 i1++; 809 i2++; 810}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 811/* Both are references; ignore the one from dir1. */ 812 retval =fn(e2, cb_data); 813 i1++; 814 i2++; 815}else{ 816die("conflict between reference and directory:%s", 817 e1->name); 818} 819}else{ 820struct ref_entry *e; 821if(cmp <0) { 822 e = e1; 823 i1++; 824}else{ 825 e = e2; 826 i2++; 827} 828if(e->flag & REF_DIR) { 829struct ref_dir *subdir =get_ref_dir(e); 830sort_ref_dir(subdir); 831 retval =do_for_each_entry_in_dir( 832 subdir,0, fn, cb_data); 833}else{ 834 retval =fn(e, cb_data); 835} 836} 837if(retval) 838return retval; 839} 840} 841 842/* 843 * Load all of the refs from the dir into our in-memory cache. The hard work 844 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 845 * through all of the sub-directories. We do not even need to care about 846 * sorting, as traversal order does not matter to us. 847 */ 848static voidprime_ref_dir(struct ref_dir *dir) 849{ 850int i; 851for(i =0; i < dir->nr; i++) { 852struct ref_entry *entry = dir->entries[i]; 853if(entry->flag & REF_DIR) 854prime_ref_dir(get_ref_dir(entry)); 855} 856} 857 858struct nonmatching_ref_data { 859const struct string_list *skip; 860const char*conflicting_refname; 861}; 862 863static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 864{ 865struct nonmatching_ref_data *data = vdata; 866 867if(data->skip &&string_list_has_string(data->skip, entry->name)) 868return0; 869 870 data->conflicting_refname = entry->name; 871return1; 872} 873 874/* 875 * Return 0 if a reference named refname could be created without 876 * conflicting with the name of an existing reference in dir. 877 * Otherwise, return a negative value and write an explanation to err. 878 * If extras is non-NULL, it is a list of additional refnames with 879 * which refname is not allowed to conflict. If skip is non-NULL, 880 * ignore potential conflicts with refs in skip (e.g., because they 881 * are scheduled for deletion in the same operation). Behavior is 882 * undefined if the same name is listed in both extras and skip. 883 * 884 * Two reference names conflict if one of them exactly matches the 885 * leading components of the other; e.g., "refs/foo/bar" conflicts 886 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 887 * "refs/foo/bar" or "refs/foo/barbados". 888 * 889 * extras and skip must be sorted. 890 */ 891static intverify_refname_available(const char*refname, 892const struct string_list *extras, 893const struct string_list *skip, 894struct ref_dir *dir, 895struct strbuf *err) 896{ 897const char*slash; 898int pos; 899struct strbuf dirname = STRBUF_INIT; 900int ret = -1; 901 902/* 903 * For the sake of comments in this function, suppose that 904 * refname is "refs/foo/bar". 905 */ 906 907assert(err); 908 909strbuf_grow(&dirname,strlen(refname) +1); 910for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 911/* Expand dirname to the new prefix, not including the trailing slash: */ 912strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 913 914/* 915 * We are still at a leading dir of the refname (e.g., 916 * "refs/foo"; if there is a reference with that name, 917 * it is a conflict, *unless* it is in skip. 918 */ 919if(dir) { 920 pos =search_ref_dir(dir, dirname.buf, dirname.len); 921if(pos >=0&& 922(!skip || !string_list_has_string(skip, dirname.buf))) { 923/* 924 * We found a reference whose name is 925 * a proper prefix of refname; e.g., 926 * "refs/foo", and is not in skip. 927 */ 928strbuf_addf(err,"'%s' exists; cannot create '%s'", 929 dirname.buf, refname); 930goto cleanup; 931} 932} 933 934if(extras &&string_list_has_string(extras, dirname.buf) && 935(!skip || !string_list_has_string(skip, dirname.buf))) { 936strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 937 refname, dirname.buf); 938goto cleanup; 939} 940 941/* 942 * Otherwise, we can try to continue our search with 943 * the next component. So try to look up the 944 * directory, e.g., "refs/foo/". If we come up empty, 945 * we know there is nothing under this whole prefix, 946 * but even in that case we still have to continue the 947 * search for conflicts with extras. 948 */ 949strbuf_addch(&dirname,'/'); 950if(dir) { 951 pos =search_ref_dir(dir, dirname.buf, dirname.len); 952if(pos <0) { 953/* 954 * There was no directory "refs/foo/", 955 * so there is nothing under this 956 * whole prefix. So there is no need 957 * to continue looking for conflicting 958 * references. But we need to continue 959 * looking for conflicting extras. 960 */ 961 dir = NULL; 962}else{ 963 dir =get_ref_dir(dir->entries[pos]); 964} 965} 966} 967 968/* 969 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 970 * There is no point in searching for a reference with that 971 * name, because a refname isn't considered to conflict with 972 * itself. But we still need to check for references whose 973 * names are in the "refs/foo/bar/" namespace, because they 974 * *do* conflict. 975 */ 976strbuf_addstr(&dirname, refname + dirname.len); 977strbuf_addch(&dirname,'/'); 978 979if(dir) { 980 pos =search_ref_dir(dir, dirname.buf, dirname.len); 981 982if(pos >=0) { 983/* 984 * We found a directory named "$refname/" 985 * (e.g., "refs/foo/bar/"). It is a problem 986 * iff it contains any ref that is not in 987 * "skip". 988 */ 989struct nonmatching_ref_data data; 990 991 data.skip = skip; 992 data.conflicting_refname = NULL; 993 dir =get_ref_dir(dir->entries[pos]); 994sort_ref_dir(dir); 995if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 996strbuf_addf(err,"'%s' exists; cannot create '%s'", 997 data.conflicting_refname, refname); 998goto cleanup; 999}1000}1001}10021003if(extras) {1004/*1005 * Check for entries in extras that start with1006 * "$refname/". We do that by looking for the place1007 * where "$refname/" would be inserted in extras. If1008 * there is an entry at that position that starts with1009 * "$refname/" and is not in skip, then we have a1010 * conflict.1011 */1012for(pos =string_list_find_insert_index(extras, dirname.buf,0);1013 pos < extras->nr; pos++) {1014const char*extra_refname = extras->items[pos].string;10151016if(!starts_with(extra_refname, dirname.buf))1017break;10181019if(!skip || !string_list_has_string(skip, extra_refname)) {1020strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1021 refname, extra_refname);1022goto cleanup;1023}1024}1025}10261027/* No conflicts were found */1028 ret =0;10291030cleanup:1031strbuf_release(&dirname);1032return ret;1033}10341035struct packed_ref_cache {1036struct ref_entry *root;10371038/*1039 * Count of references to the data structure in this instance,1040 * including the pointer from ref_cache::packed if any. The1041 * data will not be freed as long as the reference count is1042 * nonzero.1043 */1044unsigned int referrers;10451046/*1047 * Iff the packed-refs file associated with this instance is1048 * currently locked for writing, this points at the associated1049 * lock (which is owned by somebody else). The referrer count1050 * is also incremented when the file is locked and decremented1051 * when it is unlocked.1052 */1053struct lock_file *lock;10541055/* The metadata from when this packed-refs cache was read */1056struct stat_validity validity;1057};10581059/*1060 * Future: need to be in "struct repository"1061 * when doing a full libification.1062 */1063static struct ref_cache {1064struct ref_cache *next;1065struct ref_entry *loose;1066struct packed_ref_cache *packed;1067/*1068 * The submodule name, or "" for the main repo. We allocate1069 * length 1 rather than FLEX_ARRAY so that the main ref_cache1070 * is initialized correctly.1071 */1072char name[1];1073} ref_cache, *submodule_ref_caches;10741075/* Lock used for the main packed-refs file: */1076static struct lock_file packlock;10771078/*1079 * Increment the reference count of *packed_refs.1080 */1081static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1082{1083 packed_refs->referrers++;1084}10851086/*1087 * Decrease the reference count of *packed_refs. If it goes to zero,1088 * free *packed_refs and return true; otherwise return false.1089 */1090static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1091{1092if(!--packed_refs->referrers) {1093free_ref_entry(packed_refs->root);1094stat_validity_clear(&packed_refs->validity);1095free(packed_refs);1096return1;1097}else{1098return0;1099}1100}11011102static voidclear_packed_ref_cache(struct ref_cache *refs)1103{1104if(refs->packed) {1105struct packed_ref_cache *packed_refs = refs->packed;11061107if(packed_refs->lock)1108die("internal error: packed-ref cache cleared while locked");1109 refs->packed = NULL;1110release_packed_ref_cache(packed_refs);1111}1112}11131114static voidclear_loose_ref_cache(struct ref_cache *refs)1115{1116if(refs->loose) {1117free_ref_entry(refs->loose);1118 refs->loose = NULL;1119}1120}11211122static struct ref_cache *create_ref_cache(const char*submodule)1123{1124int len;1125struct ref_cache *refs;1126if(!submodule)1127 submodule ="";1128 len =strlen(submodule) +1;1129 refs =xcalloc(1,sizeof(struct ref_cache) + len);1130memcpy(refs->name, submodule, len);1131return refs;1132}11331134/*1135 * Return a pointer to a ref_cache for the specified submodule. For1136 * the main repository, use submodule==NULL. The returned structure1137 * will be allocated and initialized but not necessarily populated; it1138 * should not be freed.1139 */1140static struct ref_cache *get_ref_cache(const char*submodule)1141{1142struct ref_cache *refs;11431144if(!submodule || !*submodule)1145return&ref_cache;11461147for(refs = submodule_ref_caches; refs; refs = refs->next)1148if(!strcmp(submodule, refs->name))1149return refs;11501151 refs =create_ref_cache(submodule);1152 refs->next = submodule_ref_caches;1153 submodule_ref_caches = refs;1154return refs;1155}11561157/* The length of a peeled reference line in packed-refs, including EOL: */1158#define PEELED_LINE_LENGTH 4211591160/*1161 * The packed-refs header line that we write out. Perhaps other1162 * traits will be added later. The trailing space is required.1163 */1164static const char PACKED_REFS_HEADER[] =1165"# pack-refs with: peeled fully-peeled\n";11661167/*1168 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1169 * Return a pointer to the refname within the line (null-terminated),1170 * or NULL if there was a problem.1171 */1172static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1173{1174const char*ref;11751176/*1177 * 42: the answer to everything.1178 *1179 * In this case, it happens to be the answer to1180 * 40 (length of sha1 hex representation)1181 * +1 (space in between hex and name)1182 * +1 (newline at the end of the line)1183 */1184if(line->len <=42)1185return NULL;11861187if(get_sha1_hex(line->buf, sha1) <0)1188return NULL;1189if(!isspace(line->buf[40]))1190return NULL;11911192 ref = line->buf +41;1193if(isspace(*ref))1194return NULL;11951196if(line->buf[line->len -1] !='\n')1197return NULL;1198 line->buf[--line->len] =0;11991200return ref;1201}12021203/*1204 * Read f, which is a packed-refs file, into dir.1205 *1206 * A comment line of the form "# pack-refs with: " may contain zero or1207 * more traits. We interpret the traits as follows:1208 *1209 * No traits:1210 *1211 * Probably no references are peeled. But if the file contains a1212 * peeled value for a reference, we will use it.1213 *1214 * peeled:1215 *1216 * References under "refs/tags/", if they *can* be peeled, *are*1217 * peeled in this file. References outside of "refs/tags/" are1218 * probably not peeled even if they could have been, but if we find1219 * a peeled value for such a reference we will use it.1220 *1221 * fully-peeled:1222 *1223 * All references in the file that can be peeled are peeled.1224 * Inversely (and this is more important), any references in the1225 * file for which no peeled value is recorded is not peelable. This1226 * trait should typically be written alongside "peeled" for1227 * compatibility with older clients, but we do not require it1228 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1229 */1230static voidread_packed_refs(FILE*f,struct ref_dir *dir)1231{1232struct ref_entry *last = NULL;1233struct strbuf line = STRBUF_INIT;1234enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12351236while(strbuf_getwholeline(&line, f,'\n') != EOF) {1237unsigned char sha1[20];1238const char*refname;1239const char*traits;12401241if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1242if(strstr(traits," fully-peeled "))1243 peeled = PEELED_FULLY;1244else if(strstr(traits," peeled "))1245 peeled = PEELED_TAGS;1246/* perhaps other traits later as well */1247continue;1248}12491250 refname =parse_ref_line(&line, sha1);1251if(refname) {1252int flag = REF_ISPACKED;12531254if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1255if(!refname_is_safe(refname))1256die("packed refname is dangerous:%s", refname);1257hashclr(sha1);1258 flag |= REF_BAD_NAME | REF_ISBROKEN;1259}1260 last =create_ref_entry(refname, sha1, flag,0);1261if(peeled == PEELED_FULLY ||1262(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1263 last->flag |= REF_KNOWS_PEELED;1264add_ref(dir, last);1265continue;1266}1267if(last &&1268 line.buf[0] =='^'&&1269 line.len == PEELED_LINE_LENGTH &&1270 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1271!get_sha1_hex(line.buf +1, sha1)) {1272hashcpy(last->u.value.peeled.hash, sha1);1273/*1274 * Regardless of what the file header said,1275 * we definitely know the value of *this*1276 * reference:1277 */1278 last->flag |= REF_KNOWS_PEELED;1279}1280}12811282strbuf_release(&line);1283}12841285/*1286 * Get the packed_ref_cache for the specified ref_cache, creating it1287 * if necessary.1288 */1289static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1290{1291char*packed_refs_file;12921293if(*refs->name)1294 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1295else1296 packed_refs_file =git_pathdup("packed-refs");12971298if(refs->packed &&1299!stat_validity_check(&refs->packed->validity, packed_refs_file))1300clear_packed_ref_cache(refs);13011302if(!refs->packed) {1303FILE*f;13041305 refs->packed =xcalloc(1,sizeof(*refs->packed));1306acquire_packed_ref_cache(refs->packed);1307 refs->packed->root =create_dir_entry(refs,"",0,0);1308 f =fopen(packed_refs_file,"r");1309if(f) {1310stat_validity_update(&refs->packed->validity,fileno(f));1311read_packed_refs(f,get_ref_dir(refs->packed->root));1312fclose(f);1313}1314}1315free(packed_refs_file);1316return refs->packed;1317}13181319static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1320{1321returnget_ref_dir(packed_ref_cache->root);1322}13231324static struct ref_dir *get_packed_refs(struct ref_cache *refs)1325{1326returnget_packed_ref_dir(get_packed_ref_cache(refs));1327}13281329/*1330 * Add a reference to the in-memory packed reference cache. This may1331 * only be called while the packed-refs file is locked (see1332 * lock_packed_refs()). To actually write the packed-refs file, call1333 * commit_packed_refs().1334 */1335static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1336{1337struct packed_ref_cache *packed_ref_cache =1338get_packed_ref_cache(&ref_cache);13391340if(!packed_ref_cache->lock)1341die("internal error: packed refs not locked");1342add_ref(get_packed_ref_dir(packed_ref_cache),1343create_ref_entry(refname, sha1, REF_ISPACKED,1));1344}13451346/*1347 * Read the loose references from the namespace dirname into dir1348 * (without recursing). dirname must end with '/'. dir must be the1349 * directory entry corresponding to dirname.1350 */1351static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1352{1353struct ref_cache *refs = dir->ref_cache;1354DIR*d;1355struct dirent *de;1356int dirnamelen =strlen(dirname);1357struct strbuf refname;1358struct strbuf path = STRBUF_INIT;1359size_t path_baselen;13601361if(*refs->name)1362strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1363else1364strbuf_git_path(&path,"%s", dirname);1365 path_baselen = path.len;13661367 d =opendir(path.buf);1368if(!d) {1369strbuf_release(&path);1370return;1371}13721373strbuf_init(&refname, dirnamelen +257);1374strbuf_add(&refname, dirname, dirnamelen);13751376while((de =readdir(d)) != NULL) {1377unsigned char sha1[20];1378struct stat st;1379int flag;13801381if(de->d_name[0] =='.')1382continue;1383if(ends_with(de->d_name,".lock"))1384continue;1385strbuf_addstr(&refname, de->d_name);1386strbuf_addstr(&path, de->d_name);1387if(stat(path.buf, &st) <0) {1388;/* silently ignore */1389}else if(S_ISDIR(st.st_mode)) {1390strbuf_addch(&refname,'/');1391add_entry_to_dir(dir,1392create_dir_entry(refs, refname.buf,1393 refname.len,1));1394}else{1395int read_ok;13961397if(*refs->name) {1398hashclr(sha1);1399 flag =0;1400 read_ok = !resolve_gitlink_ref(refs->name,1401 refname.buf, sha1);1402}else{1403 read_ok = !read_ref_full(refname.buf,1404 RESOLVE_REF_READING,1405 sha1, &flag);1406}14071408if(!read_ok) {1409hashclr(sha1);1410 flag |= REF_ISBROKEN;1411}else if(is_null_sha1(sha1)) {1412/*1413 * It is so astronomically unlikely1414 * that NULL_SHA1 is the SHA-1 of an1415 * actual object that we consider its1416 * appearance in a loose reference1417 * file to be repo corruption1418 * (probably due to a software bug).1419 */1420 flag |= REF_ISBROKEN;1421}14221423if(check_refname_format(refname.buf,1424 REFNAME_ALLOW_ONELEVEL)) {1425if(!refname_is_safe(refname.buf))1426die("loose refname is dangerous:%s", refname.buf);1427hashclr(sha1);1428 flag |= REF_BAD_NAME | REF_ISBROKEN;1429}1430add_entry_to_dir(dir,1431create_ref_entry(refname.buf, sha1, flag,0));1432}1433strbuf_setlen(&refname, dirnamelen);1434strbuf_setlen(&path, path_baselen);1435}1436strbuf_release(&refname);1437strbuf_release(&path);1438closedir(d);1439}14401441static struct ref_dir *get_loose_refs(struct ref_cache *refs)1442{1443if(!refs->loose) {1444/*1445 * Mark the top-level directory complete because we1446 * are about to read the only subdirectory that can1447 * hold references:1448 */1449 refs->loose =create_dir_entry(refs,"",0,0);1450/*1451 * Create an incomplete entry for "refs/":1452 */1453add_entry_to_dir(get_ref_dir(refs->loose),1454create_dir_entry(refs,"refs/",5,1));1455}1456returnget_ref_dir(refs->loose);1457}14581459/* We allow "recursive" symbolic refs. Only within reason, though */1460#define MAXDEPTH 51461#define MAXREFLEN (1024)14621463/*1464 * Called by resolve_gitlink_ref_recursive() after it failed to read1465 * from the loose refs in ref_cache refs. Find <refname> in the1466 * packed-refs file for the submodule.1467 */1468static intresolve_gitlink_packed_ref(struct ref_cache *refs,1469const char*refname,unsigned char*sha1)1470{1471struct ref_entry *ref;1472struct ref_dir *dir =get_packed_refs(refs);14731474 ref =find_ref(dir, refname);1475if(ref == NULL)1476return-1;14771478hashcpy(sha1, ref->u.value.oid.hash);1479return0;1480}14811482static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1483const char*refname,unsigned char*sha1,1484int recursion)1485{1486int fd, len;1487char buffer[128], *p;1488char*path;14891490if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1491return-1;1492 path = *refs->name1493?git_pathdup_submodule(refs->name,"%s", refname)1494:git_pathdup("%s", refname);1495 fd =open(path, O_RDONLY);1496free(path);1497if(fd <0)1498returnresolve_gitlink_packed_ref(refs, refname, sha1);14991500 len =read(fd, buffer,sizeof(buffer)-1);1501close(fd);1502if(len <0)1503return-1;1504while(len &&isspace(buffer[len-1]))1505 len--;1506 buffer[len] =0;15071508/* Was it a detached head or an old-fashioned symlink? */1509if(!get_sha1_hex(buffer, sha1))1510return0;15111512/* Symref? */1513if(strncmp(buffer,"ref:",4))1514return-1;1515 p = buffer +4;1516while(isspace(*p))1517 p++;15181519returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1520}15211522intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1523{1524int len =strlen(path), retval;1525char*submodule;1526struct ref_cache *refs;15271528while(len && path[len-1] =='/')1529 len--;1530if(!len)1531return-1;1532 submodule =xstrndup(path, len);1533 refs =get_ref_cache(submodule);1534free(submodule);15351536 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1537return retval;1538}15391540/*1541 * Return the ref_entry for the given refname from the packed1542 * references. If it does not exist, return NULL.1543 */1544static struct ref_entry *get_packed_ref(const char*refname)1545{1546returnfind_ref(get_packed_refs(&ref_cache), refname);1547}15481549/*1550 * A loose ref file doesn't exist; check for a packed ref. The1551 * options are forwarded from resolve_safe_unsafe().1552 */1553static intresolve_missing_loose_ref(const char*refname,1554int resolve_flags,1555unsigned char*sha1,1556int*flags)1557{1558struct ref_entry *entry;15591560/*1561 * The loose reference file does not exist; check for a packed1562 * reference.1563 */1564 entry =get_packed_ref(refname);1565if(entry) {1566hashcpy(sha1, entry->u.value.oid.hash);1567if(flags)1568*flags |= REF_ISPACKED;1569return0;1570}1571/* The reference is not a packed reference, either. */1572if(resolve_flags & RESOLVE_REF_READING) {1573 errno = ENOENT;1574return-1;1575}else{1576hashclr(sha1);1577return0;1578}1579}15801581/* This function needs to return a meaningful errno on failure */1582static const char*resolve_ref_1(const char*refname,1583int resolve_flags,1584unsigned char*sha1,1585int*flags,1586struct strbuf *sb_refname,1587struct strbuf *sb_path,1588struct strbuf *sb_contents)1589{1590int depth = MAXDEPTH;1591int bad_name =0;15921593if(flags)1594*flags =0;15951596if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1597if(flags)1598*flags |= REF_BAD_NAME;15991600if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1601!refname_is_safe(refname)) {1602 errno = EINVAL;1603return NULL;1604}1605/*1606 * dwim_ref() uses REF_ISBROKEN to distinguish between1607 * missing refs and refs that were present but invalid,1608 * to complain about the latter to stderr.1609 *1610 * We don't know whether the ref exists, so don't set1611 * REF_ISBROKEN yet.1612 */1613 bad_name =1;1614}1615for(;;) {1616const char*path;1617struct stat st;1618char*buf;1619int fd;16201621if(--depth <0) {1622 errno = ELOOP;1623return NULL;1624}16251626strbuf_reset(sb_path);1627strbuf_git_path(sb_path,"%s", refname);1628 path = sb_path->buf;16291630/*1631 * We might have to loop back here to avoid a race1632 * condition: first we lstat() the file, then we try1633 * to read it as a link or as a file. But if somebody1634 * changes the type of the file (file <-> directory1635 * <-> symlink) between the lstat() and reading, then1636 * we don't want to report that as an error but rather1637 * try again starting with the lstat().1638 */1639 stat_ref:1640if(lstat(path, &st) <0) {1641if(errno != ENOENT)1642return NULL;1643if(resolve_missing_loose_ref(refname, resolve_flags,1644 sha1, flags))1645return NULL;1646if(bad_name) {1647hashclr(sha1);1648if(flags)1649*flags |= REF_ISBROKEN;1650}1651return refname;1652}16531654/* Follow "normalized" - ie "refs/.." symlinks by hand */1655if(S_ISLNK(st.st_mode)) {1656strbuf_reset(sb_contents);1657if(strbuf_readlink(sb_contents, path,0) <0) {1658if(errno == ENOENT || errno == EINVAL)1659/* inconsistent with lstat; retry */1660goto stat_ref;1661else1662return NULL;1663}1664if(starts_with(sb_contents->buf,"refs/") &&1665!check_refname_format(sb_contents->buf,0)) {1666strbuf_swap(sb_refname, sb_contents);1667 refname = sb_refname->buf;1668if(flags)1669*flags |= REF_ISSYMREF;1670if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1671hashclr(sha1);1672return refname;1673}1674continue;1675}1676}16771678/* Is it a directory? */1679if(S_ISDIR(st.st_mode)) {1680 errno = EISDIR;1681return NULL;1682}16831684/*1685 * Anything else, just open it and try to use it as1686 * a ref1687 */1688 fd =open(path, O_RDONLY);1689if(fd <0) {1690if(errno == ENOENT)1691/* inconsistent with lstat; retry */1692goto stat_ref;1693else1694return NULL;1695}1696strbuf_reset(sb_contents);1697if(strbuf_read(sb_contents, fd,256) <0) {1698int save_errno = errno;1699close(fd);1700 errno = save_errno;1701return NULL;1702}1703close(fd);1704strbuf_rtrim(sb_contents);17051706/*1707 * Is it a symbolic ref?1708 */1709if(!starts_with(sb_contents->buf,"ref:")) {1710/*1711 * Please note that FETCH_HEAD has a second1712 * line containing other data.1713 */1714if(get_sha1_hex(sb_contents->buf, sha1) ||1715(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1716if(flags)1717*flags |= REF_ISBROKEN;1718 errno = EINVAL;1719return NULL;1720}1721if(bad_name) {1722hashclr(sha1);1723if(flags)1724*flags |= REF_ISBROKEN;1725}1726return refname;1727}1728if(flags)1729*flags |= REF_ISSYMREF;1730 buf = sb_contents->buf +4;1731while(isspace(*buf))1732 buf++;1733strbuf_reset(sb_refname);1734strbuf_addstr(sb_refname, buf);1735 refname = sb_refname->buf;1736if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1737hashclr(sha1);1738return refname;1739}1740if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1741if(flags)1742*flags |= REF_ISBROKEN;17431744if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1745!refname_is_safe(buf)) {1746 errno = EINVAL;1747return NULL;1748}1749 bad_name =1;1750}1751}1752}17531754const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1755unsigned char*sha1,int*flags)1756{1757static struct strbuf sb_refname = STRBUF_INIT;1758struct strbuf sb_contents = STRBUF_INIT;1759struct strbuf sb_path = STRBUF_INIT;1760const char*ret;17611762 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1763&sb_refname, &sb_path, &sb_contents);1764strbuf_release(&sb_path);1765strbuf_release(&sb_contents);1766return ret;1767}17681769char*resolve_refdup(const char*refname,int resolve_flags,1770unsigned char*sha1,int*flags)1771{1772returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1773 sha1, flags));1774}17751776/* The argument to filter_refs */1777struct ref_filter {1778const char*pattern;1779 each_ref_fn *fn;1780void*cb_data;1781};17821783intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1784{1785if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1786return0;1787return-1;1788}17891790intread_ref(const char*refname,unsigned char*sha1)1791{1792returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1793}17941795intref_exists(const char*refname)1796{1797unsigned char sha1[20];1798return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1799}18001801static intfilter_refs(const char*refname,const struct object_id *oid,1802int flags,void*data)1803{1804struct ref_filter *filter = (struct ref_filter *)data;18051806if(wildmatch(filter->pattern, refname,0, NULL))1807return0;1808return filter->fn(refname, oid, flags, filter->cb_data);1809}18101811enum peel_status {1812/* object was peeled successfully: */1813 PEEL_PEELED =0,18141815/*1816 * object cannot be peeled because the named object (or an1817 * object referred to by a tag in the peel chain), does not1818 * exist.1819 */1820 PEEL_INVALID = -1,18211822/* object cannot be peeled because it is not a tag: */1823 PEEL_NON_TAG = -2,18241825/* ref_entry contains no peeled value because it is a symref: */1826 PEEL_IS_SYMREF = -3,18271828/*1829 * ref_entry cannot be peeled because it is broken (i.e., the1830 * symbolic reference cannot even be resolved to an object1831 * name):1832 */1833 PEEL_BROKEN = -41834};18351836/*1837 * Peel the named object; i.e., if the object is a tag, resolve the1838 * tag recursively until a non-tag is found. If successful, store the1839 * result to sha1 and return PEEL_PEELED. If the object is not a tag1840 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1841 * and leave sha1 unchanged.1842 */1843static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1844{1845struct object *o =lookup_unknown_object(name);18461847if(o->type == OBJ_NONE) {1848int type =sha1_object_info(name, NULL);1849if(type <0|| !object_as_type(o, type,0))1850return PEEL_INVALID;1851}18521853if(o->type != OBJ_TAG)1854return PEEL_NON_TAG;18551856 o =deref_tag_noverify(o);1857if(!o)1858return PEEL_INVALID;18591860hashcpy(sha1, o->sha1);1861return PEEL_PEELED;1862}18631864/*1865 * Peel the entry (if possible) and return its new peel_status. If1866 * repeel is true, re-peel the entry even if there is an old peeled1867 * value that is already stored in it.1868 *1869 * It is OK to call this function with a packed reference entry that1870 * might be stale and might even refer to an object that has since1871 * been garbage-collected. In such a case, if the entry has1872 * REF_KNOWS_PEELED then leave the status unchanged and return1873 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1874 */1875static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1876{1877enum peel_status status;18781879if(entry->flag & REF_KNOWS_PEELED) {1880if(repeel) {1881 entry->flag &= ~REF_KNOWS_PEELED;1882oidclr(&entry->u.value.peeled);1883}else{1884returnis_null_oid(&entry->u.value.peeled) ?1885 PEEL_NON_TAG : PEEL_PEELED;1886}1887}1888if(entry->flag & REF_ISBROKEN)1889return PEEL_BROKEN;1890if(entry->flag & REF_ISSYMREF)1891return PEEL_IS_SYMREF;18921893 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1894if(status == PEEL_PEELED || status == PEEL_NON_TAG)1895 entry->flag |= REF_KNOWS_PEELED;1896return status;1897}18981899intpeel_ref(const char*refname,unsigned char*sha1)1900{1901int flag;1902unsigned char base[20];19031904if(current_ref && (current_ref->name == refname1905|| !strcmp(current_ref->name, refname))) {1906if(peel_entry(current_ref,0))1907return-1;1908hashcpy(sha1, current_ref->u.value.peeled.hash);1909return0;1910}19111912if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1913return-1;19141915/*1916 * If the reference is packed, read its ref_entry from the1917 * cache in the hope that we already know its peeled value.1918 * We only try this optimization on packed references because1919 * (a) forcing the filling of the loose reference cache could1920 * be expensive and (b) loose references anyway usually do not1921 * have REF_KNOWS_PEELED.1922 */1923if(flag & REF_ISPACKED) {1924struct ref_entry *r =get_packed_ref(refname);1925if(r) {1926if(peel_entry(r,0))1927return-1;1928hashcpy(sha1, r->u.value.peeled.hash);1929return0;1930}1931}19321933returnpeel_object(base, sha1);1934}19351936struct warn_if_dangling_data {1937FILE*fp;1938const char*refname;1939const struct string_list *refnames;1940const char*msg_fmt;1941};19421943static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1944int flags,void*cb_data)1945{1946struct warn_if_dangling_data *d = cb_data;1947const char*resolves_to;1948struct object_id junk;19491950if(!(flags & REF_ISSYMREF))1951return0;19521953 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1954if(!resolves_to1955|| (d->refname1956?strcmp(resolves_to, d->refname)1957: !string_list_has_string(d->refnames, resolves_to))) {1958return0;1959}19601961fprintf(d->fp, d->msg_fmt, refname);1962fputc('\n', d->fp);1963return0;1964}19651966voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1967{1968struct warn_if_dangling_data data;19691970 data.fp = fp;1971 data.refname = refname;1972 data.refnames = NULL;1973 data.msg_fmt = msg_fmt;1974for_each_rawref(warn_if_dangling_symref, &data);1975}19761977voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1978{1979struct warn_if_dangling_data data;19801981 data.fp = fp;1982 data.refname = NULL;1983 data.refnames = refnames;1984 data.msg_fmt = msg_fmt;1985for_each_rawref(warn_if_dangling_symref, &data);1986}19871988/*1989 * Call fn for each reference in the specified ref_cache, omitting1990 * references not in the containing_dir of base. fn is called for all1991 * references, including broken ones. If fn ever returns a non-zero1992 * value, stop the iteration and return that value; otherwise, return1993 * 0.1994 */1995static intdo_for_each_entry(struct ref_cache *refs,const char*base,1996 each_ref_entry_fn fn,void*cb_data)1997{1998struct packed_ref_cache *packed_ref_cache;1999struct ref_dir *loose_dir;2000struct ref_dir *packed_dir;2001int retval =0;20022003/*2004 * We must make sure that all loose refs are read before accessing the2005 * packed-refs file; this avoids a race condition in which loose refs2006 * are migrated to the packed-refs file by a simultaneous process, but2007 * our in-memory view is from before the migration. get_packed_ref_cache()2008 * takes care of making sure our view is up to date with what is on2009 * disk.2010 */2011 loose_dir =get_loose_refs(refs);2012if(base && *base) {2013 loose_dir =find_containing_dir(loose_dir, base,0);2014}2015if(loose_dir)2016prime_ref_dir(loose_dir);20172018 packed_ref_cache =get_packed_ref_cache(refs);2019acquire_packed_ref_cache(packed_ref_cache);2020 packed_dir =get_packed_ref_dir(packed_ref_cache);2021if(base && *base) {2022 packed_dir =find_containing_dir(packed_dir, base,0);2023}20242025if(packed_dir && loose_dir) {2026sort_ref_dir(packed_dir);2027sort_ref_dir(loose_dir);2028 retval =do_for_each_entry_in_dirs(2029 packed_dir, loose_dir, fn, cb_data);2030}else if(packed_dir) {2031sort_ref_dir(packed_dir);2032 retval =do_for_each_entry_in_dir(2033 packed_dir,0, fn, cb_data);2034}else if(loose_dir) {2035sort_ref_dir(loose_dir);2036 retval =do_for_each_entry_in_dir(2037 loose_dir,0, fn, cb_data);2038}20392040release_packed_ref_cache(packed_ref_cache);2041return retval;2042}20432044/*2045 * Call fn for each reference in the specified ref_cache for which the2046 * refname begins with base. If trim is non-zero, then trim that many2047 * characters off the beginning of each refname before passing the2048 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2049 * broken references in the iteration. If fn ever returns a non-zero2050 * value, stop the iteration and return that value; otherwise, return2051 * 0.2052 */2053static intdo_for_each_ref(struct ref_cache *refs,const char*base,2054 each_ref_fn fn,int trim,int flags,void*cb_data)2055{2056struct ref_entry_cb data;2057 data.base = base;2058 data.trim = trim;2059 data.flags = flags;2060 data.fn = fn;2061 data.cb_data = cb_data;20622063if(ref_paranoia <0)2064 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2065if(ref_paranoia)2066 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20672068returndo_for_each_entry(refs, base, do_one_ref, &data);2069}20702071static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2072{2073struct object_id oid;2074int flag;20752076if(submodule) {2077if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2078returnfn("HEAD", &oid,0, cb_data);20792080return0;2081}20822083if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2084returnfn("HEAD", &oid, flag, cb_data);20852086return0;2087}20882089inthead_ref(each_ref_fn fn,void*cb_data)2090{2091returndo_head_ref(NULL, fn, cb_data);2092}20932094inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2095{2096returndo_head_ref(submodule, fn, cb_data);2097}20982099intfor_each_ref(each_ref_fn fn,void*cb_data)2100{2101returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2102}21032104intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2105{2106returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2107}21082109intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2110{2111returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2112}21132114intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2115 each_ref_fn fn,void*cb_data)2116{2117returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2118}21192120intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2121{2122returnfor_each_ref_in("refs/tags/", fn, cb_data);2123}21242125intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2126{2127returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2128}21292130intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2131{2132returnfor_each_ref_in("refs/heads/", fn, cb_data);2133}21342135intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2136{2137returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2138}21392140intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2141{2142returnfor_each_ref_in("refs/remotes/", fn, cb_data);2143}21442145intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2146{2147returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2148}21492150intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2151{2152returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2153strlen(git_replace_ref_base),0, cb_data);2154}21552156inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2157{2158struct strbuf buf = STRBUF_INIT;2159int ret =0;2160struct object_id oid;2161int flag;21622163strbuf_addf(&buf,"%sHEAD",get_git_namespace());2164if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2165 ret =fn(buf.buf, &oid, flag, cb_data);2166strbuf_release(&buf);21672168return ret;2169}21702171intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2172{2173struct strbuf buf = STRBUF_INIT;2174int ret;2175strbuf_addf(&buf,"%srefs/",get_git_namespace());2176 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2177strbuf_release(&buf);2178return ret;2179}21802181intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2182const char*prefix,void*cb_data)2183{2184struct strbuf real_pattern = STRBUF_INIT;2185struct ref_filter filter;2186int ret;21872188if(!prefix && !starts_with(pattern,"refs/"))2189strbuf_addstr(&real_pattern,"refs/");2190else if(prefix)2191strbuf_addstr(&real_pattern, prefix);2192strbuf_addstr(&real_pattern, pattern);21932194if(!has_glob_specials(pattern)) {2195/* Append implied '/' '*' if not present. */2196strbuf_complete(&real_pattern,'/');2197/* No need to check for '*', there is none. */2198strbuf_addch(&real_pattern,'*');2199}22002201 filter.pattern = real_pattern.buf;2202 filter.fn = fn;2203 filter.cb_data = cb_data;2204 ret =for_each_ref(filter_refs, &filter);22052206strbuf_release(&real_pattern);2207return ret;2208}22092210intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2211{2212returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2213}22142215intfor_each_rawref(each_ref_fn fn,void*cb_data)2216{2217returndo_for_each_ref(&ref_cache,"", fn,0,2218 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2219}22202221const char*prettify_refname(const char*name)2222{2223return name + (2224starts_with(name,"refs/heads/") ?11:2225starts_with(name,"refs/tags/") ?10:2226starts_with(name,"refs/remotes/") ?13:22270);2228}22292230static const char*ref_rev_parse_rules[] = {2231"%.*s",2232"refs/%.*s",2233"refs/tags/%.*s",2234"refs/heads/%.*s",2235"refs/remotes/%.*s",2236"refs/remotes/%.*s/HEAD",2237 NULL2238};22392240intrefname_match(const char*abbrev_name,const char*full_name)2241{2242const char**p;2243const int abbrev_name_len =strlen(abbrev_name);22442245for(p = ref_rev_parse_rules; *p; p++) {2246if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2247return1;2248}2249}22502251return0;2252}22532254static voidunlock_ref(struct ref_lock *lock)2255{2256/* Do not free lock->lk -- atexit() still looks at them */2257if(lock->lk)2258rollback_lock_file(lock->lk);2259free(lock->ref_name);2260free(lock->orig_ref_name);2261free(lock);2262}22632264/*2265 * Verify that the reference locked by lock has the value old_sha1.2266 * Fail if the reference doesn't exist and mustexist is set. Return 02267 * on success. On error, write an error message to err, set errno, and2268 * return a negative value.2269 */2270static intverify_lock(struct ref_lock *lock,2271const unsigned char*old_sha1,int mustexist,2272struct strbuf *err)2273{2274assert(err);22752276if(read_ref_full(lock->ref_name,2277 mustexist ? RESOLVE_REF_READING :0,2278 lock->old_oid.hash, NULL)) {2279int save_errno = errno;2280strbuf_addf(err,"can't verify ref%s", lock->ref_name);2281 errno = save_errno;2282return-1;2283}2284if(hashcmp(lock->old_oid.hash, old_sha1)) {2285strbuf_addf(err,"ref%sis at%sbut expected%s",2286 lock->ref_name,2287sha1_to_hex(lock->old_oid.hash),2288sha1_to_hex(old_sha1));2289 errno = EBUSY;2290return-1;2291}2292return0;2293}22942295static intremove_empty_directories(struct strbuf *path)2296{2297/*2298 * we want to create a file but there is a directory there;2299 * if that is an empty directory (or a directory that contains2300 * only empty directories), remove them.2301 */2302returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2303}23042305/*2306 * *string and *len will only be substituted, and *string returned (for2307 * later free()ing) if the string passed in is a magic short-hand form2308 * to name a branch.2309 */2310static char*substitute_branch_name(const char**string,int*len)2311{2312struct strbuf buf = STRBUF_INIT;2313int ret =interpret_branch_name(*string, *len, &buf);23142315if(ret == *len) {2316size_t size;2317*string =strbuf_detach(&buf, &size);2318*len = size;2319return(char*)*string;2320}23212322return NULL;2323}23242325intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2326{2327char*last_branch =substitute_branch_name(&str, &len);2328const char**p, *r;2329int refs_found =0;23302331*ref = NULL;2332for(p = ref_rev_parse_rules; *p; p++) {2333char fullref[PATH_MAX];2334unsigned char sha1_from_ref[20];2335unsigned char*this_result;2336int flag;23372338 this_result = refs_found ? sha1_from_ref : sha1;2339mksnpath(fullref,sizeof(fullref), *p, len, str);2340 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2341 this_result, &flag);2342if(r) {2343if(!refs_found++)2344*ref =xstrdup(r);2345if(!warn_ambiguous_refs)2346break;2347}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2348warning("ignoring dangling symref%s.", fullref);2349}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2350warning("ignoring broken ref%s.", fullref);2351}2352}2353free(last_branch);2354return refs_found;2355}23562357intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2358{2359char*last_branch =substitute_branch_name(&str, &len);2360const char**p;2361int logs_found =0;23622363*log = NULL;2364for(p = ref_rev_parse_rules; *p; p++) {2365unsigned char hash[20];2366char path[PATH_MAX];2367const char*ref, *it;23682369mksnpath(path,sizeof(path), *p, len, str);2370 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2371 hash, NULL);2372if(!ref)2373continue;2374if(reflog_exists(path))2375 it = path;2376else if(strcmp(ref, path) &&reflog_exists(ref))2377 it = ref;2378else2379continue;2380if(!logs_found++) {2381*log =xstrdup(it);2382hashcpy(sha1, hash);2383}2384if(!warn_ambiguous_refs)2385break;2386}2387free(last_branch);2388return logs_found;2389}23902391/*2392 * Locks a ref returning the lock on success and NULL on failure.2393 * On failure errno is set to something meaningful.2394 */2395static struct ref_lock *lock_ref_sha1_basic(const char*refname,2396const unsigned char*old_sha1,2397const struct string_list *extras,2398const struct string_list *skip,2399unsigned int flags,int*type_p,2400struct strbuf *err)2401{2402struct strbuf ref_file = STRBUF_INIT;2403struct strbuf orig_ref_file = STRBUF_INIT;2404const char*orig_refname = refname;2405struct ref_lock *lock;2406int last_errno =0;2407int type, lflags;2408int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2409int resolve_flags =0;2410int attempts_remaining =3;24112412assert(err);24132414 lock =xcalloc(1,sizeof(struct ref_lock));24152416if(mustexist)2417 resolve_flags |= RESOLVE_REF_READING;2418if(flags & REF_DELETING) {2419 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2420if(flags & REF_NODEREF)2421 resolve_flags |= RESOLVE_REF_NO_RECURSE;2422}24232424 refname =resolve_ref_unsafe(refname, resolve_flags,2425 lock->old_oid.hash, &type);2426if(!refname && errno == EISDIR) {2427/*2428 * we are trying to lock foo but we used to2429 * have foo/bar which now does not exist;2430 * it is normal for the empty directory 'foo'2431 * to remain.2432 */2433strbuf_git_path(&orig_ref_file,"%s", orig_refname);2434if(remove_empty_directories(&orig_ref_file)) {2435 last_errno = errno;2436if(!verify_refname_available(orig_refname, extras, skip,2437get_loose_refs(&ref_cache), err))2438strbuf_addf(err,"there are still refs under '%s'",2439 orig_refname);2440goto error_return;2441}2442 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2443 lock->old_oid.hash, &type);2444}2445if(type_p)2446*type_p = type;2447if(!refname) {2448 last_errno = errno;2449if(last_errno != ENOTDIR ||2450!verify_refname_available(orig_refname, extras, skip,2451get_loose_refs(&ref_cache), err))2452strbuf_addf(err,"unable to resolve reference%s:%s",2453 orig_refname,strerror(last_errno));24542455goto error_return;2456}2457/*2458 * If the ref did not exist and we are creating it, make sure2459 * there is no existing packed ref whose name begins with our2460 * refname, nor a packed ref whose name is a proper prefix of2461 * our refname.2462 */2463if(is_null_oid(&lock->old_oid) &&2464verify_refname_available(refname, extras, skip,2465get_packed_refs(&ref_cache), err)) {2466 last_errno = ENOTDIR;2467goto error_return;2468}24692470 lock->lk =xcalloc(1,sizeof(struct lock_file));24712472 lflags =0;2473if(flags & REF_NODEREF) {2474 refname = orig_refname;2475 lflags |= LOCK_NO_DEREF;2476}2477 lock->ref_name =xstrdup(refname);2478 lock->orig_ref_name =xstrdup(orig_refname);2479strbuf_git_path(&ref_file,"%s", refname);24802481 retry:2482switch(safe_create_leading_directories_const(ref_file.buf)) {2483case SCLD_OK:2484break;/* success */2485case SCLD_VANISHED:2486if(--attempts_remaining >0)2487goto retry;2488/* fall through */2489default:2490 last_errno = errno;2491strbuf_addf(err,"unable to create directory for%s",2492 ref_file.buf);2493goto error_return;2494}24952496if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2497 last_errno = errno;2498if(errno == ENOENT && --attempts_remaining >0)2499/*2500 * Maybe somebody just deleted one of the2501 * directories leading to ref_file. Try2502 * again:2503 */2504goto retry;2505else{2506unable_to_lock_message(ref_file.buf, errno, err);2507goto error_return;2508}2509}2510if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2511 last_errno = errno;2512goto error_return;2513}2514goto out;25152516 error_return:2517unlock_ref(lock);2518 lock = NULL;25192520 out:2521strbuf_release(&ref_file);2522strbuf_release(&orig_ref_file);2523 errno = last_errno;2524return lock;2525}25262527/*2528 * Write an entry to the packed-refs file for the specified refname.2529 * If peeled is non-NULL, write it as the entry's peeled value.2530 */2531static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2532unsigned char*peeled)2533{2534fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2535if(peeled)2536fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2537}25382539/*2540 * An each_ref_entry_fn that writes the entry to a packed-refs file.2541 */2542static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2543{2544enum peel_status peel_status =peel_entry(entry,0);25452546if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2547error("internal error:%sis not a valid packed reference!",2548 entry->name);2549write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2550 peel_status == PEEL_PEELED ?2551 entry->u.value.peeled.hash : NULL);2552return0;2553}25542555/*2556 * Lock the packed-refs file for writing. Flags is passed to2557 * hold_lock_file_for_update(). Return 0 on success. On errors, set2558 * errno appropriately and return a nonzero value.2559 */2560static intlock_packed_refs(int flags)2561{2562static int timeout_configured =0;2563static int timeout_value =1000;25642565struct packed_ref_cache *packed_ref_cache;25662567if(!timeout_configured) {2568git_config_get_int("core.packedrefstimeout", &timeout_value);2569 timeout_configured =1;2570}25712572if(hold_lock_file_for_update_timeout(2573&packlock,git_path("packed-refs"),2574 flags, timeout_value) <0)2575return-1;2576/*2577 * Get the current packed-refs while holding the lock. If the2578 * packed-refs file has been modified since we last read it,2579 * this will automatically invalidate the cache and re-read2580 * the packed-refs file.2581 */2582 packed_ref_cache =get_packed_ref_cache(&ref_cache);2583 packed_ref_cache->lock = &packlock;2584/* Increment the reference count to prevent it from being freed: */2585acquire_packed_ref_cache(packed_ref_cache);2586return0;2587}25882589/*2590 * Write the current version of the packed refs cache from memory to2591 * disk. The packed-refs file must already be locked for writing (see2592 * lock_packed_refs()). Return zero on success. On errors, set errno2593 * and return a nonzero value2594 */2595static intcommit_packed_refs(void)2596{2597struct packed_ref_cache *packed_ref_cache =2598get_packed_ref_cache(&ref_cache);2599int error =0;2600int save_errno =0;2601FILE*out;26022603if(!packed_ref_cache->lock)2604die("internal error: packed-refs not locked");26052606 out =fdopen_lock_file(packed_ref_cache->lock,"w");2607if(!out)2608die_errno("unable to fdopen packed-refs descriptor");26092610fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2611do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26120, write_packed_entry_fn, out);26132614if(commit_lock_file(packed_ref_cache->lock)) {2615 save_errno = errno;2616 error = -1;2617}2618 packed_ref_cache->lock = NULL;2619release_packed_ref_cache(packed_ref_cache);2620 errno = save_errno;2621return error;2622}26232624/*2625 * Rollback the lockfile for the packed-refs file, and discard the2626 * in-memory packed reference cache. (The packed-refs file will be2627 * read anew if it is needed again after this function is called.)2628 */2629static voidrollback_packed_refs(void)2630{2631struct packed_ref_cache *packed_ref_cache =2632get_packed_ref_cache(&ref_cache);26332634if(!packed_ref_cache->lock)2635die("internal error: packed-refs not locked");2636rollback_lock_file(packed_ref_cache->lock);2637 packed_ref_cache->lock = NULL;2638release_packed_ref_cache(packed_ref_cache);2639clear_packed_ref_cache(&ref_cache);2640}26412642struct ref_to_prune {2643struct ref_to_prune *next;2644unsigned char sha1[20];2645char name[FLEX_ARRAY];2646};26472648struct pack_refs_cb_data {2649unsigned int flags;2650struct ref_dir *packed_refs;2651struct ref_to_prune *ref_to_prune;2652};26532654/*2655 * An each_ref_entry_fn that is run over loose references only. If2656 * the loose reference can be packed, add an entry in the packed ref2657 * cache. If the reference should be pruned, also add it to2658 * ref_to_prune in the pack_refs_cb_data.2659 */2660static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2661{2662struct pack_refs_cb_data *cb = cb_data;2663enum peel_status peel_status;2664struct ref_entry *packed_entry;2665int is_tag_ref =starts_with(entry->name,"refs/tags/");26662667/* ALWAYS pack tags */2668if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2669return0;26702671/* Do not pack symbolic or broken refs: */2672if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2673return0;26742675/* Add a packed ref cache entry equivalent to the loose entry. */2676 peel_status =peel_entry(entry,1);2677if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2678die("internal error peeling reference%s(%s)",2679 entry->name,oid_to_hex(&entry->u.value.oid));2680 packed_entry =find_ref(cb->packed_refs, entry->name);2681if(packed_entry) {2682/* Overwrite existing packed entry with info from loose entry */2683 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2684oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2685}else{2686 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2687 REF_ISPACKED | REF_KNOWS_PEELED,0);2688add_ref(cb->packed_refs, packed_entry);2689}2690oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26912692/* Schedule the loose reference for pruning if requested. */2693if((cb->flags & PACK_REFS_PRUNE)) {2694int namelen =strlen(entry->name) +1;2695struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2696hashcpy(n->sha1, entry->u.value.oid.hash);2697memcpy(n->name, entry->name, namelen);/* includes NUL */2698 n->next = cb->ref_to_prune;2699 cb->ref_to_prune = n;2700}2701return0;2702}27032704/*2705 * Remove empty parents, but spare refs/ and immediate subdirs.2706 * Note: munges *name.2707 */2708static voidtry_remove_empty_parents(char*name)2709{2710char*p, *q;2711int i;2712 p = name;2713for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2714while(*p && *p !='/')2715 p++;2716/* tolerate duplicate slashes; see check_refname_format() */2717while(*p =='/')2718 p++;2719}2720for(q = p; *q; q++)2721;2722while(1) {2723while(q > p && *q !='/')2724 q--;2725while(q > p && *(q-1) =='/')2726 q--;2727if(q == p)2728break;2729*q ='\0';2730if(rmdir(git_path("%s", name)))2731break;2732}2733}27342735/* make sure nobody touched the ref, and unlink */2736static voidprune_ref(struct ref_to_prune *r)2737{2738struct ref_transaction *transaction;2739struct strbuf err = STRBUF_INIT;27402741if(check_refname_format(r->name,0))2742return;27432744 transaction =ref_transaction_begin(&err);2745if(!transaction ||2746ref_transaction_delete(transaction, r->name, r->sha1,2747 REF_ISPRUNING, NULL, &err) ||2748ref_transaction_commit(transaction, &err)) {2749ref_transaction_free(transaction);2750error("%s", err.buf);2751strbuf_release(&err);2752return;2753}2754ref_transaction_free(transaction);2755strbuf_release(&err);2756try_remove_empty_parents(r->name);2757}27582759static voidprune_refs(struct ref_to_prune *r)2760{2761while(r) {2762prune_ref(r);2763 r = r->next;2764}2765}27662767intpack_refs(unsigned int flags)2768{2769struct pack_refs_cb_data cbdata;27702771memset(&cbdata,0,sizeof(cbdata));2772 cbdata.flags = flags;27732774lock_packed_refs(LOCK_DIE_ON_ERROR);2775 cbdata.packed_refs =get_packed_refs(&ref_cache);27762777do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2778 pack_if_possible_fn, &cbdata);27792780if(commit_packed_refs())2781die_errno("unable to overwrite old ref-pack file");27822783prune_refs(cbdata.ref_to_prune);2784return0;2785}27862787/*2788 * Rewrite the packed-refs file, omitting any refs listed in2789 * 'refnames'. On error, leave packed-refs unchanged, write an error2790 * message to 'err', and return a nonzero value.2791 *2792 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2793 */2794static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2795{2796struct ref_dir *packed;2797struct string_list_item *refname;2798int ret, needs_repacking =0, removed =0;27992800assert(err);28012802/* Look for a packed ref */2803for_each_string_list_item(refname, refnames) {2804if(get_packed_ref(refname->string)) {2805 needs_repacking =1;2806break;2807}2808}28092810/* Avoid locking if we have nothing to do */2811if(!needs_repacking)2812return0;/* no refname exists in packed refs */28132814if(lock_packed_refs(0)) {2815unable_to_lock_message(git_path("packed-refs"), errno, err);2816return-1;2817}2818 packed =get_packed_refs(&ref_cache);28192820/* Remove refnames from the cache */2821for_each_string_list_item(refname, refnames)2822if(remove_entry(packed, refname->string) != -1)2823 removed =1;2824if(!removed) {2825/*2826 * All packed entries disappeared while we were2827 * acquiring the lock.2828 */2829rollback_packed_refs();2830return0;2831}28322833/* Write what remains */2834 ret =commit_packed_refs();2835if(ret)2836strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2837strerror(errno));2838return ret;2839}28402841static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2842{2843assert(err);28442845if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2846/*2847 * loose. The loose file name is the same as the2848 * lockfile name, minus ".lock":2849 */2850char*loose_filename =get_locked_file_path(lock->lk);2851int res =unlink_or_msg(loose_filename, err);2852free(loose_filename);2853if(res)2854return1;2855}2856return0;2857}28582859static intis_per_worktree_ref(const char*refname)2860{2861return!strcmp(refname,"HEAD");2862}28632864static intis_pseudoref_syntax(const char*refname)2865{2866const char*c;28672868for(c = refname; *c; c++) {2869if(!isupper(*c) && *c !='-'&& *c !='_')2870return0;2871}28722873return1;2874}28752876enum ref_type ref_type(const char*refname)2877{2878if(is_per_worktree_ref(refname))2879return REF_TYPE_PER_WORKTREE;2880if(is_pseudoref_syntax(refname))2881return REF_TYPE_PSEUDOREF;2882return REF_TYPE_NORMAL;2883}28842885static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2886const unsigned char*old_sha1,struct strbuf *err)2887{2888const char*filename;2889int fd;2890static struct lock_file lock;2891struct strbuf buf = STRBUF_INIT;2892int ret = -1;28932894strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));28952896 filename =git_path("%s", pseudoref);2897 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2898if(fd <0) {2899strbuf_addf(err,"Could not open '%s' for writing:%s",2900 filename,strerror(errno));2901return-1;2902}29032904if(old_sha1) {2905unsigned char actual_old_sha1[20];29062907if(read_ref(pseudoref, actual_old_sha1))2908die("could not read ref '%s'", pseudoref);2909if(hashcmp(actual_old_sha1, old_sha1)) {2910strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2911rollback_lock_file(&lock);2912goto done;2913}2914}29152916if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2917strbuf_addf(err,"Could not write to '%s'", filename);2918rollback_lock_file(&lock);2919goto done;2920}29212922commit_lock_file(&lock);2923 ret =0;2924done:2925strbuf_release(&buf);2926return ret;2927}29282929static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2930{2931static struct lock_file lock;2932const char*filename;29332934 filename =git_path("%s", pseudoref);29352936if(old_sha1 && !is_null_sha1(old_sha1)) {2937int fd;2938unsigned char actual_old_sha1[20];29392940 fd =hold_lock_file_for_update(&lock, filename,2941 LOCK_DIE_ON_ERROR);2942if(fd <0)2943die_errno(_("Could not open '%s' for writing"), filename);2944if(read_ref(pseudoref, actual_old_sha1))2945die("could not read ref '%s'", pseudoref);2946if(hashcmp(actual_old_sha1, old_sha1)) {2947warning("Unexpected sha1 when deleting%s", pseudoref);2948rollback_lock_file(&lock);2949return-1;2950}29512952unlink(filename);2953rollback_lock_file(&lock);2954}else{2955unlink(filename);2956}29572958return0;2959}29602961intdelete_ref(const char*refname,const unsigned char*old_sha1,2962unsigned int flags)2963{2964struct ref_transaction *transaction;2965struct strbuf err = STRBUF_INIT;29662967if(ref_type(refname) == REF_TYPE_PSEUDOREF)2968returndelete_pseudoref(refname, old_sha1);29692970 transaction =ref_transaction_begin(&err);2971if(!transaction ||2972ref_transaction_delete(transaction, refname, old_sha1,2973 flags, NULL, &err) ||2974ref_transaction_commit(transaction, &err)) {2975error("%s", err.buf);2976ref_transaction_free(transaction);2977strbuf_release(&err);2978return1;2979}2980ref_transaction_free(transaction);2981strbuf_release(&err);2982return0;2983}29842985intdelete_refs(struct string_list *refnames)2986{2987struct strbuf err = STRBUF_INIT;2988int i, result =0;29892990if(!refnames->nr)2991return0;29922993 result =repack_without_refs(refnames, &err);2994if(result) {2995/*2996 * If we failed to rewrite the packed-refs file, then2997 * it is unsafe to try to remove loose refs, because2998 * doing so might expose an obsolete packed value for2999 * a reference that might even point at an object that3000 * has been garbage collected.3001 */3002if(refnames->nr ==1)3003error(_("could not delete reference%s:%s"),3004 refnames->items[0].string, err.buf);3005else3006error(_("could not delete references:%s"), err.buf);30073008goto out;3009}30103011for(i =0; i < refnames->nr; i++) {3012const char*refname = refnames->items[i].string;30133014if(delete_ref(refname, NULL,0))3015 result |=error(_("could not remove reference%s"), refname);3016}30173018out:3019strbuf_release(&err);3020return result;3021}30223023/*3024 * People using contrib's git-new-workdir have .git/logs/refs ->3025 * /some/other/path/.git/logs/refs, and that may live on another device.3026 *3027 * IOW, to avoid cross device rename errors, the temporary renamed log must3028 * live into logs/refs.3029 */3030#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"30313032static intrename_tmp_log(const char*newrefname)3033{3034int attempts_remaining =4;3035struct strbuf path = STRBUF_INIT;3036int ret = -1;30373038 retry:3039strbuf_reset(&path);3040strbuf_git_path(&path,"logs/%s", newrefname);3041switch(safe_create_leading_directories_const(path.buf)) {3042case SCLD_OK:3043break;/* success */3044case SCLD_VANISHED:3045if(--attempts_remaining >0)3046goto retry;3047/* fall through */3048default:3049error("unable to create directory for%s", newrefname);3050goto out;3051}30523053if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {3054if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {3055/*3056 * rename(a, b) when b is an existing3057 * directory ought to result in ISDIR, but3058 * Solaris 5.8 gives ENOTDIR. Sheesh.3059 */3060if(remove_empty_directories(&path)) {3061error("Directory not empty: logs/%s", newrefname);3062goto out;3063}3064goto retry;3065}else if(errno == ENOENT && --attempts_remaining >0) {3066/*3067 * Maybe another process just deleted one of3068 * the directories in the path to newrefname.3069 * Try again from the beginning.3070 */3071goto retry;3072}else{3073error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",3074 newrefname,strerror(errno));3075goto out;3076}3077}3078 ret =0;3079out:3080strbuf_release(&path);3081return ret;3082}30833084static intrename_ref_available(const char*oldname,const char*newname)3085{3086struct string_list skip = STRING_LIST_INIT_NODUP;3087struct strbuf err = STRBUF_INIT;3088int ret;30893090string_list_insert(&skip, oldname);3091 ret = !verify_refname_available(newname, NULL, &skip,3092get_packed_refs(&ref_cache), &err)3093&& !verify_refname_available(newname, NULL, &skip,3094get_loose_refs(&ref_cache), &err);3095if(!ret)3096error("%s", err.buf);30973098string_list_clear(&skip,0);3099strbuf_release(&err);3100return ret;3101}31023103static intwrite_ref_to_lockfile(struct ref_lock *lock,3104const unsigned char*sha1,struct strbuf *err);3105static intcommit_ref_update(struct ref_lock *lock,3106const unsigned char*sha1,const char*logmsg,3107int flags,struct strbuf *err);31083109intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3110{3111unsigned char sha1[20], orig_sha1[20];3112int flag =0, logmoved =0;3113struct ref_lock *lock;3114struct stat loginfo;3115int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3116const char*symref = NULL;3117struct strbuf err = STRBUF_INIT;31183119if(log &&S_ISLNK(loginfo.st_mode))3120returnerror("reflog for%sis a symlink", oldrefname);31213122 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3123 orig_sha1, &flag);3124if(flag & REF_ISSYMREF)3125returnerror("refname%sis a symbolic ref, renaming it is not supported",3126 oldrefname);3127if(!symref)3128returnerror("refname%snot found", oldrefname);31293130if(!rename_ref_available(oldrefname, newrefname))3131return1;31323133if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3134returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3135 oldrefname,strerror(errno));31363137if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3138error("unable to delete old%s", oldrefname);3139goto rollback;3140}31413142if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3143delete_ref(newrefname, sha1, REF_NODEREF)) {3144if(errno==EISDIR) {3145struct strbuf path = STRBUF_INIT;3146int result;31473148strbuf_git_path(&path,"%s", newrefname);3149 result =remove_empty_directories(&path);3150strbuf_release(&path);31513152if(result) {3153error("Directory not empty:%s", newrefname);3154goto rollback;3155}3156}else{3157error("unable to delete existing%s", newrefname);3158goto rollback;3159}3160}31613162if(log &&rename_tmp_log(newrefname))3163goto rollback;31643165 logmoved = log;31663167 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3168if(!lock) {3169error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3170strbuf_release(&err);3171goto rollback;3172}3173hashcpy(lock->old_oid.hash, orig_sha1);31743175if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3176commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3177error("unable to write current sha1 into%s:%s", newrefname, err.buf);3178strbuf_release(&err);3179goto rollback;3180}31813182return0;31833184 rollback:3185 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3186if(!lock) {3187error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3188strbuf_release(&err);3189goto rollbacklog;3190}31913192 flag = log_all_ref_updates;3193 log_all_ref_updates =0;3194if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3195commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3196error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3197strbuf_release(&err);3198}3199 log_all_ref_updates = flag;32003201 rollbacklog:3202if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3203error("unable to restore logfile%sfrom%s:%s",3204 oldrefname, newrefname,strerror(errno));3205if(!logmoved && log &&3206rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3207error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3208 oldrefname,strerror(errno));32093210return1;3211}32123213static intclose_ref(struct ref_lock *lock)3214{3215if(close_lock_file(lock->lk))3216return-1;3217return0;3218}32193220static intcommit_ref(struct ref_lock *lock)3221{3222if(commit_lock_file(lock->lk))3223return-1;3224return0;3225}32263227/*3228 * copy the reflog message msg to buf, which has been allocated sufficiently3229 * large, while cleaning up the whitespaces. Especially, convert LF to space,3230 * because reflog file is one line per entry.3231 */3232static intcopy_msg(char*buf,const char*msg)3233{3234char*cp = buf;3235char c;3236int wasspace =1;32373238*cp++ ='\t';3239while((c = *msg++)) {3240if(wasspace &&isspace(c))3241continue;3242 wasspace =isspace(c);3243if(wasspace)3244 c =' ';3245*cp++ = c;3246}3247while(buf < cp &&isspace(cp[-1]))3248 cp--;3249*cp++ ='\n';3250return cp - buf;3251}32523253static intshould_autocreate_reflog(const char*refname)3254{3255if(!log_all_ref_updates)3256return0;3257returnstarts_with(refname,"refs/heads/") ||3258starts_with(refname,"refs/remotes/") ||3259starts_with(refname,"refs/notes/") ||3260!strcmp(refname,"HEAD");3261}32623263/*3264 * Create a reflog for a ref. If force_create = 0, the reflog will3265 * only be created for certain refs (those for which3266 * should_autocreate_reflog returns non-zero. Otherwise, create it3267 * regardless of the ref name. Fill in *err and return -1 on failure.3268 */3269static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3270{3271int logfd, oflags = O_APPEND | O_WRONLY;32723273strbuf_git_path(logfile,"logs/%s", refname);3274if(force_create ||should_autocreate_reflog(refname)) {3275if(safe_create_leading_directories(logfile->buf) <0) {3276strbuf_addf(err,"unable to create directory for%s: "3277"%s", logfile->buf,strerror(errno));3278return-1;3279}3280 oflags |= O_CREAT;3281}32823283 logfd =open(logfile->buf, oflags,0666);3284if(logfd <0) {3285if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3286return0;32873288if(errno == EISDIR) {3289if(remove_empty_directories(logfile)) {3290strbuf_addf(err,"There are still logs under "3291"'%s'", logfile->buf);3292return-1;3293}3294 logfd =open(logfile->buf, oflags,0666);3295}32963297if(logfd <0) {3298strbuf_addf(err,"unable to append to%s:%s",3299 logfile->buf,strerror(errno));3300return-1;3301}3302}33033304adjust_shared_perm(logfile->buf);3305close(logfd);3306return0;3307}330833093310intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3311{3312int ret;3313struct strbuf sb = STRBUF_INIT;33143315 ret =log_ref_setup(refname, &sb, err, force_create);3316strbuf_release(&sb);3317return ret;3318}33193320static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3321const unsigned char*new_sha1,3322const char*committer,const char*msg)3323{3324int msglen, written;3325unsigned maxlen, len;3326char*logrec;33273328 msglen = msg ?strlen(msg) :0;3329 maxlen =strlen(committer) + msglen +100;3330 logrec =xmalloc(maxlen);3331 len =xsnprintf(logrec, maxlen,"%s %s %s\n",3332sha1_to_hex(old_sha1),3333sha1_to_hex(new_sha1),3334 committer);3335if(msglen)3336 len +=copy_msg(logrec + len -1, msg) -1;33373338 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3339free(logrec);3340if(written != len)3341return-1;33423343return0;3344}33453346static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3347const unsigned char*new_sha1,const char*msg,3348struct strbuf *logfile,int flags,3349struct strbuf *err)3350{3351int logfd, result, oflags = O_APPEND | O_WRONLY;33523353if(log_all_ref_updates <0)3354 log_all_ref_updates = !is_bare_repository();33553356 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);33573358if(result)3359return result;33603361 logfd =open(logfile->buf, oflags);3362if(logfd <0)3363return0;3364 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3365git_committer_info(0), msg);3366if(result) {3367strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3368strerror(errno));3369close(logfd);3370return-1;3371}3372if(close(logfd)) {3373strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3374strerror(errno));3375return-1;3376}3377return0;3378}33793380static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3381const unsigned char*new_sha1,const char*msg,3382int flags,struct strbuf *err)3383{3384struct strbuf sb = STRBUF_INIT;3385int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3386 err);3387strbuf_release(&sb);3388return ret;3389}33903391intis_branch(const char*refname)3392{3393return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3394}33953396/*3397 * Write sha1 into the open lockfile, then close the lockfile. On3398 * errors, rollback the lockfile, fill in *err and3399 * return -1.3400 */3401static intwrite_ref_to_lockfile(struct ref_lock *lock,3402const unsigned char*sha1,struct strbuf *err)3403{3404static char term ='\n';3405struct object *o;3406int fd;34073408 o =parse_object(sha1);3409if(!o) {3410strbuf_addf(err,3411"Trying to write ref%swith nonexistent object%s",3412 lock->ref_name,sha1_to_hex(sha1));3413unlock_ref(lock);3414return-1;3415}3416if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3417strbuf_addf(err,3418"Trying to write non-commit object%sto branch%s",3419sha1_to_hex(sha1), lock->ref_name);3420unlock_ref(lock);3421return-1;3422}3423 fd =get_lock_file_fd(lock->lk);3424if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3425write_in_full(fd, &term,1) !=1||3426close_ref(lock) <0) {3427strbuf_addf(err,3428"Couldn't write%s",get_lock_file_path(lock->lk));3429unlock_ref(lock);3430return-1;3431}3432return0;3433}34343435/*3436 * Commit a change to a loose reference that has already been written3437 * to the loose reference lockfile. Also update the reflogs if3438 * necessary, using the specified lockmsg (which can be NULL).3439 */3440static intcommit_ref_update(struct ref_lock *lock,3441const unsigned char*sha1,const char*logmsg,3442int flags,struct strbuf *err)3443{3444clear_loose_ref_cache(&ref_cache);3445if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3446(strcmp(lock->ref_name, lock->orig_ref_name) &&3447log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3448char*old_msg =strbuf_detach(err, NULL);3449strbuf_addf(err,"Cannot update the ref '%s':%s",3450 lock->ref_name, old_msg);3451free(old_msg);3452unlock_ref(lock);3453return-1;3454}3455if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3456/*3457 * Special hack: If a branch is updated directly and HEAD3458 * points to it (may happen on the remote side of a push3459 * for example) then logically the HEAD reflog should be3460 * updated too.3461 * A generic solution implies reverse symref information,3462 * but finding all symrefs pointing to the given branch3463 * would be rather costly for this rare event (the direct3464 * update of a branch) to be worth it. So let's cheat and3465 * check with HEAD only which should cover 99% of all usage3466 * scenarios (even 100% of the default ones).3467 */3468unsigned char head_sha1[20];3469int head_flag;3470const char*head_ref;3471 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3472 head_sha1, &head_flag);3473if(head_ref && (head_flag & REF_ISSYMREF) &&3474!strcmp(head_ref, lock->ref_name)) {3475struct strbuf log_err = STRBUF_INIT;3476if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3477 logmsg,0, &log_err)) {3478error("%s", log_err.buf);3479strbuf_release(&log_err);3480}3481}3482}3483if(commit_ref(lock)) {3484error("Couldn't set%s", lock->ref_name);3485unlock_ref(lock);3486return-1;3487}34883489unlock_ref(lock);3490return0;3491}34923493intcreate_symref(const char*ref_target,const char*refs_heads_master,3494const char*logmsg)3495{3496char*lockpath = NULL;3497char ref[1000];3498int fd, len, written;3499char*git_HEAD =git_pathdup("%s", ref_target);3500unsigned char old_sha1[20], new_sha1[20];3501struct strbuf err = STRBUF_INIT;35023503if(logmsg &&read_ref(ref_target, old_sha1))3504hashclr(old_sha1);35053506if(safe_create_leading_directories(git_HEAD) <0)3507returnerror("unable to create directory for%s", git_HEAD);35083509#ifndef NO_SYMLINK_HEAD3510if(prefer_symlink_refs) {3511unlink(git_HEAD);3512if(!symlink(refs_heads_master, git_HEAD))3513goto done;3514fprintf(stderr,"no symlink - falling back to symbolic ref\n");3515}3516#endif35173518 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3519if(sizeof(ref) <= len) {3520error("refname too long:%s", refs_heads_master);3521goto error_free_return;3522}3523 lockpath =mkpathdup("%s.lock", git_HEAD);3524 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3525if(fd <0) {3526error("Unable to open%sfor writing", lockpath);3527goto error_free_return;3528}3529 written =write_in_full(fd, ref, len);3530if(close(fd) !=0|| written != len) {3531error("Unable to write to%s", lockpath);3532goto error_unlink_return;3533}3534if(rename(lockpath, git_HEAD) <0) {3535error("Unable to create%s", git_HEAD);3536goto error_unlink_return;3537}3538if(adjust_shared_perm(git_HEAD)) {3539error("Unable to fix permissions on%s", lockpath);3540 error_unlink_return:3541unlink_or_warn(lockpath);3542 error_free_return:3543free(lockpath);3544free(git_HEAD);3545return-1;3546}3547free(lockpath);35483549#ifndef NO_SYMLINK_HEAD3550 done:3551#endif3552if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3553log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3554error("%s", err.buf);3555strbuf_release(&err);3556}35573558free(git_HEAD);3559return0;3560}35613562struct read_ref_at_cb {3563const char*refname;3564unsigned long at_time;3565int cnt;3566int reccnt;3567unsigned char*sha1;3568int found_it;35693570unsigned char osha1[20];3571unsigned char nsha1[20];3572int tz;3573unsigned long date;3574char**msg;3575unsigned long*cutoff_time;3576int*cutoff_tz;3577int*cutoff_cnt;3578};35793580static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3581const char*email,unsigned long timestamp,int tz,3582const char*message,void*cb_data)3583{3584struct read_ref_at_cb *cb = cb_data;35853586 cb->reccnt++;3587 cb->tz = tz;3588 cb->date = timestamp;35893590if(timestamp <= cb->at_time || cb->cnt ==0) {3591if(cb->msg)3592*cb->msg =xstrdup(message);3593if(cb->cutoff_time)3594*cb->cutoff_time = timestamp;3595if(cb->cutoff_tz)3596*cb->cutoff_tz = tz;3597if(cb->cutoff_cnt)3598*cb->cutoff_cnt = cb->reccnt -1;3599/*3600 * we have not yet updated cb->[n|o]sha1 so they still3601 * hold the values for the previous record.3602 */3603if(!is_null_sha1(cb->osha1)) {3604hashcpy(cb->sha1, nsha1);3605if(hashcmp(cb->osha1, nsha1))3606warning("Log for ref%shas gap after%s.",3607 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3608}3609else if(cb->date == cb->at_time)3610hashcpy(cb->sha1, nsha1);3611else if(hashcmp(nsha1, cb->sha1))3612warning("Log for ref%sunexpectedly ended on%s.",3613 cb->refname,show_date(cb->date, cb->tz,3614DATE_MODE(RFC2822)));3615hashcpy(cb->osha1, osha1);3616hashcpy(cb->nsha1, nsha1);3617 cb->found_it =1;3618return1;3619}3620hashcpy(cb->osha1, osha1);3621hashcpy(cb->nsha1, nsha1);3622if(cb->cnt >0)3623 cb->cnt--;3624return0;3625}36263627static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3628const char*email,unsigned long timestamp,3629int tz,const char*message,void*cb_data)3630{3631struct read_ref_at_cb *cb = cb_data;36323633if(cb->msg)3634*cb->msg =xstrdup(message);3635if(cb->cutoff_time)3636*cb->cutoff_time = timestamp;3637if(cb->cutoff_tz)3638*cb->cutoff_tz = tz;3639if(cb->cutoff_cnt)3640*cb->cutoff_cnt = cb->reccnt;3641hashcpy(cb->sha1, osha1);3642if(is_null_sha1(cb->sha1))3643hashcpy(cb->sha1, nsha1);3644/* We just want the first entry */3645return1;3646}36473648intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3649unsigned char*sha1,char**msg,3650unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3651{3652struct read_ref_at_cb cb;36533654memset(&cb,0,sizeof(cb));3655 cb.refname = refname;3656 cb.at_time = at_time;3657 cb.cnt = cnt;3658 cb.msg = msg;3659 cb.cutoff_time = cutoff_time;3660 cb.cutoff_tz = cutoff_tz;3661 cb.cutoff_cnt = cutoff_cnt;3662 cb.sha1 = sha1;36633664for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);36653666if(!cb.reccnt) {3667if(flags & GET_SHA1_QUIETLY)3668exit(128);3669else3670die("Log for%sis empty.", refname);3671}3672if(cb.found_it)3673return0;36743675for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);36763677return1;3678}36793680intreflog_exists(const char*refname)3681{3682struct stat st;36833684return!lstat(git_path("logs/%s", refname), &st) &&3685S_ISREG(st.st_mode);3686}36873688intdelete_reflog(const char*refname)3689{3690returnremove_path(git_path("logs/%s", refname));3691}36923693static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3694{3695unsigned char osha1[20], nsha1[20];3696char*email_end, *message;3697unsigned long timestamp;3698int tz;36993700/* old SP new SP name <email> SP time TAB msg LF */3701if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3702get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3703get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3704!(email_end =strchr(sb->buf +82,'>')) ||3705 email_end[1] !=' '||3706!(timestamp =strtoul(email_end +2, &message,10)) ||3707!message || message[0] !=' '||3708(message[1] !='+'&& message[1] !='-') ||3709!isdigit(message[2]) || !isdigit(message[3]) ||3710!isdigit(message[4]) || !isdigit(message[5]))3711return0;/* corrupt? */3712 email_end[1] ='\0';3713 tz =strtol(message +1, NULL,10);3714if(message[6] !='\t')3715 message +=6;3716else3717 message +=7;3718returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3719}37203721static char*find_beginning_of_line(char*bob,char*scan)3722{3723while(bob < scan && *(--scan) !='\n')3724;/* keep scanning backwards */3725/*3726 * Return either beginning of the buffer, or LF at the end of3727 * the previous line.3728 */3729return scan;3730}37313732intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3733{3734struct strbuf sb = STRBUF_INIT;3735FILE*logfp;3736long pos;3737int ret =0, at_tail =1;37383739 logfp =fopen(git_path("logs/%s", refname),"r");3740if(!logfp)3741return-1;37423743/* Jump to the end */3744if(fseek(logfp,0, SEEK_END) <0)3745returnerror("cannot seek back reflog for%s:%s",3746 refname,strerror(errno));3747 pos =ftell(logfp);3748while(!ret &&0< pos) {3749int cnt;3750size_t nread;3751char buf[BUFSIZ];3752char*endp, *scanp;37533754/* Fill next block from the end */3755 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3756if(fseek(logfp, pos - cnt, SEEK_SET))3757returnerror("cannot seek back reflog for%s:%s",3758 refname,strerror(errno));3759 nread =fread(buf, cnt,1, logfp);3760if(nread !=1)3761returnerror("cannot read%dbytes from reflog for%s:%s",3762 cnt, refname,strerror(errno));3763 pos -= cnt;37643765 scanp = endp = buf + cnt;3766if(at_tail && scanp[-1] =='\n')3767/* Looking at the final LF at the end of the file */3768 scanp--;3769 at_tail =0;37703771while(buf < scanp) {3772/*3773 * terminating LF of the previous line, or the beginning3774 * of the buffer.3775 */3776char*bp;37773778 bp =find_beginning_of_line(buf, scanp);37793780if(*bp =='\n') {3781/*3782 * The newline is the end of the previous line,3783 * so we know we have complete line starting3784 * at (bp + 1). Prefix it onto any prior data3785 * we collected for the line and process it.3786 */3787strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3788 scanp = bp;3789 endp = bp +1;3790 ret =show_one_reflog_ent(&sb, fn, cb_data);3791strbuf_reset(&sb);3792if(ret)3793break;3794}else if(!pos) {3795/*3796 * We are at the start of the buffer, and the3797 * start of the file; there is no previous3798 * line, and we have everything for this one.3799 * Process it, and we can end the loop.3800 */3801strbuf_splice(&sb,0,0, buf, endp - buf);3802 ret =show_one_reflog_ent(&sb, fn, cb_data);3803strbuf_reset(&sb);3804break;3805}38063807if(bp == buf) {3808/*3809 * We are at the start of the buffer, and there3810 * is more file to read backwards. Which means3811 * we are in the middle of a line. Note that we3812 * may get here even if *bp was a newline; that3813 * just means we are at the exact end of the3814 * previous line, rather than some spot in the3815 * middle.3816 *3817 * Save away what we have to be combined with3818 * the data from the next read.3819 */3820strbuf_splice(&sb,0,0, buf, endp - buf);3821break;3822}3823}38243825}3826if(!ret && sb.len)3827die("BUG: reverse reflog parser had leftover data");38283829fclose(logfp);3830strbuf_release(&sb);3831return ret;3832}38333834intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3835{3836FILE*logfp;3837struct strbuf sb = STRBUF_INIT;3838int ret =0;38393840 logfp =fopen(git_path("logs/%s", refname),"r");3841if(!logfp)3842return-1;38433844while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3845 ret =show_one_reflog_ent(&sb, fn, cb_data);3846fclose(logfp);3847strbuf_release(&sb);3848return ret;3849}3850/*3851 * Call fn for each reflog in the namespace indicated by name. name3852 * must be empty or end with '/'. Name will be used as a scratch3853 * space, but its contents will be restored before return.3854 */3855static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3856{3857DIR*d =opendir(git_path("logs/%s", name->buf));3858int retval =0;3859struct dirent *de;3860int oldlen = name->len;38613862if(!d)3863return name->len ? errno :0;38643865while((de =readdir(d)) != NULL) {3866struct stat st;38673868if(de->d_name[0] =='.')3869continue;3870if(ends_with(de->d_name,".lock"))3871continue;3872strbuf_addstr(name, de->d_name);3873if(stat(git_path("logs/%s", name->buf), &st) <0) {3874;/* silently ignore */3875}else{3876if(S_ISDIR(st.st_mode)) {3877strbuf_addch(name,'/');3878 retval =do_for_each_reflog(name, fn, cb_data);3879}else{3880struct object_id oid;38813882if(read_ref_full(name->buf,0, oid.hash, NULL))3883 retval =error("bad ref for%s", name->buf);3884else3885 retval =fn(name->buf, &oid,0, cb_data);3886}3887if(retval)3888break;3889}3890strbuf_setlen(name, oldlen);3891}3892closedir(d);3893return retval;3894}38953896intfor_each_reflog(each_ref_fn fn,void*cb_data)3897{3898int retval;3899struct strbuf name;3900strbuf_init(&name, PATH_MAX);3901 retval =do_for_each_reflog(&name, fn, cb_data);3902strbuf_release(&name);3903return retval;3904}39053906/**3907 * Information needed for a single ref update. Set new_sha1 to the new3908 * value or to null_sha1 to delete the ref. To check the old value3909 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3910 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3911 * not exist before update.3912 */3913struct ref_update {3914/*3915 * If (flags & REF_HAVE_NEW), set the reference to this value:3916 */3917unsigned char new_sha1[20];3918/*3919 * If (flags & REF_HAVE_OLD), check that the reference3920 * previously had this value:3921 */3922unsigned char old_sha1[20];3923/*3924 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3925 * REF_DELETING, and REF_ISPRUNING:3926 */3927unsigned int flags;3928struct ref_lock *lock;3929int type;3930char*msg;3931const char refname[FLEX_ARRAY];3932};39333934/*3935 * Transaction states.3936 * OPEN: The transaction is in a valid state and can accept new updates.3937 * An OPEN transaction can be committed.3938 * CLOSED: A closed transaction is no longer active and no other operations3939 * than free can be used on it in this state.3940 * A transaction can either become closed by successfully committing3941 * an active transaction or if there is a failure while building3942 * the transaction thus rendering it failed/inactive.3943 */3944enum ref_transaction_state {3945 REF_TRANSACTION_OPEN =0,3946 REF_TRANSACTION_CLOSED =13947};39483949/*3950 * Data structure for holding a reference transaction, which can3951 * consist of checks and updates to multiple references, carried out3952 * as atomically as possible. This structure is opaque to callers.3953 */3954struct ref_transaction {3955struct ref_update **updates;3956size_t alloc;3957size_t nr;3958enum ref_transaction_state state;3959};39603961struct ref_transaction *ref_transaction_begin(struct strbuf *err)3962{3963assert(err);39643965returnxcalloc(1,sizeof(struct ref_transaction));3966}39673968voidref_transaction_free(struct ref_transaction *transaction)3969{3970int i;39713972if(!transaction)3973return;39743975for(i =0; i < transaction->nr; i++) {3976free(transaction->updates[i]->msg);3977free(transaction->updates[i]);3978}3979free(transaction->updates);3980free(transaction);3981}39823983static struct ref_update *add_update(struct ref_transaction *transaction,3984const char*refname)3985{3986size_t len =strlen(refname) +1;3987struct ref_update *update =xcalloc(1,sizeof(*update) + len);39883989memcpy((char*)update->refname, refname, len);/* includes NUL */3990ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3991 transaction->updates[transaction->nr++] = update;3992return update;3993}39943995intref_transaction_update(struct ref_transaction *transaction,3996const char*refname,3997const unsigned char*new_sha1,3998const unsigned char*old_sha1,3999unsigned int flags,const char*msg,4000struct strbuf *err)4001{4002struct ref_update *update;40034004assert(err);40054006if(transaction->state != REF_TRANSACTION_OPEN)4007die("BUG: update called for transaction that is not open");40084009if(new_sha1 && !is_null_sha1(new_sha1) &&4010check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {4011strbuf_addf(err,"refusing to update ref with bad name%s",4012 refname);4013return-1;4014}40154016 update =add_update(transaction, refname);4017if(new_sha1) {4018hashcpy(update->new_sha1, new_sha1);4019 flags |= REF_HAVE_NEW;4020}4021if(old_sha1) {4022hashcpy(update->old_sha1, old_sha1);4023 flags |= REF_HAVE_OLD;4024}4025 update->flags = flags;4026if(msg)4027 update->msg =xstrdup(msg);4028return0;4029}40304031intref_transaction_create(struct ref_transaction *transaction,4032const char*refname,4033const unsigned char*new_sha1,4034unsigned int flags,const char*msg,4035struct strbuf *err)4036{4037if(!new_sha1 ||is_null_sha1(new_sha1))4038die("BUG: create called without valid new_sha1");4039returnref_transaction_update(transaction, refname, new_sha1,4040 null_sha1, flags, msg, err);4041}40424043intref_transaction_delete(struct ref_transaction *transaction,4044const char*refname,4045const unsigned char*old_sha1,4046unsigned int flags,const char*msg,4047struct strbuf *err)4048{4049if(old_sha1 &&is_null_sha1(old_sha1))4050die("BUG: delete called with old_sha1 set to zeros");4051returnref_transaction_update(transaction, refname,4052 null_sha1, old_sha1,4053 flags, msg, err);4054}40554056intref_transaction_verify(struct ref_transaction *transaction,4057const char*refname,4058const unsigned char*old_sha1,4059unsigned int flags,4060struct strbuf *err)4061{4062if(!old_sha1)4063die("BUG: verify called with old_sha1 set to NULL");4064returnref_transaction_update(transaction, refname,4065 NULL, old_sha1,4066 flags, NULL, err);4067}40684069intupdate_ref(const char*msg,const char*refname,4070const unsigned char*new_sha1,const unsigned char*old_sha1,4071unsigned int flags,enum action_on_err onerr)4072{4073struct ref_transaction *t = NULL;4074struct strbuf err = STRBUF_INIT;4075int ret =0;40764077if(ref_type(refname) == REF_TYPE_PSEUDOREF) {4078 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);4079}else{4080 t =ref_transaction_begin(&err);4081if(!t ||4082ref_transaction_update(t, refname, new_sha1, old_sha1,4083 flags, msg, &err) ||4084ref_transaction_commit(t, &err)) {4085 ret =1;4086ref_transaction_free(t);4087}4088}4089if(ret) {4090const char*str ="update_ref failed for ref '%s':%s";40914092switch(onerr) {4093case UPDATE_REFS_MSG_ON_ERR:4094error(str, refname, err.buf);4095break;4096case UPDATE_REFS_DIE_ON_ERR:4097die(str, refname, err.buf);4098break;4099case UPDATE_REFS_QUIET_ON_ERR:4100break;4101}4102strbuf_release(&err);4103return1;4104}4105strbuf_release(&err);4106if(t)4107ref_transaction_free(t);4108return0;4109}41104111static intref_update_reject_duplicates(struct string_list *refnames,4112struct strbuf *err)4113{4114int i, n = refnames->nr;41154116assert(err);41174118for(i =1; i < n; i++)4119if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4120strbuf_addf(err,4121"Multiple updates for ref '%s' not allowed.",4122 refnames->items[i].string);4123return1;4124}4125return0;4126}41274128intref_transaction_commit(struct ref_transaction *transaction,4129struct strbuf *err)4130{4131int ret =0, i;4132int n = transaction->nr;4133struct ref_update **updates = transaction->updates;4134struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4135struct string_list_item *ref_to_delete;4136struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41374138assert(err);41394140if(transaction->state != REF_TRANSACTION_OPEN)4141die("BUG: commit called for transaction that is not open");41424143if(!n) {4144 transaction->state = REF_TRANSACTION_CLOSED;4145return0;4146}41474148/* Fail if a refname appears more than once in the transaction: */4149for(i =0; i < n; i++)4150string_list_append(&affected_refnames, updates[i]->refname);4151string_list_sort(&affected_refnames);4152if(ref_update_reject_duplicates(&affected_refnames, err)) {4153 ret = TRANSACTION_GENERIC_ERROR;4154goto cleanup;4155}41564157/*4158 * Acquire all locks, verify old values if provided, check4159 * that new values are valid, and write new values to the4160 * lockfiles, ready to be activated. Only keep one lockfile4161 * open at a time to avoid running out of file descriptors.4162 */4163for(i =0; i < n; i++) {4164struct ref_update *update = updates[i];41654166if((update->flags & REF_HAVE_NEW) &&4167is_null_sha1(update->new_sha1))4168 update->flags |= REF_DELETING;4169 update->lock =lock_ref_sha1_basic(4170 update->refname,4171((update->flags & REF_HAVE_OLD) ?4172 update->old_sha1 : NULL),4173&affected_refnames, NULL,4174 update->flags,4175&update->type,4176 err);4177if(!update->lock) {4178char*reason;41794180 ret = (errno == ENOTDIR)4181? TRANSACTION_NAME_CONFLICT4182: TRANSACTION_GENERIC_ERROR;4183 reason =strbuf_detach(err, NULL);4184strbuf_addf(err,"cannot lock ref '%s':%s",4185 update->refname, reason);4186free(reason);4187goto cleanup;4188}4189if((update->flags & REF_HAVE_NEW) &&4190!(update->flags & REF_DELETING)) {4191int overwriting_symref = ((update->type & REF_ISSYMREF) &&4192(update->flags & REF_NODEREF));41934194if(!overwriting_symref &&4195!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4196/*4197 * The reference already has the desired4198 * value, so we don't need to write it.4199 */4200}else if(write_ref_to_lockfile(update->lock,4201 update->new_sha1,4202 err)) {4203char*write_err =strbuf_detach(err, NULL);42044205/*4206 * The lock was freed upon failure of4207 * write_ref_to_lockfile():4208 */4209 update->lock = NULL;4210strbuf_addf(err,4211"cannot update the ref '%s':%s",4212 update->refname, write_err);4213free(write_err);4214 ret = TRANSACTION_GENERIC_ERROR;4215goto cleanup;4216}else{4217 update->flags |= REF_NEEDS_COMMIT;4218}4219}4220if(!(update->flags & REF_NEEDS_COMMIT)) {4221/*4222 * We didn't have to write anything to the lockfile.4223 * Close it to free up the file descriptor:4224 */4225if(close_ref(update->lock)) {4226strbuf_addf(err,"Couldn't close%s.lock",4227 update->refname);4228goto cleanup;4229}4230}4231}42324233/* Perform updates first so live commits remain referenced */4234for(i =0; i < n; i++) {4235struct ref_update *update = updates[i];42364237if(update->flags & REF_NEEDS_COMMIT) {4238if(commit_ref_update(update->lock,4239 update->new_sha1, update->msg,4240 update->flags, err)) {4241/* freed by commit_ref_update(): */4242 update->lock = NULL;4243 ret = TRANSACTION_GENERIC_ERROR;4244goto cleanup;4245}else{4246/* freed by commit_ref_update(): */4247 update->lock = NULL;4248}4249}4250}42514252/* Perform deletes now that updates are safely completed */4253for(i =0; i < n; i++) {4254struct ref_update *update = updates[i];42554256if(update->flags & REF_DELETING) {4257if(delete_ref_loose(update->lock, update->type, err)) {4258 ret = TRANSACTION_GENERIC_ERROR;4259goto cleanup;4260}42614262if(!(update->flags & REF_ISPRUNING))4263string_list_append(&refs_to_delete,4264 update->lock->ref_name);4265}4266}42674268if(repack_without_refs(&refs_to_delete, err)) {4269 ret = TRANSACTION_GENERIC_ERROR;4270goto cleanup;4271}4272for_each_string_list_item(ref_to_delete, &refs_to_delete)4273unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4274clear_loose_ref_cache(&ref_cache);42754276cleanup:4277 transaction->state = REF_TRANSACTION_CLOSED;42784279for(i =0; i < n; i++)4280if(updates[i]->lock)4281unlock_ref(updates[i]->lock);4282string_list_clear(&refs_to_delete,0);4283string_list_clear(&affected_refnames,0);4284return ret;4285}42864287static intref_present(const char*refname,4288const struct object_id *oid,int flags,void*cb_data)4289{4290struct string_list *affected_refnames = cb_data;42914292returnstring_list_has_string(affected_refnames, refname);4293}42944295intinitial_ref_transaction_commit(struct ref_transaction *transaction,4296struct strbuf *err)4297{4298struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4299struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4300int ret =0, i;4301int n = transaction->nr;4302struct ref_update **updates = transaction->updates;4303struct string_list affected_refnames = STRING_LIST_INIT_NODUP;43044305assert(err);43064307if(transaction->state != REF_TRANSACTION_OPEN)4308die("BUG: commit called for transaction that is not open");43094310/* Fail if a refname appears more than once in the transaction: */4311for(i =0; i < n; i++)4312string_list_append(&affected_refnames, updates[i]->refname);4313string_list_sort(&affected_refnames);4314if(ref_update_reject_duplicates(&affected_refnames, err)) {4315 ret = TRANSACTION_GENERIC_ERROR;4316goto cleanup;4317}43184319/*4320 * It's really undefined to call this function in an active4321 * repository or when there are existing references: we are4322 * only locking and changing packed-refs, so (1) any4323 * simultaneous processes might try to change a reference at4324 * the same time we do, and (2) any existing loose versions of4325 * the references that we are setting would have precedence4326 * over our values. But some remote helpers create the remote4327 * "HEAD" and "master" branches before calling this function,4328 * so here we really only check that none of the references4329 * that we are creating already exists.4330 */4331if(for_each_rawref(ref_present, &affected_refnames))4332die("BUG: initial ref transaction called with existing refs");43334334for(i =0; i < n; i++) {4335struct ref_update *update = updates[i];43364337if((update->flags & REF_HAVE_OLD) &&4338!is_null_sha1(update->old_sha1))4339die("BUG: initial ref transaction with old_sha1 set");4340if(verify_refname_available(update->refname,4341&affected_refnames, NULL,4342 loose_refs, err) ||4343verify_refname_available(update->refname,4344&affected_refnames, NULL,4345 packed_refs, err)) {4346 ret = TRANSACTION_NAME_CONFLICT;4347goto cleanup;4348}4349}43504351if(lock_packed_refs(0)) {4352strbuf_addf(err,"unable to lock packed-refs file:%s",4353strerror(errno));4354 ret = TRANSACTION_GENERIC_ERROR;4355goto cleanup;4356}43574358for(i =0; i < n; i++) {4359struct ref_update *update = updates[i];43604361if((update->flags & REF_HAVE_NEW) &&4362!is_null_sha1(update->new_sha1))4363add_packed_ref(update->refname, update->new_sha1);4364}43654366if(commit_packed_refs()) {4367strbuf_addf(err,"unable to commit packed-refs file:%s",4368strerror(errno));4369 ret = TRANSACTION_GENERIC_ERROR;4370goto cleanup;4371}43724373cleanup:4374 transaction->state = REF_TRANSACTION_CLOSED;4375string_list_clear(&affected_refnames,0);4376return ret;4377}43784379char*shorten_unambiguous_ref(const char*refname,int strict)4380{4381int i;4382static char**scanf_fmts;4383static int nr_rules;4384char*short_name;43854386if(!nr_rules) {4387/*4388 * Pre-generate scanf formats from ref_rev_parse_rules[].4389 * Generate a format suitable for scanf from a4390 * ref_rev_parse_rules rule by interpolating "%s" at the4391 * location of the "%.*s".4392 */4393size_t total_len =0;4394size_t offset =0;43954396/* the rule list is NULL terminated, count them first */4397for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4398/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4399 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;44004401 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);44024403 offset =0;4404for(i =0; i < nr_rules; i++) {4405assert(offset < total_len);4406 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4407 offset +=snprintf(scanf_fmts[i], total_len - offset,4408 ref_rev_parse_rules[i],2,"%s") +1;4409}4410}44114412/* bail out if there are no rules */4413if(!nr_rules)4414returnxstrdup(refname);44154416/* buffer for scanf result, at most refname must fit */4417 short_name =xstrdup(refname);44184419/* skip first rule, it will always match */4420for(i = nr_rules -1; i >0; --i) {4421int j;4422int rules_to_fail = i;4423int short_name_len;44244425if(1!=sscanf(refname, scanf_fmts[i], short_name))4426continue;44274428 short_name_len =strlen(short_name);44294430/*4431 * in strict mode, all (except the matched one) rules4432 * must fail to resolve to a valid non-ambiguous ref4433 */4434if(strict)4435 rules_to_fail = nr_rules;44364437/*4438 * check if the short name resolves to a valid ref,4439 * but use only rules prior to the matched one4440 */4441for(j =0; j < rules_to_fail; j++) {4442const char*rule = ref_rev_parse_rules[j];4443char refname[PATH_MAX];44444445/* skip matched rule */4446if(i == j)4447continue;44484449/*4450 * the short name is ambiguous, if it resolves4451 * (with this previous rule) to a valid ref4452 * read_ref() returns 0 on success4453 */4454mksnpath(refname,sizeof(refname),4455 rule, short_name_len, short_name);4456if(ref_exists(refname))4457break;4458}44594460/*4461 * short name is non-ambiguous if all previous rules4462 * haven't resolved to a valid ref4463 */4464if(j == rules_to_fail)4465return short_name;4466}44674468free(short_name);4469returnxstrdup(refname);4470}44714472static struct string_list *hide_refs;44734474intparse_hide_refs_config(const char*var,const char*value,const char*section)4475{4476if(!strcmp("transfer.hiderefs", var) ||4477/* NEEDSWORK: use parse_config_key() once both are merged */4478(starts_with(var, section) && var[strlen(section)] =='.'&&4479!strcmp(var +strlen(section),".hiderefs"))) {4480char*ref;4481int len;44824483if(!value)4484returnconfig_error_nonbool(var);4485 ref =xstrdup(value);4486 len =strlen(ref);4487while(len && ref[len -1] =='/')4488 ref[--len] ='\0';4489if(!hide_refs) {4490 hide_refs =xcalloc(1,sizeof(*hide_refs));4491 hide_refs->strdup_strings =1;4492}4493string_list_append(hide_refs, ref);4494}4495return0;4496}44974498intref_is_hidden(const char*refname)4499{4500int i;45014502if(!hide_refs)4503return0;4504for(i = hide_refs->nr -1; i >=0; i--) {4505const char*match = hide_refs->items[i].string;4506int neg =0;4507int len;45084509if(*match =='!') {4510 neg =1;4511 match++;4512}45134514if(!starts_with(refname, match))4515continue;4516 len =strlen(match);4517if(!refname[len] || refname[len] =='/')4518return!neg;4519}4520return0;4521}45224523struct expire_reflog_cb {4524unsigned int flags;4525 reflog_expiry_should_prune_fn *should_prune_fn;4526void*policy_cb;4527FILE*newlog;4528unsigned char last_kept_sha1[20];4529};45304531static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4532const char*email,unsigned long timestamp,int tz,4533const char*message,void*cb_data)4534{4535struct expire_reflog_cb *cb = cb_data;4536struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;45374538if(cb->flags & EXPIRE_REFLOGS_REWRITE)4539 osha1 = cb->last_kept_sha1;45404541if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4542 message, policy_cb)) {4543if(!cb->newlog)4544printf("would prune%s", message);4545else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4546printf("prune%s", message);4547}else{4548if(cb->newlog) {4549fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4550sha1_to_hex(osha1),sha1_to_hex(nsha1),4551 email, timestamp, tz, message);4552hashcpy(cb->last_kept_sha1, nsha1);4553}4554if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4555printf("keep%s", message);4556}4557return0;4558}45594560intreflog_expire(const char*refname,const unsigned char*sha1,4561unsigned int flags,4562 reflog_expiry_prepare_fn prepare_fn,4563 reflog_expiry_should_prune_fn should_prune_fn,4564 reflog_expiry_cleanup_fn cleanup_fn,4565void*policy_cb_data)4566{4567static struct lock_file reflog_lock;4568struct expire_reflog_cb cb;4569struct ref_lock *lock;4570char*log_file;4571int status =0;4572int type;4573struct strbuf err = STRBUF_INIT;45744575memset(&cb,0,sizeof(cb));4576 cb.flags = flags;4577 cb.policy_cb = policy_cb_data;4578 cb.should_prune_fn = should_prune_fn;45794580/*4581 * The reflog file is locked by holding the lock on the4582 * reference itself, plus we might need to update the4583 * reference if --updateref was specified:4584 */4585 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4586if(!lock) {4587error("cannot lock ref '%s':%s", refname, err.buf);4588strbuf_release(&err);4589return-1;4590}4591if(!reflog_exists(refname)) {4592unlock_ref(lock);4593return0;4594}45954596 log_file =git_pathdup("logs/%s", refname);4597if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4598/*4599 * Even though holding $GIT_DIR/logs/$reflog.lock has4600 * no locking implications, we use the lock_file4601 * machinery here anyway because it does a lot of the4602 * work we need, including cleaning up if the program4603 * exits unexpectedly.4604 */4605if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4606struct strbuf err = STRBUF_INIT;4607unable_to_lock_message(log_file, errno, &err);4608error("%s", err.buf);4609strbuf_release(&err);4610goto failure;4611}4612 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4613if(!cb.newlog) {4614error("cannot fdopen%s(%s)",4615get_lock_file_path(&reflog_lock),strerror(errno));4616goto failure;4617}4618}46194620(*prepare_fn)(refname, sha1, cb.policy_cb);4621for_each_reflog_ent(refname, expire_reflog_ent, &cb);4622(*cleanup_fn)(cb.policy_cb);46234624if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4625/*4626 * It doesn't make sense to adjust a reference pointed4627 * to by a symbolic ref based on expiring entries in4628 * the symbolic reference's reflog. Nor can we update4629 * a reference if there are no remaining reflog4630 * entries.4631 */4632int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4633!(type & REF_ISSYMREF) &&4634!is_null_sha1(cb.last_kept_sha1);46354636if(close_lock_file(&reflog_lock)) {4637 status |=error("couldn't write%s:%s", log_file,4638strerror(errno));4639}else if(update &&4640(write_in_full(get_lock_file_fd(lock->lk),4641sha1_to_hex(cb.last_kept_sha1),40) !=40||4642write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4643close_ref(lock) <0)) {4644 status |=error("couldn't write%s",4645get_lock_file_path(lock->lk));4646rollback_lock_file(&reflog_lock);4647}else if(commit_lock_file(&reflog_lock)) {4648 status |=error("unable to commit reflog '%s' (%s)",4649 log_file,strerror(errno));4650}else if(update &&commit_ref(lock)) {4651 status |=error("couldn't set%s", lock->ref_name);4652}4653}4654free(log_file);4655unlock_ref(lock);4656return status;46574658 failure:4659rollback_lock_file(&reflog_lock);4660free(log_file);4661unlock_ref(lock);4662return-1;4663}