1/* 2 * GIT - The information manager from hell 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This handles basic git sha1 object files - packing, unpacking, 7 * creation etc. 8 */ 9#include"cache.h" 10#include"config.h" 11#include"string-list.h" 12#include"lockfile.h" 13#include"delta.h" 14#include"pack.h" 15#include"blob.h" 16#include"commit.h" 17#include"run-command.h" 18#include"tag.h" 19#include"tree.h" 20#include"tree-walk.h" 21#include"refs.h" 22#include"pack-revindex.h" 23#include"sha1-lookup.h" 24#include"bulk-checkin.h" 25#include"streaming.h" 26#include"dir.h" 27#include"mru.h" 28#include"list.h" 29#include"mergesort.h" 30#include"quote.h" 31#include"packfile.h" 32 33const unsigned char null_sha1[20]; 34const struct object_id null_oid; 35const struct object_id empty_tree_oid = { 36 EMPTY_TREE_SHA1_BIN_LITERAL 37}; 38const struct object_id empty_blob_oid = { 39 EMPTY_BLOB_SHA1_BIN_LITERAL 40}; 41 42/* 43 * This is meant to hold a *small* number of objects that you would 44 * want read_sha1_file() to be able to return, but yet you do not want 45 * to write them into the object store (e.g. a browse-only 46 * application). 47 */ 48static struct cached_object { 49unsigned char sha1[20]; 50enum object_type type; 51void*buf; 52unsigned long size; 53} *cached_objects; 54static int cached_object_nr, cached_object_alloc; 55 56static struct cached_object empty_tree = { 57 EMPTY_TREE_SHA1_BIN_LITERAL, 58 OBJ_TREE, 59"", 600 61}; 62 63static struct cached_object *find_cached_object(const unsigned char*sha1) 64{ 65int i; 66struct cached_object *co = cached_objects; 67 68for(i =0; i < cached_object_nr; i++, co++) { 69if(!hashcmp(co->sha1, sha1)) 70return co; 71} 72if(!hashcmp(sha1, empty_tree.sha1)) 73return&empty_tree; 74return NULL; 75} 76 77intmkdir_in_gitdir(const char*path) 78{ 79if(mkdir(path,0777)) { 80int saved_errno = errno; 81struct stat st; 82struct strbuf sb = STRBUF_INIT; 83 84if(errno != EEXIST) 85return-1; 86/* 87 * Are we looking at a path in a symlinked worktree 88 * whose original repository does not yet have it? 89 * e.g. .git/rr-cache pointing at its original 90 * repository in which the user hasn't performed any 91 * conflict resolution yet? 92 */ 93if(lstat(path, &st) || !S_ISLNK(st.st_mode) || 94strbuf_readlink(&sb, path, st.st_size) || 95!is_absolute_path(sb.buf) || 96mkdir(sb.buf,0777)) { 97strbuf_release(&sb); 98 errno = saved_errno; 99return-1; 100} 101strbuf_release(&sb); 102} 103returnadjust_shared_perm(path); 104} 105 106enum scld_error safe_create_leading_directories(char*path) 107{ 108char*next_component = path +offset_1st_component(path); 109enum scld_error ret = SCLD_OK; 110 111while(ret == SCLD_OK && next_component) { 112struct stat st; 113char*slash = next_component, slash_character; 114 115while(*slash && !is_dir_sep(*slash)) 116 slash++; 117 118if(!*slash) 119break; 120 121 next_component = slash +1; 122while(is_dir_sep(*next_component)) 123 next_component++; 124if(!*next_component) 125break; 126 127 slash_character = *slash; 128*slash ='\0'; 129if(!stat(path, &st)) { 130/* path exists */ 131if(!S_ISDIR(st.st_mode)) { 132 errno = ENOTDIR; 133 ret = SCLD_EXISTS; 134} 135}else if(mkdir(path,0777)) { 136if(errno == EEXIST && 137!stat(path, &st) &&S_ISDIR(st.st_mode)) 138;/* somebody created it since we checked */ 139else if(errno == ENOENT) 140/* 141 * Either mkdir() failed because 142 * somebody just pruned the containing 143 * directory, or stat() failed because 144 * the file that was in our way was 145 * just removed. Either way, inform 146 * the caller that it might be worth 147 * trying again: 148 */ 149 ret = SCLD_VANISHED; 150else 151 ret = SCLD_FAILED; 152}else if(adjust_shared_perm(path)) { 153 ret = SCLD_PERMS; 154} 155*slash = slash_character; 156} 157return ret; 158} 159 160enum scld_error safe_create_leading_directories_const(const char*path) 161{ 162int save_errno; 163/* path points to cache entries, so xstrdup before messing with it */ 164char*buf =xstrdup(path); 165enum scld_error result =safe_create_leading_directories(buf); 166 167 save_errno = errno; 168free(buf); 169 errno = save_errno; 170return result; 171} 172 173intraceproof_create_file(const char*path, create_file_fn fn,void*cb) 174{ 175/* 176 * The number of times we will try to remove empty directories 177 * in the way of path. This is only 1 because if another 178 * process is racily creating directories that conflict with 179 * us, we don't want to fight against them. 180 */ 181int remove_directories_remaining =1; 182 183/* 184 * The number of times that we will try to create the 185 * directories containing path. We are willing to attempt this 186 * more than once, because another process could be trying to 187 * clean up empty directories at the same time as we are 188 * trying to create them. 189 */ 190int create_directories_remaining =3; 191 192/* A scratch copy of path, filled lazily if we need it: */ 193struct strbuf path_copy = STRBUF_INIT; 194 195int ret, save_errno; 196 197/* Sanity check: */ 198assert(*path); 199 200retry_fn: 201 ret =fn(path, cb); 202 save_errno = errno; 203if(!ret) 204goto out; 205 206if(errno == EISDIR && remove_directories_remaining-- >0) { 207/* 208 * A directory is in the way. Maybe it is empty; try 209 * to remove it: 210 */ 211if(!path_copy.len) 212strbuf_addstr(&path_copy, path); 213 214if(!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY)) 215goto retry_fn; 216}else if(errno == ENOENT && create_directories_remaining-- >0) { 217/* 218 * Maybe the containing directory didn't exist, or 219 * maybe it was just deleted by a process that is 220 * racing with us to clean up empty directories. Try 221 * to create it: 222 */ 223enum scld_error scld_result; 224 225if(!path_copy.len) 226strbuf_addstr(&path_copy, path); 227 228do{ 229 scld_result =safe_create_leading_directories(path_copy.buf); 230if(scld_result == SCLD_OK) 231goto retry_fn; 232}while(scld_result == SCLD_VANISHED && create_directories_remaining-- >0); 233} 234 235out: 236strbuf_release(&path_copy); 237 errno = save_errno; 238return ret; 239} 240 241static voidfill_sha1_path(struct strbuf *buf,const unsigned char*sha1) 242{ 243int i; 244for(i =0; i <20; i++) { 245static char hex[] ="0123456789abcdef"; 246unsigned int val = sha1[i]; 247strbuf_addch(buf, hex[val >>4]); 248strbuf_addch(buf, hex[val &0xf]); 249if(!i) 250strbuf_addch(buf,'/'); 251} 252} 253 254const char*sha1_file_name(const unsigned char*sha1) 255{ 256static struct strbuf buf = STRBUF_INIT; 257 258strbuf_reset(&buf); 259strbuf_addf(&buf,"%s/",get_object_directory()); 260 261fill_sha1_path(&buf, sha1); 262return buf.buf; 263} 264 265struct strbuf *alt_scratch_buf(struct alternate_object_database *alt) 266{ 267strbuf_setlen(&alt->scratch, alt->base_len); 268return&alt->scratch; 269} 270 271static const char*alt_sha1_path(struct alternate_object_database *alt, 272const unsigned char*sha1) 273{ 274struct strbuf *buf =alt_scratch_buf(alt); 275fill_sha1_path(buf, sha1); 276return buf->buf; 277} 278 279struct alternate_object_database *alt_odb_list; 280static struct alternate_object_database **alt_odb_tail; 281 282/* 283 * Return non-zero iff the path is usable as an alternate object database. 284 */ 285static intalt_odb_usable(struct strbuf *path,const char*normalized_objdir) 286{ 287struct alternate_object_database *alt; 288 289/* Detect cases where alternate disappeared */ 290if(!is_directory(path->buf)) { 291error("object directory%sdoes not exist; " 292"check .git/objects/info/alternates.", 293 path->buf); 294return0; 295} 296 297/* 298 * Prevent the common mistake of listing the same 299 * thing twice, or object directory itself. 300 */ 301for(alt = alt_odb_list; alt; alt = alt->next) { 302if(!fspathcmp(path->buf, alt->path)) 303return0; 304} 305if(!fspathcmp(path->buf, normalized_objdir)) 306return0; 307 308return1; 309} 310 311/* 312 * Prepare alternate object database registry. 313 * 314 * The variable alt_odb_list points at the list of struct 315 * alternate_object_database. The elements on this list come from 316 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT 317 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates, 318 * whose contents is similar to that environment variable but can be 319 * LF separated. Its base points at a statically allocated buffer that 320 * contains "/the/directory/corresponding/to/.git/objects/...", while 321 * its name points just after the slash at the end of ".git/objects/" 322 * in the example above, and has enough space to hold 40-byte hex 323 * SHA1, an extra slash for the first level indirection, and the 324 * terminating NUL. 325 */ 326static voidread_info_alternates(const char* relative_base,int depth); 327static intlink_alt_odb_entry(const char*entry,const char*relative_base, 328int depth,const char*normalized_objdir) 329{ 330struct alternate_object_database *ent; 331struct strbuf pathbuf = STRBUF_INIT; 332 333if(!is_absolute_path(entry) && relative_base) { 334strbuf_realpath(&pathbuf, relative_base,1); 335strbuf_addch(&pathbuf,'/'); 336} 337strbuf_addstr(&pathbuf, entry); 338 339if(strbuf_normalize_path(&pathbuf) <0&& relative_base) { 340error("unable to normalize alternate object path:%s", 341 pathbuf.buf); 342strbuf_release(&pathbuf); 343return-1; 344} 345 346/* 347 * The trailing slash after the directory name is given by 348 * this function at the end. Remove duplicates. 349 */ 350while(pathbuf.len && pathbuf.buf[pathbuf.len -1] =='/') 351strbuf_setlen(&pathbuf, pathbuf.len -1); 352 353if(!alt_odb_usable(&pathbuf, normalized_objdir)) { 354strbuf_release(&pathbuf); 355return-1; 356} 357 358 ent =alloc_alt_odb(pathbuf.buf); 359 360/* add the alternate entry */ 361*alt_odb_tail = ent; 362 alt_odb_tail = &(ent->next); 363 ent->next = NULL; 364 365/* recursively add alternates */ 366read_info_alternates(pathbuf.buf, depth +1); 367 368strbuf_release(&pathbuf); 369return0; 370} 371 372static const char*parse_alt_odb_entry(const char*string, 373int sep, 374struct strbuf *out) 375{ 376const char*end; 377 378strbuf_reset(out); 379 380if(*string =='#') { 381/* comment; consume up to next separator */ 382 end =strchrnul(string, sep); 383}else if(*string =='"'&& !unquote_c_style(out, string, &end)) { 384/* 385 * quoted path; unquote_c_style has copied the 386 * data for us and set "end". Broken quoting (e.g., 387 * an entry that doesn't end with a quote) falls 388 * back to the unquoted case below. 389 */ 390}else{ 391/* normal, unquoted path */ 392 end =strchrnul(string, sep); 393strbuf_add(out, string, end - string); 394} 395 396if(*end) 397 end++; 398return end; 399} 400 401static voidlink_alt_odb_entries(const char*alt,int len,int sep, 402const char*relative_base,int depth) 403{ 404struct strbuf objdirbuf = STRBUF_INIT; 405struct strbuf entry = STRBUF_INIT; 406 407if(depth >5) { 408error("%s: ignoring alternate object stores, nesting too deep.", 409 relative_base); 410return; 411} 412 413strbuf_add_absolute_path(&objdirbuf,get_object_directory()); 414if(strbuf_normalize_path(&objdirbuf) <0) 415die("unable to normalize object directory:%s", 416 objdirbuf.buf); 417 418while(*alt) { 419 alt =parse_alt_odb_entry(alt, sep, &entry); 420if(!entry.len) 421continue; 422link_alt_odb_entry(entry.buf, relative_base, depth, objdirbuf.buf); 423} 424strbuf_release(&entry); 425strbuf_release(&objdirbuf); 426} 427 428static voidread_info_alternates(const char* relative_base,int depth) 429{ 430char*map; 431size_t mapsz; 432struct stat st; 433char*path; 434int fd; 435 436 path =xstrfmt("%s/info/alternates", relative_base); 437 fd =git_open(path); 438free(path); 439if(fd <0) 440return; 441if(fstat(fd, &st) || (st.st_size ==0)) { 442close(fd); 443return; 444} 445 mapsz =xsize_t(st.st_size); 446 map =xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd,0); 447close(fd); 448 449link_alt_odb_entries(map, mapsz,'\n', relative_base, depth); 450 451munmap(map, mapsz); 452} 453 454struct alternate_object_database *alloc_alt_odb(const char*dir) 455{ 456struct alternate_object_database *ent; 457 458FLEX_ALLOC_STR(ent, path, dir); 459strbuf_init(&ent->scratch,0); 460strbuf_addf(&ent->scratch,"%s/", dir); 461 ent->base_len = ent->scratch.len; 462 463return ent; 464} 465 466voidadd_to_alternates_file(const char*reference) 467{ 468struct lock_file *lock =xcalloc(1,sizeof(struct lock_file)); 469char*alts =git_pathdup("objects/info/alternates"); 470FILE*in, *out; 471 472hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR); 473 out =fdopen_lock_file(lock,"w"); 474if(!out) 475die_errno("unable to fdopen alternates lockfile"); 476 477 in =fopen(alts,"r"); 478if(in) { 479struct strbuf line = STRBUF_INIT; 480int found =0; 481 482while(strbuf_getline(&line, in) != EOF) { 483if(!strcmp(reference, line.buf)) { 484 found =1; 485break; 486} 487fprintf_or_die(out,"%s\n", line.buf); 488} 489 490strbuf_release(&line); 491fclose(in); 492 493if(found) { 494rollback_lock_file(lock); 495 lock = NULL; 496} 497} 498else if(errno != ENOENT) 499die_errno("unable to read alternates file"); 500 501if(lock) { 502fprintf_or_die(out,"%s\n", reference); 503if(commit_lock_file(lock)) 504die_errno("unable to move new alternates file into place"); 505if(alt_odb_tail) 506link_alt_odb_entries(reference,strlen(reference),'\n', NULL,0); 507} 508free(alts); 509} 510 511voidadd_to_alternates_memory(const char*reference) 512{ 513/* 514 * Make sure alternates are initialized, or else our entry may be 515 * overwritten when they are. 516 */ 517prepare_alt_odb(); 518 519link_alt_odb_entries(reference,strlen(reference),'\n', NULL,0); 520} 521 522/* 523 * Compute the exact path an alternate is at and returns it. In case of 524 * error NULL is returned and the human readable error is added to `err` 525 * `path` may be relative and should point to $GITDIR. 526 * `err` must not be null. 527 */ 528char*compute_alternate_path(const char*path,struct strbuf *err) 529{ 530char*ref_git = NULL; 531const char*repo, *ref_git_s; 532int seen_error =0; 533 534 ref_git_s =real_path_if_valid(path); 535if(!ref_git_s) { 536 seen_error =1; 537strbuf_addf(err,_("path '%s' does not exist"), path); 538goto out; 539}else 540/* 541 * Beware: read_gitfile(), real_path() and mkpath() 542 * return static buffer 543 */ 544 ref_git =xstrdup(ref_git_s); 545 546 repo =read_gitfile(ref_git); 547if(!repo) 548 repo =read_gitfile(mkpath("%s/.git", ref_git)); 549if(repo) { 550free(ref_git); 551 ref_git =xstrdup(repo); 552} 553 554if(!repo &&is_directory(mkpath("%s/.git/objects", ref_git))) { 555char*ref_git_git =mkpathdup("%s/.git", ref_git); 556free(ref_git); 557 ref_git = ref_git_git; 558}else if(!is_directory(mkpath("%s/objects", ref_git))) { 559struct strbuf sb = STRBUF_INIT; 560 seen_error =1; 561if(get_common_dir(&sb, ref_git)) { 562strbuf_addf(err, 563_("reference repository '%s' as a linked " 564"checkout is not supported yet."), 565 path); 566goto out; 567} 568 569strbuf_addf(err,_("reference repository '%s' is not a " 570"local repository."), path); 571goto out; 572} 573 574if(!access(mkpath("%s/shallow", ref_git), F_OK)) { 575strbuf_addf(err,_("reference repository '%s' is shallow"), 576 path); 577 seen_error =1; 578goto out; 579} 580 581if(!access(mkpath("%s/info/grafts", ref_git), F_OK)) { 582strbuf_addf(err, 583_("reference repository '%s' is grafted"), 584 path); 585 seen_error =1; 586goto out; 587} 588 589out: 590if(seen_error) { 591FREE_AND_NULL(ref_git); 592} 593 594return ref_git; 595} 596 597intforeach_alt_odb(alt_odb_fn fn,void*cb) 598{ 599struct alternate_object_database *ent; 600int r =0; 601 602prepare_alt_odb(); 603for(ent = alt_odb_list; ent; ent = ent->next) { 604 r =fn(ent, cb); 605if(r) 606break; 607} 608return r; 609} 610 611voidprepare_alt_odb(void) 612{ 613const char*alt; 614 615if(alt_odb_tail) 616return; 617 618 alt =getenv(ALTERNATE_DB_ENVIRONMENT); 619if(!alt) alt =""; 620 621 alt_odb_tail = &alt_odb_list; 622link_alt_odb_entries(alt,strlen(alt), PATH_SEP, NULL,0); 623 624read_info_alternates(get_object_directory(),0); 625} 626 627/* Returns 1 if we have successfully freshened the file, 0 otherwise. */ 628static intfreshen_file(const char*fn) 629{ 630struct utimbuf t; 631 t.actime = t.modtime =time(NULL); 632return!utime(fn, &t); 633} 634 635/* 636 * All of the check_and_freshen functions return 1 if the file exists and was 637 * freshened (if freshening was requested), 0 otherwise. If they return 638 * 0, you should not assume that it is safe to skip a write of the object (it 639 * either does not exist on disk, or has a stale mtime and may be subject to 640 * pruning). 641 */ 642intcheck_and_freshen_file(const char*fn,int freshen) 643{ 644if(access(fn, F_OK)) 645return0; 646if(freshen && !freshen_file(fn)) 647return0; 648return1; 649} 650 651static intcheck_and_freshen_local(const unsigned char*sha1,int freshen) 652{ 653returncheck_and_freshen_file(sha1_file_name(sha1), freshen); 654} 655 656static intcheck_and_freshen_nonlocal(const unsigned char*sha1,int freshen) 657{ 658struct alternate_object_database *alt; 659prepare_alt_odb(); 660for(alt = alt_odb_list; alt; alt = alt->next) { 661const char*path =alt_sha1_path(alt, sha1); 662if(check_and_freshen_file(path, freshen)) 663return1; 664} 665return0; 666} 667 668static intcheck_and_freshen(const unsigned char*sha1,int freshen) 669{ 670returncheck_and_freshen_local(sha1, freshen) || 671check_and_freshen_nonlocal(sha1, freshen); 672} 673 674inthas_loose_object_nonlocal(const unsigned char*sha1) 675{ 676returncheck_and_freshen_nonlocal(sha1,0); 677} 678 679static inthas_loose_object(const unsigned char*sha1) 680{ 681returncheck_and_freshen(sha1,0); 682} 683 684static voidscan_windows(struct packed_git *p, 685struct packed_git **lru_p, 686struct pack_window **lru_w, 687struct pack_window **lru_l) 688{ 689struct pack_window *w, *w_l; 690 691for(w_l = NULL, w = p->windows; w; w = w->next) { 692if(!w->inuse_cnt) { 693if(!*lru_w || w->last_used < (*lru_w)->last_used) { 694*lru_p = p; 695*lru_w = w; 696*lru_l = w_l; 697} 698} 699 w_l = w; 700} 701} 702 703static intunuse_one_window(struct packed_git *current) 704{ 705struct packed_git *p, *lru_p = NULL; 706struct pack_window *lru_w = NULL, *lru_l = NULL; 707 708if(current) 709scan_windows(current, &lru_p, &lru_w, &lru_l); 710for(p = packed_git; p; p = p->next) 711scan_windows(p, &lru_p, &lru_w, &lru_l); 712if(lru_p) { 713munmap(lru_w->base, lru_w->len); 714 pack_mapped -= lru_w->len; 715if(lru_l) 716 lru_l->next = lru_w->next; 717else 718 lru_p->windows = lru_w->next; 719free(lru_w); 720 pack_open_windows--; 721return1; 722} 723return0; 724} 725 726voidrelease_pack_memory(size_t need) 727{ 728size_t cur = pack_mapped; 729while(need >= (cur - pack_mapped) &&unuse_one_window(NULL)) 730;/* nothing */ 731} 732 733static voidmmap_limit_check(size_t length) 734{ 735static size_t limit =0; 736if(!limit) { 737 limit =git_env_ulong("GIT_MMAP_LIMIT",0); 738if(!limit) 739 limit = SIZE_MAX; 740} 741if(length > limit) 742die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX, 743(uintmax_t)length, (uintmax_t)limit); 744} 745 746void*xmmap_gently(void*start,size_t length, 747int prot,int flags,int fd, off_t offset) 748{ 749void*ret; 750 751mmap_limit_check(length); 752 ret =mmap(start, length, prot, flags, fd, offset); 753if(ret == MAP_FAILED) { 754if(!length) 755return NULL; 756release_pack_memory(length); 757 ret =mmap(start, length, prot, flags, fd, offset); 758} 759return ret; 760} 761 762void*xmmap(void*start,size_t length, 763int prot,int flags,int fd, off_t offset) 764{ 765void*ret =xmmap_gently(start, length, prot, flags, fd, offset); 766if(ret == MAP_FAILED) 767die_errno("mmap failed"); 768return ret; 769} 770 771voidclose_pack_windows(struct packed_git *p) 772{ 773while(p->windows) { 774struct pack_window *w = p->windows; 775 776if(w->inuse_cnt) 777die("pack '%s' still has open windows to it", 778 p->pack_name); 779munmap(w->base, w->len); 780 pack_mapped -= w->len; 781 pack_open_windows--; 782 p->windows = w->next; 783free(w); 784} 785} 786 787static intclose_pack_fd(struct packed_git *p) 788{ 789if(p->pack_fd <0) 790return0; 791 792close(p->pack_fd); 793 pack_open_fds--; 794 p->pack_fd = -1; 795 796return1; 797} 798 799static voidclose_pack(struct packed_git *p) 800{ 801close_pack_windows(p); 802close_pack_fd(p); 803close_pack_index(p); 804} 805 806voidclose_all_packs(void) 807{ 808struct packed_git *p; 809 810for(p = packed_git; p; p = p->next) 811if(p->do_not_close) 812die("BUG: want to close pack marked 'do-not-close'"); 813else 814close_pack(p); 815} 816 817 818/* 819 * The LRU pack is the one with the oldest MRU window, preferring packs 820 * with no used windows, or the oldest mtime if it has no windows allocated. 821 */ 822static voidfind_lru_pack(struct packed_git *p,struct packed_git **lru_p,struct pack_window **mru_w,int*accept_windows_inuse) 823{ 824struct pack_window *w, *this_mru_w; 825int has_windows_inuse =0; 826 827/* 828 * Reject this pack if it has windows and the previously selected 829 * one does not. If this pack does not have windows, reject 830 * it if the pack file is newer than the previously selected one. 831 */ 832if(*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime)) 833return; 834 835for(w = this_mru_w = p->windows; w; w = w->next) { 836/* 837 * Reject this pack if any of its windows are in use, 838 * but the previously selected pack did not have any 839 * inuse windows. Otherwise, record that this pack 840 * has windows in use. 841 */ 842if(w->inuse_cnt) { 843if(*accept_windows_inuse) 844 has_windows_inuse =1; 845else 846return; 847} 848 849if(w->last_used > this_mru_w->last_used) 850 this_mru_w = w; 851 852/* 853 * Reject this pack if it has windows that have been 854 * used more recently than the previously selected pack. 855 * If the previously selected pack had windows inuse and 856 * we have not encountered a window in this pack that is 857 * inuse, skip this check since we prefer a pack with no 858 * inuse windows to one that has inuse windows. 859 */ 860if(*mru_w && *accept_windows_inuse == has_windows_inuse && 861 this_mru_w->last_used > (*mru_w)->last_used) 862return; 863} 864 865/* 866 * Select this pack. 867 */ 868*mru_w = this_mru_w; 869*lru_p = p; 870*accept_windows_inuse = has_windows_inuse; 871} 872 873static intclose_one_pack(void) 874{ 875struct packed_git *p, *lru_p = NULL; 876struct pack_window *mru_w = NULL; 877int accept_windows_inuse =1; 878 879for(p = packed_git; p; p = p->next) { 880if(p->pack_fd == -1) 881continue; 882find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse); 883} 884 885if(lru_p) 886returnclose_pack_fd(lru_p); 887 888return0; 889} 890 891voidunuse_pack(struct pack_window **w_cursor) 892{ 893struct pack_window *w = *w_cursor; 894if(w) { 895 w->inuse_cnt--; 896*w_cursor = NULL; 897} 898} 899 900voidclose_pack_index(struct packed_git *p) 901{ 902if(p->index_data) { 903munmap((void*)p->index_data, p->index_size); 904 p->index_data = NULL; 905} 906} 907 908static unsigned intget_max_fd_limit(void) 909{ 910#ifdef RLIMIT_NOFILE 911{ 912struct rlimit lim; 913 914if(!getrlimit(RLIMIT_NOFILE, &lim)) 915return lim.rlim_cur; 916} 917#endif 918 919#ifdef _SC_OPEN_MAX 920{ 921long open_max =sysconf(_SC_OPEN_MAX); 922if(0< open_max) 923return open_max; 924/* 925 * Otherwise, we got -1 for one of the two 926 * reasons: 927 * 928 * (1) sysconf() did not understand _SC_OPEN_MAX 929 * and signaled an error with -1; or 930 * (2) sysconf() said there is no limit. 931 * 932 * We _could_ clear errno before calling sysconf() to 933 * tell these two cases apart and return a huge number 934 * in the latter case to let the caller cap it to a 935 * value that is not so selfish, but letting the 936 * fallback OPEN_MAX codepath take care of these cases 937 * is a lot simpler. 938 */ 939} 940#endif 941 942#ifdef OPEN_MAX 943return OPEN_MAX; 944#else 945return1;/* see the caller ;-) */ 946#endif 947} 948 949/* 950 * Do not call this directly as this leaks p->pack_fd on error return; 951 * call open_packed_git() instead. 952 */ 953static intopen_packed_git_1(struct packed_git *p) 954{ 955struct stat st; 956struct pack_header hdr; 957unsigned char sha1[20]; 958unsigned char*idx_sha1; 959long fd_flag; 960 961if(!p->index_data &&open_pack_index(p)) 962returnerror("packfile%sindex unavailable", p->pack_name); 963 964if(!pack_max_fds) { 965unsigned int max_fds =get_max_fd_limit(); 966 967/* Save 3 for stdin/stdout/stderr, 22 for work */ 968if(25< max_fds) 969 pack_max_fds = max_fds -25; 970else 971 pack_max_fds =1; 972} 973 974while(pack_max_fds <= pack_open_fds &&close_one_pack()) 975;/* nothing */ 976 977 p->pack_fd =git_open(p->pack_name); 978if(p->pack_fd <0||fstat(p->pack_fd, &st)) 979return-1; 980 pack_open_fds++; 981 982/* If we created the struct before we had the pack we lack size. */ 983if(!p->pack_size) { 984if(!S_ISREG(st.st_mode)) 985returnerror("packfile%snot a regular file", p->pack_name); 986 p->pack_size = st.st_size; 987}else if(p->pack_size != st.st_size) 988returnerror("packfile%ssize changed", p->pack_name); 989 990/* We leave these file descriptors open with sliding mmap; 991 * there is no point keeping them open across exec(), though. 992 */ 993 fd_flag =fcntl(p->pack_fd, F_GETFD,0); 994if(fd_flag <0) 995returnerror("cannot determine file descriptor flags"); 996 fd_flag |= FD_CLOEXEC; 997if(fcntl(p->pack_fd, F_SETFD, fd_flag) == -1) 998returnerror("cannot set FD_CLOEXEC"); 9991000/* Verify we recognize this pack file format. */1001if(read_in_full(p->pack_fd, &hdr,sizeof(hdr)) !=sizeof(hdr))1002returnerror("file%sis far too short to be a packfile", p->pack_name);1003if(hdr.hdr_signature !=htonl(PACK_SIGNATURE))1004returnerror("file%sis not a GIT packfile", p->pack_name);1005if(!pack_version_ok(hdr.hdr_version))1006returnerror("packfile%sis version %"PRIu32" and not"1007" supported (try upgrading GIT to a newer version)",1008 p->pack_name,ntohl(hdr.hdr_version));10091010/* Verify the pack matches its index. */1011if(p->num_objects !=ntohl(hdr.hdr_entries))1012returnerror("packfile%sclaims to have %"PRIu32" objects"1013" while index indicates %"PRIu32" objects",1014 p->pack_name,ntohl(hdr.hdr_entries),1015 p->num_objects);1016if(lseek(p->pack_fd, p->pack_size -sizeof(sha1), SEEK_SET) == -1)1017returnerror("end of packfile%sis unavailable", p->pack_name);1018if(read_in_full(p->pack_fd, sha1,sizeof(sha1)) !=sizeof(sha1))1019returnerror("packfile%ssignature is unavailable", p->pack_name);1020 idx_sha1 = ((unsigned char*)p->index_data) + p->index_size -40;1021if(hashcmp(sha1, idx_sha1))1022returnerror("packfile%sdoes not match index", p->pack_name);1023return0;1024}10251026static intopen_packed_git(struct packed_git *p)1027{1028if(!open_packed_git_1(p))1029return0;1030close_pack_fd(p);1031return-1;1032}10331034static intin_window(struct pack_window *win, off_t offset)1035{1036/* We must promise at least 20 bytes (one hash) after the1037 * offset is available from this window, otherwise the offset1038 * is not actually in this window and a different window (which1039 * has that one hash excess) must be used. This is to support1040 * the object header and delta base parsing routines below.1041 */1042 off_t win_off = win->offset;1043return win_off <= offset1044&& (offset +20) <= (win_off + win->len);1045}10461047unsigned char*use_pack(struct packed_git *p,1048struct pack_window **w_cursor,1049 off_t offset,1050unsigned long*left)1051{1052struct pack_window *win = *w_cursor;10531054/* Since packfiles end in a hash of their content and it's1055 * pointless to ask for an offset into the middle of that1056 * hash, and the in_window function above wouldn't match1057 * don't allow an offset too close to the end of the file.1058 */1059if(!p->pack_size && p->pack_fd == -1&&open_packed_git(p))1060die("packfile%scannot be accessed", p->pack_name);1061if(offset > (p->pack_size -20))1062die("offset beyond end of packfile (truncated pack?)");1063if(offset <0)1064die(_("offset before end of packfile (broken .idx?)"));10651066if(!win || !in_window(win, offset)) {1067if(win)1068 win->inuse_cnt--;1069for(win = p->windows; win; win = win->next) {1070if(in_window(win, offset))1071break;1072}1073if(!win) {1074size_t window_align = packed_git_window_size /2;1075 off_t len;10761077if(p->pack_fd == -1&&open_packed_git(p))1078die("packfile%scannot be accessed", p->pack_name);10791080 win =xcalloc(1,sizeof(*win));1081 win->offset = (offset / window_align) * window_align;1082 len = p->pack_size - win->offset;1083if(len > packed_git_window_size)1084 len = packed_git_window_size;1085 win->len = (size_t)len;1086 pack_mapped += win->len;1087while(packed_git_limit < pack_mapped1088&&unuse_one_window(p))1089;/* nothing */1090 win->base =xmmap(NULL, win->len,1091 PROT_READ, MAP_PRIVATE,1092 p->pack_fd, win->offset);1093if(win->base == MAP_FAILED)1094die_errno("packfile%scannot be mapped",1095 p->pack_name);1096if(!win->offset && win->len == p->pack_size1097&& !p->do_not_close)1098close_pack_fd(p);1099 pack_mmap_calls++;1100 pack_open_windows++;1101if(pack_mapped > peak_pack_mapped)1102 peak_pack_mapped = pack_mapped;1103if(pack_open_windows > peak_pack_open_windows)1104 peak_pack_open_windows = pack_open_windows;1105 win->next = p->windows;1106 p->windows = win;1107}1108}1109if(win != *w_cursor) {1110 win->last_used = pack_used_ctr++;1111 win->inuse_cnt++;1112*w_cursor = win;1113}1114 offset -= win->offset;1115if(left)1116*left = win->len -xsize_t(offset);1117return win->base + offset;1118}11191120static struct packed_git *alloc_packed_git(int extra)1121{1122struct packed_git *p =xmalloc(st_add(sizeof(*p), extra));1123memset(p,0,sizeof(*p));1124 p->pack_fd = -1;1125return p;1126}11271128static voidtry_to_free_pack_memory(size_t size)1129{1130release_pack_memory(size);1131}11321133struct packed_git *add_packed_git(const char*path,size_t path_len,int local)1134{1135static int have_set_try_to_free_routine;1136struct stat st;1137size_t alloc;1138struct packed_git *p;11391140if(!have_set_try_to_free_routine) {1141 have_set_try_to_free_routine =1;1142set_try_to_free_routine(try_to_free_pack_memory);1143}11441145/*1146 * Make sure a corresponding .pack file exists and that1147 * the index looks sane.1148 */1149if(!strip_suffix_mem(path, &path_len,".idx"))1150return NULL;11511152/*1153 * ".pack" is long enough to hold any suffix we're adding (and1154 * the use xsnprintf double-checks that)1155 */1156 alloc =st_add3(path_len,strlen(".pack"),1);1157 p =alloc_packed_git(alloc);1158memcpy(p->pack_name, path, path_len);11591160xsnprintf(p->pack_name + path_len, alloc - path_len,".keep");1161if(!access(p->pack_name, F_OK))1162 p->pack_keep =1;11631164xsnprintf(p->pack_name + path_len, alloc - path_len,".pack");1165if(stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {1166free(p);1167return NULL;1168}11691170/* ok, it looks sane as far as we can check without1171 * actually mapping the pack file.1172 */1173 p->pack_size = st.st_size;1174 p->pack_local = local;1175 p->mtime = st.st_mtime;1176if(path_len <40||get_sha1_hex(path + path_len -40, p->sha1))1177hashclr(p->sha1);1178return p;1179}11801181voidinstall_packed_git(struct packed_git *pack)1182{1183if(pack->pack_fd != -1)1184 pack_open_fds++;11851186 pack->next = packed_git;1187 packed_git = pack;1188}11891190void(*report_garbage)(unsigned seen_bits,const char*path);11911192static voidreport_helper(const struct string_list *list,1193int seen_bits,int first,int last)1194{1195if(seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))1196return;11971198for(; first < last; first++)1199report_garbage(seen_bits, list->items[first].string);1200}12011202static voidreport_pack_garbage(struct string_list *list)1203{1204int i, baselen = -1, first =0, seen_bits =0;12051206if(!report_garbage)1207return;12081209string_list_sort(list);12101211for(i =0; i < list->nr; i++) {1212const char*path = list->items[i].string;1213if(baselen != -1&&1214strncmp(path, list->items[first].string, baselen)) {1215report_helper(list, seen_bits, first, i);1216 baselen = -1;1217 seen_bits =0;1218}1219if(baselen == -1) {1220const char*dot =strrchr(path,'.');1221if(!dot) {1222report_garbage(PACKDIR_FILE_GARBAGE, path);1223continue;1224}1225 baselen = dot - path +1;1226 first = i;1227}1228if(!strcmp(path + baselen,"pack"))1229 seen_bits |=1;1230else if(!strcmp(path + baselen,"idx"))1231 seen_bits |=2;1232}1233report_helper(list, seen_bits, first, list->nr);1234}12351236static voidprepare_packed_git_one(char*objdir,int local)1237{1238struct strbuf path = STRBUF_INIT;1239size_t dirnamelen;1240DIR*dir;1241struct dirent *de;1242struct string_list garbage = STRING_LIST_INIT_DUP;12431244strbuf_addstr(&path, objdir);1245strbuf_addstr(&path,"/pack");1246 dir =opendir(path.buf);1247if(!dir) {1248if(errno != ENOENT)1249error_errno("unable to open object pack directory:%s",1250 path.buf);1251strbuf_release(&path);1252return;1253}1254strbuf_addch(&path,'/');1255 dirnamelen = path.len;1256while((de =readdir(dir)) != NULL) {1257struct packed_git *p;1258size_t base_len;12591260if(is_dot_or_dotdot(de->d_name))1261continue;12621263strbuf_setlen(&path, dirnamelen);1264strbuf_addstr(&path, de->d_name);12651266 base_len = path.len;1267if(strip_suffix_mem(path.buf, &base_len,".idx")) {1268/* Don't reopen a pack we already have. */1269for(p = packed_git; p; p = p->next) {1270size_t len;1271if(strip_suffix(p->pack_name,".pack", &len) &&1272 len == base_len &&1273!memcmp(p->pack_name, path.buf, len))1274break;1275}1276if(p == NULL &&1277/*1278 * See if it really is a valid .idx file with1279 * corresponding .pack file that we can map.1280 */1281(p =add_packed_git(path.buf, path.len, local)) != NULL)1282install_packed_git(p);1283}12841285if(!report_garbage)1286continue;12871288if(ends_with(de->d_name,".idx") ||1289ends_with(de->d_name,".pack") ||1290ends_with(de->d_name,".bitmap") ||1291ends_with(de->d_name,".keep"))1292string_list_append(&garbage, path.buf);1293else1294report_garbage(PACKDIR_FILE_GARBAGE, path.buf);1295}1296closedir(dir);1297report_pack_garbage(&garbage);1298string_list_clear(&garbage,0);1299strbuf_release(&path);1300}13011302static int approximate_object_count_valid;13031304/*1305 * Give a fast, rough count of the number of objects in the repository. This1306 * ignores loose objects completely. If you have a lot of them, then either1307 * you should repack because your performance will be awful, or they are1308 * all unreachable objects about to be pruned, in which case they're not really1309 * interesting as a measure of repo size in the first place.1310 */1311unsigned longapproximate_object_count(void)1312{1313static unsigned long count;1314if(!approximate_object_count_valid) {1315struct packed_git *p;13161317prepare_packed_git();1318 count =0;1319for(p = packed_git; p; p = p->next) {1320if(open_pack_index(p))1321continue;1322 count += p->num_objects;1323}1324}1325return count;1326}13271328static void*get_next_packed_git(const void*p)1329{1330return((const struct packed_git *)p)->next;1331}13321333static voidset_next_packed_git(void*p,void*next)1334{1335((struct packed_git *)p)->next = next;1336}13371338static intsort_pack(const void*a_,const void*b_)1339{1340const struct packed_git *a = a_;1341const struct packed_git *b = b_;1342int st;13431344/*1345 * Local packs tend to contain objects specific to our1346 * variant of the project than remote ones. In addition,1347 * remote ones could be on a network mounted filesystem.1348 * Favor local ones for these reasons.1349 */1350 st = a->pack_local - b->pack_local;1351if(st)1352return-st;13531354/*1355 * Younger packs tend to contain more recent objects,1356 * and more recent objects tend to get accessed more1357 * often.1358 */1359if(a->mtime < b->mtime)1360return1;1361else if(a->mtime == b->mtime)1362return0;1363return-1;1364}13651366static voidrearrange_packed_git(void)1367{1368 packed_git =llist_mergesort(packed_git, get_next_packed_git,1369 set_next_packed_git, sort_pack);1370}13711372static voidprepare_packed_git_mru(void)1373{1374struct packed_git *p;13751376mru_clear(packed_git_mru);1377for(p = packed_git; p; p = p->next)1378mru_append(packed_git_mru, p);1379}13801381static int prepare_packed_git_run_once =0;1382voidprepare_packed_git(void)1383{1384struct alternate_object_database *alt;13851386if(prepare_packed_git_run_once)1387return;1388prepare_packed_git_one(get_object_directory(),1);1389prepare_alt_odb();1390for(alt = alt_odb_list; alt; alt = alt->next)1391prepare_packed_git_one(alt->path,0);1392rearrange_packed_git();1393prepare_packed_git_mru();1394 prepare_packed_git_run_once =1;1395}13961397voidreprepare_packed_git(void)1398{1399 approximate_object_count_valid =0;1400 prepare_packed_git_run_once =0;1401prepare_packed_git();1402}14031404static voidmark_bad_packed_object(struct packed_git *p,1405const unsigned char*sha1)1406{1407unsigned i;1408for(i =0; i < p->num_bad_objects; i++)1409if(!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))1410return;1411 p->bad_object_sha1 =xrealloc(p->bad_object_sha1,1412st_mult(GIT_MAX_RAWSZ,1413st_add(p->num_bad_objects,1)));1414hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);1415 p->num_bad_objects++;1416}14171418static const struct packed_git *has_packed_and_bad(const unsigned char*sha1)1419{1420struct packed_git *p;1421unsigned i;14221423for(p = packed_git; p; p = p->next)1424for(i =0; i < p->num_bad_objects; i++)1425if(!hashcmp(sha1, p->bad_object_sha1 +20* i))1426return p;1427return NULL;1428}14291430/*1431 * With an in-core object data in "map", rehash it to make sure the1432 * object name actually matches "sha1" to detect object corruption.1433 * With "map" == NULL, try reading the object named with "sha1" using1434 * the streaming interface and rehash it to do the same.1435 */1436intcheck_sha1_signature(const unsigned char*sha1,void*map,1437unsigned long size,const char*type)1438{1439unsigned char real_sha1[20];1440enum object_type obj_type;1441struct git_istream *st;1442 git_SHA_CTX c;1443char hdr[32];1444int hdrlen;14451446if(map) {1447hash_sha1_file(map, size, type, real_sha1);1448returnhashcmp(sha1, real_sha1) ? -1:0;1449}14501451 st =open_istream(sha1, &obj_type, &size, NULL);1452if(!st)1453return-1;14541455/* Generate the header */1456 hdrlen =xsnprintf(hdr,sizeof(hdr),"%s %lu",typename(obj_type), size) +1;14571458/* Sha1.. */1459git_SHA1_Init(&c);1460git_SHA1_Update(&c, hdr, hdrlen);1461for(;;) {1462char buf[1024*16];1463 ssize_t readlen =read_istream(st, buf,sizeof(buf));14641465if(readlen <0) {1466close_istream(st);1467return-1;1468}1469if(!readlen)1470break;1471git_SHA1_Update(&c, buf, readlen);1472}1473git_SHA1_Final(real_sha1, &c);1474close_istream(st);1475returnhashcmp(sha1, real_sha1) ? -1:0;1476}14771478intgit_open_cloexec(const char*name,int flags)1479{1480int fd;1481static int o_cloexec = O_CLOEXEC;14821483 fd =open(name, flags | o_cloexec);1484if((o_cloexec & O_CLOEXEC) && fd <0&& errno == EINVAL) {1485/* Try again w/o O_CLOEXEC: the kernel might not support it */1486 o_cloexec &= ~O_CLOEXEC;1487 fd =open(name, flags | o_cloexec);1488}14891490#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)1491{1492static int fd_cloexec = FD_CLOEXEC;14931494if(!o_cloexec &&0<= fd && fd_cloexec) {1495/* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */1496int flags =fcntl(fd, F_GETFD);1497if(fcntl(fd, F_SETFD, flags | fd_cloexec))1498 fd_cloexec =0;1499}1500}1501#endif1502return fd;1503}15041505/*1506 * Find "sha1" as a loose object in the local repository or in an alternate.1507 * Returns 0 on success, negative on failure.1508 *1509 * The "path" out-parameter will give the path of the object we found (if any).1510 * Note that it may point to static storage and is only valid until another1511 * call to sha1_file_name(), etc.1512 */1513static intstat_sha1_file(const unsigned char*sha1,struct stat *st,1514const char**path)1515{1516struct alternate_object_database *alt;15171518*path =sha1_file_name(sha1);1519if(!lstat(*path, st))1520return0;15211522prepare_alt_odb();1523 errno = ENOENT;1524for(alt = alt_odb_list; alt; alt = alt->next) {1525*path =alt_sha1_path(alt, sha1);1526if(!lstat(*path, st))1527return0;1528}15291530return-1;1531}15321533/*1534 * Like stat_sha1_file(), but actually open the object and return the1535 * descriptor. See the caveats on the "path" parameter above.1536 */1537static intopen_sha1_file(const unsigned char*sha1,const char**path)1538{1539int fd;1540struct alternate_object_database *alt;1541int most_interesting_errno;15421543*path =sha1_file_name(sha1);1544 fd =git_open(*path);1545if(fd >=0)1546return fd;1547 most_interesting_errno = errno;15481549prepare_alt_odb();1550for(alt = alt_odb_list; alt; alt = alt->next) {1551*path =alt_sha1_path(alt, sha1);1552 fd =git_open(*path);1553if(fd >=0)1554return fd;1555if(most_interesting_errno == ENOENT)1556 most_interesting_errno = errno;1557}1558 errno = most_interesting_errno;1559return-1;1560}15611562/*1563 * Map the loose object at "path" if it is not NULL, or the path found by1564 * searching for a loose object named "sha1".1565 */1566static void*map_sha1_file_1(const char*path,1567const unsigned char*sha1,1568unsigned long*size)1569{1570void*map;1571int fd;15721573if(path)1574 fd =git_open(path);1575else1576 fd =open_sha1_file(sha1, &path);1577 map = NULL;1578if(fd >=0) {1579struct stat st;15801581if(!fstat(fd, &st)) {1582*size =xsize_t(st.st_size);1583if(!*size) {1584/* mmap() is forbidden on empty files */1585error("object file%sis empty", path);1586return NULL;1587}1588 map =xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd,0);1589}1590close(fd);1591}1592return map;1593}15941595void*map_sha1_file(const unsigned char*sha1,unsigned long*size)1596{1597returnmap_sha1_file_1(NULL, sha1, size);1598}15991600unsigned longunpack_object_header_buffer(const unsigned char*buf,1601unsigned long len,enum object_type *type,unsigned long*sizep)1602{1603unsigned shift;1604unsigned long size, c;1605unsigned long used =0;16061607 c = buf[used++];1608*type = (c >>4) &7;1609 size = c &15;1610 shift =4;1611while(c &0x80) {1612if(len <= used ||bitsizeof(long) <= shift) {1613error("bad object header");1614 size = used =0;1615break;1616}1617 c = buf[used++];1618 size += (c &0x7f) << shift;1619 shift +=7;1620}1621*sizep = size;1622return used;1623}16241625static intunpack_sha1_short_header(git_zstream *stream,1626unsigned char*map,unsigned long mapsize,1627void*buffer,unsigned long bufsiz)1628{1629/* Get the data stream */1630memset(stream,0,sizeof(*stream));1631 stream->next_in = map;1632 stream->avail_in = mapsize;1633 stream->next_out = buffer;1634 stream->avail_out = bufsiz;16351636git_inflate_init(stream);1637returngit_inflate(stream,0);1638}16391640intunpack_sha1_header(git_zstream *stream,1641unsigned char*map,unsigned long mapsize,1642void*buffer,unsigned long bufsiz)1643{1644int status =unpack_sha1_short_header(stream, map, mapsize,1645 buffer, bufsiz);16461647if(status < Z_OK)1648return status;16491650/* Make sure we have the terminating NUL */1651if(!memchr(buffer,'\0', stream->next_out - (unsigned char*)buffer))1652return-1;1653return0;1654}16551656static intunpack_sha1_header_to_strbuf(git_zstream *stream,unsigned char*map,1657unsigned long mapsize,void*buffer,1658unsigned long bufsiz,struct strbuf *header)1659{1660int status;16611662 status =unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);1663if(status < Z_OK)1664return-1;16651666/*1667 * Check if entire header is unpacked in the first iteration.1668 */1669if(memchr(buffer,'\0', stream->next_out - (unsigned char*)buffer))1670return0;16711672/*1673 * buffer[0..bufsiz] was not large enough. Copy the partial1674 * result out to header, and then append the result of further1675 * reading the stream.1676 */1677strbuf_add(header, buffer, stream->next_out - (unsigned char*)buffer);1678 stream->next_out = buffer;1679 stream->avail_out = bufsiz;16801681do{1682 status =git_inflate(stream,0);1683strbuf_add(header, buffer, stream->next_out - (unsigned char*)buffer);1684if(memchr(buffer,'\0', stream->next_out - (unsigned char*)buffer))1685return0;1686 stream->next_out = buffer;1687 stream->avail_out = bufsiz;1688}while(status != Z_STREAM_END);1689return-1;1690}16911692static void*unpack_sha1_rest(git_zstream *stream,void*buffer,unsigned long size,const unsigned char*sha1)1693{1694int bytes =strlen(buffer) +1;1695unsigned char*buf =xmallocz(size);1696unsigned long n;1697int status = Z_OK;16981699 n = stream->total_out - bytes;1700if(n > size)1701 n = size;1702memcpy(buf, (char*) buffer + bytes, n);1703 bytes = n;1704if(bytes <= size) {1705/*1706 * The above condition must be (bytes <= size), not1707 * (bytes < size). In other words, even though we1708 * expect no more output and set avail_out to zero,1709 * the input zlib stream may have bytes that express1710 * "this concludes the stream", and we *do* want to1711 * eat that input.1712 *1713 * Otherwise we would not be able to test that we1714 * consumed all the input to reach the expected size;1715 * we also want to check that zlib tells us that all1716 * went well with status == Z_STREAM_END at the end.1717 */1718 stream->next_out = buf + bytes;1719 stream->avail_out = size - bytes;1720while(status == Z_OK)1721 status =git_inflate(stream, Z_FINISH);1722}1723if(status == Z_STREAM_END && !stream->avail_in) {1724git_inflate_end(stream);1725return buf;1726}17271728if(status <0)1729error("corrupt loose object '%s'",sha1_to_hex(sha1));1730else if(stream->avail_in)1731error("garbage at end of loose object '%s'",1732sha1_to_hex(sha1));1733free(buf);1734return NULL;1735}17361737/*1738 * We used to just use "sscanf()", but that's actually way1739 * too permissive for what we want to check. So do an anal1740 * object header parse by hand.1741 */1742static intparse_sha1_header_extended(const char*hdr,struct object_info *oi,1743unsigned int flags)1744{1745const char*type_buf = hdr;1746unsigned long size;1747int type, type_len =0;17481749/*1750 * The type can be of any size but is followed by1751 * a space.1752 */1753for(;;) {1754char c = *hdr++;1755if(!c)1756return-1;1757if(c ==' ')1758break;1759 type_len++;1760}17611762 type =type_from_string_gently(type_buf, type_len,1);1763if(oi->typename)1764strbuf_add(oi->typename, type_buf, type_len);1765/*1766 * Set type to 0 if its an unknown object and1767 * we're obtaining the type using '--allow-unknown-type'1768 * option.1769 */1770if((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type <0))1771 type =0;1772else if(type <0)1773die("invalid object type");1774if(oi->typep)1775*oi->typep = type;17761777/*1778 * The length must follow immediately, and be in canonical1779 * decimal format (ie "010" is not valid).1780 */1781 size = *hdr++ -'0';1782if(size >9)1783return-1;1784if(size) {1785for(;;) {1786unsigned long c = *hdr -'0';1787if(c >9)1788break;1789 hdr++;1790 size = size *10+ c;1791}1792}17931794if(oi->sizep)1795*oi->sizep = size;17961797/*1798 * The length must be followed by a zero byte1799 */1800return*hdr ? -1: type;1801}18021803intparse_sha1_header(const char*hdr,unsigned long*sizep)1804{1805struct object_info oi = OBJECT_INFO_INIT;18061807 oi.sizep = sizep;1808returnparse_sha1_header_extended(hdr, &oi,0);1809}18101811unsigned longget_size_from_delta(struct packed_git *p,1812struct pack_window **w_curs,1813 off_t curpos)1814{1815const unsigned char*data;1816unsigned char delta_head[20], *in;1817 git_zstream stream;1818int st;18191820memset(&stream,0,sizeof(stream));1821 stream.next_out = delta_head;1822 stream.avail_out =sizeof(delta_head);18231824git_inflate_init(&stream);1825do{1826 in =use_pack(p, w_curs, curpos, &stream.avail_in);1827 stream.next_in = in;1828 st =git_inflate(&stream, Z_FINISH);1829 curpos += stream.next_in - in;1830}while((st == Z_OK || st == Z_BUF_ERROR) &&1831 stream.total_out <sizeof(delta_head));1832git_inflate_end(&stream);1833if((st != Z_STREAM_END) && stream.total_out !=sizeof(delta_head)) {1834error("delta data unpack-initial failed");1835return0;1836}18371838/* Examine the initial part of the delta to figure out1839 * the result size.1840 */1841 data = delta_head;18421843/* ignore base size */1844get_delta_hdr_size(&data, delta_head+sizeof(delta_head));18451846/* Read the result size */1847returnget_delta_hdr_size(&data, delta_head+sizeof(delta_head));1848}18491850static off_t get_delta_base(struct packed_git *p,1851struct pack_window **w_curs,1852 off_t *curpos,1853enum object_type type,1854 off_t delta_obj_offset)1855{1856unsigned char*base_info =use_pack(p, w_curs, *curpos, NULL);1857 off_t base_offset;18581859/* use_pack() assured us we have [base_info, base_info + 20)1860 * as a range that we can look at without walking off the1861 * end of the mapped window. Its actually the hash size1862 * that is assured. An OFS_DELTA longer than the hash size1863 * is stupid, as then a REF_DELTA would be smaller to store.1864 */1865if(type == OBJ_OFS_DELTA) {1866unsigned used =0;1867unsigned char c = base_info[used++];1868 base_offset = c &127;1869while(c &128) {1870 base_offset +=1;1871if(!base_offset ||MSB(base_offset,7))1872return0;/* overflow */1873 c = base_info[used++];1874 base_offset = (base_offset <<7) + (c &127);1875}1876 base_offset = delta_obj_offset - base_offset;1877if(base_offset <=0|| base_offset >= delta_obj_offset)1878return0;/* out of bound */1879*curpos += used;1880}else if(type == OBJ_REF_DELTA) {1881/* The base entry _must_ be in the same pack */1882 base_offset =find_pack_entry_one(base_info, p);1883*curpos +=20;1884}else1885die("I am totally screwed");1886return base_offset;1887}18881889/*1890 * Like get_delta_base above, but we return the sha1 instead of the pack1891 * offset. This means it is cheaper for REF deltas (we do not have to do1892 * the final object lookup), but more expensive for OFS deltas (we1893 * have to load the revidx to convert the offset back into a sha1).1894 */1895static const unsigned char*get_delta_base_sha1(struct packed_git *p,1896struct pack_window **w_curs,1897 off_t curpos,1898enum object_type type,1899 off_t delta_obj_offset)1900{1901if(type == OBJ_REF_DELTA) {1902unsigned char*base =use_pack(p, w_curs, curpos, NULL);1903return base;1904}else if(type == OBJ_OFS_DELTA) {1905struct revindex_entry *revidx;1906 off_t base_offset =get_delta_base(p, w_curs, &curpos,1907 type, delta_obj_offset);19081909if(!base_offset)1910return NULL;19111912 revidx =find_pack_revindex(p, base_offset);1913if(!revidx)1914return NULL;19151916returnnth_packed_object_sha1(p, revidx->nr);1917}else1918return NULL;1919}19201921intunpack_object_header(struct packed_git *p,1922struct pack_window **w_curs,1923 off_t *curpos,1924unsigned long*sizep)1925{1926unsigned char*base;1927unsigned long left;1928unsigned long used;1929enum object_type type;19301931/* use_pack() assures us we have [base, base + 20) available1932 * as a range that we can look at. (Its actually the hash1933 * size that is assured.) With our object header encoding1934 * the maximum deflated object size is 2^137, which is just1935 * insane, so we know won't exceed what we have been given.1936 */1937 base =use_pack(p, w_curs, *curpos, &left);1938 used =unpack_object_header_buffer(base, left, &type, sizep);1939if(!used) {1940 type = OBJ_BAD;1941}else1942*curpos += used;19431944return type;1945}19461947static intretry_bad_packed_offset(struct packed_git *p, off_t obj_offset)1948{1949int type;1950struct revindex_entry *revidx;1951const unsigned char*sha1;1952 revidx =find_pack_revindex(p, obj_offset);1953if(!revidx)1954return OBJ_BAD;1955 sha1 =nth_packed_object_sha1(p, revidx->nr);1956mark_bad_packed_object(p, sha1);1957 type =sha1_object_info(sha1, NULL);1958if(type <= OBJ_NONE)1959return OBJ_BAD;1960return type;1961}19621963#define POI_STACK_PREALLOC 6419641965static enum object_type packed_to_object_type(struct packed_git *p,1966 off_t obj_offset,1967enum object_type type,1968struct pack_window **w_curs,1969 off_t curpos)1970{1971 off_t small_poi_stack[POI_STACK_PREALLOC];1972 off_t *poi_stack = small_poi_stack;1973int poi_stack_nr =0, poi_stack_alloc = POI_STACK_PREALLOC;19741975while(type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {1976 off_t base_offset;1977unsigned long size;1978/* Push the object we're going to leave behind */1979if(poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {1980 poi_stack_alloc =alloc_nr(poi_stack_nr);1981ALLOC_ARRAY(poi_stack, poi_stack_alloc);1982memcpy(poi_stack, small_poi_stack,sizeof(off_t)*poi_stack_nr);1983}else{1984ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);1985}1986 poi_stack[poi_stack_nr++] = obj_offset;1987/* If parsing the base offset fails, just unwind */1988 base_offset =get_delta_base(p, w_curs, &curpos, type, obj_offset);1989if(!base_offset)1990goto unwind;1991 curpos = obj_offset = base_offset;1992 type =unpack_object_header(p, w_curs, &curpos, &size);1993if(type <= OBJ_NONE) {1994/* If getting the base itself fails, we first1995 * retry the base, otherwise unwind */1996 type =retry_bad_packed_offset(p, base_offset);1997if(type > OBJ_NONE)1998goto out;1999goto unwind;2000}2001}20022003switch(type) {2004case OBJ_BAD:2005case OBJ_COMMIT:2006case OBJ_TREE:2007case OBJ_BLOB:2008case OBJ_TAG:2009break;2010default:2011error("unknown object type%iat offset %"PRIuMAX" in%s",2012 type, (uintmax_t)obj_offset, p->pack_name);2013 type = OBJ_BAD;2014}20152016out:2017if(poi_stack != small_poi_stack)2018free(poi_stack);2019return type;20202021unwind:2022while(poi_stack_nr) {2023 obj_offset = poi_stack[--poi_stack_nr];2024 type =retry_bad_packed_offset(p, obj_offset);2025if(type > OBJ_NONE)2026goto out;2027}2028 type = OBJ_BAD;2029goto out;2030}20312032static struct hashmap delta_base_cache;2033static size_t delta_base_cached;20342035staticLIST_HEAD(delta_base_cache_lru);20362037struct delta_base_cache_key {2038struct packed_git *p;2039 off_t base_offset;2040};20412042struct delta_base_cache_entry {2043struct hashmap hash;2044struct delta_base_cache_key key;2045struct list_head lru;2046void*data;2047unsigned long size;2048enum object_type type;2049};20502051static unsigned intpack_entry_hash(struct packed_git *p, off_t base_offset)2052{2053unsigned int hash;20542055 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;2056 hash += (hash >>8) + (hash >>16);2057return hash;2058}20592060static struct delta_base_cache_entry *2061get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)2062{2063struct hashmap_entry entry;2064struct delta_base_cache_key key;20652066if(!delta_base_cache.cmpfn)2067return NULL;20682069hashmap_entry_init(&entry,pack_entry_hash(p, base_offset));2070 key.p = p;2071 key.base_offset = base_offset;2072returnhashmap_get(&delta_base_cache, &entry, &key);2073}20742075static intdelta_base_cache_key_eq(const struct delta_base_cache_key *a,2076const struct delta_base_cache_key *b)2077{2078return a->p == b->p && a->base_offset == b->base_offset;2079}20802081static intdelta_base_cache_hash_cmp(const void*unused_cmp_data,2082const void*va,const void*vb,2083const void*vkey)2084{2085const struct delta_base_cache_entry *a = va, *b = vb;2086const struct delta_base_cache_key *key = vkey;2087if(key)2088return!delta_base_cache_key_eq(&a->key, key);2089else2090return!delta_base_cache_key_eq(&a->key, &b->key);2091}20922093static intin_delta_base_cache(struct packed_git *p, off_t base_offset)2094{2095return!!get_delta_base_cache_entry(p, base_offset);2096}20972098/*2099 * Remove the entry from the cache, but do _not_ free the associated2100 * entry data. The caller takes ownership of the "data" buffer, and2101 * should copy out any fields it wants before detaching.2102 */2103static voiddetach_delta_base_cache_entry(struct delta_base_cache_entry *ent)2104{2105hashmap_remove(&delta_base_cache, ent, &ent->key);2106list_del(&ent->lru);2107 delta_base_cached -= ent->size;2108free(ent);2109}21102111static void*cache_or_unpack_entry(struct packed_git *p, off_t base_offset,2112unsigned long*base_size,enum object_type *type)2113{2114struct delta_base_cache_entry *ent;21152116 ent =get_delta_base_cache_entry(p, base_offset);2117if(!ent)2118returnunpack_entry(p, base_offset, type, base_size);21192120if(type)2121*type = ent->type;2122if(base_size)2123*base_size = ent->size;2124returnxmemdupz(ent->data, ent->size);2125}21262127staticinlinevoidrelease_delta_base_cache(struct delta_base_cache_entry *ent)2128{2129free(ent->data);2130detach_delta_base_cache_entry(ent);2131}21322133voidclear_delta_base_cache(void)2134{2135struct list_head *lru, *tmp;2136list_for_each_safe(lru, tmp, &delta_base_cache_lru) {2137struct delta_base_cache_entry *entry =2138list_entry(lru,struct delta_base_cache_entry, lru);2139release_delta_base_cache(entry);2140}2141}21422143static voidadd_delta_base_cache(struct packed_git *p, off_t base_offset,2144void*base,unsigned long base_size,enum object_type type)2145{2146struct delta_base_cache_entry *ent =xmalloc(sizeof(*ent));2147struct list_head *lru, *tmp;21482149 delta_base_cached += base_size;21502151list_for_each_safe(lru, tmp, &delta_base_cache_lru) {2152struct delta_base_cache_entry *f =2153list_entry(lru,struct delta_base_cache_entry, lru);2154if(delta_base_cached <= delta_base_cache_limit)2155break;2156release_delta_base_cache(f);2157}21582159 ent->key.p = p;2160 ent->key.base_offset = base_offset;2161 ent->type = type;2162 ent->data = base;2163 ent->size = base_size;2164list_add_tail(&ent->lru, &delta_base_cache_lru);21652166if(!delta_base_cache.cmpfn)2167hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL,0);2168hashmap_entry_init(ent,pack_entry_hash(p, base_offset));2169hashmap_add(&delta_base_cache, ent);2170}21712172intpacked_object_info(struct packed_git *p, off_t obj_offset,2173struct object_info *oi)2174{2175struct pack_window *w_curs = NULL;2176unsigned long size;2177 off_t curpos = obj_offset;2178enum object_type type;21792180/*2181 * We always get the representation type, but only convert it to2182 * a "real" type later if the caller is interested.2183 */2184if(oi->contentp) {2185*oi->contentp =cache_or_unpack_entry(p, obj_offset, oi->sizep,2186&type);2187if(!*oi->contentp)2188 type = OBJ_BAD;2189}else{2190 type =unpack_object_header(p, &w_curs, &curpos, &size);2191}21922193if(!oi->contentp && oi->sizep) {2194if(type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {2195 off_t tmp_pos = curpos;2196 off_t base_offset =get_delta_base(p, &w_curs, &tmp_pos,2197 type, obj_offset);2198if(!base_offset) {2199 type = OBJ_BAD;2200goto out;2201}2202*oi->sizep =get_size_from_delta(p, &w_curs, tmp_pos);2203if(*oi->sizep ==0) {2204 type = OBJ_BAD;2205goto out;2206}2207}else{2208*oi->sizep = size;2209}2210}22112212if(oi->disk_sizep) {2213struct revindex_entry *revidx =find_pack_revindex(p, obj_offset);2214*oi->disk_sizep = revidx[1].offset - obj_offset;2215}22162217if(oi->typep || oi->typename) {2218enum object_type ptot;2219 ptot =packed_to_object_type(p, obj_offset, type, &w_curs,2220 curpos);2221if(oi->typep)2222*oi->typep = ptot;2223if(oi->typename) {2224const char*tn =typename(ptot);2225if(tn)2226strbuf_addstr(oi->typename, tn);2227}2228if(ptot <0) {2229 type = OBJ_BAD;2230goto out;2231}2232}22332234if(oi->delta_base_sha1) {2235if(type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {2236const unsigned char*base;22372238 base =get_delta_base_sha1(p, &w_curs, curpos,2239 type, obj_offset);2240if(!base) {2241 type = OBJ_BAD;2242goto out;2243}22442245hashcpy(oi->delta_base_sha1, base);2246}else2247hashclr(oi->delta_base_sha1);2248}22492250 oi->whence =in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :2251 OI_PACKED;22522253out:2254unuse_pack(&w_curs);2255return type;2256}22572258static void*unpack_compressed_entry(struct packed_git *p,2259struct pack_window **w_curs,2260 off_t curpos,2261unsigned long size)2262{2263int st;2264 git_zstream stream;2265unsigned char*buffer, *in;22662267 buffer =xmallocz_gently(size);2268if(!buffer)2269return NULL;2270memset(&stream,0,sizeof(stream));2271 stream.next_out = buffer;2272 stream.avail_out = size +1;22732274git_inflate_init(&stream);2275do{2276 in =use_pack(p, w_curs, curpos, &stream.avail_in);2277 stream.next_in = in;2278 st =git_inflate(&stream, Z_FINISH);2279if(!stream.avail_out)2280break;/* the payload is larger than it should be */2281 curpos += stream.next_in - in;2282}while(st == Z_OK || st == Z_BUF_ERROR);2283git_inflate_end(&stream);2284if((st != Z_STREAM_END) || stream.total_out != size) {2285free(buffer);2286return NULL;2287}22882289return buffer;2290}22912292static void*read_object(const unsigned char*sha1,enum object_type *type,2293unsigned long*size);22942295static voidwrite_pack_access_log(struct packed_git *p, off_t obj_offset)2296{2297static struct trace_key pack_access =TRACE_KEY_INIT(PACK_ACCESS);2298trace_printf_key(&pack_access,"%s%"PRIuMAX"\n",2299 p->pack_name, (uintmax_t)obj_offset);2300}23012302int do_check_packed_object_crc;23032304#define UNPACK_ENTRY_STACK_PREALLOC 642305struct unpack_entry_stack_ent {2306 off_t obj_offset;2307 off_t curpos;2308unsigned long size;2309};23102311void*unpack_entry(struct packed_git *p, off_t obj_offset,2312enum object_type *final_type,unsigned long*final_size)2313{2314struct pack_window *w_curs = NULL;2315 off_t curpos = obj_offset;2316void*data = NULL;2317unsigned long size;2318enum object_type type;2319struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];2320struct unpack_entry_stack_ent *delta_stack = small_delta_stack;2321int delta_stack_nr =0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;2322int base_from_cache =0;23232324write_pack_access_log(p, obj_offset);23252326/* PHASE 1: drill down to the innermost base object */2327for(;;) {2328 off_t base_offset;2329int i;2330struct delta_base_cache_entry *ent;23312332 ent =get_delta_base_cache_entry(p, curpos);2333if(ent) {2334 type = ent->type;2335 data = ent->data;2336 size = ent->size;2337detach_delta_base_cache_entry(ent);2338 base_from_cache =1;2339break;2340}23412342if(do_check_packed_object_crc && p->index_version >1) {2343struct revindex_entry *revidx =find_pack_revindex(p, obj_offset);2344 off_t len = revidx[1].offset - obj_offset;2345if(check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {2346const unsigned char*sha1 =2347nth_packed_object_sha1(p, revidx->nr);2348error("bad packed object CRC for%s",2349sha1_to_hex(sha1));2350mark_bad_packed_object(p, sha1);2351 data = NULL;2352goto out;2353}2354}23552356 type =unpack_object_header(p, &w_curs, &curpos, &size);2357if(type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)2358break;23592360 base_offset =get_delta_base(p, &w_curs, &curpos, type, obj_offset);2361if(!base_offset) {2362error("failed to validate delta base reference "2363"at offset %"PRIuMAX" from%s",2364(uintmax_t)curpos, p->pack_name);2365/* bail to phase 2, in hopes of recovery */2366 data = NULL;2367break;2368}23692370/* push object, proceed to base */2371if(delta_stack_nr >= delta_stack_alloc2372&& delta_stack == small_delta_stack) {2373 delta_stack_alloc =alloc_nr(delta_stack_nr);2374ALLOC_ARRAY(delta_stack, delta_stack_alloc);2375memcpy(delta_stack, small_delta_stack,2376sizeof(*delta_stack)*delta_stack_nr);2377}else{2378ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);2379}2380 i = delta_stack_nr++;2381 delta_stack[i].obj_offset = obj_offset;2382 delta_stack[i].curpos = curpos;2383 delta_stack[i].size = size;23842385 curpos = obj_offset = base_offset;2386}23872388/* PHASE 2: handle the base */2389switch(type) {2390case OBJ_OFS_DELTA:2391case OBJ_REF_DELTA:2392if(data)2393die("BUG: unpack_entry: left loop at a valid delta");2394break;2395case OBJ_COMMIT:2396case OBJ_TREE:2397case OBJ_BLOB:2398case OBJ_TAG:2399if(!base_from_cache)2400 data =unpack_compressed_entry(p, &w_curs, curpos, size);2401break;2402default:2403 data = NULL;2404error("unknown object type%iat offset %"PRIuMAX" in%s",2405 type, (uintmax_t)obj_offset, p->pack_name);2406}24072408/* PHASE 3: apply deltas in order */24092410/* invariants:2411 * 'data' holds the base data, or NULL if there was corruption2412 */2413while(delta_stack_nr) {2414void*delta_data;2415void*base = data;2416void*external_base = NULL;2417unsigned long delta_size, base_size = size;2418int i;24192420 data = NULL;24212422if(base)2423add_delta_base_cache(p, obj_offset, base, base_size, type);24242425if(!base) {2426/*2427 * We're probably in deep shit, but let's try to fetch2428 * the required base anyway from another pack or loose.2429 * This is costly but should happen only in the presence2430 * of a corrupted pack, and is better than failing outright.2431 */2432struct revindex_entry *revidx;2433const unsigned char*base_sha1;2434 revidx =find_pack_revindex(p, obj_offset);2435if(revidx) {2436 base_sha1 =nth_packed_object_sha1(p, revidx->nr);2437error("failed to read delta base object%s"2438" at offset %"PRIuMAX" from%s",2439sha1_to_hex(base_sha1), (uintmax_t)obj_offset,2440 p->pack_name);2441mark_bad_packed_object(p, base_sha1);2442 base =read_object(base_sha1, &type, &base_size);2443 external_base = base;2444}2445}24462447 i = --delta_stack_nr;2448 obj_offset = delta_stack[i].obj_offset;2449 curpos = delta_stack[i].curpos;2450 delta_size = delta_stack[i].size;24512452if(!base)2453continue;24542455 delta_data =unpack_compressed_entry(p, &w_curs, curpos, delta_size);24562457if(!delta_data) {2458error("failed to unpack compressed delta "2459"at offset %"PRIuMAX" from%s",2460(uintmax_t)curpos, p->pack_name);2461 data = NULL;2462free(external_base);2463continue;2464}24652466 data =patch_delta(base, base_size,2467 delta_data, delta_size,2468&size);24692470/*2471 * We could not apply the delta; warn the user, but keep going.2472 * Our failure will be noticed either in the next iteration of2473 * the loop, or if this is the final delta, in the caller when2474 * we return NULL. Those code paths will take care of making2475 * a more explicit warning and retrying with another copy of2476 * the object.2477 */2478if(!data)2479error("failed to apply delta");24802481free(delta_data);2482free(external_base);2483}24842485if(final_type)2486*final_type = type;2487if(final_size)2488*final_size = size;24892490out:2491unuse_pack(&w_curs);24922493if(delta_stack != small_delta_stack)2494free(delta_stack);24952496return data;2497}24982499const unsigned char*nth_packed_object_sha1(struct packed_git *p,2500uint32_t n)2501{2502const unsigned char*index = p->index_data;2503if(!index) {2504if(open_pack_index(p))2505return NULL;2506 index = p->index_data;2507}2508if(n >= p->num_objects)2509return NULL;2510 index +=4*256;2511if(p->index_version ==1) {2512return index +24* n +4;2513}else{2514 index +=8;2515return index +20* n;2516}2517}25182519const struct object_id *nth_packed_object_oid(struct object_id *oid,2520struct packed_git *p,2521uint32_t n)2522{2523const unsigned char*hash =nth_packed_object_sha1(p, n);2524if(!hash)2525return NULL;2526hashcpy(oid->hash, hash);2527return oid;2528}25292530voidcheck_pack_index_ptr(const struct packed_git *p,const void*vptr)2531{2532const unsigned char*ptr = vptr;2533const unsigned char*start = p->index_data;2534const unsigned char*end = start + p->index_size;2535if(ptr < start)2536die(_("offset before start of pack index for%s(corrupt index?)"),2537 p->pack_name);2538/* No need to check for underflow; .idx files must be at least 8 bytes */2539if(ptr >= end -8)2540die(_("offset beyond end of pack index for%s(truncated index?)"),2541 p->pack_name);2542}25432544off_t nth_packed_object_offset(const struct packed_git *p,uint32_t n)2545{2546const unsigned char*index = p->index_data;2547 index +=4*256;2548if(p->index_version ==1) {2549returnntohl(*((uint32_t*)(index +24* n)));2550}else{2551uint32_t off;2552 index +=8+ p->num_objects * (20+4);2553 off =ntohl(*((uint32_t*)(index +4* n)));2554if(!(off &0x80000000))2555return off;2556 index += p->num_objects *4+ (off &0x7fffffff) *8;2557check_pack_index_ptr(p, index);2558return(((uint64_t)ntohl(*((uint32_t*)(index +0)))) <<32) |2559ntohl(*((uint32_t*)(index +4)));2560}2561}25622563off_t find_pack_entry_one(const unsigned char*sha1,2564struct packed_git *p)2565{2566const uint32_t*level1_ofs = p->index_data;2567const unsigned char*index = p->index_data;2568unsigned hi, lo, stride;2569static int debug_lookup = -1;25702571if(debug_lookup <0)2572 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");25732574if(!index) {2575if(open_pack_index(p))2576return0;2577 level1_ofs = p->index_data;2578 index = p->index_data;2579}2580if(p->index_version >1) {2581 level1_ofs +=2;2582 index +=8;2583}2584 index +=4*256;2585 hi =ntohl(level1_ofs[*sha1]);2586 lo = ((*sha1 ==0x0) ?0:ntohl(level1_ofs[*sha1 -1]));2587if(p->index_version >1) {2588 stride =20;2589}else{2590 stride =24;2591 index +=4;2592}25932594if(debug_lookup)2595printf("%02x%02x%02x... lo%uhi%unr %"PRIu32"\n",2596 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);25972598while(lo < hi) {2599unsigned mi = (lo + hi) /2;2600int cmp =hashcmp(index + mi * stride, sha1);26012602if(debug_lookup)2603printf("lo%uhi%urg%umi%u\n",2604 lo, hi, hi - lo, mi);2605if(!cmp)2606returnnth_packed_object_offset(p, mi);2607if(cmp >0)2608 hi = mi;2609else2610 lo = mi+1;2611}2612return0;2613}26142615intis_pack_valid(struct packed_git *p)2616{2617/* An already open pack is known to be valid. */2618if(p->pack_fd != -1)2619return1;26202621/* If the pack has one window completely covering the2622 * file size, the pack is known to be valid even if2623 * the descriptor is not currently open.2624 */2625if(p->windows) {2626struct pack_window *w = p->windows;26272628if(!w->offset && w->len == p->pack_size)2629return1;2630}26312632/* Force the pack to open to prove its valid. */2633return!open_packed_git(p);2634}26352636static intfill_pack_entry(const unsigned char*sha1,2637struct pack_entry *e,2638struct packed_git *p)2639{2640 off_t offset;26412642if(p->num_bad_objects) {2643unsigned i;2644for(i =0; i < p->num_bad_objects; i++)2645if(!hashcmp(sha1, p->bad_object_sha1 +20* i))2646return0;2647}26482649 offset =find_pack_entry_one(sha1, p);2650if(!offset)2651return0;26522653/*2654 * We are about to tell the caller where they can locate the2655 * requested object. We better make sure the packfile is2656 * still here and can be accessed before supplying that2657 * answer, as it may have been deleted since the index was2658 * loaded!2659 */2660if(!is_pack_valid(p))2661return0;2662 e->offset = offset;2663 e->p = p;2664hashcpy(e->sha1, sha1);2665return1;2666}26672668/*2669 * Iff a pack file contains the object named by sha1, return true and2670 * store its location to e.2671 */2672static intfind_pack_entry(const unsigned char*sha1,struct pack_entry *e)2673{2674struct mru_entry *p;26752676prepare_packed_git();2677if(!packed_git)2678return0;26792680for(p = packed_git_mru->head; p; p = p->next) {2681if(fill_pack_entry(sha1, e, p->item)) {2682mru_mark(packed_git_mru, p);2683return1;2684}2685}2686return0;2687}26882689struct packed_git *find_sha1_pack(const unsigned char*sha1,2690struct packed_git *packs)2691{2692struct packed_git *p;26932694for(p = packs; p; p = p->next) {2695if(find_pack_entry_one(sha1, p))2696return p;2697}2698return NULL;26992700}27012702static intsha1_loose_object_info(const unsigned char*sha1,2703struct object_info *oi,2704int flags)2705{2706int status =0;2707unsigned long mapsize;2708void*map;2709 git_zstream stream;2710char hdr[32];2711struct strbuf hdrbuf = STRBUF_INIT;2712unsigned long size_scratch;27132714if(oi->delta_base_sha1)2715hashclr(oi->delta_base_sha1);27162717/*2718 * If we don't care about type or size, then we don't2719 * need to look inside the object at all. Note that we2720 * do not optimize out the stat call, even if the2721 * caller doesn't care about the disk-size, since our2722 * return value implicitly indicates whether the2723 * object even exists.2724 */2725if(!oi->typep && !oi->typename && !oi->sizep && !oi->contentp) {2726const char*path;2727struct stat st;2728if(stat_sha1_file(sha1, &st, &path) <0)2729return-1;2730if(oi->disk_sizep)2731*oi->disk_sizep = st.st_size;2732return0;2733}27342735 map =map_sha1_file(sha1, &mapsize);2736if(!map)2737return-1;27382739if(!oi->sizep)2740 oi->sizep = &size_scratch;27412742if(oi->disk_sizep)2743*oi->disk_sizep = mapsize;2744if((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {2745if(unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr,sizeof(hdr), &hdrbuf) <0)2746 status =error("unable to unpack%sheader with --allow-unknown-type",2747sha1_to_hex(sha1));2748}else if(unpack_sha1_header(&stream, map, mapsize, hdr,sizeof(hdr)) <0)2749 status =error("unable to unpack%sheader",2750sha1_to_hex(sha1));2751if(status <0)2752;/* Do nothing */2753else if(hdrbuf.len) {2754if((status =parse_sha1_header_extended(hdrbuf.buf, oi, flags)) <0)2755 status =error("unable to parse%sheader with --allow-unknown-type",2756sha1_to_hex(sha1));2757}else if((status =parse_sha1_header_extended(hdr, oi, flags)) <0)2758 status =error("unable to parse%sheader",sha1_to_hex(sha1));27592760if(status >=0&& oi->contentp)2761*oi->contentp =unpack_sha1_rest(&stream, hdr,2762*oi->sizep, sha1);2763else2764git_inflate_end(&stream);27652766munmap(map, mapsize);2767if(status && oi->typep)2768*oi->typep = status;2769if(oi->sizep == &size_scratch)2770 oi->sizep = NULL;2771strbuf_release(&hdrbuf);2772 oi->whence = OI_LOOSE;2773return(status <0) ? status :0;2774}27752776intsha1_object_info_extended(const unsigned char*sha1,struct object_info *oi,unsigned flags)2777{2778static struct object_info blank_oi = OBJECT_INFO_INIT;2779struct pack_entry e;2780int rtype;2781const unsigned char*real = (flags & OBJECT_INFO_LOOKUP_REPLACE) ?2782lookup_replace_object(sha1) :2783 sha1;27842785if(!oi)2786 oi = &blank_oi;27872788if(!(flags & OBJECT_INFO_SKIP_CACHED)) {2789struct cached_object *co =find_cached_object(real);2790if(co) {2791if(oi->typep)2792*(oi->typep) = co->type;2793if(oi->sizep)2794*(oi->sizep) = co->size;2795if(oi->disk_sizep)2796*(oi->disk_sizep) =0;2797if(oi->delta_base_sha1)2798hashclr(oi->delta_base_sha1);2799if(oi->typename)2800strbuf_addstr(oi->typename,typename(co->type));2801if(oi->contentp)2802*oi->contentp =xmemdupz(co->buf, co->size);2803 oi->whence = OI_CACHED;2804return0;2805}2806}28072808if(!find_pack_entry(real, &e)) {2809/* Most likely it's a loose object. */2810if(!sha1_loose_object_info(real, oi, flags))2811return0;28122813/* Not a loose object; someone else may have just packed it. */2814if(flags & OBJECT_INFO_QUICK) {2815return-1;2816}else{2817reprepare_packed_git();2818if(!find_pack_entry(real, &e))2819return-1;2820}2821}28222823if(oi == &blank_oi)2824/*2825 * We know that the caller doesn't actually need the2826 * information below, so return early.2827 */2828return0;28292830 rtype =packed_object_info(e.p, e.offset, oi);2831if(rtype <0) {2832mark_bad_packed_object(e.p, real);2833returnsha1_object_info_extended(real, oi,0);2834}else if(oi->whence == OI_PACKED) {2835 oi->u.packed.offset = e.offset;2836 oi->u.packed.pack = e.p;2837 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||2838 rtype == OBJ_OFS_DELTA);2839}28402841return0;2842}28432844/* returns enum object_type or negative */2845intsha1_object_info(const unsigned char*sha1,unsigned long*sizep)2846{2847enum object_type type;2848struct object_info oi = OBJECT_INFO_INIT;28492850 oi.typep = &type;2851 oi.sizep = sizep;2852if(sha1_object_info_extended(sha1, &oi,2853 OBJECT_INFO_LOOKUP_REPLACE) <0)2854return-1;2855return type;2856}28572858intpretend_sha1_file(void*buf,unsigned long len,enum object_type type,2859unsigned char*sha1)2860{2861struct cached_object *co;28622863hash_sha1_file(buf, len,typename(type), sha1);2864if(has_sha1_file(sha1) ||find_cached_object(sha1))2865return0;2866ALLOC_GROW(cached_objects, cached_object_nr +1, cached_object_alloc);2867 co = &cached_objects[cached_object_nr++];2868 co->size = len;2869 co->type = type;2870 co->buf =xmalloc(len);2871memcpy(co->buf, buf, len);2872hashcpy(co->sha1, sha1);2873return0;2874}28752876static void*read_object(const unsigned char*sha1,enum object_type *type,2877unsigned long*size)2878{2879struct object_info oi = OBJECT_INFO_INIT;2880void*content;2881 oi.typep = type;2882 oi.sizep = size;2883 oi.contentp = &content;28842885if(sha1_object_info_extended(sha1, &oi,0) <0)2886return NULL;2887return content;2888}28892890/*2891 * This function dies on corrupt objects; the callers who want to2892 * deal with them should arrange to call read_object() and give error2893 * messages themselves.2894 */2895void*read_sha1_file_extended(const unsigned char*sha1,2896enum object_type *type,2897unsigned long*size,2898int lookup_replace)2899{2900void*data;2901const struct packed_git *p;2902const char*path;2903struct stat st;2904const unsigned char*repl = lookup_replace ?lookup_replace_object(sha1)2905: sha1;29062907 errno =0;2908 data =read_object(repl, type, size);2909if(data)2910return data;29112912if(errno && errno != ENOENT)2913die_errno("failed to read object%s",sha1_to_hex(sha1));29142915/* die if we replaced an object with one that does not exist */2916if(repl != sha1)2917die("replacement%snot found for%s",2918sha1_to_hex(repl),sha1_to_hex(sha1));29192920if(!stat_sha1_file(repl, &st, &path))2921die("loose object%s(stored in%s) is corrupt",2922sha1_to_hex(repl), path);29232924if((p =has_packed_and_bad(repl)) != NULL)2925die("packed object%s(stored in%s) is corrupt",2926sha1_to_hex(repl), p->pack_name);29272928return NULL;2929}29302931void*read_object_with_reference(const unsigned char*sha1,2932const char*required_type_name,2933unsigned long*size,2934unsigned char*actual_sha1_return)2935{2936enum object_type type, required_type;2937void*buffer;2938unsigned long isize;2939unsigned char actual_sha1[20];29402941 required_type =type_from_string(required_type_name);2942hashcpy(actual_sha1, sha1);2943while(1) {2944int ref_length = -1;2945const char*ref_type = NULL;29462947 buffer =read_sha1_file(actual_sha1, &type, &isize);2948if(!buffer)2949return NULL;2950if(type == required_type) {2951*size = isize;2952if(actual_sha1_return)2953hashcpy(actual_sha1_return, actual_sha1);2954return buffer;2955}2956/* Handle references */2957else if(type == OBJ_COMMIT)2958 ref_type ="tree ";2959else if(type == OBJ_TAG)2960 ref_type ="object ";2961else{2962free(buffer);2963return NULL;2964}2965 ref_length =strlen(ref_type);29662967if(ref_length +40> isize ||2968memcmp(buffer, ref_type, ref_length) ||2969get_sha1_hex((char*) buffer + ref_length, actual_sha1)) {2970free(buffer);2971return NULL;2972}2973free(buffer);2974/* Now we have the ID of the referred-to object in2975 * actual_sha1. Check again. */2976}2977}29782979static voidwrite_sha1_file_prepare(const void*buf,unsigned long len,2980const char*type,unsigned char*sha1,2981char*hdr,int*hdrlen)2982{2983 git_SHA_CTX c;29842985/* Generate the header */2986*hdrlen =xsnprintf(hdr, *hdrlen,"%s %lu", type, len)+1;29872988/* Sha1.. */2989git_SHA1_Init(&c);2990git_SHA1_Update(&c, hdr, *hdrlen);2991git_SHA1_Update(&c, buf, len);2992git_SHA1_Final(sha1, &c);2993}29942995/*2996 * Move the just written object into its final resting place.2997 */2998intfinalize_object_file(const char*tmpfile,const char*filename)2999{3000int ret =0;30013002if(object_creation_mode == OBJECT_CREATION_USES_RENAMES)3003goto try_rename;3004else if(link(tmpfile, filename))3005 ret = errno;30063007/*3008 * Coda hack - coda doesn't like cross-directory links,3009 * so we fall back to a rename, which will mean that it3010 * won't be able to check collisions, but that's not a3011 * big deal.3012 *3013 * The same holds for FAT formatted media.3014 *3015 * When this succeeds, we just return. We have nothing3016 * left to unlink.3017 */3018if(ret && ret != EEXIST) {3019 try_rename:3020if(!rename(tmpfile, filename))3021goto out;3022 ret = errno;3023}3024unlink_or_warn(tmpfile);3025if(ret) {3026if(ret != EEXIST) {3027returnerror_errno("unable to write sha1 filename%s", filename);3028}3029/* FIXME!!! Collision check here ? */3030}30313032out:3033if(adjust_shared_perm(filename))3034returnerror("unable to set permission to '%s'", filename);3035return0;3036}30373038static intwrite_buffer(int fd,const void*buf,size_t len)3039{3040if(write_in_full(fd, buf, len) <0)3041returnerror_errno("file write error");3042return0;3043}30443045inthash_sha1_file(const void*buf,unsigned long len,const char*type,3046unsigned char*sha1)3047{3048char hdr[32];3049int hdrlen =sizeof(hdr);3050write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);3051return0;3052}30533054/* Finalize a file on disk, and close it. */3055static voidclose_sha1_file(int fd)3056{3057if(fsync_object_files)3058fsync_or_die(fd,"sha1 file");3059if(close(fd) !=0)3060die_errno("error when closing sha1 file");3061}30623063/* Size of directory component, including the ending '/' */3064staticinlineintdirectory_size(const char*filename)3065{3066const char*s =strrchr(filename,'/');3067if(!s)3068return0;3069return s - filename +1;3070}30713072/*3073 * This creates a temporary file in the same directory as the final3074 * 'filename'3075 *3076 * We want to avoid cross-directory filename renames, because those3077 * can have problems on various filesystems (FAT, NFS, Coda).3078 */3079static intcreate_tmpfile(struct strbuf *tmp,const char*filename)3080{3081int fd, dirlen =directory_size(filename);30823083strbuf_reset(tmp);3084strbuf_add(tmp, filename, dirlen);3085strbuf_addstr(tmp,"tmp_obj_XXXXXX");3086 fd =git_mkstemp_mode(tmp->buf,0444);3087if(fd <0&& dirlen && errno == ENOENT) {3088/*3089 * Make sure the directory exists; note that the contents3090 * of the buffer are undefined after mkstemp returns an3091 * error, so we have to rewrite the whole buffer from3092 * scratch.3093 */3094strbuf_reset(tmp);3095strbuf_add(tmp, filename, dirlen -1);3096if(mkdir(tmp->buf,0777) && errno != EEXIST)3097return-1;3098if(adjust_shared_perm(tmp->buf))3099return-1;31003101/* Try again */3102strbuf_addstr(tmp,"/tmp_obj_XXXXXX");3103 fd =git_mkstemp_mode(tmp->buf,0444);3104}3105return fd;3106}31073108static intwrite_loose_object(const unsigned char*sha1,char*hdr,int hdrlen,3109const void*buf,unsigned long len,time_t mtime)3110{3111int fd, ret;3112unsigned char compressed[4096];3113 git_zstream stream;3114 git_SHA_CTX c;3115unsigned char parano_sha1[20];3116static struct strbuf tmp_file = STRBUF_INIT;3117const char*filename =sha1_file_name(sha1);31183119 fd =create_tmpfile(&tmp_file, filename);3120if(fd <0) {3121if(errno == EACCES)3122returnerror("insufficient permission for adding an object to repository database%s",get_object_directory());3123else3124returnerror_errno("unable to create temporary file");3125}31263127/* Set it up */3128git_deflate_init(&stream, zlib_compression_level);3129 stream.next_out = compressed;3130 stream.avail_out =sizeof(compressed);3131git_SHA1_Init(&c);31323133/* First header.. */3134 stream.next_in = (unsigned char*)hdr;3135 stream.avail_in = hdrlen;3136while(git_deflate(&stream,0) == Z_OK)3137;/* nothing */3138git_SHA1_Update(&c, hdr, hdrlen);31393140/* Then the data itself.. */3141 stream.next_in = (void*)buf;3142 stream.avail_in = len;3143do{3144unsigned char*in0 = stream.next_in;3145 ret =git_deflate(&stream, Z_FINISH);3146git_SHA1_Update(&c, in0, stream.next_in - in0);3147if(write_buffer(fd, compressed, stream.next_out - compressed) <0)3148die("unable to write sha1 file");3149 stream.next_out = compressed;3150 stream.avail_out =sizeof(compressed);3151}while(ret == Z_OK);31523153if(ret != Z_STREAM_END)3154die("unable to deflate new object%s(%d)",sha1_to_hex(sha1), ret);3155 ret =git_deflate_end_gently(&stream);3156if(ret != Z_OK)3157die("deflateEnd on object%sfailed (%d)",sha1_to_hex(sha1), ret);3158git_SHA1_Final(parano_sha1, &c);3159if(hashcmp(sha1, parano_sha1) !=0)3160die("confused by unstable object source data for%s",sha1_to_hex(sha1));31613162close_sha1_file(fd);31633164if(mtime) {3165struct utimbuf utb;3166 utb.actime = mtime;3167 utb.modtime = mtime;3168if(utime(tmp_file.buf, &utb) <0)3169warning_errno("failed utime() on%s", tmp_file.buf);3170}31713172returnfinalize_object_file(tmp_file.buf, filename);3173}31743175static intfreshen_loose_object(const unsigned char*sha1)3176{3177returncheck_and_freshen(sha1,1);3178}31793180static intfreshen_packed_object(const unsigned char*sha1)3181{3182struct pack_entry e;3183if(!find_pack_entry(sha1, &e))3184return0;3185if(e.p->freshened)3186return1;3187if(!freshen_file(e.p->pack_name))3188return0;3189 e.p->freshened =1;3190return1;3191}31923193intwrite_sha1_file(const void*buf,unsigned long len,const char*type,unsigned char*sha1)3194{3195char hdr[32];3196int hdrlen =sizeof(hdr);31973198/* Normally if we have it in the pack then we do not bother writing3199 * it out into .git/objects/??/?{38} file.3200 */3201write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);3202if(freshen_packed_object(sha1) ||freshen_loose_object(sha1))3203return0;3204returnwrite_loose_object(sha1, hdr, hdrlen, buf, len,0);3205}32063207inthash_sha1_file_literally(const void*buf,unsigned long len,const char*type,3208unsigned char*sha1,unsigned flags)3209{3210char*header;3211int hdrlen, status =0;32123213/* type string, SP, %lu of the length plus NUL must fit this */3214 hdrlen =strlen(type) +32;3215 header =xmalloc(hdrlen);3216write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);32173218if(!(flags & HASH_WRITE_OBJECT))3219goto cleanup;3220if(freshen_packed_object(sha1) ||freshen_loose_object(sha1))3221goto cleanup;3222 status =write_loose_object(sha1, header, hdrlen, buf, len,0);32233224cleanup:3225free(header);3226return status;3227}32283229intforce_object_loose(const unsigned char*sha1,time_t mtime)3230{3231void*buf;3232unsigned long len;3233enum object_type type;3234char hdr[32];3235int hdrlen;3236int ret;32373238if(has_loose_object(sha1))3239return0;3240 buf =read_object(sha1, &type, &len);3241if(!buf)3242returnerror("cannot read sha1_file for%s",sha1_to_hex(sha1));3243 hdrlen =xsnprintf(hdr,sizeof(hdr),"%s %lu",typename(type), len) +1;3244 ret =write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);3245free(buf);32463247return ret;3248}32493250inthas_pack_index(const unsigned char*sha1)3251{3252struct stat st;3253if(stat(sha1_pack_index_name(sha1), &st))3254return0;3255return1;3256}32573258inthas_sha1_pack(const unsigned char*sha1)3259{3260struct pack_entry e;3261returnfind_pack_entry(sha1, &e);3262}32633264inthas_sha1_file_with_flags(const unsigned char*sha1,int flags)3265{3266if(!startup_info->have_repository)3267return0;3268returnsha1_object_info_extended(sha1, NULL,3269 flags | OBJECT_INFO_SKIP_CACHED) >=0;3270}32713272inthas_object_file(const struct object_id *oid)3273{3274returnhas_sha1_file(oid->hash);3275}32763277inthas_object_file_with_flags(const struct object_id *oid,int flags)3278{3279returnhas_sha1_file_with_flags(oid->hash, flags);3280}32813282static voidcheck_tree(const void*buf,size_t size)3283{3284struct tree_desc desc;3285struct name_entry entry;32863287init_tree_desc(&desc, buf, size);3288while(tree_entry(&desc, &entry))3289/* do nothing3290 * tree_entry() will die() on malformed entries */3291;3292}32933294static voidcheck_commit(const void*buf,size_t size)3295{3296struct commit c;3297memset(&c,0,sizeof(c));3298if(parse_commit_buffer(&c, buf, size))3299die("corrupt commit");3300}33013302static voidcheck_tag(const void*buf,size_t size)3303{3304struct tag t;3305memset(&t,0,sizeof(t));3306if(parse_tag_buffer(&t, buf, size))3307die("corrupt tag");3308}33093310static intindex_mem(unsigned char*sha1,void*buf,size_t size,3311enum object_type type,3312const char*path,unsigned flags)3313{3314int ret, re_allocated =0;3315int write_object = flags & HASH_WRITE_OBJECT;33163317if(!type)3318 type = OBJ_BLOB;33193320/*3321 * Convert blobs to git internal format3322 */3323if((type == OBJ_BLOB) && path) {3324struct strbuf nbuf = STRBUF_INIT;3325if(convert_to_git(&the_index, path, buf, size, &nbuf,3326 write_object ? safe_crlf : SAFE_CRLF_FALSE)) {3327 buf =strbuf_detach(&nbuf, &size);3328 re_allocated =1;3329}3330}3331if(flags & HASH_FORMAT_CHECK) {3332if(type == OBJ_TREE)3333check_tree(buf, size);3334if(type == OBJ_COMMIT)3335check_commit(buf, size);3336if(type == OBJ_TAG)3337check_tag(buf, size);3338}33393340if(write_object)3341 ret =write_sha1_file(buf, size,typename(type), sha1);3342else3343 ret =hash_sha1_file(buf, size,typename(type), sha1);3344if(re_allocated)3345free(buf);3346return ret;3347}33483349static intindex_stream_convert_blob(unsigned char*sha1,int fd,3350const char*path,unsigned flags)3351{3352int ret;3353const int write_object = flags & HASH_WRITE_OBJECT;3354struct strbuf sbuf = STRBUF_INIT;33553356assert(path);3357assert(would_convert_to_git_filter_fd(path));33583359convert_to_git_filter_fd(&the_index, path, fd, &sbuf,3360 write_object ? safe_crlf : SAFE_CRLF_FALSE);33613362if(write_object)3363 ret =write_sha1_file(sbuf.buf, sbuf.len,typename(OBJ_BLOB),3364 sha1);3365else3366 ret =hash_sha1_file(sbuf.buf, sbuf.len,typename(OBJ_BLOB),3367 sha1);3368strbuf_release(&sbuf);3369return ret;3370}33713372static intindex_pipe(unsigned char*sha1,int fd,enum object_type type,3373const char*path,unsigned flags)3374{3375struct strbuf sbuf = STRBUF_INIT;3376int ret;33773378if(strbuf_read(&sbuf, fd,4096) >=0)3379 ret =index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);3380else3381 ret = -1;3382strbuf_release(&sbuf);3383return ret;3384}33853386#define SMALL_FILE_SIZE (32*1024)33873388static intindex_core(unsigned char*sha1,int fd,size_t size,3389enum object_type type,const char*path,3390unsigned flags)3391{3392int ret;33933394if(!size) {3395 ret =index_mem(sha1,"", size, type, path, flags);3396}else if(size <= SMALL_FILE_SIZE) {3397char*buf =xmalloc(size);3398if(size ==read_in_full(fd, buf, size))3399 ret =index_mem(sha1, buf, size, type, path, flags);3400else3401 ret =error_errno("short read");3402free(buf);3403}else{3404void*buf =xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd,0);3405 ret =index_mem(sha1, buf, size, type, path, flags);3406munmap(buf, size);3407}3408return ret;3409}34103411/*3412 * This creates one packfile per large blob unless bulk-checkin3413 * machinery is "plugged".3414 *3415 * This also bypasses the usual "convert-to-git" dance, and that is on3416 * purpose. We could write a streaming version of the converting3417 * functions and insert that before feeding the data to fast-import3418 * (or equivalent in-core API described above). However, that is3419 * somewhat complicated, as we do not know the size of the filter3420 * result, which we need to know beforehand when writing a git object.3421 * Since the primary motivation for trying to stream from the working3422 * tree file and to avoid mmaping it in core is to deal with large3423 * binary blobs, they generally do not want to get any conversion, and3424 * callers should avoid this code path when filters are requested.3425 */3426static intindex_stream(unsigned char*sha1,int fd,size_t size,3427enum object_type type,const char*path,3428unsigned flags)3429{3430returnindex_bulk_checkin(sha1, fd, size, type, path, flags);3431}34323433intindex_fd(unsigned char*sha1,int fd,struct stat *st,3434enum object_type type,const char*path,unsigned flags)3435{3436int ret;34373438/*3439 * Call xsize_t() only when needed to avoid potentially unnecessary3440 * die() for large files.3441 */3442if(type == OBJ_BLOB && path &&would_convert_to_git_filter_fd(path))3443 ret =index_stream_convert_blob(sha1, fd, path, flags);3444else if(!S_ISREG(st->st_mode))3445 ret =index_pipe(sha1, fd, type, path, flags);3446else if(st->st_size <= big_file_threshold || type != OBJ_BLOB ||3447(path &&would_convert_to_git(&the_index, path)))3448 ret =index_core(sha1, fd,xsize_t(st->st_size), type, path,3449 flags);3450else3451 ret =index_stream(sha1, fd,xsize_t(st->st_size), type, path,3452 flags);3453close(fd);3454return ret;3455}34563457intindex_path(unsigned char*sha1,const char*path,struct stat *st,unsigned flags)3458{3459int fd;3460struct strbuf sb = STRBUF_INIT;34613462switch(st->st_mode & S_IFMT) {3463case S_IFREG:3464 fd =open(path, O_RDONLY);3465if(fd <0)3466returnerror_errno("open(\"%s\")", path);3467if(index_fd(sha1, fd, st, OBJ_BLOB, path, flags) <0)3468returnerror("%s: failed to insert into database",3469 path);3470break;3471case S_IFLNK:3472if(strbuf_readlink(&sb, path, st->st_size))3473returnerror_errno("readlink(\"%s\")", path);3474if(!(flags & HASH_WRITE_OBJECT))3475hash_sha1_file(sb.buf, sb.len, blob_type, sha1);3476else if(write_sha1_file(sb.buf, sb.len, blob_type, sha1))3477returnerror("%s: failed to insert into database",3478 path);3479strbuf_release(&sb);3480break;3481case S_IFDIR:3482returnresolve_gitlink_ref(path,"HEAD", sha1);3483default:3484returnerror("%s: unsupported file type", path);3485}3486return0;3487}34883489intread_pack_header(int fd,struct pack_header *header)3490{3491if(read_in_full(fd, header,sizeof(*header)) <sizeof(*header))3492/* "eof before pack header was fully read" */3493return PH_ERROR_EOF;34943495if(header->hdr_signature !=htonl(PACK_SIGNATURE))3496/* "protocol error (pack signature mismatch detected)" */3497return PH_ERROR_PACK_SIGNATURE;3498if(!pack_version_ok(header->hdr_version))3499/* "protocol error (pack version unsupported)" */3500return PH_ERROR_PROTOCOL;3501return0;3502}35033504voidassert_sha1_type(const unsigned char*sha1,enum object_type expect)3505{3506enum object_type type =sha1_object_info(sha1, NULL);3507if(type <0)3508die("%sis not a valid object",sha1_to_hex(sha1));3509if(type != expect)3510die("%sis not a valid '%s' object",sha1_to_hex(sha1),3511typename(expect));3512}35133514intfor_each_file_in_obj_subdir(unsigned int subdir_nr,3515struct strbuf *path,3516 each_loose_object_fn obj_cb,3517 each_loose_cruft_fn cruft_cb,3518 each_loose_subdir_fn subdir_cb,3519void*data)3520{3521size_t origlen, baselen;3522DIR*dir;3523struct dirent *de;3524int r =0;35253526if(subdir_nr >0xff)3527BUG("invalid loose object subdirectory:%x", subdir_nr);35283529 origlen = path->len;3530strbuf_complete(path,'/');3531strbuf_addf(path,"%02x", subdir_nr);3532 baselen = path->len;35333534 dir =opendir(path->buf);3535if(!dir) {3536if(errno != ENOENT)3537 r =error_errno("unable to open%s", path->buf);3538strbuf_setlen(path, origlen);3539return r;3540}35413542while((de =readdir(dir))) {3543if(is_dot_or_dotdot(de->d_name))3544continue;35453546strbuf_setlen(path, baselen);3547strbuf_addf(path,"/%s", de->d_name);35483549if(strlen(de->d_name) == GIT_SHA1_HEXSZ -2) {3550char hex[GIT_MAX_HEXSZ+1];3551struct object_id oid;35523553xsnprintf(hex,sizeof(hex),"%02x%s",3554 subdir_nr, de->d_name);3555if(!get_oid_hex(hex, &oid)) {3556if(obj_cb) {3557 r =obj_cb(&oid, path->buf, data);3558if(r)3559break;3560}3561continue;3562}3563}35643565if(cruft_cb) {3566 r =cruft_cb(de->d_name, path->buf, data);3567if(r)3568break;3569}3570}3571closedir(dir);35723573strbuf_setlen(path, baselen);3574if(!r && subdir_cb)3575 r =subdir_cb(subdir_nr, path->buf, data);35763577strbuf_setlen(path, origlen);35783579return r;3580}35813582intfor_each_loose_file_in_objdir_buf(struct strbuf *path,3583 each_loose_object_fn obj_cb,3584 each_loose_cruft_fn cruft_cb,3585 each_loose_subdir_fn subdir_cb,3586void*data)3587{3588int r =0;3589int i;35903591for(i =0; i <256; i++) {3592 r =for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,3593 subdir_cb, data);3594if(r)3595break;3596}35973598return r;3599}36003601intfor_each_loose_file_in_objdir(const char*path,3602 each_loose_object_fn obj_cb,3603 each_loose_cruft_fn cruft_cb,3604 each_loose_subdir_fn subdir_cb,3605void*data)3606{3607struct strbuf buf = STRBUF_INIT;3608int r;36093610strbuf_addstr(&buf, path);3611 r =for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,3612 subdir_cb, data);3613strbuf_release(&buf);36143615return r;3616}36173618struct loose_alt_odb_data {3619 each_loose_object_fn *cb;3620void*data;3621};36223623static intloose_from_alt_odb(struct alternate_object_database *alt,3624void*vdata)3625{3626struct loose_alt_odb_data *data = vdata;3627struct strbuf buf = STRBUF_INIT;3628int r;36293630strbuf_addstr(&buf, alt->path);3631 r =for_each_loose_file_in_objdir_buf(&buf,3632 data->cb, NULL, NULL,3633 data->data);3634strbuf_release(&buf);3635return r;3636}36373638intfor_each_loose_object(each_loose_object_fn cb,void*data,unsigned flags)3639{3640struct loose_alt_odb_data alt;3641int r;36423643 r =for_each_loose_file_in_objdir(get_object_directory(),3644 cb, NULL, NULL, data);3645if(r)3646return r;36473648if(flags & FOR_EACH_OBJECT_LOCAL_ONLY)3649return0;36503651 alt.cb = cb;3652 alt.data = data;3653returnforeach_alt_odb(loose_from_alt_odb, &alt);3654}36553656static intfor_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb,void*data)3657{3658uint32_t i;3659int r =0;36603661for(i =0; i < p->num_objects; i++) {3662struct object_id oid;36633664if(!nth_packed_object_oid(&oid, p, i))3665returnerror("unable to get sha1 of object%uin%s",3666 i, p->pack_name);36673668 r =cb(&oid, p, i, data);3669if(r)3670break;3671}3672return r;3673}36743675intfor_each_packed_object(each_packed_object_fn cb,void*data,unsigned flags)3676{3677struct packed_git *p;3678int r =0;3679int pack_errors =0;36803681prepare_packed_git();3682for(p = packed_git; p; p = p->next) {3683if((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)3684continue;3685if(open_pack_index(p)) {3686 pack_errors =1;3687continue;3688}3689 r =for_each_object_in_pack(p, cb, data);3690if(r)3691break;3692}3693return r ? r : pack_errors;3694}36953696static intcheck_stream_sha1(git_zstream *stream,3697const char*hdr,3698unsigned long size,3699const char*path,3700const unsigned char*expected_sha1)3701{3702 git_SHA_CTX c;3703unsigned char real_sha1[GIT_MAX_RAWSZ];3704unsigned char buf[4096];3705unsigned long total_read;3706int status = Z_OK;37073708git_SHA1_Init(&c);3709git_SHA1_Update(&c, hdr, stream->total_out);37103711/*3712 * We already read some bytes into hdr, but the ones up to the NUL3713 * do not count against the object's content size.3714 */3715 total_read = stream->total_out -strlen(hdr) -1;37163717/*3718 * This size comparison must be "<=" to read the final zlib packets;3719 * see the comment in unpack_sha1_rest for details.3720 */3721while(total_read <= size &&3722(status == Z_OK || status == Z_BUF_ERROR)) {3723 stream->next_out = buf;3724 stream->avail_out =sizeof(buf);3725if(size - total_read < stream->avail_out)3726 stream->avail_out = size - total_read;3727 status =git_inflate(stream, Z_FINISH);3728git_SHA1_Update(&c, buf, stream->next_out - buf);3729 total_read += stream->next_out - buf;3730}3731git_inflate_end(stream);37323733if(status != Z_STREAM_END) {3734error("corrupt loose object '%s'",sha1_to_hex(expected_sha1));3735return-1;3736}3737if(stream->avail_in) {3738error("garbage at end of loose object '%s'",3739sha1_to_hex(expected_sha1));3740return-1;3741}37423743git_SHA1_Final(real_sha1, &c);3744if(hashcmp(expected_sha1, real_sha1)) {3745error("sha1 mismatch for%s(expected%s)", path,3746sha1_to_hex(expected_sha1));3747return-1;3748}37493750return0;3751}37523753intread_loose_object(const char*path,3754const unsigned char*expected_sha1,3755enum object_type *type,3756unsigned long*size,3757void**contents)3758{3759int ret = -1;3760void*map = NULL;3761unsigned long mapsize;3762 git_zstream stream;3763char hdr[32];37643765*contents = NULL;37663767 map =map_sha1_file_1(path, NULL, &mapsize);3768if(!map) {3769error_errno("unable to mmap%s", path);3770goto out;3771}37723773if(unpack_sha1_header(&stream, map, mapsize, hdr,sizeof(hdr)) <0) {3774error("unable to unpack header of%s", path);3775goto out;3776}37773778*type =parse_sha1_header(hdr, size);3779if(*type <0) {3780error("unable to parse header of%s", path);3781git_inflate_end(&stream);3782goto out;3783}37843785if(*type == OBJ_BLOB) {3786if(check_stream_sha1(&stream, hdr, *size, path, expected_sha1) <0)3787goto out;3788}else{3789*contents =unpack_sha1_rest(&stream, hdr, *size, expected_sha1);3790if(!*contents) {3791error("unable to unpack contents of%s", path);3792git_inflate_end(&stream);3793goto out;3794}3795if(check_sha1_signature(expected_sha1, *contents,3796*size,typename(*type))) {3797error("sha1 mismatch for%s(expected%s)", path,3798sha1_to_hex(expected_sha1));3799free(*contents);3800goto out;3801}3802}38033804 ret =0;/* everything checks out */38053806out:3807if(map)3808munmap(map, mapsize);3809return ret;3810}