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{ 815return1; 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 intgitdiff_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); 838return0; 839} 840 841if(*name) { 842int len =strlen(*name); 843char*another; 844if(isnull) 845returnerror(_("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)) { 849free(another); 850returnerror((side == DIFF_NEW_NAME) ? 851_("git apply: bad git-diff - inconsistent new filename on line%d") : 852_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 853} 854free(another); 855}else{ 856/* expect "/dev/null" */ 857if(memcmp("/dev/null", line,9) || line[9] !='\n') 858returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 859} 860 861return0; 862} 863 864static intgitdiff_oldname(struct apply_state *state, 865const char*line, 866struct patch *patch) 867{ 868returngitdiff_verify_name(state, line, 869 patch->is_new, &patch->old_name, 870 DIFF_OLD_NAME); 871} 872 873static intgitdiff_newname(struct apply_state *state, 874const char*line, 875struct patch *patch) 876{ 877returngitdiff_verify_name(state, line, 878 patch->is_delete, &patch->new_name, 879 DIFF_NEW_NAME); 880} 881 882static intgitdiff_oldmode(struct apply_state *state, 883const char*line, 884struct patch *patch) 885{ 886 patch->old_mode =strtoul(line, NULL,8); 887return0; 888} 889 890static intgitdiff_newmode(struct apply_state *state, 891const char*line, 892struct patch *patch) 893{ 894 patch->new_mode =strtoul(line, NULL,8); 895return0; 896} 897 898static intgitdiff_delete(struct apply_state *state, 899const char*line, 900struct patch *patch) 901{ 902 patch->is_delete =1; 903free(patch->old_name); 904 patch->old_name =xstrdup_or_null(patch->def_name); 905returngitdiff_oldmode(state, line, patch); 906} 907 908static intgitdiff_newfile(struct apply_state *state, 909const char*line, 910struct patch *patch) 911{ 912 patch->is_new =1; 913free(patch->new_name); 914 patch->new_name =xstrdup_or_null(patch->def_name); 915returngitdiff_newmode(state, line, patch); 916} 917 918static intgitdiff_copysrc(struct apply_state *state, 919const char*line, 920struct patch *patch) 921{ 922 patch->is_copy =1; 923free(patch->old_name); 924 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 925return0; 926} 927 928static intgitdiff_copydst(struct apply_state *state, 929const char*line, 930struct patch *patch) 931{ 932 patch->is_copy =1; 933free(patch->new_name); 934 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 935return0; 936} 937 938static intgitdiff_renamesrc(struct apply_state *state, 939const char*line, 940struct patch *patch) 941{ 942 patch->is_rename =1; 943free(patch->old_name); 944 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 945return0; 946} 947 948static intgitdiff_renamedst(struct apply_state *state, 949const char*line, 950struct patch *patch) 951{ 952 patch->is_rename =1; 953free(patch->new_name); 954 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 955return0; 956} 957 958static intgitdiff_similarity(struct apply_state *state, 959const char*line, 960struct patch *patch) 961{ 962unsigned long val =strtoul(line, NULL,10); 963if(val <=100) 964 patch->score = val; 965return0; 966} 967 968static intgitdiff_dissimilarity(struct apply_state *state, 969const char*line, 970struct patch *patch) 971{ 972unsigned long val =strtoul(line, NULL,10); 973if(val <=100) 974 patch->score = val; 975return0; 976} 977 978static intgitdiff_index(struct apply_state *state, 979const char*line, 980struct patch *patch) 981{ 982/* 983 * index line is N hexadecimal, "..", N hexadecimal, 984 * and optional space with octal mode. 985 */ 986const char*ptr, *eol; 987int len; 988 989 ptr =strchr(line,'.'); 990if(!ptr || ptr[1] !='.'||40< ptr - line) 991return0; 992 len = ptr - line; 993memcpy(patch->old_sha1_prefix, line, len); 994 patch->old_sha1_prefix[len] =0; 995 996 line = ptr +2; 997 ptr =strchr(line,' '); 998 eol =strchrnul(line,'\n'); 9991000if(!ptr || eol < ptr)1001 ptr = eol;1002 len = ptr - line;10031004if(40< len)1005return0;1006memcpy(patch->new_sha1_prefix, line, len);1007 patch->new_sha1_prefix[len] =0;1008if(*ptr ==' ')1009 patch->old_mode =strtoul(ptr+1, NULL,8);1010return0;1011}10121013/*1014 * This is normal for a diff that doesn't change anything: we'll fall through1015 * into the next diff. Tell the parser to break out.1016 */1017static intgitdiff_unrecognized(struct apply_state *state,1018const char*line,1019struct patch *patch)1020{1021return1;1022}10231024/*1025 * Skip p_value leading components from "line"; as we do not accept1026 * absolute paths, return NULL in that case.1027 */1028static const char*skip_tree_prefix(struct apply_state *state,1029const char*line,1030int llen)1031{1032int nslash;1033int i;10341035if(!state->p_value)1036return(llen && line[0] =='/') ? NULL : line;10371038 nslash = state->p_value;1039for(i =0; i < llen; i++) {1040int ch = line[i];1041if(ch =='/'&& --nslash <=0)1042return(i ==0) ? NULL : &line[i +1];1043}1044return NULL;1045}10461047/*1048 * This is to extract the same name that appears on "diff --git"1049 * line. We do not find and return anything if it is a rename1050 * patch, and it is OK because we will find the name elsewhere.1051 * We need to reliably find name only when it is mode-change only,1052 * creation or deletion of an empty file. In any of these cases,1053 * both sides are the same name under a/ and b/ respectively.1054 */1055static char*git_header_name(struct apply_state *state,1056const char*line,1057int llen)1058{1059const char*name;1060const char*second = NULL;1061size_t len, line_len;10621063 line +=strlen("diff --git ");1064 llen -=strlen("diff --git ");10651066if(*line =='"') {1067const char*cp;1068struct strbuf first = STRBUF_INIT;1069struct strbuf sp = STRBUF_INIT;10701071if(unquote_c_style(&first, line, &second))1072goto free_and_fail1;10731074/* strip the a/b prefix including trailing slash */1075 cp =skip_tree_prefix(state, first.buf, first.len);1076if(!cp)1077goto free_and_fail1;1078strbuf_remove(&first,0, cp - first.buf);10791080/*1081 * second points at one past closing dq of name.1082 * find the second name.1083 */1084while((second < line + llen) &&isspace(*second))1085 second++;10861087if(line + llen <= second)1088goto free_and_fail1;1089if(*second =='"') {1090if(unquote_c_style(&sp, second, NULL))1091goto free_and_fail1;1092 cp =skip_tree_prefix(state, sp.buf, sp.len);1093if(!cp)1094goto free_and_fail1;1095/* They must match, otherwise ignore */1096if(strcmp(cp, first.buf))1097goto free_and_fail1;1098strbuf_release(&sp);1099returnstrbuf_detach(&first, NULL);1100}11011102/* unquoted second */1103 cp =skip_tree_prefix(state, second, line + llen - second);1104if(!cp)1105goto free_and_fail1;1106if(line + llen - cp != first.len ||1107memcmp(first.buf, cp, first.len))1108goto free_and_fail1;1109returnstrbuf_detach(&first, NULL);11101111 free_and_fail1:1112strbuf_release(&first);1113strbuf_release(&sp);1114return NULL;1115}11161117/* unquoted first name */1118 name =skip_tree_prefix(state, line, llen);1119if(!name)1120return NULL;11211122/*1123 * since the first name is unquoted, a dq if exists must be1124 * the beginning of the second name.1125 */1126for(second = name; second < line + llen; second++) {1127if(*second =='"') {1128struct strbuf sp = STRBUF_INIT;1129const char*np;11301131if(unquote_c_style(&sp, second, NULL))1132goto free_and_fail2;11331134 np =skip_tree_prefix(state, sp.buf, sp.len);1135if(!np)1136goto free_and_fail2;11371138 len = sp.buf + sp.len - np;1139if(len < second - name &&1140!strncmp(np, name, len) &&1141isspace(name[len])) {1142/* Good */1143strbuf_remove(&sp,0, np - sp.buf);1144returnstrbuf_detach(&sp, NULL);1145}11461147 free_and_fail2:1148strbuf_release(&sp);1149return NULL;1150}1151}11521153/*1154 * Accept a name only if it shows up twice, exactly the same1155 * form.1156 */1157 second =strchr(name,'\n');1158if(!second)1159return NULL;1160 line_len = second - name;1161for(len =0; ; len++) {1162switch(name[len]) {1163default:1164continue;1165case'\n':1166return NULL;1167case'\t':case' ':1168/*1169 * Is this the separator between the preimage1170 * and the postimage pathname? Again, we are1171 * only interested in the case where there is1172 * no rename, as this is only to set def_name1173 * and a rename patch has the names elsewhere1174 * in an unambiguous form.1175 */1176if(!name[len +1])1177return NULL;/* no postimage name */1178 second =skip_tree_prefix(state, name + len +1,1179 line_len - (len +1));1180if(!second)1181return NULL;1182/*1183 * Does len bytes starting at "name" and "second"1184 * (that are separated by one HT or SP we just1185 * found) exactly match?1186 */1187if(second[len] =='\n'&& !strncmp(name, second, len))1188returnxmemdupz(name, len);1189}1190}1191}11921193/* Verify that we recognize the lines following a git header */1194static intparse_git_header(struct apply_state *state,1195const char*line,1196int len,1197unsigned int size,1198struct patch *patch)1199{1200unsigned long offset;12011202/* A git diff has explicit new/delete information, so we don't guess */1203 patch->is_new =0;1204 patch->is_delete =0;12051206/*1207 * Some things may not have the old name in the1208 * rest of the headers anywhere (pure mode changes,1209 * or removing or adding empty files), so we get1210 * the default name from the header.1211 */1212 patch->def_name =git_header_name(state, line, len);1213if(patch->def_name && state->root.len) {1214char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1215free(patch->def_name);1216 patch->def_name = s;1217}12181219 line += len;1220 size -= len;1221 state->linenr++;1222for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1223static const struct opentry {1224const char*str;1225int(*fn)(struct apply_state *,const char*,struct patch *);1226} optable[] = {1227{"@@ -", gitdiff_hdrend },1228{"--- ", gitdiff_oldname },1229{"+++ ", gitdiff_newname },1230{"old mode ", gitdiff_oldmode },1231{"new mode ", gitdiff_newmode },1232{"deleted file mode ", gitdiff_delete },1233{"new file mode ", gitdiff_newfile },1234{"copy from ", gitdiff_copysrc },1235{"copy to ", gitdiff_copydst },1236{"rename old ", gitdiff_renamesrc },1237{"rename new ", gitdiff_renamedst },1238{"rename from ", gitdiff_renamesrc },1239{"rename to ", gitdiff_renamedst },1240{"similarity index ", gitdiff_similarity },1241{"dissimilarity index ", gitdiff_dissimilarity },1242{"index ", gitdiff_index },1243{"", gitdiff_unrecognized },1244};1245int i;12461247 len =linelen(line, size);1248if(!len || line[len-1] !='\n')1249break;1250for(i =0; i <ARRAY_SIZE(optable); i++) {1251const struct opentry *p = optable + i;1252int oplen =strlen(p->str);1253int res;1254if(len < oplen ||memcmp(p->str, line, oplen))1255continue;1256 res = p->fn(state, line + oplen, patch);1257if(res <0)1258return-1;1259if(res >0)1260return offset;1261break;1262}1263}12641265return offset;1266}12671268static intparse_num(const char*line,unsigned long*p)1269{1270char*ptr;12711272if(!isdigit(*line))1273return0;1274*p =strtoul(line, &ptr,10);1275return ptr - line;1276}12771278static intparse_range(const char*line,int len,int offset,const char*expect,1279unsigned long*p1,unsigned long*p2)1280{1281int digits, ex;12821283if(offset <0|| offset >= len)1284return-1;1285 line += offset;1286 len -= offset;12871288 digits =parse_num(line, p1);1289if(!digits)1290return-1;12911292 offset += digits;1293 line += digits;1294 len -= digits;12951296*p2 =1;1297if(*line ==',') {1298 digits =parse_num(line+1, p2);1299if(!digits)1300return-1;13011302 offset += digits+1;1303 line += digits+1;1304 len -= digits+1;1305}13061307 ex =strlen(expect);1308if(ex > len)1309return-1;1310if(memcmp(line, expect, ex))1311return-1;13121313return offset + ex;1314}13151316static voidrecount_diff(const char*line,int size,struct fragment *fragment)1317{1318int oldlines =0, newlines =0, ret =0;13191320if(size <1) {1321warning("recount: ignore empty hunk");1322return;1323}13241325for(;;) {1326int len =linelen(line, size);1327 size -= len;1328 line += len;13291330if(size <1)1331break;13321333switch(*line) {1334case' ':case'\n':1335 newlines++;1336/* fall through */1337case'-':1338 oldlines++;1339continue;1340case'+':1341 newlines++;1342continue;1343case'\\':1344continue;1345case'@':1346 ret = size <3|| !starts_with(line,"@@ ");1347break;1348case'd':1349 ret = size <5|| !starts_with(line,"diff ");1350break;1351default:1352 ret = -1;1353break;1354}1355if(ret) {1356warning(_("recount: unexpected line: %.*s"),1357(int)linelen(line, size), line);1358return;1359}1360break;1361}1362 fragment->oldlines = oldlines;1363 fragment->newlines = newlines;1364}13651366/*1367 * Parse a unified diff fragment header of the1368 * form "@@ -a,b +c,d @@"1369 */1370static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1371{1372int offset;13731374if(!len || line[len-1] !='\n')1375return-1;13761377/* Figure out the number of lines in a fragment */1378 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1379 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);13801381return offset;1382}13831384/*1385 * Find file diff header1386 *1387 * Returns:1388 * -1 if no header was found1389 * -128 in case of error1390 * the size of the header in bytes (called "offset") otherwise1391 */1392static intfind_header(struct apply_state *state,1393const char*line,1394unsigned long size,1395int*hdrsize,1396struct patch *patch)1397{1398unsigned long offset, len;13991400 patch->is_toplevel_relative =0;1401 patch->is_rename = patch->is_copy =0;1402 patch->is_new = patch->is_delete = -1;1403 patch->old_mode = patch->new_mode =0;1404 patch->old_name = patch->new_name = NULL;1405for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1406unsigned long nextlen;14071408 len =linelen(line, size);1409if(!len)1410break;14111412/* Testing this early allows us to take a few shortcuts.. */1413if(len <6)1414continue;14151416/*1417 * Make sure we don't find any unconnected patch fragments.1418 * That's a sign that we didn't find a header, and that a1419 * patch has become corrupted/broken up.1420 */1421if(!memcmp("@@ -", line,4)) {1422struct fragment dummy;1423if(parse_fragment_header(line, len, &dummy) <0)1424continue;1425error(_("patch fragment without header at line%d: %.*s"),1426 state->linenr, (int)len-1, line);1427return-128;1428}14291430if(size < len +6)1431break;14321433/*1434 * Git patch? It might not have a real patch, just a rename1435 * or mode change, so we handle that specially1436 */1437if(!memcmp("diff --git ", line,11)) {1438int git_hdr_len =parse_git_header(state, line, len, size, patch);1439if(git_hdr_len <0)1440return-128;1441if(git_hdr_len <= len)1442continue;1443if(!patch->old_name && !patch->new_name) {1444if(!patch->def_name) {1445error(Q_("git diff header lacks filename information when removing "1446"%dleading pathname component (line%d)",1447"git diff header lacks filename information when removing "1448"%dleading pathname components (line%d)",1449 state->p_value),1450 state->p_value, state->linenr);1451return-128;1452}1453 patch->old_name =xstrdup(patch->def_name);1454 patch->new_name =xstrdup(patch->def_name);1455}1456if(!patch->is_delete && !patch->new_name) {1457error("git diff header lacks filename information "1458"(line%d)", state->linenr);1459return-128;1460}1461 patch->is_toplevel_relative =1;1462*hdrsize = git_hdr_len;1463return offset;1464}14651466/* --- followed by +++ ? */1467if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1468continue;14691470/*1471 * We only accept unified patches, so we want it to1472 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1473 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1474 */1475 nextlen =linelen(line + len, size - len);1476if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1477continue;14781479/* Ok, we'll consider it a patch */1480if(parse_traditional_patch(state, line, line+len, patch))1481return-128;1482*hdrsize = len + nextlen;1483 state->linenr +=2;1484return offset;1485}1486return-1;1487}14881489static voidrecord_ws_error(struct apply_state *state,1490unsigned result,1491const char*line,1492int len,1493int linenr)1494{1495char*err;14961497if(!result)1498return;14991500 state->whitespace_error++;1501if(state->squelch_whitespace_errors &&1502 state->squelch_whitespace_errors < state->whitespace_error)1503return;15041505 err =whitespace_error_string(result);1506fprintf(stderr,"%s:%d:%s.\n%.*s\n",1507 state->patch_input_file, linenr, err, len, line);1508free(err);1509}15101511static voidcheck_whitespace(struct apply_state *state,1512const char*line,1513int len,1514unsigned ws_rule)1515{1516unsigned result =ws_check(line +1, len -1, ws_rule);15171518record_ws_error(state, result, line +1, len -2, state->linenr);1519}15201521/*1522 * Parse a unified diff. Note that this really needs to parse each1523 * fragment separately, since the only way to know the difference1524 * between a "---" that is part of a patch, and a "---" that starts1525 * the next patch is to look at the line counts..1526 */1527static intparse_fragment(struct apply_state *state,1528const char*line,1529unsigned long size,1530struct patch *patch,1531struct fragment *fragment)1532{1533int added, deleted;1534int len =linelen(line, size), offset;1535unsigned long oldlines, newlines;1536unsigned long leading, trailing;15371538 offset =parse_fragment_header(line, len, fragment);1539if(offset <0)1540return-1;1541if(offset >0&& patch->recount)1542recount_diff(line + offset, size - offset, fragment);1543 oldlines = fragment->oldlines;1544 newlines = fragment->newlines;1545 leading =0;1546 trailing =0;15471548/* Parse the thing.. */1549 line += len;1550 size -= len;1551 state->linenr++;1552 added = deleted =0;1553for(offset = len;15540< size;1555 offset += len, size -= len, line += len, state->linenr++) {1556if(!oldlines && !newlines)1557break;1558 len =linelen(line, size);1559if(!len || line[len-1] !='\n')1560return-1;1561switch(*line) {1562default:1563return-1;1564case'\n':/* newer GNU diff, an empty context line */1565case' ':1566 oldlines--;1567 newlines--;1568if(!deleted && !added)1569 leading++;1570 trailing++;1571if(!state->apply_in_reverse &&1572 state->ws_error_action == correct_ws_error)1573check_whitespace(state, line, len, patch->ws_rule);1574break;1575case'-':1576if(state->apply_in_reverse &&1577 state->ws_error_action != nowarn_ws_error)1578check_whitespace(state, line, len, patch->ws_rule);1579 deleted++;1580 oldlines--;1581 trailing =0;1582break;1583case'+':1584if(!state->apply_in_reverse &&1585 state->ws_error_action != nowarn_ws_error)1586check_whitespace(state, line, len, patch->ws_rule);1587 added++;1588 newlines--;1589 trailing =0;1590break;15911592/*1593 * We allow "\ No newline at end of file". Depending1594 * on locale settings when the patch was produced we1595 * don't know what this line looks like. The only1596 * thing we do know is that it begins with "\ ".1597 * Checking for 12 is just for sanity check -- any1598 * l10n of "\ No newline..." is at least that long.1599 */1600case'\\':1601if(len <12||memcmp(line,"\\",2))1602return-1;1603break;1604}1605}1606if(oldlines || newlines)1607return-1;1608if(!deleted && !added)1609return-1;16101611 fragment->leading = leading;1612 fragment->trailing = trailing;16131614/*1615 * If a fragment ends with an incomplete line, we failed to include1616 * it in the above loop because we hit oldlines == newlines == 01617 * before seeing it.1618 */1619if(12< size && !memcmp(line,"\\",2))1620 offset +=linelen(line, size);16211622 patch->lines_added += added;1623 patch->lines_deleted += deleted;16241625if(0< patch->is_new && oldlines)1626returnerror(_("new file depends on old contents"));1627if(0< patch->is_delete && newlines)1628returnerror(_("deleted file still has contents"));1629return offset;1630}16311632/*1633 * We have seen "diff --git a/... b/..." header (or a traditional patch1634 * header). Read hunks that belong to this patch into fragments and hang1635 * them to the given patch structure.1636 *1637 * The (fragment->patch, fragment->size) pair points into the memory given1638 * by the caller, not a copy, when we return.1639 *1640 * Returns:1641 * -1 in case of error,1642 * the number of bytes in the patch otherwise.1643 */1644static intparse_single_patch(struct apply_state *state,1645const char*line,1646unsigned long size,1647struct patch *patch)1648{1649unsigned long offset =0;1650unsigned long oldlines =0, newlines =0, context =0;1651struct fragment **fragp = &patch->fragments;16521653while(size >4&& !memcmp(line,"@@ -",4)) {1654struct fragment *fragment;1655int len;16561657 fragment =xcalloc(1,sizeof(*fragment));1658 fragment->linenr = state->linenr;1659 len =parse_fragment(state, line, size, patch, fragment);1660if(len <=0) {1661free(fragment);1662returnerror(_("corrupt patch at line%d"), state->linenr);1663}1664 fragment->patch = line;1665 fragment->size = len;1666 oldlines += fragment->oldlines;1667 newlines += fragment->newlines;1668 context += fragment->leading + fragment->trailing;16691670*fragp = fragment;1671 fragp = &fragment->next;16721673 offset += len;1674 line += len;1675 size -= len;1676}16771678/*1679 * If something was removed (i.e. we have old-lines) it cannot1680 * be creation, and if something was added it cannot be1681 * deletion. However, the reverse is not true; --unified=01682 * patches that only add are not necessarily creation even1683 * though they do not have any old lines, and ones that only1684 * delete are not necessarily deletion.1685 *1686 * Unfortunately, a real creation/deletion patch do _not_ have1687 * any context line by definition, so we cannot safely tell it1688 * apart with --unified=0 insanity. At least if the patch has1689 * more than one hunk it is not creation or deletion.1690 */1691if(patch->is_new <0&&1692(oldlines || (patch->fragments && patch->fragments->next)))1693 patch->is_new =0;1694if(patch->is_delete <0&&1695(newlines || (patch->fragments && patch->fragments->next)))1696 patch->is_delete =0;16971698if(0< patch->is_new && oldlines)1699returnerror(_("new file%sdepends on old contents"), patch->new_name);1700if(0< patch->is_delete && newlines)1701returnerror(_("deleted file%sstill has contents"), patch->old_name);1702if(!patch->is_delete && !newlines && context)1703fprintf_ln(stderr,1704_("** warning: "1705"file%sbecomes empty but is not deleted"),1706 patch->new_name);17071708return offset;1709}17101711staticinlineintmetadata_changes(struct patch *patch)1712{1713return patch->is_rename >0||1714 patch->is_copy >0||1715 patch->is_new >0||1716 patch->is_delete ||1717(patch->old_mode && patch->new_mode &&1718 patch->old_mode != patch->new_mode);1719}17201721static char*inflate_it(const void*data,unsigned long size,1722unsigned long inflated_size)1723{1724 git_zstream stream;1725void*out;1726int st;17271728memset(&stream,0,sizeof(stream));17291730 stream.next_in = (unsigned char*)data;1731 stream.avail_in = size;1732 stream.next_out = out =xmalloc(inflated_size);1733 stream.avail_out = inflated_size;1734git_inflate_init(&stream);1735 st =git_inflate(&stream, Z_FINISH);1736git_inflate_end(&stream);1737if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1738free(out);1739return NULL;1740}1741return out;1742}17431744/*1745 * Read a binary hunk and return a new fragment; fragment->patch1746 * points at an allocated memory that the caller must free, so1747 * it is marked as "->free_patch = 1".1748 */1749static struct fragment *parse_binary_hunk(struct apply_state *state,1750char**buf_p,1751unsigned long*sz_p,1752int*status_p,1753int*used_p)1754{1755/*1756 * Expect a line that begins with binary patch method ("literal"1757 * or "delta"), followed by the length of data before deflating.1758 * a sequence of 'length-byte' followed by base-85 encoded data1759 * should follow, terminated by a newline.1760 *1761 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1762 * and we would limit the patch line to 66 characters,1763 * so one line can fit up to 13 groups that would decode1764 * to 52 bytes max. The length byte 'A'-'Z' corresponds1765 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1766 */1767int llen, used;1768unsigned long size = *sz_p;1769char*buffer = *buf_p;1770int patch_method;1771unsigned long origlen;1772char*data = NULL;1773int hunk_size =0;1774struct fragment *frag;17751776 llen =linelen(buffer, size);1777 used = llen;17781779*status_p =0;17801781if(starts_with(buffer,"delta ")) {1782 patch_method = BINARY_DELTA_DEFLATED;1783 origlen =strtoul(buffer +6, NULL,10);1784}1785else if(starts_with(buffer,"literal ")) {1786 patch_method = BINARY_LITERAL_DEFLATED;1787 origlen =strtoul(buffer +8, NULL,10);1788}1789else1790return NULL;17911792 state->linenr++;1793 buffer += llen;1794while(1) {1795int byte_length, max_byte_length, newsize;1796 llen =linelen(buffer, size);1797 used += llen;1798 state->linenr++;1799if(llen ==1) {1800/* consume the blank line */1801 buffer++;1802 size--;1803break;1804}1805/*1806 * Minimum line is "A00000\n" which is 7-byte long,1807 * and the line length must be multiple of 5 plus 2.1808 */1809if((llen <7) || (llen-2) %5)1810goto corrupt;1811 max_byte_length = (llen -2) /5*4;1812 byte_length = *buffer;1813if('A'<= byte_length && byte_length <='Z')1814 byte_length = byte_length -'A'+1;1815else if('a'<= byte_length && byte_length <='z')1816 byte_length = byte_length -'a'+27;1817else1818goto corrupt;1819/* if the input length was not multiple of 4, we would1820 * have filler at the end but the filler should never1821 * exceed 3 bytes1822 */1823if(max_byte_length < byte_length ||1824 byte_length <= max_byte_length -4)1825goto corrupt;1826 newsize = hunk_size + byte_length;1827 data =xrealloc(data, newsize);1828if(decode_85(data + hunk_size, buffer +1, byte_length))1829goto corrupt;1830 hunk_size = newsize;1831 buffer += llen;1832 size -= llen;1833}18341835 frag =xcalloc(1,sizeof(*frag));1836 frag->patch =inflate_it(data, hunk_size, origlen);1837 frag->free_patch =1;1838if(!frag->patch)1839goto corrupt;1840free(data);1841 frag->size = origlen;1842*buf_p = buffer;1843*sz_p = size;1844*used_p = used;1845 frag->binary_patch_method = patch_method;1846return frag;18471848 corrupt:1849free(data);1850*status_p = -1;1851error(_("corrupt binary patch at line%d: %.*s"),1852 state->linenr-1, llen-1, buffer);1853return NULL;1854}18551856/*1857 * Returns:1858 * -1 in case of error,1859 * the length of the parsed binary patch otherwise1860 */1861static intparse_binary(struct apply_state *state,1862char*buffer,1863unsigned long size,1864struct patch *patch)1865{1866/*1867 * We have read "GIT binary patch\n"; what follows is a line1868 * that says the patch method (currently, either "literal" or1869 * "delta") and the length of data before deflating; a1870 * sequence of 'length-byte' followed by base-85 encoded data1871 * follows.1872 *1873 * When a binary patch is reversible, there is another binary1874 * hunk in the same format, starting with patch method (either1875 * "literal" or "delta") with the length of data, and a sequence1876 * of length-byte + base-85 encoded data, terminated with another1877 * empty line. This data, when applied to the postimage, produces1878 * the preimage.1879 */1880struct fragment *forward;1881struct fragment *reverse;1882int status;1883int used, used_1;18841885 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1886if(!forward && !status)1887/* there has to be one hunk (forward hunk) */1888returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1889if(status)1890/* otherwise we already gave an error message */1891return status;18921893 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1894if(reverse)1895 used += used_1;1896else if(status) {1897/*1898 * Not having reverse hunk is not an error, but having1899 * a corrupt reverse hunk is.1900 */1901free((void*) forward->patch);1902free(forward);1903return status;1904}1905 forward->next = reverse;1906 patch->fragments = forward;1907 patch->is_binary =1;1908return used;1909}19101911static voidprefix_one(struct apply_state *state,char**name)1912{1913char*old_name = *name;1914if(!old_name)1915return;1916*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1917free(old_name);1918}19191920static voidprefix_patch(struct apply_state *state,struct patch *p)1921{1922if(!state->prefix || p->is_toplevel_relative)1923return;1924prefix_one(state, &p->new_name);1925prefix_one(state, &p->old_name);1926}19271928/*1929 * include/exclude1930 */19311932static voidadd_name_limit(struct apply_state *state,1933const char*name,1934int exclude)1935{1936struct string_list_item *it;19371938 it =string_list_append(&state->limit_by_name, name);1939 it->util = exclude ? NULL : (void*)1;1940}19411942static intuse_patch(struct apply_state *state,struct patch *p)1943{1944const char*pathname = p->new_name ? p->new_name : p->old_name;1945int i;19461947/* Paths outside are not touched regardless of "--include" */1948if(0< state->prefix_length) {1949int pathlen =strlen(pathname);1950if(pathlen <= state->prefix_length ||1951memcmp(state->prefix, pathname, state->prefix_length))1952return0;1953}19541955/* See if it matches any of exclude/include rule */1956for(i =0; i < state->limit_by_name.nr; i++) {1957struct string_list_item *it = &state->limit_by_name.items[i];1958if(!wildmatch(it->string, pathname,0, NULL))1959return(it->util != NULL);1960}19611962/*1963 * If we had any include, a path that does not match any rule is1964 * not used. Otherwise, we saw bunch of exclude rules (or none)1965 * and such a path is used.1966 */1967return!state->has_include;1968}19691970/*1971 * Read the patch text in "buffer" that extends for "size" bytes; stop1972 * reading after seeing a single patch (i.e. changes to a single file).1973 * Create fragments (i.e. patch hunks) and hang them to the given patch.1974 *1975 * Returns:1976 * -1 if no header was found or parse_binary() failed,1977 * -128 on another error,1978 * the number of bytes consumed otherwise,1979 * so that the caller can call us again for the next patch.1980 */1981static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1982{1983int hdrsize, patchsize;1984int offset =find_header(state, buffer, size, &hdrsize, patch);19851986if(offset <0)1987return offset;19881989prefix_patch(state, patch);19901991if(!use_patch(state, patch))1992 patch->ws_rule =0;1993else1994 patch->ws_rule =whitespace_rule(patch->new_name1995? patch->new_name1996: patch->old_name);19971998 patchsize =parse_single_patch(state,1999 buffer + offset + hdrsize,2000 size - offset - hdrsize,2001 patch);20022003if(patchsize <0)2004return-128;20052006if(!patchsize) {2007static const char git_binary[] ="GIT binary patch\n";2008int hd = hdrsize + offset;2009unsigned long llen =linelen(buffer + hd, size - hd);20102011if(llen ==sizeof(git_binary) -1&&2012!memcmp(git_binary, buffer + hd, llen)) {2013int used;2014 state->linenr++;2015 used =parse_binary(state, buffer + hd + llen,2016 size - hd - llen, patch);2017if(used <0)2018return-1;2019if(used)2020 patchsize = used + llen;2021else2022 patchsize =0;2023}2024else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2025static const char*binhdr[] = {2026"Binary files ",2027"Files ",2028 NULL,2029};2030int i;2031for(i =0; binhdr[i]; i++) {2032int len =strlen(binhdr[i]);2033if(len < size - hd &&2034!memcmp(binhdr[i], buffer + hd, len)) {2035 state->linenr++;2036 patch->is_binary =1;2037 patchsize = llen;2038break;2039}2040}2041}20422043/* Empty patch cannot be applied if it is a text patch2044 * without metadata change. A binary patch appears2045 * empty to us here.2046 */2047if((state->apply || state->check) &&2048(!patch->is_binary && !metadata_changes(patch))) {2049error(_("patch with only garbage at line%d"), state->linenr);2050return-128;2051}2052}20532054return offset + hdrsize + patchsize;2055}20562057#define swap(a,b) myswap((a),(b),sizeof(a))20582059#define myswap(a, b, size) do { \2060 unsigned char mytmp[size]; \2061 memcpy(mytmp, &a, size); \2062 memcpy(&a, &b, size); \2063 memcpy(&b, mytmp, size); \2064} while (0)20652066static voidreverse_patches(struct patch *p)2067{2068for(; p; p = p->next) {2069struct fragment *frag = p->fragments;20702071swap(p->new_name, p->old_name);2072swap(p->new_mode, p->old_mode);2073swap(p->is_new, p->is_delete);2074swap(p->lines_added, p->lines_deleted);2075swap(p->old_sha1_prefix, p->new_sha1_prefix);20762077for(; frag; frag = frag->next) {2078swap(frag->newpos, frag->oldpos);2079swap(frag->newlines, frag->oldlines);2080}2081}2082}20832084static const char pluses[] =2085"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2086static const char minuses[]=2087"----------------------------------------------------------------------";20882089static voidshow_stats(struct apply_state *state,struct patch *patch)2090{2091struct strbuf qname = STRBUF_INIT;2092char*cp = patch->new_name ? patch->new_name : patch->old_name;2093int max, add, del;20942095quote_c_style(cp, &qname, NULL,0);20962097/*2098 * "scale" the filename2099 */2100 max = state->max_len;2101if(max >50)2102 max =50;21032104if(qname.len > max) {2105 cp =strchr(qname.buf + qname.len +3- max,'/');2106if(!cp)2107 cp = qname.buf + qname.len +3- max;2108strbuf_splice(&qname,0, cp - qname.buf,"...",3);2109}21102111if(patch->is_binary) {2112printf(" %-*s | Bin\n", max, qname.buf);2113strbuf_release(&qname);2114return;2115}21162117printf(" %-*s |", max, qname.buf);2118strbuf_release(&qname);21192120/*2121 * scale the add/delete2122 */2123 max = max + state->max_change >70?70- max : state->max_change;2124 add = patch->lines_added;2125 del = patch->lines_deleted;21262127if(state->max_change >0) {2128int total = ((add + del) * max + state->max_change /2) / state->max_change;2129 add = (add * max + state->max_change /2) / state->max_change;2130 del = total - add;2131}2132printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2133 add, pluses, del, minuses);2134}21352136static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2137{2138switch(st->st_mode & S_IFMT) {2139case S_IFLNK:2140if(strbuf_readlink(buf, path, st->st_size) <0)2141returnerror(_("unable to read symlink%s"), path);2142return0;2143case S_IFREG:2144if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2145returnerror(_("unable to open or read%s"), path);2146convert_to_git(path, buf->buf, buf->len, buf,0);2147return0;2148default:2149return-1;2150}2151}21522153/*2154 * Update the preimage, and the common lines in postimage,2155 * from buffer buf of length len. If postlen is 0 the postimage2156 * is updated in place, otherwise it's updated on a new buffer2157 * of length postlen2158 */21592160static voidupdate_pre_post_images(struct image *preimage,2161struct image *postimage,2162char*buf,2163size_t len,size_t postlen)2164{2165int i, ctx, reduced;2166char*new, *old, *fixed;2167struct image fixed_preimage;21682169/*2170 * Update the preimage with whitespace fixes. Note that we2171 * are not losing preimage->buf -- apply_one_fragment() will2172 * free "oldlines".2173 */2174prepare_image(&fixed_preimage, buf, len,1);2175assert(postlen2176? fixed_preimage.nr == preimage->nr2177: fixed_preimage.nr <= preimage->nr);2178for(i =0; i < fixed_preimage.nr; i++)2179 fixed_preimage.line[i].flag = preimage->line[i].flag;2180free(preimage->line_allocated);2181*preimage = fixed_preimage;21822183/*2184 * Adjust the common context lines in postimage. This can be2185 * done in-place when we are shrinking it with whitespace2186 * fixing, but needs a new buffer when ignoring whitespace or2187 * expanding leading tabs to spaces.2188 *2189 * We trust the caller to tell us if the update can be done2190 * in place (postlen==0) or not.2191 */2192 old = postimage->buf;2193if(postlen)2194new= postimage->buf =xmalloc(postlen);2195else2196new= old;2197 fixed = preimage->buf;21982199for(i = reduced = ctx =0; i < postimage->nr; i++) {2200size_t l_len = postimage->line[i].len;2201if(!(postimage->line[i].flag & LINE_COMMON)) {2202/* an added line -- no counterparts in preimage */2203memmove(new, old, l_len);2204 old += l_len;2205new+= l_len;2206continue;2207}22082209/* a common context -- skip it in the original postimage */2210 old += l_len;22112212/* and find the corresponding one in the fixed preimage */2213while(ctx < preimage->nr &&2214!(preimage->line[ctx].flag & LINE_COMMON)) {2215 fixed += preimage->line[ctx].len;2216 ctx++;2217}22182219/*2220 * preimage is expected to run out, if the caller2221 * fixed addition of trailing blank lines.2222 */2223if(preimage->nr <= ctx) {2224 reduced++;2225continue;2226}22272228/* and copy it in, while fixing the line length */2229 l_len = preimage->line[ctx].len;2230memcpy(new, fixed, l_len);2231new+= l_len;2232 fixed += l_len;2233 postimage->line[i].len = l_len;2234 ctx++;2235}22362237if(postlen2238? postlen <new- postimage->buf2239: postimage->len <new- postimage->buf)2240die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2241(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22422243/* Fix the length of the whole thing */2244 postimage->len =new- postimage->buf;2245 postimage->nr -= reduced;2246}22472248static intline_by_line_fuzzy_match(struct image *img,2249struct image *preimage,2250struct image *postimage,2251unsigned longtry,2252int try_lno,2253int preimage_limit)2254{2255int i;2256size_t imgoff =0;2257size_t preoff =0;2258size_t postlen = postimage->len;2259size_t extra_chars;2260char*buf;2261char*preimage_eof;2262char*preimage_end;2263struct strbuf fixed;2264char*fixed_buf;2265size_t fixed_len;22662267for(i =0; i < preimage_limit; i++) {2268size_t prelen = preimage->line[i].len;2269size_t imglen = img->line[try_lno+i].len;22702271if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2272 preimage->buf + preoff, prelen))2273return0;2274if(preimage->line[i].flag & LINE_COMMON)2275 postlen += imglen - prelen;2276 imgoff += imglen;2277 preoff += prelen;2278}22792280/*2281 * Ok, the preimage matches with whitespace fuzz.2282 *2283 * imgoff now holds the true length of the target that2284 * matches the preimage before the end of the file.2285 *2286 * Count the number of characters in the preimage that fall2287 * beyond the end of the file and make sure that all of them2288 * are whitespace characters. (This can only happen if2289 * we are removing blank lines at the end of the file.)2290 */2291 buf = preimage_eof = preimage->buf + preoff;2292for( ; i < preimage->nr; i++)2293 preoff += preimage->line[i].len;2294 preimage_end = preimage->buf + preoff;2295for( ; buf < preimage_end; buf++)2296if(!isspace(*buf))2297return0;22982299/*2300 * Update the preimage and the common postimage context2301 * lines to use the same whitespace as the target.2302 * If whitespace is missing in the target (i.e.2303 * if the preimage extends beyond the end of the file),2304 * use the whitespace from the preimage.2305 */2306 extra_chars = preimage_end - preimage_eof;2307strbuf_init(&fixed, imgoff + extra_chars);2308strbuf_add(&fixed, img->buf +try, imgoff);2309strbuf_add(&fixed, preimage_eof, extra_chars);2310 fixed_buf =strbuf_detach(&fixed, &fixed_len);2311update_pre_post_images(preimage, postimage,2312 fixed_buf, fixed_len, postlen);2313return1;2314}23152316static intmatch_fragment(struct apply_state *state,2317struct image *img,2318struct image *preimage,2319struct image *postimage,2320unsigned longtry,2321int try_lno,2322unsigned ws_rule,2323int match_beginning,int match_end)2324{2325int i;2326char*fixed_buf, *buf, *orig, *target;2327struct strbuf fixed;2328size_t fixed_len, postlen;2329int preimage_limit;23302331if(preimage->nr + try_lno <= img->nr) {2332/*2333 * The hunk falls within the boundaries of img.2334 */2335 preimage_limit = preimage->nr;2336if(match_end && (preimage->nr + try_lno != img->nr))2337return0;2338}else if(state->ws_error_action == correct_ws_error &&2339(ws_rule & WS_BLANK_AT_EOF)) {2340/*2341 * This hunk extends beyond the end of img, and we are2342 * removing blank lines at the end of the file. This2343 * many lines from the beginning of the preimage must2344 * match with img, and the remainder of the preimage2345 * must be blank.2346 */2347 preimage_limit = img->nr - try_lno;2348}else{2349/*2350 * The hunk extends beyond the end of the img and2351 * we are not removing blanks at the end, so we2352 * should reject the hunk at this position.2353 */2354return0;2355}23562357if(match_beginning && try_lno)2358return0;23592360/* Quick hash check */2361for(i =0; i < preimage_limit; i++)2362if((img->line[try_lno + i].flag & LINE_PATCHED) ||2363(preimage->line[i].hash != img->line[try_lno + i].hash))2364return0;23652366if(preimage_limit == preimage->nr) {2367/*2368 * Do we have an exact match? If we were told to match2369 * at the end, size must be exactly at try+fragsize,2370 * otherwise try+fragsize must be still within the preimage,2371 * and either case, the old piece should match the preimage2372 * exactly.2373 */2374if((match_end2375? (try+ preimage->len == img->len)2376: (try+ preimage->len <= img->len)) &&2377!memcmp(img->buf +try, preimage->buf, preimage->len))2378return1;2379}else{2380/*2381 * The preimage extends beyond the end of img, so2382 * there cannot be an exact match.2383 *2384 * There must be one non-blank context line that match2385 * a line before the end of img.2386 */2387char*buf_end;23882389 buf = preimage->buf;2390 buf_end = buf;2391for(i =0; i < preimage_limit; i++)2392 buf_end += preimage->line[i].len;23932394for( ; buf < buf_end; buf++)2395if(!isspace(*buf))2396break;2397if(buf == buf_end)2398return0;2399}24002401/*2402 * No exact match. If we are ignoring whitespace, run a line-by-line2403 * fuzzy matching. We collect all the line length information because2404 * we need it to adjust whitespace if we match.2405 */2406if(state->ws_ignore_action == ignore_ws_change)2407returnline_by_line_fuzzy_match(img, preimage, postimage,2408try, try_lno, preimage_limit);24092410if(state->ws_error_action != correct_ws_error)2411return0;24122413/*2414 * The hunk does not apply byte-by-byte, but the hash says2415 * it might with whitespace fuzz. We weren't asked to2416 * ignore whitespace, we were asked to correct whitespace2417 * errors, so let's try matching after whitespace correction.2418 *2419 * While checking the preimage against the target, whitespace2420 * errors in both fixed, we count how large the corresponding2421 * postimage needs to be. The postimage prepared by2422 * apply_one_fragment() has whitespace errors fixed on added2423 * lines already, but the common lines were propagated as-is,2424 * which may become longer when their whitespace errors are2425 * fixed.2426 */24272428/* First count added lines in postimage */2429 postlen =0;2430for(i =0; i < postimage->nr; i++) {2431if(!(postimage->line[i].flag & LINE_COMMON))2432 postlen += postimage->line[i].len;2433}24342435/*2436 * The preimage may extend beyond the end of the file,2437 * but in this loop we will only handle the part of the2438 * preimage that falls within the file.2439 */2440strbuf_init(&fixed, preimage->len +1);2441 orig = preimage->buf;2442 target = img->buf +try;2443for(i =0; i < preimage_limit; i++) {2444size_t oldlen = preimage->line[i].len;2445size_t tgtlen = img->line[try_lno + i].len;2446size_t fixstart = fixed.len;2447struct strbuf tgtfix;2448int match;24492450/* Try fixing the line in the preimage */2451ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24522453/* Try fixing the line in the target */2454strbuf_init(&tgtfix, tgtlen);2455ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24562457/*2458 * If they match, either the preimage was based on2459 * a version before our tree fixed whitespace breakage,2460 * or we are lacking a whitespace-fix patch the tree2461 * the preimage was based on already had (i.e. target2462 * has whitespace breakage, the preimage doesn't).2463 * In either case, we are fixing the whitespace breakages2464 * so we might as well take the fix together with their2465 * real change.2466 */2467 match = (tgtfix.len == fixed.len - fixstart &&2468!memcmp(tgtfix.buf, fixed.buf + fixstart,2469 fixed.len - fixstart));24702471/* Add the length if this is common with the postimage */2472if(preimage->line[i].flag & LINE_COMMON)2473 postlen += tgtfix.len;24742475strbuf_release(&tgtfix);2476if(!match)2477goto unmatch_exit;24782479 orig += oldlen;2480 target += tgtlen;2481}248224832484/*2485 * Now handle the lines in the preimage that falls beyond the2486 * end of the file (if any). They will only match if they are2487 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2488 * false).2489 */2490for( ; i < preimage->nr; i++) {2491size_t fixstart = fixed.len;/* start of the fixed preimage */2492size_t oldlen = preimage->line[i].len;2493int j;24942495/* Try fixing the line in the preimage */2496ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24972498for(j = fixstart; j < fixed.len; j++)2499if(!isspace(fixed.buf[j]))2500goto unmatch_exit;25012502 orig += oldlen;2503}25042505/*2506 * Yes, the preimage is based on an older version that still2507 * has whitespace breakages unfixed, and fixing them makes the2508 * hunk match. Update the context lines in the postimage.2509 */2510 fixed_buf =strbuf_detach(&fixed, &fixed_len);2511if(postlen < postimage->len)2512 postlen =0;2513update_pre_post_images(preimage, postimage,2514 fixed_buf, fixed_len, postlen);2515return1;25162517 unmatch_exit:2518strbuf_release(&fixed);2519return0;2520}25212522static intfind_pos(struct apply_state *state,2523struct image *img,2524struct image *preimage,2525struct image *postimage,2526int line,2527unsigned ws_rule,2528int match_beginning,int match_end)2529{2530int i;2531unsigned long backwards, forwards,try;2532int backwards_lno, forwards_lno, try_lno;25332534/*2535 * If match_beginning or match_end is specified, there is no2536 * point starting from a wrong line that will never match and2537 * wander around and wait for a match at the specified end.2538 */2539if(match_beginning)2540 line =0;2541else if(match_end)2542 line = img->nr - preimage->nr;25432544/*2545 * Because the comparison is unsigned, the following test2546 * will also take care of a negative line number that can2547 * result when match_end and preimage is larger than the target.2548 */2549if((size_t) line > img->nr)2550 line = img->nr;25512552try=0;2553for(i =0; i < line; i++)2554try+= img->line[i].len;25552556/*2557 * There's probably some smart way to do this, but I'll leave2558 * that to the smart and beautiful people. I'm simple and stupid.2559 */2560 backwards =try;2561 backwards_lno = line;2562 forwards =try;2563 forwards_lno = line;2564 try_lno = line;25652566for(i =0; ; i++) {2567if(match_fragment(state, img, preimage, postimage,2568try, try_lno, ws_rule,2569 match_beginning, match_end))2570return try_lno;25712572 again:2573if(backwards_lno ==0&& forwards_lno == img->nr)2574break;25752576if(i &1) {2577if(backwards_lno ==0) {2578 i++;2579goto again;2580}2581 backwards_lno--;2582 backwards -= img->line[backwards_lno].len;2583try= backwards;2584 try_lno = backwards_lno;2585}else{2586if(forwards_lno == img->nr) {2587 i++;2588goto again;2589}2590 forwards += img->line[forwards_lno].len;2591 forwards_lno++;2592try= forwards;2593 try_lno = forwards_lno;2594}25952596}2597return-1;2598}25992600static voidremove_first_line(struct image *img)2601{2602 img->buf += img->line[0].len;2603 img->len -= img->line[0].len;2604 img->line++;2605 img->nr--;2606}26072608static voidremove_last_line(struct image *img)2609{2610 img->len -= img->line[--img->nr].len;2611}26122613/*2614 * The change from "preimage" and "postimage" has been found to2615 * apply at applied_pos (counts in line numbers) in "img".2616 * Update "img" to remove "preimage" and replace it with "postimage".2617 */2618static voidupdate_image(struct apply_state *state,2619struct image *img,2620int applied_pos,2621struct image *preimage,2622struct image *postimage)2623{2624/*2625 * remove the copy of preimage at offset in img2626 * and replace it with postimage2627 */2628int i, nr;2629size_t remove_count, insert_count, applied_at =0;2630char*result;2631int preimage_limit;26322633/*2634 * If we are removing blank lines at the end of img,2635 * the preimage may extend beyond the end.2636 * If that is the case, we must be careful only to2637 * remove the part of the preimage that falls within2638 * the boundaries of img. Initialize preimage_limit2639 * to the number of lines in the preimage that falls2640 * within the boundaries.2641 */2642 preimage_limit = preimage->nr;2643if(preimage_limit > img->nr - applied_pos)2644 preimage_limit = img->nr - applied_pos;26452646for(i =0; i < applied_pos; i++)2647 applied_at += img->line[i].len;26482649 remove_count =0;2650for(i =0; i < preimage_limit; i++)2651 remove_count += img->line[applied_pos + i].len;2652 insert_count = postimage->len;26532654/* Adjust the contents */2655 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2656memcpy(result, img->buf, applied_at);2657memcpy(result + applied_at, postimage->buf, postimage->len);2658memcpy(result + applied_at + postimage->len,2659 img->buf + (applied_at + remove_count),2660 img->len - (applied_at + remove_count));2661free(img->buf);2662 img->buf = result;2663 img->len += insert_count - remove_count;2664 result[img->len] ='\0';26652666/* Adjust the line table */2667 nr = img->nr + postimage->nr - preimage_limit;2668if(preimage_limit < postimage->nr) {2669/*2670 * NOTE: this knows that we never call remove_first_line()2671 * on anything other than pre/post image.2672 */2673REALLOC_ARRAY(img->line, nr);2674 img->line_allocated = img->line;2675}2676if(preimage_limit != postimage->nr)2677memmove(img->line + applied_pos + postimage->nr,2678 img->line + applied_pos + preimage_limit,2679(img->nr - (applied_pos + preimage_limit)) *2680sizeof(*img->line));2681memcpy(img->line + applied_pos,2682 postimage->line,2683 postimage->nr *sizeof(*img->line));2684if(!state->allow_overlap)2685for(i =0; i < postimage->nr; i++)2686 img->line[applied_pos + i].flag |= LINE_PATCHED;2687 img->nr = nr;2688}26892690/*2691 * Use the patch-hunk text in "frag" to prepare two images (preimage and2692 * postimage) for the hunk. Find lines that match "preimage" in "img" and2693 * replace the part of "img" with "postimage" text.2694 */2695static intapply_one_fragment(struct apply_state *state,2696struct image *img,struct fragment *frag,2697int inaccurate_eof,unsigned ws_rule,2698int nth_fragment)2699{2700int match_beginning, match_end;2701const char*patch = frag->patch;2702int size = frag->size;2703char*old, *oldlines;2704struct strbuf newlines;2705int new_blank_lines_at_end =0;2706int found_new_blank_lines_at_end =0;2707int hunk_linenr = frag->linenr;2708unsigned long leading, trailing;2709int pos, applied_pos;2710struct image preimage;2711struct image postimage;27122713memset(&preimage,0,sizeof(preimage));2714memset(&postimage,0,sizeof(postimage));2715 oldlines =xmalloc(size);2716strbuf_init(&newlines, size);27172718 old = oldlines;2719while(size >0) {2720char first;2721int len =linelen(patch, size);2722int plen;2723int added_blank_line =0;2724int is_blank_context =0;2725size_t start;27262727if(!len)2728break;27292730/*2731 * "plen" is how much of the line we should use for2732 * the actual patch data. Normally we just remove the2733 * first character on the line, but if the line is2734 * followed by "\ No newline", then we also remove the2735 * last one (which is the newline, of course).2736 */2737 plen = len -1;2738if(len < size && patch[len] =='\\')2739 plen--;2740 first = *patch;2741if(state->apply_in_reverse) {2742if(first =='-')2743 first ='+';2744else if(first =='+')2745 first ='-';2746}27472748switch(first) {2749case'\n':2750/* Newer GNU diff, empty context line */2751if(plen <0)2752/* ... followed by '\No newline'; nothing */2753break;2754*old++ ='\n';2755strbuf_addch(&newlines,'\n');2756add_line_info(&preimage,"\n",1, LINE_COMMON);2757add_line_info(&postimage,"\n",1, LINE_COMMON);2758 is_blank_context =1;2759break;2760case' ':2761if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2762ws_blank_line(patch +1, plen, ws_rule))2763 is_blank_context =1;2764case'-':2765memcpy(old, patch +1, plen);2766add_line_info(&preimage, old, plen,2767(first ==' '? LINE_COMMON :0));2768 old += plen;2769if(first =='-')2770break;2771/* Fall-through for ' ' */2772case'+':2773/* --no-add does not add new lines */2774if(first =='+'&& state->no_add)2775break;27762777 start = newlines.len;2778if(first !='+'||2779!state->whitespace_error ||2780 state->ws_error_action != correct_ws_error) {2781strbuf_add(&newlines, patch +1, plen);2782}2783else{2784ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2785}2786add_line_info(&postimage, newlines.buf + start, newlines.len - start,2787(first =='+'?0: LINE_COMMON));2788if(first =='+'&&2789(ws_rule & WS_BLANK_AT_EOF) &&2790ws_blank_line(patch +1, plen, ws_rule))2791 added_blank_line =1;2792break;2793case'@':case'\\':2794/* Ignore it, we already handled it */2795break;2796default:2797if(state->apply_verbosely)2798error(_("invalid start of line: '%c'"), first);2799 applied_pos = -1;2800goto out;2801}2802if(added_blank_line) {2803if(!new_blank_lines_at_end)2804 found_new_blank_lines_at_end = hunk_linenr;2805 new_blank_lines_at_end++;2806}2807else if(is_blank_context)2808;2809else2810 new_blank_lines_at_end =0;2811 patch += len;2812 size -= len;2813 hunk_linenr++;2814}2815if(inaccurate_eof &&2816 old > oldlines && old[-1] =='\n'&&2817 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2818 old--;2819strbuf_setlen(&newlines, newlines.len -1);2820}28212822 leading = frag->leading;2823 trailing = frag->trailing;28242825/*2826 * A hunk to change lines at the beginning would begin with2827 * @@ -1,L +N,M @@2828 * but we need to be careful. -U0 that inserts before the second2829 * line also has this pattern.2830 *2831 * And a hunk to add to an empty file would begin with2832 * @@ -0,0 +N,M @@2833 *2834 * In other words, a hunk that is (frag->oldpos <= 1) with or2835 * without leading context must match at the beginning.2836 */2837 match_beginning = (!frag->oldpos ||2838(frag->oldpos ==1&& !state->unidiff_zero));28392840/*2841 * A hunk without trailing lines must match at the end.2842 * However, we simply cannot tell if a hunk must match end2843 * from the lack of trailing lines if the patch was generated2844 * with unidiff without any context.2845 */2846 match_end = !state->unidiff_zero && !trailing;28472848 pos = frag->newpos ? (frag->newpos -1) :0;2849 preimage.buf = oldlines;2850 preimage.len = old - oldlines;2851 postimage.buf = newlines.buf;2852 postimage.len = newlines.len;2853 preimage.line = preimage.line_allocated;2854 postimage.line = postimage.line_allocated;28552856for(;;) {28572858 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2859 ws_rule, match_beginning, match_end);28602861if(applied_pos >=0)2862break;28632864/* Am I at my context limits? */2865if((leading <= state->p_context) && (trailing <= state->p_context))2866break;2867if(match_beginning || match_end) {2868 match_beginning = match_end =0;2869continue;2870}28712872/*2873 * Reduce the number of context lines; reduce both2874 * leading and trailing if they are equal otherwise2875 * just reduce the larger context.2876 */2877if(leading >= trailing) {2878remove_first_line(&preimage);2879remove_first_line(&postimage);2880 pos--;2881 leading--;2882}2883if(trailing > leading) {2884remove_last_line(&preimage);2885remove_last_line(&postimage);2886 trailing--;2887}2888}28892890if(applied_pos >=0) {2891if(new_blank_lines_at_end &&2892 preimage.nr + applied_pos >= img->nr &&2893(ws_rule & WS_BLANK_AT_EOF) &&2894 state->ws_error_action != nowarn_ws_error) {2895record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2896 found_new_blank_lines_at_end);2897if(state->ws_error_action == correct_ws_error) {2898while(new_blank_lines_at_end--)2899remove_last_line(&postimage);2900}2901/*2902 * We would want to prevent write_out_results()2903 * from taking place in apply_patch() that follows2904 * the callchain led us here, which is:2905 * apply_patch->check_patch_list->check_patch->2906 * apply_data->apply_fragments->apply_one_fragment2907 */2908if(state->ws_error_action == die_on_ws_error)2909 state->apply =0;2910}29112912if(state->apply_verbosely && applied_pos != pos) {2913int offset = applied_pos - pos;2914if(state->apply_in_reverse)2915 offset =0- offset;2916fprintf_ln(stderr,2917Q_("Hunk #%dsucceeded at%d(offset%dline).",2918"Hunk #%dsucceeded at%d(offset%dlines).",2919 offset),2920 nth_fragment, applied_pos +1, offset);2921}29222923/*2924 * Warn if it was necessary to reduce the number2925 * of context lines.2926 */2927if((leading != frag->leading) ||2928(trailing != frag->trailing))2929fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2930" to apply fragment at%d"),2931 leading, trailing, applied_pos+1);2932update_image(state, img, applied_pos, &preimage, &postimage);2933}else{2934if(state->apply_verbosely)2935error(_("while searching for:\n%.*s"),2936(int)(old - oldlines), oldlines);2937}29382939out:2940free(oldlines);2941strbuf_release(&newlines);2942free(preimage.line_allocated);2943free(postimage.line_allocated);29442945return(applied_pos <0);2946}29472948static intapply_binary_fragment(struct apply_state *state,2949struct image *img,2950struct patch *patch)2951{2952struct fragment *fragment = patch->fragments;2953unsigned long len;2954void*dst;29552956if(!fragment)2957returnerror(_("missing binary patch data for '%s'"),2958 patch->new_name ?2959 patch->new_name :2960 patch->old_name);29612962/* Binary patch is irreversible without the optional second hunk */2963if(state->apply_in_reverse) {2964if(!fragment->next)2965returnerror("cannot reverse-apply a binary patch "2966"without the reverse hunk to '%s'",2967 patch->new_name2968? patch->new_name : patch->old_name);2969 fragment = fragment->next;2970}2971switch(fragment->binary_patch_method) {2972case BINARY_DELTA_DEFLATED:2973 dst =patch_delta(img->buf, img->len, fragment->patch,2974 fragment->size, &len);2975if(!dst)2976return-1;2977clear_image(img);2978 img->buf = dst;2979 img->len = len;2980return0;2981case BINARY_LITERAL_DEFLATED:2982clear_image(img);2983 img->len = fragment->size;2984 img->buf =xmemdupz(fragment->patch, img->len);2985return0;2986}2987return-1;2988}29892990/*2991 * Replace "img" with the result of applying the binary patch.2992 * The binary patch data itself in patch->fragment is still kept2993 * but the preimage prepared by the caller in "img" is freed here2994 * or in the helper function apply_binary_fragment() this calls.2995 */2996static intapply_binary(struct apply_state *state,2997struct image *img,2998struct patch *patch)2999{3000const char*name = patch->old_name ? patch->old_name : patch->new_name;3001unsigned char sha1[20];30023003/*3004 * For safety, we require patch index line to contain3005 * full 40-byte textual SHA1 for old and new, at least for now.3006 */3007if(strlen(patch->old_sha1_prefix) !=40||3008strlen(patch->new_sha1_prefix) !=40||3009get_sha1_hex(patch->old_sha1_prefix, sha1) ||3010get_sha1_hex(patch->new_sha1_prefix, sha1))3011returnerror("cannot apply binary patch to '%s' "3012"without full index line", name);30133014if(patch->old_name) {3015/*3016 * See if the old one matches what the patch3017 * applies to.3018 */3019hash_sha1_file(img->buf, img->len, blob_type, sha1);3020if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3021returnerror("the patch applies to '%s' (%s), "3022"which does not match the "3023"current contents.",3024 name,sha1_to_hex(sha1));3025}3026else{3027/* Otherwise, the old one must be empty. */3028if(img->len)3029returnerror("the patch applies to an empty "3030"'%s' but it is not empty", name);3031}30323033get_sha1_hex(patch->new_sha1_prefix, sha1);3034if(is_null_sha1(sha1)) {3035clear_image(img);3036return0;/* deletion patch */3037}30383039if(has_sha1_file(sha1)) {3040/* We already have the postimage */3041enum object_type type;3042unsigned long size;3043char*result;30443045 result =read_sha1_file(sha1, &type, &size);3046if(!result)3047returnerror("the necessary postimage%sfor "3048"'%s' cannot be read",3049 patch->new_sha1_prefix, name);3050clear_image(img);3051 img->buf = result;3052 img->len = size;3053}else{3054/*3055 * We have verified buf matches the preimage;3056 * apply the patch data to it, which is stored3057 * in the patch->fragments->{patch,size}.3058 */3059if(apply_binary_fragment(state, img, patch))3060returnerror(_("binary patch does not apply to '%s'"),3061 name);30623063/* verify that the result matches */3064hash_sha1_file(img->buf, img->len, blob_type, sha1);3065if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3066returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3067 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3068}30693070return0;3071}30723073static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3074{3075struct fragment *frag = patch->fragments;3076const char*name = patch->old_name ? patch->old_name : patch->new_name;3077unsigned ws_rule = patch->ws_rule;3078unsigned inaccurate_eof = patch->inaccurate_eof;3079int nth =0;30803081if(patch->is_binary)3082returnapply_binary(state, img, patch);30833084while(frag) {3085 nth++;3086if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3087error(_("patch failed:%s:%ld"), name, frag->oldpos);3088if(!state->apply_with_reject)3089return-1;3090 frag->rejected =1;3091}3092 frag = frag->next;3093}3094return0;3095}30963097static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3098{3099if(S_ISGITLINK(mode)) {3100strbuf_grow(buf,100);3101strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3102}else{3103enum object_type type;3104unsigned long sz;3105char*result;31063107 result =read_sha1_file(sha1, &type, &sz);3108if(!result)3109return-1;3110/* XXX read_sha1_file NUL-terminates */3111strbuf_attach(buf, result, sz, sz +1);3112}3113return0;3114}31153116static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3117{3118if(!ce)3119return0;3120returnread_blob_object(buf, ce->sha1, ce->ce_mode);3121}31223123static struct patch *in_fn_table(struct apply_state *state,const char*name)3124{3125struct string_list_item *item;31263127if(name == NULL)3128return NULL;31293130 item =string_list_lookup(&state->fn_table, name);3131if(item != NULL)3132return(struct patch *)item->util;31333134return NULL;3135}31363137/*3138 * item->util in the filename table records the status of the path.3139 * Usually it points at a patch (whose result records the contents3140 * of it after applying it), but it could be PATH_WAS_DELETED for a3141 * path that a previously applied patch has already removed, or3142 * PATH_TO_BE_DELETED for a path that a later patch would remove.3143 *3144 * The latter is needed to deal with a case where two paths A and B3145 * are swapped by first renaming A to B and then renaming B to A;3146 * moving A to B should not be prevented due to presence of B as we3147 * will remove it in a later patch.3148 */3149#define PATH_TO_BE_DELETED ((struct patch *) -2)3150#define PATH_WAS_DELETED ((struct patch *) -1)31513152static intto_be_deleted(struct patch *patch)3153{3154return patch == PATH_TO_BE_DELETED;3155}31563157static intwas_deleted(struct patch *patch)3158{3159return patch == PATH_WAS_DELETED;3160}31613162static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3163{3164struct string_list_item *item;31653166/*3167 * Always add new_name unless patch is a deletion3168 * This should cover the cases for normal diffs,3169 * file creations and copies3170 */3171if(patch->new_name != NULL) {3172 item =string_list_insert(&state->fn_table, patch->new_name);3173 item->util = patch;3174}31753176/*3177 * store a failure on rename/deletion cases because3178 * later chunks shouldn't patch old names3179 */3180if((patch->new_name == NULL) || (patch->is_rename)) {3181 item =string_list_insert(&state->fn_table, patch->old_name);3182 item->util = PATH_WAS_DELETED;3183}3184}31853186static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3187{3188/*3189 * store information about incoming file deletion3190 */3191while(patch) {3192if((patch->new_name == NULL) || (patch->is_rename)) {3193struct string_list_item *item;3194 item =string_list_insert(&state->fn_table, patch->old_name);3195 item->util = PATH_TO_BE_DELETED;3196}3197 patch = patch->next;3198}3199}32003201static intcheckout_target(struct index_state *istate,3202struct cache_entry *ce,struct stat *st)3203{3204struct checkout costate;32053206memset(&costate,0,sizeof(costate));3207 costate.base_dir ="";3208 costate.refresh_cache =1;3209 costate.istate = istate;3210if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3211returnerror(_("cannot checkout%s"), ce->name);3212return0;3213}32143215static struct patch *previous_patch(struct apply_state *state,3216struct patch *patch,3217int*gone)3218{3219struct patch *previous;32203221*gone =0;3222if(patch->is_copy || patch->is_rename)3223return NULL;/* "git" patches do not depend on the order */32243225 previous =in_fn_table(state, patch->old_name);3226if(!previous)3227return NULL;32283229if(to_be_deleted(previous))3230return NULL;/* the deletion hasn't happened yet */32313232if(was_deleted(previous))3233*gone =1;32343235return previous;3236}32373238static intverify_index_match(const struct cache_entry *ce,struct stat *st)3239{3240if(S_ISGITLINK(ce->ce_mode)) {3241if(!S_ISDIR(st->st_mode))3242return-1;3243return0;3244}3245returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3246}32473248#define SUBMODULE_PATCH_WITHOUT_INDEX 132493250static intload_patch_target(struct apply_state *state,3251struct strbuf *buf,3252const struct cache_entry *ce,3253struct stat *st,3254const char*name,3255unsigned expected_mode)3256{3257if(state->cached || state->check_index) {3258if(read_file_or_gitlink(ce, buf))3259returnerror(_("failed to read%s"), name);3260}else if(name) {3261if(S_ISGITLINK(expected_mode)) {3262if(ce)3263returnread_file_or_gitlink(ce, buf);3264else3265return SUBMODULE_PATCH_WITHOUT_INDEX;3266}else if(has_symlink_leading_path(name,strlen(name))) {3267returnerror(_("reading from '%s' beyond a symbolic link"), name);3268}else{3269if(read_old_data(st, name, buf))3270returnerror(_("failed to read%s"), name);3271}3272}3273return0;3274}32753276/*3277 * We are about to apply "patch"; populate the "image" with the3278 * current version we have, from the working tree or from the index,3279 * depending on the situation e.g. --cached/--index. If we are3280 * applying a non-git patch that incrementally updates the tree,3281 * we read from the result of a previous diff.3282 */3283static intload_preimage(struct apply_state *state,3284struct image *image,3285struct patch *patch,struct stat *st,3286const struct cache_entry *ce)3287{3288struct strbuf buf = STRBUF_INIT;3289size_t len;3290char*img;3291struct patch *previous;3292int status;32933294 previous =previous_patch(state, patch, &status);3295if(status)3296returnerror(_("path%shas been renamed/deleted"),3297 patch->old_name);3298if(previous) {3299/* We have a patched copy in memory; use that. */3300strbuf_add(&buf, previous->result, previous->resultsize);3301}else{3302 status =load_patch_target(state, &buf, ce, st,3303 patch->old_name, patch->old_mode);3304if(status <0)3305return status;3306else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3307/*3308 * There is no way to apply subproject3309 * patch without looking at the index.3310 * NEEDSWORK: shouldn't this be flagged3311 * as an error???3312 */3313free_fragment_list(patch->fragments);3314 patch->fragments = NULL;3315}else if(status) {3316returnerror(_("failed to read%s"), patch->old_name);3317}3318}33193320 img =strbuf_detach(&buf, &len);3321prepare_image(image, img, len, !patch->is_binary);3322return0;3323}33243325static intthree_way_merge(struct image *image,3326char*path,3327const unsigned char*base,3328const unsigned char*ours,3329const unsigned char*theirs)3330{3331 mmfile_t base_file, our_file, their_file;3332 mmbuffer_t result = { NULL };3333int status;33343335read_mmblob(&base_file, base);3336read_mmblob(&our_file, ours);3337read_mmblob(&their_file, theirs);3338 status =ll_merge(&result, path,3339&base_file,"base",3340&our_file,"ours",3341&their_file,"theirs", NULL);3342free(base_file.ptr);3343free(our_file.ptr);3344free(their_file.ptr);3345if(status <0|| !result.ptr) {3346free(result.ptr);3347return-1;3348}3349clear_image(image);3350 image->buf = result.ptr;3351 image->len = result.size;33523353return status;3354}33553356/*3357 * When directly falling back to add/add three-way merge, we read from3358 * the current contents of the new_name. In no cases other than that3359 * this function will be called.3360 */3361static intload_current(struct apply_state *state,3362struct image *image,3363struct patch *patch)3364{3365struct strbuf buf = STRBUF_INIT;3366int status, pos;3367size_t len;3368char*img;3369struct stat st;3370struct cache_entry *ce;3371char*name = patch->new_name;3372unsigned mode = patch->new_mode;33733374if(!patch->is_new)3375die("BUG: patch to%sis not a creation", patch->old_name);33763377 pos =cache_name_pos(name,strlen(name));3378if(pos <0)3379returnerror(_("%s: does not exist in index"), name);3380 ce = active_cache[pos];3381if(lstat(name, &st)) {3382if(errno != ENOENT)3383returnerror(_("%s:%s"), name,strerror(errno));3384if(checkout_target(&the_index, ce, &st))3385return-1;3386}3387if(verify_index_match(ce, &st))3388returnerror(_("%s: does not match index"), name);33893390 status =load_patch_target(state, &buf, ce, &st, name, mode);3391if(status <0)3392return status;3393else if(status)3394return-1;3395 img =strbuf_detach(&buf, &len);3396prepare_image(image, img, len, !patch->is_binary);3397return0;3398}33993400static inttry_threeway(struct apply_state *state,3401struct image *image,3402struct patch *patch,3403struct stat *st,3404const struct cache_entry *ce)3405{3406unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3407struct strbuf buf = STRBUF_INIT;3408size_t len;3409int status;3410char*img;3411struct image tmp_image;34123413/* No point falling back to 3-way merge in these cases */3414if(patch->is_delete ||3415S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3416return-1;34173418/* Preimage the patch was prepared for */3419if(patch->is_new)3420write_sha1_file("",0, blob_type, pre_sha1);3421else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3422read_blob_object(&buf, pre_sha1, patch->old_mode))3423returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34243425fprintf(stderr,"Falling back to three-way merge...\n");34263427 img =strbuf_detach(&buf, &len);3428prepare_image(&tmp_image, img, len,1);3429/* Apply the patch to get the post image */3430if(apply_fragments(state, &tmp_image, patch) <0) {3431clear_image(&tmp_image);3432return-1;3433}3434/* post_sha1[] is theirs */3435write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3436clear_image(&tmp_image);34373438/* our_sha1[] is ours */3439if(patch->is_new) {3440if(load_current(state, &tmp_image, patch))3441returnerror("cannot read the current contents of '%s'",3442 patch->new_name);3443}else{3444if(load_preimage(state, &tmp_image, patch, st, ce))3445returnerror("cannot read the current contents of '%s'",3446 patch->old_name);3447}3448write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3449clear_image(&tmp_image);34503451/* in-core three-way merge between post and our using pre as base */3452 status =three_way_merge(image, patch->new_name,3453 pre_sha1, our_sha1, post_sha1);3454if(status <0) {3455fprintf(stderr,"Failed to fall back on three-way merge...\n");3456return status;3457}34583459if(status) {3460 patch->conflicted_threeway =1;3461if(patch->is_new)3462oidclr(&patch->threeway_stage[0]);3463else3464hashcpy(patch->threeway_stage[0].hash, pre_sha1);3465hashcpy(patch->threeway_stage[1].hash, our_sha1);3466hashcpy(patch->threeway_stage[2].hash, post_sha1);3467fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3468}else{3469fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3470}3471return0;3472}34733474static intapply_data(struct apply_state *state,struct patch *patch,3475struct stat *st,const struct cache_entry *ce)3476{3477struct image image;34783479if(load_preimage(state, &image, patch, st, ce) <0)3480return-1;34813482if(patch->direct_to_threeway ||3483apply_fragments(state, &image, patch) <0) {3484/* Note: with --reject, apply_fragments() returns 0 */3485if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3486return-1;3487}3488 patch->result = image.buf;3489 patch->resultsize = image.len;3490add_to_fn_table(state, patch);3491free(image.line_allocated);34923493if(0< patch->is_delete && patch->resultsize)3494returnerror(_("removal patch leaves file contents"));34953496return0;3497}34983499/*3500 * If "patch" that we are looking at modifies or deletes what we have,3501 * we would want it not to lose any local modification we have, either3502 * in the working tree or in the index.3503 *3504 * This also decides if a non-git patch is a creation patch or a3505 * modification to an existing empty file. We do not check the state3506 * of the current tree for a creation patch in this function; the caller3507 * check_patch() separately makes sure (and errors out otherwise) that3508 * the path the patch creates does not exist in the current tree.3509 */3510static intcheck_preimage(struct apply_state *state,3511struct patch *patch,3512struct cache_entry **ce,3513struct stat *st)3514{3515const char*old_name = patch->old_name;3516struct patch *previous = NULL;3517int stat_ret =0, status;3518unsigned st_mode =0;35193520if(!old_name)3521return0;35223523assert(patch->is_new <=0);3524 previous =previous_patch(state, patch, &status);35253526if(status)3527returnerror(_("path%shas been renamed/deleted"), old_name);3528if(previous) {3529 st_mode = previous->new_mode;3530}else if(!state->cached) {3531 stat_ret =lstat(old_name, st);3532if(stat_ret && errno != ENOENT)3533returnerror(_("%s:%s"), old_name,strerror(errno));3534}35353536if(state->check_index && !previous) {3537int pos =cache_name_pos(old_name,strlen(old_name));3538if(pos <0) {3539if(patch->is_new <0)3540goto is_new;3541returnerror(_("%s: does not exist in index"), old_name);3542}3543*ce = active_cache[pos];3544if(stat_ret <0) {3545if(checkout_target(&the_index, *ce, st))3546return-1;3547}3548if(!state->cached &&verify_index_match(*ce, st))3549returnerror(_("%s: does not match index"), old_name);3550if(state->cached)3551 st_mode = (*ce)->ce_mode;3552}else if(stat_ret <0) {3553if(patch->is_new <0)3554goto is_new;3555returnerror(_("%s:%s"), old_name,strerror(errno));3556}35573558if(!state->cached && !previous)3559 st_mode =ce_mode_from_stat(*ce, st->st_mode);35603561if(patch->is_new <0)3562 patch->is_new =0;3563if(!patch->old_mode)3564 patch->old_mode = st_mode;3565if((st_mode ^ patch->old_mode) & S_IFMT)3566returnerror(_("%s: wrong type"), old_name);3567if(st_mode != patch->old_mode)3568warning(_("%shas type%o, expected%o"),3569 old_name, st_mode, patch->old_mode);3570if(!patch->new_mode && !patch->is_delete)3571 patch->new_mode = st_mode;3572return0;35733574 is_new:3575 patch->is_new =1;3576 patch->is_delete =0;3577free(patch->old_name);3578 patch->old_name = NULL;3579return0;3580}358135823583#define EXISTS_IN_INDEX 13584#define EXISTS_IN_WORKTREE 235853586static intcheck_to_create(struct apply_state *state,3587const char*new_name,3588int ok_if_exists)3589{3590struct stat nst;35913592if(state->check_index &&3593cache_name_pos(new_name,strlen(new_name)) >=0&&3594!ok_if_exists)3595return EXISTS_IN_INDEX;3596if(state->cached)3597return0;35983599if(!lstat(new_name, &nst)) {3600if(S_ISDIR(nst.st_mode) || ok_if_exists)3601return0;3602/*3603 * A leading component of new_name might be a symlink3604 * that is going to be removed with this patch, but3605 * still pointing at somewhere that has the path.3606 * In such a case, path "new_name" does not exist as3607 * far as git is concerned.3608 */3609if(has_symlink_leading_path(new_name,strlen(new_name)))3610return0;36113612return EXISTS_IN_WORKTREE;3613}else if((errno != ENOENT) && (errno != ENOTDIR)) {3614returnerror("%s:%s", new_name,strerror(errno));3615}3616return0;3617}36183619static uintptr_tregister_symlink_changes(struct apply_state *state,3620const char*path,3621uintptr_t what)3622{3623struct string_list_item *ent;36243625 ent =string_list_lookup(&state->symlink_changes, path);3626if(!ent) {3627 ent =string_list_insert(&state->symlink_changes, path);3628 ent->util = (void*)0;3629}3630 ent->util = (void*)(what | ((uintptr_t)ent->util));3631return(uintptr_t)ent->util;3632}36333634static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3635{3636struct string_list_item *ent;36373638 ent =string_list_lookup(&state->symlink_changes, path);3639if(!ent)3640return0;3641return(uintptr_t)ent->util;3642}36433644static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3645{3646for( ; patch; patch = patch->next) {3647if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3648(patch->is_rename || patch->is_delete))3649/* the symlink at patch->old_name is removed */3650register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36513652if(patch->new_name &&S_ISLNK(patch->new_mode))3653/* the symlink at patch->new_name is created or remains */3654register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3655}3656}36573658static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3659{3660do{3661unsigned int change;36623663while(--name->len && name->buf[name->len] !='/')3664;/* scan backwards */3665if(!name->len)3666break;3667 name->buf[name->len] ='\0';3668 change =check_symlink_changes(state, name->buf);3669if(change & APPLY_SYMLINK_IN_RESULT)3670return1;3671if(change & APPLY_SYMLINK_GOES_AWAY)3672/*3673 * This cannot be "return 0", because we may3674 * see a new one created at a higher level.3675 */3676continue;36773678/* otherwise, check the preimage */3679if(state->check_index) {3680struct cache_entry *ce;36813682 ce =cache_file_exists(name->buf, name->len, ignore_case);3683if(ce &&S_ISLNK(ce->ce_mode))3684return1;3685}else{3686struct stat st;3687if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3688return1;3689}3690}while(1);3691return0;3692}36933694static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3695{3696int ret;3697struct strbuf name = STRBUF_INIT;36983699assert(*name_ !='\0');3700strbuf_addstr(&name, name_);3701 ret =path_is_beyond_symlink_1(state, &name);3702strbuf_release(&name);37033704return ret;3705}37063707static voiddie_on_unsafe_path(struct patch *patch)3708{3709const char*old_name = NULL;3710const char*new_name = NULL;3711if(patch->is_delete)3712 old_name = patch->old_name;3713else if(!patch->is_new && !patch->is_copy)3714 old_name = patch->old_name;3715if(!patch->is_delete)3716 new_name = patch->new_name;37173718if(old_name && !verify_path(old_name))3719die(_("invalid path '%s'"), old_name);3720if(new_name && !verify_path(new_name))3721die(_("invalid path '%s'"), new_name);3722}37233724/*3725 * Check and apply the patch in-core; leave the result in patch->result3726 * for the caller to write it out to the final destination.3727 */3728static intcheck_patch(struct apply_state *state,struct patch *patch)3729{3730struct stat st;3731const char*old_name = patch->old_name;3732const char*new_name = patch->new_name;3733const char*name = old_name ? old_name : new_name;3734struct cache_entry *ce = NULL;3735struct patch *tpatch;3736int ok_if_exists;3737int status;37383739 patch->rejected =1;/* we will drop this after we succeed */37403741 status =check_preimage(state, patch, &ce, &st);3742if(status)3743return status;3744 old_name = patch->old_name;37453746/*3747 * A type-change diff is always split into a patch to delete3748 * old, immediately followed by a patch to create new (see3749 * diff.c::run_diff()); in such a case it is Ok that the entry3750 * to be deleted by the previous patch is still in the working3751 * tree and in the index.3752 *3753 * A patch to swap-rename between A and B would first rename A3754 * to B and then rename B to A. While applying the first one,3755 * the presence of B should not stop A from getting renamed to3756 * B; ask to_be_deleted() about the later rename. Removal of3757 * B and rename from A to B is handled the same way by asking3758 * was_deleted().3759 */3760if((tpatch =in_fn_table(state, new_name)) &&3761(was_deleted(tpatch) ||to_be_deleted(tpatch)))3762 ok_if_exists =1;3763else3764 ok_if_exists =0;37653766if(new_name &&3767((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3768int err =check_to_create(state, new_name, ok_if_exists);37693770if(err && state->threeway) {3771 patch->direct_to_threeway =1;3772}else switch(err) {3773case0:3774break;/* happy */3775case EXISTS_IN_INDEX:3776returnerror(_("%s: already exists in index"), new_name);3777break;3778case EXISTS_IN_WORKTREE:3779returnerror(_("%s: already exists in working directory"),3780 new_name);3781default:3782return err;3783}37843785if(!patch->new_mode) {3786if(0< patch->is_new)3787 patch->new_mode = S_IFREG |0644;3788else3789 patch->new_mode = patch->old_mode;3790}3791}37923793if(new_name && old_name) {3794int same = !strcmp(old_name, new_name);3795if(!patch->new_mode)3796 patch->new_mode = patch->old_mode;3797if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3798if(same)3799returnerror(_("new mode (%o) of%sdoes not "3800"match old mode (%o)"),3801 patch->new_mode, new_name,3802 patch->old_mode);3803else3804returnerror(_("new mode (%o) of%sdoes not "3805"match old mode (%o) of%s"),3806 patch->new_mode, new_name,3807 patch->old_mode, old_name);3808}3809}38103811if(!state->unsafe_paths)3812die_on_unsafe_path(patch);38133814/*3815 * An attempt to read from or delete a path that is beyond a3816 * symbolic link will be prevented by load_patch_target() that3817 * is called at the beginning of apply_data() so we do not3818 * have to worry about a patch marked with "is_delete" bit3819 * here. We however need to make sure that the patch result3820 * is not deposited to a path that is beyond a symbolic link3821 * here.3822 */3823if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3824returnerror(_("affected file '%s' is beyond a symbolic link"),3825 patch->new_name);38263827if(apply_data(state, patch, &st, ce) <0)3828returnerror(_("%s: patch does not apply"), name);3829 patch->rejected =0;3830return0;3831}38323833static intcheck_patch_list(struct apply_state *state,struct patch *patch)3834{3835int err =0;38363837prepare_symlink_changes(state, patch);3838prepare_fn_table(state, patch);3839while(patch) {3840if(state->apply_verbosely)3841say_patch_name(stderr,3842_("Checking patch%s..."), patch);3843 err |=check_patch(state, patch);3844 patch = patch->next;3845}3846return err;3847}38483849/* This function tries to read the sha1 from the current index */3850static intget_current_sha1(const char*path,unsigned char*sha1)3851{3852int pos;38533854if(read_cache() <0)3855return-1;3856 pos =cache_name_pos(path,strlen(path));3857if(pos <0)3858return-1;3859hashcpy(sha1, active_cache[pos]->sha1);3860return0;3861}38623863static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3864{3865/*3866 * A usable gitlink patch has only one fragment (hunk) that looks like:3867 * @@ -1 +1 @@3868 * -Subproject commit <old sha1>3869 * +Subproject commit <new sha1>3870 * or3871 * @@ -1 +0,0 @@3872 * -Subproject commit <old sha1>3873 * for a removal patch.3874 */3875struct fragment *hunk = p->fragments;3876static const char heading[] ="-Subproject commit ";3877char*preimage;38783879if(/* does the patch have only one hunk? */3880 hunk && !hunk->next &&3881/* is its preimage one line? */3882 hunk->oldpos ==1&& hunk->oldlines ==1&&3883/* does preimage begin with the heading? */3884(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3885starts_with(++preimage, heading) &&3886/* does it record full SHA-1? */3887!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3888 preimage[sizeof(heading) +40-1] =='\n'&&3889/* does the abbreviated name on the index line agree with it? */3890starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3891return0;/* it all looks fine */38923893/* we may have full object name on the index line */3894returnget_sha1_hex(p->old_sha1_prefix, sha1);3895}38963897/* Build an index that contains the just the files needed for a 3way merge */3898static voidbuild_fake_ancestor(struct patch *list,const char*filename)3899{3900struct patch *patch;3901struct index_state result = { NULL };3902static struct lock_file lock;39033904/* Once we start supporting the reverse patch, it may be3905 * worth showing the new sha1 prefix, but until then...3906 */3907for(patch = list; patch; patch = patch->next) {3908unsigned char sha1[20];3909struct cache_entry *ce;3910const char*name;39113912 name = patch->old_name ? patch->old_name : patch->new_name;3913if(0< patch->is_new)3914continue;39153916if(S_ISGITLINK(patch->old_mode)) {3917if(!preimage_sha1_in_gitlink_patch(patch, sha1))3918;/* ok, the textual part looks sane */3919else3920die("sha1 information is lacking or useless for submodule%s",3921 name);3922}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3923;/* ok */3924}else if(!patch->lines_added && !patch->lines_deleted) {3925/* mode-only change: update the current */3926if(get_current_sha1(patch->old_name, sha1))3927die("mode change for%s, which is not "3928"in current HEAD", name);3929}else3930die("sha1 information is lacking or useless "3931"(%s).", name);39323933 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3934if(!ce)3935die(_("make_cache_entry failed for path '%s'"), name);3936if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3937die("Could not add%sto temporary index", name);3938}39393940hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3941if(write_locked_index(&result, &lock, COMMIT_LOCK))3942die("Could not write temporary index to%s", filename);39433944discard_index(&result);3945}39463947static voidstat_patch_list(struct apply_state *state,struct patch *patch)3948{3949int files, adds, dels;39503951for(files = adds = dels =0; patch ; patch = patch->next) {3952 files++;3953 adds += patch->lines_added;3954 dels += patch->lines_deleted;3955show_stats(state, patch);3956}39573958print_stat_summary(stdout, files, adds, dels);3959}39603961static voidnumstat_patch_list(struct apply_state *state,3962struct patch *patch)3963{3964for( ; patch; patch = patch->next) {3965const char*name;3966 name = patch->new_name ? patch->new_name : patch->old_name;3967if(patch->is_binary)3968printf("-\t-\t");3969else3970printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3971write_name_quoted(name, stdout, state->line_termination);3972}3973}39743975static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3976{3977if(mode)3978printf("%smode%06o%s\n", newdelete, mode, name);3979else3980printf("%s %s\n", newdelete, name);3981}39823983static voidshow_mode_change(struct patch *p,int show_name)3984{3985if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3986if(show_name)3987printf(" mode change%06o =>%06o%s\n",3988 p->old_mode, p->new_mode, p->new_name);3989else3990printf(" mode change%06o =>%06o\n",3991 p->old_mode, p->new_mode);3992}3993}39943995static voidshow_rename_copy(struct patch *p)3996{3997const char*renamecopy = p->is_rename ?"rename":"copy";3998const char*old, *new;39994000/* Find common prefix */4001 old = p->old_name;4002new= p->new_name;4003while(1) {4004const char*slash_old, *slash_new;4005 slash_old =strchr(old,'/');4006 slash_new =strchr(new,'/');4007if(!slash_old ||4008!slash_new ||4009 slash_old - old != slash_new -new||4010memcmp(old,new, slash_new -new))4011break;4012 old = slash_old +1;4013new= slash_new +1;4014}4015/* p->old_name thru old is the common prefix, and old and new4016 * through the end of names are renames4017 */4018if(old != p->old_name)4019printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4020(int)(old - p->old_name), p->old_name,4021 old,new, p->score);4022else4023printf("%s %s=>%s(%d%%)\n", renamecopy,4024 p->old_name, p->new_name, p->score);4025show_mode_change(p,0);4026}40274028static voidsummary_patch_list(struct patch *patch)4029{4030struct patch *p;40314032for(p = patch; p; p = p->next) {4033if(p->is_new)4034show_file_mode_name("create", p->new_mode, p->new_name);4035else if(p->is_delete)4036show_file_mode_name("delete", p->old_mode, p->old_name);4037else{4038if(p->is_rename || p->is_copy)4039show_rename_copy(p);4040else{4041if(p->score) {4042printf(" rewrite%s(%d%%)\n",4043 p->new_name, p->score);4044show_mode_change(p,0);4045}4046else4047show_mode_change(p,1);4048}4049}4050}4051}40524053static voidpatch_stats(struct apply_state *state,struct patch *patch)4054{4055int lines = patch->lines_added + patch->lines_deleted;40564057if(lines > state->max_change)4058 state->max_change = lines;4059if(patch->old_name) {4060int len =quote_c_style(patch->old_name, NULL, NULL,0);4061if(!len)4062 len =strlen(patch->old_name);4063if(len > state->max_len)4064 state->max_len = len;4065}4066if(patch->new_name) {4067int len =quote_c_style(patch->new_name, NULL, NULL,0);4068if(!len)4069 len =strlen(patch->new_name);4070if(len > state->max_len)4071 state->max_len = len;4072}4073}40744075static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4076{4077if(state->update_index) {4078if(remove_file_from_cache(patch->old_name) <0)4079die(_("unable to remove%sfrom index"), patch->old_name);4080}4081if(!state->cached) {4082if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4083remove_path(patch->old_name);4084}4085}4086}40874088static voidadd_index_file(struct apply_state *state,4089const char*path,4090unsigned mode,4091void*buf,4092unsigned long size)4093{4094struct stat st;4095struct cache_entry *ce;4096int namelen =strlen(path);4097unsigned ce_size =cache_entry_size(namelen);40984099if(!state->update_index)4100return;41014102 ce =xcalloc(1, ce_size);4103memcpy(ce->name, path, namelen);4104 ce->ce_mode =create_ce_mode(mode);4105 ce->ce_flags =create_ce_flags(0);4106 ce->ce_namelen = namelen;4107if(S_ISGITLINK(mode)) {4108const char*s;41094110if(!skip_prefix(buf,"Subproject commit ", &s) ||4111get_sha1_hex(s, ce->sha1))4112die(_("corrupt patch for submodule%s"), path);4113}else{4114if(!state->cached) {4115if(lstat(path, &st) <0)4116die_errno(_("unable to stat newly created file '%s'"),4117 path);4118fill_stat_cache_info(ce, &st);4119}4120if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4121die(_("unable to create backing store for newly created file%s"), path);4122}4123if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4124die(_("unable to add cache entry for%s"), path);4125}41264127static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4128{4129int fd;4130struct strbuf nbuf = STRBUF_INIT;41314132if(S_ISGITLINK(mode)) {4133struct stat st;4134if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4135return0;4136returnmkdir(path,0777);4137}41384139if(has_symlinks &&S_ISLNK(mode))4140/* Although buf:size is counted string, it also is NUL4141 * terminated.4142 */4143returnsymlink(buf, path);41444145 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4146if(fd <0)4147return-1;41484149if(convert_to_working_tree(path, buf, size, &nbuf)) {4150 size = nbuf.len;4151 buf = nbuf.buf;4152}4153write_or_die(fd, buf, size);4154strbuf_release(&nbuf);41554156if(close(fd) <0)4157die_errno(_("closing file '%s'"), path);4158return0;4159}41604161/*4162 * We optimistically assume that the directories exist,4163 * which is true 99% of the time anyway. If they don't,4164 * we create them and try again.4165 */4166static voidcreate_one_file(struct apply_state *state,4167char*path,4168unsigned mode,4169const char*buf,4170unsigned long size)4171{4172if(state->cached)4173return;4174if(!try_create_file(path, mode, buf, size))4175return;41764177if(errno == ENOENT) {4178if(safe_create_leading_directories(path))4179return;4180if(!try_create_file(path, mode, buf, size))4181return;4182}41834184if(errno == EEXIST || errno == EACCES) {4185/* We may be trying to create a file where a directory4186 * used to be.4187 */4188struct stat st;4189if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4190 errno = EEXIST;4191}41924193if(errno == EEXIST) {4194unsigned int nr =getpid();41954196for(;;) {4197char newpath[PATH_MAX];4198mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4199if(!try_create_file(newpath, mode, buf, size)) {4200if(!rename(newpath, path))4201return;4202unlink_or_warn(newpath);4203break;4204}4205if(errno != EEXIST)4206break;4207++nr;4208}4209}4210die_errno(_("unable to write file '%s' mode%o"), path, mode);4211}42124213static voidadd_conflicted_stages_file(struct apply_state *state,4214struct patch *patch)4215{4216int stage, namelen;4217unsigned ce_size, mode;4218struct cache_entry *ce;42194220if(!state->update_index)4221return;4222 namelen =strlen(patch->new_name);4223 ce_size =cache_entry_size(namelen);4224 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42254226remove_file_from_cache(patch->new_name);4227for(stage =1; stage <4; stage++) {4228if(is_null_oid(&patch->threeway_stage[stage -1]))4229continue;4230 ce =xcalloc(1, ce_size);4231memcpy(ce->name, patch->new_name, namelen);4232 ce->ce_mode =create_ce_mode(mode);4233 ce->ce_flags =create_ce_flags(stage);4234 ce->ce_namelen = namelen;4235hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4236if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4237die(_("unable to add cache entry for%s"), patch->new_name);4238}4239}42404241static voidcreate_file(struct apply_state *state,struct patch *patch)4242{4243char*path = patch->new_name;4244unsigned mode = patch->new_mode;4245unsigned long size = patch->resultsize;4246char*buf = patch->result;42474248if(!mode)4249 mode = S_IFREG |0644;4250create_one_file(state, path, mode, buf, size);42514252if(patch->conflicted_threeway)4253add_conflicted_stages_file(state, patch);4254else4255add_index_file(state, path, mode, buf, size);4256}42574258/* phase zero is to remove, phase one is to create */4259static voidwrite_out_one_result(struct apply_state *state,4260struct patch *patch,4261int phase)4262{4263if(patch->is_delete >0) {4264if(phase ==0)4265remove_file(state, patch,1);4266return;4267}4268if(patch->is_new >0|| patch->is_copy) {4269if(phase ==1)4270create_file(state, patch);4271return;4272}4273/*4274 * Rename or modification boils down to the same4275 * thing: remove the old, write the new4276 */4277if(phase ==0)4278remove_file(state, patch, patch->is_rename);4279if(phase ==1)4280create_file(state, patch);4281}42824283static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4284{4285FILE*rej;4286char namebuf[PATH_MAX];4287struct fragment *frag;4288int cnt =0;4289struct strbuf sb = STRBUF_INIT;42904291for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4292if(!frag->rejected)4293continue;4294 cnt++;4295}42964297if(!cnt) {4298if(state->apply_verbosely)4299say_patch_name(stderr,4300_("Applied patch%scleanly."), patch);4301return0;4302}43034304/* This should not happen, because a removal patch that leaves4305 * contents are marked "rejected" at the patch level.4306 */4307if(!patch->new_name)4308die(_("internal error"));43094310/* Say this even without --verbose */4311strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4312"Applying patch %%swith%drejects...",4313 cnt),4314 cnt);4315say_patch_name(stderr, sb.buf, patch);4316strbuf_release(&sb);43174318 cnt =strlen(patch->new_name);4319if(ARRAY_SIZE(namebuf) <= cnt +5) {4320 cnt =ARRAY_SIZE(namebuf) -5;4321warning(_("truncating .rej filename to %.*s.rej"),4322 cnt -1, patch->new_name);4323}4324memcpy(namebuf, patch->new_name, cnt);4325memcpy(namebuf + cnt,".rej",5);43264327 rej =fopen(namebuf,"w");4328if(!rej)4329returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43304331/* Normal git tools never deal with .rej, so do not pretend4332 * this is a git patch by saying --git or giving extended4333 * headers. While at it, maybe please "kompare" that wants4334 * the trailing TAB and some garbage at the end of line ;-).4335 */4336fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4337 patch->new_name, patch->new_name);4338for(cnt =1, frag = patch->fragments;4339 frag;4340 cnt++, frag = frag->next) {4341if(!frag->rejected) {4342fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4343continue;4344}4345fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4346fprintf(rej,"%.*s", frag->size, frag->patch);4347if(frag->patch[frag->size-1] !='\n')4348fputc('\n', rej);4349}4350fclose(rej);4351return-1;4352}43534354static intwrite_out_results(struct apply_state *state,struct patch *list)4355{4356int phase;4357int errs =0;4358struct patch *l;4359struct string_list cpath = STRING_LIST_INIT_DUP;43604361for(phase =0; phase <2; phase++) {4362 l = list;4363while(l) {4364if(l->rejected)4365 errs =1;4366else{4367write_out_one_result(state, l, phase);4368if(phase ==1) {4369if(write_out_one_reject(state, l))4370 errs =1;4371if(l->conflicted_threeway) {4372string_list_append(&cpath, l->new_name);4373 errs =1;4374}4375}4376}4377 l = l->next;4378}4379}43804381if(cpath.nr) {4382struct string_list_item *item;43834384string_list_sort(&cpath);4385for_each_string_list_item(item, &cpath)4386fprintf(stderr,"U%s\n", item->string);4387string_list_clear(&cpath,0);43884389rerere(0);4390}43914392return errs;4393}43944395static struct lock_file lock_file;43964397#define INACCURATE_EOF (1<<0)4398#define RECOUNT (1<<1)43994400/*4401 * Try to apply a patch.4402 *4403 * Returns:4404 * -128 if a bad error happened (like patch unreadable)4405 * -1 if patch did not apply and user cannot deal with it4406 * 0 if the patch applied4407 * 1 if the patch did not apply but user might fix it4408 */4409static intapply_patch(struct apply_state *state,4410int fd,4411const char*filename,4412int options)4413{4414size_t offset;4415struct strbuf buf = STRBUF_INIT;/* owns the patch text */4416struct patch *list = NULL, **listp = &list;4417int skipped_patch =0;4418int res =0;44194420 state->patch_input_file = filename;4421if(read_patch_file(&buf, fd) <0)4422return-128;4423 offset =0;4424while(offset < buf.len) {4425struct patch *patch;4426int nr;44274428 patch =xcalloc(1,sizeof(*patch));4429 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4430 patch->recount = !!(options & RECOUNT);4431 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4432if(nr <0) {4433free_patch(patch);4434if(nr == -128) {4435 res = -128;4436goto end;4437}4438break;4439}4440if(state->apply_in_reverse)4441reverse_patches(patch);4442if(use_patch(state, patch)) {4443patch_stats(state, patch);4444*listp = patch;4445 listp = &patch->next;4446}4447else{4448if(state->apply_verbosely)4449say_patch_name(stderr,_("Skipped patch '%s'."), patch);4450free_patch(patch);4451 skipped_patch++;4452}4453 offset += nr;4454}44554456if(!list && !skipped_patch) {4457error(_("unrecognized input"));4458 res = -128;4459goto end;4460}44614462if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4463 state->apply =0;44644465 state->update_index = state->check_index && state->apply;4466if(state->update_index && state->newfd <0)4467 state->newfd =hold_locked_index(state->lock_file,1);44684469if(state->check_index &&read_cache() <0) {4470error(_("unable to read index file"));4471 res = -128;4472goto end;4473}44744475if((state->check || state->apply) &&4476check_patch_list(state, list) <0&&4477!state->apply_with_reject) {4478 res = -1;4479goto end;4480}44814482if(state->apply &&write_out_results(state, list)) {4483/* with --3way, we still need to write the index out */4484 res = state->apply_with_reject ? -1:1;4485goto end;4486}44874488if(state->fake_ancestor)4489build_fake_ancestor(list, state->fake_ancestor);44904491if(state->diffstat)4492stat_patch_list(state, list);44934494if(state->numstat)4495numstat_patch_list(state, list);44964497if(state->summary)4498summary_patch_list(list);44994500end:4501free_patch_list(list);4502strbuf_release(&buf);4503string_list_clear(&state->fn_table,0);4504return res;4505}45064507static intoption_parse_exclude(const struct option *opt,4508const char*arg,int unset)4509{4510struct apply_state *state = opt->value;4511add_name_limit(state, arg,1);4512return0;4513}45144515static intoption_parse_include(const struct option *opt,4516const char*arg,int unset)4517{4518struct apply_state *state = opt->value;4519add_name_limit(state, arg,0);4520 state->has_include =1;4521return0;4522}45234524static intoption_parse_p(const struct option *opt,4525const char*arg,4526int unset)4527{4528struct apply_state *state = opt->value;4529 state->p_value =atoi(arg);4530 state->p_value_known =1;4531return0;4532}45334534static intoption_parse_space_change(const struct option *opt,4535const char*arg,int unset)4536{4537struct apply_state *state = opt->value;4538if(unset)4539 state->ws_ignore_action = ignore_ws_none;4540else4541 state->ws_ignore_action = ignore_ws_change;4542return0;4543}45444545static intoption_parse_whitespace(const struct option *opt,4546const char*arg,int unset)4547{4548struct apply_state *state = opt->value;4549 state->whitespace_option = arg;4550if(parse_whitespace_option(state, arg))4551exit(1);4552return0;4553}45544555static intoption_parse_directory(const struct option *opt,4556const char*arg,int unset)4557{4558struct apply_state *state = opt->value;4559strbuf_reset(&state->root);4560strbuf_addstr(&state->root, arg);4561strbuf_complete(&state->root,'/');4562return0;4563}45644565static intapply_all_patches(struct apply_state *state,4566int argc,4567const char**argv,4568int options)4569{4570int i;4571int res;4572int errs =0;4573int read_stdin =1;45744575for(i =0; i < argc; i++) {4576const char*arg = argv[i];4577int fd;45784579if(!strcmp(arg,"-")) {4580 res =apply_patch(state,0,"<stdin>", options);4581if(res <0)4582goto end;4583 errs |= res;4584 read_stdin =0;4585continue;4586}else if(0< state->prefix_length)4587 arg =prefix_filename(state->prefix,4588 state->prefix_length,4589 arg);45904591 fd =open(arg, O_RDONLY);4592if(fd <0) {4593error(_("can't open patch '%s':%s"), arg,strerror(errno));4594 res = -128;4595goto end;4596}4597 read_stdin =0;4598set_default_whitespace_mode(state);4599 res =apply_patch(state, fd, arg, options);4600close(fd);4601if(res <0)4602goto end;4603 errs |= res;4604}4605set_default_whitespace_mode(state);4606if(read_stdin) {4607 res =apply_patch(state,0,"<stdin>", options);4608if(res <0)4609goto end;4610 errs |= res;4611}46124613if(state->whitespace_error) {4614if(state->squelch_whitespace_errors &&4615 state->squelch_whitespace_errors < state->whitespace_error) {4616int squelched =4617 state->whitespace_error - state->squelch_whitespace_errors;4618warning(Q_("squelched%dwhitespace error",4619"squelched%dwhitespace errors",4620 squelched),4621 squelched);4622}4623if(state->ws_error_action == die_on_ws_error) {4624error(Q_("%dline adds whitespace errors.",4625"%dlines add whitespace errors.",4626 state->whitespace_error),4627 state->whitespace_error);4628 res = -128;4629goto end;4630}4631if(state->applied_after_fixing_ws && state->apply)4632warning("%dline%sapplied after"4633" fixing whitespace errors.",4634 state->applied_after_fixing_ws,4635 state->applied_after_fixing_ws ==1?"":"s");4636else if(state->whitespace_error)4637warning(Q_("%dline adds whitespace errors.",4638"%dlines add whitespace errors.",4639 state->whitespace_error),4640 state->whitespace_error);4641}46424643if(state->update_index) {4644 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4645if(res) {4646error(_("Unable to write new index file"));4647 res = -128;4648goto end;4649}4650 state->newfd = -1;4651}46524653return!!errs;46544655end:4656if(state->newfd >=0) {4657rollback_lock_file(state->lock_file);4658 state->newfd = -1;4659}46604661return(res == -1?1:128);4662}46634664intcmd_apply(int argc,const char**argv,const char*prefix)4665{4666int force_apply =0;4667int options =0;4668int ret;4669struct apply_state state;46704671struct option builtin_apply_options[] = {4672{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4673N_("don't apply changes matching the given path"),46740, option_parse_exclude },4675{ OPTION_CALLBACK,0,"include", &state,N_("path"),4676N_("apply changes matching the given path"),46770, option_parse_include },4678{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4679N_("remove <num> leading slashes from traditional diff paths"),46800, option_parse_p },4681OPT_BOOL(0,"no-add", &state.no_add,4682N_("ignore additions made by the patch")),4683OPT_BOOL(0,"stat", &state.diffstat,4684N_("instead of applying the patch, output diffstat for the input")),4685OPT_NOOP_NOARG(0,"allow-binary-replacement"),4686OPT_NOOP_NOARG(0,"binary"),4687OPT_BOOL(0,"numstat", &state.numstat,4688N_("show number of added and deleted lines in decimal notation")),4689OPT_BOOL(0,"summary", &state.summary,4690N_("instead of applying the patch, output a summary for the input")),4691OPT_BOOL(0,"check", &state.check,4692N_("instead of applying the patch, see if the patch is applicable")),4693OPT_BOOL(0,"index", &state.check_index,4694N_("make sure the patch is applicable to the current index")),4695OPT_BOOL(0,"cached", &state.cached,4696N_("apply a patch without touching the working tree")),4697OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4698N_("accept a patch that touches outside the working area")),4699OPT_BOOL(0,"apply", &force_apply,4700N_("also apply the patch (use with --stat/--summary/--check)")),4701OPT_BOOL('3',"3way", &state.threeway,4702N_("attempt three-way merge if a patch does not apply")),4703OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4704N_("build a temporary index based on embedded index information")),4705/* Think twice before adding "--nul" synonym to this */4706OPT_SET_INT('z', NULL, &state.line_termination,4707N_("paths are separated with NUL character"),'\0'),4708OPT_INTEGER('C', NULL, &state.p_context,4709N_("ensure at least <n> lines of context match")),4710{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4711N_("detect new or modified lines that have whitespace errors"),47120, option_parse_whitespace },4713{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4714N_("ignore changes in whitespace when finding context"),4715 PARSE_OPT_NOARG, option_parse_space_change },4716{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4717N_("ignore changes in whitespace when finding context"),4718 PARSE_OPT_NOARG, option_parse_space_change },4719OPT_BOOL('R',"reverse", &state.apply_in_reverse,4720N_("apply the patch in reverse")),4721OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4722N_("don't expect at least one line of context")),4723OPT_BOOL(0,"reject", &state.apply_with_reject,4724N_("leave the rejected hunks in corresponding *.rej files")),4725OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4726N_("allow overlapping hunks")),4727OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4728OPT_BIT(0,"inaccurate-eof", &options,4729N_("tolerate incorrectly detected missing new-line at the end of file"),4730 INACCURATE_EOF),4731OPT_BIT(0,"recount", &options,4732N_("do not trust the line counts in the hunk headers"),4733 RECOUNT),4734{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4735N_("prepend <root> to all filenames"),47360, option_parse_directory },4737OPT_END()4738};47394740if(init_apply_state(&state, prefix, &lock_file))4741exit(128);47424743 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4744 apply_usage,0);47454746if(check_apply_state(&state, force_apply))4747exit(128);47484749 ret =apply_all_patches(&state, argc, argv, options);47504751clear_apply_state(&state);47524753return ret;4754}