1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"lockfile.h" 11#include"cache-tree.h" 12#include"quote.h" 13#include"blob.h" 14#include"delta.h" 15#include"builtin.h" 16#include"string-list.h" 17#include"dir.h" 18#include"diff.h" 19#include"parse-options.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"rerere.h" 23#include"apply.h" 24 25static const char*const apply_usage[] = { 26N_("git apply [<options>] [<patch>...]"), 27 NULL 28}; 29 30static voidparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return; 56} 57die(_("unrecognized whitespace option '%s'"), option); 58} 59 60static voidparse_ignorewhitespace_option(struct apply_state *state, 61const char*option) 62{ 63if(!option || !strcmp(option,"no") || 64!strcmp(option,"false") || !strcmp(option,"never") || 65!strcmp(option,"none")) { 66 state->ws_ignore_action = ignore_ws_none; 67return; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return; 72} 73die(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76static voidset_default_whitespace_mode(struct apply_state *state) 77{ 78if(!state->whitespace_option && !apply_default_whitespace) 79 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 80} 81 82/* 83 * This represents one "hunk" from a patch, starting with 84 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 85 * patch text is pointed at by patch, and its byte length 86 * is stored in size. leading and trailing are the number 87 * of context lines. 88 */ 89struct fragment { 90unsigned long leading, trailing; 91unsigned long oldpos, oldlines; 92unsigned long newpos, newlines; 93/* 94 * 'patch' is usually borrowed from buf in apply_patch(), 95 * but some codepaths store an allocated buffer. 96 */ 97const char*patch; 98unsigned free_patch:1, 99 rejected:1; 100int size; 101int linenr; 102struct fragment *next; 103}; 104 105/* 106 * When dealing with a binary patch, we reuse "leading" field 107 * to store the type of the binary hunk, either deflated "delta" 108 * or deflated "literal". 109 */ 110#define binary_patch_method leading 111#define BINARY_DELTA_DEFLATED 1 112#define BINARY_LITERAL_DEFLATED 2 113 114/* 115 * This represents a "patch" to a file, both metainfo changes 116 * such as creation/deletion, filemode and content changes represented 117 * as a series of fragments. 118 */ 119struct patch { 120char*new_name, *old_name, *def_name; 121unsigned int old_mode, new_mode; 122int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 123int rejected; 124unsigned ws_rule; 125int lines_added, lines_deleted; 126int score; 127unsigned int is_toplevel_relative:1; 128unsigned int inaccurate_eof:1; 129unsigned int is_binary:1; 130unsigned int is_copy:1; 131unsigned int is_rename:1; 132unsigned int recount:1; 133unsigned int conflicted_threeway:1; 134unsigned int direct_to_threeway:1; 135struct fragment *fragments; 136char*result; 137size_t resultsize; 138char old_sha1_prefix[41]; 139char new_sha1_prefix[41]; 140struct patch *next; 141 142/* three-way fallback result */ 143struct object_id threeway_stage[3]; 144}; 145 146static voidfree_fragment_list(struct fragment *list) 147{ 148while(list) { 149struct fragment *next = list->next; 150if(list->free_patch) 151free((char*)list->patch); 152free(list); 153 list = next; 154} 155} 156 157static voidfree_patch(struct patch *patch) 158{ 159free_fragment_list(patch->fragments); 160free(patch->def_name); 161free(patch->old_name); 162free(patch->new_name); 163free(patch->result); 164free(patch); 165} 166 167static voidfree_patch_list(struct patch *list) 168{ 169while(list) { 170struct patch *next = list->next; 171free_patch(list); 172 list = next; 173} 174} 175 176/* 177 * A line in a file, len-bytes long (includes the terminating LF, 178 * except for an incomplete line at the end if the file ends with 179 * one), and its contents hashes to 'hash'. 180 */ 181struct line { 182size_t len; 183unsigned hash :24; 184unsigned flag :8; 185#define LINE_COMMON 1 186#define LINE_PATCHED 2 187}; 188 189/* 190 * This represents a "file", which is an array of "lines". 191 */ 192struct image { 193char*buf; 194size_t len; 195size_t nr; 196size_t alloc; 197struct line *line_allocated; 198struct line *line; 199}; 200 201static uint32_thash_line(const char*cp,size_t len) 202{ 203size_t i; 204uint32_t h; 205for(i =0, h =0; i < len; i++) { 206if(!isspace(cp[i])) { 207 h = h *3+ (cp[i] &0xff); 208} 209} 210return h; 211} 212 213/* 214 * Compare lines s1 of length n1 and s2 of length n2, ignoring 215 * whitespace difference. Returns 1 if they match, 0 otherwise 216 */ 217static intfuzzy_matchlines(const char*s1,size_t n1, 218const char*s2,size_t n2) 219{ 220const char*last1 = s1 + n1 -1; 221const char*last2 = s2 + n2 -1; 222int result =0; 223 224/* ignore line endings */ 225while((*last1 =='\r') || (*last1 =='\n')) 226 last1--; 227while((*last2 =='\r') || (*last2 =='\n')) 228 last2--; 229 230/* skip leading whitespaces, if both begin with whitespace */ 231if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 232while(isspace(*s1) && (s1 <= last1)) 233 s1++; 234while(isspace(*s2) && (s2 <= last2)) 235 s2++; 236} 237/* early return if both lines are empty */ 238if((s1 > last1) && (s2 > last2)) 239return1; 240while(!result) { 241 result = *s1++ - *s2++; 242/* 243 * Skip whitespace inside. We check for whitespace on 244 * both buffers because we don't want "a b" to match 245 * "ab" 246 */ 247if(isspace(*s1) &&isspace(*s2)) { 248while(isspace(*s1) && s1 <= last1) 249 s1++; 250while(isspace(*s2) && s2 <= last2) 251 s2++; 252} 253/* 254 * If we reached the end on one side only, 255 * lines don't match 256 */ 257if( 258((s2 > last2) && (s1 <= last1)) || 259((s1 > last1) && (s2 <= last2))) 260return0; 261if((s1 > last1) && (s2 > last2)) 262break; 263} 264 265return!result; 266} 267 268static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 269{ 270ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 271 img->line_allocated[img->nr].len = len; 272 img->line_allocated[img->nr].hash =hash_line(bol, len); 273 img->line_allocated[img->nr].flag = flag; 274 img->nr++; 275} 276 277/* 278 * "buf" has the file contents to be patched (read from various sources). 279 * attach it to "image" and add line-based index to it. 280 * "image" now owns the "buf". 281 */ 282static voidprepare_image(struct image *image,char*buf,size_t len, 283int prepare_linetable) 284{ 285const char*cp, *ep; 286 287memset(image,0,sizeof(*image)); 288 image->buf = buf; 289 image->len = len; 290 291if(!prepare_linetable) 292return; 293 294 ep = image->buf + image->len; 295 cp = image->buf; 296while(cp < ep) { 297const char*next; 298for(next = cp; next < ep && *next !='\n'; next++) 299; 300if(next < ep) 301 next++; 302add_line_info(image, cp, next - cp,0); 303 cp = next; 304} 305 image->line = image->line_allocated; 306} 307 308static voidclear_image(struct image *image) 309{ 310free(image->buf); 311free(image->line_allocated); 312memset(image,0,sizeof(*image)); 313} 314 315/* fmt must contain _one_ %s and no other substitution */ 316static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 317{ 318struct strbuf sb = STRBUF_INIT; 319 320if(patch->old_name && patch->new_name && 321strcmp(patch->old_name, patch->new_name)) { 322quote_c_style(patch->old_name, &sb, NULL,0); 323strbuf_addstr(&sb," => "); 324quote_c_style(patch->new_name, &sb, NULL,0); 325}else{ 326const char*n = patch->new_name; 327if(!n) 328 n = patch->old_name; 329quote_c_style(n, &sb, NULL,0); 330} 331fprintf(output, fmt, sb.buf); 332fputc('\n', output); 333strbuf_release(&sb); 334} 335 336#define SLOP (16) 337 338static intread_patch_file(struct strbuf *sb,int fd) 339{ 340if(strbuf_read(sb, fd,0) <0) 341returnerror_errno("git apply: failed to read"); 342 343/* 344 * Make sure that we have some slop in the buffer 345 * so that we can do speculative "memcmp" etc, and 346 * see to it that it is NUL-filled. 347 */ 348strbuf_grow(sb, SLOP); 349memset(sb->buf + sb->len,0, SLOP); 350return0; 351} 352 353static unsigned longlinelen(const char*buffer,unsigned long size) 354{ 355unsigned long len =0; 356while(size--) { 357 len++; 358if(*buffer++ =='\n') 359break; 360} 361return len; 362} 363 364static intis_dev_null(const char*str) 365{ 366returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 367} 368 369#define TERM_SPACE 1 370#define TERM_TAB 2 371 372static intname_terminate(int c,int terminate) 373{ 374if(c ==' '&& !(terminate & TERM_SPACE)) 375return0; 376if(c =='\t'&& !(terminate & TERM_TAB)) 377return0; 378 379return1; 380} 381 382/* remove double slashes to make --index work with such filenames */ 383static char*squash_slash(char*name) 384{ 385int i =0, j =0; 386 387if(!name) 388return NULL; 389 390while(name[i]) { 391if((name[j++] = name[i++]) =='/') 392while(name[i] =='/') 393 i++; 394} 395 name[j] ='\0'; 396return name; 397} 398 399static char*find_name_gnu(struct apply_state *state, 400const char*line, 401const char*def, 402int p_value) 403{ 404struct strbuf name = STRBUF_INIT; 405char*cp; 406 407/* 408 * Proposed "new-style" GNU patch/diff format; see 409 * http://marc.info/?l=git&m=112927316408690&w=2 410 */ 411if(unquote_c_style(&name, line, NULL)) { 412strbuf_release(&name); 413return NULL; 414} 415 416for(cp = name.buf; p_value; p_value--) { 417 cp =strchr(cp,'/'); 418if(!cp) { 419strbuf_release(&name); 420return NULL; 421} 422 cp++; 423} 424 425strbuf_remove(&name,0, cp - name.buf); 426if(state->root.len) 427strbuf_insert(&name,0, state->root.buf, state->root.len); 428returnsquash_slash(strbuf_detach(&name, NULL)); 429} 430 431static size_tsane_tz_len(const char*line,size_t len) 432{ 433const char*tz, *p; 434 435if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 436return0; 437 tz = line + len -strlen(" +0500"); 438 439if(tz[1] !='+'&& tz[1] !='-') 440return0; 441 442for(p = tz +2; p != line + len; p++) 443if(!isdigit(*p)) 444return0; 445 446return line + len - tz; 447} 448 449static size_ttz_with_colon_len(const char*line,size_t len) 450{ 451const char*tz, *p; 452 453if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 454return0; 455 tz = line + len -strlen(" +08:00"); 456 457if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 458return0; 459 p = tz +2; 460if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 461!isdigit(*p++) || !isdigit(*p++)) 462return0; 463 464return line + len - tz; 465} 466 467static size_tdate_len(const char*line,size_t len) 468{ 469const char*date, *p; 470 471if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 472return0; 473 p = date = line + len -strlen("72-02-05"); 474 475if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 476!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 477!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 478return0; 479 480if(date - line >=strlen("19") && 481isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 482 date -=strlen("19"); 483 484return line + len - date; 485} 486 487static size_tshort_time_len(const char*line,size_t len) 488{ 489const char*time, *p; 490 491if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 492return0; 493 p = time = line + len -strlen(" 07:01:32"); 494 495/* Permit 1-digit hours? */ 496if(*p++ !=' '|| 497!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 498!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 499!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 500return0; 501 502return line + len - time; 503} 504 505static size_tfractional_time_len(const char*line,size_t len) 506{ 507const char*p; 508size_t n; 509 510/* Expected format: 19:41:17.620000023 */ 511if(!len || !isdigit(line[len -1])) 512return0; 513 p = line + len -1; 514 515/* Fractional seconds. */ 516while(p > line &&isdigit(*p)) 517 p--; 518if(*p !='.') 519return0; 520 521/* Hours, minutes, and whole seconds. */ 522 n =short_time_len(line, p - line); 523if(!n) 524return0; 525 526return line + len - p + n; 527} 528 529static size_ttrailing_spaces_len(const char*line,size_t len) 530{ 531const char*p; 532 533/* Expected format: ' ' x (1 or more) */ 534if(!len || line[len -1] !=' ') 535return0; 536 537 p = line + len; 538while(p != line) { 539 p--; 540if(*p !=' ') 541return line + len - (p +1); 542} 543 544/* All spaces! */ 545return len; 546} 547 548static size_tdiff_timestamp_len(const char*line,size_t len) 549{ 550const char*end = line + len; 551size_t n; 552 553/* 554 * Posix: 2010-07-05 19:41:17 555 * GNU: 2010-07-05 19:41:17.620000023 -0500 556 */ 557 558if(!isdigit(end[-1])) 559return0; 560 561 n =sane_tz_len(line, end - line); 562if(!n) 563 n =tz_with_colon_len(line, end - line); 564 end -= n; 565 566 n =short_time_len(line, end - line); 567if(!n) 568 n =fractional_time_len(line, end - line); 569 end -= n; 570 571 n =date_len(line, end - line); 572if(!n)/* No date. Too bad. */ 573return0; 574 end -= n; 575 576if(end == line)/* No space before date. */ 577return0; 578if(end[-1] =='\t') {/* Success! */ 579 end--; 580return line + len - end; 581} 582if(end[-1] !=' ')/* No space before date. */ 583return0; 584 585/* Whitespace damage. */ 586 end -=trailing_spaces_len(line, end - line); 587return line + len - end; 588} 589 590static char*find_name_common(struct apply_state *state, 591const char*line, 592const char*def, 593int p_value, 594const char*end, 595int terminate) 596{ 597int len; 598const char*start = NULL; 599 600if(p_value ==0) 601 start = line; 602while(line != end) { 603char c = *line; 604 605if(!end &&isspace(c)) { 606if(c =='\n') 607break; 608if(name_terminate(c, terminate)) 609break; 610} 611 line++; 612if(c =='/'&& !--p_value) 613 start = line; 614} 615if(!start) 616returnsquash_slash(xstrdup_or_null(def)); 617 len = line - start; 618if(!len) 619returnsquash_slash(xstrdup_or_null(def)); 620 621/* 622 * Generally we prefer the shorter name, especially 623 * if the other one is just a variation of that with 624 * something else tacked on to the end (ie "file.orig" 625 * or "file~"). 626 */ 627if(def) { 628int deflen =strlen(def); 629if(deflen < len && !strncmp(start, def, deflen)) 630returnsquash_slash(xstrdup(def)); 631} 632 633if(state->root.len) { 634char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 635returnsquash_slash(ret); 636} 637 638returnsquash_slash(xmemdupz(start, len)); 639} 640 641static char*find_name(struct apply_state *state, 642const char*line, 643char*def, 644int p_value, 645int terminate) 646{ 647if(*line =='"') { 648char*name =find_name_gnu(state, line, def, p_value); 649if(name) 650return name; 651} 652 653returnfind_name_common(state, line, def, p_value, NULL, terminate); 654} 655 656static char*find_name_traditional(struct apply_state *state, 657const char*line, 658char*def, 659int p_value) 660{ 661size_t len; 662size_t date_len; 663 664if(*line =='"') { 665char*name =find_name_gnu(state, line, def, p_value); 666if(name) 667return name; 668} 669 670 len =strchrnul(line,'\n') - line; 671 date_len =diff_timestamp_len(line, len); 672if(!date_len) 673returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 674 len -= date_len; 675 676returnfind_name_common(state, line, def, p_value, line + len,0); 677} 678 679static intcount_slashes(const char*cp) 680{ 681int cnt =0; 682char ch; 683 684while((ch = *cp++)) 685if(ch =='/') 686 cnt++; 687return cnt; 688} 689 690/* 691 * Given the string after "--- " or "+++ ", guess the appropriate 692 * p_value for the given patch. 693 */ 694static intguess_p_value(struct apply_state *state,const char*nameline) 695{ 696char*name, *cp; 697int val = -1; 698 699if(is_dev_null(nameline)) 700return-1; 701 name =find_name_traditional(state, nameline, NULL,0); 702if(!name) 703return-1; 704 cp =strchr(name,'/'); 705if(!cp) 706 val =0; 707else if(state->prefix) { 708/* 709 * Does it begin with "a/$our-prefix" and such? Then this is 710 * very likely to apply to our directory. 711 */ 712if(!strncmp(name, state->prefix, state->prefix_length)) 713 val =count_slashes(state->prefix); 714else{ 715 cp++; 716if(!strncmp(cp, state->prefix, state->prefix_length)) 717 val =count_slashes(state->prefix) +1; 718} 719} 720free(name); 721return val; 722} 723 724/* 725 * Does the ---/+++ line have the POSIX timestamp after the last HT? 726 * GNU diff puts epoch there to signal a creation/deletion event. Is 727 * this such a timestamp? 728 */ 729static inthas_epoch_timestamp(const char*nameline) 730{ 731/* 732 * We are only interested in epoch timestamp; any non-zero 733 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 734 * For the same reason, the date must be either 1969-12-31 or 735 * 1970-01-01, and the seconds part must be "00". 736 */ 737const char stamp_regexp[] = 738"^(1969-12-31|1970-01-01)" 739" " 740"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 741" " 742"([-+][0-2][0-9]:?[0-5][0-9])\n"; 743const char*timestamp = NULL, *cp, *colon; 744static regex_t *stamp; 745 regmatch_t m[10]; 746int zoneoffset; 747int hourminute; 748int status; 749 750for(cp = nameline; *cp !='\n'; cp++) { 751if(*cp =='\t') 752 timestamp = cp +1; 753} 754if(!timestamp) 755return0; 756if(!stamp) { 757 stamp =xmalloc(sizeof(*stamp)); 758if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 759warning(_("Cannot prepare timestamp regexp%s"), 760 stamp_regexp); 761return0; 762} 763} 764 765 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 766if(status) { 767if(status != REG_NOMATCH) 768warning(_("regexec returned%dfor input:%s"), 769 status, timestamp); 770return0; 771} 772 773 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 774if(*colon ==':') 775 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 776else 777 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 778if(timestamp[m[3].rm_so] =='-') 779 zoneoffset = -zoneoffset; 780 781/* 782 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 783 * (west of GMT) or 1970-01-01 (east of GMT) 784 */ 785if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 786(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 787return0; 788 789 hourminute = (strtol(timestamp +11, NULL,10) *60+ 790strtol(timestamp +14, NULL,10) - 791 zoneoffset); 792 793return((zoneoffset <0&& hourminute ==1440) || 794(0<= zoneoffset && !hourminute)); 795} 796 797/* 798 * Get the name etc info from the ---/+++ lines of a traditional patch header 799 * 800 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 801 * files, we can happily check the index for a match, but for creating a 802 * new file we should try to match whatever "patch" does. I have no idea. 803 */ 804static voidparse_traditional_patch(struct apply_state *state, 805const char*first, 806const char*second, 807struct patch *patch) 808{ 809char*name; 810 811 first +=4;/* skip "--- " */ 812 second +=4;/* skip "+++ " */ 813if(!state->p_value_known) { 814int p, q; 815 p =guess_p_value(state, first); 816 q =guess_p_value(state, second); 817if(p <0) p = q; 818if(0<= p && p == q) { 819 state->p_value = p; 820 state->p_value_known =1; 821} 822} 823if(is_dev_null(first)) { 824 patch->is_new =1; 825 patch->is_delete =0; 826 name =find_name_traditional(state, second, NULL, state->p_value); 827 patch->new_name = name; 828}else if(is_dev_null(second)) { 829 patch->is_new =0; 830 patch->is_delete =1; 831 name =find_name_traditional(state, first, NULL, state->p_value); 832 patch->old_name = name; 833}else{ 834char*first_name; 835 first_name =find_name_traditional(state, first, NULL, state->p_value); 836 name =find_name_traditional(state, second, first_name, state->p_value); 837free(first_name); 838if(has_epoch_timestamp(first)) { 839 patch->is_new =1; 840 patch->is_delete =0; 841 patch->new_name = name; 842}else if(has_epoch_timestamp(second)) { 843 patch->is_new =0; 844 patch->is_delete =1; 845 patch->old_name = name; 846}else{ 847 patch->old_name = name; 848 patch->new_name =xstrdup_or_null(name); 849} 850} 851if(!name) 852die(_("unable to find filename in patch at line%d"), state->linenr); 853} 854 855static intgitdiff_hdrend(struct apply_state *state, 856const char*line, 857struct patch *patch) 858{ 859return-1; 860} 861 862/* 863 * We're anal about diff header consistency, to make 864 * sure that we don't end up having strange ambiguous 865 * patches floating around. 866 * 867 * As a result, gitdiff_{old|new}name() will check 868 * their names against any previous information, just 869 * to make sure.. 870 */ 871#define DIFF_OLD_NAME 0 872#define DIFF_NEW_NAME 1 873 874static voidgitdiff_verify_name(struct apply_state *state, 875const char*line, 876int isnull, 877char**name, 878int side) 879{ 880if(!*name && !isnull) { 881*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 882return; 883} 884 885if(*name) { 886int len =strlen(*name); 887char*another; 888if(isnull) 889die(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 890*name, state->linenr); 891 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 892if(!another ||memcmp(another, *name, len +1)) 893die((side == DIFF_NEW_NAME) ? 894_("git apply: bad git-diff - inconsistent new filename on line%d") : 895_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 896free(another); 897}else{ 898/* expect "/dev/null" */ 899if(memcmp("/dev/null", line,9) || line[9] !='\n') 900die(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 901} 902} 903 904static intgitdiff_oldname(struct apply_state *state, 905const char*line, 906struct patch *patch) 907{ 908gitdiff_verify_name(state, line, 909 patch->is_new, &patch->old_name, 910 DIFF_OLD_NAME); 911return0; 912} 913 914static intgitdiff_newname(struct apply_state *state, 915const char*line, 916struct patch *patch) 917{ 918gitdiff_verify_name(state, line, 919 patch->is_delete, &patch->new_name, 920 DIFF_NEW_NAME); 921return0; 922} 923 924static intgitdiff_oldmode(struct apply_state *state, 925const char*line, 926struct patch *patch) 927{ 928 patch->old_mode =strtoul(line, NULL,8); 929return0; 930} 931 932static intgitdiff_newmode(struct apply_state *state, 933const char*line, 934struct patch *patch) 935{ 936 patch->new_mode =strtoul(line, NULL,8); 937return0; 938} 939 940static intgitdiff_delete(struct apply_state *state, 941const char*line, 942struct patch *patch) 943{ 944 patch->is_delete =1; 945free(patch->old_name); 946 patch->old_name =xstrdup_or_null(patch->def_name); 947returngitdiff_oldmode(state, line, patch); 948} 949 950static intgitdiff_newfile(struct apply_state *state, 951const char*line, 952struct patch *patch) 953{ 954 patch->is_new =1; 955free(patch->new_name); 956 patch->new_name =xstrdup_or_null(patch->def_name); 957returngitdiff_newmode(state, line, patch); 958} 959 960static intgitdiff_copysrc(struct apply_state *state, 961const char*line, 962struct patch *patch) 963{ 964 patch->is_copy =1; 965free(patch->old_name); 966 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 967return0; 968} 969 970static intgitdiff_copydst(struct apply_state *state, 971const char*line, 972struct patch *patch) 973{ 974 patch->is_copy =1; 975free(patch->new_name); 976 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 977return0; 978} 979 980static intgitdiff_renamesrc(struct apply_state *state, 981const char*line, 982struct patch *patch) 983{ 984 patch->is_rename =1; 985free(patch->old_name); 986 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 987return0; 988} 989 990static intgitdiff_renamedst(struct apply_state *state, 991const char*line, 992struct patch *patch) 993{ 994 patch->is_rename =1; 995free(patch->new_name); 996 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0); 997return0; 998} 9991000static intgitdiff_similarity(struct apply_state *state,1001const char*line,1002struct patch *patch)1003{1004unsigned long val =strtoul(line, NULL,10);1005if(val <=100)1006 patch->score = val;1007return0;1008}10091010static intgitdiff_dissimilarity(struct apply_state *state,1011const char*line,1012struct patch *patch)1013{1014unsigned long val =strtoul(line, NULL,10);1015if(val <=100)1016 patch->score = val;1017return0;1018}10191020static intgitdiff_index(struct apply_state *state,1021const char*line,1022struct patch *patch)1023{1024/*1025 * index line is N hexadecimal, "..", N hexadecimal,1026 * and optional space with octal mode.1027 */1028const char*ptr, *eol;1029int len;10301031 ptr =strchr(line,'.');1032if(!ptr || ptr[1] !='.'||40< ptr - line)1033return0;1034 len = ptr - line;1035memcpy(patch->old_sha1_prefix, line, len);1036 patch->old_sha1_prefix[len] =0;10371038 line = ptr +2;1039 ptr =strchr(line,' ');1040 eol =strchrnul(line,'\n');10411042if(!ptr || eol < ptr)1043 ptr = eol;1044 len = ptr - line;10451046if(40< len)1047return0;1048memcpy(patch->new_sha1_prefix, line, len);1049 patch->new_sha1_prefix[len] =0;1050if(*ptr ==' ')1051 patch->old_mode =strtoul(ptr+1, NULL,8);1052return0;1053}10541055/*1056 * This is normal for a diff that doesn't change anything: we'll fall through1057 * into the next diff. Tell the parser to break out.1058 */1059static intgitdiff_unrecognized(struct apply_state *state,1060const char*line,1061struct patch *patch)1062{1063return-1;1064}10651066/*1067 * Skip p_value leading components from "line"; as we do not accept1068 * absolute paths, return NULL in that case.1069 */1070static const char*skip_tree_prefix(struct apply_state *state,1071const char*line,1072int llen)1073{1074int nslash;1075int i;10761077if(!state->p_value)1078return(llen && line[0] =='/') ? NULL : line;10791080 nslash = state->p_value;1081for(i =0; i < llen; i++) {1082int ch = line[i];1083if(ch =='/'&& --nslash <=0)1084return(i ==0) ? NULL : &line[i +1];1085}1086return NULL;1087}10881089/*1090 * This is to extract the same name that appears on "diff --git"1091 * line. We do not find and return anything if it is a rename1092 * patch, and it is OK because we will find the name elsewhere.1093 * We need to reliably find name only when it is mode-change only,1094 * creation or deletion of an empty file. In any of these cases,1095 * both sides are the same name under a/ and b/ respectively.1096 */1097static char*git_header_name(struct apply_state *state,1098const char*line,1099int llen)1100{1101const char*name;1102const char*second = NULL;1103size_t len, line_len;11041105 line +=strlen("diff --git ");1106 llen -=strlen("diff --git ");11071108if(*line =='"') {1109const char*cp;1110struct strbuf first = STRBUF_INIT;1111struct strbuf sp = STRBUF_INIT;11121113if(unquote_c_style(&first, line, &second))1114goto free_and_fail1;11151116/* strip the a/b prefix including trailing slash */1117 cp =skip_tree_prefix(state, first.buf, first.len);1118if(!cp)1119goto free_and_fail1;1120strbuf_remove(&first,0, cp - first.buf);11211122/*1123 * second points at one past closing dq of name.1124 * find the second name.1125 */1126while((second < line + llen) &&isspace(*second))1127 second++;11281129if(line + llen <= second)1130goto free_and_fail1;1131if(*second =='"') {1132if(unquote_c_style(&sp, second, NULL))1133goto free_and_fail1;1134 cp =skip_tree_prefix(state, sp.buf, sp.len);1135if(!cp)1136goto free_and_fail1;1137/* They must match, otherwise ignore */1138if(strcmp(cp, first.buf))1139goto free_and_fail1;1140strbuf_release(&sp);1141returnstrbuf_detach(&first, NULL);1142}11431144/* unquoted second */1145 cp =skip_tree_prefix(state, second, line + llen - second);1146if(!cp)1147goto free_and_fail1;1148if(line + llen - cp != first.len ||1149memcmp(first.buf, cp, first.len))1150goto free_and_fail1;1151returnstrbuf_detach(&first, NULL);11521153 free_and_fail1:1154strbuf_release(&first);1155strbuf_release(&sp);1156return NULL;1157}11581159/* unquoted first name */1160 name =skip_tree_prefix(state, line, llen);1161if(!name)1162return NULL;11631164/*1165 * since the first name is unquoted, a dq if exists must be1166 * the beginning of the second name.1167 */1168for(second = name; second < line + llen; second++) {1169if(*second =='"') {1170struct strbuf sp = STRBUF_INIT;1171const char*np;11721173if(unquote_c_style(&sp, second, NULL))1174goto free_and_fail2;11751176 np =skip_tree_prefix(state, sp.buf, sp.len);1177if(!np)1178goto free_and_fail2;11791180 len = sp.buf + sp.len - np;1181if(len < second - name &&1182!strncmp(np, name, len) &&1183isspace(name[len])) {1184/* Good */1185strbuf_remove(&sp,0, np - sp.buf);1186returnstrbuf_detach(&sp, NULL);1187}11881189 free_and_fail2:1190strbuf_release(&sp);1191return NULL;1192}1193}11941195/*1196 * Accept a name only if it shows up twice, exactly the same1197 * form.1198 */1199 second =strchr(name,'\n');1200if(!second)1201return NULL;1202 line_len = second - name;1203for(len =0; ; len++) {1204switch(name[len]) {1205default:1206continue;1207case'\n':1208return NULL;1209case'\t':case' ':1210/*1211 * Is this the separator between the preimage1212 * and the postimage pathname? Again, we are1213 * only interested in the case where there is1214 * no rename, as this is only to set def_name1215 * and a rename patch has the names elsewhere1216 * in an unambiguous form.1217 */1218if(!name[len +1])1219return NULL;/* no postimage name */1220 second =skip_tree_prefix(state, name + len +1,1221 line_len - (len +1));1222if(!second)1223return NULL;1224/*1225 * Does len bytes starting at "name" and "second"1226 * (that are separated by one HT or SP we just1227 * found) exactly match?1228 */1229if(second[len] =='\n'&& !strncmp(name, second, len))1230returnxmemdupz(name, len);1231}1232}1233}12341235/* Verify that we recognize the lines following a git header */1236static intparse_git_header(struct apply_state *state,1237const char*line,1238int len,1239unsigned int size,1240struct patch *patch)1241{1242unsigned long offset;12431244/* A git diff has explicit new/delete information, so we don't guess */1245 patch->is_new =0;1246 patch->is_delete =0;12471248/*1249 * Some things may not have the old name in the1250 * rest of the headers anywhere (pure mode changes,1251 * or removing or adding empty files), so we get1252 * the default name from the header.1253 */1254 patch->def_name =git_header_name(state, line, len);1255if(patch->def_name && state->root.len) {1256char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1257free(patch->def_name);1258 patch->def_name = s;1259}12601261 line += len;1262 size -= len;1263 state->linenr++;1264for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1265static const struct opentry {1266const char*str;1267int(*fn)(struct apply_state *,const char*,struct patch *);1268} optable[] = {1269{"@@ -", gitdiff_hdrend },1270{"--- ", gitdiff_oldname },1271{"+++ ", gitdiff_newname },1272{"old mode ", gitdiff_oldmode },1273{"new mode ", gitdiff_newmode },1274{"deleted file mode ", gitdiff_delete },1275{"new file mode ", gitdiff_newfile },1276{"copy from ", gitdiff_copysrc },1277{"copy to ", gitdiff_copydst },1278{"rename old ", gitdiff_renamesrc },1279{"rename new ", gitdiff_renamedst },1280{"rename from ", gitdiff_renamesrc },1281{"rename to ", gitdiff_renamedst },1282{"similarity index ", gitdiff_similarity },1283{"dissimilarity index ", gitdiff_dissimilarity },1284{"index ", gitdiff_index },1285{"", gitdiff_unrecognized },1286};1287int i;12881289 len =linelen(line, size);1290if(!len || line[len-1] !='\n')1291break;1292for(i =0; i <ARRAY_SIZE(optable); i++) {1293const struct opentry *p = optable + i;1294int oplen =strlen(p->str);1295if(len < oplen ||memcmp(p->str, line, oplen))1296continue;1297if(p->fn(state, line + oplen, patch) <0)1298return offset;1299break;1300}1301}13021303return offset;1304}13051306static intparse_num(const char*line,unsigned long*p)1307{1308char*ptr;13091310if(!isdigit(*line))1311return0;1312*p =strtoul(line, &ptr,10);1313return ptr - line;1314}13151316static intparse_range(const char*line,int len,int offset,const char*expect,1317unsigned long*p1,unsigned long*p2)1318{1319int digits, ex;13201321if(offset <0|| offset >= len)1322return-1;1323 line += offset;1324 len -= offset;13251326 digits =parse_num(line, p1);1327if(!digits)1328return-1;13291330 offset += digits;1331 line += digits;1332 len -= digits;13331334*p2 =1;1335if(*line ==',') {1336 digits =parse_num(line+1, p2);1337if(!digits)1338return-1;13391340 offset += digits+1;1341 line += digits+1;1342 len -= digits+1;1343}13441345 ex =strlen(expect);1346if(ex > len)1347return-1;1348if(memcmp(line, expect, ex))1349return-1;13501351return offset + ex;1352}13531354static voidrecount_diff(const char*line,int size,struct fragment *fragment)1355{1356int oldlines =0, newlines =0, ret =0;13571358if(size <1) {1359warning("recount: ignore empty hunk");1360return;1361}13621363for(;;) {1364int len =linelen(line, size);1365 size -= len;1366 line += len;13671368if(size <1)1369break;13701371switch(*line) {1372case' ':case'\n':1373 newlines++;1374/* fall through */1375case'-':1376 oldlines++;1377continue;1378case'+':1379 newlines++;1380continue;1381case'\\':1382continue;1383case'@':1384 ret = size <3|| !starts_with(line,"@@ ");1385break;1386case'd':1387 ret = size <5|| !starts_with(line,"diff ");1388break;1389default:1390 ret = -1;1391break;1392}1393if(ret) {1394warning(_("recount: unexpected line: %.*s"),1395(int)linelen(line, size), line);1396return;1397}1398break;1399}1400 fragment->oldlines = oldlines;1401 fragment->newlines = newlines;1402}14031404/*1405 * Parse a unified diff fragment header of the1406 * form "@@ -a,b +c,d @@"1407 */1408static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1409{1410int offset;14111412if(!len || line[len-1] !='\n')1413return-1;14141415/* Figure out the number of lines in a fragment */1416 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1417 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14181419return offset;1420}14211422static intfind_header(struct apply_state *state,1423const char*line,1424unsigned long size,1425int*hdrsize,1426struct patch *patch)1427{1428unsigned long offset, len;14291430 patch->is_toplevel_relative =0;1431 patch->is_rename = patch->is_copy =0;1432 patch->is_new = patch->is_delete = -1;1433 patch->old_mode = patch->new_mode =0;1434 patch->old_name = patch->new_name = NULL;1435for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1436unsigned long nextlen;14371438 len =linelen(line, size);1439if(!len)1440break;14411442/* Testing this early allows us to take a few shortcuts.. */1443if(len <6)1444continue;14451446/*1447 * Make sure we don't find any unconnected patch fragments.1448 * That's a sign that we didn't find a header, and that a1449 * patch has become corrupted/broken up.1450 */1451if(!memcmp("@@ -", line,4)) {1452struct fragment dummy;1453if(parse_fragment_header(line, len, &dummy) <0)1454continue;1455die(_("patch fragment without header at line%d: %.*s"),1456 state->linenr, (int)len-1, line);1457}14581459if(size < len +6)1460break;14611462/*1463 * Git patch? It might not have a real patch, just a rename1464 * or mode change, so we handle that specially1465 */1466if(!memcmp("diff --git ", line,11)) {1467int git_hdr_len =parse_git_header(state, line, len, size, patch);1468if(git_hdr_len <= len)1469continue;1470if(!patch->old_name && !patch->new_name) {1471if(!patch->def_name)1472die(Q_("git diff header lacks filename information when removing "1473"%dleading pathname component (line%d)",1474"git diff header lacks filename information when removing "1475"%dleading pathname components (line%d)",1476 state->p_value),1477 state->p_value, state->linenr);1478 patch->old_name =xstrdup(patch->def_name);1479 patch->new_name =xstrdup(patch->def_name);1480}1481if(!patch->is_delete && !patch->new_name)1482die("git diff header lacks filename information "1483"(line%d)", state->linenr);1484 patch->is_toplevel_relative =1;1485*hdrsize = git_hdr_len;1486return offset;1487}14881489/* --- followed by +++ ? */1490if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1491continue;14921493/*1494 * We only accept unified patches, so we want it to1495 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1496 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1497 */1498 nextlen =linelen(line + len, size - len);1499if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1500continue;15011502/* Ok, we'll consider it a patch */1503parse_traditional_patch(state, line, line+len, patch);1504*hdrsize = len + nextlen;1505 state->linenr +=2;1506return offset;1507}1508return-1;1509}15101511static voidrecord_ws_error(struct apply_state *state,1512unsigned result,1513const char*line,1514int len,1515int linenr)1516{1517char*err;15181519if(!result)1520return;15211522 state->whitespace_error++;1523if(state->squelch_whitespace_errors &&1524 state->squelch_whitespace_errors < state->whitespace_error)1525return;15261527 err =whitespace_error_string(result);1528fprintf(stderr,"%s:%d:%s.\n%.*s\n",1529 state->patch_input_file, linenr, err, len, line);1530free(err);1531}15321533static voidcheck_whitespace(struct apply_state *state,1534const char*line,1535int len,1536unsigned ws_rule)1537{1538unsigned result =ws_check(line +1, len -1, ws_rule);15391540record_ws_error(state, result, line +1, len -2, state->linenr);1541}15421543/*1544 * Parse a unified diff. Note that this really needs to parse each1545 * fragment separately, since the only way to know the difference1546 * between a "---" that is part of a patch, and a "---" that starts1547 * the next patch is to look at the line counts..1548 */1549static intparse_fragment(struct apply_state *state,1550const char*line,1551unsigned long size,1552struct patch *patch,1553struct fragment *fragment)1554{1555int added, deleted;1556int len =linelen(line, size), offset;1557unsigned long oldlines, newlines;1558unsigned long leading, trailing;15591560 offset =parse_fragment_header(line, len, fragment);1561if(offset <0)1562return-1;1563if(offset >0&& patch->recount)1564recount_diff(line + offset, size - offset, fragment);1565 oldlines = fragment->oldlines;1566 newlines = fragment->newlines;1567 leading =0;1568 trailing =0;15691570/* Parse the thing.. */1571 line += len;1572 size -= len;1573 state->linenr++;1574 added = deleted =0;1575for(offset = len;15760< size;1577 offset += len, size -= len, line += len, state->linenr++) {1578if(!oldlines && !newlines)1579break;1580 len =linelen(line, size);1581if(!len || line[len-1] !='\n')1582return-1;1583switch(*line) {1584default:1585return-1;1586case'\n':/* newer GNU diff, an empty context line */1587case' ':1588 oldlines--;1589 newlines--;1590if(!deleted && !added)1591 leading++;1592 trailing++;1593if(!state->apply_in_reverse &&1594 state->ws_error_action == correct_ws_error)1595check_whitespace(state, line, len, patch->ws_rule);1596break;1597case'-':1598if(state->apply_in_reverse &&1599 state->ws_error_action != nowarn_ws_error)1600check_whitespace(state, line, len, patch->ws_rule);1601 deleted++;1602 oldlines--;1603 trailing =0;1604break;1605case'+':1606if(!state->apply_in_reverse &&1607 state->ws_error_action != nowarn_ws_error)1608check_whitespace(state, line, len, patch->ws_rule);1609 added++;1610 newlines--;1611 trailing =0;1612break;16131614/*1615 * We allow "\ No newline at end of file". Depending1616 * on locale settings when the patch was produced we1617 * don't know what this line looks like. The only1618 * thing we do know is that it begins with "\ ".1619 * Checking for 12 is just for sanity check -- any1620 * l10n of "\ No newline..." is at least that long.1621 */1622case'\\':1623if(len <12||memcmp(line,"\\",2))1624return-1;1625break;1626}1627}1628if(oldlines || newlines)1629return-1;1630if(!deleted && !added)1631return-1;16321633 fragment->leading = leading;1634 fragment->trailing = trailing;16351636/*1637 * If a fragment ends with an incomplete line, we failed to include1638 * it in the above loop because we hit oldlines == newlines == 01639 * before seeing it.1640 */1641if(12< size && !memcmp(line,"\\",2))1642 offset +=linelen(line, size);16431644 patch->lines_added += added;1645 patch->lines_deleted += deleted;16461647if(0< patch->is_new && oldlines)1648returnerror(_("new file depends on old contents"));1649if(0< patch->is_delete && newlines)1650returnerror(_("deleted file still has contents"));1651return offset;1652}16531654/*1655 * We have seen "diff --git a/... b/..." header (or a traditional patch1656 * header). Read hunks that belong to this patch into fragments and hang1657 * them to the given patch structure.1658 *1659 * The (fragment->patch, fragment->size) pair points into the memory given1660 * by the caller, not a copy, when we return.1661 */1662static intparse_single_patch(struct apply_state *state,1663const char*line,1664unsigned long size,1665struct patch *patch)1666{1667unsigned long offset =0;1668unsigned long oldlines =0, newlines =0, context =0;1669struct fragment **fragp = &patch->fragments;16701671while(size >4&& !memcmp(line,"@@ -",4)) {1672struct fragment *fragment;1673int len;16741675 fragment =xcalloc(1,sizeof(*fragment));1676 fragment->linenr = state->linenr;1677 len =parse_fragment(state, line, size, patch, fragment);1678if(len <=0)1679die(_("corrupt patch at line%d"), state->linenr);1680 fragment->patch = line;1681 fragment->size = len;1682 oldlines += fragment->oldlines;1683 newlines += fragment->newlines;1684 context += fragment->leading + fragment->trailing;16851686*fragp = fragment;1687 fragp = &fragment->next;16881689 offset += len;1690 line += len;1691 size -= len;1692}16931694/*1695 * If something was removed (i.e. we have old-lines) it cannot1696 * be creation, and if something was added it cannot be1697 * deletion. However, the reverse is not true; --unified=01698 * patches that only add are not necessarily creation even1699 * though they do not have any old lines, and ones that only1700 * delete are not necessarily deletion.1701 *1702 * Unfortunately, a real creation/deletion patch do _not_ have1703 * any context line by definition, so we cannot safely tell it1704 * apart with --unified=0 insanity. At least if the patch has1705 * more than one hunk it is not creation or deletion.1706 */1707if(patch->is_new <0&&1708(oldlines || (patch->fragments && patch->fragments->next)))1709 patch->is_new =0;1710if(patch->is_delete <0&&1711(newlines || (patch->fragments && patch->fragments->next)))1712 patch->is_delete =0;17131714if(0< patch->is_new && oldlines)1715die(_("new file%sdepends on old contents"), patch->new_name);1716if(0< patch->is_delete && newlines)1717die(_("deleted file%sstill has contents"), patch->old_name);1718if(!patch->is_delete && !newlines && context)1719fprintf_ln(stderr,1720_("** warning: "1721"file%sbecomes empty but is not deleted"),1722 patch->new_name);17231724return offset;1725}17261727staticinlineintmetadata_changes(struct patch *patch)1728{1729return patch->is_rename >0||1730 patch->is_copy >0||1731 patch->is_new >0||1732 patch->is_delete ||1733(patch->old_mode && patch->new_mode &&1734 patch->old_mode != patch->new_mode);1735}17361737static char*inflate_it(const void*data,unsigned long size,1738unsigned long inflated_size)1739{1740 git_zstream stream;1741void*out;1742int st;17431744memset(&stream,0,sizeof(stream));17451746 stream.next_in = (unsigned char*)data;1747 stream.avail_in = size;1748 stream.next_out = out =xmalloc(inflated_size);1749 stream.avail_out = inflated_size;1750git_inflate_init(&stream);1751 st =git_inflate(&stream, Z_FINISH);1752git_inflate_end(&stream);1753if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1754free(out);1755return NULL;1756}1757return out;1758}17591760/*1761 * Read a binary hunk and return a new fragment; fragment->patch1762 * points at an allocated memory that the caller must free, so1763 * it is marked as "->free_patch = 1".1764 */1765static struct fragment *parse_binary_hunk(struct apply_state *state,1766char**buf_p,1767unsigned long*sz_p,1768int*status_p,1769int*used_p)1770{1771/*1772 * Expect a line that begins with binary patch method ("literal"1773 * or "delta"), followed by the length of data before deflating.1774 * a sequence of 'length-byte' followed by base-85 encoded data1775 * should follow, terminated by a newline.1776 *1777 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1778 * and we would limit the patch line to 66 characters,1779 * so one line can fit up to 13 groups that would decode1780 * to 52 bytes max. The length byte 'A'-'Z' corresponds1781 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1782 */1783int llen, used;1784unsigned long size = *sz_p;1785char*buffer = *buf_p;1786int patch_method;1787unsigned long origlen;1788char*data = NULL;1789int hunk_size =0;1790struct fragment *frag;17911792 llen =linelen(buffer, size);1793 used = llen;17941795*status_p =0;17961797if(starts_with(buffer,"delta ")) {1798 patch_method = BINARY_DELTA_DEFLATED;1799 origlen =strtoul(buffer +6, NULL,10);1800}1801else if(starts_with(buffer,"literal ")) {1802 patch_method = BINARY_LITERAL_DEFLATED;1803 origlen =strtoul(buffer +8, NULL,10);1804}1805else1806return NULL;18071808 state->linenr++;1809 buffer += llen;1810while(1) {1811int byte_length, max_byte_length, newsize;1812 llen =linelen(buffer, size);1813 used += llen;1814 state->linenr++;1815if(llen ==1) {1816/* consume the blank line */1817 buffer++;1818 size--;1819break;1820}1821/*1822 * Minimum line is "A00000\n" which is 7-byte long,1823 * and the line length must be multiple of 5 plus 2.1824 */1825if((llen <7) || (llen-2) %5)1826goto corrupt;1827 max_byte_length = (llen -2) /5*4;1828 byte_length = *buffer;1829if('A'<= byte_length && byte_length <='Z')1830 byte_length = byte_length -'A'+1;1831else if('a'<= byte_length && byte_length <='z')1832 byte_length = byte_length -'a'+27;1833else1834goto corrupt;1835/* if the input length was not multiple of 4, we would1836 * have filler at the end but the filler should never1837 * exceed 3 bytes1838 */1839if(max_byte_length < byte_length ||1840 byte_length <= max_byte_length -4)1841goto corrupt;1842 newsize = hunk_size + byte_length;1843 data =xrealloc(data, newsize);1844if(decode_85(data + hunk_size, buffer +1, byte_length))1845goto corrupt;1846 hunk_size = newsize;1847 buffer += llen;1848 size -= llen;1849}18501851 frag =xcalloc(1,sizeof(*frag));1852 frag->patch =inflate_it(data, hunk_size, origlen);1853 frag->free_patch =1;1854if(!frag->patch)1855goto corrupt;1856free(data);1857 frag->size = origlen;1858*buf_p = buffer;1859*sz_p = size;1860*used_p = used;1861 frag->binary_patch_method = patch_method;1862return frag;18631864 corrupt:1865free(data);1866*status_p = -1;1867error(_("corrupt binary patch at line%d: %.*s"),1868 state->linenr-1, llen-1, buffer);1869return NULL;1870}18711872/*1873 * Returns:1874 * -1 in case of error,1875 * the length of the parsed binary patch otherwise1876 */1877static intparse_binary(struct apply_state *state,1878char*buffer,1879unsigned long size,1880struct patch *patch)1881{1882/*1883 * We have read "GIT binary patch\n"; what follows is a line1884 * that says the patch method (currently, either "literal" or1885 * "delta") and the length of data before deflating; a1886 * sequence of 'length-byte' followed by base-85 encoded data1887 * follows.1888 *1889 * When a binary patch is reversible, there is another binary1890 * hunk in the same format, starting with patch method (either1891 * "literal" or "delta") with the length of data, and a sequence1892 * of length-byte + base-85 encoded data, terminated with another1893 * empty line. This data, when applied to the postimage, produces1894 * the preimage.1895 */1896struct fragment *forward;1897struct fragment *reverse;1898int status;1899int used, used_1;19001901 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);1902if(!forward && !status)1903/* there has to be one hunk (forward hunk) */1904returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);1905if(status)1906/* otherwise we already gave an error message */1907return status;19081909 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);1910if(reverse)1911 used += used_1;1912else if(status) {1913/*1914 * Not having reverse hunk is not an error, but having1915 * a corrupt reverse hunk is.1916 */1917free((void*) forward->patch);1918free(forward);1919return status;1920}1921 forward->next = reverse;1922 patch->fragments = forward;1923 patch->is_binary =1;1924return used;1925}19261927static voidprefix_one(struct apply_state *state,char**name)1928{1929char*old_name = *name;1930if(!old_name)1931return;1932*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));1933free(old_name);1934}19351936static voidprefix_patch(struct apply_state *state,struct patch *p)1937{1938if(!state->prefix || p->is_toplevel_relative)1939return;1940prefix_one(state, &p->new_name);1941prefix_one(state, &p->old_name);1942}19431944/*1945 * include/exclude1946 */19471948static voidadd_name_limit(struct apply_state *state,1949const char*name,1950int exclude)1951{1952struct string_list_item *it;19531954 it =string_list_append(&state->limit_by_name, name);1955 it->util = exclude ? NULL : (void*)1;1956}19571958static intuse_patch(struct apply_state *state,struct patch *p)1959{1960const char*pathname = p->new_name ? p->new_name : p->old_name;1961int i;19621963/* Paths outside are not touched regardless of "--include" */1964if(0< state->prefix_length) {1965int pathlen =strlen(pathname);1966if(pathlen <= state->prefix_length ||1967memcmp(state->prefix, pathname, state->prefix_length))1968return0;1969}19701971/* See if it matches any of exclude/include rule */1972for(i =0; i < state->limit_by_name.nr; i++) {1973struct string_list_item *it = &state->limit_by_name.items[i];1974if(!wildmatch(it->string, pathname,0, NULL))1975return(it->util != NULL);1976}19771978/*1979 * If we had any include, a path that does not match any rule is1980 * not used. Otherwise, we saw bunch of exclude rules (or none)1981 * and such a path is used.1982 */1983return!state->has_include;1984}198519861987/*1988 * Read the patch text in "buffer" that extends for "size" bytes; stop1989 * reading after seeing a single patch (i.e. changes to a single file).1990 * Create fragments (i.e. patch hunks) and hang them to the given patch.1991 * Return the number of bytes consumed, so that the caller can call us1992 * again for the next patch.1993 */1994static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)1995{1996int hdrsize, patchsize;1997int offset =find_header(state, buffer, size, &hdrsize, patch);19981999if(offset <0)2000return offset;20012002prefix_patch(state, patch);20032004if(!use_patch(state, patch))2005 patch->ws_rule =0;2006else2007 patch->ws_rule =whitespace_rule(patch->new_name2008? patch->new_name2009: patch->old_name);20102011 patchsize =parse_single_patch(state,2012 buffer + offset + hdrsize,2013 size - offset - hdrsize,2014 patch);20152016if(!patchsize) {2017static const char git_binary[] ="GIT binary patch\n";2018int hd = hdrsize + offset;2019unsigned long llen =linelen(buffer + hd, size - hd);20202021if(llen ==sizeof(git_binary) -1&&2022!memcmp(git_binary, buffer + hd, llen)) {2023int used;2024 state->linenr++;2025 used =parse_binary(state, buffer + hd + llen,2026 size - hd - llen, patch);2027if(used <0)2028return-1;2029if(used)2030 patchsize = used + llen;2031else2032 patchsize =0;2033}2034else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2035static const char*binhdr[] = {2036"Binary files ",2037"Files ",2038 NULL,2039};2040int i;2041for(i =0; binhdr[i]; i++) {2042int len =strlen(binhdr[i]);2043if(len < size - hd &&2044!memcmp(binhdr[i], buffer + hd, len)) {2045 state->linenr++;2046 patch->is_binary =1;2047 patchsize = llen;2048break;2049}2050}2051}20522053/* Empty patch cannot be applied if it is a text patch2054 * without metadata change. A binary patch appears2055 * empty to us here.2056 */2057if((state->apply || state->check) &&2058(!patch->is_binary && !metadata_changes(patch)))2059die(_("patch with only garbage at line%d"), state->linenr);2060}20612062return offset + hdrsize + patchsize;2063}20642065#define swap(a,b) myswap((a),(b),sizeof(a))20662067#define myswap(a, b, size) do { \2068 unsigned char mytmp[size]; \2069 memcpy(mytmp, &a, size); \2070 memcpy(&a, &b, size); \2071 memcpy(&b, mytmp, size); \2072} while (0)20732074static voidreverse_patches(struct patch *p)2075{2076for(; p; p = p->next) {2077struct fragment *frag = p->fragments;20782079swap(p->new_name, p->old_name);2080swap(p->new_mode, p->old_mode);2081swap(p->is_new, p->is_delete);2082swap(p->lines_added, p->lines_deleted);2083swap(p->old_sha1_prefix, p->new_sha1_prefix);20842085for(; frag; frag = frag->next) {2086swap(frag->newpos, frag->oldpos);2087swap(frag->newlines, frag->oldlines);2088}2089}2090}20912092static const char pluses[] =2093"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2094static const char minuses[]=2095"----------------------------------------------------------------------";20962097static voidshow_stats(struct apply_state *state,struct patch *patch)2098{2099struct strbuf qname = STRBUF_INIT;2100char*cp = patch->new_name ? patch->new_name : patch->old_name;2101int max, add, del;21022103quote_c_style(cp, &qname, NULL,0);21042105/*2106 * "scale" the filename2107 */2108 max = state->max_len;2109if(max >50)2110 max =50;21112112if(qname.len > max) {2113 cp =strchr(qname.buf + qname.len +3- max,'/');2114if(!cp)2115 cp = qname.buf + qname.len +3- max;2116strbuf_splice(&qname,0, cp - qname.buf,"...",3);2117}21182119if(patch->is_binary) {2120printf(" %-*s | Bin\n", max, qname.buf);2121strbuf_release(&qname);2122return;2123}21242125printf(" %-*s |", max, qname.buf);2126strbuf_release(&qname);21272128/*2129 * scale the add/delete2130 */2131 max = max + state->max_change >70?70- max : state->max_change;2132 add = patch->lines_added;2133 del = patch->lines_deleted;21342135if(state->max_change >0) {2136int total = ((add + del) * max + state->max_change /2) / state->max_change;2137 add = (add * max + state->max_change /2) / state->max_change;2138 del = total - add;2139}2140printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2141 add, pluses, del, minuses);2142}21432144static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2145{2146switch(st->st_mode & S_IFMT) {2147case S_IFLNK:2148if(strbuf_readlink(buf, path, st->st_size) <0)2149returnerror(_("unable to read symlink%s"), path);2150return0;2151case S_IFREG:2152if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2153returnerror(_("unable to open or read%s"), path);2154convert_to_git(path, buf->buf, buf->len, buf,0);2155return0;2156default:2157return-1;2158}2159}21602161/*2162 * Update the preimage, and the common lines in postimage,2163 * from buffer buf of length len. If postlen is 0 the postimage2164 * is updated in place, otherwise it's updated on a new buffer2165 * of length postlen2166 */21672168static voidupdate_pre_post_images(struct image *preimage,2169struct image *postimage,2170char*buf,2171size_t len,size_t postlen)2172{2173int i, ctx, reduced;2174char*new, *old, *fixed;2175struct image fixed_preimage;21762177/*2178 * Update the preimage with whitespace fixes. Note that we2179 * are not losing preimage->buf -- apply_one_fragment() will2180 * free "oldlines".2181 */2182prepare_image(&fixed_preimage, buf, len,1);2183assert(postlen2184? fixed_preimage.nr == preimage->nr2185: fixed_preimage.nr <= preimage->nr);2186for(i =0; i < fixed_preimage.nr; i++)2187 fixed_preimage.line[i].flag = preimage->line[i].flag;2188free(preimage->line_allocated);2189*preimage = fixed_preimage;21902191/*2192 * Adjust the common context lines in postimage. This can be2193 * done in-place when we are shrinking it with whitespace2194 * fixing, but needs a new buffer when ignoring whitespace or2195 * expanding leading tabs to spaces.2196 *2197 * We trust the caller to tell us if the update can be done2198 * in place (postlen==0) or not.2199 */2200 old = postimage->buf;2201if(postlen)2202new= postimage->buf =xmalloc(postlen);2203else2204new= old;2205 fixed = preimage->buf;22062207for(i = reduced = ctx =0; i < postimage->nr; i++) {2208size_t l_len = postimage->line[i].len;2209if(!(postimage->line[i].flag & LINE_COMMON)) {2210/* an added line -- no counterparts in preimage */2211memmove(new, old, l_len);2212 old += l_len;2213new+= l_len;2214continue;2215}22162217/* a common context -- skip it in the original postimage */2218 old += l_len;22192220/* and find the corresponding one in the fixed preimage */2221while(ctx < preimage->nr &&2222!(preimage->line[ctx].flag & LINE_COMMON)) {2223 fixed += preimage->line[ctx].len;2224 ctx++;2225}22262227/*2228 * preimage is expected to run out, if the caller2229 * fixed addition of trailing blank lines.2230 */2231if(preimage->nr <= ctx) {2232 reduced++;2233continue;2234}22352236/* and copy it in, while fixing the line length */2237 l_len = preimage->line[ctx].len;2238memcpy(new, fixed, l_len);2239new+= l_len;2240 fixed += l_len;2241 postimage->line[i].len = l_len;2242 ctx++;2243}22442245if(postlen2246? postlen <new- postimage->buf2247: postimage->len <new- postimage->buf)2248die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2249(int)postlen, (int) postimage->len, (int)(new- postimage->buf));22502251/* Fix the length of the whole thing */2252 postimage->len =new- postimage->buf;2253 postimage->nr -= reduced;2254}22552256static intline_by_line_fuzzy_match(struct image *img,2257struct image *preimage,2258struct image *postimage,2259unsigned longtry,2260int try_lno,2261int preimage_limit)2262{2263int i;2264size_t imgoff =0;2265size_t preoff =0;2266size_t postlen = postimage->len;2267size_t extra_chars;2268char*buf;2269char*preimage_eof;2270char*preimage_end;2271struct strbuf fixed;2272char*fixed_buf;2273size_t fixed_len;22742275for(i =0; i < preimage_limit; i++) {2276size_t prelen = preimage->line[i].len;2277size_t imglen = img->line[try_lno+i].len;22782279if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2280 preimage->buf + preoff, prelen))2281return0;2282if(preimage->line[i].flag & LINE_COMMON)2283 postlen += imglen - prelen;2284 imgoff += imglen;2285 preoff += prelen;2286}22872288/*2289 * Ok, the preimage matches with whitespace fuzz.2290 *2291 * imgoff now holds the true length of the target that2292 * matches the preimage before the end of the file.2293 *2294 * Count the number of characters in the preimage that fall2295 * beyond the end of the file and make sure that all of them2296 * are whitespace characters. (This can only happen if2297 * we are removing blank lines at the end of the file.)2298 */2299 buf = preimage_eof = preimage->buf + preoff;2300for( ; i < preimage->nr; i++)2301 preoff += preimage->line[i].len;2302 preimage_end = preimage->buf + preoff;2303for( ; buf < preimage_end; buf++)2304if(!isspace(*buf))2305return0;23062307/*2308 * Update the preimage and the common postimage context2309 * lines to use the same whitespace as the target.2310 * If whitespace is missing in the target (i.e.2311 * if the preimage extends beyond the end of the file),2312 * use the whitespace from the preimage.2313 */2314 extra_chars = preimage_end - preimage_eof;2315strbuf_init(&fixed, imgoff + extra_chars);2316strbuf_add(&fixed, img->buf +try, imgoff);2317strbuf_add(&fixed, preimage_eof, extra_chars);2318 fixed_buf =strbuf_detach(&fixed, &fixed_len);2319update_pre_post_images(preimage, postimage,2320 fixed_buf, fixed_len, postlen);2321return1;2322}23232324static intmatch_fragment(struct apply_state *state,2325struct image *img,2326struct image *preimage,2327struct image *postimage,2328unsigned longtry,2329int try_lno,2330unsigned ws_rule,2331int match_beginning,int match_end)2332{2333int i;2334char*fixed_buf, *buf, *orig, *target;2335struct strbuf fixed;2336size_t fixed_len, postlen;2337int preimage_limit;23382339if(preimage->nr + try_lno <= img->nr) {2340/*2341 * The hunk falls within the boundaries of img.2342 */2343 preimage_limit = preimage->nr;2344if(match_end && (preimage->nr + try_lno != img->nr))2345return0;2346}else if(state->ws_error_action == correct_ws_error &&2347(ws_rule & WS_BLANK_AT_EOF)) {2348/*2349 * This hunk extends beyond the end of img, and we are2350 * removing blank lines at the end of the file. This2351 * many lines from the beginning of the preimage must2352 * match with img, and the remainder of the preimage2353 * must be blank.2354 */2355 preimage_limit = img->nr - try_lno;2356}else{2357/*2358 * The hunk extends beyond the end of the img and2359 * we are not removing blanks at the end, so we2360 * should reject the hunk at this position.2361 */2362return0;2363}23642365if(match_beginning && try_lno)2366return0;23672368/* Quick hash check */2369for(i =0; i < preimage_limit; i++)2370if((img->line[try_lno + i].flag & LINE_PATCHED) ||2371(preimage->line[i].hash != img->line[try_lno + i].hash))2372return0;23732374if(preimage_limit == preimage->nr) {2375/*2376 * Do we have an exact match? If we were told to match2377 * at the end, size must be exactly at try+fragsize,2378 * otherwise try+fragsize must be still within the preimage,2379 * and either case, the old piece should match the preimage2380 * exactly.2381 */2382if((match_end2383? (try+ preimage->len == img->len)2384: (try+ preimage->len <= img->len)) &&2385!memcmp(img->buf +try, preimage->buf, preimage->len))2386return1;2387}else{2388/*2389 * The preimage extends beyond the end of img, so2390 * there cannot be an exact match.2391 *2392 * There must be one non-blank context line that match2393 * a line before the end of img.2394 */2395char*buf_end;23962397 buf = preimage->buf;2398 buf_end = buf;2399for(i =0; i < preimage_limit; i++)2400 buf_end += preimage->line[i].len;24012402for( ; buf < buf_end; buf++)2403if(!isspace(*buf))2404break;2405if(buf == buf_end)2406return0;2407}24082409/*2410 * No exact match. If we are ignoring whitespace, run a line-by-line2411 * fuzzy matching. We collect all the line length information because2412 * we need it to adjust whitespace if we match.2413 */2414if(state->ws_ignore_action == ignore_ws_change)2415returnline_by_line_fuzzy_match(img, preimage, postimage,2416try, try_lno, preimage_limit);24172418if(state->ws_error_action != correct_ws_error)2419return0;24202421/*2422 * The hunk does not apply byte-by-byte, but the hash says2423 * it might with whitespace fuzz. We weren't asked to2424 * ignore whitespace, we were asked to correct whitespace2425 * errors, so let's try matching after whitespace correction.2426 *2427 * While checking the preimage against the target, whitespace2428 * errors in both fixed, we count how large the corresponding2429 * postimage needs to be. The postimage prepared by2430 * apply_one_fragment() has whitespace errors fixed on added2431 * lines already, but the common lines were propagated as-is,2432 * which may become longer when their whitespace errors are2433 * fixed.2434 */24352436/* First count added lines in postimage */2437 postlen =0;2438for(i =0; i < postimage->nr; i++) {2439if(!(postimage->line[i].flag & LINE_COMMON))2440 postlen += postimage->line[i].len;2441}24422443/*2444 * The preimage may extend beyond the end of the file,2445 * but in this loop we will only handle the part of the2446 * preimage that falls within the file.2447 */2448strbuf_init(&fixed, preimage->len +1);2449 orig = preimage->buf;2450 target = img->buf +try;2451for(i =0; i < preimage_limit; i++) {2452size_t oldlen = preimage->line[i].len;2453size_t tgtlen = img->line[try_lno + i].len;2454size_t fixstart = fixed.len;2455struct strbuf tgtfix;2456int match;24572458/* Try fixing the line in the preimage */2459ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);24602461/* Try fixing the line in the target */2462strbuf_init(&tgtfix, tgtlen);2463ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);24642465/*2466 * If they match, either the preimage was based on2467 * a version before our tree fixed whitespace breakage,2468 * or we are lacking a whitespace-fix patch the tree2469 * the preimage was based on already had (i.e. target2470 * has whitespace breakage, the preimage doesn't).2471 * In either case, we are fixing the whitespace breakages2472 * so we might as well take the fix together with their2473 * real change.2474 */2475 match = (tgtfix.len == fixed.len - fixstart &&2476!memcmp(tgtfix.buf, fixed.buf + fixstart,2477 fixed.len - fixstart));24782479/* Add the length if this is common with the postimage */2480if(preimage->line[i].flag & LINE_COMMON)2481 postlen += tgtfix.len;24822483strbuf_release(&tgtfix);2484if(!match)2485goto unmatch_exit;24862487 orig += oldlen;2488 target += tgtlen;2489}249024912492/*2493 * Now handle the lines in the preimage that falls beyond the2494 * end of the file (if any). They will only match if they are2495 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2496 * false).2497 */2498for( ; i < preimage->nr; i++) {2499size_t fixstart = fixed.len;/* start of the fixed preimage */2500size_t oldlen = preimage->line[i].len;2501int j;25022503/* Try fixing the line in the preimage */2504ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25052506for(j = fixstart; j < fixed.len; j++)2507if(!isspace(fixed.buf[j]))2508goto unmatch_exit;25092510 orig += oldlen;2511}25122513/*2514 * Yes, the preimage is based on an older version that still2515 * has whitespace breakages unfixed, and fixing them makes the2516 * hunk match. Update the context lines in the postimage.2517 */2518 fixed_buf =strbuf_detach(&fixed, &fixed_len);2519if(postlen < postimage->len)2520 postlen =0;2521update_pre_post_images(preimage, postimage,2522 fixed_buf, fixed_len, postlen);2523return1;25242525 unmatch_exit:2526strbuf_release(&fixed);2527return0;2528}25292530static intfind_pos(struct apply_state *state,2531struct image *img,2532struct image *preimage,2533struct image *postimage,2534int line,2535unsigned ws_rule,2536int match_beginning,int match_end)2537{2538int i;2539unsigned long backwards, forwards,try;2540int backwards_lno, forwards_lno, try_lno;25412542/*2543 * If match_beginning or match_end is specified, there is no2544 * point starting from a wrong line that will never match and2545 * wander around and wait for a match at the specified end.2546 */2547if(match_beginning)2548 line =0;2549else if(match_end)2550 line = img->nr - preimage->nr;25512552/*2553 * Because the comparison is unsigned, the following test2554 * will also take care of a negative line number that can2555 * result when match_end and preimage is larger than the target.2556 */2557if((size_t) line > img->nr)2558 line = img->nr;25592560try=0;2561for(i =0; i < line; i++)2562try+= img->line[i].len;25632564/*2565 * There's probably some smart way to do this, but I'll leave2566 * that to the smart and beautiful people. I'm simple and stupid.2567 */2568 backwards =try;2569 backwards_lno = line;2570 forwards =try;2571 forwards_lno = line;2572 try_lno = line;25732574for(i =0; ; i++) {2575if(match_fragment(state, img, preimage, postimage,2576try, try_lno, ws_rule,2577 match_beginning, match_end))2578return try_lno;25792580 again:2581if(backwards_lno ==0&& forwards_lno == img->nr)2582break;25832584if(i &1) {2585if(backwards_lno ==0) {2586 i++;2587goto again;2588}2589 backwards_lno--;2590 backwards -= img->line[backwards_lno].len;2591try= backwards;2592 try_lno = backwards_lno;2593}else{2594if(forwards_lno == img->nr) {2595 i++;2596goto again;2597}2598 forwards += img->line[forwards_lno].len;2599 forwards_lno++;2600try= forwards;2601 try_lno = forwards_lno;2602}26032604}2605return-1;2606}26072608static voidremove_first_line(struct image *img)2609{2610 img->buf += img->line[0].len;2611 img->len -= img->line[0].len;2612 img->line++;2613 img->nr--;2614}26152616static voidremove_last_line(struct image *img)2617{2618 img->len -= img->line[--img->nr].len;2619}26202621/*2622 * The change from "preimage" and "postimage" has been found to2623 * apply at applied_pos (counts in line numbers) in "img".2624 * Update "img" to remove "preimage" and replace it with "postimage".2625 */2626static voidupdate_image(struct apply_state *state,2627struct image *img,2628int applied_pos,2629struct image *preimage,2630struct image *postimage)2631{2632/*2633 * remove the copy of preimage at offset in img2634 * and replace it with postimage2635 */2636int i, nr;2637size_t remove_count, insert_count, applied_at =0;2638char*result;2639int preimage_limit;26402641/*2642 * If we are removing blank lines at the end of img,2643 * the preimage may extend beyond the end.2644 * If that is the case, we must be careful only to2645 * remove the part of the preimage that falls within2646 * the boundaries of img. Initialize preimage_limit2647 * to the number of lines in the preimage that falls2648 * within the boundaries.2649 */2650 preimage_limit = preimage->nr;2651if(preimage_limit > img->nr - applied_pos)2652 preimage_limit = img->nr - applied_pos;26532654for(i =0; i < applied_pos; i++)2655 applied_at += img->line[i].len;26562657 remove_count =0;2658for(i =0; i < preimage_limit; i++)2659 remove_count += img->line[applied_pos + i].len;2660 insert_count = postimage->len;26612662/* Adjust the contents */2663 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2664memcpy(result, img->buf, applied_at);2665memcpy(result + applied_at, postimage->buf, postimage->len);2666memcpy(result + applied_at + postimage->len,2667 img->buf + (applied_at + remove_count),2668 img->len - (applied_at + remove_count));2669free(img->buf);2670 img->buf = result;2671 img->len += insert_count - remove_count;2672 result[img->len] ='\0';26732674/* Adjust the line table */2675 nr = img->nr + postimage->nr - preimage_limit;2676if(preimage_limit < postimage->nr) {2677/*2678 * NOTE: this knows that we never call remove_first_line()2679 * on anything other than pre/post image.2680 */2681REALLOC_ARRAY(img->line, nr);2682 img->line_allocated = img->line;2683}2684if(preimage_limit != postimage->nr)2685memmove(img->line + applied_pos + postimage->nr,2686 img->line + applied_pos + preimage_limit,2687(img->nr - (applied_pos + preimage_limit)) *2688sizeof(*img->line));2689memcpy(img->line + applied_pos,2690 postimage->line,2691 postimage->nr *sizeof(*img->line));2692if(!state->allow_overlap)2693for(i =0; i < postimage->nr; i++)2694 img->line[applied_pos + i].flag |= LINE_PATCHED;2695 img->nr = nr;2696}26972698/*2699 * Use the patch-hunk text in "frag" to prepare two images (preimage and2700 * postimage) for the hunk. Find lines that match "preimage" in "img" and2701 * replace the part of "img" with "postimage" text.2702 */2703static intapply_one_fragment(struct apply_state *state,2704struct image *img,struct fragment *frag,2705int inaccurate_eof,unsigned ws_rule,2706int nth_fragment)2707{2708int match_beginning, match_end;2709const char*patch = frag->patch;2710int size = frag->size;2711char*old, *oldlines;2712struct strbuf newlines;2713int new_blank_lines_at_end =0;2714int found_new_blank_lines_at_end =0;2715int hunk_linenr = frag->linenr;2716unsigned long leading, trailing;2717int pos, applied_pos;2718struct image preimage;2719struct image postimage;27202721memset(&preimage,0,sizeof(preimage));2722memset(&postimage,0,sizeof(postimage));2723 oldlines =xmalloc(size);2724strbuf_init(&newlines, size);27252726 old = oldlines;2727while(size >0) {2728char first;2729int len =linelen(patch, size);2730int plen;2731int added_blank_line =0;2732int is_blank_context =0;2733size_t start;27342735if(!len)2736break;27372738/*2739 * "plen" is how much of the line we should use for2740 * the actual patch data. Normally we just remove the2741 * first character on the line, but if the line is2742 * followed by "\ No newline", then we also remove the2743 * last one (which is the newline, of course).2744 */2745 plen = len -1;2746if(len < size && patch[len] =='\\')2747 plen--;2748 first = *patch;2749if(state->apply_in_reverse) {2750if(first =='-')2751 first ='+';2752else if(first =='+')2753 first ='-';2754}27552756switch(first) {2757case'\n':2758/* Newer GNU diff, empty context line */2759if(plen <0)2760/* ... followed by '\No newline'; nothing */2761break;2762*old++ ='\n';2763strbuf_addch(&newlines,'\n');2764add_line_info(&preimage,"\n",1, LINE_COMMON);2765add_line_info(&postimage,"\n",1, LINE_COMMON);2766 is_blank_context =1;2767break;2768case' ':2769if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2770ws_blank_line(patch +1, plen, ws_rule))2771 is_blank_context =1;2772case'-':2773memcpy(old, patch +1, plen);2774add_line_info(&preimage, old, plen,2775(first ==' '? LINE_COMMON :0));2776 old += plen;2777if(first =='-')2778break;2779/* Fall-through for ' ' */2780case'+':2781/* --no-add does not add new lines */2782if(first =='+'&& state->no_add)2783break;27842785 start = newlines.len;2786if(first !='+'||2787!state->whitespace_error ||2788 state->ws_error_action != correct_ws_error) {2789strbuf_add(&newlines, patch +1, plen);2790}2791else{2792ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2793}2794add_line_info(&postimage, newlines.buf + start, newlines.len - start,2795(first =='+'?0: LINE_COMMON));2796if(first =='+'&&2797(ws_rule & WS_BLANK_AT_EOF) &&2798ws_blank_line(patch +1, plen, ws_rule))2799 added_blank_line =1;2800break;2801case'@':case'\\':2802/* Ignore it, we already handled it */2803break;2804default:2805if(state->apply_verbosely)2806error(_("invalid start of line: '%c'"), first);2807 applied_pos = -1;2808goto out;2809}2810if(added_blank_line) {2811if(!new_blank_lines_at_end)2812 found_new_blank_lines_at_end = hunk_linenr;2813 new_blank_lines_at_end++;2814}2815else if(is_blank_context)2816;2817else2818 new_blank_lines_at_end =0;2819 patch += len;2820 size -= len;2821 hunk_linenr++;2822}2823if(inaccurate_eof &&2824 old > oldlines && old[-1] =='\n'&&2825 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2826 old--;2827strbuf_setlen(&newlines, newlines.len -1);2828}28292830 leading = frag->leading;2831 trailing = frag->trailing;28322833/*2834 * A hunk to change lines at the beginning would begin with2835 * @@ -1,L +N,M @@2836 * but we need to be careful. -U0 that inserts before the second2837 * line also has this pattern.2838 *2839 * And a hunk to add to an empty file would begin with2840 * @@ -0,0 +N,M @@2841 *2842 * In other words, a hunk that is (frag->oldpos <= 1) with or2843 * without leading context must match at the beginning.2844 */2845 match_beginning = (!frag->oldpos ||2846(frag->oldpos ==1&& !state->unidiff_zero));28472848/*2849 * A hunk without trailing lines must match at the end.2850 * However, we simply cannot tell if a hunk must match end2851 * from the lack of trailing lines if the patch was generated2852 * with unidiff without any context.2853 */2854 match_end = !state->unidiff_zero && !trailing;28552856 pos = frag->newpos ? (frag->newpos -1) :0;2857 preimage.buf = oldlines;2858 preimage.len = old - oldlines;2859 postimage.buf = newlines.buf;2860 postimage.len = newlines.len;2861 preimage.line = preimage.line_allocated;2862 postimage.line = postimage.line_allocated;28632864for(;;) {28652866 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2867 ws_rule, match_beginning, match_end);28682869if(applied_pos >=0)2870break;28712872/* Am I at my context limits? */2873if((leading <= state->p_context) && (trailing <= state->p_context))2874break;2875if(match_beginning || match_end) {2876 match_beginning = match_end =0;2877continue;2878}28792880/*2881 * Reduce the number of context lines; reduce both2882 * leading and trailing if they are equal otherwise2883 * just reduce the larger context.2884 */2885if(leading >= trailing) {2886remove_first_line(&preimage);2887remove_first_line(&postimage);2888 pos--;2889 leading--;2890}2891if(trailing > leading) {2892remove_last_line(&preimage);2893remove_last_line(&postimage);2894 trailing--;2895}2896}28972898if(applied_pos >=0) {2899if(new_blank_lines_at_end &&2900 preimage.nr + applied_pos >= img->nr &&2901(ws_rule & WS_BLANK_AT_EOF) &&2902 state->ws_error_action != nowarn_ws_error) {2903record_ws_error(state, WS_BLANK_AT_EOF,"+",1,2904 found_new_blank_lines_at_end);2905if(state->ws_error_action == correct_ws_error) {2906while(new_blank_lines_at_end--)2907remove_last_line(&postimage);2908}2909/*2910 * We would want to prevent write_out_results()2911 * from taking place in apply_patch() that follows2912 * the callchain led us here, which is:2913 * apply_patch->check_patch_list->check_patch->2914 * apply_data->apply_fragments->apply_one_fragment2915 */2916if(state->ws_error_action == die_on_ws_error)2917 state->apply =0;2918}29192920if(state->apply_verbosely && applied_pos != pos) {2921int offset = applied_pos - pos;2922if(state->apply_in_reverse)2923 offset =0- offset;2924fprintf_ln(stderr,2925Q_("Hunk #%dsucceeded at%d(offset%dline).",2926"Hunk #%dsucceeded at%d(offset%dlines).",2927 offset),2928 nth_fragment, applied_pos +1, offset);2929}29302931/*2932 * Warn if it was necessary to reduce the number2933 * of context lines.2934 */2935if((leading != frag->leading) ||2936(trailing != frag->trailing))2937fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"2938" to apply fragment at%d"),2939 leading, trailing, applied_pos+1);2940update_image(state, img, applied_pos, &preimage, &postimage);2941}else{2942if(state->apply_verbosely)2943error(_("while searching for:\n%.*s"),2944(int)(old - oldlines), oldlines);2945}29462947out:2948free(oldlines);2949strbuf_release(&newlines);2950free(preimage.line_allocated);2951free(postimage.line_allocated);29522953return(applied_pos <0);2954}29552956static intapply_binary_fragment(struct apply_state *state,2957struct image *img,2958struct patch *patch)2959{2960struct fragment *fragment = patch->fragments;2961unsigned long len;2962void*dst;29632964if(!fragment)2965returnerror(_("missing binary patch data for '%s'"),2966 patch->new_name ?2967 patch->new_name :2968 patch->old_name);29692970/* Binary patch is irreversible without the optional second hunk */2971if(state->apply_in_reverse) {2972if(!fragment->next)2973returnerror("cannot reverse-apply a binary patch "2974"without the reverse hunk to '%s'",2975 patch->new_name2976? patch->new_name : patch->old_name);2977 fragment = fragment->next;2978}2979switch(fragment->binary_patch_method) {2980case BINARY_DELTA_DEFLATED:2981 dst =patch_delta(img->buf, img->len, fragment->patch,2982 fragment->size, &len);2983if(!dst)2984return-1;2985clear_image(img);2986 img->buf = dst;2987 img->len = len;2988return0;2989case BINARY_LITERAL_DEFLATED:2990clear_image(img);2991 img->len = fragment->size;2992 img->buf =xmemdupz(fragment->patch, img->len);2993return0;2994}2995return-1;2996}29972998/*2999 * Replace "img" with the result of applying the binary patch.3000 * The binary patch data itself in patch->fragment is still kept3001 * but the preimage prepared by the caller in "img" is freed here3002 * or in the helper function apply_binary_fragment() this calls.3003 */3004static intapply_binary(struct apply_state *state,3005struct image *img,3006struct patch *patch)3007{3008const char*name = patch->old_name ? patch->old_name : patch->new_name;3009unsigned char sha1[20];30103011/*3012 * For safety, we require patch index line to contain3013 * full 40-byte textual SHA1 for old and new, at least for now.3014 */3015if(strlen(patch->old_sha1_prefix) !=40||3016strlen(patch->new_sha1_prefix) !=40||3017get_sha1_hex(patch->old_sha1_prefix, sha1) ||3018get_sha1_hex(patch->new_sha1_prefix, sha1))3019returnerror("cannot apply binary patch to '%s' "3020"without full index line", name);30213022if(patch->old_name) {3023/*3024 * See if the old one matches what the patch3025 * applies to.3026 */3027hash_sha1_file(img->buf, img->len, blob_type, sha1);3028if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3029returnerror("the patch applies to '%s' (%s), "3030"which does not match the "3031"current contents.",3032 name,sha1_to_hex(sha1));3033}3034else{3035/* Otherwise, the old one must be empty. */3036if(img->len)3037returnerror("the patch applies to an empty "3038"'%s' but it is not empty", name);3039}30403041get_sha1_hex(patch->new_sha1_prefix, sha1);3042if(is_null_sha1(sha1)) {3043clear_image(img);3044return0;/* deletion patch */3045}30463047if(has_sha1_file(sha1)) {3048/* We already have the postimage */3049enum object_type type;3050unsigned long size;3051char*result;30523053 result =read_sha1_file(sha1, &type, &size);3054if(!result)3055returnerror("the necessary postimage%sfor "3056"'%s' cannot be read",3057 patch->new_sha1_prefix, name);3058clear_image(img);3059 img->buf = result;3060 img->len = size;3061}else{3062/*3063 * We have verified buf matches the preimage;3064 * apply the patch data to it, which is stored3065 * in the patch->fragments->{patch,size}.3066 */3067if(apply_binary_fragment(state, img, patch))3068returnerror(_("binary patch does not apply to '%s'"),3069 name);30703071/* verify that the result matches */3072hash_sha1_file(img->buf, img->len, blob_type, sha1);3073if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3074returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3075 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3076}30773078return0;3079}30803081static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3082{3083struct fragment *frag = patch->fragments;3084const char*name = patch->old_name ? patch->old_name : patch->new_name;3085unsigned ws_rule = patch->ws_rule;3086unsigned inaccurate_eof = patch->inaccurate_eof;3087int nth =0;30883089if(patch->is_binary)3090returnapply_binary(state, img, patch);30913092while(frag) {3093 nth++;3094if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3095error(_("patch failed:%s:%ld"), name, frag->oldpos);3096if(!state->apply_with_reject)3097return-1;3098 frag->rejected =1;3099}3100 frag = frag->next;3101}3102return0;3103}31043105static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3106{3107if(S_ISGITLINK(mode)) {3108strbuf_grow(buf,100);3109strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3110}else{3111enum object_type type;3112unsigned long sz;3113char*result;31143115 result =read_sha1_file(sha1, &type, &sz);3116if(!result)3117return-1;3118/* XXX read_sha1_file NUL-terminates */3119strbuf_attach(buf, result, sz, sz +1);3120}3121return0;3122}31233124static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3125{3126if(!ce)3127return0;3128returnread_blob_object(buf, ce->sha1, ce->ce_mode);3129}31303131static struct patch *in_fn_table(struct apply_state *state,const char*name)3132{3133struct string_list_item *item;31343135if(name == NULL)3136return NULL;31373138 item =string_list_lookup(&state->fn_table, name);3139if(item != NULL)3140return(struct patch *)item->util;31413142return NULL;3143}31443145/*3146 * item->util in the filename table records the status of the path.3147 * Usually it points at a patch (whose result records the contents3148 * of it after applying it), but it could be PATH_WAS_DELETED for a3149 * path that a previously applied patch has already removed, or3150 * PATH_TO_BE_DELETED for a path that a later patch would remove.3151 *3152 * The latter is needed to deal with a case where two paths A and B3153 * are swapped by first renaming A to B and then renaming B to A;3154 * moving A to B should not be prevented due to presence of B as we3155 * will remove it in a later patch.3156 */3157#define PATH_TO_BE_DELETED ((struct patch *) -2)3158#define PATH_WAS_DELETED ((struct patch *) -1)31593160static intto_be_deleted(struct patch *patch)3161{3162return patch == PATH_TO_BE_DELETED;3163}31643165static intwas_deleted(struct patch *patch)3166{3167return patch == PATH_WAS_DELETED;3168}31693170static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3171{3172struct string_list_item *item;31733174/*3175 * Always add new_name unless patch is a deletion3176 * This should cover the cases for normal diffs,3177 * file creations and copies3178 */3179if(patch->new_name != NULL) {3180 item =string_list_insert(&state->fn_table, patch->new_name);3181 item->util = patch;3182}31833184/*3185 * store a failure on rename/deletion cases because3186 * later chunks shouldn't patch old names3187 */3188if((patch->new_name == NULL) || (patch->is_rename)) {3189 item =string_list_insert(&state->fn_table, patch->old_name);3190 item->util = PATH_WAS_DELETED;3191}3192}31933194static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3195{3196/*3197 * store information about incoming file deletion3198 */3199while(patch) {3200if((patch->new_name == NULL) || (patch->is_rename)) {3201struct string_list_item *item;3202 item =string_list_insert(&state->fn_table, patch->old_name);3203 item->util = PATH_TO_BE_DELETED;3204}3205 patch = patch->next;3206}3207}32083209static intcheckout_target(struct index_state *istate,3210struct cache_entry *ce,struct stat *st)3211{3212struct checkout costate;32133214memset(&costate,0,sizeof(costate));3215 costate.base_dir ="";3216 costate.refresh_cache =1;3217 costate.istate = istate;3218if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3219returnerror(_("cannot checkout%s"), ce->name);3220return0;3221}32223223static struct patch *previous_patch(struct apply_state *state,3224struct patch *patch,3225int*gone)3226{3227struct patch *previous;32283229*gone =0;3230if(patch->is_copy || patch->is_rename)3231return NULL;/* "git" patches do not depend on the order */32323233 previous =in_fn_table(state, patch->old_name);3234if(!previous)3235return NULL;32363237if(to_be_deleted(previous))3238return NULL;/* the deletion hasn't happened yet */32393240if(was_deleted(previous))3241*gone =1;32423243return previous;3244}32453246static intverify_index_match(const struct cache_entry *ce,struct stat *st)3247{3248if(S_ISGITLINK(ce->ce_mode)) {3249if(!S_ISDIR(st->st_mode))3250return-1;3251return0;3252}3253returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3254}32553256#define SUBMODULE_PATCH_WITHOUT_INDEX 132573258static intload_patch_target(struct apply_state *state,3259struct strbuf *buf,3260const struct cache_entry *ce,3261struct stat *st,3262const char*name,3263unsigned expected_mode)3264{3265if(state->cached || state->check_index) {3266if(read_file_or_gitlink(ce, buf))3267returnerror(_("failed to read%s"), name);3268}else if(name) {3269if(S_ISGITLINK(expected_mode)) {3270if(ce)3271returnread_file_or_gitlink(ce, buf);3272else3273return SUBMODULE_PATCH_WITHOUT_INDEX;3274}else if(has_symlink_leading_path(name,strlen(name))) {3275returnerror(_("reading from '%s' beyond a symbolic link"), name);3276}else{3277if(read_old_data(st, name, buf))3278returnerror(_("failed to read%s"), name);3279}3280}3281return0;3282}32833284/*3285 * We are about to apply "patch"; populate the "image" with the3286 * current version we have, from the working tree or from the index,3287 * depending on the situation e.g. --cached/--index. If we are3288 * applying a non-git patch that incrementally updates the tree,3289 * we read from the result of a previous diff.3290 */3291static intload_preimage(struct apply_state *state,3292struct image *image,3293struct patch *patch,struct stat *st,3294const struct cache_entry *ce)3295{3296struct strbuf buf = STRBUF_INIT;3297size_t len;3298char*img;3299struct patch *previous;3300int status;33013302 previous =previous_patch(state, patch, &status);3303if(status)3304returnerror(_("path%shas been renamed/deleted"),3305 patch->old_name);3306if(previous) {3307/* We have a patched copy in memory; use that. */3308strbuf_add(&buf, previous->result, previous->resultsize);3309}else{3310 status =load_patch_target(state, &buf, ce, st,3311 patch->old_name, patch->old_mode);3312if(status <0)3313return status;3314else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3315/*3316 * There is no way to apply subproject3317 * patch without looking at the index.3318 * NEEDSWORK: shouldn't this be flagged3319 * as an error???3320 */3321free_fragment_list(patch->fragments);3322 patch->fragments = NULL;3323}else if(status) {3324returnerror(_("failed to read%s"), patch->old_name);3325}3326}33273328 img =strbuf_detach(&buf, &len);3329prepare_image(image, img, len, !patch->is_binary);3330return0;3331}33323333static intthree_way_merge(struct image *image,3334char*path,3335const unsigned char*base,3336const unsigned char*ours,3337const unsigned char*theirs)3338{3339 mmfile_t base_file, our_file, their_file;3340 mmbuffer_t result = { NULL };3341int status;33423343read_mmblob(&base_file, base);3344read_mmblob(&our_file, ours);3345read_mmblob(&their_file, theirs);3346 status =ll_merge(&result, path,3347&base_file,"base",3348&our_file,"ours",3349&their_file,"theirs", NULL);3350free(base_file.ptr);3351free(our_file.ptr);3352free(their_file.ptr);3353if(status <0|| !result.ptr) {3354free(result.ptr);3355return-1;3356}3357clear_image(image);3358 image->buf = result.ptr;3359 image->len = result.size;33603361return status;3362}33633364/*3365 * When directly falling back to add/add three-way merge, we read from3366 * the current contents of the new_name. In no cases other than that3367 * this function will be called.3368 */3369static intload_current(struct apply_state *state,3370struct image *image,3371struct patch *patch)3372{3373struct strbuf buf = STRBUF_INIT;3374int status, pos;3375size_t len;3376char*img;3377struct stat st;3378struct cache_entry *ce;3379char*name = patch->new_name;3380unsigned mode = patch->new_mode;33813382if(!patch->is_new)3383die("BUG: patch to%sis not a creation", patch->old_name);33843385 pos =cache_name_pos(name,strlen(name));3386if(pos <0)3387returnerror(_("%s: does not exist in index"), name);3388 ce = active_cache[pos];3389if(lstat(name, &st)) {3390if(errno != ENOENT)3391returnerror(_("%s:%s"), name,strerror(errno));3392if(checkout_target(&the_index, ce, &st))3393return-1;3394}3395if(verify_index_match(ce, &st))3396returnerror(_("%s: does not match index"), name);33973398 status =load_patch_target(state, &buf, ce, &st, name, mode);3399if(status <0)3400return status;3401else if(status)3402return-1;3403 img =strbuf_detach(&buf, &len);3404prepare_image(image, img, len, !patch->is_binary);3405return0;3406}34073408static inttry_threeway(struct apply_state *state,3409struct image *image,3410struct patch *patch,3411struct stat *st,3412const struct cache_entry *ce)3413{3414unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3415struct strbuf buf = STRBUF_INIT;3416size_t len;3417int status;3418char*img;3419struct image tmp_image;34203421/* No point falling back to 3-way merge in these cases */3422if(patch->is_delete ||3423S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3424return-1;34253426/* Preimage the patch was prepared for */3427if(patch->is_new)3428write_sha1_file("",0, blob_type, pre_sha1);3429else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3430read_blob_object(&buf, pre_sha1, patch->old_mode))3431returnerror("repository lacks the necessary blob to fall back on 3-way merge.");34323433fprintf(stderr,"Falling back to three-way merge...\n");34343435 img =strbuf_detach(&buf, &len);3436prepare_image(&tmp_image, img, len,1);3437/* Apply the patch to get the post image */3438if(apply_fragments(state, &tmp_image, patch) <0) {3439clear_image(&tmp_image);3440return-1;3441}3442/* post_sha1[] is theirs */3443write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3444clear_image(&tmp_image);34453446/* our_sha1[] is ours */3447if(patch->is_new) {3448if(load_current(state, &tmp_image, patch))3449returnerror("cannot read the current contents of '%s'",3450 patch->new_name);3451}else{3452if(load_preimage(state, &tmp_image, patch, st, ce))3453returnerror("cannot read the current contents of '%s'",3454 patch->old_name);3455}3456write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3457clear_image(&tmp_image);34583459/* in-core three-way merge between post and our using pre as base */3460 status =three_way_merge(image, patch->new_name,3461 pre_sha1, our_sha1, post_sha1);3462if(status <0) {3463fprintf(stderr,"Failed to fall back on three-way merge...\n");3464return status;3465}34663467if(status) {3468 patch->conflicted_threeway =1;3469if(patch->is_new)3470oidclr(&patch->threeway_stage[0]);3471else3472hashcpy(patch->threeway_stage[0].hash, pre_sha1);3473hashcpy(patch->threeway_stage[1].hash, our_sha1);3474hashcpy(patch->threeway_stage[2].hash, post_sha1);3475fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3476}else{3477fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3478}3479return0;3480}34813482static intapply_data(struct apply_state *state,struct patch *patch,3483struct stat *st,const struct cache_entry *ce)3484{3485struct image image;34863487if(load_preimage(state, &image, patch, st, ce) <0)3488return-1;34893490if(patch->direct_to_threeway ||3491apply_fragments(state, &image, patch) <0) {3492/* Note: with --reject, apply_fragments() returns 0 */3493if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3494return-1;3495}3496 patch->result = image.buf;3497 patch->resultsize = image.len;3498add_to_fn_table(state, patch);3499free(image.line_allocated);35003501if(0< patch->is_delete && patch->resultsize)3502returnerror(_("removal patch leaves file contents"));35033504return0;3505}35063507/*3508 * If "patch" that we are looking at modifies or deletes what we have,3509 * we would want it not to lose any local modification we have, either3510 * in the working tree or in the index.3511 *3512 * This also decides if a non-git patch is a creation patch or a3513 * modification to an existing empty file. We do not check the state3514 * of the current tree for a creation patch in this function; the caller3515 * check_patch() separately makes sure (and errors out otherwise) that3516 * the path the patch creates does not exist in the current tree.3517 */3518static intcheck_preimage(struct apply_state *state,3519struct patch *patch,3520struct cache_entry **ce,3521struct stat *st)3522{3523const char*old_name = patch->old_name;3524struct patch *previous = NULL;3525int stat_ret =0, status;3526unsigned st_mode =0;35273528if(!old_name)3529return0;35303531assert(patch->is_new <=0);3532 previous =previous_patch(state, patch, &status);35333534if(status)3535returnerror(_("path%shas been renamed/deleted"), old_name);3536if(previous) {3537 st_mode = previous->new_mode;3538}else if(!state->cached) {3539 stat_ret =lstat(old_name, st);3540if(stat_ret && errno != ENOENT)3541returnerror(_("%s:%s"), old_name,strerror(errno));3542}35433544if(state->check_index && !previous) {3545int pos =cache_name_pos(old_name,strlen(old_name));3546if(pos <0) {3547if(patch->is_new <0)3548goto is_new;3549returnerror(_("%s: does not exist in index"), old_name);3550}3551*ce = active_cache[pos];3552if(stat_ret <0) {3553if(checkout_target(&the_index, *ce, st))3554return-1;3555}3556if(!state->cached &&verify_index_match(*ce, st))3557returnerror(_("%s: does not match index"), old_name);3558if(state->cached)3559 st_mode = (*ce)->ce_mode;3560}else if(stat_ret <0) {3561if(patch->is_new <0)3562goto is_new;3563returnerror(_("%s:%s"), old_name,strerror(errno));3564}35653566if(!state->cached && !previous)3567 st_mode =ce_mode_from_stat(*ce, st->st_mode);35683569if(patch->is_new <0)3570 patch->is_new =0;3571if(!patch->old_mode)3572 patch->old_mode = st_mode;3573if((st_mode ^ patch->old_mode) & S_IFMT)3574returnerror(_("%s: wrong type"), old_name);3575if(st_mode != patch->old_mode)3576warning(_("%shas type%o, expected%o"),3577 old_name, st_mode, patch->old_mode);3578if(!patch->new_mode && !patch->is_delete)3579 patch->new_mode = st_mode;3580return0;35813582 is_new:3583 patch->is_new =1;3584 patch->is_delete =0;3585free(patch->old_name);3586 patch->old_name = NULL;3587return0;3588}358935903591#define EXISTS_IN_INDEX 13592#define EXISTS_IN_WORKTREE 235933594static intcheck_to_create(struct apply_state *state,3595const char*new_name,3596int ok_if_exists)3597{3598struct stat nst;35993600if(state->check_index &&3601cache_name_pos(new_name,strlen(new_name)) >=0&&3602!ok_if_exists)3603return EXISTS_IN_INDEX;3604if(state->cached)3605return0;36063607if(!lstat(new_name, &nst)) {3608if(S_ISDIR(nst.st_mode) || ok_if_exists)3609return0;3610/*3611 * A leading component of new_name might be a symlink3612 * that is going to be removed with this patch, but3613 * still pointing at somewhere that has the path.3614 * In such a case, path "new_name" does not exist as3615 * far as git is concerned.3616 */3617if(has_symlink_leading_path(new_name,strlen(new_name)))3618return0;36193620return EXISTS_IN_WORKTREE;3621}else if((errno != ENOENT) && (errno != ENOTDIR)) {3622returnerror("%s:%s", new_name,strerror(errno));3623}3624return0;3625}36263627static uintptr_tregister_symlink_changes(struct apply_state *state,3628const char*path,3629uintptr_t what)3630{3631struct string_list_item *ent;36323633 ent =string_list_lookup(&state->symlink_changes, path);3634if(!ent) {3635 ent =string_list_insert(&state->symlink_changes, path);3636 ent->util = (void*)0;3637}3638 ent->util = (void*)(what | ((uintptr_t)ent->util));3639return(uintptr_t)ent->util;3640}36413642static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3643{3644struct string_list_item *ent;36453646 ent =string_list_lookup(&state->symlink_changes, path);3647if(!ent)3648return0;3649return(uintptr_t)ent->util;3650}36513652static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3653{3654for( ; patch; patch = patch->next) {3655if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3656(patch->is_rename || patch->is_delete))3657/* the symlink at patch->old_name is removed */3658register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);36593660if(patch->new_name &&S_ISLNK(patch->new_mode))3661/* the symlink at patch->new_name is created or remains */3662register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3663}3664}36653666static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3667{3668do{3669unsigned int change;36703671while(--name->len && name->buf[name->len] !='/')3672;/* scan backwards */3673if(!name->len)3674break;3675 name->buf[name->len] ='\0';3676 change =check_symlink_changes(state, name->buf);3677if(change & APPLY_SYMLINK_IN_RESULT)3678return1;3679if(change & APPLY_SYMLINK_GOES_AWAY)3680/*3681 * This cannot be "return 0", because we may3682 * see a new one created at a higher level.3683 */3684continue;36853686/* otherwise, check the preimage */3687if(state->check_index) {3688struct cache_entry *ce;36893690 ce =cache_file_exists(name->buf, name->len, ignore_case);3691if(ce &&S_ISLNK(ce->ce_mode))3692return1;3693}else{3694struct stat st;3695if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3696return1;3697}3698}while(1);3699return0;3700}37013702static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3703{3704int ret;3705struct strbuf name = STRBUF_INIT;37063707assert(*name_ !='\0');3708strbuf_addstr(&name, name_);3709 ret =path_is_beyond_symlink_1(state, &name);3710strbuf_release(&name);37113712return ret;3713}37143715static voiddie_on_unsafe_path(struct patch *patch)3716{3717const char*old_name = NULL;3718const char*new_name = NULL;3719if(patch->is_delete)3720 old_name = patch->old_name;3721else if(!patch->is_new && !patch->is_copy)3722 old_name = patch->old_name;3723if(!patch->is_delete)3724 new_name = patch->new_name;37253726if(old_name && !verify_path(old_name))3727die(_("invalid path '%s'"), old_name);3728if(new_name && !verify_path(new_name))3729die(_("invalid path '%s'"), new_name);3730}37313732/*3733 * Check and apply the patch in-core; leave the result in patch->result3734 * for the caller to write it out to the final destination.3735 */3736static intcheck_patch(struct apply_state *state,struct patch *patch)3737{3738struct stat st;3739const char*old_name = patch->old_name;3740const char*new_name = patch->new_name;3741const char*name = old_name ? old_name : new_name;3742struct cache_entry *ce = NULL;3743struct patch *tpatch;3744int ok_if_exists;3745int status;37463747 patch->rejected =1;/* we will drop this after we succeed */37483749 status =check_preimage(state, patch, &ce, &st);3750if(status)3751return status;3752 old_name = patch->old_name;37533754/*3755 * A type-change diff is always split into a patch to delete3756 * old, immediately followed by a patch to create new (see3757 * diff.c::run_diff()); in such a case it is Ok that the entry3758 * to be deleted by the previous patch is still in the working3759 * tree and in the index.3760 *3761 * A patch to swap-rename between A and B would first rename A3762 * to B and then rename B to A. While applying the first one,3763 * the presence of B should not stop A from getting renamed to3764 * B; ask to_be_deleted() about the later rename. Removal of3765 * B and rename from A to B is handled the same way by asking3766 * was_deleted().3767 */3768if((tpatch =in_fn_table(state, new_name)) &&3769(was_deleted(tpatch) ||to_be_deleted(tpatch)))3770 ok_if_exists =1;3771else3772 ok_if_exists =0;37733774if(new_name &&3775((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3776int err =check_to_create(state, new_name, ok_if_exists);37773778if(err && state->threeway) {3779 patch->direct_to_threeway =1;3780}else switch(err) {3781case0:3782break;/* happy */3783case EXISTS_IN_INDEX:3784returnerror(_("%s: already exists in index"), new_name);3785break;3786case EXISTS_IN_WORKTREE:3787returnerror(_("%s: already exists in working directory"),3788 new_name);3789default:3790return err;3791}37923793if(!patch->new_mode) {3794if(0< patch->is_new)3795 patch->new_mode = S_IFREG |0644;3796else3797 patch->new_mode = patch->old_mode;3798}3799}38003801if(new_name && old_name) {3802int same = !strcmp(old_name, new_name);3803if(!patch->new_mode)3804 patch->new_mode = patch->old_mode;3805if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3806if(same)3807returnerror(_("new mode (%o) of%sdoes not "3808"match old mode (%o)"),3809 patch->new_mode, new_name,3810 patch->old_mode);3811else3812returnerror(_("new mode (%o) of%sdoes not "3813"match old mode (%o) of%s"),3814 patch->new_mode, new_name,3815 patch->old_mode, old_name);3816}3817}38183819if(!state->unsafe_paths)3820die_on_unsafe_path(patch);38213822/*3823 * An attempt to read from or delete a path that is beyond a3824 * symbolic link will be prevented by load_patch_target() that3825 * is called at the beginning of apply_data() so we do not3826 * have to worry about a patch marked with "is_delete" bit3827 * here. We however need to make sure that the patch result3828 * is not deposited to a path that is beyond a symbolic link3829 * here.3830 */3831if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3832returnerror(_("affected file '%s' is beyond a symbolic link"),3833 patch->new_name);38343835if(apply_data(state, patch, &st, ce) <0)3836returnerror(_("%s: patch does not apply"), name);3837 patch->rejected =0;3838return0;3839}38403841static intcheck_patch_list(struct apply_state *state,struct patch *patch)3842{3843int err =0;38443845prepare_symlink_changes(state, patch);3846prepare_fn_table(state, patch);3847while(patch) {3848if(state->apply_verbosely)3849say_patch_name(stderr,3850_("Checking patch%s..."), patch);3851 err |=check_patch(state, patch);3852 patch = patch->next;3853}3854return err;3855}38563857/* This function tries to read the sha1 from the current index */3858static intget_current_sha1(const char*path,unsigned char*sha1)3859{3860int pos;38613862if(read_cache() <0)3863return-1;3864 pos =cache_name_pos(path,strlen(path));3865if(pos <0)3866return-1;3867hashcpy(sha1, active_cache[pos]->sha1);3868return0;3869}38703871static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3872{3873/*3874 * A usable gitlink patch has only one fragment (hunk) that looks like:3875 * @@ -1 +1 @@3876 * -Subproject commit <old sha1>3877 * +Subproject commit <new sha1>3878 * or3879 * @@ -1 +0,0 @@3880 * -Subproject commit <old sha1>3881 * for a removal patch.3882 */3883struct fragment *hunk = p->fragments;3884static const char heading[] ="-Subproject commit ";3885char*preimage;38863887if(/* does the patch have only one hunk? */3888 hunk && !hunk->next &&3889/* is its preimage one line? */3890 hunk->oldpos ==1&& hunk->oldlines ==1&&3891/* does preimage begin with the heading? */3892(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&3893starts_with(++preimage, heading) &&3894/* does it record full SHA-1? */3895!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&3896 preimage[sizeof(heading) +40-1] =='\n'&&3897/* does the abbreviated name on the index line agree with it? */3898starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))3899return0;/* it all looks fine */39003901/* we may have full object name on the index line */3902returnget_sha1_hex(p->old_sha1_prefix, sha1);3903}39043905/* Build an index that contains the just the files needed for a 3way merge */3906static voidbuild_fake_ancestor(struct patch *list,const char*filename)3907{3908struct patch *patch;3909struct index_state result = { NULL };3910static struct lock_file lock;39113912/* Once we start supporting the reverse patch, it may be3913 * worth showing the new sha1 prefix, but until then...3914 */3915for(patch = list; patch; patch = patch->next) {3916unsigned char sha1[20];3917struct cache_entry *ce;3918const char*name;39193920 name = patch->old_name ? patch->old_name : patch->new_name;3921if(0< patch->is_new)3922continue;39233924if(S_ISGITLINK(patch->old_mode)) {3925if(!preimage_sha1_in_gitlink_patch(patch, sha1))3926;/* ok, the textual part looks sane */3927else3928die("sha1 information is lacking or useless for submodule%s",3929 name);3930}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {3931;/* ok */3932}else if(!patch->lines_added && !patch->lines_deleted) {3933/* mode-only change: update the current */3934if(get_current_sha1(patch->old_name, sha1))3935die("mode change for%s, which is not "3936"in current HEAD", name);3937}else3938die("sha1 information is lacking or useless "3939"(%s).", name);39403941 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);3942if(!ce)3943die(_("make_cache_entry failed for path '%s'"), name);3944if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3945die("Could not add%sto temporary index", name);3946}39473948hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);3949if(write_locked_index(&result, &lock, COMMIT_LOCK))3950die("Could not write temporary index to%s", filename);39513952discard_index(&result);3953}39543955static voidstat_patch_list(struct apply_state *state,struct patch *patch)3956{3957int files, adds, dels;39583959for(files = adds = dels =0; patch ; patch = patch->next) {3960 files++;3961 adds += patch->lines_added;3962 dels += patch->lines_deleted;3963show_stats(state, patch);3964}39653966print_stat_summary(stdout, files, adds, dels);3967}39683969static voidnumstat_patch_list(struct apply_state *state,3970struct patch *patch)3971{3972for( ; patch; patch = patch->next) {3973const char*name;3974 name = patch->new_name ? patch->new_name : patch->old_name;3975if(patch->is_binary)3976printf("-\t-\t");3977else3978printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3979write_name_quoted(name, stdout, state->line_termination);3980}3981}39823983static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)3984{3985if(mode)3986printf("%smode%06o%s\n", newdelete, mode, name);3987else3988printf("%s %s\n", newdelete, name);3989}39903991static voidshow_mode_change(struct patch *p,int show_name)3992{3993if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3994if(show_name)3995printf(" mode change%06o =>%06o%s\n",3996 p->old_mode, p->new_mode, p->new_name);3997else3998printf(" mode change%06o =>%06o\n",3999 p->old_mode, p->new_mode);4000}4001}40024003static voidshow_rename_copy(struct patch *p)4004{4005const char*renamecopy = p->is_rename ?"rename":"copy";4006const char*old, *new;40074008/* Find common prefix */4009 old = p->old_name;4010new= p->new_name;4011while(1) {4012const char*slash_old, *slash_new;4013 slash_old =strchr(old,'/');4014 slash_new =strchr(new,'/');4015if(!slash_old ||4016!slash_new ||4017 slash_old - old != slash_new -new||4018memcmp(old,new, slash_new -new))4019break;4020 old = slash_old +1;4021new= slash_new +1;4022}4023/* p->old_name thru old is the common prefix, and old and new4024 * through the end of names are renames4025 */4026if(old != p->old_name)4027printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4028(int)(old - p->old_name), p->old_name,4029 old,new, p->score);4030else4031printf("%s %s=>%s(%d%%)\n", renamecopy,4032 p->old_name, p->new_name, p->score);4033show_mode_change(p,0);4034}40354036static voidsummary_patch_list(struct patch *patch)4037{4038struct patch *p;40394040for(p = patch; p; p = p->next) {4041if(p->is_new)4042show_file_mode_name("create", p->new_mode, p->new_name);4043else if(p->is_delete)4044show_file_mode_name("delete", p->old_mode, p->old_name);4045else{4046if(p->is_rename || p->is_copy)4047show_rename_copy(p);4048else{4049if(p->score) {4050printf(" rewrite%s(%d%%)\n",4051 p->new_name, p->score);4052show_mode_change(p,0);4053}4054else4055show_mode_change(p,1);4056}4057}4058}4059}40604061static voidpatch_stats(struct apply_state *state,struct patch *patch)4062{4063int lines = patch->lines_added + patch->lines_deleted;40644065if(lines > state->max_change)4066 state->max_change = lines;4067if(patch->old_name) {4068int len =quote_c_style(patch->old_name, NULL, NULL,0);4069if(!len)4070 len =strlen(patch->old_name);4071if(len > state->max_len)4072 state->max_len = len;4073}4074if(patch->new_name) {4075int len =quote_c_style(patch->new_name, NULL, NULL,0);4076if(!len)4077 len =strlen(patch->new_name);4078if(len > state->max_len)4079 state->max_len = len;4080}4081}40824083static voidremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4084{4085if(state->update_index) {4086if(remove_file_from_cache(patch->old_name) <0)4087die(_("unable to remove%sfrom index"), patch->old_name);4088}4089if(!state->cached) {4090if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4091remove_path(patch->old_name);4092}4093}4094}40954096static voidadd_index_file(struct apply_state *state,4097const char*path,4098unsigned mode,4099void*buf,4100unsigned long size)4101{4102struct stat st;4103struct cache_entry *ce;4104int namelen =strlen(path);4105unsigned ce_size =cache_entry_size(namelen);41064107if(!state->update_index)4108return;41094110 ce =xcalloc(1, ce_size);4111memcpy(ce->name, path, namelen);4112 ce->ce_mode =create_ce_mode(mode);4113 ce->ce_flags =create_ce_flags(0);4114 ce->ce_namelen = namelen;4115if(S_ISGITLINK(mode)) {4116const char*s;41174118if(!skip_prefix(buf,"Subproject commit ", &s) ||4119get_sha1_hex(s, ce->sha1))4120die(_("corrupt patch for submodule%s"), path);4121}else{4122if(!state->cached) {4123if(lstat(path, &st) <0)4124die_errno(_("unable to stat newly created file '%s'"),4125 path);4126fill_stat_cache_info(ce, &st);4127}4128if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)4129die(_("unable to create backing store for newly created file%s"), path);4130}4131if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4132die(_("unable to add cache entry for%s"), path);4133}41344135static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4136{4137int fd;4138struct strbuf nbuf = STRBUF_INIT;41394140if(S_ISGITLINK(mode)) {4141struct stat st;4142if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4143return0;4144returnmkdir(path,0777);4145}41464147if(has_symlinks &&S_ISLNK(mode))4148/* Although buf:size is counted string, it also is NUL4149 * terminated.4150 */4151returnsymlink(buf, path);41524153 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4154if(fd <0)4155return-1;41564157if(convert_to_working_tree(path, buf, size, &nbuf)) {4158 size = nbuf.len;4159 buf = nbuf.buf;4160}4161write_or_die(fd, buf, size);4162strbuf_release(&nbuf);41634164if(close(fd) <0)4165die_errno(_("closing file '%s'"), path);4166return0;4167}41684169/*4170 * We optimistically assume that the directories exist,4171 * which is true 99% of the time anyway. If they don't,4172 * we create them and try again.4173 */4174static voidcreate_one_file(struct apply_state *state,4175char*path,4176unsigned mode,4177const char*buf,4178unsigned long size)4179{4180if(state->cached)4181return;4182if(!try_create_file(path, mode, buf, size))4183return;41844185if(errno == ENOENT) {4186if(safe_create_leading_directories(path))4187return;4188if(!try_create_file(path, mode, buf, size))4189return;4190}41914192if(errno == EEXIST || errno == EACCES) {4193/* We may be trying to create a file where a directory4194 * used to be.4195 */4196struct stat st;4197if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4198 errno = EEXIST;4199}42004201if(errno == EEXIST) {4202unsigned int nr =getpid();42034204for(;;) {4205char newpath[PATH_MAX];4206mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4207if(!try_create_file(newpath, mode, buf, size)) {4208if(!rename(newpath, path))4209return;4210unlink_or_warn(newpath);4211break;4212}4213if(errno != EEXIST)4214break;4215++nr;4216}4217}4218die_errno(_("unable to write file '%s' mode%o"), path, mode);4219}42204221static voidadd_conflicted_stages_file(struct apply_state *state,4222struct patch *patch)4223{4224int stage, namelen;4225unsigned ce_size, mode;4226struct cache_entry *ce;42274228if(!state->update_index)4229return;4230 namelen =strlen(patch->new_name);4231 ce_size =cache_entry_size(namelen);4232 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);42334234remove_file_from_cache(patch->new_name);4235for(stage =1; stage <4; stage++) {4236if(is_null_oid(&patch->threeway_stage[stage -1]))4237continue;4238 ce =xcalloc(1, ce_size);4239memcpy(ce->name, patch->new_name, namelen);4240 ce->ce_mode =create_ce_mode(mode);4241 ce->ce_flags =create_ce_flags(stage);4242 ce->ce_namelen = namelen;4243hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4244if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)4245die(_("unable to add cache entry for%s"), patch->new_name);4246}4247}42484249static voidcreate_file(struct apply_state *state,struct patch *patch)4250{4251char*path = patch->new_name;4252unsigned mode = patch->new_mode;4253unsigned long size = patch->resultsize;4254char*buf = patch->result;42554256if(!mode)4257 mode = S_IFREG |0644;4258create_one_file(state, path, mode, buf, size);42594260if(patch->conflicted_threeway)4261add_conflicted_stages_file(state, patch);4262else4263add_index_file(state, path, mode, buf, size);4264}42654266/* phase zero is to remove, phase one is to create */4267static voidwrite_out_one_result(struct apply_state *state,4268struct patch *patch,4269int phase)4270{4271if(patch->is_delete >0) {4272if(phase ==0)4273remove_file(state, patch,1);4274return;4275}4276if(patch->is_new >0|| patch->is_copy) {4277if(phase ==1)4278create_file(state, patch);4279return;4280}4281/*4282 * Rename or modification boils down to the same4283 * thing: remove the old, write the new4284 */4285if(phase ==0)4286remove_file(state, patch, patch->is_rename);4287if(phase ==1)4288create_file(state, patch);4289}42904291static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4292{4293FILE*rej;4294char namebuf[PATH_MAX];4295struct fragment *frag;4296int cnt =0;4297struct strbuf sb = STRBUF_INIT;42984299for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4300if(!frag->rejected)4301continue;4302 cnt++;4303}43044305if(!cnt) {4306if(state->apply_verbosely)4307say_patch_name(stderr,4308_("Applied patch%scleanly."), patch);4309return0;4310}43114312/* This should not happen, because a removal patch that leaves4313 * contents are marked "rejected" at the patch level.4314 */4315if(!patch->new_name)4316die(_("internal error"));43174318/* Say this even without --verbose */4319strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4320"Applying patch %%swith%drejects...",4321 cnt),4322 cnt);4323say_patch_name(stderr, sb.buf, patch);4324strbuf_release(&sb);43254326 cnt =strlen(patch->new_name);4327if(ARRAY_SIZE(namebuf) <= cnt +5) {4328 cnt =ARRAY_SIZE(namebuf) -5;4329warning(_("truncating .rej filename to %.*s.rej"),4330 cnt -1, patch->new_name);4331}4332memcpy(namebuf, patch->new_name, cnt);4333memcpy(namebuf + cnt,".rej",5);43344335 rej =fopen(namebuf,"w");4336if(!rej)4337returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));43384339/* Normal git tools never deal with .rej, so do not pretend4340 * this is a git patch by saying --git or giving extended4341 * headers. While at it, maybe please "kompare" that wants4342 * the trailing TAB and some garbage at the end of line ;-).4343 */4344fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4345 patch->new_name, patch->new_name);4346for(cnt =1, frag = patch->fragments;4347 frag;4348 cnt++, frag = frag->next) {4349if(!frag->rejected) {4350fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4351continue;4352}4353fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4354fprintf(rej,"%.*s", frag->size, frag->patch);4355if(frag->patch[frag->size-1] !='\n')4356fputc('\n', rej);4357}4358fclose(rej);4359return-1;4360}43614362static intwrite_out_results(struct apply_state *state,struct patch *list)4363{4364int phase;4365int errs =0;4366struct patch *l;4367struct string_list cpath = STRING_LIST_INIT_DUP;43684369for(phase =0; phase <2; phase++) {4370 l = list;4371while(l) {4372if(l->rejected)4373 errs =1;4374else{4375write_out_one_result(state, l, phase);4376if(phase ==1) {4377if(write_out_one_reject(state, l))4378 errs =1;4379if(l->conflicted_threeway) {4380string_list_append(&cpath, l->new_name);4381 errs =1;4382}4383}4384}4385 l = l->next;4386}4387}43884389if(cpath.nr) {4390struct string_list_item *item;43914392string_list_sort(&cpath);4393for_each_string_list_item(item, &cpath)4394fprintf(stderr,"U%s\n", item->string);4395string_list_clear(&cpath,0);43964397rerere(0);4398}43994400return errs;4401}44024403static struct lock_file lock_file;44044405#define INACCURATE_EOF (1<<0)4406#define RECOUNT (1<<1)44074408/*4409 * Try to apply a patch.4410 *4411 * Returns:4412 * -128 if a bad error happened (like patch unreadable)4413 * -1 if patch did not apply and user cannot deal with it4414 * 0 if the patch applied4415 * 1 if the patch did not apply but user might fix it4416 */4417static intapply_patch(struct apply_state *state,4418int fd,4419const char*filename,4420int options)4421{4422size_t offset;4423struct strbuf buf = STRBUF_INIT;/* owns the patch text */4424struct patch *list = NULL, **listp = &list;4425int skipped_patch =0;4426int res =0;44274428 state->patch_input_file = filename;4429if(read_patch_file(&buf, fd) <0)4430return-128;4431 offset =0;4432while(offset < buf.len) {4433struct patch *patch;4434int nr;44354436 patch =xcalloc(1,sizeof(*patch));4437 patch->inaccurate_eof = !!(options & INACCURATE_EOF);4438 patch->recount = !!(options & RECOUNT);4439 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4440if(nr <0) {4441free_patch(patch);4442break;4443}4444if(state->apply_in_reverse)4445reverse_patches(patch);4446if(use_patch(state, patch)) {4447patch_stats(state, patch);4448*listp = patch;4449 listp = &patch->next;4450}4451else{4452if(state->apply_verbosely)4453say_patch_name(stderr,_("Skipped patch '%s'."), patch);4454free_patch(patch);4455 skipped_patch++;4456}4457 offset += nr;4458}44594460if(!list && !skipped_patch) {4461error(_("unrecognized input"));4462 res = -128;4463goto end;4464}44654466if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4467 state->apply =0;44684469 state->update_index = state->check_index && state->apply;4470if(state->update_index && state->newfd <0)4471 state->newfd =hold_locked_index(state->lock_file,1);44724473if(state->check_index &&read_cache() <0) {4474error(_("unable to read index file"));4475 res = -128;4476goto end;4477}44784479if((state->check || state->apply) &&4480check_patch_list(state, list) <0&&4481!state->apply_with_reject) {4482 res = -1;4483goto end;4484}44854486if(state->apply &&write_out_results(state, list)) {4487/* with --3way, we still need to write the index out */4488 res = state->apply_with_reject ? -1:1;4489goto end;4490}44914492if(state->fake_ancestor)4493build_fake_ancestor(list, state->fake_ancestor);44944495if(state->diffstat)4496stat_patch_list(state, list);44974498if(state->numstat)4499numstat_patch_list(state, list);45004501if(state->summary)4502summary_patch_list(list);45034504end:4505free_patch_list(list);4506strbuf_release(&buf);4507string_list_clear(&state->fn_table,0);4508return res;4509}45104511static voidgit_apply_config(void)4512{4513git_config_get_string_const("apply.whitespace", &apply_default_whitespace);4514git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);4515git_config(git_default_config, NULL);4516}45174518static intoption_parse_exclude(const struct option *opt,4519const char*arg,int unset)4520{4521struct apply_state *state = opt->value;4522add_name_limit(state, arg,1);4523return0;4524}45254526static intoption_parse_include(const struct option *opt,4527const char*arg,int unset)4528{4529struct apply_state *state = opt->value;4530add_name_limit(state, arg,0);4531 state->has_include =1;4532return0;4533}45344535static intoption_parse_p(const struct option *opt,4536const char*arg,4537int unset)4538{4539struct apply_state *state = opt->value;4540 state->p_value =atoi(arg);4541 state->p_value_known =1;4542return0;4543}45444545static intoption_parse_space_change(const struct option *opt,4546const char*arg,int unset)4547{4548struct apply_state *state = opt->value;4549if(unset)4550 state->ws_ignore_action = ignore_ws_none;4551else4552 state->ws_ignore_action = ignore_ws_change;4553return0;4554}45554556static intoption_parse_whitespace(const struct option *opt,4557const char*arg,int unset)4558{4559struct apply_state *state = opt->value;4560 state->whitespace_option = arg;4561parse_whitespace_option(state, arg);4562return0;4563}45644565static intoption_parse_directory(const struct option *opt,4566const char*arg,int unset)4567{4568struct apply_state *state = opt->value;4569strbuf_reset(&state->root);4570strbuf_addstr(&state->root, arg);4571strbuf_complete(&state->root,'/');4572return0;4573}45744575static voidinit_apply_state(struct apply_state *state,4576const char*prefix,4577struct lock_file *lock_file)4578{4579memset(state,0,sizeof(*state));4580 state->prefix = prefix;4581 state->prefix_length = state->prefix ?strlen(state->prefix) :0;4582 state->lock_file = lock_file;4583 state->newfd = -1;4584 state->apply =1;4585 state->line_termination ='\n';4586 state->p_value =1;4587 state->p_context = UINT_MAX;4588 state->squelch_whitespace_errors =5;4589 state->ws_error_action = warn_on_ws_error;4590 state->ws_ignore_action = ignore_ws_none;4591 state->linenr =1;4592string_list_init(&state->fn_table,0);4593string_list_init(&state->limit_by_name,0);4594string_list_init(&state->symlink_changes,0);4595strbuf_init(&state->root,0);45964597git_apply_config();4598if(apply_default_whitespace)4599parse_whitespace_option(state, apply_default_whitespace);4600if(apply_default_ignorewhitespace)4601parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);4602}46034604static voidclear_apply_state(struct apply_state *state)4605{4606string_list_clear(&state->limit_by_name,0);4607string_list_clear(&state->symlink_changes,0);4608strbuf_release(&state->root);46094610/* &state->fn_table is cleared at the end of apply_patch() */4611}46124613static voidcheck_apply_state(struct apply_state *state,int force_apply)4614{4615int is_not_gitdir = !startup_info->have_repository;46164617if(state->apply_with_reject && state->threeway)4618die("--reject and --3way cannot be used together.");4619if(state->cached && state->threeway)4620die("--cached and --3way cannot be used together.");4621if(state->threeway) {4622if(is_not_gitdir)4623die(_("--3way outside a repository"));4624 state->check_index =1;4625}4626if(state->apply_with_reject)4627 state->apply = state->apply_verbosely =1;4628if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))4629 state->apply =0;4630if(state->check_index && is_not_gitdir)4631die(_("--index outside a repository"));4632if(state->cached) {4633if(is_not_gitdir)4634die(_("--cached outside a repository"));4635 state->check_index =1;4636}4637if(state->check_index)4638 state->unsafe_paths =0;4639if(!state->lock_file)4640die("BUG: state->lock_file should not be NULL");4641}46424643static intapply_all_patches(struct apply_state *state,4644int argc,4645const char**argv,4646int options)4647{4648int i;4649int res;4650int errs =0;4651int read_stdin =1;46524653for(i =0; i < argc; i++) {4654const char*arg = argv[i];4655int fd;46564657if(!strcmp(arg,"-")) {4658 res =apply_patch(state,0,"<stdin>", options);4659if(res <0)4660goto end;4661 errs |= res;4662 read_stdin =0;4663continue;4664}else if(0< state->prefix_length)4665 arg =prefix_filename(state->prefix,4666 state->prefix_length,4667 arg);46684669 fd =open(arg, O_RDONLY);4670if(fd <0)4671die_errno(_("can't open patch '%s'"), arg);4672 read_stdin =0;4673set_default_whitespace_mode(state);4674 res =apply_patch(state, fd, arg, options);4675if(res <0)4676goto end;4677 errs |= res;4678close(fd);4679}4680set_default_whitespace_mode(state);4681if(read_stdin) {4682 res =apply_patch(state,0,"<stdin>", options);4683if(res <0)4684goto end;4685 errs |= res;4686}46874688if(state->whitespace_error) {4689if(state->squelch_whitespace_errors &&4690 state->squelch_whitespace_errors < state->whitespace_error) {4691int squelched =4692 state->whitespace_error - state->squelch_whitespace_errors;4693warning(Q_("squelched%dwhitespace error",4694"squelched%dwhitespace errors",4695 squelched),4696 squelched);4697}4698if(state->ws_error_action == die_on_ws_error)4699die(Q_("%dline adds whitespace errors.",4700"%dlines add whitespace errors.",4701 state->whitespace_error),4702 state->whitespace_error);4703if(state->applied_after_fixing_ws && state->apply)4704warning("%dline%sapplied after"4705" fixing whitespace errors.",4706 state->applied_after_fixing_ws,4707 state->applied_after_fixing_ws ==1?"":"s");4708else if(state->whitespace_error)4709warning(Q_("%dline adds whitespace errors.",4710"%dlines add whitespace errors.",4711 state->whitespace_error),4712 state->whitespace_error);4713}47144715if(state->update_index) {4716if(write_locked_index(&the_index, state->lock_file, COMMIT_LOCK))4717die(_("Unable to write new index file"));4718 state->newfd = -1;4719}47204721return!!errs;47224723end:4724exit(res == -1?1:128);4725}47264727intcmd_apply(int argc,const char**argv,const char*prefix)4728{4729int force_apply =0;4730int options =0;4731int ret;4732struct apply_state state;47334734struct option builtin_apply_options[] = {4735{ OPTION_CALLBACK,0,"exclude", &state,N_("path"),4736N_("don't apply changes matching the given path"),47370, option_parse_exclude },4738{ OPTION_CALLBACK,0,"include", &state,N_("path"),4739N_("apply changes matching the given path"),47400, option_parse_include },4741{ OPTION_CALLBACK,'p', NULL, &state,N_("num"),4742N_("remove <num> leading slashes from traditional diff paths"),47430, option_parse_p },4744OPT_BOOL(0,"no-add", &state.no_add,4745N_("ignore additions made by the patch")),4746OPT_BOOL(0,"stat", &state.diffstat,4747N_("instead of applying the patch, output diffstat for the input")),4748OPT_NOOP_NOARG(0,"allow-binary-replacement"),4749OPT_NOOP_NOARG(0,"binary"),4750OPT_BOOL(0,"numstat", &state.numstat,4751N_("show number of added and deleted lines in decimal notation")),4752OPT_BOOL(0,"summary", &state.summary,4753N_("instead of applying the patch, output a summary for the input")),4754OPT_BOOL(0,"check", &state.check,4755N_("instead of applying the patch, see if the patch is applicable")),4756OPT_BOOL(0,"index", &state.check_index,4757N_("make sure the patch is applicable to the current index")),4758OPT_BOOL(0,"cached", &state.cached,4759N_("apply a patch without touching the working tree")),4760OPT_BOOL(0,"unsafe-paths", &state.unsafe_paths,4761N_("accept a patch that touches outside the working area")),4762OPT_BOOL(0,"apply", &force_apply,4763N_("also apply the patch (use with --stat/--summary/--check)")),4764OPT_BOOL('3',"3way", &state.threeway,4765N_("attempt three-way merge if a patch does not apply")),4766OPT_FILENAME(0,"build-fake-ancestor", &state.fake_ancestor,4767N_("build a temporary index based on embedded index information")),4768/* Think twice before adding "--nul" synonym to this */4769OPT_SET_INT('z', NULL, &state.line_termination,4770N_("paths are separated with NUL character"),'\0'),4771OPT_INTEGER('C', NULL, &state.p_context,4772N_("ensure at least <n> lines of context match")),4773{ OPTION_CALLBACK,0,"whitespace", &state,N_("action"),4774N_("detect new or modified lines that have whitespace errors"),47750, option_parse_whitespace },4776{ OPTION_CALLBACK,0,"ignore-space-change", &state, NULL,4777N_("ignore changes in whitespace when finding context"),4778 PARSE_OPT_NOARG, option_parse_space_change },4779{ OPTION_CALLBACK,0,"ignore-whitespace", &state, NULL,4780N_("ignore changes in whitespace when finding context"),4781 PARSE_OPT_NOARG, option_parse_space_change },4782OPT_BOOL('R',"reverse", &state.apply_in_reverse,4783N_("apply the patch in reverse")),4784OPT_BOOL(0,"unidiff-zero", &state.unidiff_zero,4785N_("don't expect at least one line of context")),4786OPT_BOOL(0,"reject", &state.apply_with_reject,4787N_("leave the rejected hunks in corresponding *.rej files")),4788OPT_BOOL(0,"allow-overlap", &state.allow_overlap,4789N_("allow overlapping hunks")),4790OPT__VERBOSE(&state.apply_verbosely,N_("be verbose")),4791OPT_BIT(0,"inaccurate-eof", &options,4792N_("tolerate incorrectly detected missing new-line at the end of file"),4793 INACCURATE_EOF),4794OPT_BIT(0,"recount", &options,4795N_("do not trust the line counts in the hunk headers"),4796 RECOUNT),4797{ OPTION_CALLBACK,0,"directory", &state,N_("root"),4798N_("prepend <root> to all filenames"),47990, option_parse_directory },4800OPT_END()4801};48024803init_apply_state(&state, prefix, &lock_file);48044805 argc =parse_options(argc, argv, state.prefix, builtin_apply_options,4806 apply_usage,0);48074808check_apply_state(&state, force_apply);48094810 ret =apply_all_patches(&state, argc, argv, options);48114812clear_apply_state(&state);48134814return ret;4815}