1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23#include"apply.h" 24 25static const char*const apply_usage[] = { 26N_("git apply [<options>] [<patch>...]"), 27 NULL 28}; 29 30static voidparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return; 56} 57die(_("unrecognized whitespace option '%s'"), option); 58} 59 60static voidparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return; 72} 73die(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76static voidset_default_whitespace_mode(struct apply_state *state) 77{ 78if(!state->whitespace_option && !apply_default_whitespace) 79 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 80} 81 82/* 83 * This represents one "hunk" from a patch, starting with 84 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 85 * patch text is pointed at by patch, and its byte length 86 * is stored in size. leading and trailing are the number 87 * of context lines. 88 */ 89struct fragment { 90unsigned long leading, trailing; 91unsigned long oldpos, oldlines; 92unsigned long newpos, newlines; 93/* 94 * 'patch' is usually borrowed from buf in apply_patch(), 95 * but some codepaths store an allocated buffer. 96 */ 97const char*patch; 98unsigned free_patch:1, 99 rejected:1; 100int size; 101int linenr; 102struct fragment *next; 103}; 104 105/* 106 * When dealing with a binary patch, we reuse "leading" field 107 * to store the type of the binary hunk, either deflated "delta" 108 * or deflated "literal". 109 */ 110#define binary_patch_method leading 111#define BINARY_DELTA_DEFLATED 1 112#define BINARY_LITERAL_DEFLATED 2 113 114/* 115 * This represents a "patch" to a file, both metainfo changes 116 * such as creation/deletion, filemode and content changes represented 117 * as a series of fragments. 118 */ 119struct patch { 120char*new_name, *old_name, *def_name; 121unsigned int old_mode, new_mode; 122int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 123int rejected; 124unsigned ws_rule; 125int lines_added, lines_deleted; 126int score; 127unsigned int is_toplevel_relative:1; 128unsigned int inaccurate_eof:1; 129unsigned int is_binary:1; 130unsigned int is_copy:1; 131unsigned int is_rename:1; 132unsigned int recount:1; 133unsigned int conflicted_threeway:1; 134unsigned int direct_to_threeway:1; 135struct fragment *fragments; 136char*result; 137size_t resultsize; 138char old_sha1_prefix[41]; 139char new_sha1_prefix[41]; 140struct patch *next; 141 142/* three-way fallback result */ 143struct object_id threeway_stage[3]; 144}; 145 146static voidfree_fragment_list(struct fragment *list) 147{ 148while(list) { 149struct fragment *next = list->next; 150if(list->free_patch) 151free((char*)list->patch); 152free(list); 153 list = next; 154} 155} 156 157static voidfree_patch(struct patch *patch) 158{ 159free_fragment_list(patch->fragments); 160free(patch->def_name); 161free(patch->old_name); 162free(patch->new_name); 163free(patch->result); 164free(patch); 165} 166 167static voidfree_patch_list(struct patch *list) 168{ 169while(list) { 170struct patch *next = list->next; 171free_patch(list); 172 list = next; 173} 174} 175 176/* 177 * A line in a file, len-bytes long (includes the terminating LF, 178 * except for an incomplete line at the end if the file ends with 179 * one), and its contents hashes to 'hash'. 180 */ 181struct line { 182size_t len; 183unsigned hash :24; 184unsigned flag :8; 185#define LINE_COMMON 1 186#define LINE_PATCHED 2 187}; 188 189/* 190 * This represents a "file", which is an array of "lines". 191 */ 192struct image { 193char*buf; 194size_t len; 195size_t nr; 196size_t alloc; 197struct line *line_allocated; 198struct line *line; 199}; 200 201static uint32_thash_line(const char*cp,size_t len) 202{ 203size_t i; 204uint32_t h; 205for(i =0, h =0; i < len; i++) { 206if(!isspace(cp[i])) { 207 h = h *3+ (cp[i] &0xff); 208} 209} 210return h; 211} 212 213/* 214 * Compare lines s1 of length n1 and s2 of length n2, ignoring 215 * whitespace difference. Returns 1 if they match, 0 otherwise 216 */ 217static intfuzzy_matchlines(const char*s1,size_t n1, 218const char*s2,size_t n2) 219{ 220const char*last1 = s1 + n1 -1; 221const char*last2 = s2 + n2 -1; 222int result =0; 223 224/* ignore line endings */ 225while((*last1 =='\r') || (*last1 =='\n')) 226 last1--; 227while((*last2 =='\r') || (*last2 =='\n')) 228 last2--; 229 230/* skip leading whitespaces, if both begin with whitespace */ 231if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 232while(isspace(*s1) && (s1 <= last1)) 233 s1++; 234while(isspace(*s2) && (s2 <= last2)) 235 s2++; 236} 237/* early return if both lines are empty */ 238if((s1 > last1) && (s2 > last2)) 239return1; 240while(!result) { 241 result = *s1++ - *s2++; 242/* 243 * Skip whitespace inside. We check for whitespace on 244 * both buffers because we don't want "a b" to match 245 * "ab" 246 */ 247if(isspace(*s1) &&isspace(*s2)) { 248while(isspace(*s1) && s1 <= last1) 249 s1++; 250while(isspace(*s2) && s2 <= last2) 251 s2++; 252} 253/* 254 * If we reached the end on one side only, 255 * lines don't match 256 */ 257if( 258((s2 > last2) && (s1 <= last1)) || 259((s1 > last1) && (s2 <= last2))) 260return0; 261if((s1 > last1) && (s2 > last2)) 262break; 263} 264 265return!result; 266} 267 268static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 269{ 270ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 271 img->line_allocated[img->nr].len = len; 272 img->line_allocated[img->nr].hash =hash_line(bol, len); 273 img->line_allocated[img->nr].flag = flag; 274 img->nr++; 275} 276 277/* 278 * "buf" has the file contents to be patched (read from various sources). 279 * attach it to "image" and add line-based index to it. 280 * "image" now owns the "buf". 281 */ 282static voidprepare_image(struct image *image,char*buf,size_t len, 283int prepare_linetable) 284{ 285const char*cp, *ep; 286 287memset(image,0,sizeof(*image)); 288 image->buf = buf; 289 image->len = len; 290 291if(!prepare_linetable) 292return; 293 294 ep = image->buf + image->len; 295 cp = image->buf; 296while(cp < ep) { 297const char*next; 298for(next = cp; next < ep && *next !='\n'; next++) 299; 300if(next < ep) 301 next++; 302add_line_info(image, cp, next - cp,0); 303 cp = next; 304} 305 image->line = image->line_allocated; 306} 307 308static voidclear_image(struct image *image) 309{ 310free(image->buf); 311free(image->line_allocated); 312memset(image,0,sizeof(*image)); 313} 314 315/* fmt must contain _one_ %s and no other substitution */ 316static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 317{ 318struct strbuf sb = STRBUF_INIT; 319 320if(patch->old_name && patch->new_name && 321strcmp(patch->old_name, patch->new_name)) { 322quote_c_style(patch->old_name, &sb, NULL,0); 323strbuf_addstr(&sb," => "); 324quote_c_style(patch->new_name, &sb, NULL,0); 325}else{ 326const char*n = patch->new_name; 327if(!n) 328 n = patch->old_name; 329quote_c_style(n, &sb, NULL,0); 330} 331fprintf(output, fmt, sb.buf); 332fputc('\n', output); 333strbuf_release(&sb); 334} 335 336#define SLOP (16) 337 338static voidread_patch_file(struct strbuf *sb,int fd) 339{ 340if(strbuf_read(sb, fd,0) <0) 341die_errno("git apply: failed to read"); 342 343/* 344 * Make sure that we have some slop in the buffer 345 * so that we can do speculative "memcmp" etc, and 346 * see to it that it is NUL-filled. 347 */ 348strbuf_grow(sb, SLOP); 349memset(sb->buf + sb->len,0, SLOP); 350} 351 352static unsigned longlinelen(const char*buffer,unsigned long size) 353{ 354unsigned long len =0; 355while(size--) { 356 len++; 357if(*buffer++ =='\n') 358break; 359} 360return len; 361} 362 363static intis_dev_null(const char*str) 364{ 365returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 366} 367 368#define TERM_SPACE 1 369#define TERM_TAB 2 370 371static intname_terminate(int c,int terminate) 372{ 373if(c ==' '&& !(terminate & TERM_SPACE)) 374return0; 375if(c =='\t'&& !(terminate & TERM_TAB)) 376return0; 377 378return1; 379} 380 381/* remove double slashes to make --index work with such filenames */ 382static char*squash_slash(char*name) 383{ 384int i =0, j =0; 385 386if(!name) 387return NULL; 388 389while(name[i]) { 390if((name[j++] = name[i++]) =='/') 391while(name[i] =='/') 392 i++; 393} 394 name[j] ='\0'; 395return name; 396} 397 398static char*find_name_gnu(struct apply_state *state, 399const char*line, 400const char*def, 401int p_value) 402{ 403struct strbuf name = STRBUF_INIT; 404char*cp; 405 406/* 407 * Proposed "new-style" GNU patch/diff format; see 408 * http://marc.info/?l=git&m=112927316408690&w=2 409 */ 410if(unquote_c_style(&name, line, NULL)) { 411strbuf_release(&name); 412return NULL; 413} 414 415for(cp = name.buf; p_value; p_value--) { 416 cp =strchr(cp,'/'); 417if(!cp) { 418strbuf_release(&name); 419return NULL; 420} 421 cp++; 422} 423 424strbuf_remove(&name,0, cp - name.buf); 425if(state->root.len) 426strbuf_insert(&name,0, state->root.buf, state->root.len); 427returnsquash_slash(strbuf_detach(&name, NULL)); 428} 429 430static size_tsane_tz_len(const char*line,size_t len) 431{ 432const char*tz, *p; 433 434if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 435return0; 436 tz = line + len -strlen(" +0500"); 437 438if(tz[1] !='+'&& tz[1] !='-') 439return0; 440 441for(p = tz +2; p != line + len; p++) 442if(!isdigit(*p)) 443return0; 444 445return line + len - tz; 446} 447 448static size_ttz_with_colon_len(const char*line,size_t len) 449{ 450const char*tz, *p; 451 452if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 453return0; 454 tz = line + len -strlen(" +08:00"); 455 456if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 457return0; 458 p = tz +2; 459if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 460!isdigit(*p++) || !isdigit(*p++)) 461return0; 462 463return line + len - tz; 464} 465 466static size_tdate_len(const char*line,size_t len) 467{ 468const char*date, *p; 469 470if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 471return0; 472 p = date = line + len -strlen("72-02-05"); 473 474if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 475!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 476!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 477return0; 478 479if(date - line >=strlen("19") && 480isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 481 date -=strlen("19"); 482 483return line + len - date; 484} 485 486static size_tshort_time_len(const char*line,size_t len) 487{ 488const char*time, *p; 489 490if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 491return0; 492 p = time = line + len -strlen(" 07:01:32"); 493 494/* Permit 1-digit hours? */ 495if(*p++ !=' '|| 496!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 497!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 498!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 499return0; 500 501return line + len - time; 502} 503 504static size_tfractional_time_len(const char*line,size_t len) 505{ 506const char*p; 507size_t n; 508 509/* Expected format: 19:41:17.620000023 */ 510if(!len || !isdigit(line[len -1])) 511return0; 512 p = line + len -1; 513 514/* Fractional seconds. */ 515while(p > line &&isdigit(*p)) 516 p--; 517if(*p !='.') 518return0; 519 520/* Hours, minutes, and whole seconds. */ 521 n =short_time_len(line, p - line); 522if(!n) 523return0; 524 525return line + len - p + n; 526} 527 528static size_ttrailing_spaces_len(const char*line,size_t len) 529{ 530const char*p; 531 532/* Expected format: ' ' x (1 or more) */ 533if(!len || line[len -1] !=' ') 534return0; 535 536 p = line + len; 537while(p != line) { 538 p--; 539if(*p !=' ') 540return line + len - (p +1); 541} 542 543/* All spaces! */ 544return len; 545} 546 547static size_tdiff_timestamp_len(const char*line,size_t len) 548{ 549const char*end = line + len; 550size_t n; 551 552/* 553 * Posix: 2010-07-05 19:41:17 554 * GNU: 2010-07-05 19:41:17.620000023 -0500 555 */ 556 557if(!isdigit(end[-1])) 558return0; 559 560 n =sane_tz_len(line, end - line); 561if(!n) 562 n =tz_with_colon_len(line, end - line); 563 end -= n; 564 565 n =short_time_len(line, end - line); 566if(!n) 567 n =fractional_time_len(line, end - line); 568 end -= n; 569 570 n =date_len(line, end - line); 571if(!n)/* No date. Too bad. */ 572return0; 573 end -= n; 574 575if(end == line)/* No space before date. */ 576return0; 577if(end[-1] =='\t') {/* Success! */ 578 end--; 579return line + len - end; 580} 581if(end[-1] !=' ')/* No space before date. */ 582return0; 583 584/* Whitespace damage. */ 585 end -=trailing_spaces_len(line, end - line); 586return line + len - end; 587} 588 589static char*find_name_common(struct apply_state *state, 590const char*line, 591const char*def, 592int p_value, 593const char*end, 594int terminate) 595{ 596int len; 597const char*start = NULL; 598 599if(p_value ==0) 600 start = line; 601while(line != end) { 602char c = *line; 603 604if(!end &&isspace(c)) { 605if(c =='\n') 606break; 607if(name_terminate(c, terminate)) 608break; 609} 610 line++; 611if(c =='/'&& !--p_value) 612 start = line; 613} 614if(!start) 615returnsquash_slash(xstrdup_or_null(def)); 616 len = line - start; 617if(!len) 618returnsquash_slash(xstrdup_or_null(def)); 619 620/* 621 * Generally we prefer the shorter name, especially 622 * if the other one is just a variation of that with 623 * something else tacked on to the end (ie "file.orig" 624 * or "file~"). 625 */ 626if(def) { 627int deflen =strlen(def); 628if(deflen < len && !strncmp(start, def, deflen)) 629returnsquash_slash(xstrdup(def)); 630} 631 632if(state->root.len) { 633char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 634returnsquash_slash(ret); 635} 636 637returnsquash_slash(xmemdupz(start, len)); 638} 639 640static char*find_name(struct apply_state *state, 641const char*line, 642char*def, 643int p_value, 644int terminate) 645{ 646if(*line =='"') { 647char*name =find_name_gnu(state, line, def, p_value); 648if(name) 649return name; 650} 651 652returnfind_name_common(state, line, def, p_value, NULL, terminate); 653} 654 655static char*find_name_traditional(struct apply_state *state, 656const char*line, 657char*def, 658int p_value) 659{ 660size_t len; 661size_t date_len; 662 663if(*line =='"') { 664char*name =find_name_gnu(state, line, def, p_value); 665if(name) 666return name; 667} 668 669 len =strchrnul(line,'\n') - line; 670 date_len =diff_timestamp_len(line, len); 671if(!date_len) 672returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 673 len -= date_len; 674 675returnfind_name_common(state, line, def, p_value, line + len,0); 676} 677 678static intcount_slashes(const char*cp) 679{ 680int cnt =0; 681char ch; 682 683while((ch = *cp++)) 684if(ch =='/') 685 cnt++; 686return cnt; 687} 688 689/* 690 * Given the string after "--- " or "+++ ", guess the appropriate 691 * p_value for the given patch. 692 */ 693static intguess_p_value(struct apply_state *state,const char*nameline) 694{ 695char*name, *cp; 696int val = -1; 697 698if(is_dev_null(nameline)) 699return-1; 700 name =find_name_traditional(state, nameline, NULL,0); 701if(!name) 702return-1; 703 cp =strchr(name,'/'); 704if(!cp) 705 val =0; 706else if(state->prefix) { 707/* 708 * Does it begin with "a/$our-prefix" and such? Then this is 709 * very likely to apply to our directory. 710 */ 711if(!strncmp(name, state->prefix, state->prefix_length)) 712 val =count_slashes(state->prefix); 713else{ 714 cp++; 715if(!strncmp(cp, state->prefix, state->prefix_length)) 716 val =count_slashes(state->prefix) +1; 717} 718} 719free(name); 720return val; 721} 722 723/* 724 * Does the ---/+++ line have the POSIX timestamp after the last HT? 725 * GNU diff puts epoch there to signal a creation/deletion event. Is 726 * this such a timestamp? 727 */ 728static inthas_epoch_timestamp(const char*nameline) 729{ 730/* 731 * We are only interested in epoch timestamp; any non-zero 732 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 733 * For the same reason, the date must be either 1969-12-31 or 734 * 1970-01-01, and the seconds part must be "00". 735 */ 736const char stamp_regexp[] = 737"^(1969-12-31|1970-01-01)" 738" " 739"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 740" " 741"([-+][0-2][0-9]:?[0-5][0-9])\n"; 742const char*timestamp = NULL, *cp, *colon; 743static regex_t *stamp; 744 regmatch_t m[10]; 745int zoneoffset; 746int hourminute; 747int status; 748 749for(cp = nameline; *cp !='\n'; cp++) { 750if(*cp =='\t') 751 timestamp = cp +1; 752} 753if(!timestamp) 754return0; 755if(!stamp) { 756 stamp =xmalloc(sizeof(*stamp)); 757if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 758warning(_("Cannot prepare timestamp regexp%s"), 759 stamp_regexp); 760return0; 761} 762} 763 764 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 765if(status) { 766if(status != REG_NOMATCH) 767warning(_("regexec returned%dfor input:%s"), 768 status, timestamp); 769return0; 770} 771 772 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 773if(*colon ==':') 774 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 775else 776 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 777if(timestamp[m[3].rm_so] =='-') 778 zoneoffset = -zoneoffset; 779 780/* 781 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 782 * (west of GMT) or 1970-01-01 (east of GMT) 783 */ 784if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 785(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 786return0; 787 788 hourminute = (strtol(timestamp +11, NULL,10) *60+ 789strtol(timestamp +14, NULL,10) - 790 zoneoffset); 791 792return((zoneoffset <0&& hourminute ==1440) || 793(0<= zoneoffset && !hourminute)); 794} 795 796/* 797 * Get the name etc info from the ---/+++ lines of a traditional patch header 798 * 799 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 800 * files, we can happily check the index for a match, but for creating a 801 * new file we should try to match whatever "patch" does. I have no idea. 802 */ 803static voidparse_traditional_patch(struct apply_state *state, 804const char*first, 805const char*second, 806struct patch *patch) 807{ 808char*name; 809 810 first +=4;/* skip "--- " */ 811 second +=4;/* skip "+++ " */ 812if(!state->p_value_known) { 813int p, q; 814 p =guess_p_value(state, first); 815 q =guess_p_value(state, second); 816if(p <0) p = q; 817if(0<= p && p == q) { 818 state->p_value = p; 819 state->p_value_known =1; 820} 821} 822if(is_dev_null(first)) { 823 patch->is_new =1; 824 patch->is_delete =0; 825 name =find_name_traditional(state, second, NULL, state->p_value); 826 patch->new_name = name; 827}else if(is_dev_null(second)) { 828 patch->is_new =0; 829 patch->is_delete =1; 830 name =find_name_traditional(state, first, NULL, state->p_value); 831 patch->old_name = name; 832}else{ 833char*first_name; 834 first_name =find_name_traditional(state, first, NULL, state->p_value); 835 name =find_name_traditional(state, second, first_name, state->p_value); 836free(first_name); 837if(has_epoch_timestamp(first)) { 838 patch->is_new =1; 839 patch->is_delete =0; 840 patch->new_name = name; 841}else if(has_epoch_timestamp(second)) { 842 patch->is_new =0; 843 patch->is_delete =1; 844 patch->old_name = name; 845}else{ 846 patch->old_name = name; 847 patch->new_name =xstrdup_or_null(name); 848} 849} 850if(!name) 851die(_("unable to find filename in patch at line%d"), state->linenr); 852} 853 854static intgitdiff_hdrend(struct apply_state *state, 855const char*line, 856struct patch *patch) 857{ 858return-1; 859} 860 861/* 862 * We're anal about diff header consistency, to make 863 * sure that we don't end up having strange ambiguous 864 * patches floating around. 865 * 866 * As a result, gitdiff_{old|new}name() will check 867 * their names against any previous information, just 868 * to make sure.. 869 */ 870#define DIFF_OLD_NAME 0 871#define DIFF_NEW_NAME 1 872 873static voidgitdiff_verify_name(struct apply_state *state, 874const char*line, 875int isnull, 876char**name, 877int side) 878{ 879if(!*name && !isnull) { 880*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 881return; 882} 883 884if(*name) { 885int len =strlen(*name); 886char*another; 887if(isnull) 888die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 889*name, state->linenr); 890 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 891if(!another ||memcmp(another, *name, len +1)) 892die((side == DIFF_NEW_NAME) ? 893_("git apply: bad git-diff - inconsistent new filename on line%d") : 894_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 895free(another); 896}else{ 897/* expect "/dev/null" */ 898if(memcmp("/dev/null", line,9) || line[9] !='\n') 899die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 900} 901} 902 903static intgitdiff_oldname(struct apply_state *state, 904const char*line, 905struct patch *patch) 906{ 907gitdiff_verify_name(state, line, 908 patch->is_new, &patch->old_name, 909 DIFF_OLD_NAME); 910return0; 911} 912 913static intgitdiff_newname(struct apply_state *state, 914const char*line, 915struct patch *patch) 916{ 917gitdiff_verify_name(state, line, 918 patch->is_delete, &patch->new_name, 919 DIFF_NEW_NAME); 920return0; 921} 922 923static intgitdiff_oldmode(struct apply_state *state, 924const char*line, 925struct patch *patch) 926{ 927 patch->old_mode =strtoul(line, NULL,8); 928return0; 929} 930 931static intgitdiff_newmode(struct apply_state *state, 932const char*line, 933struct patch *patch) 934{ 935 patch->new_mode =strtoul(line, NULL,8); 936return0; 937} 938 939static intgitdiff_delete(struct apply_state *state, 940const char*line, 941struct patch *patch) 942{ 943 patch->is_delete =1; 944free(patch->old_name); 945 patch->old_name =xstrdup_or_null(patch->def_name); 946returngitdiff_oldmode(state, line, patch); 947} 948 949static intgitdiff_newfile(struct apply_state *state, 950const char*line, 951struct patch *patch) 952{ 953 patch->is_new =1; 954free(patch->new_name); 955 patch->new_name =xstrdup_or_null(patch->def_name); 956returngitdiff_newmode(state, line, patch); 957} 958 959static intgitdiff_copysrc(struct apply_state *state, 960const char*line, 961struct patch *patch) 962{ 963 patch->is_copy =1; 964free(patch->old_name); 965 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 966return0; 967} 968 969static intgitdiff_copydst(struct apply_state *state, 970const char*line, 971struct patch *patch) 972{ 973 patch->is_copy =1; 974free(patch->new_name); 975 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 976return0; 977} 978 979static intgitdiff_renamesrc(struct apply_state *state, 980const char*line, 981struct patch *patch) 982{ 983 patch->is_rename =1; 984free(patch->old_name); 985 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 986return0; 987} 988 989static intgitdiff_renamedst(struct apply_state *state, 990const char*line, 991struct patch *patch) 992{ 993 patch->is_rename =1; 994free(patch->new_name); 995 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 996return0; 997} 998 999static intgitdiff_similarity(struct apply_state *state,1000const char*line,1001struct patch *patch)1002{1003unsigned long val =strtoul(line, NULL,10);1004if(val <=100)1005 patch->score = val;1006return0;1007}10081009static intgitdiff_dissimilarity(struct apply_state *state,1010const char*line,1011struct patch *patch)1012{1013unsigned long val =strtoul(line, NULL,10);1014if(val <=100)1015 patch->score = val;1016return0;1017}10181019static intgitdiff_index(struct apply_state *state,1020const char*line,1021struct patch *patch)1022{1023/*1024 * index line is N hexadecimal, "..", N hexadecimal,1025 * and optional space with octal mode.1026 */1027const char*ptr, *eol;1028int len;10291030 ptr =strchr(line,'.');1031if(!ptr || ptr[1] !='.'||40< ptr - line)1032return0;1033 len = ptr - line;1034memcpy(patch->old_sha1_prefix, line, len);1035 patch->old_sha1_prefix[len] =0;10361037 line = ptr +2;1038 ptr =strchr(line,' ');1039 eol =strchrnul(line,'\n');10401041if(!ptr || eol < ptr)1042 ptr = eol;1043 len = ptr - line;10441045if(40< len)1046return0;1047memcpy(patch->new_sha1_prefix, line, len);1048 patch->new_sha1_prefix[len] =0;1049if(*ptr ==' ')1050 patch->old_mode =strtoul(ptr+1, NULL,8);1051return0;1052}10531054/*1055 * This is normal for a diff that doesn't change anything: we'll fall through1056 * into the next diff. Tell the parser to break out.1057 */1058static intgitdiff_unrecognized(struct apply_state *state,1059const char*line,1060struct patch *patch)1061{1062return-1;1063}10641065/*1066 * Skip p_value leading components from "line"; as we do not accept1067 * absolute paths, return NULL in that case.1068 */1069static const char*skip_tree_prefix(struct apply_state *state,1070const char*line,1071int llen)1072{1073int nslash;1074int i;10751076if(!state->p_value)1077return(llen && line[0] =='/') ? NULL : line;10781079 nslash = state->p_value;1080for(i =0; i < llen; i++) {1081int ch = line[i];1082if(ch =='/'&& --nslash <=0)1083return(i ==0) ? NULL : &line[i +1];1084}1085return NULL;1086}10871088/*1089 * This is to extract the same name that appears on "diff --git"1090 * line. We do not find and return anything if it is a rename1091 * patch, and it is OK because we will find the name elsewhere.1092 * We need to reliably find name only when it is mode-change only,1093 * creation or deletion of an empty file. In any of these cases,1094 * both sides are the same name under a/ and b/ respectively.1095 */1096static char*git_header_name(struct apply_state *state,1097const char*line,1098int llen)1099{1100const char*name;1101const char*second = NULL;1102size_t len, line_len;11031104 line +=strlen("diff --git ");1105 llen -=strlen("diff --git ");11061107if(*line =='"') {1108const char*cp;1109struct strbuf first = STRBUF_INIT;1110struct strbuf sp = STRBUF_INIT;11111112if(unquote_c_style(&first, line, &second))1113goto free_and_fail1;11141115/* strip the a/b prefix including trailing slash */1116 cp =skip_tree_prefix(state, first.buf, first.len);1117if(!cp)1118goto free_and_fail1;1119strbuf_remove(&first,0, cp - first.buf);11201121/*1122 * second points at one past closing dq of name.1123 * find the second name.1124 */1125while((second < line + llen) &&isspace(*second))1126 second++;11271128if(line + llen <= second)1129goto free_and_fail1;1130if(*second =='"') {1131if(unquote_c_style(&sp, second, NULL))1132goto free_and_fail1;1133 cp =skip_tree_prefix(state, sp.buf, sp.len);1134if(!cp)1135goto free_and_fail1;1136/* They must match, otherwise ignore */1137if(strcmp(cp, first.buf))1138goto free_and_fail1;1139strbuf_release(&sp);1140returnstrbuf_detach(&first, NULL);1141}11421143/* unquoted second */1144 cp =skip_tree_prefix(state, second, line + llen - second);1145if(!cp)1146goto free_and_fail1;1147if(line + llen - cp != first.len ||1148memcmp(first.buf, cp, first.len))1149goto free_and_fail1;1150returnstrbuf_detach(&first, NULL);11511152 free_and_fail1:1153strbuf_release(&first);1154strbuf_release(&sp);1155return NULL;1156}11571158/* unquoted first name */1159 name =skip_tree_prefix(state, line, llen);1160if(!name)1161return NULL;11621163/*1164 * since the first name is unquoted, a dq if exists must be1165 * the beginning of the second name.1166 */1167for(second = name; second < line + llen; second++) {1168if(*second =='"') {1169struct strbuf sp = STRBUF_INIT;1170const char*np;11711172if(unquote_c_style(&sp, second, NULL))1173goto free_and_fail2;11741175 np =skip_tree_prefix(state, sp.buf, sp.len);1176if(!np)1177goto free_and_fail2;11781179 len = sp.buf + sp.len - np;1180if(len < second - name &&1181!strncmp(np, name, len) &&1182isspace(name[len])) {1183/* Good */1184strbuf_remove(&sp,0, np - sp.buf);1185returnstrbuf_detach(&sp, NULL);1186}11871188 free_and_fail2:1189strbuf_release(&sp);1190return NULL;1191}1192}11931194/*1195 * Accept a name only if it shows up twice, exactly the same1196 * form.1197 */1198 second =strchr(name,'\n');1199if(!second)1200return NULL;1201 line_len = second - name;1202for(len =0; ; len++) {1203switch(name[len]) {1204default:1205continue;1206case'\n':1207return NULL;1208case'\t':case' ':1209/*1210 * Is this the separator between the preimage1211 * and the postimage pathname? Again, we are1212 * only interested in the case where there is1213 * no rename, as this is only to set def_name1214 * and a rename patch has the names elsewhere1215 * in an unambiguous form.1216 */1217if(!name[len +1])1218return NULL;/* no postimage name */1219 second =skip_tree_prefix(state, name + len +1,1220 line_len - (len +1));1221if(!second)1222return NULL;1223/*1224 * Does len bytes starting at "name" and "second"1225 * (that are separated by one HT or SP we just1226 * found) exactly match?1227 */1228if(second[len] =='\n'&& !strncmp(name, second, len))1229returnxmemdupz(name, len);1230}1231}1232}12331234/* Verify that we recognize the lines following a git header */1235static intparse_git_header(struct apply_state *state,1236const char*line,1237int len,1238unsigned int size,1239struct patch *patch)1240{1241unsigned long offset;12421243/* A git diff has explicit new/delete information, so we don't guess */1244 patch->is_new =0;1245 patch->is_delete =0;12461247/*1248 * Some things may not have the old name in the1249 * rest of the headers anywhere (pure mode changes,1250 * or removing or adding empty files), so we get1251 * the default name from the header.1252 */1253 patch->def_name =git_header_name(state, line, len);1254if(patch->def_name && state->root.len) {1255char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1256free(patch->def_name);1257 patch->def_name = s;1258}12591260 line += len;1261 size -= len;1262 state->linenr++;1263for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1264static const struct opentry {1265const char*str;1266int(*fn)(struct apply_state *,const char*,struct patch *);1267} optable[] = {1268{"@@ -", gitdiff_hdrend },1269{"--- ", gitdiff_oldname },1270{"+++ ", gitdiff_newname },1271{"old mode ", gitdiff_oldmode },1272{"new mode ", gitdiff_newmode },1273{"deleted file mode ", gitdiff_delete },1274{"new file mode ", gitdiff_newfile },1275{"copy from ", gitdiff_copysrc },1276{"copy to ", gitdiff_copydst },1277{"rename old ", gitdiff_renamesrc },1278{"rename new ", gitdiff_renamedst },1279{"rename from ", gitdiff_renamesrc },1280{"rename to ", gitdiff_renamedst },1281{"similarity index ", gitdiff_similarity },1282{"dissimilarity index ", gitdiff_dissimilarity },1283{"index ", gitdiff_index },1284{"", gitdiff_unrecognized },1285};1286int i;12871288 len =linelen(line, size);1289if(!len || line[len-1] !='\n')1290break;1291for(i =0; i <ARRAY_SIZE(optable); i++) {1292const struct opentry *p = optable + i;1293int oplen =strlen(p->str);1294if(len < oplen ||memcmp(p->str, line, oplen))1295continue;1296if(p->fn(state, line + oplen, patch) <0)1297return offset;1298break;1299}1300}13011302return offset;1303}13041305static intparse_num(const char*line,unsigned long*p)1306{1307char*ptr;13081309if(!isdigit(*line))1310return0;1311*p =strtoul(line, &ptr,10);1312return ptr - line;1313}13141315static intparse_range(const char*line,int len,int offset,const char*expect,1316unsigned long*p1,unsigned long*p2)1317{1318int digits, ex;13191320if(offset <0|| offset >= len)1321return-1;1322 line += offset;1323 len -= offset;13241325 digits =parse_num(line, p1);1326if(!digits)1327return-1;13281329 offset += digits;1330 line += digits;1331 len -= digits;13321333*p2 =1;1334if(*line ==',') {1335 digits =parse_num(line+1, p2);1336if(!digits)1337return-1;13381339 offset += digits+1;1340 line += digits+1;1341 len -= digits+1;1342}13431344 ex =strlen(expect);1345if(ex > len)1346return-1;1347if(memcmp(line, expect, ex))1348return-1;13491350return offset + ex;1351}13521353static voidrecount_diff(const char*line,int size,struct fragment *fragment)1354{1355int oldlines =0, newlines =0, ret =0;13561357if(size <1) {1358warning("recount: ignore empty hunk");1359return;1360}13611362for(;;) {1363int len =linelen(line, size);1364 size -= len;1365 line += len;13661367if(size <1)1368break;13691370switch(*line) {1371case' ':case'\n':1372 newlines++;1373/* fall through */1374case'-':1375 oldlines++;1376continue;1377case'+':1378 newlines++;1379continue;1380case'\\':1381continue;1382case'@':1383 ret = size <3|| !starts_with(line,"@@ ");1384break;1385case'd':1386 ret = size <5|| !starts_with(line,"diff ");1387break;1388default:1389 ret = -1;1390break;1391}1392if(ret) {1393warning(_("recount: unexpected line: %.*s"),1394(int)linelen(line, size), line);1395return;1396}1397break;1398}1399 fragment->oldlines = oldlines;1400 fragment->newlines = newlines;1401}14021403/*1404 * Parse a unified diff fragment header of the1405 * form "@@ -a,b +c,d @@"1406 */1407static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1408{1409int offset;14101411if(!len || line[len-1] !='\n')1412return-1;14131414/* Figure out the number of lines in a fragment */1415 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1416 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14171418return offset;1419}14201421static intfind_header(struct apply_state *state,1422const char*line,1423unsigned long size,1424int*hdrsize,1425struct patch *patch)1426{1427unsigned long offset, len;14281429 patch->is_toplevel_relative =0;1430 patch->is_rename = patch->is_copy =0;1431 patch->is_new = patch->is_delete = -1;1432 patch->old_mode = patch->new_mode =0;1433 patch->old_name = patch->new_name = NULL;1434for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1435unsigned long nextlen;14361437 len =linelen(line, size);1438if(!len)1439break;14401441/* Testing this early allows us to take a few shortcuts.. */1442if(len <6)1443continue;14441445/*1446 * Make sure we don't find any unconnected patch fragments.1447 * That's a sign that we didn't find a header, and that a1448 * patch has become corrupted/broken up.1449 */1450if(!memcmp("@@ -", line,4)) {1451struct fragment dummy;1452if(parse_fragment_header(line, len, &dummy) <0)1453continue;1454die(_("patch fragment without header at line%d: %.*s"),1455 state->linenr, (int)len-1, line);1456}14571458if(size < len +6)1459break;14601461/*1462 * Git patch? It might not have a real patch, just a rename1463 * or mode change, so we handle that specially1464 */1465if(!memcmp("diff --git ", line,11)) {1466int git_hdr_len =parse_git_header(state, line, len, size, patch);1467if(git_hdr_len <= len)1468continue;1469if(!patch->old_name && !patch->new_name) {1470if(!patch->def_name)1471die(Q_("git diff header lacks filename information when removing "1472"%dleading pathname component (line%d)",1473"git diff header lacks filename information when removing "1474"%dleading pathname components (line%d)",1475 state->p_value),1476 state->p_value, state->linenr);1477 patch->old_name =xstrdup(patch->def_name);1478 patch->new_name =xstrdup(patch->def_name);1479}1480if(!patch->is_delete && !patch->new_name)1481die("git diff header lacks filename information "1482"(line%d)", state->linenr);1483 patch->is_toplevel_relative =1;1484*hdrsize = git_hdr_len;1485return offset;1486}14871488/* --- followed by +++ ? */1489if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1490continue;14911492/*1493 * We only accept unified patches, so we want it to1494 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1495 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1496 */1497 nextlen =linelen(line + len, size - len);1498if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1499continue;15001501/* Ok, we'll consider it a patch */1502parse_traditional_patch(state, line, line+len, patch);1503*hdrsize = len + nextlen;1504 state->linenr +=2;1505return offset;1506}1507return-1;1508}15091510static voidrecord_ws_error(struct apply_state *state,1511unsigned result,1512const char*line,1513int len,1514int linenr)1515{1516char*err;15171518if(!result)1519return;15201521 state->whitespace_error++;1522if(state->squelch_whitespace_errors &&1523 state->squelch_whitespace_errors < state->whitespace_error)1524return;15251526 err =whitespace_error_string(result);1527fprintf(stderr,"%s:%d:%s.\n%.*s\n",1528 state->patch_input_file, linenr, err, len, line);1529free(err);1530}15311532static voidcheck_whitespace(struct apply_state *state,1533const char*line,1534int len,1535unsigned ws_rule)1536{1537unsigned result =ws_check(line +1, len -1, ws_rule);15381539record_ws_error(state, result, line +1, len -2, state->linenr);1540}15411542/*1543 * Parse a unified diff. Note that this really needs to parse each1544 * fragment separately, since the only way to know the difference1545 * between a "---" that is part of a patch, and a "---" that starts1546 * the next patch is to look at the line counts..1547 */1548static intparse_fragment(struct apply_state *state,1549const char*line,1550unsigned long size,1551struct patch *patch,1552struct fragment *fragment)1553{1554int added, deleted;1555int len =linelen(line, size), offset;1556unsigned long oldlines, newlines;1557unsigned long leading, trailing;15581559 offset =parse_fragment_header(line, len, fragment);1560if(offset <0)1561return-1;1562if(offset >0&& patch->recount)1563recount_diff(line + offset, size - offset, fragment);1564 oldlines = fragment->oldlines;1565 newlines = fragment->newlines;1566 leading =0;1567 trailing =0;15681569/* Parse the thing.. */1570 line += len;1571 size -= len;1572 state->linenr++;1573 added = deleted =0;1574for(offset = len;15750< size;1576 offset += len, size -= len, line += len, state->linenr++) {1577if(!oldlines && !newlines)1578break;1579 len =linelen(line, size);1580if(!len || line[len-1] !='\n')1581return-1;1582switch(*line) {1583default:1584return-1;1585case'\n':/* newer GNU diff, an empty context line */1586case' ':1587 oldlines--;1588 newlines--;1589if(!deleted && !added)1590 leading++;1591 trailing++;1592if(!state->apply_in_reverse &&1593 state->ws_error_action == correct_ws_error)1594check_whitespace(state, line, len, patch->ws_rule);1595break;1596case'-':1597if(state->apply_in_reverse &&1598 state->ws_error_action != nowarn_ws_error)1599check_whitespace(state, line, len, patch->ws_rule);1600 deleted++;1601 oldlines--;1602 trailing =0;1603break;1604case'+':1605if(!state->apply_in_reverse &&1606 state->ws_error_action != nowarn_ws_error)1607check_whitespace(state, line, len, patch->ws_rule);1608 added++;1609 newlines--;1610 trailing =0;1611break;16121613/*1614 * We allow "\ No newline at end of file". Depending1615 * on locale settings when the patch was produced we1616 * don't know what this line looks like. The only1617 * thing we do know is that it begins with "\ ".1618 * Checking for 12 is just for sanity check -- any1619 * l10n of "\ No newline..." is at least that long.1620 */1621case'\\':1622if(len <12||memcmp(line,"\\",2))1623return-1;1624break;1625}1626}1627if(oldlines || newlines)1628return-1;1629if(!deleted && !added)1630return-1;16311632 fragment->leading = leading;1633 fragment->trailing = trailing;16341635/*1636 * If a fragment ends with an incomplete line, we failed to include1637 * it in the above loop because we hit oldlines == newlines == 01638 * before seeing it.1639 */1640if(12< size && !memcmp(line,"\\",2))1641 offset +=linelen(line, size);16421643 patch->lines_added += added;1644 patch->lines_deleted += deleted;16451646if(0< patch->is_new && oldlines)1647returnerror(_("new file depends on old contents"));1648if(0< patch->is_delete && newlines)1649returnerror(_("deleted file still has contents"));1650return offset;1651}16521653/*1654 * We have seen "diff --git a/... b/..." header (or a traditional patch1655 * header). Read hunks that belong to this patch into fragments and hang1656 * them to the given patch structure.1657 *1658 * The (fragment->patch, fragment->size) pair points into the memory given1659 * by the caller, not a copy, when we return.1660 */1661static intparse_single_patch(struct apply_state *state,1662const char*line,1663unsigned long size,1664struct patch *patch)1665{1666unsigned long offset =0;1667unsigned long oldlines =0, newlines =0, context =0;1668struct fragment **fragp = &patch->fragments;16691670while(size >4&& !memcmp(line,"@@ -",4)) {1671struct fragment *fragment;1672int len;16731674 fragment =xcalloc(1,sizeof(*fragment));1675 fragment->linenr = state->linenr;1676 len =parse_fragment(state, line, size, patch, fragment);1677if(len <=0)1678die(_("corrupt patch at line%d"), state->linenr);1679 fragment->patch = line;1680 fragment->size = len;1681 oldlines += fragment->oldlines;1682 newlines += fragment->newlines;1683 context += fragment->leading + fragment->trailing;16841685*fragp = fragment;1686 fragp = &fragment->next;16871688 offset += len;1689 line += len;1690 size -= len;1691}16921693/*1694 * If something was removed (i.e. we have old-lines) it cannot1695 * be creation, and if something was added it cannot be1696 * deletion. However, the reverse is not true; --unified=01697 * patches that only add are not necessarily creation even1698 * though they do not have any old lines, and ones that only1699 * delete are not necessarily deletion.1700 *1701 * Unfortunately, a real creation/deletion patch do _not_ have1702 * any context line by definition, so we cannot safely tell it1703 * apart with --unified=0 insanity. At least if the patch has1704 * more than one hunk it is not creation or deletion.1705 */1706if(patch->is_new <0&&1707(oldlines || (patch->fragments && patch->fragments->next)))1708 patch->is_new =0;1709if(patch->is_delete <0&&1710(newlines || (patch->fragments && patch->fragments->next)))1711 patch->is_delete =0;17121713if(0< patch->is_new && oldlines)1714die(_("new file%sdepends on old contents"), patch->new_name);1715if(0< patch->is_delete && newlines)1716die(_("deleted file%sstill has contents"), patch->old_name);1717if(!patch->is_delete && !newlines && context)1718fprintf_ln(stderr,1719_("** warning: "1720"file%sbecomes empty but is not deleted"),1721 patch->new_name);17221723return offset;1724}17251726staticinlineintmetadata_changes(struct patch *patch)1727{1728return patch->is_rename >0||1729 patch->is_copy >0||1730 patch->is_new >0||1731 patch->is_delete ||1732(patch->old_mode && patch->new_mode &&1733 patch->old_mode != patch->new_mode);1734}17351736static char*inflate_it(const void*data,unsigned long size,1737unsigned long inflated_size)1738{1739 git_zstream stream;1740void*out;1741int st;17421743memset(&stream,0,sizeof(stream));17441745 stream.next_in = (unsigned char*)data;1746 stream.avail_in = size;1747 stream.next_out = out =xmalloc(inflated_size);1748 stream.avail_out = inflated_size;1749git_inflate_init(&stream);1750 st =git_inflate(&stream, Z_FINISH);1751git_inflate_end(&stream);1752if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1753free(out);1754return NULL;1755}1756return out;1757}17581759/*1760 * Read a binary hunk and return a new fragment; fragment->patch1761 * points at an allocated memory that the caller must free, so1762 * it is marked as "->free_patch = 1".1763 */1764static struct fragment *parse_binary_hunk(struct apply_state *state,1765char**buf_p,1766unsigned long*sz_p,1767int*status_p,1768int*used_p)1769{1770/*1771 * Expect a line that begins with binary patch method ("literal"1772 * or "delta"), followed by the length of data before deflating.1773 * a sequence of 'length-byte' followed by base-85 encoded data1774 * should follow, terminated by a newline.1775 *1776 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1777 * and we would limit the patch line to 66 characters,1778 * so one line can fit up to 13 groups that would decode1779 * to 52 bytes max. The length byte 'A'-'Z' corresponds1780 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1781 */1782int llen, used;1783unsigned long size = *sz_p;1784char*buffer = *buf_p;1785int patch_method;1786unsigned long origlen;1787char*data = NULL;1788int hunk_size =0;1789struct fragment *frag;17901791 llen =linelen(buffer, size);1792 used = llen;17931794*status_p =0;17951796if(starts_with(buffer,"delta ")) {1797 patch_method = BINARY_DELTA_DEFLATED;1798 origlen =strtoul(buffer +6, NULL,10);1799}1800else if(starts_with(buffer,"literal ")) {1801 patch_method = BINARY_LITERAL_DEFLATED;1802 origlen =strtoul(buffer +8, NULL,10);1803}1804else1805return NULL;18061807 state->linenr++;1808 buffer += llen;1809while(1) {1810int byte_length, max_byte_length, newsize;1811 llen =linelen(buffer, size);1812 used += llen;1813 state->linenr++;1814if(llen ==1) {1815/* consume the blank line */1816 buffer++;1817 size--;1818break;1819}1820/*1821 * Minimum line is "A00000\n" which is 7-byte long,1822 * and the line length must be multiple of 5 plus 2.1823 */1824if((llen <7) || (llen-2) %5)1825goto corrupt;1826 max_byte_length = (llen -2) /5*4;1827 byte_length = *buffer;1828if('A'<= byte_length && byte_length <='Z')1829 byte_length = byte_length -'A'+1;1830else if('a'<= byte_length && byte_length <='z')1831 byte_length = byte_length -'a'+27;1832else1833goto corrupt;1834/* if the input length was not multiple of 4, we would1835 * have filler at the end but the filler should never1836 * exceed 3 bytes1837 */1838if(max_byte_length < byte_length ||1839 byte_length <= max_byte_length -4)1840goto corrupt;1841 newsize = hunk_size + byte_length;1842 data =xrealloc(data, newsize);1843if(decode_85(data + hunk_size, buffer +1, byte_length))1844goto corrupt;1845 hunk_size = newsize;1846 buffer += llen;1847 size -= llen;1848}18491850 frag =xcalloc(1,sizeof(*frag));1851 frag->patch =inflate_it(data, hunk_size, origlen);1852 frag->free_patch =1;1853if(!frag->patch)1854goto corrupt;1855free(data);1856 frag->size = origlen;1857*buf_p = buffer;1858*sz_p = size;1859*used_p = used;1860 frag->binary_patch_method = patch_method;1861return frag;18621863 corrupt:1864free(data);1865*status_p = -1;1866error(_("corrupt binary patch at line%d: %.*s"),1867 state->linenr-1, llen-1, buffer);1868return NULL;1869}18701871/*1872 * Returns:1873 * -1 in case of error,1874 * the length of the parsed binary patch otherwise1875 */1876static intparse_binary(struct apply_state *state,1877char*buffer,1878unsigned long size,1879struct patch *patch)1880{1881/*1882 * We have read "GIT binary patch\n"; what follows is a line1883 * that says the patch method (currently, either "literal" or1884 * "delta") and the length of data before deflating; a1885 * sequence of 'length-byte' followed by base-85 encoded data1886 * follows.1887 *1888 * When a binary patch is reversible, there is another binary1889 * hunk in the same format, starting with patch method (either1890 * "literal" or "delta") with the length of data, and a sequence1891 * of length-byte + base-85 encoded data, terminated with another1892 * empty line. This data, when applied to the postimage, produces1893 * the preimage.1894 */1895struct fragment *forward;1896struct fragment *reverse;1897int status;1898int used, used_1;18991900 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1901if(!forward && !status)1902/* there has to be one hunk (forward hunk) */1903returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1904if(status)1905/* otherwise we already gave an error message */1906return status;19071908 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1909if(reverse)1910 used += used_1;1911else if(status) {1912/*1913 * Not having reverse hunk is not an error, but having1914 * a corrupt reverse hunk is.1915 */1916free((void*) forward->patch);1917free(forward);1918return status;1919}1920 forward->next = reverse;1921 patch->fragments = forward;1922 patch->is_binary =1;1923return used;1924}19251926static voidprefix_one(struct apply_state *state,char**name)1927{1928char*old_name = *name;1929if(!old_name)1930return;1931*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1932free(old_name);1933}19341935static voidprefix_patch(struct apply_state *state,struct patch *p)1936{1937if(!state->prefix || p->is_toplevel_relative)1938return;1939prefix_one(state, &p->new_name);1940prefix_one(state, &p->old_name);1941}19421943/*1944 * include/exclude1945 */19461947static voidadd_name_limit(struct apply_state *state,1948const char*name,1949int exclude)1950{1951struct string_list_item *it;19521953 it =string_list_append(&state->limit_by_name, name);1954 it->util = exclude ? NULL : (void*)1;1955}19561957static intuse_patch(struct apply_state *state,struct patch *p)1958{1959const char*pathname = p->new_name ? p->new_name : p->old_name;1960int i;19611962/* Paths outside are not touched regardless of "--include" */1963if(0< state->prefix_length) {1964int pathlen =strlen(pathname);1965if(pathlen <= state->prefix_length ||1966memcmp(state->prefix, pathname, state->prefix_length))1967return0;1968}19691970/* See if it matches any of exclude/include rule */1971for(i =0; i < state->limit_by_name.nr; i++) {1972struct string_list_item *it = &state->limit_by_name.items[i];1973if(!wildmatch(it->string, pathname,0, NULL))1974return(it->util != NULL);1975}19761977/*1978 * If we had any include, a path that does not match any rule is1979 * not used. Otherwise, we saw bunch of exclude rules (or none)1980 * and such a path is used.1981 */1982return!state->has_include;1983}198419851986/*1987 * Read the patch text in "buffer" that extends for "size" bytes; stop1988 * reading after seeing a single patch (i.e. changes to a single file).1989 * Create fragments (i.e. patch hunks) and hang them to the given patch.1990 * Return the number of bytes consumed, so that the caller can call us1991 * again for the next patch.1992 */1993static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1994{1995int hdrsize, patchsize;1996int offset =find_header(state, buffer, size, &hdrsize, patch);19971998if(offset <0)1999return offset;20002001prefix_patch(state, patch);20022003if(!use_patch(state, patch))2004 patch->ws_rule =0;2005else2006 patch->ws_rule =whitespace_rule(patch->new_name2007? patch->new_name2008: patch->old_name);20092010 patchsize =parse_single_patch(state,2011 buffer + offset + hdrsize,2012 size - offset - hdrsize,2013 patch);20142015if(!patchsize) {2016static const char git_binary[] ="GIT binary patch\n";2017int hd = hdrsize + offset;2018unsigned long llen =linelen(buffer + hd, size - hd);20192020if(llen ==sizeof(git_binary) -1&&2021!memcmp(git_binary, buffer + hd, llen)) {2022int used;2023 state->linenr++;2024 used =parse_binary(state, buffer + hd + llen,2025 size - hd - llen, patch);2026if(used <0)2027return-1;2028if(used)2029 patchsize = used + llen;2030else2031 patchsize =0;2032}2033else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2034static const char*binhdr[] = {2035"Binary files ",2036"Files ",2037 NULL,2038};2039int i;2040for(i =0; binhdr[i]; i++) {2041int len =strlen(binhdr[i]);2042if(len < size - hd &&2043!memcmp(binhdr[i], buffer + hd, len)) {2044 state->linenr++;2045 patch->is_binary =1;2046 patchsize = llen;2047break;2048}2049}2050}20512052/* Empty patch cannot be applied if it is a text patch2053 * without metadata change. A binary patch appears2054 * empty to us here.2055 */2056if((state->apply || state->check) &&2057(!patch->is_binary && !metadata_changes(patch)))2058die(_("patch with only garbage at line%d"), state->linenr);2059}20602061return offset + hdrsize + patchsize;2062}20632064#define swap(a,b) myswap((a),(b),sizeof(a))20652066#define myswap(a, b, size) do { \2067 unsigned char mytmp[size]; \2068 memcpy(mytmp, &a, size); \2069 memcpy(&a, &b, size); \2070 memcpy(&b, mytmp, size); \2071} while (0)20722073static voidreverse_patches(struct patch *p)2074{2075for(; p; p = p->next) {2076struct fragment *frag = p->fragments;20772078swap(p->new_name, p->old_name);2079swap(p->new_mode, p->old_mode);2080swap(p->is_new, p->is_delete);2081swap(p->lines_added, p->lines_deleted);2082swap(p->old_sha1_prefix, p->new_sha1_prefix);20832084for(; frag; frag = frag->next) {2085swap(frag->newpos, frag->oldpos);2086swap(frag->newlines, frag->oldlines);2087}2088}2089}20902091static const char pluses[] =2092"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2093static const char minuses[]=2094"----------------------------------------------------------------------";20952096static voidshow_stats(struct apply_state *state,struct patch *patch)2097{2098struct strbuf qname = STRBUF_INIT;2099char*cp = patch->new_name ? patch->new_name : patch->old_name;2100int max, add, del;21012102quote_c_style(cp, &qname, NULL,0);21032104/*2105 * "scale" the filename2106 */2107 max = state->max_len;2108if(max >50)2109 max =50;21102111if(qname.len > max) {2112 cp =strchr(qname.buf + qname.len +3- max,'/');2113if(!cp)2114 cp = qname.buf + qname.len +3- max;2115strbuf_splice(&qname,0, cp - qname.buf,"...",3);2116}21172118if(patch->is_binary) {2119printf(" %-*s | Bin\n", max, qname.buf);2120strbuf_release(&qname);2121return;2122}21232124printf(" %-*s |", max, qname.buf);2125strbuf_release(&qname);21262127/*2128 * scale the add/delete2129 */2130 max = max + state->max_change >70?70- max : state->max_change;2131 add = patch->lines_added;2132 del = patch->lines_deleted;21332134if(state->max_change >0) {2135int total = ((add + del) * max + state->max_change /2) / state->max_change;2136 add = (add * max + state->max_change /2) / state->max_change;2137 del = total - add;2138}2139printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2140 add, pluses, del, minuses);2141}21422143static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2144{2145switch(st->st_mode & S_IFMT) {2146case S_IFLNK:2147if(strbuf_readlink(buf, path, st->st_size) <0)2148returnerror(_("unable to read symlink%s"), path);2149return0;2150case S_IFREG:2151if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2152returnerror(_("unable to open or read%s"), path);2153convert_to_git(path, buf->buf, buf->len, buf,0);2154return0;2155default:2156return-1;2157}2158}21592160/*2161 * Update the preimage, and the common lines in postimage,2162 * from buffer buf of length len. If postlen is 0 the postimage2163 * is updated in place, otherwise it's updated on a new buffer2164 * of length postlen2165 */21662167static voidupdate_pre_post_images(struct image *preimage,2168struct image *postimage,2169char*buf,2170size_t len,size_t postlen)2171{2172int i, ctx, reduced;2173char*new, *old, *fixed;2174struct image fixed_preimage;21752176/*2177 * Update the preimage with whitespace fixes. Note that we2178 * are not losing preimage->buf -- apply_one_fragment() will2179 * free "oldlines".2180 */2181prepare_image(&fixed_preimage, buf, len,1);2182assert(postlen2183? fixed_preimage.nr == preimage->nr2184: fixed_preimage.nr <= preimage->nr);2185for(i =0; i < fixed_preimage.nr; i++)2186 fixed_preimage.line[i].flag = preimage->line[i].flag;2187free(preimage->line_allocated);2188*preimage = fixed_preimage;21892190/*2191 * Adjust the common context lines in postimage. This can be2192 * done in-place when we are shrinking it with whitespace2193 * fixing, but needs a new buffer when ignoring whitespace or2194 * expanding leading tabs to spaces.2195 *2196 * We trust the caller to tell us if the update can be done2197 * in place (postlen==0) or not.2198 */2199 old = postimage->buf;2200if(postlen)2201new= postimage->buf =xmalloc(postlen);2202else2203new= old;2204 fixed = preimage->buf;22052206for(i = reduced = ctx =0; i < postimage->nr; i++) {2207size_t l_len = postimage->line[i].len;2208if(!(postimage->line[i].flag & LINE_COMMON)) {2209/* an added line -- no counterparts in preimage */2210memmove(new, old, l_len);2211 old += l_len;2212new+= l_len;2213continue;2214}22152216/* a common context -- skip it in the original postimage */2217 old += l_len;22182219/* and find the corresponding one in the fixed preimage */2220while(ctx < preimage->nr &&2221!(preimage->line[ctx].flag & LINE_COMMON)) {2222 fixed += preimage->line[ctx].len;2223 ctx++;2224}22252226/*2227 * preimage is expected to run out, if the caller2228 * fixed addition of trailing blank lines.2229 */2230if(preimage->nr <= ctx) {2231 reduced++;2232continue;2233}22342235/* and copy it in, while fixing the line length */2236 l_len = preimage->line[ctx].len;2237memcpy(new, fixed, l_len);2238new+= l_len;2239 fixed += l_len;2240 postimage->line[i].len = l_len;2241 ctx++;2242}22432244if(postlen2245? postlen <new- postimage->buf2246: postimage->len <new- postimage->buf)2247die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2248(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22492250/* Fix the length of the whole thing */2251 postimage->len =new- postimage->buf;2252 postimage->nr -= reduced;2253}22542255static intline_by_line_fuzzy_match(struct image *img,2256struct image *preimage,2257struct image *postimage,2258unsigned longtry,2259int try_lno,2260int preimage_limit)2261{2262int i;2263size_t imgoff =0;2264size_t preoff =0;2265size_t postlen = postimage->len;2266size_t extra_chars;2267char*buf;2268char*preimage_eof;2269char*preimage_end;2270struct strbuf fixed;2271char*fixed_buf;2272size_t fixed_len;22732274for(i =0; i < preimage_limit; i++) {2275size_t prelen = preimage->line[i].len;2276size_t imglen = img->line[try_lno+i].len;22772278if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2279 preimage->buf + preoff, prelen))2280return0;2281if(preimage->line[i].flag & LINE_COMMON)2282 postlen += imglen - prelen;2283 imgoff += imglen;2284 preoff += prelen;2285}22862287/*2288 * Ok, the preimage matches with whitespace fuzz.2289 *2290 * imgoff now holds the true length of the target that2291 * matches the preimage before the end of the file.2292 *2293 * Count the number of characters in the preimage that fall2294 * beyond the end of the file and make sure that all of them2295 * are whitespace characters. (This can only happen if2296 * we are removing blank lines at the end of the file.)2297 */2298 buf = preimage_eof = preimage->buf + preoff;2299for( ; i < preimage->nr; i++)2300 preoff += preimage->line[i].len;2301 preimage_end = preimage->buf + preoff;2302for( ; buf < preimage_end; buf++)2303if(!isspace(*buf))2304return0;23052306/*2307 * Update the preimage and the common postimage context2308 * lines to use the same whitespace as the target.2309 * If whitespace is missing in the target (i.e.2310 * if the preimage extends beyond the end of the file),2311 * use the whitespace from the preimage.2312 */2313 extra_chars = preimage_end - preimage_eof;2314strbuf_init(&fixed, imgoff + extra_chars);2315strbuf_add(&fixed, img->buf +try, imgoff);2316strbuf_add(&fixed, preimage_eof, extra_chars);2317 fixed_buf =strbuf_detach(&fixed, &fixed_len);2318update_pre_post_images(preimage, postimage,2319 fixed_buf, fixed_len, postlen);2320return1;2321}23222323static intmatch_fragment(struct apply_state *state,2324struct image *img,2325struct image *preimage,2326struct image *postimage,2327unsigned longtry,2328int try_lno,2329unsigned ws_rule,2330int match_beginning,int match_end)2331{2332int i;2333char*fixed_buf, *buf, *orig, *target;2334struct strbuf fixed;2335size_t fixed_len, postlen;2336int preimage_limit;23372338if(preimage->nr + try_lno <= img->nr) {2339/*2340 * The hunk falls within the boundaries of img.2341 */2342 preimage_limit = preimage->nr;2343if(match_end && (preimage->nr + try_lno != img->nr))2344return0;2345}else if(state->ws_error_action == correct_ws_error &&2346(ws_rule & WS_BLANK_AT_EOF)) {2347/*2348 * This hunk extends beyond the end of img, and we are2349 * removing blank lines at the end of the file. This2350 * many lines from the beginning of the preimage must2351 * match with img, and the remainder of the preimage2352 * must be blank.2353 */2354 preimage_limit = img->nr - try_lno;2355}else{2356/*2357 * The hunk extends beyond the end of the img and2358 * we are not removing blanks at the end, so we2359 * should reject the hunk at this position.2360 */2361return0;2362}23632364if(match_beginning && try_lno)2365return0;23662367/* Quick hash check */2368for(i =0; i < preimage_limit; i++)2369if((img->line[try_lno + i].flag & LINE_PATCHED) ||2370(preimage->line[i].hash != img->line[try_lno + i].hash))2371return0;23722373if(preimage_limit == preimage->nr) {2374/*2375 * Do we have an exact match? If we were told to match2376 * at the end, size must be exactly at try+fragsize,2377 * otherwise try+fragsize must be still within the preimage,2378 * and either case, the old piece should match the preimage2379 * exactly.2380 */2381if((match_end2382? (try+ preimage->len == img->len)2383: (try+ preimage->len <= img->len)) &&2384!memcmp(img->buf +try, preimage->buf, preimage->len))2385return1;2386}else{2387/*2388 * The preimage extends beyond the end of img, so2389 * there cannot be an exact match.2390 *2391 * There must be one non-blank context line that match2392 * a line before the end of img.2393 */2394char*buf_end;23952396 buf = preimage->buf;2397 buf_end = buf;2398for(i =0; i < preimage_limit; i++)2399 buf_end += preimage->line[i].len;24002401for( ; buf < buf_end; buf++)2402if(!isspace(*buf))2403break;2404if(buf == buf_end)2405return0;2406}24072408/*2409 * No exact match. If we are ignoring whitespace, run a line-by-line2410 * fuzzy matching. We collect all the line length information because2411 * we need it to adjust whitespace if we match.2412 */2413if(state->ws_ignore_action == ignore_ws_change)2414returnline_by_line_fuzzy_match(img, preimage, postimage,2415try, try_lno, preimage_limit);24162417if(state->ws_error_action != correct_ws_error)2418return0;24192420/*2421 * The hunk does not apply byte-by-byte, but the hash says2422 * it might with whitespace fuzz. We weren't asked to2423 * ignore whitespace, we were asked to correct whitespace2424 * errors, so let's try matching after whitespace correction.2425 *2426 * While checking the preimage against the target, whitespace2427 * errors in both fixed, we count how large the corresponding2428 * postimage needs to be. The postimage prepared by2429 * apply_one_fragment() has whitespace errors fixed on added2430 * lines already, but the common lines were propagated as-is,2431 * which may become longer when their whitespace errors are2432 * fixed.2433 */24342435/* First count added lines in postimage */2436 postlen =0;2437for(i =0; i < postimage->nr; i++) {2438if(!(postimage->line[i].flag & LINE_COMMON))2439 postlen += postimage->line[i].len;2440}24412442/*2443 * The preimage may extend beyond the end of the file,2444 * but in this loop we will only handle the part of the2445 * preimage that falls within the file.2446 */2447strbuf_init(&fixed, preimage->len +1);2448 orig = preimage->buf;2449 target = img->buf +try;2450for(i =0; i < preimage_limit; i++) {2451size_t oldlen = preimage->line[i].len;2452size_t tgtlen = img->line[try_lno + i].len;2453size_t fixstart = fixed.len;2454struct strbuf tgtfix;2455int match;24562457/* Try fixing the line in the preimage */2458ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24592460/* Try fixing the line in the target */2461strbuf_init(&tgtfix, tgtlen);2462ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24632464/*2465 * If they match, either the preimage was based on2466 * a version before our tree fixed whitespace breakage,2467 * or we are lacking a whitespace-fix patch the tree2468 * the preimage was based on already had (i.e. target2469 * has whitespace breakage, the preimage doesn't).2470 * In either case, we are fixing the whitespace breakages2471 * so we might as well take the fix together with their2472 * real change.2473 */2474 match = (tgtfix.len == fixed.len - fixstart &&2475!memcmp(tgtfix.buf, fixed.buf + fixstart,2476 fixed.len - fixstart));24772478/* Add the length if this is common with the postimage */2479if(preimage->line[i].flag & LINE_COMMON)2480 postlen += tgtfix.len;24812482strbuf_release(&tgtfix);2483if(!match)2484goto unmatch_exit;24852486 orig += oldlen;2487 target += tgtlen;2488}248924902491/*2492 * Now handle the lines in the preimage that falls beyond the2493 * end of the file (if any). They will only match if they are2494 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2495 * false).2496 */2497for( ; i < preimage->nr; i++) {2498size_t fixstart = fixed.len;/* start of the fixed preimage */2499size_t oldlen = preimage->line[i].len;2500int j;25012502/* Try fixing the line in the preimage */2503ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25042505for(j = fixstart; j < fixed.len; j++)2506if(!isspace(fixed.buf[j]))2507goto unmatch_exit;25082509 orig += oldlen;2510}25112512/*2513 * Yes, the preimage is based on an older version that still2514 * has whitespace breakages unfixed, and fixing them makes the2515 * hunk match. Update the context lines in the postimage.2516 */2517 fixed_buf =strbuf_detach(&fixed, &fixed_len);2518if(postlen < postimage->len)2519 postlen =0;2520update_pre_post_images(preimage, postimage,2521 fixed_buf, fixed_len, postlen);2522return1;25232524 unmatch_exit:2525strbuf_release(&fixed);2526return0;2527}25282529static intfind_pos(struct apply_state *state,2530struct image *img,2531struct image *preimage,2532struct image *postimage,2533int line,2534unsigned ws_rule,2535int match_beginning,int match_end)2536{2537int i;2538unsigned long backwards, forwards,try;2539int backwards_lno, forwards_lno, try_lno;25402541/*2542 * If match_beginning or match_end is specified, there is no2543 * point starting from a wrong line that will never match and2544 * wander around and wait for a match at the specified end.2545 */2546if(match_beginning)2547 line =0;2548else if(match_end)2549 line = img->nr - preimage->nr;25502551/*2552 * Because the comparison is unsigned, the following test2553 * will also take care of a negative line number that can2554 * result when match_end and preimage is larger than the target.2555 */2556if((size_t) line > img->nr)2557 line = img->nr;25582559try=0;2560for(i =0; i < line; i++)2561try+= img->line[i].len;25622563/*2564 * There's probably some smart way to do this, but I'll leave2565 * that to the smart and beautiful people. I'm simple and stupid.2566 */2567 backwards =try;2568 backwards_lno = line;2569 forwards =try;2570 forwards_lno = line;2571 try_lno = line;25722573for(i =0; ; i++) {2574if(match_fragment(state, img, preimage, postimage,2575try, try_lno, ws_rule,2576 match_beginning, match_end))2577return try_lno;25782579 again:2580if(backwards_lno ==0&& forwards_lno == img->nr)2581break;25822583if(i &1) {2584if(backwards_lno ==0) {2585 i++;2586goto again;2587}2588 backwards_lno--;2589 backwards -= img->line[backwards_lno].len;2590try= backwards;2591 try_lno = backwards_lno;2592}else{2593if(forwards_lno == img->nr) {2594 i++;2595goto again;2596}2597 forwards += img->line[forwards_lno].len;2598 forwards_lno++;2599try= forwards;2600 try_lno = forwards_lno;2601}26022603}2604return-1;2605}26062607static voidremove_first_line(struct image *img)2608{2609 img->buf += img->line[0].len;2610 img->len -= img->line[0].len;2611 img->line++;2612 img->nr--;2613}26142615static voidremove_last_line(struct image *img)2616{2617 img->len -= img->line[--img->nr].len;2618}26192620/*2621 * The change from "preimage" and "postimage" has been found to2622 * apply at applied_pos (counts in line numbers) in "img".2623 * Update "img" to remove "preimage" and replace it with "postimage".2624 */2625static voidupdate_image(struct apply_state *state,2626struct image *img,2627int applied_pos,2628struct image *preimage,2629struct image *postimage)2630{2631/*2632 * remove the copy of preimage at offset in img2633 * and replace it with postimage2634 */2635int i, nr;2636size_t remove_count, insert_count, applied_at =0;2637char*result;2638int preimage_limit;26392640/*2641 * If we are removing blank lines at the end of img,2642 * the preimage may extend beyond the end.2643 * If that is the case, we must be careful only to2644 * remove the part of the preimage that falls within2645 * the boundaries of img. Initialize preimage_limit2646 * to the number of lines in the preimage that falls2647 * within the boundaries.2648 */2649 preimage_limit = preimage->nr;2650if(preimage_limit > img->nr - applied_pos)2651 preimage_limit = img->nr - applied_pos;26522653for(i =0; i < applied_pos; i++)2654 applied_at += img->line[i].len;26552656 remove_count =0;2657for(i =0; i < preimage_limit; i++)2658 remove_count += img->line[applied_pos + i].len;2659 insert_count = postimage->len;26602661/* Adjust the contents */2662 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2663memcpy(result, img->buf, applied_at);2664memcpy(result + applied_at, postimage->buf, postimage->len);2665memcpy(result + applied_at + postimage->len,2666 img->buf + (applied_at + remove_count),2667 img->len - (applied_at + remove_count));2668free(img->buf);2669 img->buf = result;2670 img->len += insert_count - remove_count;2671 result[img->len] ='\0';26722673/* Adjust the line table */2674 nr = img->nr + postimage->nr - preimage_limit;2675if(preimage_limit < postimage->nr) {2676/*2677 * NOTE: this knows that we never call remove_first_line()2678 * on anything other than pre/post image.2679 */2680REALLOC_ARRAY(img->line, nr);2681 img->line_allocated = img->line;2682}2683if(preimage_limit != postimage->nr)2684memmove(img->line + applied_pos + postimage->nr,2685 img->line + applied_pos + preimage_limit,2686(img->nr - (applied_pos + preimage_limit)) *2687sizeof(*img->line));2688memcpy(img->line + applied_pos,2689 postimage->line,2690 postimage->nr *sizeof(*img->line));2691if(!state->allow_overlap)2692for(i =0; i < postimage->nr; i++)2693 img->line[applied_pos + i].flag |= LINE_PATCHED;2694 img->nr = nr;2695}26962697/*2698 * Use the patch-hunk text in "frag" to prepare two images (preimage and2699 * postimage) for the hunk. Find lines that match "preimage" in "img" and2700 * replace the part of "img" with "postimage" text.2701 */2702static intapply_one_fragment(struct apply_state *state,2703struct image *img,struct fragment *frag,2704int inaccurate_eof,unsigned ws_rule,2705int nth_fragment)2706{2707int match_beginning, match_end;2708const char*patch = frag->patch;2709int size = frag->size;2710char*old, *oldlines;2711struct strbuf newlines;2712int new_blank_lines_at_end =0;2713int found_new_blank_lines_at_end =0;2714int hunk_linenr = frag->linenr;2715unsigned long leading, trailing;2716int pos, applied_pos;2717struct image preimage;2718struct image postimage;27192720memset(&preimage,0,sizeof(preimage));2721memset(&postimage,0,sizeof(postimage));2722 oldlines =xmalloc(size);2723strbuf_init(&newlines, size);27242725 old = oldlines;2726while(size >0) {2727char first;2728int len =linelen(patch, size);2729int plen;2730int added_blank_line =0;2731int is_blank_context =0;2732size_t start;27332734if(!len)2735break;27362737/*2738 * "plen" is how much of the line we should use for2739 * the actual patch data. Normally we just remove the2740 * first character on the line, but if the line is2741 * followed by "\ No newline", then we also remove the2742 * last one (which is the newline, of course).2743 */2744 plen = len -1;2745if(len < size && patch[len] =='\\')2746 plen--;2747 first = *patch;2748if(state->apply_in_reverse) {2749if(first =='-')2750 first ='+';2751else if(first =='+')2752 first ='-';2753}27542755switch(first) {2756case'\n':2757/* Newer GNU diff, empty context line */2758if(plen <0)2759/* ... followed by '\No newline'; nothing */2760break;2761*old++ ='\n';2762strbuf_addch(&newlines,'\n');2763add_line_info(&preimage,"\n",1, LINE_COMMON);2764add_line_info(&postimage,"\n",1, LINE_COMMON);2765 is_blank_context =1;2766break;2767case' ':2768if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2769ws_blank_line(patch +1, plen, ws_rule))2770 is_blank_context =1;2771case'-':2772memcpy(old, patch +1, plen);2773add_line_info(&preimage, old, plen,2774(first ==' '? LINE_COMMON :0));2775 old += plen;2776if(first =='-')2777break;2778/* Fall-through for ' ' */2779case'+':2780/* --no-add does not add new lines */2781if(first =='+'&& state->no_add)2782break;27832784 start = newlines.len;2785if(first !='+'||2786!state->whitespace_error ||2787 state->ws_error_action != correct_ws_error) {2788strbuf_add(&newlines, patch +1, plen);2789}2790else{2791ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2792}2793add_line_info(&postimage, newlines.buf + start, newlines.len - start,2794(first =='+'?0: LINE_COMMON));2795if(first =='+'&&2796(ws_rule & WS_BLANK_AT_EOF) &&2797ws_blank_line(patch +1, plen, ws_rule))2798 added_blank_line =1;2799break;2800case'@':case'\\':2801/* Ignore it, we already handled it */2802break;2803default:2804if(state->apply_verbosely)2805error(_("invalid start of line: '%c'"), first);2806 applied_pos = -1;2807goto out;2808}2809if(added_blank_line) {2810if(!new_blank_lines_at_end)2811 found_new_blank_lines_at_end = hunk_linenr;2812 new_blank_lines_at_end++;2813}2814else if(is_blank_context)2815;2816else2817 new_blank_lines_at_end =0;2818 patch += len;2819 size -= len;2820 hunk_linenr++;2821}2822if(inaccurate_eof &&2823 old > oldlines && old[-1] =='\n'&&2824 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2825 old--;2826strbuf_setlen(&newlines, newlines.len -1);2827}28282829 leading = frag->leading;2830 trailing = frag->trailing;28312832/*2833 * A hunk to change lines at the beginning would begin with2834 * @@ -1,L +N,M @@2835 * but we need to be careful. -U0 that inserts before the second2836 * line also has this pattern.2837 *2838 * And a hunk to add to an empty file would begin with2839 * @@ -0,0 +N,M @@2840 *2841 * In other words, a hunk that is (frag->oldpos <= 1) with or2842 * without leading context must match at the beginning.2843 */2844 match_beginning = (!frag->oldpos ||2845(frag->oldpos ==1&& !state->unidiff_zero));28462847/*2848 * A hunk without trailing lines must match at the end.2849 * However, we simply cannot tell if a hunk must match end2850 * from the lack of trailing lines if the patch was generated2851 * with unidiff without any context.2852 */2853 match_end = !state->unidiff_zero && !trailing;28542855 pos = frag->newpos ? (frag->newpos -1) :0;2856 preimage.buf = oldlines;2857 preimage.len = old - oldlines;2858 postimage.buf = newlines.buf;2859 postimage.len = newlines.len;2860 preimage.line = preimage.line_allocated;2861 postimage.line = postimage.line_allocated;28622863for(;;) {28642865 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2866 ws_rule, match_beginning, match_end);28672868if(applied_pos >=0)2869break;28702871/* Am I at my context limits? */2872if((leading <= state->p_context) && (trailing <= state->p_context))2873break;2874if(match_beginning || match_end) {2875 match_beginning = match_end =0;2876continue;2877}28782879/*2880 * Reduce the number of context lines; reduce both2881 * leading and trailing if they are equal otherwise2882 * just reduce the larger context.2883 */2884if(leading >= trailing) {2885remove_first_line(&preimage);2886remove_first_line(&postimage);2887 pos--;2888 leading--;2889}2890if(trailing > leading) {2891remove_last_line(&preimage);2892remove_last_line(&postimage);2893 trailing--;2894}2895}28962897if(applied_pos >=0) {2898if(new_blank_lines_at_end &&2899 preimage.nr + applied_pos >= img->nr &&2900(ws_rule & WS_BLANK_AT_EOF) &&2901 state->ws_error_action != nowarn_ws_error) {2902record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2903 found_new_blank_lines_at_end);2904if(state->ws_error_action == correct_ws_error) {2905while(new_blank_lines_at_end--)2906remove_last_line(&postimage);2907}2908/*2909 * We would want to prevent write_out_results()2910 * from taking place in apply_patch() that follows2911 * the callchain led us here, which is:2912 * apply_patch->check_patch_list->check_patch->2913 * apply_data->apply_fragments->apply_one_fragment2914 */2915if(state->ws_error_action == die_on_ws_error)2916 state->apply =0;2917}29182919if(state->apply_verbosely && applied_pos != pos) {2920int offset = applied_pos - pos;2921if(state->apply_in_reverse)2922 offset =0- offset;2923fprintf_ln(stderr,2924Q_("Hunk #%dsucceeded at%d(offset%dline).",2925"Hunk #%dsucceeded at%d(offset%dlines).",2926 offset),2927 nth_fragment, applied_pos +1, offset);2928}29292930/*2931 * Warn if it was necessary to reduce the number2932 * of context lines.2933 */2934if((leading != frag->leading) ||2935(trailing != frag->trailing))2936fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2937" to apply fragment at%d"),2938 leading, trailing, applied_pos+1);2939update_image(state, img, applied_pos, &preimage, &postimage);2940}else{2941if(state->apply_verbosely)2942error(_("while searching for:\n%.*s"),2943(int)(old - oldlines), oldlines);2944}29452946out:2947free(oldlines);2948strbuf_release(&newlines);2949free(preimage.line_allocated);2950free(postimage.line_allocated);29512952return(applied_pos <0);2953}29542955static intapply_binary_fragment(struct apply_state *state,2956struct image *img,2957struct patch *patch)2958{2959struct fragment *fragment = patch->fragments;2960unsigned long len;2961void*dst;29622963if(!fragment)2964returnerror(_("missing binary patch data for '%s'"),2965 patch->new_name ?2966 patch->new_name :2967 patch->old_name);29682969/* Binary patch is irreversible without the optional second hunk */2970if(state->apply_in_reverse) {2971if(!fragment->next)2972returnerror("cannot reverse-apply a binary patch "2973"without the reverse hunk to '%s'",2974 patch->new_name2975? patch->new_name : patch->old_name);2976 fragment = fragment->next;2977}2978switch(fragment->binary_patch_method) {2979case BINARY_DELTA_DEFLATED:2980 dst =patch_delta(img->buf, img->len, fragment->patch,2981 fragment->size, &len);2982if(!dst)2983return-1;2984clear_image(img);2985 img->buf = dst;2986 img->len = len;2987return0;2988case BINARY_LITERAL_DEFLATED:2989clear_image(img);2990 img->len = fragment->size;2991 img->buf =xmemdupz(fragment->patch, img->len);2992return0;2993}2994return-1;2995}29962997/*2998 * Replace "img" with the result of applying the binary patch.2999 * The binary patch data itself in patch->fragment is still kept3000 * but the preimage prepared by the caller in "img" is freed here3001 * or in the helper function apply_binary_fragment() this calls.3002 */3003static intapply_binary(struct apply_state *state,3004struct image *img,3005struct patch *patch)3006{3007const char*name = patch->old_name ? patch->old_name : patch->new_name;3008unsigned char sha1[20];30093010/*3011 * For safety, we require patch index line to contain3012 * full 40-byte textual SHA1 for old and new, at least for now.3013 */3014if(strlen(patch->old_sha1_prefix) !=40||3015strlen(patch->new_sha1_prefix) !=40||3016get_sha1_hex(patch->old_sha1_prefix, sha1) ||3017get_sha1_hex(patch->new_sha1_prefix, sha1))3018returnerror("cannot apply binary patch to '%s' "3019"without full index line", name);30203021if(patch->old_name) {3022/*3023 * See if the old one matches what the patch3024 * applies to.3025 */3026hash_sha1_file(img->buf, img->len, blob_type, sha1);3027if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3028returnerror("the patch applies to '%s' (%s), "3029"which does not match the "3030"current contents.",3031 name,sha1_to_hex(sha1));3032}3033else{3034/* Otherwise, the old one must be empty. */3035if(img->len)3036returnerror("the patch applies to an empty "3037"'%s' but it is not empty", name);3038}30393040get_sha1_hex(patch->new_sha1_prefix, sha1);3041if(is_null_sha1(sha1)) {3042clear_image(img);3043return0;/* deletion patch */3044}30453046if(has_sha1_file(sha1)) {3047/* We already have the postimage */3048enum object_type type;3049unsigned long size;3050char*result;30513052 result =read_sha1_file(sha1, &type, &size);3053if(!result)3054returnerror("the necessary postimage%sfor "3055"'%s' cannot be read",3056 patch->new_sha1_prefix, name);3057clear_image(img);3058 img->buf = result;3059 img->len = size;3060}else{3061/*3062 * We have verified buf matches the preimage;3063 * apply the patch data to it, which is stored3064 * in the patch->fragments->{patch,size}.3065 */3066if(apply_binary_fragment(state, img, patch))3067returnerror(_("binary patch does not apply to '%s'"),3068 name);30693070/* verify that the result matches */3071hash_sha1_file(img->buf, img->len, blob_type, sha1);3072if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3073returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3074 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3075}30763077return0;3078}30793080static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3081{3082struct fragment *frag = patch->fragments;3083const char*name = patch->old_name ? patch->old_name : patch->new_name;3084unsigned ws_rule = patch->ws_rule;3085unsigned inaccurate_eof = patch->inaccurate_eof;3086int nth =0;30873088if(patch->is_binary)3089returnapply_binary(state, img, patch);30903091while(frag) {3092 nth++;3093if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3094error(_("patch failed:%s:%ld"), name, frag->oldpos);3095if(!state->apply_with_reject)3096return-1;3097 frag->rejected =1;3098}3099 frag = frag->next;3100}3101return0;3102}31033104static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3105{3106if(S_ISGITLINK(mode)) {3107strbuf_grow(buf,100);3108strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3109}else{3110enum object_type type;3111unsigned long sz;3112char*result;31133114 result =read_sha1_file(sha1, &type, &sz);3115if(!result)3116return-1;3117/* XXX read_sha1_file NUL-terminates */3118strbuf_attach(buf, result, sz, sz +1);3119}3120return0;3121}31223123static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3124{3125if(!ce)3126return0;3127returnread_blob_object(buf, ce->sha1, ce->ce_mode);3128}31293130static struct patch *in_fn_table(struct apply_state *state,const char*name)3131{3132struct string_list_item *item;31333134if(name == NULL)3135return NULL;31363137 item =string_list_lookup(&state->fn_table, name);3138if(item != NULL)3139return(struct patch *)item->util;31403141return NULL;3142}31433144/*3145 * item->util in the filename table records the status of the path.3146 * Usually it points at a patch (whose result records the contents3147 * of it after applying it), but it could be PATH_WAS_DELETED for a3148 * path that a previously applied patch has already removed, or3149 * PATH_TO_BE_DELETED for a path that a later patch would remove.3150 *3151 * The latter is needed to deal with a case where two paths A and B3152 * are swapped by first renaming A to B and then renaming B to A;3153 * moving A to B should not be prevented due to presence of B as we3154 * will remove it in a later patch.3155 */3156#define PATH_TO_BE_DELETED ((struct patch *) -2)3157#define PATH_WAS_DELETED ((struct patch *) -1)31583159static intto_be_deleted(struct patch *patch)3160{3161return patch == PATH_TO_BE_DELETED;3162}31633164static intwas_deleted(struct patch *patch)3165{3166return patch == PATH_WAS_DELETED;3167}31683169static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3170{3171struct string_list_item *item;31723173/*3174 * Always add new_name unless patch is a deletion3175 * This should cover the cases for normal diffs,3176 * file creations and copies3177 */3178if(patch->new_name != NULL) {3179 item =string_list_insert(&state->fn_table, patch->new_name);3180 item->util = patch;3181}31823183/*3184 * store a failure on rename/deletion cases because3185 * later chunks shouldn't patch old names3186 */3187if((patch->new_name == NULL) || (patch->is_rename)) {3188 item =string_list_insert(&state->fn_table, patch->old_name);3189 item->util = PATH_WAS_DELETED;3190}3191}31923193static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3194{3195/*3196 * store information about incoming file deletion3197 */3198while(patch) {3199if((patch->new_name == NULL) || (patch->is_rename)) {3200struct string_list_item *item;3201 item =string_list_insert(&state->fn_table, patch->old_name);3202 item->util = PATH_TO_BE_DELETED;3203}3204 patch = patch->next;3205}3206}32073208static intcheckout_target(struct index_state *istate,3209struct cache_entry *ce,struct stat *st)3210{3211struct checkout costate;32123213memset(&costate,0,sizeof(costate));3214 costate.base_dir ="";3215 costate.refresh_cache =1;3216 costate.istate = istate;3217if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3218returnerror(_("cannot checkout%s"), ce->name);3219return0;3220}32213222static struct patch *previous_patch(struct apply_state *state,3223struct patch *patch,3224int*gone)3225{3226struct patch *previous;32273228*gone =0;3229if(patch->is_copy || patch->is_rename)3230return NULL;/* "git" patches do not depend on the order */32313232 previous =in_fn_table(state, patch->old_name);3233if(!previous)3234return NULL;32353236if(to_be_deleted(previous))3237return NULL;/* the deletion hasn't happened yet */32383239if(was_deleted(previous))3240*gone =1;32413242return previous;3243}32443245static intverify_index_match(const struct cache_entry *ce,struct stat *st)3246{3247if(S_ISGITLINK(ce->ce_mode)) {3248if(!S_ISDIR(st->st_mode))3249return-1;3250return0;3251}3252returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3253}32543255#define SUBMODULE_PATCH_WITHOUT_INDEX 132563257static intload_patch_target(struct apply_state *state,3258struct strbuf *buf,3259const struct cache_entry *ce,3260struct stat *st,3261const char*name,3262unsigned expected_mode)3263{3264if(state->cached || state->check_index) {3265if(read_file_or_gitlink(ce, buf))3266returnerror(_("failed to read%s"), name);3267}else if(name) {3268if(S_ISGITLINK(expected_mode)) {3269if(ce)3270returnread_file_or_gitlink(ce, buf);3271else3272return SUBMODULE_PATCH_WITHOUT_INDEX;3273}else if(has_symlink_leading_path(name,strlen(name))) {3274returnerror(_("reading from '%s' beyond a symbolic link"), name);3275}else{3276if(read_old_data(st, name, buf))3277returnerror(_("failed to read%s"), name);3278}3279}3280return0;3281}32823283/*3284 * We are about to apply "patch"; populate the "image" with the3285 * current version we have, from the working tree or from the index,3286 * depending on the situation e.g. --cached/--index. If we are3287 * applying a non-git patch that incrementally updates the tree,3288 * we read from the result of a previous diff.3289 */3290static intload_preimage(struct apply_state *state,3291struct image *image,3292struct patch *patch,struct stat *st,3293const struct cache_entry *ce)3294{3295struct strbuf buf = STRBUF_INIT;3296size_t len;3297char*img;3298struct patch *previous;3299int status;33003301 previous =previous_patch(state, patch, &status);3302if(status)3303returnerror(_("path%shas been renamed/deleted"),3304 patch->old_name);3305if(previous) {3306/* We have a patched copy in memory; use that. */3307strbuf_add(&buf, previous->result, previous->resultsize);3308}else{3309 status =load_patch_target(state, &buf, ce, st,3310 patch->old_name, patch->old_mode);3311if(status <0)3312return status;3313else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3314/*3315 * There is no way to apply subproject3316 * patch without looking at the index.3317 * NEEDSWORK: shouldn't this be flagged3318 * as an error???3319 */3320free_fragment_list(patch->fragments);3321 patch->fragments = NULL;3322}else if(status) {3323returnerror(_("failed to read%s"), patch->old_name);3324}3325}33263327 img =strbuf_detach(&buf, &len);3328prepare_image(image, img, len, !patch->is_binary);3329return0;3330}33313332static intthree_way_merge(struct image *image,3333char*path,3334const unsigned char*base,3335const unsigned char*ours,3336const unsigned char*theirs)3337{3338 mmfile_t base_file, our_file, their_file;3339 mmbuffer_t result = { NULL };3340int status;33413342read_mmblob(&base_file, base);3343read_mmblob(&our_file, ours);3344read_mmblob(&their_file, theirs);3345 status =ll_merge(&result, path,3346&base_file,"base",3347&our_file,"ours",3348&their_file,"theirs", NULL);3349free(base_file.ptr);3350free(our_file.ptr);3351free(their_file.ptr);3352if(status <0|| !result.ptr) {3353free(result.ptr);3354return-1;3355}3356clear_image(image);3357 image->buf = result.ptr;3358 image->len = result.size;33593360return status;3361}33623363/*3364 * When directly falling back to add/add three-way merge, we read from3365 * the current contents of the new_name. In no cases other than that3366 * this function will be called.3367 */3368static intload_current(struct apply_state *state,3369struct image *image,3370struct patch *patch)3371{3372struct strbuf buf = STRBUF_INIT;3373int status, pos;3374size_t len;3375char*img;3376struct stat st;3377struct cache_entry *ce;3378char*name = patch->new_name;3379unsigned mode = patch->new_mode;33803381if(!patch->is_new)3382die("BUG: patch to%sis not a creation", patch->old_name);33833384 pos =cache_name_pos(name,strlen(name));3385if(pos <0)3386returnerror(_("%s: does not exist in index"), name);3387 ce = active_cache[pos];3388if(lstat(name, &st)) {3389if(errno != ENOENT)3390returnerror(_("%s:%s"), name,strerror(errno));3391if(checkout_target(&the_index, ce, &st))3392return-1;3393}3394if(verify_index_match(ce, &st))3395returnerror(_("%s: does not match index"), name);33963397 status =load_patch_target(state, &buf, ce, &st, name, mode);3398if(status <0)3399return status;3400else if(status)3401return-1;3402 img =strbuf_detach(&buf, &len);3403prepare_image(image, img, len, !patch->is_binary);3404return0;3405}34063407static inttry_threeway(struct apply_state *state,3408struct image *image,3409struct patch *patch,3410struct stat *st,3411const struct cache_entry *ce)3412{3413unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3414struct strbuf buf = STRBUF_INIT;3415size_t len;3416int status;3417char*img;3418struct image tmp_image;34193420/* No point falling back to 3-way merge in these cases */3421if(patch->is_delete ||3422S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3423return-1;34243425/* Preimage the patch was prepared for */3426if(patch->is_new)3427write_sha1_file("",0, blob_type, pre_sha1);3428else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3429read_blob_object(&buf, pre_sha1, patch->old_mode))3430returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34313432fprintf(stderr,"Falling back to three-way merge...\n");34333434 img =strbuf_detach(&buf, &len);3435prepare_image(&tmp_image, img, len,1);3436/* Apply the patch to get the post image */3437if(apply_fragments(state, &tmp_image, patch) <0) {3438clear_image(&tmp_image);3439return-1;3440}3441/* post_sha1[] is theirs */3442write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3443clear_image(&tmp_image);34443445/* our_sha1[] is ours */3446if(patch->is_new) {3447if(load_current(state, &tmp_image, patch))3448returnerror("cannot read the current contents of '%s'",3449 patch->new_name);3450}else{3451if(load_preimage(state, &tmp_image, patch, st, ce))3452returnerror("cannot read the current contents of '%s'",3453 patch->old_name);3454}3455write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3456clear_image(&tmp_image);34573458/* in-core three-way merge between post and our using pre as base */3459 status =three_way_merge(image, patch->new_name,3460 pre_sha1, our_sha1, post_sha1);3461if(status <0) {3462fprintf(stderr,"Failed to fall back on three-way merge...\n");3463return status;3464}34653466if(status) {3467 patch->conflicted_threeway =1;3468if(patch->is_new)3469oidclr(&patch->threeway_stage[0]);3470else3471hashcpy(patch->threeway_stage[0].hash, pre_sha1);3472hashcpy(patch->threeway_stage[1].hash, our_sha1);3473hashcpy(patch->threeway_stage[2].hash, post_sha1);3474fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3475}else{3476fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3477}3478return0;3479}34803481static intapply_data(struct apply_state *state,struct patch *patch,3482struct stat *st,const struct cache_entry *ce)3483{3484struct image image;34853486if(load_preimage(state, &image, patch, st, ce) <0)3487return-1;34883489if(patch->direct_to_threeway ||3490apply_fragments(state, &image, patch) <0) {3491/* Note: with --reject, apply_fragments() returns 0 */3492if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3493return-1;3494}3495 patch->result = image.buf;3496 patch->resultsize = image.len;3497add_to_fn_table(state, patch);3498free(image.line_allocated);34993500if(0< patch->is_delete && patch->resultsize)3501returnerror(_("removal patch leaves file contents"));35023503return0;3504}35053506/*3507 * If "patch" that we are looking at modifies or deletes what we have,3508 * we would want it not to lose any local modification we have, either3509 * in the working tree or in the index.3510 *3511 * This also decides if a non-git patch is a creation patch or a3512 * modification to an existing empty file. We do not check the state3513 * of the current tree for a creation patch in this function; the caller3514 * check_patch() separately makes sure (and errors out otherwise) that3515 * the path the patch creates does not exist in the current tree.3516 */3517static intcheck_preimage(struct apply_state *state,3518struct patch *patch,3519struct cache_entry **ce,3520struct stat *st)3521{3522const char*old_name = patch->old_name;3523struct patch *previous = NULL;3524int stat_ret =0, status;3525unsigned st_mode =0;35263527if(!old_name)3528return0;35293530assert(patch->is_new <=0);3531 previous =previous_patch(state, patch, &status);35323533if(status)3534returnerror(_("path%shas been renamed/deleted"), old_name);3535if(previous) {3536 st_mode = previous->new_mode;3537}else if(!state->cached) {3538 stat_ret =lstat(old_name, st);3539if(stat_ret && errno != ENOENT)3540returnerror(_("%s:%s"), old_name,strerror(errno));3541}35423543if(state->check_index && !previous) {3544int pos =cache_name_pos(old_name,strlen(old_name));3545if(pos <0) {3546if(patch->is_new <0)3547goto is_new;3548returnerror(_("%s: does not exist in index"), old_name);3549}3550*ce = active_cache[pos];3551if(stat_ret <0) {3552if(checkout_target(&the_index, *ce, st))3553return-1;3554}3555if(!state->cached &&verify_index_match(*ce, st))3556returnerror(_("%s: does not match index"), old_name);3557if(state->cached)3558 st_mode = (*ce)->ce_mode;3559}else if(stat_ret <0) {3560if(patch->is_new <0)3561goto is_new;3562returnerror(_("%s:%s"), old_name,strerror(errno));3563}35643565if(!state->cached && !previous)3566 st_mode =ce_mode_from_stat(*ce, st->st_mode);35673568if(patch->is_new <0)3569 patch->is_new =0;3570if(!patch->old_mode)3571 patch->old_mode = st_mode;3572if((st_mode ^ patch->old_mode) & S_IFMT)3573returnerror(_("%s: wrong type"), old_name);3574if(st_mode != patch->old_mode)3575warning(_("%shas type%o, expected%o"),3576 old_name, st_mode, patch->old_mode);3577if(!patch->new_mode && !patch->is_delete)3578 patch->new_mode = st_mode;3579return0;35803581 is_new:3582 patch->is_new =1;3583 patch->is_delete =0;3584free(patch->old_name);3585 patch->old_name = NULL;3586return0;3587}358835893590#define EXISTS_IN_INDEX 13591#define EXISTS_IN_WORKTREE 235923593static intcheck_to_create(struct apply_state *state,3594const char*new_name,3595int ok_if_exists)3596{3597struct stat nst;35983599if(state->check_index &&3600cache_name_pos(new_name,strlen(new_name)) >=0&&3601!ok_if_exists)3602return EXISTS_IN_INDEX;3603if(state->cached)3604return0;36053606if(!lstat(new_name, &nst)) {3607if(S_ISDIR(nst.st_mode) || ok_if_exists)3608return0;3609/*3610 * A leading component of new_name might be a symlink3611 * that is going to be removed with this patch, but3612 * still pointing at somewhere that has the path.3613 * In such a case, path "new_name" does not exist as3614 * far as git is concerned.3615 */3616if(has_symlink_leading_path(new_name,strlen(new_name)))3617return0;36183619return EXISTS_IN_WORKTREE;3620}else if((errno != ENOENT) && (errno != ENOTDIR)) {3621returnerror("%s:%s", new_name,strerror(errno));3622}3623return0;3624}36253626static uintptr_tregister_symlink_changes(struct apply_state *state,3627const char*path,3628uintptr_t what)3629{3630struct string_list_item *ent;36313632 ent =string_list_lookup(&state->symlink_changes, path);3633if(!ent) {3634 ent =string_list_insert(&state->symlink_changes, path);3635 ent->util = (void*)0;3636}3637 ent->util = (void*)(what | ((uintptr_t)ent->util));3638return(uintptr_t)ent->util;3639}36403641static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3642{3643struct string_list_item *ent;36443645 ent =string_list_lookup(&state->symlink_changes, path);3646if(!ent)3647return0;3648return(uintptr_t)ent->util;3649}36503651static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3652{3653for( ; patch; patch = patch->next) {3654if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3655(patch->is_rename || patch->is_delete))3656/* the symlink at patch->old_name is removed */3657register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36583659if(patch->new_name &&S_ISLNK(patch->new_mode))3660/* the symlink at patch->new_name is created or remains */3661register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3662}3663}36643665static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3666{3667do{3668unsigned int change;36693670while(--name->len && name->buf[name->len] !='/')3671;/* scan backwards */3672if(!name->len)3673break;3674 name->buf[name->len] ='\0';3675 change =check_symlink_changes(state, name->buf);3676if(change & APPLY_SYMLINK_IN_RESULT)3677return1;3678if(change & APPLY_SYMLINK_GOES_AWAY)3679/*3680 * This cannot be "return 0", because we may3681 * see a new one created at a higher level.3682 */3683continue;36843685/* otherwise, check the preimage */3686if(state->check_index) {3687struct cache_entry *ce;36883689 ce =cache_file_exists(name->buf, name->len, ignore_case);3690if(ce &&S_ISLNK(ce->ce_mode))3691return1;3692}else{3693struct stat st;3694if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3695return1;3696}3697}while(1);3698return0;3699}37003701static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3702{3703int ret;3704struct strbuf name = STRBUF_INIT;37053706assert(*name_ !='\0');3707strbuf_addstr(&name, name_);3708 ret =path_is_beyond_symlink_1(state, &name);3709strbuf_release(&name);37103711return ret;3712}37133714static voiddie_on_unsafe_path(struct patch *patch)3715{3716const char*old_name = NULL;3717const char*new_name = NULL;3718if(patch->is_delete)3719 old_name = patch->old_name;3720else if(!patch->is_new && !patch->is_copy)3721 old_name = patch->old_name;3722if(!patch->is_delete)3723 new_name = patch->new_name;37243725if(old_name && !verify_path(old_name))3726die(_("invalid path '%s'"), old_name);3727if(new_name && !verify_path(new_name))3728die(_("invalid path '%s'"), new_name);3729}37303731/*3732 * Check and apply the patch in-core; leave the result in patch->result3733 * for the caller to write it out to the final destination.3734 */3735static intcheck_patch(struct apply_state *state,struct patch *patch)3736{3737struct stat st;3738const char*old_name = patch->old_name;3739const char*new_name = patch->new_name;3740const char*name = old_name ? old_name : new_name;3741struct cache_entry *ce = NULL;3742struct patch *tpatch;3743int ok_if_exists;3744int status;37453746 patch->rejected =1;/* we will drop this after we succeed */37473748 status =check_preimage(state, patch, &ce, &st);3749if(status)3750return status;3751 old_name = patch->old_name;37523753/*3754 * A type-change diff is always split into a patch to delete3755 * old, immediately followed by a patch to create new (see3756 * diff.c::run_diff()); in such a case it is Ok that the entry3757 * to be deleted by the previous patch is still in the working3758 * tree and in the index.3759 *3760 * A patch to swap-rename between A and B would first rename A3761 * to B and then rename B to A. While applying the first one,3762 * the presence of B should not stop A from getting renamed to3763 * B; ask to_be_deleted() about the later rename. Removal of3764 * B and rename from A to B is handled the same way by asking3765 * was_deleted().3766 */3767if((tpatch =in_fn_table(state, new_name)) &&3768(was_deleted(tpatch) ||to_be_deleted(tpatch)))3769 ok_if_exists =1;3770else3771 ok_if_exists =0;37723773if(new_name &&3774((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3775int err =check_to_create(state, new_name, ok_if_exists);37763777if(err && state->threeway) {3778 patch->direct_to_threeway =1;3779}else switch(err) {3780case0:3781break;/* happy */3782case EXISTS_IN_INDEX:3783returnerror(_("%s: already exists in index"), new_name);3784break;3785case EXISTS_IN_WORKTREE:3786returnerror(_("%s: already exists in working directory"),3787 new_name);3788default:3789return err;3790}37913792if(!patch->new_mode) {3793if(0< patch->is_new)3794 patch->new_mode = S_IFREG |0644;3795else3796 patch->new_mode = patch->old_mode;3797}3798}37993800if(new_name && old_name) {3801int same = !strcmp(old_name, new_name);3802if(!patch->new_mode)3803 patch->new_mode = patch->old_mode;3804if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3805if(same)3806returnerror(_("new mode (%o) of%sdoes not "3807"match old mode (%o)"),3808 patch->new_mode, new_name,3809 patch->old_mode);3810else3811returnerror(_("new mode (%o) of%sdoes not "3812"match old mode (%o) of%s"),3813 patch->new_mode, new_name,3814 patch->old_mode, old_name);3815}3816}38173818if(!state->unsafe_paths)3819die_on_unsafe_path(patch);38203821/*3822 * An attempt to read from or delete a path that is beyond a3823 * symbolic link will be prevented by load_patch_target() that3824 * is called at the beginning of apply_data() so we do not3825 * have to worry about a patch marked with "is_delete" bit3826 * here. We however need to make sure that the patch result3827 * is not deposited to a path that is beyond a symbolic link3828 * here.3829 */3830if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3831returnerror(_("affected file '%s' is beyond a symbolic link"),3832 patch->new_name);38333834if(apply_data(state, patch, &st, ce) <0)3835returnerror(_("%s: patch does not apply"), name);3836 patch->rejected =0;3837return0;3838}38393840static intcheck_patch_list(struct apply_state *state,struct patch *patch)3841{3842int err =0;38433844prepare_symlink_changes(state, patch);3845prepare_fn_table(state, patch);3846while(patch) {3847if(state->apply_verbosely)3848say_patch_name(stderr,3849_("Checking patch%s..."), patch);3850 err |=check_patch(state, patch);3851 patch = patch->next;3852}3853return err;3854}38553856/* This function tries to read the sha1 from the current index */3857static intget_current_sha1(const char*path,unsigned char*sha1)3858{3859int pos;38603861if(read_cache() <0)3862return-1;3863 pos =cache_name_pos(path,strlen(path));3864if(pos <0)3865return-1;3866hashcpy(sha1, active_cache[pos]->sha1);3867return0;3868}38693870static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3871{3872/*3873 * A usable gitlink patch has only one fragment (hunk) that looks like:3874 * @@ -1 +1 @@3875 * -Subproject commit <old sha1>3876 * +Subproject commit <new sha1>3877 * or3878 * @@ -1 +0,0 @@3879 * -Subproject commit <old sha1>3880 * for a removal patch.3881 */3882struct fragment *hunk = p->fragments;3883static const char heading[] ="-Subproject commit ";3884char*preimage;38853886if(/* does the patch have only one hunk? */3887 hunk && !hunk->next &&3888/* is its preimage one line? */3889 hunk->oldpos ==1&& hunk->oldlines ==1&&3890/* does preimage begin with the heading? */3891(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3892starts_with(++preimage, heading) &&3893/* does it record full SHA-1? */3894!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3895 preimage[sizeof(heading) +40-1] =='\n'&&3896/* does the abbreviated name on the index line agree with it? */3897starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3898return0;/* it all looks fine */38993900/* we may have full object name on the index line */3901returnget_sha1_hex(p->old_sha1_prefix, sha1);3902}39033904/* Build an index that contains the just the files needed for a 3way merge */3905static voidbuild_fake_ancestor(struct patch *list,const char*filename)3906{3907struct patch *patch;3908struct index_state result = { NULL };3909static struct lock_file lock;39103911/* Once we start supporting the reverse patch, it may be3912 * worth showing the new sha1 prefix, but until then...3913 */3914for(patch = list; patch; patch = patch->next) {3915unsigned char sha1[20];3916struct cache_entry *ce;3917const char*name;39183919 name = patch->old_name ? patch->old_name : patch->new_name;3920if(0< patch->is_new)3921continue;39223923if(S_ISGITLINK(patch->old_mode)) {3924if(!preimage_sha1_in_gitlink_patch(patch, sha1))3925;/* ok, the textual part looks sane */3926else3927die("sha1 information is lacking or useless for submodule%s",3928 name);3929}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3930;/* ok */3931}else if(!patch->lines_added && !patch->lines_deleted) {3932/* mode-only change: update the current */3933if(get_current_sha1(patch->old_name, sha1))3934die("mode change for%s, which is not "3935"in current HEAD", name);3936}else3937die("sha1 information is lacking or useless "3938"(%s).", name);39393940 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3941if(!ce)3942die(_("make_cache_entry failed for path '%s'"), name);3943if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3944die("Could not add%sto temporary index", name);3945}39463947hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3948if(write_locked_index(&result, &lock, COMMIT_LOCK))3949die("Could not write temporary index to%s", filename);39503951discard_index(&result);3952}39533954static voidstat_patch_list(struct apply_state *state,struct patch *patch)3955{3956int files, adds, dels;39573958for(files = adds = dels =0; patch ; patch = patch->next) {3959 files++;3960 adds += patch->lines_added;3961 dels += patch->lines_deleted;3962show_stats(state, patch);3963}39643965print_stat_summary(stdout, files, adds, dels);3966}39673968static voidnumstat_patch_list(struct apply_state *state,3969struct patch *patch)3970{3971for( ; patch; patch = patch->next) {3972const char*name;3973 name = patch->new_name ? patch->new_name : patch->old_name;3974if(patch->is_binary)3975printf("-\t-\t");3976else3977printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3978write_name_quoted(name, stdout, state->line_termination);3979}3980}39813982static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3983{3984if(mode)3985printf("%smode%06o%s\n", newdelete, mode, name);3986else3987printf("%s %s\n", newdelete, name);3988}39893990static voidshow_mode_change(struct patch *p,int show_name)3991{3992if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3993if(show_name)3994printf(" mode change%06o =>%06o%s\n",3995 p->old_mode, p->new_mode, p->new_name);3996else3997printf(" mode change%06o =>%06o\n",3998 p->old_mode, p->new_mode);3999}4000}40014002static voidshow_rename_copy(struct patch *p)4003{4004const char*renamecopy = p->is_rename ?"rename":"copy";4005const char*old, *new;40064007/* Find common prefix */4008 old = p->old_name;4009new= p->new_name;4010while(1) {4011const char*slash_old, *slash_new;4012 slash_old =strchr(old,'/');4013 slash_new =strchr(new,'/');4014if(!slash_old ||4015!slash_new ||4016 slash_old - old != slash_new -new||4017memcmp(old,new, slash_new -new))4018break;4019 old = slash_old +1;4020new= slash_new +1;4021}4022/* p->old_name thru old is the common prefix, and old and new4023 * through the end of names are renames4024 */4025if(old != p->old_name)4026printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4027(int)(old - p->old_name), p->old_name,4028 old,new, p->score);4029else4030printf("%s %s=>%s(%d%%)\n", renamecopy,4031 p->old_name, p->new_name, p->score);4032show_mode_change(p,0);4033}40344035static voidsummary_patch_list(struct patch *patch)4036{4037struct patch *p;40384039for(p = patch; p; p = p->next) {4040if(p->is_new)4041show_file_mode_name("create", p->new_mode, p->new_name);4042else if(p->is_delete)4043show_file_mode_name("delete", p->old_mode, p->old_name);4044else{4045if(p->is_rename || p->is_copy)4046show_rename_copy(p);4047else{4048if(p->score) {4049printf(" rewrite%s(%d%%)\n",4050 p->new_name, p->score);4051show_mode_change(p,0);4052}4053else4054show_mode_change(p,1);4055}4056}4057}4058}40594060static voidpatch_stats(struct apply_state *state,struct patch *patch)4061{4062int lines = patch->lines_added + patch->lines_deleted;40634064if(lines > state->max_change)4065 state->max_change = lines;4066if(patch->old_name) {4067int len =quote_c_style(patch->old_name, NULL, NULL,0);4068if(!len)4069 len =strlen(patch->old_name);4070if(len > state->max_len)4071 state->max_len = len;4072}4073if(patch->new_name) {4074int len =quote_c_style(patch->new_name, NULL, NULL,0);4075if(!len)4076 len =strlen(patch->new_name);4077if(len > state->max_len)4078 state->max_len = len;4079}4080}40814082static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4083{4084if(state->update_index) {4085if(remove_file_from_cache(patch->old_name) <0)4086die(_("unable to remove%sfrom index"), patch->old_name);4087}4088if(!state->cached) {4089if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4090remove_path(patch->old_name);4091}4092}4093}40944095static voidadd_index_file(struct apply_state *state,4096const char*path,4097unsigned mode,4098void*buf,4099unsigned long size)4100{4101struct stat st;4102struct cache_entry *ce;4103int namelen =strlen(path);4104unsigned ce_size =cache_entry_size(namelen);41054106if(!state->update_index)4107return;41084109 ce =xcalloc(1, ce_size);4110memcpy(ce->name, path, namelen);4111 ce->ce_mode =create_ce_mode(mode);4112 ce->ce_flags =create_ce_flags(0);4113 ce->ce_namelen = namelen;4114if(S_ISGITLINK(mode)) {4115const char*s;41164117if(!skip_prefix(buf,"Subproject commit ", &s) ||4118get_sha1_hex(s, ce->sha1))4119die(_("corrupt patch for submodule%s"), path);4120}else{4121if(!state->cached) {4122if(lstat(path, &st) <0)4123die_errno(_("unable to stat newly created file '%s'"),4124 path);4125fill_stat_cache_info(ce, &st);4126}4127if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4128die(_("unable to create backing store for newly created file%s"), path);4129}4130if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4131die(_("unable to add cache entry for%s"), path);4132}41334134static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4135{4136int fd;4137struct strbuf nbuf = STRBUF_INIT;41384139if(S_ISGITLINK(mode)) {4140struct stat st;4141if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4142return0;4143returnmkdir(path,0777);4144}41454146if(has_symlinks &&S_ISLNK(mode))4147/* Although buf:size is counted string, it also is NUL4148 * terminated.4149 */4150returnsymlink(buf, path);41514152 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4153if(fd <0)4154return-1;41554156if(convert_to_working_tree(path, buf, size, &nbuf)) {4157 size = nbuf.len;4158 buf = nbuf.buf;4159}4160write_or_die(fd, buf, size);4161strbuf_release(&nbuf);41624163if(close(fd) <0)4164die_errno(_("closing file '%s'"), path);4165return0;4166}41674168/*4169 * We optimistically assume that the directories exist,4170 * which is true 99% of the time anyway. If they don't,4171 * we create them and try again.4172 */4173static voidcreate_one_file(struct apply_state *state,4174char*path,4175unsigned mode,4176const char*buf,4177unsigned long size)4178{4179if(state->cached)4180return;4181if(!try_create_file(path, mode, buf, size))4182return;41834184if(errno == ENOENT) {4185if(safe_create_leading_directories(path))4186return;4187if(!try_create_file(path, mode, buf, size))4188return;4189}41904191if(errno == EEXIST || errno == EACCES) {4192/* We may be trying to create a file where a directory4193 * used to be.4194 */4195struct stat st;4196if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4197 errno = EEXIST;4198}41994200if(errno == EEXIST) {4201unsigned int nr =getpid();42024203for(;;) {4204char newpath[PATH_MAX];4205mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4206if(!try_create_file(newpath, mode, buf, size)) {4207if(!rename(newpath, path))4208return;4209unlink_or_warn(newpath);4210break;4211}4212if(errno != EEXIST)4213break;4214++nr;4215}4216}4217die_errno(_("unable to write file '%s' mode%o"), path, mode);4218}42194220static voidadd_conflicted_stages_file(struct apply_state *state,4221struct patch *patch)4222{4223int stage, namelen;4224unsigned ce_size, mode;4225struct cache_entry *ce;42264227if(!state->update_index)4228return;4229 namelen =strlen(patch->new_name);4230 ce_size =cache_entry_size(namelen);4231 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42324233remove_file_from_cache(patch->new_name);4234for(stage =1; stage <4; stage++) {4235if(is_null_oid(&patch->threeway_stage[stage -1]))4236continue;4237 ce =xcalloc(1, ce_size);4238memcpy(ce->name, patch->new_name, namelen);4239 ce->ce_mode =create_ce_mode(mode);4240 ce->ce_flags =create_ce_flags(stage);4241 ce->ce_namelen = namelen;4242hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4243if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4244die(_("unable to add cache entry for%s"), patch->new_name);4245}4246}42474248static voidcreate_file(struct apply_state *state,struct patch *patch)4249{4250char*path = patch->new_name;4251unsigned mode = patch->new_mode;4252unsigned long size = patch->resultsize;4253char*buf = patch->result;42544255if(!mode)4256 mode = S_IFREG |0644;4257create_one_file(state, path, mode, buf, size);42584259if(patch->conflicted_threeway)4260add_conflicted_stages_file(state, patch);4261else4262add_index_file(state, path, mode, buf, size);4263}42644265/* phase zero is to remove, phase one is to create */4266static voidwrite_out_one_result(struct apply_state *state,4267struct patch *patch,4268int phase)4269{4270if(patch->is_delete >0) {4271if(phase ==0)4272remove_file(state, patch,1);4273return;4274}4275if(patch->is_new >0|| patch->is_copy) {4276if(phase ==1)4277create_file(state, patch);4278return;4279}4280/*4281 * Rename or modification boils down to the same4282 * thing: remove the old, write the new4283 */4284if(phase ==0)4285remove_file(state, patch, patch->is_rename);4286if(phase ==1)4287create_file(state, patch);4288}42894290static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4291{4292FILE*rej;4293char namebuf[PATH_MAX];4294struct fragment *frag;4295int cnt =0;4296struct strbuf sb = STRBUF_INIT;42974298for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4299if(!frag->rejected)4300continue;4301 cnt++;4302}43034304if(!cnt) {4305if(state->apply_verbosely)4306say_patch_name(stderr,4307_("Applied patch%scleanly."), patch);4308return0;4309}43104311/* This should not happen, because a removal patch that leaves4312 * contents are marked "rejected" at the patch level.4313 */4314if(!patch->new_name)4315die(_("internal error"));43164317/* Say this even without --verbose */4318strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4319"Applying patch %%swith%drejects...",4320 cnt),4321 cnt);4322say_patch_name(stderr, sb.buf, patch);4323strbuf_release(&sb);43244325 cnt =strlen(patch->new_name);4326if(ARRAY_SIZE(namebuf) <= cnt +5) {4327 cnt =ARRAY_SIZE(namebuf) -5;4328warning(_("truncating .rej filename to %.*s.rej"),4329 cnt -1, patch->new_name);4330}4331memcpy(namebuf, patch->new_name, cnt);4332memcpy(namebuf + cnt,".rej",5);43334334 rej =fopen(namebuf,"w");4335if(!rej)4336returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43374338/* Normal git tools never deal with .rej, so do not pretend4339 * this is a git patch by saying --git or giving extended4340 * headers. While at it, maybe please "kompare" that wants4341 * the trailing TAB and some garbage at the end of line ;-).4342 */4343fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4344 patch->new_name, patch->new_name);4345for(cnt =1, frag = patch->fragments;4346 frag;4347 cnt++, frag = frag->next) {4348if(!frag->rejected) {4349fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4350continue;4351}4352fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4353fprintf(rej,"%.*s", frag->size, frag->patch);4354if(frag->patch[frag->size-1] !='\n')4355fputc('\n', rej);4356}4357fclose(rej);4358return-1;4359}43604361static intwrite_out_results(struct apply_state *state,struct patch *list)4362{4363int phase;4364int errs =0;4365struct patch *l;4366struct string_list cpath = STRING_LIST_INIT_DUP;43674368for(phase =0; phase <2; phase++) {4369 l = list;4370while(l) {4371if(l->rejected)4372 errs =1;4373else{4374write_out_one_result(state, l, phase);4375if(phase ==1) {4376if(write_out_one_reject(state, l))4377 errs =1;4378if(l->conflicted_threeway) {4379string_list_append(&cpath, l->new_name);4380 errs =1;4381}4382}4383}4384 l = l->next;4385}4386}43874388if(cpath.nr) {4389struct string_list_item *item;43904391string_list_sort(&cpath);4392for_each_string_list_item(item, &cpath)4393fprintf(stderr,"U%s\n", item->string);4394string_list_clear(&cpath,0);43954396rerere(0);4397}43984399return errs;4400}44014402static struct lock_file lock_file;44034404#define INACCURATE_EOF (1<<0)4405#define RECOUNT (1<<1)44064407/*4408 * Try to apply a patch.4409 *4410 * Returns:4411 * -128 if a bad error happened (like patch unreadable)4412 * -1 if patch did not apply and user cannot deal with it4413 * 0 if the patch applied4414 * 1 if the patch did not apply but user might fix it4415 */4416static intapply_patch(struct apply_state *state,4417int fd,4418const char*filename,4419int options)4420{4421size_t offset;4422struct strbuf buf = STRBUF_INIT;/* owns the patch text */4423struct patch *list = NULL, **listp = &list;4424int skipped_patch =0;4425int res =0;44264427 state->patch_input_file = filename;4428read_patch_file(&buf, fd);4429 offset =0;4430while(offset < buf.len) {4431struct patch *patch;4432int nr;44334434 patch =xcalloc(1,sizeof(*patch));4435 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4436 patch->recount = !!(options & RECOUNT);4437 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4438if(nr <0) {4439free_patch(patch);4440break;4441}4442if(state->apply_in_reverse)4443reverse_patches(patch);4444if(use_patch(state, patch)) {4445patch_stats(state, patch);4446*listp = patch;4447 listp = &patch->next;4448}4449else{4450if(state->apply_verbosely)4451say_patch_name(stderr,_("Skipped patch '%s'."), patch);4452free_patch(patch);4453 skipped_patch++;4454}4455 offset += nr;4456}44574458if(!list && !skipped_patch) {4459error(_("unrecognized input"));4460 res = -128;4461goto end;4462}44634464if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4465 state->apply =0;44664467 state->update_index = state->check_index && state->apply;4468if(state->update_index && state->newfd <0)4469 state->newfd =hold_locked_index(state->lock_file,1);44704471if(state->check_index &&read_cache() <0) {4472error(_("unable to read index file"));4473 res = -128;4474goto end;4475}44764477if((state->check || state->apply) &&4478check_patch_list(state, list) <0&&4479!state->apply_with_reject) {4480 res = -1;4481goto end;4482}44834484if(state->apply &&write_out_results(state, list)) {4485/* with --3way, we still need to write the index out */4486 res = state->apply_with_reject ? -1:1;4487goto end;4488}44894490if(state->fake_ancestor)4491build_fake_ancestor(list, state->fake_ancestor);44924493if(state->diffstat)4494stat_patch_list(state, list);44954496if(state->numstat)4497numstat_patch_list(state, list);44984499if(state->summary)4500summary_patch_list(list);45014502end:4503free_patch_list(list);4504strbuf_release(&buf);4505string_list_clear(&state->fn_table,0);4506return res;4507}45084509static voidgit_apply_config(void)4510{4511git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4512git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4513git_config(git_default_config, NULL);4514}45154516static intoption_parse_exclude(const struct option *opt,4517const char*arg,int unset)4518{4519struct apply_state *state = opt->value;4520add_name_limit(state, arg,1);4521return0;4522}45234524static intoption_parse_include(const struct option *opt,4525const char*arg,int unset)4526{4527struct apply_state *state = opt->value;4528add_name_limit(state, arg,0);4529 state->has_include =1;4530return0;4531}45324533static intoption_parse_p(const struct option *opt,4534const char*arg,4535int unset)4536{4537struct apply_state *state = opt->value;4538 state->p_value =atoi(arg);4539 state->p_value_known =1;4540return0;4541}45424543static intoption_parse_space_change(const struct option *opt,4544const char*arg,int unset)4545{4546struct apply_state *state = opt->value;4547if(unset)4548 state->ws_ignore_action = ignore_ws_none;4549else4550 state->ws_ignore_action = ignore_ws_change;4551return0;4552}45534554static intoption_parse_whitespace(const struct option *opt,4555const char*arg,int unset)4556{4557struct apply_state *state = opt->value;4558 state->whitespace_option = arg;4559parse_whitespace_option(state, arg);4560return0;4561}45624563static intoption_parse_directory(const struct option *opt,4564const char*arg,int unset)4565{4566struct apply_state *state = opt->value;4567strbuf_reset(&state->root);4568strbuf_addstr(&state->root, arg);4569strbuf_complete(&state->root,'/');4570return0;4571}45724573static voidinit_apply_state(struct apply_state *state,4574const char*prefix,4575struct lock_file *lock_file)4576{4577memset(state,0,sizeof(*state));4578 state->prefix = prefix;4579 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4580 state->lock_file = lock_file;4581 state->newfd = -1;4582 state->apply =1;4583 state->line_termination ='\n';4584 state->p_value =1;4585 state->p_context = UINT_MAX;4586 state->squelch_whitespace_errors =5;4587 state->ws_error_action = warn_on_ws_error;4588 state->ws_ignore_action = ignore_ws_none;4589 state->linenr =1;4590string_list_init(&state->fn_table,0);4591string_list_init(&state->limit_by_name,0);4592string_list_init(&state->symlink_changes,0);4593strbuf_init(&state->root,0);45944595git_apply_config();4596if(apply_default_whitespace)4597parse_whitespace_option(state, apply_default_whitespace);4598if(apply_default_ignorewhitespace)4599parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4600}46014602static voidclear_apply_state(struct apply_state *state)4603{4604string_list_clear(&state->limit_by_name,0);4605string_list_clear(&state->symlink_changes,0);4606strbuf_release(&state->root);46074608/* &state->fn_table is cleared at the end of apply_patch() */4609}46104611static voidcheck_apply_state(struct apply_state *state,int force_apply)4612{4613int is_not_gitdir = !startup_info->have_repository;46144615if(state->apply_with_reject && state->threeway)4616die("--reject and --3way cannot be used together.");4617if(state->cached && state->threeway)4618die("--cached and --3way cannot be used together.");4619if(state->threeway) {4620if(is_not_gitdir)4621die(_("--3way outside a repository"));4622 state->check_index =1;4623}4624if(state->apply_with_reject)4625 state->apply = state->apply_verbosely =1;4626if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4627 state->apply =0;4628if(state->check_index && is_not_gitdir)4629die(_("--index outside a repository"));4630if(state->cached) {4631if(is_not_gitdir)4632die(_("--cached outside a repository"));4633 state->check_index =1;4634}4635if(state->check_index)4636 state->unsafe_paths =0;4637if(!state->lock_file)4638die("BUG: state->lock_file should not be NULL");4639}46404641static intapply_all_patches(struct apply_state *state,4642int argc,4643const char**argv,4644int options)4645{4646int i;4647int res;4648int errs =0;4649int read_stdin =1;46504651for(i =0; i < argc; i++) {4652const char*arg = argv[i];4653int fd;46544655if(!strcmp(arg,"-")) {4656 res =apply_patch(state,0,"<stdin>", options);4657if(res <0)4658goto end;4659 errs |= res;4660 read_stdin =0;4661continue;4662}else if(0< state->prefix_length)4663 arg =prefix_filename(state->prefix,4664 state->prefix_length,4665 arg);46664667 fd =open(arg, O_RDONLY);4668if(fd <0)4669die_errno(_("can't open patch '%s'"), arg);4670 read_stdin =0;4671set_default_whitespace_mode(state);4672 res =apply_patch(state, fd, arg, options);4673if(res <0)4674goto end;4675 errs |= res;4676close(fd);4677}4678set_default_whitespace_mode(state);4679if(read_stdin) {4680 res =apply_patch(state,0,"<stdin>", options);4681if(res <0)4682goto end;4683 errs |= res;4684}46854686if(state->whitespace_error) {4687if(state->squelch_whitespace_errors &&4688 state->squelch_whitespace_errors < state->whitespace_error) {4689int squelched =4690 state->whitespace_error - state->squelch_whitespace_errors;4691warning(Q_("squelched%dwhitespace error",4692"squelched%dwhitespace errors",4693 squelched),4694 squelched);4695}4696if(state->ws_error_action == die_on_ws_error)4697die(Q_("%dline adds whitespace errors.",4698"%dlines add whitespace errors.",4699 state->whitespace_error),4700 state->whitespace_error);4701if(state->applied_after_fixing_ws && state->apply)4702warning("%dline%sapplied after"4703" fixing whitespace errors.",4704 state->applied_after_fixing_ws,4705 state->applied_after_fixing_ws ==1?"":"s");4706else if(state->whitespace_error)4707warning(Q_("%dline adds whitespace errors.",4708"%dlines add whitespace errors.",4709 state->whitespace_error),4710 state->whitespace_error);4711}47124713if(state->update_index) {4714if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4715die(_("Unable to write new index file"));4716 state->newfd = -1;4717}47184719return!!errs;47204721end:4722exit(res == -1?1:128);4723}47244725intcmd_apply(int argc,const char**argv,const char*prefix)4726{4727int force_apply =0;4728int options =0;4729int ret;4730struct apply_state state;47314732struct option builtin_apply_options[] = {4733{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4734N_("don't apply changes matching the given path"),47350, option_parse_exclude },4736{ OPTION_CALLBACK,0,"include", &state,N_("path"),4737N_("apply changes matching the given path"),47380, option_parse_include },4739{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4740N_("remove <num> leading slashes from traditional diff paths"),47410, option_parse_p },4742OPT_BOOL(0,"no-add", &state.no_add,4743N_("ignore additions made by the patch")),4744OPT_BOOL(0,"stat", &state.diffstat,4745N_("instead of applying the patch, output diffstat for the input")),4746OPT_NOOP_NOARG(0,"allow-binary-replacement"),4747OPT_NOOP_NOARG(0,"binary"),4748OPT_BOOL(0,"numstat", &state.numstat,4749N_("show number of added and deleted lines in decimal notation")),4750OPT_BOOL(0,"summary", &state.summary,4751N_("instead of applying the patch, output a summary for the input")),4752OPT_BOOL(0,"check", &state.check,4753N_("instead of applying the patch, see if the patch is applicable")),4754OPT_BOOL(0,"index", &state.check_index,4755N_("make sure the patch is applicable to the current index")),4756OPT_BOOL(0,"cached", &state.cached,4757N_("apply a patch without touching the working tree")),4758OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4759N_("accept a patch that touches outside the working area")),4760OPT_BOOL(0,"apply", &force_apply,4761N_("also apply the patch (use with --stat/--summary/--check)")),4762OPT_BOOL('3',"3way", &state.threeway,4763N_("attempt three-way merge if a patch does not apply")),4764OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4765N_("build a temporary index based on embedded index information")),4766/* Think twice before adding "--nul" synonym to this */4767OPT_SET_INT('z', NULL, &state.line_termination,4768N_("paths are separated with NUL character"),'\0'),4769OPT_INTEGER('C', NULL, &state.p_context,4770N_("ensure at least <n> lines of context match")),4771{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4772N_("detect new or modified lines that have whitespace errors"),47730, option_parse_whitespace },4774{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4775N_("ignore changes in whitespace when finding context"),4776 PARSE_OPT_NOARG, option_parse_space_change },4777{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4778N_("ignore changes in whitespace when finding context"),4779 PARSE_OPT_NOARG, option_parse_space_change },4780OPT_BOOL('R',"reverse", &state.apply_in_reverse,4781N_("apply the patch in reverse")),4782OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4783N_("don't expect at least one line of context")),4784OPT_BOOL(0,"reject", &state.apply_with_reject,4785N_("leave the rejected hunks in corresponding *.rej files")),4786OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4787N_("allow overlapping hunks")),4788OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4789OPT_BIT(0,"inaccurate-eof", &options,4790N_("tolerate incorrectly detected missing new-line at the end of file"),4791 INACCURATE_EOF),4792OPT_BIT(0,"recount", &options,4793N_("do not trust the line counts in the hunk headers"),4794 RECOUNT),4795{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4796N_("prepend <root> to all filenames"),47970, option_parse_directory },4798OPT_END()4799};48004801init_apply_state(&state, prefix, &lock_file);48024803 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4804 apply_usage,0);48054806check_apply_state(&state, force_apply);48074808 ret =apply_all_patches(&state, argc, argv, options);48094810clear_apply_state(&state);48114812return ret;4813}