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 voidset_default_whitespace_mode(struct apply_state *state) 31{ 32if(!state->whitespace_option && !apply_default_whitespace) 33 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 34} 35 36/* 37 * This represents one "hunk" from a patch, starting with 38 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 39 * patch text is pointed at by patch, and its byte length 40 * is stored in size. leading and trailing are the number 41 * of context lines. 42 */ 43struct fragment { 44unsigned long leading, trailing; 45unsigned long oldpos, oldlines; 46unsigned long newpos, newlines; 47/* 48 * 'patch' is usually borrowed from buf in apply_patch(), 49 * but some codepaths store an allocated buffer. 50 */ 51const char*patch; 52unsigned free_patch:1, 53 rejected:1; 54int size; 55int linenr; 56struct fragment *next; 57}; 58 59/* 60 * When dealing with a binary patch, we reuse "leading" field 61 * to store the type of the binary hunk, either deflated "delta" 62 * or deflated "literal". 63 */ 64#define binary_patch_method leading 65#define BINARY_DELTA_DEFLATED 1 66#define BINARY_LITERAL_DEFLATED 2 67 68/* 69 * This represents a "patch" to a file, both metainfo changes 70 * such as creation/deletion, filemode and content changes represented 71 * as a series of fragments. 72 */ 73struct patch { 74char*new_name, *old_name, *def_name; 75unsigned int old_mode, new_mode; 76int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 77int rejected; 78unsigned ws_rule; 79int lines_added, lines_deleted; 80int score; 81unsigned int is_toplevel_relative:1; 82unsigned int inaccurate_eof:1; 83unsigned int is_binary:1; 84unsigned int is_copy:1; 85unsigned int is_rename:1; 86unsigned int recount:1; 87unsigned int conflicted_threeway:1; 88unsigned int direct_to_threeway:1; 89struct fragment *fragments; 90char*result; 91size_t resultsize; 92char old_sha1_prefix[41]; 93char new_sha1_prefix[41]; 94struct patch *next; 95 96/* three-way fallback result */ 97struct object_id threeway_stage[3]; 98}; 99 100static voidfree_fragment_list(struct fragment *list) 101{ 102while(list) { 103struct fragment *next = list->next; 104if(list->free_patch) 105free((char*)list->patch); 106free(list); 107 list = next; 108} 109} 110 111static voidfree_patch(struct patch *patch) 112{ 113free_fragment_list(patch->fragments); 114free(patch->def_name); 115free(patch->old_name); 116free(patch->new_name); 117free(patch->result); 118free(patch); 119} 120 121static voidfree_patch_list(struct patch *list) 122{ 123while(list) { 124struct patch *next = list->next; 125free_patch(list); 126 list = next; 127} 128} 129 130/* 131 * A line in a file, len-bytes long (includes the terminating LF, 132 * except for an incomplete line at the end if the file ends with 133 * one), and its contents hashes to 'hash'. 134 */ 135struct line { 136size_t len; 137unsigned hash :24; 138unsigned flag :8; 139#define LINE_COMMON 1 140#define LINE_PATCHED 2 141}; 142 143/* 144 * This represents a "file", which is an array of "lines". 145 */ 146struct image { 147char*buf; 148size_t len; 149size_t nr; 150size_t alloc; 151struct line *line_allocated; 152struct line *line; 153}; 154 155static uint32_thash_line(const char*cp,size_t len) 156{ 157size_t i; 158uint32_t h; 159for(i =0, h =0; i < len; i++) { 160if(!isspace(cp[i])) { 161 h = h *3+ (cp[i] &0xff); 162} 163} 164return h; 165} 166 167/* 168 * Compare lines s1 of length n1 and s2 of length n2, ignoring 169 * whitespace difference. Returns 1 if they match, 0 otherwise 170 */ 171static intfuzzy_matchlines(const char*s1,size_t n1, 172const char*s2,size_t n2) 173{ 174const char*last1 = s1 + n1 -1; 175const char*last2 = s2 + n2 -1; 176int result =0; 177 178/* ignore line endings */ 179while((*last1 =='\r') || (*last1 =='\n')) 180 last1--; 181while((*last2 =='\r') || (*last2 =='\n')) 182 last2--; 183 184/* skip leading whitespaces, if both begin with whitespace */ 185if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 186while(isspace(*s1) && (s1 <= last1)) 187 s1++; 188while(isspace(*s2) && (s2 <= last2)) 189 s2++; 190} 191/* early return if both lines are empty */ 192if((s1 > last1) && (s2 > last2)) 193return1; 194while(!result) { 195 result = *s1++ - *s2++; 196/* 197 * Skip whitespace inside. We check for whitespace on 198 * both buffers because we don't want "a b" to match 199 * "ab" 200 */ 201if(isspace(*s1) &&isspace(*s2)) { 202while(isspace(*s1) && s1 <= last1) 203 s1++; 204while(isspace(*s2) && s2 <= last2) 205 s2++; 206} 207/* 208 * If we reached the end on one side only, 209 * lines don't match 210 */ 211if( 212((s2 > last2) && (s1 <= last1)) || 213((s1 > last1) && (s2 <= last2))) 214return0; 215if((s1 > last1) && (s2 > last2)) 216break; 217} 218 219return!result; 220} 221 222static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 223{ 224ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 225 img->line_allocated[img->nr].len = len; 226 img->line_allocated[img->nr].hash =hash_line(bol, len); 227 img->line_allocated[img->nr].flag = flag; 228 img->nr++; 229} 230 231/* 232 * "buf" has the file contents to be patched (read from various sources). 233 * attach it to "image" and add line-based index to it. 234 * "image" now owns the "buf". 235 */ 236static voidprepare_image(struct image *image,char*buf,size_t len, 237int prepare_linetable) 238{ 239const char*cp, *ep; 240 241memset(image,0,sizeof(*image)); 242 image->buf = buf; 243 image->len = len; 244 245if(!prepare_linetable) 246return; 247 248 ep = image->buf + image->len; 249 cp = image->buf; 250while(cp < ep) { 251const char*next; 252for(next = cp; next < ep && *next !='\n'; next++) 253; 254if(next < ep) 255 next++; 256add_line_info(image, cp, next - cp,0); 257 cp = next; 258} 259 image->line = image->line_allocated; 260} 261 262static voidclear_image(struct image *image) 263{ 264free(image->buf); 265free(image->line_allocated); 266memset(image,0,sizeof(*image)); 267} 268 269/* fmt must contain _one_ %s and no other substitution */ 270static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 271{ 272struct strbuf sb = STRBUF_INIT; 273 274if(patch->old_name && patch->new_name && 275strcmp(patch->old_name, patch->new_name)) { 276quote_c_style(patch->old_name, &sb, NULL,0); 277strbuf_addstr(&sb," => "); 278quote_c_style(patch->new_name, &sb, NULL,0); 279}else{ 280const char*n = patch->new_name; 281if(!n) 282 n = patch->old_name; 283quote_c_style(n, &sb, NULL,0); 284} 285fprintf(output, fmt, sb.buf); 286fputc('\n', output); 287strbuf_release(&sb); 288} 289 290#define SLOP (16) 291 292static intread_patch_file(struct strbuf *sb,int fd) 293{ 294if(strbuf_read(sb, fd,0) <0) 295returnerror_errno("git apply: failed to read"); 296 297/* 298 * Make sure that we have some slop in the buffer 299 * so that we can do speculative "memcmp" etc, and 300 * see to it that it is NUL-filled. 301 */ 302strbuf_grow(sb, SLOP); 303memset(sb->buf + sb->len,0, SLOP); 304return0; 305} 306 307static unsigned longlinelen(const char*buffer,unsigned long size) 308{ 309unsigned long len =0; 310while(size--) { 311 len++; 312if(*buffer++ =='\n') 313break; 314} 315return len; 316} 317 318static intis_dev_null(const char*str) 319{ 320returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 321} 322 323#define TERM_SPACE 1 324#define TERM_TAB 2 325 326static intname_terminate(int c,int terminate) 327{ 328if(c ==' '&& !(terminate & TERM_SPACE)) 329return0; 330if(c =='\t'&& !(terminate & TERM_TAB)) 331return0; 332 333return1; 334} 335 336/* remove double slashes to make --index work with such filenames */ 337static char*squash_slash(char*name) 338{ 339int i =0, j =0; 340 341if(!name) 342return NULL; 343 344while(name[i]) { 345if((name[j++] = name[i++]) =='/') 346while(name[i] =='/') 347 i++; 348} 349 name[j] ='\0'; 350return name; 351} 352 353static char*find_name_gnu(struct apply_state *state, 354const char*line, 355const char*def, 356int p_value) 357{ 358struct strbuf name = STRBUF_INIT; 359char*cp; 360 361/* 362 * Proposed "new-style" GNU patch/diff format; see 363 * http://marc.info/?l=git&m=112927316408690&w=2 364 */ 365if(unquote_c_style(&name, line, NULL)) { 366strbuf_release(&name); 367return NULL; 368} 369 370for(cp = name.buf; p_value; p_value--) { 371 cp =strchr(cp,'/'); 372if(!cp) { 373strbuf_release(&name); 374return NULL; 375} 376 cp++; 377} 378 379strbuf_remove(&name,0, cp - name.buf); 380if(state->root.len) 381strbuf_insert(&name,0, state->root.buf, state->root.len); 382returnsquash_slash(strbuf_detach(&name, NULL)); 383} 384 385static size_tsane_tz_len(const char*line,size_t len) 386{ 387const char*tz, *p; 388 389if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 390return0; 391 tz = line + len -strlen(" +0500"); 392 393if(tz[1] !='+'&& tz[1] !='-') 394return0; 395 396for(p = tz +2; p != line + len; p++) 397if(!isdigit(*p)) 398return0; 399 400return line + len - tz; 401} 402 403static size_ttz_with_colon_len(const char*line,size_t len) 404{ 405const char*tz, *p; 406 407if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 408return0; 409 tz = line + len -strlen(" +08:00"); 410 411if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 412return0; 413 p = tz +2; 414if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 415!isdigit(*p++) || !isdigit(*p++)) 416return0; 417 418return line + len - tz; 419} 420 421static size_tdate_len(const char*line,size_t len) 422{ 423const char*date, *p; 424 425if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 426return0; 427 p = date = line + len -strlen("72-02-05"); 428 429if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 430!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 431!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 432return0; 433 434if(date - line >=strlen("19") && 435isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 436 date -=strlen("19"); 437 438return line + len - date; 439} 440 441static size_tshort_time_len(const char*line,size_t len) 442{ 443const char*time, *p; 444 445if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 446return0; 447 p = time = line + len -strlen(" 07:01:32"); 448 449/* Permit 1-digit hours? */ 450if(*p++ !=' '|| 451!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 452!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 453!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 454return0; 455 456return line + len - time; 457} 458 459static size_tfractional_time_len(const char*line,size_t len) 460{ 461const char*p; 462size_t n; 463 464/* Expected format: 19:41:17.620000023 */ 465if(!len || !isdigit(line[len -1])) 466return0; 467 p = line + len -1; 468 469/* Fractional seconds. */ 470while(p > line &&isdigit(*p)) 471 p--; 472if(*p !='.') 473return0; 474 475/* Hours, minutes, and whole seconds. */ 476 n =short_time_len(line, p - line); 477if(!n) 478return0; 479 480return line + len - p + n; 481} 482 483static size_ttrailing_spaces_len(const char*line,size_t len) 484{ 485const char*p; 486 487/* Expected format: ' ' x (1 or more) */ 488if(!len || line[len -1] !=' ') 489return0; 490 491 p = line + len; 492while(p != line) { 493 p--; 494if(*p !=' ') 495return line + len - (p +1); 496} 497 498/* All spaces! */ 499return len; 500} 501 502static size_tdiff_timestamp_len(const char*line,size_t len) 503{ 504const char*end = line + len; 505size_t n; 506 507/* 508 * Posix: 2010-07-05 19:41:17 509 * GNU: 2010-07-05 19:41:17.620000023 -0500 510 */ 511 512if(!isdigit(end[-1])) 513return0; 514 515 n =sane_tz_len(line, end - line); 516if(!n) 517 n =tz_with_colon_len(line, end - line); 518 end -= n; 519 520 n =short_time_len(line, end - line); 521if(!n) 522 n =fractional_time_len(line, end - line); 523 end -= n; 524 525 n =date_len(line, end - line); 526if(!n)/* No date. Too bad. */ 527return0; 528 end -= n; 529 530if(end == line)/* No space before date. */ 531return0; 532if(end[-1] =='\t') {/* Success! */ 533 end--; 534return line + len - end; 535} 536if(end[-1] !=' ')/* No space before date. */ 537return0; 538 539/* Whitespace damage. */ 540 end -=trailing_spaces_len(line, end - line); 541return line + len - end; 542} 543 544static char*find_name_common(struct apply_state *state, 545const char*line, 546const char*def, 547int p_value, 548const char*end, 549int terminate) 550{ 551int len; 552const char*start = NULL; 553 554if(p_value ==0) 555 start = line; 556while(line != end) { 557char c = *line; 558 559if(!end &&isspace(c)) { 560if(c =='\n') 561break; 562if(name_terminate(c, terminate)) 563break; 564} 565 line++; 566if(c =='/'&& !--p_value) 567 start = line; 568} 569if(!start) 570returnsquash_slash(xstrdup_or_null(def)); 571 len = line - start; 572if(!len) 573returnsquash_slash(xstrdup_or_null(def)); 574 575/* 576 * Generally we prefer the shorter name, especially 577 * if the other one is just a variation of that with 578 * something else tacked on to the end (ie "file.orig" 579 * or "file~"). 580 */ 581if(def) { 582int deflen =strlen(def); 583if(deflen < len && !strncmp(start, def, deflen)) 584returnsquash_slash(xstrdup(def)); 585} 586 587if(state->root.len) { 588char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 589returnsquash_slash(ret); 590} 591 592returnsquash_slash(xmemdupz(start, len)); 593} 594 595static char*find_name(struct apply_state *state, 596const char*line, 597char*def, 598int p_value, 599int terminate) 600{ 601if(*line =='"') { 602char*name =find_name_gnu(state, line, def, p_value); 603if(name) 604return name; 605} 606 607returnfind_name_common(state, line, def, p_value, NULL, terminate); 608} 609 610static char*find_name_traditional(struct apply_state *state, 611const char*line, 612char*def, 613int p_value) 614{ 615size_t len; 616size_t date_len; 617 618if(*line =='"') { 619char*name =find_name_gnu(state, line, def, p_value); 620if(name) 621return name; 622} 623 624 len =strchrnul(line,'\n') - line; 625 date_len =diff_timestamp_len(line, len); 626if(!date_len) 627returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 628 len -= date_len; 629 630returnfind_name_common(state, line, def, p_value, line + len,0); 631} 632 633static intcount_slashes(const char*cp) 634{ 635int cnt =0; 636char ch; 637 638while((ch = *cp++)) 639if(ch =='/') 640 cnt++; 641return cnt; 642} 643 644/* 645 * Given the string after "--- " or "+++ ", guess the appropriate 646 * p_value for the given patch. 647 */ 648static intguess_p_value(struct apply_state *state,const char*nameline) 649{ 650char*name, *cp; 651int val = -1; 652 653if(is_dev_null(nameline)) 654return-1; 655 name =find_name_traditional(state, nameline, NULL,0); 656if(!name) 657return-1; 658 cp =strchr(name,'/'); 659if(!cp) 660 val =0; 661else if(state->prefix) { 662/* 663 * Does it begin with "a/$our-prefix" and such? Then this is 664 * very likely to apply to our directory. 665 */ 666if(!strncmp(name, state->prefix, state->prefix_length)) 667 val =count_slashes(state->prefix); 668else{ 669 cp++; 670if(!strncmp(cp, state->prefix, state->prefix_length)) 671 val =count_slashes(state->prefix) +1; 672} 673} 674free(name); 675return val; 676} 677 678/* 679 * Does the ---/+++ line have the POSIX timestamp after the last HT? 680 * GNU diff puts epoch there to signal a creation/deletion event. Is 681 * this such a timestamp? 682 */ 683static inthas_epoch_timestamp(const char*nameline) 684{ 685/* 686 * We are only interested in epoch timestamp; any non-zero 687 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 688 * For the same reason, the date must be either 1969-12-31 or 689 * 1970-01-01, and the seconds part must be "00". 690 */ 691const char stamp_regexp[] = 692"^(1969-12-31|1970-01-01)" 693" " 694"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 695" " 696"([-+][0-2][0-9]:?[0-5][0-9])\n"; 697const char*timestamp = NULL, *cp, *colon; 698static regex_t *stamp; 699 regmatch_t m[10]; 700int zoneoffset; 701int hourminute; 702int status; 703 704for(cp = nameline; *cp !='\n'; cp++) { 705if(*cp =='\t') 706 timestamp = cp +1; 707} 708if(!timestamp) 709return0; 710if(!stamp) { 711 stamp =xmalloc(sizeof(*stamp)); 712if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 713warning(_("Cannot prepare timestamp regexp%s"), 714 stamp_regexp); 715return0; 716} 717} 718 719 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 720if(status) { 721if(status != REG_NOMATCH) 722warning(_("regexec returned%dfor input:%s"), 723 status, timestamp); 724return0; 725} 726 727 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 728if(*colon ==':') 729 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 730else 731 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 732if(timestamp[m[3].rm_so] =='-') 733 zoneoffset = -zoneoffset; 734 735/* 736 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 737 * (west of GMT) or 1970-01-01 (east of GMT) 738 */ 739if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 740(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 741return0; 742 743 hourminute = (strtol(timestamp +11, NULL,10) *60+ 744strtol(timestamp +14, NULL,10) - 745 zoneoffset); 746 747return((zoneoffset <0&& hourminute ==1440) || 748(0<= zoneoffset && !hourminute)); 749} 750 751/* 752 * Get the name etc info from the ---/+++ lines of a traditional patch header 753 * 754 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 755 * files, we can happily check the index for a match, but for creating a 756 * new file we should try to match whatever "patch" does. I have no idea. 757 */ 758static intparse_traditional_patch(struct apply_state *state, 759const char*first, 760const char*second, 761struct patch *patch) 762{ 763char*name; 764 765 first +=4;/* skip "--- " */ 766 second +=4;/* skip "+++ " */ 767if(!state->p_value_known) { 768int p, q; 769 p =guess_p_value(state, first); 770 q =guess_p_value(state, second); 771if(p <0) p = q; 772if(0<= p && p == q) { 773 state->p_value = p; 774 state->p_value_known =1; 775} 776} 777if(is_dev_null(first)) { 778 patch->is_new =1; 779 patch->is_delete =0; 780 name =find_name_traditional(state, second, NULL, state->p_value); 781 patch->new_name = name; 782}else if(is_dev_null(second)) { 783 patch->is_new =0; 784 patch->is_delete =1; 785 name =find_name_traditional(state, first, NULL, state->p_value); 786 patch->old_name = name; 787}else{ 788char*first_name; 789 first_name =find_name_traditional(state, first, NULL, state->p_value); 790 name =find_name_traditional(state, second, first_name, state->p_value); 791free(first_name); 792if(has_epoch_timestamp(first)) { 793 patch->is_new =1; 794 patch->is_delete =0; 795 patch->new_name = name; 796}else if(has_epoch_timestamp(second)) { 797 patch->is_new =0; 798 patch->is_delete =1; 799 patch->old_name = name; 800}else{ 801 patch->old_name = name; 802 patch->new_name =xstrdup_or_null(name); 803} 804} 805if(!name) 806returnerror(_("unable to find filename in patch at line%d"), state->linenr); 807 808return0; 809} 810 811static intgitdiff_hdrend(struct apply_state *state, 812const char*line, 813struct patch *patch) 814{ 815return-1; 816} 817 818/* 819 * We're anal about diff header consistency, to make 820 * sure that we don't end up having strange ambiguous 821 * patches floating around. 822 * 823 * As a result, gitdiff_{old|new}name() will check 824 * their names against any previous information, just 825 * to make sure.. 826 */ 827#define DIFF_OLD_NAME 0 828#define DIFF_NEW_NAME 1 829 830static voidgitdiff_verify_name(struct apply_state *state, 831const char*line, 832int isnull, 833char**name, 834int side) 835{ 836if(!*name && !isnull) { 837*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 838return; 839} 840 841if(*name) { 842int len =strlen(*name); 843char*another; 844if(isnull) 845die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 846*name, state->linenr); 847 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 848if(!another ||memcmp(another, *name, len +1)) 849die((side == DIFF_NEW_NAME) ? 850_("git apply: bad git-diff - inconsistent new filename on line%d") : 851_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 852free(another); 853}else{ 854/* expect "/dev/null" */ 855if(memcmp("/dev/null", line,9) || line[9] !='\n') 856die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 857} 858} 859 860static intgitdiff_oldname(struct apply_state *state, 861const char*line, 862struct patch *patch) 863{ 864gitdiff_verify_name(state, line, 865 patch->is_new, &patch->old_name, 866 DIFF_OLD_NAME); 867return0; 868} 869 870static intgitdiff_newname(struct apply_state *state, 871const char*line, 872struct patch *patch) 873{ 874gitdiff_verify_name(state, line, 875 patch->is_delete, &patch->new_name, 876 DIFF_NEW_NAME); 877return0; 878} 879 880static intgitdiff_oldmode(struct apply_state *state, 881const char*line, 882struct patch *patch) 883{ 884 patch->old_mode =strtoul(line, NULL,8); 885return0; 886} 887 888static intgitdiff_newmode(struct apply_state *state, 889const char*line, 890struct patch *patch) 891{ 892 patch->new_mode =strtoul(line, NULL,8); 893return0; 894} 895 896static intgitdiff_delete(struct apply_state *state, 897const char*line, 898struct patch *patch) 899{ 900 patch->is_delete =1; 901free(patch->old_name); 902 patch->old_name =xstrdup_or_null(patch->def_name); 903returngitdiff_oldmode(state, line, patch); 904} 905 906static intgitdiff_newfile(struct apply_state *state, 907const char*line, 908struct patch *patch) 909{ 910 patch->is_new =1; 911free(patch->new_name); 912 patch->new_name =xstrdup_or_null(patch->def_name); 913returngitdiff_newmode(state, line, patch); 914} 915 916static intgitdiff_copysrc(struct apply_state *state, 917const char*line, 918struct patch *patch) 919{ 920 patch->is_copy =1; 921free(patch->old_name); 922 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 923return0; 924} 925 926static intgitdiff_copydst(struct apply_state *state, 927const char*line, 928struct patch *patch) 929{ 930 patch->is_copy =1; 931free(patch->new_name); 932 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 933return0; 934} 935 936static intgitdiff_renamesrc(struct apply_state *state, 937const char*line, 938struct patch *patch) 939{ 940 patch->is_rename =1; 941free(patch->old_name); 942 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 943return0; 944} 945 946static intgitdiff_renamedst(struct apply_state *state, 947const char*line, 948struct patch *patch) 949{ 950 patch->is_rename =1; 951free(patch->new_name); 952 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 953return0; 954} 955 956static intgitdiff_similarity(struct apply_state *state, 957const char*line, 958struct patch *patch) 959{ 960unsigned long val =strtoul(line, NULL,10); 961if(val <=100) 962 patch->score = val; 963return0; 964} 965 966static intgitdiff_dissimilarity(struct apply_state *state, 967const char*line, 968struct patch *patch) 969{ 970unsigned long val =strtoul(line, NULL,10); 971if(val <=100) 972 patch->score = val; 973return0; 974} 975 976static intgitdiff_index(struct apply_state *state, 977const char*line, 978struct patch *patch) 979{ 980/* 981 * index line is N hexadecimal, "..", N hexadecimal, 982 * and optional space with octal mode. 983 */ 984const char*ptr, *eol; 985int len; 986 987 ptr =strchr(line,'.'); 988if(!ptr || ptr[1] !='.'||40< ptr - line) 989return0; 990 len = ptr - line; 991memcpy(patch->old_sha1_prefix, line, len); 992 patch->old_sha1_prefix[len] =0; 993 994 line = ptr +2; 995 ptr =strchr(line,' '); 996 eol =strchrnul(line,'\n'); 997 998if(!ptr || eol < ptr) 999 ptr = eol;1000 len = ptr - line;10011002if(40< len)1003return0;1004memcpy(patch->new_sha1_prefix, line, len);1005 patch->new_sha1_prefix[len] =0;1006if(*ptr ==' ')1007 patch->old_mode =strtoul(ptr+1, NULL,8);1008return0;1009}10101011/*1012 * This is normal for a diff that doesn't change anything: we'll fall through1013 * into the next diff. Tell the parser to break out.1014 */1015static intgitdiff_unrecognized(struct apply_state *state,1016const char*line,1017struct patch *patch)1018{1019return-1;1020}10211022/*1023 * Skip p_value leading components from "line"; as we do not accept1024 * absolute paths, return NULL in that case.1025 */1026static const char*skip_tree_prefix(struct apply_state *state,1027const char*line,1028int llen)1029{1030int nslash;1031int i;10321033if(!state->p_value)1034return(llen && line[0] =='/') ? NULL : line;10351036 nslash = state->p_value;1037for(i =0; i < llen; i++) {1038int ch = line[i];1039if(ch =='/'&& --nslash <=0)1040return(i ==0) ? NULL : &line[i +1];1041}1042return NULL;1043}10441045/*1046 * This is to extract the same name that appears on "diff --git"1047 * line. We do not find and return anything if it is a rename1048 * patch, and it is OK because we will find the name elsewhere.1049 * We need to reliably find name only when it is mode-change only,1050 * creation or deletion of an empty file. In any of these cases,1051 * both sides are the same name under a/ and b/ respectively.1052 */1053static char*git_header_name(struct apply_state *state,1054const char*line,1055int llen)1056{1057const char*name;1058const char*second = NULL;1059size_t len, line_len;10601061 line +=strlen("diff --git ");1062 llen -=strlen("diff --git ");10631064if(*line =='"') {1065const char*cp;1066struct strbuf first = STRBUF_INIT;1067struct strbuf sp = STRBUF_INIT;10681069if(unquote_c_style(&first, line, &second))1070goto free_and_fail1;10711072/* strip the a/b prefix including trailing slash */1073 cp =skip_tree_prefix(state, first.buf, first.len);1074if(!cp)1075goto free_and_fail1;1076strbuf_remove(&first,0, cp - first.buf);10771078/*1079 * second points at one past closing dq of name.1080 * find the second name.1081 */1082while((second < line + llen) &&isspace(*second))1083 second++;10841085if(line + llen <= second)1086goto free_and_fail1;1087if(*second =='"') {1088if(unquote_c_style(&sp, second, NULL))1089goto free_and_fail1;1090 cp =skip_tree_prefix(state, sp.buf, sp.len);1091if(!cp)1092goto free_and_fail1;1093/* They must match, otherwise ignore */1094if(strcmp(cp, first.buf))1095goto free_and_fail1;1096strbuf_release(&sp);1097returnstrbuf_detach(&first, NULL);1098}10991100/* unquoted second */1101 cp =skip_tree_prefix(state, second, line + llen - second);1102if(!cp)1103goto free_and_fail1;1104if(line + llen - cp != first.len ||1105memcmp(first.buf, cp, first.len))1106goto free_and_fail1;1107returnstrbuf_detach(&first, NULL);11081109 free_and_fail1:1110strbuf_release(&first);1111strbuf_release(&sp);1112return NULL;1113}11141115/* unquoted first name */1116 name =skip_tree_prefix(state, line, llen);1117if(!name)1118return NULL;11191120/*1121 * since the first name is unquoted, a dq if exists must be1122 * the beginning of the second name.1123 */1124for(second = name; second < line + llen; second++) {1125if(*second =='"') {1126struct strbuf sp = STRBUF_INIT;1127const char*np;11281129if(unquote_c_style(&sp, second, NULL))1130goto free_and_fail2;11311132 np =skip_tree_prefix(state, sp.buf, sp.len);1133if(!np)1134goto free_and_fail2;11351136 len = sp.buf + sp.len - np;1137if(len < second - name &&1138!strncmp(np, name, len) &&1139isspace(name[len])) {1140/* Good */1141strbuf_remove(&sp,0, np - sp.buf);1142returnstrbuf_detach(&sp, NULL);1143}11441145 free_and_fail2:1146strbuf_release(&sp);1147return NULL;1148}1149}11501151/*1152 * Accept a name only if it shows up twice, exactly the same1153 * form.1154 */1155 second =strchr(name,'\n');1156if(!second)1157return NULL;1158 line_len = second - name;1159for(len =0; ; len++) {1160switch(name[len]) {1161default:1162continue;1163case'\n':1164return NULL;1165case'\t':case' ':1166/*1167 * Is this the separator between the preimage1168 * and the postimage pathname? Again, we are1169 * only interested in the case where there is1170 * no rename, as this is only to set def_name1171 * and a rename patch has the names elsewhere1172 * in an unambiguous form.1173 */1174if(!name[len +1])1175return NULL;/* no postimage name */1176 second =skip_tree_prefix(state, name + len +1,1177 line_len - (len +1));1178if(!second)1179return NULL;1180/*1181 * Does len bytes starting at "name" and "second"1182 * (that are separated by one HT or SP we just1183 * found) exactly match?1184 */1185if(second[len] =='\n'&& !strncmp(name, second, len))1186returnxmemdupz(name, len);1187}1188}1189}11901191/* Verify that we recognize the lines following a git header */1192static intparse_git_header(struct apply_state *state,1193const char*line,1194int len,1195unsigned int size,1196struct patch *patch)1197{1198unsigned long offset;11991200/* A git diff has explicit new/delete information, so we don't guess */1201 patch->is_new =0;1202 patch->is_delete =0;12031204/*1205 * Some things may not have the old name in the1206 * rest of the headers anywhere (pure mode changes,1207 * or removing or adding empty files), so we get1208 * the default name from the header.1209 */1210 patch->def_name =git_header_name(state, line, len);1211if(patch->def_name && state->root.len) {1212char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1213free(patch->def_name);1214 patch->def_name = s;1215}12161217 line += len;1218 size -= len;1219 state->linenr++;1220for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1221static const struct opentry {1222const char*str;1223int(*fn)(struct apply_state *,const char*,struct patch *);1224} optable[] = {1225{"@@ -", gitdiff_hdrend },1226{"--- ", gitdiff_oldname },1227{"+++ ", gitdiff_newname },1228{"old mode ", gitdiff_oldmode },1229{"new mode ", gitdiff_newmode },1230{"deleted file mode ", gitdiff_delete },1231{"new file mode ", gitdiff_newfile },1232{"copy from ", gitdiff_copysrc },1233{"copy to ", gitdiff_copydst },1234{"rename old ", gitdiff_renamesrc },1235{"rename new ", gitdiff_renamedst },1236{"rename from ", gitdiff_renamesrc },1237{"rename to ", gitdiff_renamedst },1238{"similarity index ", gitdiff_similarity },1239{"dissimilarity index ", gitdiff_dissimilarity },1240{"index ", gitdiff_index },1241{"", gitdiff_unrecognized },1242};1243int i;12441245 len =linelen(line, size);1246if(!len || line[len-1] !='\n')1247break;1248for(i =0; i <ARRAY_SIZE(optable); i++) {1249const struct opentry *p = optable + i;1250int oplen =strlen(p->str);1251if(len < oplen ||memcmp(p->str, line, oplen))1252continue;1253if(p->fn(state, line + oplen, patch) <0)1254return offset;1255break;1256}1257}12581259return offset;1260}12611262static intparse_num(const char*line,unsigned long*p)1263{1264char*ptr;12651266if(!isdigit(*line))1267return0;1268*p =strtoul(line, &ptr,10);1269return ptr - line;1270}12711272static intparse_range(const char*line,int len,int offset,const char*expect,1273unsigned long*p1,unsigned long*p2)1274{1275int digits, ex;12761277if(offset <0|| offset >= len)1278return-1;1279 line += offset;1280 len -= offset;12811282 digits =parse_num(line, p1);1283if(!digits)1284return-1;12851286 offset += digits;1287 line += digits;1288 len -= digits;12891290*p2 =1;1291if(*line ==',') {1292 digits =parse_num(line+1, p2);1293if(!digits)1294return-1;12951296 offset += digits+1;1297 line += digits+1;1298 len -= digits+1;1299}13001301 ex =strlen(expect);1302if(ex > len)1303return-1;1304if(memcmp(line, expect, ex))1305return-1;13061307return offset + ex;1308}13091310static voidrecount_diff(const char*line,int size,struct fragment *fragment)1311{1312int oldlines =0, newlines =0, ret =0;13131314if(size <1) {1315warning("recount: ignore empty hunk");1316return;1317}13181319for(;;) {1320int len =linelen(line, size);1321 size -= len;1322 line += len;13231324if(size <1)1325break;13261327switch(*line) {1328case' ':case'\n':1329 newlines++;1330/* fall through */1331case'-':1332 oldlines++;1333continue;1334case'+':1335 newlines++;1336continue;1337case'\\':1338continue;1339case'@':1340 ret = size <3|| !starts_with(line,"@@ ");1341break;1342case'd':1343 ret = size <5|| !starts_with(line,"diff ");1344break;1345default:1346 ret = -1;1347break;1348}1349if(ret) {1350warning(_("recount: unexpected line: %.*s"),1351(int)linelen(line, size), line);1352return;1353}1354break;1355}1356 fragment->oldlines = oldlines;1357 fragment->newlines = newlines;1358}13591360/*1361 * Parse a unified diff fragment header of the1362 * form "@@ -a,b +c,d @@"1363 */1364static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1365{1366int offset;13671368if(!len || line[len-1] !='\n')1369return-1;13701371/* Figure out the number of lines in a fragment */1372 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1373 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13741375return offset;1376}13771378/*1379 * Find file diff header1380 *1381 * Returns:1382 * -1 if no header was found1383 * -128 in case of error1384 * the size of the header in bytes (called "offset") otherwise1385 */1386static intfind_header(struct apply_state *state,1387const char*line,1388unsigned long size,1389int*hdrsize,1390struct patch *patch)1391{1392unsigned long offset, len;13931394 patch->is_toplevel_relative =0;1395 patch->is_rename = patch->is_copy =0;1396 patch->is_new = patch->is_delete = -1;1397 patch->old_mode = patch->new_mode =0;1398 patch->old_name = patch->new_name = NULL;1399for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1400unsigned long nextlen;14011402 len =linelen(line, size);1403if(!len)1404break;14051406/* Testing this early allows us to take a few shortcuts.. */1407if(len <6)1408continue;14091410/*1411 * Make sure we don't find any unconnected patch fragments.1412 * That's a sign that we didn't find a header, and that a1413 * patch has become corrupted/broken up.1414 */1415if(!memcmp("@@ -", line,4)) {1416struct fragment dummy;1417if(parse_fragment_header(line, len, &dummy) <0)1418continue;1419error(_("patch fragment without header at line%d: %.*s"),1420 state->linenr, (int)len-1, line);1421return-128;1422}14231424if(size < len +6)1425break;14261427/*1428 * Git patch? It might not have a real patch, just a rename1429 * or mode change, so we handle that specially1430 */1431if(!memcmp("diff --git ", line,11)) {1432int git_hdr_len =parse_git_header(state, line, len, size, patch);1433if(git_hdr_len <= len)1434continue;1435if(!patch->old_name && !patch->new_name) {1436if(!patch->def_name) {1437error(Q_("git diff header lacks filename information when removing "1438"%dleading pathname component (line%d)",1439"git diff header lacks filename information when removing "1440"%dleading pathname components (line%d)",1441 state->p_value),1442 state->p_value, state->linenr);1443return-128;1444}1445 patch->old_name =xstrdup(patch->def_name);1446 patch->new_name =xstrdup(patch->def_name);1447}1448if(!patch->is_delete && !patch->new_name) {1449error("git diff header lacks filename information "1450"(line%d)", state->linenr);1451return-128;1452}1453 patch->is_toplevel_relative =1;1454*hdrsize = git_hdr_len;1455return offset;1456}14571458/* --- followed by +++ ? */1459if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1460continue;14611462/*1463 * We only accept unified patches, so we want it to1464 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1465 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1466 */1467 nextlen =linelen(line + len, size - len);1468if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1469continue;14701471/* Ok, we'll consider it a patch */1472if(parse_traditional_patch(state, line, line+len, patch))1473return-128;1474*hdrsize = len + nextlen;1475 state->linenr +=2;1476return offset;1477}1478return-1;1479}14801481static voidrecord_ws_error(struct apply_state *state,1482unsigned result,1483const char*line,1484int len,1485int linenr)1486{1487char*err;14881489if(!result)1490return;14911492 state->whitespace_error++;1493if(state->squelch_whitespace_errors &&1494 state->squelch_whitespace_errors < state->whitespace_error)1495return;14961497 err =whitespace_error_string(result);1498fprintf(stderr,"%s:%d:%s.\n%.*s\n",1499 state->patch_input_file, linenr, err, len, line);1500free(err);1501}15021503static voidcheck_whitespace(struct apply_state *state,1504const char*line,1505int len,1506unsigned ws_rule)1507{1508unsigned result =ws_check(line +1, len -1, ws_rule);15091510record_ws_error(state, result, line +1, len -2, state->linenr);1511}15121513/*1514 * Parse a unified diff. Note that this really needs to parse each1515 * fragment separately, since the only way to know the difference1516 * between a "---" that is part of a patch, and a "---" that starts1517 * the next patch is to look at the line counts..1518 */1519static intparse_fragment(struct apply_state *state,1520const char*line,1521unsigned long size,1522struct patch *patch,1523struct fragment *fragment)1524{1525int added, deleted;1526int len =linelen(line, size), offset;1527unsigned long oldlines, newlines;1528unsigned long leading, trailing;15291530 offset =parse_fragment_header(line, len, fragment);1531if(offset <0)1532return-1;1533if(offset >0&& patch->recount)1534recount_diff(line + offset, size - offset, fragment);1535 oldlines = fragment->oldlines;1536 newlines = fragment->newlines;1537 leading =0;1538 trailing =0;15391540/* Parse the thing.. */1541 line += len;1542 size -= len;1543 state->linenr++;1544 added = deleted =0;1545for(offset = len;15460< size;1547 offset += len, size -= len, line += len, state->linenr++) {1548if(!oldlines && !newlines)1549break;1550 len =linelen(line, size);1551if(!len || line[len-1] !='\n')1552return-1;1553switch(*line) {1554default:1555return-1;1556case'\n':/* newer GNU diff, an empty context line */1557case' ':1558 oldlines--;1559 newlines--;1560if(!deleted && !added)1561 leading++;1562 trailing++;1563if(!state->apply_in_reverse &&1564 state->ws_error_action == correct_ws_error)1565check_whitespace(state, line, len, patch->ws_rule);1566break;1567case'-':1568if(state->apply_in_reverse &&1569 state->ws_error_action != nowarn_ws_error)1570check_whitespace(state, line, len, patch->ws_rule);1571 deleted++;1572 oldlines--;1573 trailing =0;1574break;1575case'+':1576if(!state->apply_in_reverse &&1577 state->ws_error_action != nowarn_ws_error)1578check_whitespace(state, line, len, patch->ws_rule);1579 added++;1580 newlines--;1581 trailing =0;1582break;15831584/*1585 * We allow "\ No newline at end of file". Depending1586 * on locale settings when the patch was produced we1587 * don't know what this line looks like. The only1588 * thing we do know is that it begins with "\ ".1589 * Checking for 12 is just for sanity check -- any1590 * l10n of "\ No newline..." is at least that long.1591 */1592case'\\':1593if(len <12||memcmp(line,"\\",2))1594return-1;1595break;1596}1597}1598if(oldlines || newlines)1599return-1;1600if(!deleted && !added)1601return-1;16021603 fragment->leading = leading;1604 fragment->trailing = trailing;16051606/*1607 * If a fragment ends with an incomplete line, we failed to include1608 * it in the above loop because we hit oldlines == newlines == 01609 * before seeing it.1610 */1611if(12< size && !memcmp(line,"\\",2))1612 offset +=linelen(line, size);16131614 patch->lines_added += added;1615 patch->lines_deleted += deleted;16161617if(0< patch->is_new && oldlines)1618returnerror(_("new file depends on old contents"));1619if(0< patch->is_delete && newlines)1620returnerror(_("deleted file still has contents"));1621return offset;1622}16231624/*1625 * We have seen "diff --git a/... b/..." header (or a traditional patch1626 * header). Read hunks that belong to this patch into fragments and hang1627 * them to the given patch structure.1628 *1629 * The (fragment->patch, fragment->size) pair points into the memory given1630 * by the caller, not a copy, when we return.1631 *1632 * Returns:1633 * -1 in case of error,1634 * the number of bytes in the patch otherwise.1635 */1636static intparse_single_patch(struct apply_state *state,1637const char*line,1638unsigned long size,1639struct patch *patch)1640{1641unsigned long offset =0;1642unsigned long oldlines =0, newlines =0, context =0;1643struct fragment **fragp = &patch->fragments;16441645while(size >4&& !memcmp(line,"@@ -",4)) {1646struct fragment *fragment;1647int len;16481649 fragment =xcalloc(1,sizeof(*fragment));1650 fragment->linenr = state->linenr;1651 len =parse_fragment(state, line, size, patch, fragment);1652if(len <=0) {1653free(fragment);1654returnerror(_("corrupt patch at line%d"), state->linenr);1655}1656 fragment->patch = line;1657 fragment->size = len;1658 oldlines += fragment->oldlines;1659 newlines += fragment->newlines;1660 context += fragment->leading + fragment->trailing;16611662*fragp = fragment;1663 fragp = &fragment->next;16641665 offset += len;1666 line += len;1667 size -= len;1668}16691670/*1671 * If something was removed (i.e. we have old-lines) it cannot1672 * be creation, and if something was added it cannot be1673 * deletion. However, the reverse is not true; --unified=01674 * patches that only add are not necessarily creation even1675 * though they do not have any old lines, and ones that only1676 * delete are not necessarily deletion.1677 *1678 * Unfortunately, a real creation/deletion patch do _not_ have1679 * any context line by definition, so we cannot safely tell it1680 * apart with --unified=0 insanity. At least if the patch has1681 * more than one hunk it is not creation or deletion.1682 */1683if(patch->is_new <0&&1684(oldlines || (patch->fragments && patch->fragments->next)))1685 patch->is_new =0;1686if(patch->is_delete <0&&1687(newlines || (patch->fragments && patch->fragments->next)))1688 patch->is_delete =0;16891690if(0< patch->is_new && oldlines)1691returnerror(_("new file%sdepends on old contents"), patch->new_name);1692if(0< patch->is_delete && newlines)1693returnerror(_("deleted file%sstill has contents"), patch->old_name);1694if(!patch->is_delete && !newlines && context)1695fprintf_ln(stderr,1696_("** warning: "1697"file%sbecomes empty but is not deleted"),1698 patch->new_name);16991700return offset;1701}17021703staticinlineintmetadata_changes(struct patch *patch)1704{1705return patch->is_rename >0||1706 patch->is_copy >0||1707 patch->is_new >0||1708 patch->is_delete ||1709(patch->old_mode && patch->new_mode &&1710 patch->old_mode != patch->new_mode);1711}17121713static char*inflate_it(const void*data,unsigned long size,1714unsigned long inflated_size)1715{1716 git_zstream stream;1717void*out;1718int st;17191720memset(&stream,0,sizeof(stream));17211722 stream.next_in = (unsigned char*)data;1723 stream.avail_in = size;1724 stream.next_out = out =xmalloc(inflated_size);1725 stream.avail_out = inflated_size;1726git_inflate_init(&stream);1727 st =git_inflate(&stream, Z_FINISH);1728git_inflate_end(&stream);1729if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1730free(out);1731return NULL;1732}1733return out;1734}17351736/*1737 * Read a binary hunk and return a new fragment; fragment->patch1738 * points at an allocated memory that the caller must free, so1739 * it is marked as "->free_patch = 1".1740 */1741static struct fragment *parse_binary_hunk(struct apply_state *state,1742char**buf_p,1743unsigned long*sz_p,1744int*status_p,1745int*used_p)1746{1747/*1748 * Expect a line that begins with binary patch method ("literal"1749 * or "delta"), followed by the length of data before deflating.1750 * a sequence of 'length-byte' followed by base-85 encoded data1751 * should follow, terminated by a newline.1752 *1753 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1754 * and we would limit the patch line to 66 characters,1755 * so one line can fit up to 13 groups that would decode1756 * to 52 bytes max. The length byte 'A'-'Z' corresponds1757 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1758 */1759int llen, used;1760unsigned long size = *sz_p;1761char*buffer = *buf_p;1762int patch_method;1763unsigned long origlen;1764char*data = NULL;1765int hunk_size =0;1766struct fragment *frag;17671768 llen =linelen(buffer, size);1769 used = llen;17701771*status_p =0;17721773if(starts_with(buffer,"delta ")) {1774 patch_method = BINARY_DELTA_DEFLATED;1775 origlen =strtoul(buffer +6, NULL,10);1776}1777else if(starts_with(buffer,"literal ")) {1778 patch_method = BINARY_LITERAL_DEFLATED;1779 origlen =strtoul(buffer +8, NULL,10);1780}1781else1782return NULL;17831784 state->linenr++;1785 buffer += llen;1786while(1) {1787int byte_length, max_byte_length, newsize;1788 llen =linelen(buffer, size);1789 used += llen;1790 state->linenr++;1791if(llen ==1) {1792/* consume the blank line */1793 buffer++;1794 size--;1795break;1796}1797/*1798 * Minimum line is "A00000\n" which is 7-byte long,1799 * and the line length must be multiple of 5 plus 2.1800 */1801if((llen <7) || (llen-2) %5)1802goto corrupt;1803 max_byte_length = (llen -2) /5*4;1804 byte_length = *buffer;1805if('A'<= byte_length && byte_length <='Z')1806 byte_length = byte_length -'A'+1;1807else if('a'<= byte_length && byte_length <='z')1808 byte_length = byte_length -'a'+27;1809else1810goto corrupt;1811/* if the input length was not multiple of 4, we would1812 * have filler at the end but the filler should never1813 * exceed 3 bytes1814 */1815if(max_byte_length < byte_length ||1816 byte_length <= max_byte_length -4)1817goto corrupt;1818 newsize = hunk_size + byte_length;1819 data =xrealloc(data, newsize);1820if(decode_85(data + hunk_size, buffer +1, byte_length))1821goto corrupt;1822 hunk_size = newsize;1823 buffer += llen;1824 size -= llen;1825}18261827 frag =xcalloc(1,sizeof(*frag));1828 frag->patch =inflate_it(data, hunk_size, origlen);1829 frag->free_patch =1;1830if(!frag->patch)1831goto corrupt;1832free(data);1833 frag->size = origlen;1834*buf_p = buffer;1835*sz_p = size;1836*used_p = used;1837 frag->binary_patch_method = patch_method;1838return frag;18391840 corrupt:1841free(data);1842*status_p = -1;1843error(_("corrupt binary patch at line%d: %.*s"),1844 state->linenr-1, llen-1, buffer);1845return NULL;1846}18471848/*1849 * Returns:1850 * -1 in case of error,1851 * the length of the parsed binary patch otherwise1852 */1853static intparse_binary(struct apply_state *state,1854char*buffer,1855unsigned long size,1856struct patch *patch)1857{1858/*1859 * We have read "GIT binary patch\n"; what follows is a line1860 * that says the patch method (currently, either "literal" or1861 * "delta") and the length of data before deflating; a1862 * sequence of 'length-byte' followed by base-85 encoded data1863 * follows.1864 *1865 * When a binary patch is reversible, there is another binary1866 * hunk in the same format, starting with patch method (either1867 * "literal" or "delta") with the length of data, and a sequence1868 * of length-byte + base-85 encoded data, terminated with another1869 * empty line. This data, when applied to the postimage, produces1870 * the preimage.1871 */1872struct fragment *forward;1873struct fragment *reverse;1874int status;1875int used, used_1;18761877 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1878if(!forward && !status)1879/* there has to be one hunk (forward hunk) */1880returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1881if(status)1882/* otherwise we already gave an error message */1883return status;18841885 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1886if(reverse)1887 used += used_1;1888else if(status) {1889/*1890 * Not having reverse hunk is not an error, but having1891 * a corrupt reverse hunk is.1892 */1893free((void*) forward->patch);1894free(forward);1895return status;1896}1897 forward->next = reverse;1898 patch->fragments = forward;1899 patch->is_binary =1;1900return used;1901}19021903static voidprefix_one(struct apply_state *state,char**name)1904{1905char*old_name = *name;1906if(!old_name)1907return;1908*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1909free(old_name);1910}19111912static voidprefix_patch(struct apply_state *state,struct patch *p)1913{1914if(!state->prefix || p->is_toplevel_relative)1915return;1916prefix_one(state, &p->new_name);1917prefix_one(state, &p->old_name);1918}19191920/*1921 * include/exclude1922 */19231924static voidadd_name_limit(struct apply_state *state,1925const char*name,1926int exclude)1927{1928struct string_list_item *it;19291930 it =string_list_append(&state->limit_by_name, name);1931 it->util = exclude ? NULL : (void*)1;1932}19331934static intuse_patch(struct apply_state *state,struct patch *p)1935{1936const char*pathname = p->new_name ? p->new_name : p->old_name;1937int i;19381939/* Paths outside are not touched regardless of "--include" */1940if(0< state->prefix_length) {1941int pathlen =strlen(pathname);1942if(pathlen <= state->prefix_length ||1943memcmp(state->prefix, pathname, state->prefix_length))1944return0;1945}19461947/* See if it matches any of exclude/include rule */1948for(i =0; i < state->limit_by_name.nr; i++) {1949struct string_list_item *it = &state->limit_by_name.items[i];1950if(!wildmatch(it->string, pathname,0, NULL))1951return(it->util != NULL);1952}19531954/*1955 * If we had any include, a path that does not match any rule is1956 * not used. Otherwise, we saw bunch of exclude rules (or none)1957 * and such a path is used.1958 */1959return!state->has_include;1960}19611962/*1963 * Read the patch text in "buffer" that extends for "size" bytes; stop1964 * reading after seeing a single patch (i.e. changes to a single file).1965 * Create fragments (i.e. patch hunks) and hang them to the given patch.1966 *1967 * Returns:1968 * -1 if no header was found or parse_binary() failed,1969 * -128 on another error,1970 * the number of bytes consumed otherwise,1971 * so that the caller can call us again for the next patch.1972 */1973static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1974{1975int hdrsize, patchsize;1976int offset =find_header(state, buffer, size, &hdrsize, patch);19771978if(offset <0)1979return offset;19801981prefix_patch(state, patch);19821983if(!use_patch(state, patch))1984 patch->ws_rule =0;1985else1986 patch->ws_rule =whitespace_rule(patch->new_name1987? patch->new_name1988: patch->old_name);19891990 patchsize =parse_single_patch(state,1991 buffer + offset + hdrsize,1992 size - offset - hdrsize,1993 patch);19941995if(patchsize <0)1996return-128;19971998if(!patchsize) {1999static const char git_binary[] ="GIT binary patch\n";2000int hd = hdrsize + offset;2001unsigned long llen =linelen(buffer + hd, size - hd);20022003if(llen ==sizeof(git_binary) -1&&2004!memcmp(git_binary, buffer + hd, llen)) {2005int used;2006 state->linenr++;2007 used =parse_binary(state, buffer + hd + llen,2008 size - hd - llen, patch);2009if(used <0)2010return-1;2011if(used)2012 patchsize = used + llen;2013else2014 patchsize =0;2015}2016else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2017static const char*binhdr[] = {2018"Binary files ",2019"Files ",2020 NULL,2021};2022int i;2023for(i =0; binhdr[i]; i++) {2024int len =strlen(binhdr[i]);2025if(len < size - hd &&2026!memcmp(binhdr[i], buffer + hd, len)) {2027 state->linenr++;2028 patch->is_binary =1;2029 patchsize = llen;2030break;2031}2032}2033}20342035/* Empty patch cannot be applied if it is a text patch2036 * without metadata change. A binary patch appears2037 * empty to us here.2038 */2039if((state->apply || state->check) &&2040(!patch->is_binary && !metadata_changes(patch))) {2041error(_("patch with only garbage at line%d"), state->linenr);2042return-128;2043}2044}20452046return offset + hdrsize + patchsize;2047}20482049#define swap(a,b) myswap((a),(b),sizeof(a))20502051#define myswap(a, b, size) do { \2052 unsigned char mytmp[size]; \2053 memcpy(mytmp, &a, size); \2054 memcpy(&a, &b, size); \2055 memcpy(&b, mytmp, size); \2056} while (0)20572058static voidreverse_patches(struct patch *p)2059{2060for(; p; p = p->next) {2061struct fragment *frag = p->fragments;20622063swap(p->new_name, p->old_name);2064swap(p->new_mode, p->old_mode);2065swap(p->is_new, p->is_delete);2066swap(p->lines_added, p->lines_deleted);2067swap(p->old_sha1_prefix, p->new_sha1_prefix);20682069for(; frag; frag = frag->next) {2070swap(frag->newpos, frag->oldpos);2071swap(frag->newlines, frag->oldlines);2072}2073}2074}20752076static const char pluses[] =2077"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2078static const char minuses[]=2079"----------------------------------------------------------------------";20802081static voidshow_stats(struct apply_state *state,struct patch *patch)2082{2083struct strbuf qname = STRBUF_INIT;2084char*cp = patch->new_name ? patch->new_name : patch->old_name;2085int max, add, del;20862087quote_c_style(cp, &qname, NULL,0);20882089/*2090 * "scale" the filename2091 */2092 max = state->max_len;2093if(max >50)2094 max =50;20952096if(qname.len > max) {2097 cp =strchr(qname.buf + qname.len +3- max,'/');2098if(!cp)2099 cp = qname.buf + qname.len +3- max;2100strbuf_splice(&qname,0, cp - qname.buf,"...",3);2101}21022103if(patch->is_binary) {2104printf(" %-*s | Bin\n", max, qname.buf);2105strbuf_release(&qname);2106return;2107}21082109printf(" %-*s |", max, qname.buf);2110strbuf_release(&qname);21112112/*2113 * scale the add/delete2114 */2115 max = max + state->max_change >70?70- max : state->max_change;2116 add = patch->lines_added;2117 del = patch->lines_deleted;21182119if(state->max_change >0) {2120int total = ((add + del) * max + state->max_change /2) / state->max_change;2121 add = (add * max + state->max_change /2) / state->max_change;2122 del = total - add;2123}2124printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2125 add, pluses, del, minuses);2126}21272128static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2129{2130switch(st->st_mode & S_IFMT) {2131case S_IFLNK:2132if(strbuf_readlink(buf, path, st->st_size) <0)2133returnerror(_("unable to read symlink%s"), path);2134return0;2135case S_IFREG:2136if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2137returnerror(_("unable to open or read%s"), path);2138convert_to_git(path, buf->buf, buf->len, buf,0);2139return0;2140default:2141return-1;2142}2143}21442145/*2146 * Update the preimage, and the common lines in postimage,2147 * from buffer buf of length len. If postlen is 0 the postimage2148 * is updated in place, otherwise it's updated on a new buffer2149 * of length postlen2150 */21512152static voidupdate_pre_post_images(struct image *preimage,2153struct image *postimage,2154char*buf,2155size_t len,size_t postlen)2156{2157int i, ctx, reduced;2158char*new, *old, *fixed;2159struct image fixed_preimage;21602161/*2162 * Update the preimage with whitespace fixes. Note that we2163 * are not losing preimage->buf -- apply_one_fragment() will2164 * free "oldlines".2165 */2166prepare_image(&fixed_preimage, buf, len,1);2167assert(postlen2168? fixed_preimage.nr == preimage->nr2169: fixed_preimage.nr <= preimage->nr);2170for(i =0; i < fixed_preimage.nr; i++)2171 fixed_preimage.line[i].flag = preimage->line[i].flag;2172free(preimage->line_allocated);2173*preimage = fixed_preimage;21742175/*2176 * Adjust the common context lines in postimage. This can be2177 * done in-place when we are shrinking it with whitespace2178 * fixing, but needs a new buffer when ignoring whitespace or2179 * expanding leading tabs to spaces.2180 *2181 * We trust the caller to tell us if the update can be done2182 * in place (postlen==0) or not.2183 */2184 old = postimage->buf;2185if(postlen)2186new= postimage->buf =xmalloc(postlen);2187else2188new= old;2189 fixed = preimage->buf;21902191for(i = reduced = ctx =0; i < postimage->nr; i++) {2192size_t l_len = postimage->line[i].len;2193if(!(postimage->line[i].flag & LINE_COMMON)) {2194/* an added line -- no counterparts in preimage */2195memmove(new, old, l_len);2196 old += l_len;2197new+= l_len;2198continue;2199}22002201/* a common context -- skip it in the original postimage */2202 old += l_len;22032204/* and find the corresponding one in the fixed preimage */2205while(ctx < preimage->nr &&2206!(preimage->line[ctx].flag & LINE_COMMON)) {2207 fixed += preimage->line[ctx].len;2208 ctx++;2209}22102211/*2212 * preimage is expected to run out, if the caller2213 * fixed addition of trailing blank lines.2214 */2215if(preimage->nr <= ctx) {2216 reduced++;2217continue;2218}22192220/* and copy it in, while fixing the line length */2221 l_len = preimage->line[ctx].len;2222memcpy(new, fixed, l_len);2223new+= l_len;2224 fixed += l_len;2225 postimage->line[i].len = l_len;2226 ctx++;2227}22282229if(postlen2230? postlen <new- postimage->buf2231: postimage->len <new- postimage->buf)2232die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2233(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22342235/* Fix the length of the whole thing */2236 postimage->len =new- postimage->buf;2237 postimage->nr -= reduced;2238}22392240static intline_by_line_fuzzy_match(struct image *img,2241struct image *preimage,2242struct image *postimage,2243unsigned longtry,2244int try_lno,2245int preimage_limit)2246{2247int i;2248size_t imgoff =0;2249size_t preoff =0;2250size_t postlen = postimage->len;2251size_t extra_chars;2252char*buf;2253char*preimage_eof;2254char*preimage_end;2255struct strbuf fixed;2256char*fixed_buf;2257size_t fixed_len;22582259for(i =0; i < preimage_limit; i++) {2260size_t prelen = preimage->line[i].len;2261size_t imglen = img->line[try_lno+i].len;22622263if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2264 preimage->buf + preoff, prelen))2265return0;2266if(preimage->line[i].flag & LINE_COMMON)2267 postlen += imglen - prelen;2268 imgoff += imglen;2269 preoff += prelen;2270}22712272/*2273 * Ok, the preimage matches with whitespace fuzz.2274 *2275 * imgoff now holds the true length of the target that2276 * matches the preimage before the end of the file.2277 *2278 * Count the number of characters in the preimage that fall2279 * beyond the end of the file and make sure that all of them2280 * are whitespace characters. (This can only happen if2281 * we are removing blank lines at the end of the file.)2282 */2283 buf = preimage_eof = preimage->buf + preoff;2284for( ; i < preimage->nr; i++)2285 preoff += preimage->line[i].len;2286 preimage_end = preimage->buf + preoff;2287for( ; buf < preimage_end; buf++)2288if(!isspace(*buf))2289return0;22902291/*2292 * Update the preimage and the common postimage context2293 * lines to use the same whitespace as the target.2294 * If whitespace is missing in the target (i.e.2295 * if the preimage extends beyond the end of the file),2296 * use the whitespace from the preimage.2297 */2298 extra_chars = preimage_end - preimage_eof;2299strbuf_init(&fixed, imgoff + extra_chars);2300strbuf_add(&fixed, img->buf +try, imgoff);2301strbuf_add(&fixed, preimage_eof, extra_chars);2302 fixed_buf =strbuf_detach(&fixed, &fixed_len);2303update_pre_post_images(preimage, postimage,2304 fixed_buf, fixed_len, postlen);2305return1;2306}23072308static intmatch_fragment(struct apply_state *state,2309struct image *img,2310struct image *preimage,2311struct image *postimage,2312unsigned longtry,2313int try_lno,2314unsigned ws_rule,2315int match_beginning,int match_end)2316{2317int i;2318char*fixed_buf, *buf, *orig, *target;2319struct strbuf fixed;2320size_t fixed_len, postlen;2321int preimage_limit;23222323if(preimage->nr + try_lno <= img->nr) {2324/*2325 * The hunk falls within the boundaries of img.2326 */2327 preimage_limit = preimage->nr;2328if(match_end && (preimage->nr + try_lno != img->nr))2329return0;2330}else if(state->ws_error_action == correct_ws_error &&2331(ws_rule & WS_BLANK_AT_EOF)) {2332/*2333 * This hunk extends beyond the end of img, and we are2334 * removing blank lines at the end of the file. This2335 * many lines from the beginning of the preimage must2336 * match with img, and the remainder of the preimage2337 * must be blank.2338 */2339 preimage_limit = img->nr - try_lno;2340}else{2341/*2342 * The hunk extends beyond the end of the img and2343 * we are not removing blanks at the end, so we2344 * should reject the hunk at this position.2345 */2346return0;2347}23482349if(match_beginning && try_lno)2350return0;23512352/* Quick hash check */2353for(i =0; i < preimage_limit; i++)2354if((img->line[try_lno + i].flag & LINE_PATCHED) ||2355(preimage->line[i].hash != img->line[try_lno + i].hash))2356return0;23572358if(preimage_limit == preimage->nr) {2359/*2360 * Do we have an exact match? If we were told to match2361 * at the end, size must be exactly at try+fragsize,2362 * otherwise try+fragsize must be still within the preimage,2363 * and either case, the old piece should match the preimage2364 * exactly.2365 */2366if((match_end2367? (try+ preimage->len == img->len)2368: (try+ preimage->len <= img->len)) &&2369!memcmp(img->buf +try, preimage->buf, preimage->len))2370return1;2371}else{2372/*2373 * The preimage extends beyond the end of img, so2374 * there cannot be an exact match.2375 *2376 * There must be one non-blank context line that match2377 * a line before the end of img.2378 */2379char*buf_end;23802381 buf = preimage->buf;2382 buf_end = buf;2383for(i =0; i < preimage_limit; i++)2384 buf_end += preimage->line[i].len;23852386for( ; buf < buf_end; buf++)2387if(!isspace(*buf))2388break;2389if(buf == buf_end)2390return0;2391}23922393/*2394 * No exact match. If we are ignoring whitespace, run a line-by-line2395 * fuzzy matching. We collect all the line length information because2396 * we need it to adjust whitespace if we match.2397 */2398if(state->ws_ignore_action == ignore_ws_change)2399returnline_by_line_fuzzy_match(img, preimage, postimage,2400try, try_lno, preimage_limit);24012402if(state->ws_error_action != correct_ws_error)2403return0;24042405/*2406 * The hunk does not apply byte-by-byte, but the hash says2407 * it might with whitespace fuzz. We weren't asked to2408 * ignore whitespace, we were asked to correct whitespace2409 * errors, so let's try matching after whitespace correction.2410 *2411 * While checking the preimage against the target, whitespace2412 * errors in both fixed, we count how large the corresponding2413 * postimage needs to be. The postimage prepared by2414 * apply_one_fragment() has whitespace errors fixed on added2415 * lines already, but the common lines were propagated as-is,2416 * which may become longer when their whitespace errors are2417 * fixed.2418 */24192420/* First count added lines in postimage */2421 postlen =0;2422for(i =0; i < postimage->nr; i++) {2423if(!(postimage->line[i].flag & LINE_COMMON))2424 postlen += postimage->line[i].len;2425}24262427/*2428 * The preimage may extend beyond the end of the file,2429 * but in this loop we will only handle the part of the2430 * preimage that falls within the file.2431 */2432strbuf_init(&fixed, preimage->len +1);2433 orig = preimage->buf;2434 target = img->buf +try;2435for(i =0; i < preimage_limit; i++) {2436size_t oldlen = preimage->line[i].len;2437size_t tgtlen = img->line[try_lno + i].len;2438size_t fixstart = fixed.len;2439struct strbuf tgtfix;2440int match;24412442/* Try fixing the line in the preimage */2443ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24442445/* Try fixing the line in the target */2446strbuf_init(&tgtfix, tgtlen);2447ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24482449/*2450 * If they match, either the preimage was based on2451 * a version before our tree fixed whitespace breakage,2452 * or we are lacking a whitespace-fix patch the tree2453 * the preimage was based on already had (i.e. target2454 * has whitespace breakage, the preimage doesn't).2455 * In either case, we are fixing the whitespace breakages2456 * so we might as well take the fix together with their2457 * real change.2458 */2459 match = (tgtfix.len == fixed.len - fixstart &&2460!memcmp(tgtfix.buf, fixed.buf + fixstart,2461 fixed.len - fixstart));24622463/* Add the length if this is common with the postimage */2464if(preimage->line[i].flag & LINE_COMMON)2465 postlen += tgtfix.len;24662467strbuf_release(&tgtfix);2468if(!match)2469goto unmatch_exit;24702471 orig += oldlen;2472 target += tgtlen;2473}247424752476/*2477 * Now handle the lines in the preimage that falls beyond the2478 * end of the file (if any). They will only match if they are2479 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2480 * false).2481 */2482for( ; i < preimage->nr; i++) {2483size_t fixstart = fixed.len;/* start of the fixed preimage */2484size_t oldlen = preimage->line[i].len;2485int j;24862487/* Try fixing the line in the preimage */2488ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24892490for(j = fixstart; j < fixed.len; j++)2491if(!isspace(fixed.buf[j]))2492goto unmatch_exit;24932494 orig += oldlen;2495}24962497/*2498 * Yes, the preimage is based on an older version that still2499 * has whitespace breakages unfixed, and fixing them makes the2500 * hunk match. Update the context lines in the postimage.2501 */2502 fixed_buf =strbuf_detach(&fixed, &fixed_len);2503if(postlen < postimage->len)2504 postlen =0;2505update_pre_post_images(preimage, postimage,2506 fixed_buf, fixed_len, postlen);2507return1;25082509 unmatch_exit:2510strbuf_release(&fixed);2511return0;2512}25132514static intfind_pos(struct apply_state *state,2515struct image *img,2516struct image *preimage,2517struct image *postimage,2518int line,2519unsigned ws_rule,2520int match_beginning,int match_end)2521{2522int i;2523unsigned long backwards, forwards,try;2524int backwards_lno, forwards_lno, try_lno;25252526/*2527 * If match_beginning or match_end is specified, there is no2528 * point starting from a wrong line that will never match and2529 * wander around and wait for a match at the specified end.2530 */2531if(match_beginning)2532 line =0;2533else if(match_end)2534 line = img->nr - preimage->nr;25352536/*2537 * Because the comparison is unsigned, the following test2538 * will also take care of a negative line number that can2539 * result when match_end and preimage is larger than the target.2540 */2541if((size_t) line > img->nr)2542 line = img->nr;25432544try=0;2545for(i =0; i < line; i++)2546try+= img->line[i].len;25472548/*2549 * There's probably some smart way to do this, but I'll leave2550 * that to the smart and beautiful people. I'm simple and stupid.2551 */2552 backwards =try;2553 backwards_lno = line;2554 forwards =try;2555 forwards_lno = line;2556 try_lno = line;25572558for(i =0; ; i++) {2559if(match_fragment(state, img, preimage, postimage,2560try, try_lno, ws_rule,2561 match_beginning, match_end))2562return try_lno;25632564 again:2565if(backwards_lno ==0&& forwards_lno == img->nr)2566break;25672568if(i &1) {2569if(backwards_lno ==0) {2570 i++;2571goto again;2572}2573 backwards_lno--;2574 backwards -= img->line[backwards_lno].len;2575try= backwards;2576 try_lno = backwards_lno;2577}else{2578if(forwards_lno == img->nr) {2579 i++;2580goto again;2581}2582 forwards += img->line[forwards_lno].len;2583 forwards_lno++;2584try= forwards;2585 try_lno = forwards_lno;2586}25872588}2589return-1;2590}25912592static voidremove_first_line(struct image *img)2593{2594 img->buf += img->line[0].len;2595 img->len -= img->line[0].len;2596 img->line++;2597 img->nr--;2598}25992600static voidremove_last_line(struct image *img)2601{2602 img->len -= img->line[--img->nr].len;2603}26042605/*2606 * The change from "preimage" and "postimage" has been found to2607 * apply at applied_pos (counts in line numbers) in "img".2608 * Update "img" to remove "preimage" and replace it with "postimage".2609 */2610static voidupdate_image(struct apply_state *state,2611struct image *img,2612int applied_pos,2613struct image *preimage,2614struct image *postimage)2615{2616/*2617 * remove the copy of preimage at offset in img2618 * and replace it with postimage2619 */2620int i, nr;2621size_t remove_count, insert_count, applied_at =0;2622char*result;2623int preimage_limit;26242625/*2626 * If we are removing blank lines at the end of img,2627 * the preimage may extend beyond the end.2628 * If that is the case, we must be careful only to2629 * remove the part of the preimage that falls within2630 * the boundaries of img. Initialize preimage_limit2631 * to the number of lines in the preimage that falls2632 * within the boundaries.2633 */2634 preimage_limit = preimage->nr;2635if(preimage_limit > img->nr - applied_pos)2636 preimage_limit = img->nr - applied_pos;26372638for(i =0; i < applied_pos; i++)2639 applied_at += img->line[i].len;26402641 remove_count =0;2642for(i =0; i < preimage_limit; i++)2643 remove_count += img->line[applied_pos + i].len;2644 insert_count = postimage->len;26452646/* Adjust the contents */2647 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2648memcpy(result, img->buf, applied_at);2649memcpy(result + applied_at, postimage->buf, postimage->len);2650memcpy(result + applied_at + postimage->len,2651 img->buf + (applied_at + remove_count),2652 img->len - (applied_at + remove_count));2653free(img->buf);2654 img->buf = result;2655 img->len += insert_count - remove_count;2656 result[img->len] ='\0';26572658/* Adjust the line table */2659 nr = img->nr + postimage->nr - preimage_limit;2660if(preimage_limit < postimage->nr) {2661/*2662 * NOTE: this knows that we never call remove_first_line()2663 * on anything other than pre/post image.2664 */2665REALLOC_ARRAY(img->line, nr);2666 img->line_allocated = img->line;2667}2668if(preimage_limit != postimage->nr)2669memmove(img->line + applied_pos + postimage->nr,2670 img->line + applied_pos + preimage_limit,2671(img->nr - (applied_pos + preimage_limit)) *2672sizeof(*img->line));2673memcpy(img->line + applied_pos,2674 postimage->line,2675 postimage->nr *sizeof(*img->line));2676if(!state->allow_overlap)2677for(i =0; i < postimage->nr; i++)2678 img->line[applied_pos + i].flag |= LINE_PATCHED;2679 img->nr = nr;2680}26812682/*2683 * Use the patch-hunk text in "frag" to prepare two images (preimage and2684 * postimage) for the hunk. Find lines that match "preimage" in "img" and2685 * replace the part of "img" with "postimage" text.2686 */2687static intapply_one_fragment(struct apply_state *state,2688struct image *img,struct fragment *frag,2689int inaccurate_eof,unsigned ws_rule,2690int nth_fragment)2691{2692int match_beginning, match_end;2693const char*patch = frag->patch;2694int size = frag->size;2695char*old, *oldlines;2696struct strbuf newlines;2697int new_blank_lines_at_end =0;2698int found_new_blank_lines_at_end =0;2699int hunk_linenr = frag->linenr;2700unsigned long leading, trailing;2701int pos, applied_pos;2702struct image preimage;2703struct image postimage;27042705memset(&preimage,0,sizeof(preimage));2706memset(&postimage,0,sizeof(postimage));2707 oldlines =xmalloc(size);2708strbuf_init(&newlines, size);27092710 old = oldlines;2711while(size >0) {2712char first;2713int len =linelen(patch, size);2714int plen;2715int added_blank_line =0;2716int is_blank_context =0;2717size_t start;27182719if(!len)2720break;27212722/*2723 * "plen" is how much of the line we should use for2724 * the actual patch data. Normally we just remove the2725 * first character on the line, but if the line is2726 * followed by "\ No newline", then we also remove the2727 * last one (which is the newline, of course).2728 */2729 plen = len -1;2730if(len < size && patch[len] =='\\')2731 plen--;2732 first = *patch;2733if(state->apply_in_reverse) {2734if(first =='-')2735 first ='+';2736else if(first =='+')2737 first ='-';2738}27392740switch(first) {2741case'\n':2742/* Newer GNU diff, empty context line */2743if(plen <0)2744/* ... followed by '\No newline'; nothing */2745break;2746*old++ ='\n';2747strbuf_addch(&newlines,'\n');2748add_line_info(&preimage,"\n",1, LINE_COMMON);2749add_line_info(&postimage,"\n",1, LINE_COMMON);2750 is_blank_context =1;2751break;2752case' ':2753if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2754ws_blank_line(patch +1, plen, ws_rule))2755 is_blank_context =1;2756case'-':2757memcpy(old, patch +1, plen);2758add_line_info(&preimage, old, plen,2759(first ==' '? LINE_COMMON :0));2760 old += plen;2761if(first =='-')2762break;2763/* Fall-through for ' ' */2764case'+':2765/* --no-add does not add new lines */2766if(first =='+'&& state->no_add)2767break;27682769 start = newlines.len;2770if(first !='+'||2771!state->whitespace_error ||2772 state->ws_error_action != correct_ws_error) {2773strbuf_add(&newlines, patch +1, plen);2774}2775else{2776ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2777}2778add_line_info(&postimage, newlines.buf + start, newlines.len - start,2779(first =='+'?0: LINE_COMMON));2780if(first =='+'&&2781(ws_rule & WS_BLANK_AT_EOF) &&2782ws_blank_line(patch +1, plen, ws_rule))2783 added_blank_line =1;2784break;2785case'@':case'\\':2786/* Ignore it, we already handled it */2787break;2788default:2789if(state->apply_verbosely)2790error(_("invalid start of line: '%c'"), first);2791 applied_pos = -1;2792goto out;2793}2794if(added_blank_line) {2795if(!new_blank_lines_at_end)2796 found_new_blank_lines_at_end = hunk_linenr;2797 new_blank_lines_at_end++;2798}2799else if(is_blank_context)2800;2801else2802 new_blank_lines_at_end =0;2803 patch += len;2804 size -= len;2805 hunk_linenr++;2806}2807if(inaccurate_eof &&2808 old > oldlines && old[-1] =='\n'&&2809 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2810 old--;2811strbuf_setlen(&newlines, newlines.len -1);2812}28132814 leading = frag->leading;2815 trailing = frag->trailing;28162817/*2818 * A hunk to change lines at the beginning would begin with2819 * @@ -1,L +N,M @@2820 * but we need to be careful. -U0 that inserts before the second2821 * line also has this pattern.2822 *2823 * And a hunk to add to an empty file would begin with2824 * @@ -0,0 +N,M @@2825 *2826 * In other words, a hunk that is (frag->oldpos <= 1) with or2827 * without leading context must match at the beginning.2828 */2829 match_beginning = (!frag->oldpos ||2830(frag->oldpos ==1&& !state->unidiff_zero));28312832/*2833 * A hunk without trailing lines must match at the end.2834 * However, we simply cannot tell if a hunk must match end2835 * from the lack of trailing lines if the patch was generated2836 * with unidiff without any context.2837 */2838 match_end = !state->unidiff_zero && !trailing;28392840 pos = frag->newpos ? (frag->newpos -1) :0;2841 preimage.buf = oldlines;2842 preimage.len = old - oldlines;2843 postimage.buf = newlines.buf;2844 postimage.len = newlines.len;2845 preimage.line = preimage.line_allocated;2846 postimage.line = postimage.line_allocated;28472848for(;;) {28492850 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2851 ws_rule, match_beginning, match_end);28522853if(applied_pos >=0)2854break;28552856/* Am I at my context limits? */2857if((leading <= state->p_context) && (trailing <= state->p_context))2858break;2859if(match_beginning || match_end) {2860 match_beginning = match_end =0;2861continue;2862}28632864/*2865 * Reduce the number of context lines; reduce both2866 * leading and trailing if they are equal otherwise2867 * just reduce the larger context.2868 */2869if(leading >= trailing) {2870remove_first_line(&preimage);2871remove_first_line(&postimage);2872 pos--;2873 leading--;2874}2875if(trailing > leading) {2876remove_last_line(&preimage);2877remove_last_line(&postimage);2878 trailing--;2879}2880}28812882if(applied_pos >=0) {2883if(new_blank_lines_at_end &&2884 preimage.nr + applied_pos >= img->nr &&2885(ws_rule & WS_BLANK_AT_EOF) &&2886 state->ws_error_action != nowarn_ws_error) {2887record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2888 found_new_blank_lines_at_end);2889if(state->ws_error_action == correct_ws_error) {2890while(new_blank_lines_at_end--)2891remove_last_line(&postimage);2892}2893/*2894 * We would want to prevent write_out_results()2895 * from taking place in apply_patch() that follows2896 * the callchain led us here, which is:2897 * apply_patch->check_patch_list->check_patch->2898 * apply_data->apply_fragments->apply_one_fragment2899 */2900if(state->ws_error_action == die_on_ws_error)2901 state->apply =0;2902}29032904if(state->apply_verbosely && applied_pos != pos) {2905int offset = applied_pos - pos;2906if(state->apply_in_reverse)2907 offset =0- offset;2908fprintf_ln(stderr,2909Q_("Hunk #%dsucceeded at%d(offset%dline).",2910"Hunk #%dsucceeded at%d(offset%dlines).",2911 offset),2912 nth_fragment, applied_pos +1, offset);2913}29142915/*2916 * Warn if it was necessary to reduce the number2917 * of context lines.2918 */2919if((leading != frag->leading) ||2920(trailing != frag->trailing))2921fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2922" to apply fragment at%d"),2923 leading, trailing, applied_pos+1);2924update_image(state, img, applied_pos, &preimage, &postimage);2925}else{2926if(state->apply_verbosely)2927error(_("while searching for:\n%.*s"),2928(int)(old - oldlines), oldlines);2929}29302931out:2932free(oldlines);2933strbuf_release(&newlines);2934free(preimage.line_allocated);2935free(postimage.line_allocated);29362937return(applied_pos <0);2938}29392940static intapply_binary_fragment(struct apply_state *state,2941struct image *img,2942struct patch *patch)2943{2944struct fragment *fragment = patch->fragments;2945unsigned long len;2946void*dst;29472948if(!fragment)2949returnerror(_("missing binary patch data for '%s'"),2950 patch->new_name ?2951 patch->new_name :2952 patch->old_name);29532954/* Binary patch is irreversible without the optional second hunk */2955if(state->apply_in_reverse) {2956if(!fragment->next)2957returnerror("cannot reverse-apply a binary patch "2958"without the reverse hunk to '%s'",2959 patch->new_name2960? patch->new_name : patch->old_name);2961 fragment = fragment->next;2962}2963switch(fragment->binary_patch_method) {2964case BINARY_DELTA_DEFLATED:2965 dst =patch_delta(img->buf, img->len, fragment->patch,2966 fragment->size, &len);2967if(!dst)2968return-1;2969clear_image(img);2970 img->buf = dst;2971 img->len = len;2972return0;2973case BINARY_LITERAL_DEFLATED:2974clear_image(img);2975 img->len = fragment->size;2976 img->buf =xmemdupz(fragment->patch, img->len);2977return0;2978}2979return-1;2980}29812982/*2983 * Replace "img" with the result of applying the binary patch.2984 * The binary patch data itself in patch->fragment is still kept2985 * but the preimage prepared by the caller in "img" is freed here2986 * or in the helper function apply_binary_fragment() this calls.2987 */2988static intapply_binary(struct apply_state *state,2989struct image *img,2990struct patch *patch)2991{2992const char*name = patch->old_name ? patch->old_name : patch->new_name;2993unsigned char sha1[20];29942995/*2996 * For safety, we require patch index line to contain2997 * full 40-byte textual SHA1 for old and new, at least for now.2998 */2999if(strlen(patch->old_sha1_prefix) !=40||3000strlen(patch->new_sha1_prefix) !=40||3001get_sha1_hex(patch->old_sha1_prefix, sha1) ||3002get_sha1_hex(patch->new_sha1_prefix, sha1))3003returnerror("cannot apply binary patch to '%s' "3004"without full index line", name);30053006if(patch->old_name) {3007/*3008 * See if the old one matches what the patch3009 * applies to.3010 */3011hash_sha1_file(img->buf, img->len, blob_type, sha1);3012if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3013returnerror("the patch applies to '%s' (%s), "3014"which does not match the "3015"current contents.",3016 name,sha1_to_hex(sha1));3017}3018else{3019/* Otherwise, the old one must be empty. */3020if(img->len)3021returnerror("the patch applies to an empty "3022"'%s' but it is not empty", name);3023}30243025get_sha1_hex(patch->new_sha1_prefix, sha1);3026if(is_null_sha1(sha1)) {3027clear_image(img);3028return0;/* deletion patch */3029}30303031if(has_sha1_file(sha1)) {3032/* We already have the postimage */3033enum object_type type;3034unsigned long size;3035char*result;30363037 result =read_sha1_file(sha1, &type, &size);3038if(!result)3039returnerror("the necessary postimage%sfor "3040"'%s' cannot be read",3041 patch->new_sha1_prefix, name);3042clear_image(img);3043 img->buf = result;3044 img->len = size;3045}else{3046/*3047 * We have verified buf matches the preimage;3048 * apply the patch data to it, which is stored3049 * in the patch->fragments->{patch,size}.3050 */3051if(apply_binary_fragment(state, img, patch))3052returnerror(_("binary patch does not apply to '%s'"),3053 name);30543055/* verify that the result matches */3056hash_sha1_file(img->buf, img->len, blob_type, sha1);3057if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3058returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3059 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3060}30613062return0;3063}30643065static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3066{3067struct fragment *frag = patch->fragments;3068const char*name = patch->old_name ? patch->old_name : patch->new_name;3069unsigned ws_rule = patch->ws_rule;3070unsigned inaccurate_eof = patch->inaccurate_eof;3071int nth =0;30723073if(patch->is_binary)3074returnapply_binary(state, img, patch);30753076while(frag) {3077 nth++;3078if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3079error(_("patch failed:%s:%ld"), name, frag->oldpos);3080if(!state->apply_with_reject)3081return-1;3082 frag->rejected =1;3083}3084 frag = frag->next;3085}3086return0;3087}30883089static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3090{3091if(S_ISGITLINK(mode)) {3092strbuf_grow(buf,100);3093strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3094}else{3095enum object_type type;3096unsigned long sz;3097char*result;30983099 result =read_sha1_file(sha1, &type, &sz);3100if(!result)3101return-1;3102/* XXX read_sha1_file NUL-terminates */3103strbuf_attach(buf, result, sz, sz +1);3104}3105return0;3106}31073108static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3109{3110if(!ce)3111return0;3112returnread_blob_object(buf, ce->sha1, ce->ce_mode);3113}31143115static struct patch *in_fn_table(struct apply_state *state,const char*name)3116{3117struct string_list_item *item;31183119if(name == NULL)3120return NULL;31213122 item =string_list_lookup(&state->fn_table, name);3123if(item != NULL)3124return(struct patch *)item->util;31253126return NULL;3127}31283129/*3130 * item->util in the filename table records the status of the path.3131 * Usually it points at a patch (whose result records the contents3132 * of it after applying it), but it could be PATH_WAS_DELETED for a3133 * path that a previously applied patch has already removed, or3134 * PATH_TO_BE_DELETED for a path that a later patch would remove.3135 *3136 * The latter is needed to deal with a case where two paths A and B3137 * are swapped by first renaming A to B and then renaming B to A;3138 * moving A to B should not be prevented due to presence of B as we3139 * will remove it in a later patch.3140 */3141#define PATH_TO_BE_DELETED ((struct patch *) -2)3142#define PATH_WAS_DELETED ((struct patch *) -1)31433144static intto_be_deleted(struct patch *patch)3145{3146return patch == PATH_TO_BE_DELETED;3147}31483149static intwas_deleted(struct patch *patch)3150{3151return patch == PATH_WAS_DELETED;3152}31533154static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3155{3156struct string_list_item *item;31573158/*3159 * Always add new_name unless patch is a deletion3160 * This should cover the cases for normal diffs,3161 * file creations and copies3162 */3163if(patch->new_name != NULL) {3164 item =string_list_insert(&state->fn_table, patch->new_name);3165 item->util = patch;3166}31673168/*3169 * store a failure on rename/deletion cases because3170 * later chunks shouldn't patch old names3171 */3172if((patch->new_name == NULL) || (patch->is_rename)) {3173 item =string_list_insert(&state->fn_table, patch->old_name);3174 item->util = PATH_WAS_DELETED;3175}3176}31773178static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3179{3180/*3181 * store information about incoming file deletion3182 */3183while(patch) {3184if((patch->new_name == NULL) || (patch->is_rename)) {3185struct string_list_item *item;3186 item =string_list_insert(&state->fn_table, patch->old_name);3187 item->util = PATH_TO_BE_DELETED;3188}3189 patch = patch->next;3190}3191}31923193static intcheckout_target(struct index_state *istate,3194struct cache_entry *ce,struct stat *st)3195{3196struct checkout costate;31973198memset(&costate,0,sizeof(costate));3199 costate.base_dir ="";3200 costate.refresh_cache =1;3201 costate.istate = istate;3202if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3203returnerror(_("cannot checkout%s"), ce->name);3204return0;3205}32063207static struct patch *previous_patch(struct apply_state *state,3208struct patch *patch,3209int*gone)3210{3211struct patch *previous;32123213*gone =0;3214if(patch->is_copy || patch->is_rename)3215return NULL;/* "git" patches do not depend on the order */32163217 previous =in_fn_table(state, patch->old_name);3218if(!previous)3219return NULL;32203221if(to_be_deleted(previous))3222return NULL;/* the deletion hasn't happened yet */32233224if(was_deleted(previous))3225*gone =1;32263227return previous;3228}32293230static intverify_index_match(const struct cache_entry *ce,struct stat *st)3231{3232if(S_ISGITLINK(ce->ce_mode)) {3233if(!S_ISDIR(st->st_mode))3234return-1;3235return0;3236}3237returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3238}32393240#define SUBMODULE_PATCH_WITHOUT_INDEX 132413242static intload_patch_target(struct apply_state *state,3243struct strbuf *buf,3244const struct cache_entry *ce,3245struct stat *st,3246const char*name,3247unsigned expected_mode)3248{3249if(state->cached || state->check_index) {3250if(read_file_or_gitlink(ce, buf))3251returnerror(_("failed to read%s"), name);3252}else if(name) {3253if(S_ISGITLINK(expected_mode)) {3254if(ce)3255returnread_file_or_gitlink(ce, buf);3256else3257return SUBMODULE_PATCH_WITHOUT_INDEX;3258}else if(has_symlink_leading_path(name,strlen(name))) {3259returnerror(_("reading from '%s' beyond a symbolic link"), name);3260}else{3261if(read_old_data(st, name, buf))3262returnerror(_("failed to read%s"), name);3263}3264}3265return0;3266}32673268/*3269 * We are about to apply "patch"; populate the "image" with the3270 * current version we have, from the working tree or from the index,3271 * depending on the situation e.g. --cached/--index. If we are3272 * applying a non-git patch that incrementally updates the tree,3273 * we read from the result of a previous diff.3274 */3275static intload_preimage(struct apply_state *state,3276struct image *image,3277struct patch *patch,struct stat *st,3278const struct cache_entry *ce)3279{3280struct strbuf buf = STRBUF_INIT;3281size_t len;3282char*img;3283struct patch *previous;3284int status;32853286 previous =previous_patch(state, patch, &status);3287if(status)3288returnerror(_("path%shas been renamed/deleted"),3289 patch->old_name);3290if(previous) {3291/* We have a patched copy in memory; use that. */3292strbuf_add(&buf, previous->result, previous->resultsize);3293}else{3294 status =load_patch_target(state, &buf, ce, st,3295 patch->old_name, patch->old_mode);3296if(status <0)3297return status;3298else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3299/*3300 * There is no way to apply subproject3301 * patch without looking at the index.3302 * NEEDSWORK: shouldn't this be flagged3303 * as an error???3304 */3305free_fragment_list(patch->fragments);3306 patch->fragments = NULL;3307}else if(status) {3308returnerror(_("failed to read%s"), patch->old_name);3309}3310}33113312 img =strbuf_detach(&buf, &len);3313prepare_image(image, img, len, !patch->is_binary);3314return0;3315}33163317static intthree_way_merge(struct image *image,3318char*path,3319const unsigned char*base,3320const unsigned char*ours,3321const unsigned char*theirs)3322{3323 mmfile_t base_file, our_file, their_file;3324 mmbuffer_t result = { NULL };3325int status;33263327read_mmblob(&base_file, base);3328read_mmblob(&our_file, ours);3329read_mmblob(&their_file, theirs);3330 status =ll_merge(&result, path,3331&base_file,"base",3332&our_file,"ours",3333&their_file,"theirs", NULL);3334free(base_file.ptr);3335free(our_file.ptr);3336free(their_file.ptr);3337if(status <0|| !result.ptr) {3338free(result.ptr);3339return-1;3340}3341clear_image(image);3342 image->buf = result.ptr;3343 image->len = result.size;33443345return status;3346}33473348/*3349 * When directly falling back to add/add three-way merge, we read from3350 * the current contents of the new_name. In no cases other than that3351 * this function will be called.3352 */3353static intload_current(struct apply_state *state,3354struct image *image,3355struct patch *patch)3356{3357struct strbuf buf = STRBUF_INIT;3358int status, pos;3359size_t len;3360char*img;3361struct stat st;3362struct cache_entry *ce;3363char*name = patch->new_name;3364unsigned mode = patch->new_mode;33653366if(!patch->is_new)3367die("BUG: patch to%sis not a creation", patch->old_name);33683369 pos =cache_name_pos(name,strlen(name));3370if(pos <0)3371returnerror(_("%s: does not exist in index"), name);3372 ce = active_cache[pos];3373if(lstat(name, &st)) {3374if(errno != ENOENT)3375returnerror(_("%s:%s"), name,strerror(errno));3376if(checkout_target(&the_index, ce, &st))3377return-1;3378}3379if(verify_index_match(ce, &st))3380returnerror(_("%s: does not match index"), name);33813382 status =load_patch_target(state, &buf, ce, &st, name, mode);3383if(status <0)3384return status;3385else if(status)3386return-1;3387 img =strbuf_detach(&buf, &len);3388prepare_image(image, img, len, !patch->is_binary);3389return0;3390}33913392static inttry_threeway(struct apply_state *state,3393struct image *image,3394struct patch *patch,3395struct stat *st,3396const struct cache_entry *ce)3397{3398unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3399struct strbuf buf = STRBUF_INIT;3400size_t len;3401int status;3402char*img;3403struct image tmp_image;34043405/* No point falling back to 3-way merge in these cases */3406if(patch->is_delete ||3407S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3408return-1;34093410/* Preimage the patch was prepared for */3411if(patch->is_new)3412write_sha1_file("",0, blob_type, pre_sha1);3413else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3414read_blob_object(&buf, pre_sha1, patch->old_mode))3415returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34163417fprintf(stderr,"Falling back to three-way merge...\n");34183419 img =strbuf_detach(&buf, &len);3420prepare_image(&tmp_image, img, len,1);3421/* Apply the patch to get the post image */3422if(apply_fragments(state, &tmp_image, patch) <0) {3423clear_image(&tmp_image);3424return-1;3425}3426/* post_sha1[] is theirs */3427write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3428clear_image(&tmp_image);34293430/* our_sha1[] is ours */3431if(patch->is_new) {3432if(load_current(state, &tmp_image, patch))3433returnerror("cannot read the current contents of '%s'",3434 patch->new_name);3435}else{3436if(load_preimage(state, &tmp_image, patch, st, ce))3437returnerror("cannot read the current contents of '%s'",3438 patch->old_name);3439}3440write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3441clear_image(&tmp_image);34423443/* in-core three-way merge between post and our using pre as base */3444 status =three_way_merge(image, patch->new_name,3445 pre_sha1, our_sha1, post_sha1);3446if(status <0) {3447fprintf(stderr,"Failed to fall back on three-way merge...\n");3448return status;3449}34503451if(status) {3452 patch->conflicted_threeway =1;3453if(patch->is_new)3454oidclr(&patch->threeway_stage[0]);3455else3456hashcpy(patch->threeway_stage[0].hash, pre_sha1);3457hashcpy(patch->threeway_stage[1].hash, our_sha1);3458hashcpy(patch->threeway_stage[2].hash, post_sha1);3459fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3460}else{3461fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3462}3463return0;3464}34653466static intapply_data(struct apply_state *state,struct patch *patch,3467struct stat *st,const struct cache_entry *ce)3468{3469struct image image;34703471if(load_preimage(state, &image, patch, st, ce) <0)3472return-1;34733474if(patch->direct_to_threeway ||3475apply_fragments(state, &image, patch) <0) {3476/* Note: with --reject, apply_fragments() returns 0 */3477if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3478return-1;3479}3480 patch->result = image.buf;3481 patch->resultsize = image.len;3482add_to_fn_table(state, patch);3483free(image.line_allocated);34843485if(0< patch->is_delete && patch->resultsize)3486returnerror(_("removal patch leaves file contents"));34873488return0;3489}34903491/*3492 * If "patch" that we are looking at modifies or deletes what we have,3493 * we would want it not to lose any local modification we have, either3494 * in the working tree or in the index.3495 *3496 * This also decides if a non-git patch is a creation patch or a3497 * modification to an existing empty file. We do not check the state3498 * of the current tree for a creation patch in this function; the caller3499 * check_patch() separately makes sure (and errors out otherwise) that3500 * the path the patch creates does not exist in the current tree.3501 */3502static intcheck_preimage(struct apply_state *state,3503struct patch *patch,3504struct cache_entry **ce,3505struct stat *st)3506{3507const char*old_name = patch->old_name;3508struct patch *previous = NULL;3509int stat_ret =0, status;3510unsigned st_mode =0;35113512if(!old_name)3513return0;35143515assert(patch->is_new <=0);3516 previous =previous_patch(state, patch, &status);35173518if(status)3519returnerror(_("path%shas been renamed/deleted"), old_name);3520if(previous) {3521 st_mode = previous->new_mode;3522}else if(!state->cached) {3523 stat_ret =lstat(old_name, st);3524if(stat_ret && errno != ENOENT)3525returnerror(_("%s:%s"), old_name,strerror(errno));3526}35273528if(state->check_index && !previous) {3529int pos =cache_name_pos(old_name,strlen(old_name));3530if(pos <0) {3531if(patch->is_new <0)3532goto is_new;3533returnerror(_("%s: does not exist in index"), old_name);3534}3535*ce = active_cache[pos];3536if(stat_ret <0) {3537if(checkout_target(&the_index, *ce, st))3538return-1;3539}3540if(!state->cached &&verify_index_match(*ce, st))3541returnerror(_("%s: does not match index"), old_name);3542if(state->cached)3543 st_mode = (*ce)->ce_mode;3544}else if(stat_ret <0) {3545if(patch->is_new <0)3546goto is_new;3547returnerror(_("%s:%s"), old_name,strerror(errno));3548}35493550if(!state->cached && !previous)3551 st_mode =ce_mode_from_stat(*ce, st->st_mode);35523553if(patch->is_new <0)3554 patch->is_new =0;3555if(!patch->old_mode)3556 patch->old_mode = st_mode;3557if((st_mode ^ patch->old_mode) & S_IFMT)3558returnerror(_("%s: wrong type"), old_name);3559if(st_mode != patch->old_mode)3560warning(_("%shas type%o, expected%o"),3561 old_name, st_mode, patch->old_mode);3562if(!patch->new_mode && !patch->is_delete)3563 patch->new_mode = st_mode;3564return0;35653566 is_new:3567 patch->is_new =1;3568 patch->is_delete =0;3569free(patch->old_name);3570 patch->old_name = NULL;3571return0;3572}357335743575#define EXISTS_IN_INDEX 13576#define EXISTS_IN_WORKTREE 235773578static intcheck_to_create(struct apply_state *state,3579const char*new_name,3580int ok_if_exists)3581{3582struct stat nst;35833584if(state->check_index &&3585cache_name_pos(new_name,strlen(new_name)) >=0&&3586!ok_if_exists)3587return EXISTS_IN_INDEX;3588if(state->cached)3589return0;35903591if(!lstat(new_name, &nst)) {3592if(S_ISDIR(nst.st_mode) || ok_if_exists)3593return0;3594/*3595 * A leading component of new_name might be a symlink3596 * that is going to be removed with this patch, but3597 * still pointing at somewhere that has the path.3598 * In such a case, path "new_name" does not exist as3599 * far as git is concerned.3600 */3601if(has_symlink_leading_path(new_name,strlen(new_name)))3602return0;36033604return EXISTS_IN_WORKTREE;3605}else if((errno != ENOENT) && (errno != ENOTDIR)) {3606returnerror("%s:%s", new_name,strerror(errno));3607}3608return0;3609}36103611static uintptr_tregister_symlink_changes(struct apply_state *state,3612const char*path,3613uintptr_t what)3614{3615struct string_list_item *ent;36163617 ent =string_list_lookup(&state->symlink_changes, path);3618if(!ent) {3619 ent =string_list_insert(&state->symlink_changes, path);3620 ent->util = (void*)0;3621}3622 ent->util = (void*)(what | ((uintptr_t)ent->util));3623return(uintptr_t)ent->util;3624}36253626static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3627{3628struct string_list_item *ent;36293630 ent =string_list_lookup(&state->symlink_changes, path);3631if(!ent)3632return0;3633return(uintptr_t)ent->util;3634}36353636static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3637{3638for( ; patch; patch = patch->next) {3639if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3640(patch->is_rename || patch->is_delete))3641/* the symlink at patch->old_name is removed */3642register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36433644if(patch->new_name &&S_ISLNK(patch->new_mode))3645/* the symlink at patch->new_name is created or remains */3646register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3647}3648}36493650static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3651{3652do{3653unsigned int change;36543655while(--name->len && name->buf[name->len] !='/')3656;/* scan backwards */3657if(!name->len)3658break;3659 name->buf[name->len] ='\0';3660 change =check_symlink_changes(state, name->buf);3661if(change & APPLY_SYMLINK_IN_RESULT)3662return1;3663if(change & APPLY_SYMLINK_GOES_AWAY)3664/*3665 * This cannot be "return 0", because we may3666 * see a new one created at a higher level.3667 */3668continue;36693670/* otherwise, check the preimage */3671if(state->check_index) {3672struct cache_entry *ce;36733674 ce =cache_file_exists(name->buf, name->len, ignore_case);3675if(ce &&S_ISLNK(ce->ce_mode))3676return1;3677}else{3678struct stat st;3679if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3680return1;3681}3682}while(1);3683return0;3684}36853686static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3687{3688int ret;3689struct strbuf name = STRBUF_INIT;36903691assert(*name_ !='\0');3692strbuf_addstr(&name, name_);3693 ret =path_is_beyond_symlink_1(state, &name);3694strbuf_release(&name);36953696return ret;3697}36983699static voiddie_on_unsafe_path(struct patch *patch)3700{3701const char*old_name = NULL;3702const char*new_name = NULL;3703if(patch->is_delete)3704 old_name = patch->old_name;3705else if(!patch->is_new && !patch->is_copy)3706 old_name = patch->old_name;3707if(!patch->is_delete)3708 new_name = patch->new_name;37093710if(old_name && !verify_path(old_name))3711die(_("invalid path '%s'"), old_name);3712if(new_name && !verify_path(new_name))3713die(_("invalid path '%s'"), new_name);3714}37153716/*3717 * Check and apply the patch in-core; leave the result in patch->result3718 * for the caller to write it out to the final destination.3719 */3720static intcheck_patch(struct apply_state *state,struct patch *patch)3721{3722struct stat st;3723const char*old_name = patch->old_name;3724const char*new_name = patch->new_name;3725const char*name = old_name ? old_name : new_name;3726struct cache_entry *ce = NULL;3727struct patch *tpatch;3728int ok_if_exists;3729int status;37303731 patch->rejected =1;/* we will drop this after we succeed */37323733 status =check_preimage(state, patch, &ce, &st);3734if(status)3735return status;3736 old_name = patch->old_name;37373738/*3739 * A type-change diff is always split into a patch to delete3740 * old, immediately followed by a patch to create new (see3741 * diff.c::run_diff()); in such a case it is Ok that the entry3742 * to be deleted by the previous patch is still in the working3743 * tree and in the index.3744 *3745 * A patch to swap-rename between A and B would first rename A3746 * to B and then rename B to A. While applying the first one,3747 * the presence of B should not stop A from getting renamed to3748 * B; ask to_be_deleted() about the later rename. Removal of3749 * B and rename from A to B is handled the same way by asking3750 * was_deleted().3751 */3752if((tpatch =in_fn_table(state, new_name)) &&3753(was_deleted(tpatch) ||to_be_deleted(tpatch)))3754 ok_if_exists =1;3755else3756 ok_if_exists =0;37573758if(new_name &&3759((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3760int err =check_to_create(state, new_name, ok_if_exists);37613762if(err && state->threeway) {3763 patch->direct_to_threeway =1;3764}else switch(err) {3765case0:3766break;/* happy */3767case EXISTS_IN_INDEX:3768returnerror(_("%s: already exists in index"), new_name);3769break;3770case EXISTS_IN_WORKTREE:3771returnerror(_("%s: already exists in working directory"),3772 new_name);3773default:3774return err;3775}37763777if(!patch->new_mode) {3778if(0< patch->is_new)3779 patch->new_mode = S_IFREG |0644;3780else3781 patch->new_mode = patch->old_mode;3782}3783}37843785if(new_name && old_name) {3786int same = !strcmp(old_name, new_name);3787if(!patch->new_mode)3788 patch->new_mode = patch->old_mode;3789if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3790if(same)3791returnerror(_("new mode (%o) of%sdoes not "3792"match old mode (%o)"),3793 patch->new_mode, new_name,3794 patch->old_mode);3795else3796returnerror(_("new mode (%o) of%sdoes not "3797"match old mode (%o) of%s"),3798 patch->new_mode, new_name,3799 patch->old_mode, old_name);3800}3801}38023803if(!state->unsafe_paths)3804die_on_unsafe_path(patch);38053806/*3807 * An attempt to read from or delete a path that is beyond a3808 * symbolic link will be prevented by load_patch_target() that3809 * is called at the beginning of apply_data() so we do not3810 * have to worry about a patch marked with "is_delete" bit3811 * here. We however need to make sure that the patch result3812 * is not deposited to a path that is beyond a symbolic link3813 * here.3814 */3815if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3816returnerror(_("affected file '%s' is beyond a symbolic link"),3817 patch->new_name);38183819if(apply_data(state, patch, &st, ce) <0)3820returnerror(_("%s: patch does not apply"), name);3821 patch->rejected =0;3822return0;3823}38243825static intcheck_patch_list(struct apply_state *state,struct patch *patch)3826{3827int err =0;38283829prepare_symlink_changes(state, patch);3830prepare_fn_table(state, patch);3831while(patch) {3832if(state->apply_verbosely)3833say_patch_name(stderr,3834_("Checking patch%s..."), patch);3835 err |=check_patch(state, patch);3836 patch = patch->next;3837}3838return err;3839}38403841/* This function tries to read the sha1 from the current index */3842static intget_current_sha1(const char*path,unsigned char*sha1)3843{3844int pos;38453846if(read_cache() <0)3847return-1;3848 pos =cache_name_pos(path,strlen(path));3849if(pos <0)3850return-1;3851hashcpy(sha1, active_cache[pos]->sha1);3852return0;3853}38543855static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3856{3857/*3858 * A usable gitlink patch has only one fragment (hunk) that looks like:3859 * @@ -1 +1 @@3860 * -Subproject commit <old sha1>3861 * +Subproject commit <new sha1>3862 * or3863 * @@ -1 +0,0 @@3864 * -Subproject commit <old sha1>3865 * for a removal patch.3866 */3867struct fragment *hunk = p->fragments;3868static const char heading[] ="-Subproject commit ";3869char*preimage;38703871if(/* does the patch have only one hunk? */3872 hunk && !hunk->next &&3873/* is its preimage one line? */3874 hunk->oldpos ==1&& hunk->oldlines ==1&&3875/* does preimage begin with the heading? */3876(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3877starts_with(++preimage, heading) &&3878/* does it record full SHA-1? */3879!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3880 preimage[sizeof(heading) +40-1] =='\n'&&3881/* does the abbreviated name on the index line agree with it? */3882starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3883return0;/* it all looks fine */38843885/* we may have full object name on the index line */3886returnget_sha1_hex(p->old_sha1_prefix, sha1);3887}38883889/* Build an index that contains the just the files needed for a 3way merge */3890static voidbuild_fake_ancestor(struct patch *list,const char*filename)3891{3892struct patch *patch;3893struct index_state result = { NULL };3894static struct lock_file lock;38953896/* Once we start supporting the reverse patch, it may be3897 * worth showing the new sha1 prefix, but until then...3898 */3899for(patch = list; patch; patch = patch->next) {3900unsigned char sha1[20];3901struct cache_entry *ce;3902const char*name;39033904 name = patch->old_name ? patch->old_name : patch->new_name;3905if(0< patch->is_new)3906continue;39073908if(S_ISGITLINK(patch->old_mode)) {3909if(!preimage_sha1_in_gitlink_patch(patch, sha1))3910;/* ok, the textual part looks sane */3911else3912die("sha1 information is lacking or useless for submodule%s",3913 name);3914}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3915;/* ok */3916}else if(!patch->lines_added && !patch->lines_deleted) {3917/* mode-only change: update the current */3918if(get_current_sha1(patch->old_name, sha1))3919die("mode change for%s, which is not "3920"in current HEAD", name);3921}else3922die("sha1 information is lacking or useless "3923"(%s).", name);39243925 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3926if(!ce)3927die(_("make_cache_entry failed for path '%s'"), name);3928if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3929die("Could not add%sto temporary index", name);3930}39313932hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3933if(write_locked_index(&result, &lock, COMMIT_LOCK))3934die("Could not write temporary index to%s", filename);39353936discard_index(&result);3937}39383939static voidstat_patch_list(struct apply_state *state,struct patch *patch)3940{3941int files, adds, dels;39423943for(files = adds = dels =0; patch ; patch = patch->next) {3944 files++;3945 adds += patch->lines_added;3946 dels += patch->lines_deleted;3947show_stats(state, patch);3948}39493950print_stat_summary(stdout, files, adds, dels);3951}39523953static voidnumstat_patch_list(struct apply_state *state,3954struct patch *patch)3955{3956for( ; patch; patch = patch->next) {3957const char*name;3958 name = patch->new_name ? patch->new_name : patch->old_name;3959if(patch->is_binary)3960printf("-\t-\t");3961else3962printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3963write_name_quoted(name, stdout, state->line_termination);3964}3965}39663967static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3968{3969if(mode)3970printf("%smode%06o%s\n", newdelete, mode, name);3971else3972printf("%s %s\n", newdelete, name);3973}39743975static voidshow_mode_change(struct patch *p,int show_name)3976{3977if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3978if(show_name)3979printf(" mode change%06o =>%06o%s\n",3980 p->old_mode, p->new_mode, p->new_name);3981else3982printf(" mode change%06o =>%06o\n",3983 p->old_mode, p->new_mode);3984}3985}39863987static voidshow_rename_copy(struct patch *p)3988{3989const char*renamecopy = p->is_rename ?"rename":"copy";3990const char*old, *new;39913992/* Find common prefix */3993 old = p->old_name;3994new= p->new_name;3995while(1) {3996const char*slash_old, *slash_new;3997 slash_old =strchr(old,'/');3998 slash_new =strchr(new,'/');3999if(!slash_old ||4000!slash_new ||4001 slash_old - old != slash_new -new||4002memcmp(old,new, slash_new -new))4003break;4004 old = slash_old +1;4005new= slash_new +1;4006}4007/* p->old_name thru old is the common prefix, and old and new4008 * through the end of names are renames4009 */4010if(old != p->old_name)4011printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4012(int)(old - p->old_name), p->old_name,4013 old,new, p->score);4014else4015printf("%s %s=>%s(%d%%)\n", renamecopy,4016 p->old_name, p->new_name, p->score);4017show_mode_change(p,0);4018}40194020static voidsummary_patch_list(struct patch *patch)4021{4022struct patch *p;40234024for(p = patch; p; p = p->next) {4025if(p->is_new)4026show_file_mode_name("create", p->new_mode, p->new_name);4027else if(p->is_delete)4028show_file_mode_name("delete", p->old_mode, p->old_name);4029else{4030if(p->is_rename || p->is_copy)4031show_rename_copy(p);4032else{4033if(p->score) {4034printf(" rewrite%s(%d%%)\n",4035 p->new_name, p->score);4036show_mode_change(p,0);4037}4038else4039show_mode_change(p,1);4040}4041}4042}4043}40444045static voidpatch_stats(struct apply_state *state,struct patch *patch)4046{4047int lines = patch->lines_added + patch->lines_deleted;40484049if(lines > state->max_change)4050 state->max_change = lines;4051if(patch->old_name) {4052int len =quote_c_style(patch->old_name, NULL, NULL,0);4053if(!len)4054 len =strlen(patch->old_name);4055if(len > state->max_len)4056 state->max_len = len;4057}4058if(patch->new_name) {4059int len =quote_c_style(patch->new_name, NULL, NULL,0);4060if(!len)4061 len =strlen(patch->new_name);4062if(len > state->max_len)4063 state->max_len = len;4064}4065}40664067static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4068{4069if(state->update_index) {4070if(remove_file_from_cache(patch->old_name) <0)4071die(_("unable to remove%sfrom index"), patch->old_name);4072}4073if(!state->cached) {4074if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4075remove_path(patch->old_name);4076}4077}4078}40794080static voidadd_index_file(struct apply_state *state,4081const char*path,4082unsigned mode,4083void*buf,4084unsigned long size)4085{4086struct stat st;4087struct cache_entry *ce;4088int namelen =strlen(path);4089unsigned ce_size =cache_entry_size(namelen);40904091if(!state->update_index)4092return;40934094 ce =xcalloc(1, ce_size);4095memcpy(ce->name, path, namelen);4096 ce->ce_mode =create_ce_mode(mode);4097 ce->ce_flags =create_ce_flags(0);4098 ce->ce_namelen = namelen;4099if(S_ISGITLINK(mode)) {4100const char*s;41014102if(!skip_prefix(buf,"Subproject commit ", &s) ||4103get_sha1_hex(s, ce->sha1))4104die(_("corrupt patch for submodule%s"), path);4105}else{4106if(!state->cached) {4107if(lstat(path, &st) <0)4108die_errno(_("unable to stat newly created file '%s'"),4109 path);4110fill_stat_cache_info(ce, &st);4111}4112if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4113die(_("unable to create backing store for newly created file%s"), path);4114}4115if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4116die(_("unable to add cache entry for%s"), path);4117}41184119static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4120{4121int fd;4122struct strbuf nbuf = STRBUF_INIT;41234124if(S_ISGITLINK(mode)) {4125struct stat st;4126if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4127return0;4128returnmkdir(path,0777);4129}41304131if(has_symlinks &&S_ISLNK(mode))4132/* Although buf:size is counted string, it also is NUL4133 * terminated.4134 */4135returnsymlink(buf, path);41364137 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4138if(fd <0)4139return-1;41404141if(convert_to_working_tree(path, buf, size, &nbuf)) {4142 size = nbuf.len;4143 buf = nbuf.buf;4144}4145write_or_die(fd, buf, size);4146strbuf_release(&nbuf);41474148if(close(fd) <0)4149die_errno(_("closing file '%s'"), path);4150return0;4151}41524153/*4154 * We optimistically assume that the directories exist,4155 * which is true 99% of the time anyway. If they don't,4156 * we create them and try again.4157 */4158static voidcreate_one_file(struct apply_state *state,4159char*path,4160unsigned mode,4161const char*buf,4162unsigned long size)4163{4164if(state->cached)4165return;4166if(!try_create_file(path, mode, buf, size))4167return;41684169if(errno == ENOENT) {4170if(safe_create_leading_directories(path))4171return;4172if(!try_create_file(path, mode, buf, size))4173return;4174}41754176if(errno == EEXIST || errno == EACCES) {4177/* We may be trying to create a file where a directory4178 * used to be.4179 */4180struct stat st;4181if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4182 errno = EEXIST;4183}41844185if(errno == EEXIST) {4186unsigned int nr =getpid();41874188for(;;) {4189char newpath[PATH_MAX];4190mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4191if(!try_create_file(newpath, mode, buf, size)) {4192if(!rename(newpath, path))4193return;4194unlink_or_warn(newpath);4195break;4196}4197if(errno != EEXIST)4198break;4199++nr;4200}4201}4202die_errno(_("unable to write file '%s' mode%o"), path, mode);4203}42044205static voidadd_conflicted_stages_file(struct apply_state *state,4206struct patch *patch)4207{4208int stage, namelen;4209unsigned ce_size, mode;4210struct cache_entry *ce;42114212if(!state->update_index)4213return;4214 namelen =strlen(patch->new_name);4215 ce_size =cache_entry_size(namelen);4216 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42174218remove_file_from_cache(patch->new_name);4219for(stage =1; stage <4; stage++) {4220if(is_null_oid(&patch->threeway_stage[stage -1]))4221continue;4222 ce =xcalloc(1, ce_size);4223memcpy(ce->name, patch->new_name, namelen);4224 ce->ce_mode =create_ce_mode(mode);4225 ce->ce_flags =create_ce_flags(stage);4226 ce->ce_namelen = namelen;4227hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4228if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4229die(_("unable to add cache entry for%s"), patch->new_name);4230}4231}42324233static voidcreate_file(struct apply_state *state,struct patch *patch)4234{4235char*path = patch->new_name;4236unsigned mode = patch->new_mode;4237unsigned long size = patch->resultsize;4238char*buf = patch->result;42394240if(!mode)4241 mode = S_IFREG |0644;4242create_one_file(state, path, mode, buf, size);42434244if(patch->conflicted_threeway)4245add_conflicted_stages_file(state, patch);4246else4247add_index_file(state, path, mode, buf, size);4248}42494250/* phase zero is to remove, phase one is to create */4251static voidwrite_out_one_result(struct apply_state *state,4252struct patch *patch,4253int phase)4254{4255if(patch->is_delete >0) {4256if(phase ==0)4257remove_file(state, patch,1);4258return;4259}4260if(patch->is_new >0|| patch->is_copy) {4261if(phase ==1)4262create_file(state, patch);4263return;4264}4265/*4266 * Rename or modification boils down to the same4267 * thing: remove the old, write the new4268 */4269if(phase ==0)4270remove_file(state, patch, patch->is_rename);4271if(phase ==1)4272create_file(state, patch);4273}42744275static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4276{4277FILE*rej;4278char namebuf[PATH_MAX];4279struct fragment *frag;4280int cnt =0;4281struct strbuf sb = STRBUF_INIT;42824283for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4284if(!frag->rejected)4285continue;4286 cnt++;4287}42884289if(!cnt) {4290if(state->apply_verbosely)4291say_patch_name(stderr,4292_("Applied patch%scleanly."), patch);4293return0;4294}42954296/* This should not happen, because a removal patch that leaves4297 * contents are marked "rejected" at the patch level.4298 */4299if(!patch->new_name)4300die(_("internal error"));43014302/* Say this even without --verbose */4303strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4304"Applying patch %%swith%drejects...",4305 cnt),4306 cnt);4307say_patch_name(stderr, sb.buf, patch);4308strbuf_release(&sb);43094310 cnt =strlen(patch->new_name);4311if(ARRAY_SIZE(namebuf) <= cnt +5) {4312 cnt =ARRAY_SIZE(namebuf) -5;4313warning(_("truncating .rej filename to %.*s.rej"),4314 cnt -1, patch->new_name);4315}4316memcpy(namebuf, patch->new_name, cnt);4317memcpy(namebuf + cnt,".rej",5);43184319 rej =fopen(namebuf,"w");4320if(!rej)4321returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43224323/* Normal git tools never deal with .rej, so do not pretend4324 * this is a git patch by saying --git or giving extended4325 * headers. While at it, maybe please "kompare" that wants4326 * the trailing TAB and some garbage at the end of line ;-).4327 */4328fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4329 patch->new_name, patch->new_name);4330for(cnt =1, frag = patch->fragments;4331 frag;4332 cnt++, frag = frag->next) {4333if(!frag->rejected) {4334fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4335continue;4336}4337fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4338fprintf(rej,"%.*s", frag->size, frag->patch);4339if(frag->patch[frag->size-1] !='\n')4340fputc('\n', rej);4341}4342fclose(rej);4343return-1;4344}43454346static intwrite_out_results(struct apply_state *state,struct patch *list)4347{4348int phase;4349int errs =0;4350struct patch *l;4351struct string_list cpath = STRING_LIST_INIT_DUP;43524353for(phase =0; phase <2; phase++) {4354 l = list;4355while(l) {4356if(l->rejected)4357 errs =1;4358else{4359write_out_one_result(state, l, phase);4360if(phase ==1) {4361if(write_out_one_reject(state, l))4362 errs =1;4363if(l->conflicted_threeway) {4364string_list_append(&cpath, l->new_name);4365 errs =1;4366}4367}4368}4369 l = l->next;4370}4371}43724373if(cpath.nr) {4374struct string_list_item *item;43754376string_list_sort(&cpath);4377for_each_string_list_item(item, &cpath)4378fprintf(stderr,"U%s\n", item->string);4379string_list_clear(&cpath,0);43804381rerere(0);4382}43834384return errs;4385}43864387static struct lock_file lock_file;43884389#define INACCURATE_EOF (1<<0)4390#define RECOUNT (1<<1)43914392/*4393 * Try to apply a patch.4394 *4395 * Returns:4396 * -128 if a bad error happened (like patch unreadable)4397 * -1 if patch did not apply and user cannot deal with it4398 * 0 if the patch applied4399 * 1 if the patch did not apply but user might fix it4400 */4401static intapply_patch(struct apply_state *state,4402int fd,4403const char*filename,4404int options)4405{4406size_t offset;4407struct strbuf buf = STRBUF_INIT;/* owns the patch text */4408struct patch *list = NULL, **listp = &list;4409int skipped_patch =0;4410int res =0;44114412 state->patch_input_file = filename;4413if(read_patch_file(&buf, fd) <0)4414return-128;4415 offset =0;4416while(offset < buf.len) {4417struct patch *patch;4418int nr;44194420 patch =xcalloc(1,sizeof(*patch));4421 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4422 patch->recount = !!(options & RECOUNT);4423 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4424if(nr <0) {4425free_patch(patch);4426if(nr == -128) {4427 res = -128;4428goto end;4429}4430break;4431}4432if(state->apply_in_reverse)4433reverse_patches(patch);4434if(use_patch(state, patch)) {4435patch_stats(state, patch);4436*listp = patch;4437 listp = &patch->next;4438}4439else{4440if(state->apply_verbosely)4441say_patch_name(stderr,_("Skipped patch '%s'."), patch);4442free_patch(patch);4443 skipped_patch++;4444}4445 offset += nr;4446}44474448if(!list && !skipped_patch) {4449error(_("unrecognized input"));4450 res = -128;4451goto end;4452}44534454if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4455 state->apply =0;44564457 state->update_index = state->check_index && state->apply;4458if(state->update_index && state->newfd <0)4459 state->newfd =hold_locked_index(state->lock_file,1);44604461if(state->check_index &&read_cache() <0) {4462error(_("unable to read index file"));4463 res = -128;4464goto end;4465}44664467if((state->check || state->apply) &&4468check_patch_list(state, list) <0&&4469!state->apply_with_reject) {4470 res = -1;4471goto end;4472}44734474if(state->apply &&write_out_results(state, list)) {4475/* with --3way, we still need to write the index out */4476 res = state->apply_with_reject ? -1:1;4477goto end;4478}44794480if(state->fake_ancestor)4481build_fake_ancestor(list, state->fake_ancestor);44824483if(state->diffstat)4484stat_patch_list(state, list);44854486if(state->numstat)4487numstat_patch_list(state, list);44884489if(state->summary)4490summary_patch_list(list);44914492end:4493free_patch_list(list);4494strbuf_release(&buf);4495string_list_clear(&state->fn_table,0);4496return res;4497}44984499static intoption_parse_exclude(const struct option *opt,4500const char*arg,int unset)4501{4502struct apply_state *state = opt->value;4503add_name_limit(state, arg,1);4504return0;4505}45064507static intoption_parse_include(const struct option *opt,4508const char*arg,int unset)4509{4510struct apply_state *state = opt->value;4511add_name_limit(state, arg,0);4512 state->has_include =1;4513return0;4514}45154516static intoption_parse_p(const struct option *opt,4517const char*arg,4518int unset)4519{4520struct apply_state *state = opt->value;4521 state->p_value =atoi(arg);4522 state->p_value_known =1;4523return0;4524}45254526static intoption_parse_space_change(const struct option *opt,4527const char*arg,int unset)4528{4529struct apply_state *state = opt->value;4530if(unset)4531 state->ws_ignore_action = ignore_ws_none;4532else4533 state->ws_ignore_action = ignore_ws_change;4534return0;4535}45364537static intoption_parse_whitespace(const struct option *opt,4538const char*arg,int unset)4539{4540struct apply_state *state = opt->value;4541 state->whitespace_option = arg;4542if(parse_whitespace_option(state, arg))4543exit(1);4544return0;4545}45464547static intoption_parse_directory(const struct option *opt,4548const char*arg,int unset)4549{4550struct apply_state *state = opt->value;4551strbuf_reset(&state->root);4552strbuf_addstr(&state->root, arg);4553strbuf_complete(&state->root,'/');4554return0;4555}45564557static intapply_all_patches(struct apply_state *state,4558int argc,4559const char**argv,4560int options)4561{4562int i;4563int res;4564int errs =0;4565int read_stdin =1;45664567for(i =0; i < argc; i++) {4568const char*arg = argv[i];4569int fd;45704571if(!strcmp(arg,"-")) {4572 res =apply_patch(state,0,"<stdin>", options);4573if(res <0)4574goto end;4575 errs |= res;4576 read_stdin =0;4577continue;4578}else if(0< state->prefix_length)4579 arg =prefix_filename(state->prefix,4580 state->prefix_length,4581 arg);45824583 fd =open(arg, O_RDONLY);4584if(fd <0) {4585error(_("can't open patch '%s':%s"), arg,strerror(errno));4586 res = -128;4587goto end;4588}4589 read_stdin =0;4590set_default_whitespace_mode(state);4591 res =apply_patch(state, fd, arg, options);4592close(fd);4593if(res <0)4594goto end;4595 errs |= res;4596}4597set_default_whitespace_mode(state);4598if(read_stdin) {4599 res =apply_patch(state,0,"<stdin>", options);4600if(res <0)4601goto end;4602 errs |= res;4603}46044605if(state->whitespace_error) {4606if(state->squelch_whitespace_errors &&4607 state->squelch_whitespace_errors < state->whitespace_error) {4608int squelched =4609 state->whitespace_error - state->squelch_whitespace_errors;4610warning(Q_("squelched%dwhitespace error",4611"squelched%dwhitespace errors",4612 squelched),4613 squelched);4614}4615if(state->ws_error_action == die_on_ws_error) {4616error(Q_("%dline adds whitespace errors.",4617"%dlines add whitespace errors.",4618 state->whitespace_error),4619 state->whitespace_error);4620 res = -128;4621goto end;4622}4623if(state->applied_after_fixing_ws && state->apply)4624warning("%dline%sapplied after"4625" fixing whitespace errors.",4626 state->applied_after_fixing_ws,4627 state->applied_after_fixing_ws ==1?"":"s");4628else if(state->whitespace_error)4629warning(Q_("%dline adds whitespace errors.",4630"%dlines add whitespace errors.",4631 state->whitespace_error),4632 state->whitespace_error);4633}46344635if(state->update_index) {4636 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4637if(res) {4638error(_("Unable to write new index file"));4639 res = -128;4640goto end;4641}4642 state->newfd = -1;4643}46444645return!!errs;46464647end:4648if(state->newfd >=0) {4649rollback_lock_file(state->lock_file);4650 state->newfd = -1;4651}46524653return(res == -1?1:128);4654}46554656intcmd_apply(int argc,const char**argv,const char*prefix)4657{4658int force_apply =0;4659int options =0;4660int ret;4661struct apply_state state;46624663struct option builtin_apply_options[] = {4664{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4665N_("don't apply changes matching the given path"),46660, option_parse_exclude },4667{ OPTION_CALLBACK,0,"include", &state,N_("path"),4668N_("apply changes matching the given path"),46690, option_parse_include },4670{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4671N_("remove <num> leading slashes from traditional diff paths"),46720, option_parse_p },4673OPT_BOOL(0,"no-add", &state.no_add,4674N_("ignore additions made by the patch")),4675OPT_BOOL(0,"stat", &state.diffstat,4676N_("instead of applying the patch, output diffstat for the input")),4677OPT_NOOP_NOARG(0,"allow-binary-replacement"),4678OPT_NOOP_NOARG(0,"binary"),4679OPT_BOOL(0,"numstat", &state.numstat,4680N_("show number of added and deleted lines in decimal notation")),4681OPT_BOOL(0,"summary", &state.summary,4682N_("instead of applying the patch, output a summary for the input")),4683OPT_BOOL(0,"check", &state.check,4684N_("instead of applying the patch, see if the patch is applicable")),4685OPT_BOOL(0,"index", &state.check_index,4686N_("make sure the patch is applicable to the current index")),4687OPT_BOOL(0,"cached", &state.cached,4688N_("apply a patch without touching the working tree")),4689OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4690N_("accept a patch that touches outside the working area")),4691OPT_BOOL(0,"apply", &force_apply,4692N_("also apply the patch (use with --stat/--summary/--check)")),4693OPT_BOOL('3',"3way", &state.threeway,4694N_("attempt three-way merge if a patch does not apply")),4695OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4696N_("build a temporary index based on embedded index information")),4697/* Think twice before adding "--nul" synonym to this */4698OPT_SET_INT('z', NULL, &state.line_termination,4699N_("paths are separated with NUL character"),'\0'),4700OPT_INTEGER('C', NULL, &state.p_context,4701N_("ensure at least <n> lines of context match")),4702{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4703N_("detect new or modified lines that have whitespace errors"),47040, option_parse_whitespace },4705{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4706N_("ignore changes in whitespace when finding context"),4707 PARSE_OPT_NOARG, option_parse_space_change },4708{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4709N_("ignore changes in whitespace when finding context"),4710 PARSE_OPT_NOARG, option_parse_space_change },4711OPT_BOOL('R',"reverse", &state.apply_in_reverse,4712N_("apply the patch in reverse")),4713OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4714N_("don't expect at least one line of context")),4715OPT_BOOL(0,"reject", &state.apply_with_reject,4716N_("leave the rejected hunks in corresponding *.rej files")),4717OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4718N_("allow overlapping hunks")),4719OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4720OPT_BIT(0,"inaccurate-eof", &options,4721N_("tolerate incorrectly detected missing new-line at the end of file"),4722 INACCURATE_EOF),4723OPT_BIT(0,"recount", &options,4724N_("do not trust the line counts in the hunk headers"),4725 RECOUNT),4726{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4727N_("prepend <root> to all filenames"),47280, option_parse_directory },4729OPT_END()4730};47314732if(init_apply_state(&state, prefix, &lock_file))4733exit(128);47344735 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4736 apply_usage,0);47374738if(check_apply_state(&state, force_apply))4739exit(128);47404741 ret =apply_all_patches(&state, argc, argv, options);47424743clear_apply_state(&state);47444745return ret;4746}