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 10#include"cache.h" 11#include"blob.h" 12#include"delta.h" 13#include"diff.h" 14#include"dir.h" 15#include"xdiff-interface.h" 16#include"ll-merge.h" 17#include"lockfile.h" 18#include"parse-options.h" 19#include"quote.h" 20#include"rerere.h" 21#include"apply.h" 22 23static voidgit_apply_config(void) 24{ 25git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 26git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 27git_config(git_default_config, NULL); 28} 29 30intparse_whitespace_option(struct apply_state *state,const char*option) 31{ 32if(!option) { 33 state->ws_error_action = warn_on_ws_error; 34return0; 35} 36if(!strcmp(option,"warn")) { 37 state->ws_error_action = warn_on_ws_error; 38return0; 39} 40if(!strcmp(option,"nowarn")) { 41 state->ws_error_action = nowarn_ws_error; 42return0; 43} 44if(!strcmp(option,"error")) { 45 state->ws_error_action = die_on_ws_error; 46return0; 47} 48if(!strcmp(option,"error-all")) { 49 state->ws_error_action = die_on_ws_error; 50 state->squelch_whitespace_errors =0; 51return0; 52} 53if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 54 state->ws_error_action = correct_ws_error; 55return0; 56} 57returnerror(_("unrecognized whitespace option '%s'"), option); 58} 59 60intparse_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; 67return0; 68} 69if(!strcmp(option,"change")) { 70 state->ws_ignore_action = ignore_ws_change; 71return0; 72} 73returnerror(_("unrecognized whitespace ignore option '%s'"), option); 74} 75 76intinit_apply_state(struct apply_state *state, 77const char*prefix, 78struct lock_file *lock_file) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->prefix_length = state->prefix ?strlen(state->prefix) :0; 83 state->lock_file = lock_file; 84 state->newfd = -1; 85 state->apply =1; 86 state->line_termination ='\n'; 87 state->p_value =1; 88 state->p_context = UINT_MAX; 89 state->squelch_whitespace_errors =5; 90 state->ws_error_action = warn_on_ws_error; 91 state->ws_ignore_action = ignore_ws_none; 92 state->linenr =1; 93string_list_init(&state->fn_table,0); 94string_list_init(&state->limit_by_name,0); 95string_list_init(&state->symlink_changes,0); 96strbuf_init(&state->root,0); 97 98git_apply_config(); 99if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 100return-1; 101if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 102return-1; 103return0; 104} 105 106voidclear_apply_state(struct apply_state *state) 107{ 108string_list_clear(&state->limit_by_name,0); 109string_list_clear(&state->symlink_changes,0); 110strbuf_release(&state->root); 111 112/* &state->fn_table is cleared at the end of apply_patch() */ 113} 114 115intcheck_apply_state(struct apply_state *state,int force_apply) 116{ 117int is_not_gitdir = !startup_info->have_repository; 118 119if(state->apply_with_reject && state->threeway) 120returnerror("--reject and --3way cannot be used together."); 121if(state->cached && state->threeway) 122returnerror("--cached and --3way cannot be used together."); 123if(state->threeway) { 124if(is_not_gitdir) 125returnerror(_("--3way outside a repository")); 126 state->check_index =1; 127} 128if(state->apply_with_reject) 129 state->apply = state->apply_verbosely =1; 130if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 131 state->apply =0; 132if(state->check_index && is_not_gitdir) 133returnerror(_("--index outside a repository")); 134if(state->cached) { 135if(is_not_gitdir) 136returnerror(_("--cached outside a repository")); 137 state->check_index =1; 138} 139if(state->check_index) 140 state->unsafe_paths =0; 141if(!state->lock_file) 142returnerror("BUG: state->lock_file should not be NULL"); 143 144return0; 145} 146 147static voidset_default_whitespace_mode(struct apply_state *state) 148{ 149if(!state->whitespace_option && !apply_default_whitespace) 150 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 151} 152 153/* 154 * This represents one "hunk" from a patch, starting with 155 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 156 * patch text is pointed at by patch, and its byte length 157 * is stored in size. leading and trailing are the number 158 * of context lines. 159 */ 160struct fragment { 161unsigned long leading, trailing; 162unsigned long oldpos, oldlines; 163unsigned long newpos, newlines; 164/* 165 * 'patch' is usually borrowed from buf in apply_patch(), 166 * but some codepaths store an allocated buffer. 167 */ 168const char*patch; 169unsigned free_patch:1, 170 rejected:1; 171int size; 172int linenr; 173struct fragment *next; 174}; 175 176/* 177 * When dealing with a binary patch, we reuse "leading" field 178 * to store the type of the binary hunk, either deflated "delta" 179 * or deflated "literal". 180 */ 181#define binary_patch_method leading 182#define BINARY_DELTA_DEFLATED 1 183#define BINARY_LITERAL_DEFLATED 2 184 185/* 186 * This represents a "patch" to a file, both metainfo changes 187 * such as creation/deletion, filemode and content changes represented 188 * as a series of fragments. 189 */ 190struct patch { 191char*new_name, *old_name, *def_name; 192unsigned int old_mode, new_mode; 193int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 194int rejected; 195unsigned ws_rule; 196int lines_added, lines_deleted; 197int score; 198unsigned int is_toplevel_relative:1; 199unsigned int inaccurate_eof:1; 200unsigned int is_binary:1; 201unsigned int is_copy:1; 202unsigned int is_rename:1; 203unsigned int recount:1; 204unsigned int conflicted_threeway:1; 205unsigned int direct_to_threeway:1; 206struct fragment *fragments; 207char*result; 208size_t resultsize; 209char old_sha1_prefix[41]; 210char new_sha1_prefix[41]; 211struct patch *next; 212 213/* three-way fallback result */ 214struct object_id threeway_stage[3]; 215}; 216 217static voidfree_fragment_list(struct fragment *list) 218{ 219while(list) { 220struct fragment *next = list->next; 221if(list->free_patch) 222free((char*)list->patch); 223free(list); 224 list = next; 225} 226} 227 228static voidfree_patch(struct patch *patch) 229{ 230free_fragment_list(patch->fragments); 231free(patch->def_name); 232free(patch->old_name); 233free(patch->new_name); 234free(patch->result); 235free(patch); 236} 237 238static voidfree_patch_list(struct patch *list) 239{ 240while(list) { 241struct patch *next = list->next; 242free_patch(list); 243 list = next; 244} 245} 246 247/* 248 * A line in a file, len-bytes long (includes the terminating LF, 249 * except for an incomplete line at the end if the file ends with 250 * one), and its contents hashes to 'hash'. 251 */ 252struct line { 253size_t len; 254unsigned hash :24; 255unsigned flag :8; 256#define LINE_COMMON 1 257#define LINE_PATCHED 2 258}; 259 260/* 261 * This represents a "file", which is an array of "lines". 262 */ 263struct image { 264char*buf; 265size_t len; 266size_t nr; 267size_t alloc; 268struct line *line_allocated; 269struct line *line; 270}; 271 272static uint32_thash_line(const char*cp,size_t len) 273{ 274size_t i; 275uint32_t h; 276for(i =0, h =0; i < len; i++) { 277if(!isspace(cp[i])) { 278 h = h *3+ (cp[i] &0xff); 279} 280} 281return h; 282} 283 284/* 285 * Compare lines s1 of length n1 and s2 of length n2, ignoring 286 * whitespace difference. Returns 1 if they match, 0 otherwise 287 */ 288static intfuzzy_matchlines(const char*s1,size_t n1, 289const char*s2,size_t n2) 290{ 291const char*last1 = s1 + n1 -1; 292const char*last2 = s2 + n2 -1; 293int result =0; 294 295/* ignore line endings */ 296while((*last1 =='\r') || (*last1 =='\n')) 297 last1--; 298while((*last2 =='\r') || (*last2 =='\n')) 299 last2--; 300 301/* skip leading whitespaces, if both begin with whitespace */ 302if(s1 <= last1 && s2 <= last2 &&isspace(*s1) &&isspace(*s2)) { 303while(isspace(*s1) && (s1 <= last1)) 304 s1++; 305while(isspace(*s2) && (s2 <= last2)) 306 s2++; 307} 308/* early return if both lines are empty */ 309if((s1 > last1) && (s2 > last2)) 310return1; 311while(!result) { 312 result = *s1++ - *s2++; 313/* 314 * Skip whitespace inside. We check for whitespace on 315 * both buffers because we don't want "a b" to match 316 * "ab" 317 */ 318if(isspace(*s1) &&isspace(*s2)) { 319while(isspace(*s1) && s1 <= last1) 320 s1++; 321while(isspace(*s2) && s2 <= last2) 322 s2++; 323} 324/* 325 * If we reached the end on one side only, 326 * lines don't match 327 */ 328if( 329((s2 > last2) && (s1 <= last1)) || 330((s1 > last1) && (s2 <= last2))) 331return0; 332if((s1 > last1) && (s2 > last2)) 333break; 334} 335 336return!result; 337} 338 339static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 340{ 341ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 342 img->line_allocated[img->nr].len = len; 343 img->line_allocated[img->nr].hash =hash_line(bol, len); 344 img->line_allocated[img->nr].flag = flag; 345 img->nr++; 346} 347 348/* 349 * "buf" has the file contents to be patched (read from various sources). 350 * attach it to "image" and add line-based index to it. 351 * "image" now owns the "buf". 352 */ 353static voidprepare_image(struct image *image,char*buf,size_t len, 354int prepare_linetable) 355{ 356const char*cp, *ep; 357 358memset(image,0,sizeof(*image)); 359 image->buf = buf; 360 image->len = len; 361 362if(!prepare_linetable) 363return; 364 365 ep = image->buf + image->len; 366 cp = image->buf; 367while(cp < ep) { 368const char*next; 369for(next = cp; next < ep && *next !='\n'; next++) 370; 371if(next < ep) 372 next++; 373add_line_info(image, cp, next - cp,0); 374 cp = next; 375} 376 image->line = image->line_allocated; 377} 378 379static voidclear_image(struct image *image) 380{ 381free(image->buf); 382free(image->line_allocated); 383memset(image,0,sizeof(*image)); 384} 385 386/* fmt must contain _one_ %s and no other substitution */ 387static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 388{ 389struct strbuf sb = STRBUF_INIT; 390 391if(patch->old_name && patch->new_name && 392strcmp(patch->old_name, patch->new_name)) { 393quote_c_style(patch->old_name, &sb, NULL,0); 394strbuf_addstr(&sb," => "); 395quote_c_style(patch->new_name, &sb, NULL,0); 396}else{ 397const char*n = patch->new_name; 398if(!n) 399 n = patch->old_name; 400quote_c_style(n, &sb, NULL,0); 401} 402fprintf(output, fmt, sb.buf); 403fputc('\n', output); 404strbuf_release(&sb); 405} 406 407#define SLOP (16) 408 409static intread_patch_file(struct strbuf *sb,int fd) 410{ 411if(strbuf_read(sb, fd,0) <0) 412returnerror_errno("git apply: failed to read"); 413 414/* 415 * Make sure that we have some slop in the buffer 416 * so that we can do speculative "memcmp" etc, and 417 * see to it that it is NUL-filled. 418 */ 419strbuf_grow(sb, SLOP); 420memset(sb->buf + sb->len,0, SLOP); 421return0; 422} 423 424static unsigned longlinelen(const char*buffer,unsigned long size) 425{ 426unsigned long len =0; 427while(size--) { 428 len++; 429if(*buffer++ =='\n') 430break; 431} 432return len; 433} 434 435static intis_dev_null(const char*str) 436{ 437returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 438} 439 440#define TERM_SPACE 1 441#define TERM_TAB 2 442 443static intname_terminate(int c,int terminate) 444{ 445if(c ==' '&& !(terminate & TERM_SPACE)) 446return0; 447if(c =='\t'&& !(terminate & TERM_TAB)) 448return0; 449 450return1; 451} 452 453/* remove double slashes to make --index work with such filenames */ 454static char*squash_slash(char*name) 455{ 456int i =0, j =0; 457 458if(!name) 459return NULL; 460 461while(name[i]) { 462if((name[j++] = name[i++]) =='/') 463while(name[i] =='/') 464 i++; 465} 466 name[j] ='\0'; 467return name; 468} 469 470static char*find_name_gnu(struct apply_state *state, 471const char*line, 472const char*def, 473int p_value) 474{ 475struct strbuf name = STRBUF_INIT; 476char*cp; 477 478/* 479 * Proposed "new-style" GNU patch/diff format; see 480 * http://marc.info/?l=git&m=112927316408690&w=2 481 */ 482if(unquote_c_style(&name, line, NULL)) { 483strbuf_release(&name); 484return NULL; 485} 486 487for(cp = name.buf; p_value; p_value--) { 488 cp =strchr(cp,'/'); 489if(!cp) { 490strbuf_release(&name); 491return NULL; 492} 493 cp++; 494} 495 496strbuf_remove(&name,0, cp - name.buf); 497if(state->root.len) 498strbuf_insert(&name,0, state->root.buf, state->root.len); 499returnsquash_slash(strbuf_detach(&name, NULL)); 500} 501 502static size_tsane_tz_len(const char*line,size_t len) 503{ 504const char*tz, *p; 505 506if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 507return0; 508 tz = line + len -strlen(" +0500"); 509 510if(tz[1] !='+'&& tz[1] !='-') 511return0; 512 513for(p = tz +2; p != line + len; p++) 514if(!isdigit(*p)) 515return0; 516 517return line + len - tz; 518} 519 520static size_ttz_with_colon_len(const char*line,size_t len) 521{ 522const char*tz, *p; 523 524if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 525return0; 526 tz = line + len -strlen(" +08:00"); 527 528if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 529return0; 530 p = tz +2; 531if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 532!isdigit(*p++) || !isdigit(*p++)) 533return0; 534 535return line + len - tz; 536} 537 538static size_tdate_len(const char*line,size_t len) 539{ 540const char*date, *p; 541 542if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 543return0; 544 p = date = line + len -strlen("72-02-05"); 545 546if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 547!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 548!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 549return0; 550 551if(date - line >=strlen("19") && 552isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 553 date -=strlen("19"); 554 555return line + len - date; 556} 557 558static size_tshort_time_len(const char*line,size_t len) 559{ 560const char*time, *p; 561 562if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 563return0; 564 p = time = line + len -strlen(" 07:01:32"); 565 566/* Permit 1-digit hours? */ 567if(*p++ !=' '|| 568!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 569!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 570!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 571return0; 572 573return line + len - time; 574} 575 576static size_tfractional_time_len(const char*line,size_t len) 577{ 578const char*p; 579size_t n; 580 581/* Expected format: 19:41:17.620000023 */ 582if(!len || !isdigit(line[len -1])) 583return0; 584 p = line + len -1; 585 586/* Fractional seconds. */ 587while(p > line &&isdigit(*p)) 588 p--; 589if(*p !='.') 590return0; 591 592/* Hours, minutes, and whole seconds. */ 593 n =short_time_len(line, p - line); 594if(!n) 595return0; 596 597return line + len - p + n; 598} 599 600static size_ttrailing_spaces_len(const char*line,size_t len) 601{ 602const char*p; 603 604/* Expected format: ' ' x (1 or more) */ 605if(!len || line[len -1] !=' ') 606return0; 607 608 p = line + len; 609while(p != line) { 610 p--; 611if(*p !=' ') 612return line + len - (p +1); 613} 614 615/* All spaces! */ 616return len; 617} 618 619static size_tdiff_timestamp_len(const char*line,size_t len) 620{ 621const char*end = line + len; 622size_t n; 623 624/* 625 * Posix: 2010-07-05 19:41:17 626 * GNU: 2010-07-05 19:41:17.620000023 -0500 627 */ 628 629if(!isdigit(end[-1])) 630return0; 631 632 n =sane_tz_len(line, end - line); 633if(!n) 634 n =tz_with_colon_len(line, end - line); 635 end -= n; 636 637 n =short_time_len(line, end - line); 638if(!n) 639 n =fractional_time_len(line, end - line); 640 end -= n; 641 642 n =date_len(line, end - line); 643if(!n)/* No date. Too bad. */ 644return0; 645 end -= n; 646 647if(end == line)/* No space before date. */ 648return0; 649if(end[-1] =='\t') {/* Success! */ 650 end--; 651return line + len - end; 652} 653if(end[-1] !=' ')/* No space before date. */ 654return0; 655 656/* Whitespace damage. */ 657 end -=trailing_spaces_len(line, end - line); 658return line + len - end; 659} 660 661static char*find_name_common(struct apply_state *state, 662const char*line, 663const char*def, 664int p_value, 665const char*end, 666int terminate) 667{ 668int len; 669const char*start = NULL; 670 671if(p_value ==0) 672 start = line; 673while(line != end) { 674char c = *line; 675 676if(!end &&isspace(c)) { 677if(c =='\n') 678break; 679if(name_terminate(c, terminate)) 680break; 681} 682 line++; 683if(c =='/'&& !--p_value) 684 start = line; 685} 686if(!start) 687returnsquash_slash(xstrdup_or_null(def)); 688 len = line - start; 689if(!len) 690returnsquash_slash(xstrdup_or_null(def)); 691 692/* 693 * Generally we prefer the shorter name, especially 694 * if the other one is just a variation of that with 695 * something else tacked on to the end (ie "file.orig" 696 * or "file~"). 697 */ 698if(def) { 699int deflen =strlen(def); 700if(deflen < len && !strncmp(start, def, deflen)) 701returnsquash_slash(xstrdup(def)); 702} 703 704if(state->root.len) { 705char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 706returnsquash_slash(ret); 707} 708 709returnsquash_slash(xmemdupz(start, len)); 710} 711 712static char*find_name(struct apply_state *state, 713const char*line, 714char*def, 715int p_value, 716int terminate) 717{ 718if(*line =='"') { 719char*name =find_name_gnu(state, line, def, p_value); 720if(name) 721return name; 722} 723 724returnfind_name_common(state, line, def, p_value, NULL, terminate); 725} 726 727static char*find_name_traditional(struct apply_state *state, 728const char*line, 729char*def, 730int p_value) 731{ 732size_t len; 733size_t date_len; 734 735if(*line =='"') { 736char*name =find_name_gnu(state, line, def, p_value); 737if(name) 738return name; 739} 740 741 len =strchrnul(line,'\n') - line; 742 date_len =diff_timestamp_len(line, len); 743if(!date_len) 744returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 745 len -= date_len; 746 747returnfind_name_common(state, line, def, p_value, line + len,0); 748} 749 750static intcount_slashes(const char*cp) 751{ 752int cnt =0; 753char ch; 754 755while((ch = *cp++)) 756if(ch =='/') 757 cnt++; 758return cnt; 759} 760 761/* 762 * Given the string after "--- " or "+++ ", guess the appropriate 763 * p_value for the given patch. 764 */ 765static intguess_p_value(struct apply_state *state,const char*nameline) 766{ 767char*name, *cp; 768int val = -1; 769 770if(is_dev_null(nameline)) 771return-1; 772 name =find_name_traditional(state, nameline, NULL,0); 773if(!name) 774return-1; 775 cp =strchr(name,'/'); 776if(!cp) 777 val =0; 778else if(state->prefix) { 779/* 780 * Does it begin with "a/$our-prefix" and such? Then this is 781 * very likely to apply to our directory. 782 */ 783if(!strncmp(name, state->prefix, state->prefix_length)) 784 val =count_slashes(state->prefix); 785else{ 786 cp++; 787if(!strncmp(cp, state->prefix, state->prefix_length)) 788 val =count_slashes(state->prefix) +1; 789} 790} 791free(name); 792return val; 793} 794 795/* 796 * Does the ---/+++ line have the POSIX timestamp after the last HT? 797 * GNU diff puts epoch there to signal a creation/deletion event. Is 798 * this such a timestamp? 799 */ 800static inthas_epoch_timestamp(const char*nameline) 801{ 802/* 803 * We are only interested in epoch timestamp; any non-zero 804 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 805 * For the same reason, the date must be either 1969-12-31 or 806 * 1970-01-01, and the seconds part must be "00". 807 */ 808const char stamp_regexp[] = 809"^(1969-12-31|1970-01-01)" 810" " 811"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 812" " 813"([-+][0-2][0-9]:?[0-5][0-9])\n"; 814const char*timestamp = NULL, *cp, *colon; 815static regex_t *stamp; 816 regmatch_t m[10]; 817int zoneoffset; 818int hourminute; 819int status; 820 821for(cp = nameline; *cp !='\n'; cp++) { 822if(*cp =='\t') 823 timestamp = cp +1; 824} 825if(!timestamp) 826return0; 827if(!stamp) { 828 stamp =xmalloc(sizeof(*stamp)); 829if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 830warning(_("Cannot prepare timestamp regexp%s"), 831 stamp_regexp); 832return0; 833} 834} 835 836 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 837if(status) { 838if(status != REG_NOMATCH) 839warning(_("regexec returned%dfor input:%s"), 840 status, timestamp); 841return0; 842} 843 844 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 845if(*colon ==':') 846 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 847else 848 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 849if(timestamp[m[3].rm_so] =='-') 850 zoneoffset = -zoneoffset; 851 852/* 853 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 854 * (west of GMT) or 1970-01-01 (east of GMT) 855 */ 856if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 857(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 858return0; 859 860 hourminute = (strtol(timestamp +11, NULL,10) *60+ 861strtol(timestamp +14, NULL,10) - 862 zoneoffset); 863 864return((zoneoffset <0&& hourminute ==1440) || 865(0<= zoneoffset && !hourminute)); 866} 867 868/* 869 * Get the name etc info from the ---/+++ lines of a traditional patch header 870 * 871 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 872 * files, we can happily check the index for a match, but for creating a 873 * new file we should try to match whatever "patch" does. I have no idea. 874 */ 875static intparse_traditional_patch(struct apply_state *state, 876const char*first, 877const char*second, 878struct patch *patch) 879{ 880char*name; 881 882 first +=4;/* skip "--- " */ 883 second +=4;/* skip "+++ " */ 884if(!state->p_value_known) { 885int p, q; 886 p =guess_p_value(state, first); 887 q =guess_p_value(state, second); 888if(p <0) p = q; 889if(0<= p && p == q) { 890 state->p_value = p; 891 state->p_value_known =1; 892} 893} 894if(is_dev_null(first)) { 895 patch->is_new =1; 896 patch->is_delete =0; 897 name =find_name_traditional(state, second, NULL, state->p_value); 898 patch->new_name = name; 899}else if(is_dev_null(second)) { 900 patch->is_new =0; 901 patch->is_delete =1; 902 name =find_name_traditional(state, first, NULL, state->p_value); 903 patch->old_name = name; 904}else{ 905char*first_name; 906 first_name =find_name_traditional(state, first, NULL, state->p_value); 907 name =find_name_traditional(state, second, first_name, state->p_value); 908free(first_name); 909if(has_epoch_timestamp(first)) { 910 patch->is_new =1; 911 patch->is_delete =0; 912 patch->new_name = name; 913}else if(has_epoch_timestamp(second)) { 914 patch->is_new =0; 915 patch->is_delete =1; 916 patch->old_name = name; 917}else{ 918 patch->old_name = name; 919 patch->new_name =xstrdup_or_null(name); 920} 921} 922if(!name) 923returnerror(_("unable to find filename in patch at line%d"), state->linenr); 924 925return0; 926} 927 928static intgitdiff_hdrend(struct apply_state *state, 929const char*line, 930struct patch *patch) 931{ 932return1; 933} 934 935/* 936 * We're anal about diff header consistency, to make 937 * sure that we don't end up having strange ambiguous 938 * patches floating around. 939 * 940 * As a result, gitdiff_{old|new}name() will check 941 * their names against any previous information, just 942 * to make sure.. 943 */ 944#define DIFF_OLD_NAME 0 945#define DIFF_NEW_NAME 1 946 947static intgitdiff_verify_name(struct apply_state *state, 948const char*line, 949int isnull, 950char**name, 951int side) 952{ 953if(!*name && !isnull) { 954*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 955return0; 956} 957 958if(*name) { 959char*another; 960if(isnull) 961returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 962*name, state->linenr); 963 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 964if(!another ||strcmp(another, *name)) { 965free(another); 966returnerror((side == DIFF_NEW_NAME) ? 967_("git apply: bad git-diff - inconsistent new filename on line%d") : 968_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 969} 970free(another); 971}else{ 972if(!starts_with(line,"/dev/null\n")) 973returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 974} 975 976return0; 977} 978 979static intgitdiff_oldname(struct apply_state *state, 980const char*line, 981struct patch *patch) 982{ 983returngitdiff_verify_name(state, line, 984 patch->is_new, &patch->old_name, 985 DIFF_OLD_NAME); 986} 987 988static intgitdiff_newname(struct apply_state *state, 989const char*line, 990struct patch *patch) 991{ 992returngitdiff_verify_name(state, line, 993 patch->is_delete, &patch->new_name, 994 DIFF_NEW_NAME); 995} 996 997static intgitdiff_oldmode(struct apply_state *state, 998const char*line, 999struct patch *patch)1000{1001 patch->old_mode =strtoul(line, NULL,8);1002return0;1003}10041005static intgitdiff_newmode(struct apply_state *state,1006const char*line,1007struct patch *patch)1008{1009 patch->new_mode =strtoul(line, NULL,8);1010return0;1011}10121013static intgitdiff_delete(struct apply_state *state,1014const char*line,1015struct patch *patch)1016{1017 patch->is_delete =1;1018free(patch->old_name);1019 patch->old_name =xstrdup_or_null(patch->def_name);1020returngitdiff_oldmode(state, line, patch);1021}10221023static intgitdiff_newfile(struct apply_state *state,1024const char*line,1025struct patch *patch)1026{1027 patch->is_new =1;1028free(patch->new_name);1029 patch->new_name =xstrdup_or_null(patch->def_name);1030returngitdiff_newmode(state, line, patch);1031}10321033static intgitdiff_copysrc(struct apply_state *state,1034const char*line,1035struct patch *patch)1036{1037 patch->is_copy =1;1038free(patch->old_name);1039 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1040return0;1041}10421043static intgitdiff_copydst(struct apply_state *state,1044const char*line,1045struct patch *patch)1046{1047 patch->is_copy =1;1048free(patch->new_name);1049 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1050return0;1051}10521053static intgitdiff_renamesrc(struct apply_state *state,1054const char*line,1055struct patch *patch)1056{1057 patch->is_rename =1;1058free(patch->old_name);1059 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1060return0;1061}10621063static intgitdiff_renamedst(struct apply_state *state,1064const char*line,1065struct patch *patch)1066{1067 patch->is_rename =1;1068free(patch->new_name);1069 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1070return0;1071}10721073static intgitdiff_similarity(struct apply_state *state,1074const char*line,1075struct patch *patch)1076{1077unsigned long val =strtoul(line, NULL,10);1078if(val <=100)1079 patch->score = val;1080return0;1081}10821083static intgitdiff_dissimilarity(struct apply_state *state,1084const char*line,1085struct patch *patch)1086{1087unsigned long val =strtoul(line, NULL,10);1088if(val <=100)1089 patch->score = val;1090return0;1091}10921093static intgitdiff_index(struct apply_state *state,1094const char*line,1095struct patch *patch)1096{1097/*1098 * index line is N hexadecimal, "..", N hexadecimal,1099 * and optional space with octal mode.1100 */1101const char*ptr, *eol;1102int len;11031104 ptr =strchr(line,'.');1105if(!ptr || ptr[1] !='.'||40< ptr - line)1106return0;1107 len = ptr - line;1108memcpy(patch->old_sha1_prefix, line, len);1109 patch->old_sha1_prefix[len] =0;11101111 line = ptr +2;1112 ptr =strchr(line,' ');1113 eol =strchrnul(line,'\n');11141115if(!ptr || eol < ptr)1116 ptr = eol;1117 len = ptr - line;11181119if(40< len)1120return0;1121memcpy(patch->new_sha1_prefix, line, len);1122 patch->new_sha1_prefix[len] =0;1123if(*ptr ==' ')1124 patch->old_mode =strtoul(ptr+1, NULL,8);1125return0;1126}11271128/*1129 * This is normal for a diff that doesn't change anything: we'll fall through1130 * into the next diff. Tell the parser to break out.1131 */1132static intgitdiff_unrecognized(struct apply_state *state,1133const char*line,1134struct patch *patch)1135{1136return1;1137}11381139/*1140 * Skip p_value leading components from "line"; as we do not accept1141 * absolute paths, return NULL in that case.1142 */1143static const char*skip_tree_prefix(struct apply_state *state,1144const char*line,1145int llen)1146{1147int nslash;1148int i;11491150if(!state->p_value)1151return(llen && line[0] =='/') ? NULL : line;11521153 nslash = state->p_value;1154for(i =0; i < llen; i++) {1155int ch = line[i];1156if(ch =='/'&& --nslash <=0)1157return(i ==0) ? NULL : &line[i +1];1158}1159return NULL;1160}11611162/*1163 * This is to extract the same name that appears on "diff --git"1164 * line. We do not find and return anything if it is a rename1165 * patch, and it is OK because we will find the name elsewhere.1166 * We need to reliably find name only when it is mode-change only,1167 * creation or deletion of an empty file. In any of these cases,1168 * both sides are the same name under a/ and b/ respectively.1169 */1170static char*git_header_name(struct apply_state *state,1171const char*line,1172int llen)1173{1174const char*name;1175const char*second = NULL;1176size_t len, line_len;11771178 line +=strlen("diff --git ");1179 llen -=strlen("diff --git ");11801181if(*line =='"') {1182const char*cp;1183struct strbuf first = STRBUF_INIT;1184struct strbuf sp = STRBUF_INIT;11851186if(unquote_c_style(&first, line, &second))1187goto free_and_fail1;11881189/* strip the a/b prefix including trailing slash */1190 cp =skip_tree_prefix(state, first.buf, first.len);1191if(!cp)1192goto free_and_fail1;1193strbuf_remove(&first,0, cp - first.buf);11941195/*1196 * second points at one past closing dq of name.1197 * find the second name.1198 */1199while((second < line + llen) &&isspace(*second))1200 second++;12011202if(line + llen <= second)1203goto free_and_fail1;1204if(*second =='"') {1205if(unquote_c_style(&sp, second, NULL))1206goto free_and_fail1;1207 cp =skip_tree_prefix(state, sp.buf, sp.len);1208if(!cp)1209goto free_and_fail1;1210/* They must match, otherwise ignore */1211if(strcmp(cp, first.buf))1212goto free_and_fail1;1213strbuf_release(&sp);1214returnstrbuf_detach(&first, NULL);1215}12161217/* unquoted second */1218 cp =skip_tree_prefix(state, second, line + llen - second);1219if(!cp)1220goto free_and_fail1;1221if(line + llen - cp != first.len ||1222memcmp(first.buf, cp, first.len))1223goto free_and_fail1;1224returnstrbuf_detach(&first, NULL);12251226 free_and_fail1:1227strbuf_release(&first);1228strbuf_release(&sp);1229return NULL;1230}12311232/* unquoted first name */1233 name =skip_tree_prefix(state, line, llen);1234if(!name)1235return NULL;12361237/*1238 * since the first name is unquoted, a dq if exists must be1239 * the beginning of the second name.1240 */1241for(second = name; second < line + llen; second++) {1242if(*second =='"') {1243struct strbuf sp = STRBUF_INIT;1244const char*np;12451246if(unquote_c_style(&sp, second, NULL))1247goto free_and_fail2;12481249 np =skip_tree_prefix(state, sp.buf, sp.len);1250if(!np)1251goto free_and_fail2;12521253 len = sp.buf + sp.len - np;1254if(len < second - name &&1255!strncmp(np, name, len) &&1256isspace(name[len])) {1257/* Good */1258strbuf_remove(&sp,0, np - sp.buf);1259returnstrbuf_detach(&sp, NULL);1260}12611262 free_and_fail2:1263strbuf_release(&sp);1264return NULL;1265}1266}12671268/*1269 * Accept a name only if it shows up twice, exactly the same1270 * form.1271 */1272 second =strchr(name,'\n');1273if(!second)1274return NULL;1275 line_len = second - name;1276for(len =0; ; len++) {1277switch(name[len]) {1278default:1279continue;1280case'\n':1281return NULL;1282case'\t':case' ':1283/*1284 * Is this the separator between the preimage1285 * and the postimage pathname? Again, we are1286 * only interested in the case where there is1287 * no rename, as this is only to set def_name1288 * and a rename patch has the names elsewhere1289 * in an unambiguous form.1290 */1291if(!name[len +1])1292return NULL;/* no postimage name */1293 second =skip_tree_prefix(state, name + len +1,1294 line_len - (len +1));1295if(!second)1296return NULL;1297/*1298 * Does len bytes starting at "name" and "second"1299 * (that are separated by one HT or SP we just1300 * found) exactly match?1301 */1302if(second[len] =='\n'&& !strncmp(name, second, len))1303returnxmemdupz(name, len);1304}1305}1306}13071308/* Verify that we recognize the lines following a git header */1309static intparse_git_header(struct apply_state *state,1310const char*line,1311int len,1312unsigned int size,1313struct patch *patch)1314{1315unsigned long offset;13161317/* A git diff has explicit new/delete information, so we don't guess */1318 patch->is_new =0;1319 patch->is_delete =0;13201321/*1322 * Some things may not have the old name in the1323 * rest of the headers anywhere (pure mode changes,1324 * or removing or adding empty files), so we get1325 * the default name from the header.1326 */1327 patch->def_name =git_header_name(state, line, len);1328if(patch->def_name && state->root.len) {1329char*s =xstrfmt("%s%s", state->root.buf, patch->def_name);1330free(patch->def_name);1331 patch->def_name = s;1332}13331334 line += len;1335 size -= len;1336 state->linenr++;1337for(offset = len ; size >0; offset += len, size -= len, line += len, state->linenr++) {1338static const struct opentry {1339const char*str;1340int(*fn)(struct apply_state *,const char*,struct patch *);1341} optable[] = {1342{"@@ -", gitdiff_hdrend },1343{"--- ", gitdiff_oldname },1344{"+++ ", gitdiff_newname },1345{"old mode ", gitdiff_oldmode },1346{"new mode ", gitdiff_newmode },1347{"deleted file mode ", gitdiff_delete },1348{"new file mode ", gitdiff_newfile },1349{"copy from ", gitdiff_copysrc },1350{"copy to ", gitdiff_copydst },1351{"rename old ", gitdiff_renamesrc },1352{"rename new ", gitdiff_renamedst },1353{"rename from ", gitdiff_renamesrc },1354{"rename to ", gitdiff_renamedst },1355{"similarity index ", gitdiff_similarity },1356{"dissimilarity index ", gitdiff_dissimilarity },1357{"index ", gitdiff_index },1358{"", gitdiff_unrecognized },1359};1360int i;13611362 len =linelen(line, size);1363if(!len || line[len-1] !='\n')1364break;1365for(i =0; i <ARRAY_SIZE(optable); i++) {1366const struct opentry *p = optable + i;1367int oplen =strlen(p->str);1368int res;1369if(len < oplen ||memcmp(p->str, line, oplen))1370continue;1371 res = p->fn(state, line + oplen, patch);1372if(res <0)1373return-1;1374if(res >0)1375return offset;1376break;1377}1378}13791380return offset;1381}13821383static intparse_num(const char*line,unsigned long*p)1384{1385char*ptr;13861387if(!isdigit(*line))1388return0;1389*p =strtoul(line, &ptr,10);1390return ptr - line;1391}13921393static intparse_range(const char*line,int len,int offset,const char*expect,1394unsigned long*p1,unsigned long*p2)1395{1396int digits, ex;13971398if(offset <0|| offset >= len)1399return-1;1400 line += offset;1401 len -= offset;14021403 digits =parse_num(line, p1);1404if(!digits)1405return-1;14061407 offset += digits;1408 line += digits;1409 len -= digits;14101411*p2 =1;1412if(*line ==',') {1413 digits =parse_num(line+1, p2);1414if(!digits)1415return-1;14161417 offset += digits+1;1418 line += digits+1;1419 len -= digits+1;1420}14211422 ex =strlen(expect);1423if(ex > len)1424return-1;1425if(memcmp(line, expect, ex))1426return-1;14271428return offset + ex;1429}14301431static voidrecount_diff(const char*line,int size,struct fragment *fragment)1432{1433int oldlines =0, newlines =0, ret =0;14341435if(size <1) {1436warning("recount: ignore empty hunk");1437return;1438}14391440for(;;) {1441int len =linelen(line, size);1442 size -= len;1443 line += len;14441445if(size <1)1446break;14471448switch(*line) {1449case' ':case'\n':1450 newlines++;1451/* fall through */1452case'-':1453 oldlines++;1454continue;1455case'+':1456 newlines++;1457continue;1458case'\\':1459continue;1460case'@':1461 ret = size <3|| !starts_with(line,"@@ ");1462break;1463case'd':1464 ret = size <5|| !starts_with(line,"diff ");1465break;1466default:1467 ret = -1;1468break;1469}1470if(ret) {1471warning(_("recount: unexpected line: %.*s"),1472(int)linelen(line, size), line);1473return;1474}1475break;1476}1477 fragment->oldlines = oldlines;1478 fragment->newlines = newlines;1479}14801481/*1482 * Parse a unified diff fragment header of the1483 * form "@@ -a,b +c,d @@"1484 */1485static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1486{1487int offset;14881489if(!len || line[len-1] !='\n')1490return-1;14911492/* Figure out the number of lines in a fragment */1493 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1494 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14951496return offset;1497}14981499/*1500 * Find file diff header1501 *1502 * Returns:1503 * -1 if no header was found1504 * -128 in case of error1505 * the size of the header in bytes (called "offset") otherwise1506 */1507static intfind_header(struct apply_state *state,1508const char*line,1509unsigned long size,1510int*hdrsize,1511struct patch *patch)1512{1513unsigned long offset, len;15141515 patch->is_toplevel_relative =0;1516 patch->is_rename = patch->is_copy =0;1517 patch->is_new = patch->is_delete = -1;1518 patch->old_mode = patch->new_mode =0;1519 patch->old_name = patch->new_name = NULL;1520for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1521unsigned long nextlen;15221523 len =linelen(line, size);1524if(!len)1525break;15261527/* Testing this early allows us to take a few shortcuts.. */1528if(len <6)1529continue;15301531/*1532 * Make sure we don't find any unconnected patch fragments.1533 * That's a sign that we didn't find a header, and that a1534 * patch has become corrupted/broken up.1535 */1536if(!memcmp("@@ -", line,4)) {1537struct fragment dummy;1538if(parse_fragment_header(line, len, &dummy) <0)1539continue;1540error(_("patch fragment without header at line%d: %.*s"),1541 state->linenr, (int)len-1, line);1542return-128;1543}15441545if(size < len +6)1546break;15471548/*1549 * Git patch? It might not have a real patch, just a rename1550 * or mode change, so we handle that specially1551 */1552if(!memcmp("diff --git ", line,11)) {1553int git_hdr_len =parse_git_header(state, line, len, size, patch);1554if(git_hdr_len <0)1555return-128;1556if(git_hdr_len <= len)1557continue;1558if(!patch->old_name && !patch->new_name) {1559if(!patch->def_name) {1560error(Q_("git diff header lacks filename information when removing "1561"%dleading pathname component (line%d)",1562"git diff header lacks filename information when removing "1563"%dleading pathname components (line%d)",1564 state->p_value),1565 state->p_value, state->linenr);1566return-128;1567}1568 patch->old_name =xstrdup(patch->def_name);1569 patch->new_name =xstrdup(patch->def_name);1570}1571if(!patch->is_delete && !patch->new_name) {1572error("git diff header lacks filename information "1573"(line%d)", state->linenr);1574return-128;1575}1576 patch->is_toplevel_relative =1;1577*hdrsize = git_hdr_len;1578return offset;1579}15801581/* --- followed by +++ ? */1582if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1583continue;15841585/*1586 * We only accept unified patches, so we want it to1587 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1588 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1589 */1590 nextlen =linelen(line + len, size - len);1591if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1592continue;15931594/* Ok, we'll consider it a patch */1595if(parse_traditional_patch(state, line, line+len, patch))1596return-128;1597*hdrsize = len + nextlen;1598 state->linenr +=2;1599return offset;1600}1601return-1;1602}16031604static voidrecord_ws_error(struct apply_state *state,1605unsigned result,1606const char*line,1607int len,1608int linenr)1609{1610char*err;16111612if(!result)1613return;16141615 state->whitespace_error++;1616if(state->squelch_whitespace_errors &&1617 state->squelch_whitespace_errors < state->whitespace_error)1618return;16191620 err =whitespace_error_string(result);1621fprintf(stderr,"%s:%d:%s.\n%.*s\n",1622 state->patch_input_file, linenr, err, len, line);1623free(err);1624}16251626static voidcheck_whitespace(struct apply_state *state,1627const char*line,1628int len,1629unsigned ws_rule)1630{1631unsigned result =ws_check(line +1, len -1, ws_rule);16321633record_ws_error(state, result, line +1, len -2, state->linenr);1634}16351636/*1637 * Parse a unified diff. Note that this really needs to parse each1638 * fragment separately, since the only way to know the difference1639 * between a "---" that is part of a patch, and a "---" that starts1640 * the next patch is to look at the line counts..1641 */1642static intparse_fragment(struct apply_state *state,1643const char*line,1644unsigned long size,1645struct patch *patch,1646struct fragment *fragment)1647{1648int added, deleted;1649int len =linelen(line, size), offset;1650unsigned long oldlines, newlines;1651unsigned long leading, trailing;16521653 offset =parse_fragment_header(line, len, fragment);1654if(offset <0)1655return-1;1656if(offset >0&& patch->recount)1657recount_diff(line + offset, size - offset, fragment);1658 oldlines = fragment->oldlines;1659 newlines = fragment->newlines;1660 leading =0;1661 trailing =0;16621663/* Parse the thing.. */1664 line += len;1665 size -= len;1666 state->linenr++;1667 added = deleted =0;1668for(offset = len;16690< size;1670 offset += len, size -= len, line += len, state->linenr++) {1671if(!oldlines && !newlines)1672break;1673 len =linelen(line, size);1674if(!len || line[len-1] !='\n')1675return-1;1676switch(*line) {1677default:1678return-1;1679case'\n':/* newer GNU diff, an empty context line */1680case' ':1681 oldlines--;1682 newlines--;1683if(!deleted && !added)1684 leading++;1685 trailing++;1686if(!state->apply_in_reverse &&1687 state->ws_error_action == correct_ws_error)1688check_whitespace(state, line, len, patch->ws_rule);1689break;1690case'-':1691if(state->apply_in_reverse &&1692 state->ws_error_action != nowarn_ws_error)1693check_whitespace(state, line, len, patch->ws_rule);1694 deleted++;1695 oldlines--;1696 trailing =0;1697break;1698case'+':1699if(!state->apply_in_reverse &&1700 state->ws_error_action != nowarn_ws_error)1701check_whitespace(state, line, len, patch->ws_rule);1702 added++;1703 newlines--;1704 trailing =0;1705break;17061707/*1708 * We allow "\ No newline at end of file". Depending1709 * on locale settings when the patch was produced we1710 * don't know what this line looks like. The only1711 * thing we do know is that it begins with "\ ".1712 * Checking for 12 is just for sanity check -- any1713 * l10n of "\ No newline..." is at least that long.1714 */1715case'\\':1716if(len <12||memcmp(line,"\\",2))1717return-1;1718break;1719}1720}1721if(oldlines || newlines)1722return-1;1723if(!deleted && !added)1724return-1;17251726 fragment->leading = leading;1727 fragment->trailing = trailing;17281729/*1730 * If a fragment ends with an incomplete line, we failed to include1731 * it in the above loop because we hit oldlines == newlines == 01732 * before seeing it.1733 */1734if(12< size && !memcmp(line,"\\",2))1735 offset +=linelen(line, size);17361737 patch->lines_added += added;1738 patch->lines_deleted += deleted;17391740if(0< patch->is_new && oldlines)1741returnerror(_("new file depends on old contents"));1742if(0< patch->is_delete && newlines)1743returnerror(_("deleted file still has contents"));1744return offset;1745}17461747/*1748 * We have seen "diff --git a/... b/..." header (or a traditional patch1749 * header). Read hunks that belong to this patch into fragments and hang1750 * them to the given patch structure.1751 *1752 * The (fragment->patch, fragment->size) pair points into the memory given1753 * by the caller, not a copy, when we return.1754 *1755 * Returns:1756 * -1 in case of error,1757 * the number of bytes in the patch otherwise.1758 */1759static intparse_single_patch(struct apply_state *state,1760const char*line,1761unsigned long size,1762struct patch *patch)1763{1764unsigned long offset =0;1765unsigned long oldlines =0, newlines =0, context =0;1766struct fragment **fragp = &patch->fragments;17671768while(size >4&& !memcmp(line,"@@ -",4)) {1769struct fragment *fragment;1770int len;17711772 fragment =xcalloc(1,sizeof(*fragment));1773 fragment->linenr = state->linenr;1774 len =parse_fragment(state, line, size, patch, fragment);1775if(len <=0) {1776free(fragment);1777returnerror(_("corrupt patch at line%d"), state->linenr);1778}1779 fragment->patch = line;1780 fragment->size = len;1781 oldlines += fragment->oldlines;1782 newlines += fragment->newlines;1783 context += fragment->leading + fragment->trailing;17841785*fragp = fragment;1786 fragp = &fragment->next;17871788 offset += len;1789 line += len;1790 size -= len;1791}17921793/*1794 * If something was removed (i.e. we have old-lines) it cannot1795 * be creation, and if something was added it cannot be1796 * deletion. However, the reverse is not true; --unified=01797 * patches that only add are not necessarily creation even1798 * though they do not have any old lines, and ones that only1799 * delete are not necessarily deletion.1800 *1801 * Unfortunately, a real creation/deletion patch do _not_ have1802 * any context line by definition, so we cannot safely tell it1803 * apart with --unified=0 insanity. At least if the patch has1804 * more than one hunk it is not creation or deletion.1805 */1806if(patch->is_new <0&&1807(oldlines || (patch->fragments && patch->fragments->next)))1808 patch->is_new =0;1809if(patch->is_delete <0&&1810(newlines || (patch->fragments && patch->fragments->next)))1811 patch->is_delete =0;18121813if(0< patch->is_new && oldlines)1814returnerror(_("new file%sdepends on old contents"), patch->new_name);1815if(0< patch->is_delete && newlines)1816returnerror(_("deleted file%sstill has contents"), patch->old_name);1817if(!patch->is_delete && !newlines && context)1818fprintf_ln(stderr,1819_("** warning: "1820"file%sbecomes empty but is not deleted"),1821 patch->new_name);18221823return offset;1824}18251826staticinlineintmetadata_changes(struct patch *patch)1827{1828return patch->is_rename >0||1829 patch->is_copy >0||1830 patch->is_new >0||1831 patch->is_delete ||1832(patch->old_mode && patch->new_mode &&1833 patch->old_mode != patch->new_mode);1834}18351836static char*inflate_it(const void*data,unsigned long size,1837unsigned long inflated_size)1838{1839 git_zstream stream;1840void*out;1841int st;18421843memset(&stream,0,sizeof(stream));18441845 stream.next_in = (unsigned char*)data;1846 stream.avail_in = size;1847 stream.next_out = out =xmalloc(inflated_size);1848 stream.avail_out = inflated_size;1849git_inflate_init(&stream);1850 st =git_inflate(&stream, Z_FINISH);1851git_inflate_end(&stream);1852if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1853free(out);1854return NULL;1855}1856return out;1857}18581859/*1860 * Read a binary hunk and return a new fragment; fragment->patch1861 * points at an allocated memory that the caller must free, so1862 * it is marked as "->free_patch = 1".1863 */1864static struct fragment *parse_binary_hunk(struct apply_state *state,1865char**buf_p,1866unsigned long*sz_p,1867int*status_p,1868int*used_p)1869{1870/*1871 * Expect a line that begins with binary patch method ("literal"1872 * or "delta"), followed by the length of data before deflating.1873 * a sequence of 'length-byte' followed by base-85 encoded data1874 * should follow, terminated by a newline.1875 *1876 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1877 * and we would limit the patch line to 66 characters,1878 * so one line can fit up to 13 groups that would decode1879 * to 52 bytes max. The length byte 'A'-'Z' corresponds1880 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1881 */1882int llen, used;1883unsigned long size = *sz_p;1884char*buffer = *buf_p;1885int patch_method;1886unsigned long origlen;1887char*data = NULL;1888int hunk_size =0;1889struct fragment *frag;18901891 llen =linelen(buffer, size);1892 used = llen;18931894*status_p =0;18951896if(starts_with(buffer,"delta ")) {1897 patch_method = BINARY_DELTA_DEFLATED;1898 origlen =strtoul(buffer +6, NULL,10);1899}1900else if(starts_with(buffer,"literal ")) {1901 patch_method = BINARY_LITERAL_DEFLATED;1902 origlen =strtoul(buffer +8, NULL,10);1903}1904else1905return NULL;19061907 state->linenr++;1908 buffer += llen;1909while(1) {1910int byte_length, max_byte_length, newsize;1911 llen =linelen(buffer, size);1912 used += llen;1913 state->linenr++;1914if(llen ==1) {1915/* consume the blank line */1916 buffer++;1917 size--;1918break;1919}1920/*1921 * Minimum line is "A00000\n" which is 7-byte long,1922 * and the line length must be multiple of 5 plus 2.1923 */1924if((llen <7) || (llen-2) %5)1925goto corrupt;1926 max_byte_length = (llen -2) /5*4;1927 byte_length = *buffer;1928if('A'<= byte_length && byte_length <='Z')1929 byte_length = byte_length -'A'+1;1930else if('a'<= byte_length && byte_length <='z')1931 byte_length = byte_length -'a'+27;1932else1933goto corrupt;1934/* if the input length was not multiple of 4, we would1935 * have filler at the end but the filler should never1936 * exceed 3 bytes1937 */1938if(max_byte_length < byte_length ||1939 byte_length <= max_byte_length -4)1940goto corrupt;1941 newsize = hunk_size + byte_length;1942 data =xrealloc(data, newsize);1943if(decode_85(data + hunk_size, buffer +1, byte_length))1944goto corrupt;1945 hunk_size = newsize;1946 buffer += llen;1947 size -= llen;1948}19491950 frag =xcalloc(1,sizeof(*frag));1951 frag->patch =inflate_it(data, hunk_size, origlen);1952 frag->free_patch =1;1953if(!frag->patch)1954goto corrupt;1955free(data);1956 frag->size = origlen;1957*buf_p = buffer;1958*sz_p = size;1959*used_p = used;1960 frag->binary_patch_method = patch_method;1961return frag;19621963 corrupt:1964free(data);1965*status_p = -1;1966error(_("corrupt binary patch at line%d: %.*s"),1967 state->linenr-1, llen-1, buffer);1968return NULL;1969}19701971/*1972 * Returns:1973 * -1 in case of error,1974 * the length of the parsed binary patch otherwise1975 */1976static intparse_binary(struct apply_state *state,1977char*buffer,1978unsigned long size,1979struct patch *patch)1980{1981/*1982 * We have read "GIT binary patch\n"; what follows is a line1983 * that says the patch method (currently, either "literal" or1984 * "delta") and the length of data before deflating; a1985 * sequence of 'length-byte' followed by base-85 encoded data1986 * follows.1987 *1988 * When a binary patch is reversible, there is another binary1989 * hunk in the same format, starting with patch method (either1990 * "literal" or "delta") with the length of data, and a sequence1991 * of length-byte + base-85 encoded data, terminated with another1992 * empty line. This data, when applied to the postimage, produces1993 * the preimage.1994 */1995struct fragment *forward;1996struct fragment *reverse;1997int status;1998int used, used_1;19992000 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2001if(!forward && !status)2002/* there has to be one hunk (forward hunk) */2003returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2004if(status)2005/* otherwise we already gave an error message */2006return status;20072008 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2009if(reverse)2010 used += used_1;2011else if(status) {2012/*2013 * Not having reverse hunk is not an error, but having2014 * a corrupt reverse hunk is.2015 */2016free((void*) forward->patch);2017free(forward);2018return status;2019}2020 forward->next = reverse;2021 patch->fragments = forward;2022 patch->is_binary =1;2023return used;2024}20252026static voidprefix_one(struct apply_state *state,char**name)2027{2028char*old_name = *name;2029if(!old_name)2030return;2031*name =xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));2032free(old_name);2033}20342035static voidprefix_patch(struct apply_state *state,struct patch *p)2036{2037if(!state->prefix || p->is_toplevel_relative)2038return;2039prefix_one(state, &p->new_name);2040prefix_one(state, &p->old_name);2041}20422043/*2044 * include/exclude2045 */20462047static voidadd_name_limit(struct apply_state *state,2048const char*name,2049int exclude)2050{2051struct string_list_item *it;20522053 it =string_list_append(&state->limit_by_name, name);2054 it->util = exclude ? NULL : (void*)1;2055}20562057static intuse_patch(struct apply_state *state,struct patch *p)2058{2059const char*pathname = p->new_name ? p->new_name : p->old_name;2060int i;20612062/* Paths outside are not touched regardless of "--include" */2063if(0< state->prefix_length) {2064int pathlen =strlen(pathname);2065if(pathlen <= state->prefix_length ||2066memcmp(state->prefix, pathname, state->prefix_length))2067return0;2068}20692070/* See if it matches any of exclude/include rule */2071for(i =0; i < state->limit_by_name.nr; i++) {2072struct string_list_item *it = &state->limit_by_name.items[i];2073if(!wildmatch(it->string, pathname,0, NULL))2074return(it->util != NULL);2075}20762077/*2078 * If we had any include, a path that does not match any rule is2079 * not used. Otherwise, we saw bunch of exclude rules (or none)2080 * and such a path is used.2081 */2082return!state->has_include;2083}20842085/*2086 * Read the patch text in "buffer" that extends for "size" bytes; stop2087 * reading after seeing a single patch (i.e. changes to a single file).2088 * Create fragments (i.e. patch hunks) and hang them to the given patch.2089 *2090 * Returns:2091 * -1 if no header was found or parse_binary() failed,2092 * -128 on another error,2093 * the number of bytes consumed otherwise,2094 * so that the caller can call us again for the next patch.2095 */2096static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2097{2098int hdrsize, patchsize;2099int offset =find_header(state, buffer, size, &hdrsize, patch);21002101if(offset <0)2102return offset;21032104prefix_patch(state, patch);21052106if(!use_patch(state, patch))2107 patch->ws_rule =0;2108else2109 patch->ws_rule =whitespace_rule(patch->new_name2110? patch->new_name2111: patch->old_name);21122113 patchsize =parse_single_patch(state,2114 buffer + offset + hdrsize,2115 size - offset - hdrsize,2116 patch);21172118if(patchsize <0)2119return-128;21202121if(!patchsize) {2122static const char git_binary[] ="GIT binary patch\n";2123int hd = hdrsize + offset;2124unsigned long llen =linelen(buffer + hd, size - hd);21252126if(llen ==sizeof(git_binary) -1&&2127!memcmp(git_binary, buffer + hd, llen)) {2128int used;2129 state->linenr++;2130 used =parse_binary(state, buffer + hd + llen,2131 size - hd - llen, patch);2132if(used <0)2133return-1;2134if(used)2135 patchsize = used + llen;2136else2137 patchsize =0;2138}2139else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2140static const char*binhdr[] = {2141"Binary files ",2142"Files ",2143 NULL,2144};2145int i;2146for(i =0; binhdr[i]; i++) {2147int len =strlen(binhdr[i]);2148if(len < size - hd &&2149!memcmp(binhdr[i], buffer + hd, len)) {2150 state->linenr++;2151 patch->is_binary =1;2152 patchsize = llen;2153break;2154}2155}2156}21572158/* Empty patch cannot be applied if it is a text patch2159 * without metadata change. A binary patch appears2160 * empty to us here.2161 */2162if((state->apply || state->check) &&2163(!patch->is_binary && !metadata_changes(patch))) {2164error(_("patch with only garbage at line%d"), state->linenr);2165return-128;2166}2167}21682169return offset + hdrsize + patchsize;2170}21712172#define swap(a,b) myswap((a),(b),sizeof(a))21732174#define myswap(a, b, size) do { \2175 unsigned char mytmp[size]; \2176 memcpy(mytmp, &a, size); \2177 memcpy(&a, &b, size); \2178 memcpy(&b, mytmp, size); \2179} while (0)21802181static voidreverse_patches(struct patch *p)2182{2183for(; p; p = p->next) {2184struct fragment *frag = p->fragments;21852186swap(p->new_name, p->old_name);2187swap(p->new_mode, p->old_mode);2188swap(p->is_new, p->is_delete);2189swap(p->lines_added, p->lines_deleted);2190swap(p->old_sha1_prefix, p->new_sha1_prefix);21912192for(; frag; frag = frag->next) {2193swap(frag->newpos, frag->oldpos);2194swap(frag->newlines, frag->oldlines);2195}2196}2197}21982199static const char pluses[] =2200"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2201static const char minuses[]=2202"----------------------------------------------------------------------";22032204static voidshow_stats(struct apply_state *state,struct patch *patch)2205{2206struct strbuf qname = STRBUF_INIT;2207char*cp = patch->new_name ? patch->new_name : patch->old_name;2208int max, add, del;22092210quote_c_style(cp, &qname, NULL,0);22112212/*2213 * "scale" the filename2214 */2215 max = state->max_len;2216if(max >50)2217 max =50;22182219if(qname.len > max) {2220 cp =strchr(qname.buf + qname.len +3- max,'/');2221if(!cp)2222 cp = qname.buf + qname.len +3- max;2223strbuf_splice(&qname,0, cp - qname.buf,"...",3);2224}22252226if(patch->is_binary) {2227printf(" %-*s | Bin\n", max, qname.buf);2228strbuf_release(&qname);2229return;2230}22312232printf(" %-*s |", max, qname.buf);2233strbuf_release(&qname);22342235/*2236 * scale the add/delete2237 */2238 max = max + state->max_change >70?70- max : state->max_change;2239 add = patch->lines_added;2240 del = patch->lines_deleted;22412242if(state->max_change >0) {2243int total = ((add + del) * max + state->max_change /2) / state->max_change;2244 add = (add * max + state->max_change /2) / state->max_change;2245 del = total - add;2246}2247printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2248 add, pluses, del, minuses);2249}22502251static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)2252{2253switch(st->st_mode & S_IFMT) {2254case S_IFLNK:2255if(strbuf_readlink(buf, path, st->st_size) <0)2256returnerror(_("unable to read symlink%s"), path);2257return0;2258case S_IFREG:2259if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2260returnerror(_("unable to open or read%s"), path);2261convert_to_git(path, buf->buf, buf->len, buf,0);2262return0;2263default:2264return-1;2265}2266}22672268/*2269 * Update the preimage, and the common lines in postimage,2270 * from buffer buf of length len. If postlen is 0 the postimage2271 * is updated in place, otherwise it's updated on a new buffer2272 * of length postlen2273 */22742275static voidupdate_pre_post_images(struct image *preimage,2276struct image *postimage,2277char*buf,2278size_t len,size_t postlen)2279{2280int i, ctx, reduced;2281char*new, *old, *fixed;2282struct image fixed_preimage;22832284/*2285 * Update the preimage with whitespace fixes. Note that we2286 * are not losing preimage->buf -- apply_one_fragment() will2287 * free "oldlines".2288 */2289prepare_image(&fixed_preimage, buf, len,1);2290assert(postlen2291? fixed_preimage.nr == preimage->nr2292: fixed_preimage.nr <= preimage->nr);2293for(i =0; i < fixed_preimage.nr; i++)2294 fixed_preimage.line[i].flag = preimage->line[i].flag;2295free(preimage->line_allocated);2296*preimage = fixed_preimage;22972298/*2299 * Adjust the common context lines in postimage. This can be2300 * done in-place when we are shrinking it with whitespace2301 * fixing, but needs a new buffer when ignoring whitespace or2302 * expanding leading tabs to spaces.2303 *2304 * We trust the caller to tell us if the update can be done2305 * in place (postlen==0) or not.2306 */2307 old = postimage->buf;2308if(postlen)2309new= postimage->buf =xmalloc(postlen);2310else2311new= old;2312 fixed = preimage->buf;23132314for(i = reduced = ctx =0; i < postimage->nr; i++) {2315size_t l_len = postimage->line[i].len;2316if(!(postimage->line[i].flag & LINE_COMMON)) {2317/* an added line -- no counterparts in preimage */2318memmove(new, old, l_len);2319 old += l_len;2320new+= l_len;2321continue;2322}23232324/* a common context -- skip it in the original postimage */2325 old += l_len;23262327/* and find the corresponding one in the fixed preimage */2328while(ctx < preimage->nr &&2329!(preimage->line[ctx].flag & LINE_COMMON)) {2330 fixed += preimage->line[ctx].len;2331 ctx++;2332}23332334/*2335 * preimage is expected to run out, if the caller2336 * fixed addition of trailing blank lines.2337 */2338if(preimage->nr <= ctx) {2339 reduced++;2340continue;2341}23422343/* and copy it in, while fixing the line length */2344 l_len = preimage->line[ctx].len;2345memcpy(new, fixed, l_len);2346new+= l_len;2347 fixed += l_len;2348 postimage->line[i].len = l_len;2349 ctx++;2350}23512352if(postlen2353? postlen <new- postimage->buf2354: postimage->len <new- postimage->buf)2355die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2356(int)postlen, (int) postimage->len, (int)(new- postimage->buf));23572358/* Fix the length of the whole thing */2359 postimage->len =new- postimage->buf;2360 postimage->nr -= reduced;2361}23622363static intline_by_line_fuzzy_match(struct image *img,2364struct image *preimage,2365struct image *postimage,2366unsigned longtry,2367int try_lno,2368int preimage_limit)2369{2370int i;2371size_t imgoff =0;2372size_t preoff =0;2373size_t postlen = postimage->len;2374size_t extra_chars;2375char*buf;2376char*preimage_eof;2377char*preimage_end;2378struct strbuf fixed;2379char*fixed_buf;2380size_t fixed_len;23812382for(i =0; i < preimage_limit; i++) {2383size_t prelen = preimage->line[i].len;2384size_t imglen = img->line[try_lno+i].len;23852386if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,2387 preimage->buf + preoff, prelen))2388return0;2389if(preimage->line[i].flag & LINE_COMMON)2390 postlen += imglen - prelen;2391 imgoff += imglen;2392 preoff += prelen;2393}23942395/*2396 * Ok, the preimage matches with whitespace fuzz.2397 *2398 * imgoff now holds the true length of the target that2399 * matches the preimage before the end of the file.2400 *2401 * Count the number of characters in the preimage that fall2402 * beyond the end of the file and make sure that all of them2403 * are whitespace characters. (This can only happen if2404 * we are removing blank lines at the end of the file.)2405 */2406 buf = preimage_eof = preimage->buf + preoff;2407for( ; i < preimage->nr; i++)2408 preoff += preimage->line[i].len;2409 preimage_end = preimage->buf + preoff;2410for( ; buf < preimage_end; buf++)2411if(!isspace(*buf))2412return0;24132414/*2415 * Update the preimage and the common postimage context2416 * lines to use the same whitespace as the target.2417 * If whitespace is missing in the target (i.e.2418 * if the preimage extends beyond the end of the file),2419 * use the whitespace from the preimage.2420 */2421 extra_chars = preimage_end - preimage_eof;2422strbuf_init(&fixed, imgoff + extra_chars);2423strbuf_add(&fixed, img->buf +try, imgoff);2424strbuf_add(&fixed, preimage_eof, extra_chars);2425 fixed_buf =strbuf_detach(&fixed, &fixed_len);2426update_pre_post_images(preimage, postimage,2427 fixed_buf, fixed_len, postlen);2428return1;2429}24302431static intmatch_fragment(struct apply_state *state,2432struct image *img,2433struct image *preimage,2434struct image *postimage,2435unsigned longtry,2436int try_lno,2437unsigned ws_rule,2438int match_beginning,int match_end)2439{2440int i;2441char*fixed_buf, *buf, *orig, *target;2442struct strbuf fixed;2443size_t fixed_len, postlen;2444int preimage_limit;24452446if(preimage->nr + try_lno <= img->nr) {2447/*2448 * The hunk falls within the boundaries of img.2449 */2450 preimage_limit = preimage->nr;2451if(match_end && (preimage->nr + try_lno != img->nr))2452return0;2453}else if(state->ws_error_action == correct_ws_error &&2454(ws_rule & WS_BLANK_AT_EOF)) {2455/*2456 * This hunk extends beyond the end of img, and we are2457 * removing blank lines at the end of the file. This2458 * many lines from the beginning of the preimage must2459 * match with img, and the remainder of the preimage2460 * must be blank.2461 */2462 preimage_limit = img->nr - try_lno;2463}else{2464/*2465 * The hunk extends beyond the end of the img and2466 * we are not removing blanks at the end, so we2467 * should reject the hunk at this position.2468 */2469return0;2470}24712472if(match_beginning && try_lno)2473return0;24742475/* Quick hash check */2476for(i =0; i < preimage_limit; i++)2477if((img->line[try_lno + i].flag & LINE_PATCHED) ||2478(preimage->line[i].hash != img->line[try_lno + i].hash))2479return0;24802481if(preimage_limit == preimage->nr) {2482/*2483 * Do we have an exact match? If we were told to match2484 * at the end, size must be exactly at try+fragsize,2485 * otherwise try+fragsize must be still within the preimage,2486 * and either case, the old piece should match the preimage2487 * exactly.2488 */2489if((match_end2490? (try+ preimage->len == img->len)2491: (try+ preimage->len <= img->len)) &&2492!memcmp(img->buf +try, preimage->buf, preimage->len))2493return1;2494}else{2495/*2496 * The preimage extends beyond the end of img, so2497 * there cannot be an exact match.2498 *2499 * There must be one non-blank context line that match2500 * a line before the end of img.2501 */2502char*buf_end;25032504 buf = preimage->buf;2505 buf_end = buf;2506for(i =0; i < preimage_limit; i++)2507 buf_end += preimage->line[i].len;25082509for( ; buf < buf_end; buf++)2510if(!isspace(*buf))2511break;2512if(buf == buf_end)2513return0;2514}25152516/*2517 * No exact match. If we are ignoring whitespace, run a line-by-line2518 * fuzzy matching. We collect all the line length information because2519 * we need it to adjust whitespace if we match.2520 */2521if(state->ws_ignore_action == ignore_ws_change)2522returnline_by_line_fuzzy_match(img, preimage, postimage,2523try, try_lno, preimage_limit);25242525if(state->ws_error_action != correct_ws_error)2526return0;25272528/*2529 * The hunk does not apply byte-by-byte, but the hash says2530 * it might with whitespace fuzz. We weren't asked to2531 * ignore whitespace, we were asked to correct whitespace2532 * errors, so let's try matching after whitespace correction.2533 *2534 * While checking the preimage against the target, whitespace2535 * errors in both fixed, we count how large the corresponding2536 * postimage needs to be. The postimage prepared by2537 * apply_one_fragment() has whitespace errors fixed on added2538 * lines already, but the common lines were propagated as-is,2539 * which may become longer when their whitespace errors are2540 * fixed.2541 */25422543/* First count added lines in postimage */2544 postlen =0;2545for(i =0; i < postimage->nr; i++) {2546if(!(postimage->line[i].flag & LINE_COMMON))2547 postlen += postimage->line[i].len;2548}25492550/*2551 * The preimage may extend beyond the end of the file,2552 * but in this loop we will only handle the part of the2553 * preimage that falls within the file.2554 */2555strbuf_init(&fixed, preimage->len +1);2556 orig = preimage->buf;2557 target = img->buf +try;2558for(i =0; i < preimage_limit; i++) {2559size_t oldlen = preimage->line[i].len;2560size_t tgtlen = img->line[try_lno + i].len;2561size_t fixstart = fixed.len;2562struct strbuf tgtfix;2563int match;25642565/* Try fixing the line in the preimage */2566ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25672568/* Try fixing the line in the target */2569strbuf_init(&tgtfix, tgtlen);2570ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25712572/*2573 * If they match, either the preimage was based on2574 * a version before our tree fixed whitespace breakage,2575 * or we are lacking a whitespace-fix patch the tree2576 * the preimage was based on already had (i.e. target2577 * has whitespace breakage, the preimage doesn't).2578 * In either case, we are fixing the whitespace breakages2579 * so we might as well take the fix together with their2580 * real change.2581 */2582 match = (tgtfix.len == fixed.len - fixstart &&2583!memcmp(tgtfix.buf, fixed.buf + fixstart,2584 fixed.len - fixstart));25852586/* Add the length if this is common with the postimage */2587if(preimage->line[i].flag & LINE_COMMON)2588 postlen += tgtfix.len;25892590strbuf_release(&tgtfix);2591if(!match)2592goto unmatch_exit;25932594 orig += oldlen;2595 target += tgtlen;2596}259725982599/*2600 * Now handle the lines in the preimage that falls beyond the2601 * end of the file (if any). They will only match if they are2602 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2603 * false).2604 */2605for( ; i < preimage->nr; i++) {2606size_t fixstart = fixed.len;/* start of the fixed preimage */2607size_t oldlen = preimage->line[i].len;2608int j;26092610/* Try fixing the line in the preimage */2611ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26122613for(j = fixstart; j < fixed.len; j++)2614if(!isspace(fixed.buf[j]))2615goto unmatch_exit;26162617 orig += oldlen;2618}26192620/*2621 * Yes, the preimage is based on an older version that still2622 * has whitespace breakages unfixed, and fixing them makes the2623 * hunk match. Update the context lines in the postimage.2624 */2625 fixed_buf =strbuf_detach(&fixed, &fixed_len);2626if(postlen < postimage->len)2627 postlen =0;2628update_pre_post_images(preimage, postimage,2629 fixed_buf, fixed_len, postlen);2630return1;26312632 unmatch_exit:2633strbuf_release(&fixed);2634return0;2635}26362637static intfind_pos(struct apply_state *state,2638struct image *img,2639struct image *preimage,2640struct image *postimage,2641int line,2642unsigned ws_rule,2643int match_beginning,int match_end)2644{2645int i;2646unsigned long backwards, forwards,try;2647int backwards_lno, forwards_lno, try_lno;26482649/*2650 * If match_beginning or match_end is specified, there is no2651 * point starting from a wrong line that will never match and2652 * wander around and wait for a match at the specified end.2653 */2654if(match_beginning)2655 line =0;2656else if(match_end)2657 line = img->nr - preimage->nr;26582659/*2660 * Because the comparison is unsigned, the following test2661 * will also take care of a negative line number that can2662 * result when match_end and preimage is larger than the target.2663 */2664if((size_t) line > img->nr)2665 line = img->nr;26662667try=0;2668for(i =0; i < line; i++)2669try+= img->line[i].len;26702671/*2672 * There's probably some smart way to do this, but I'll leave2673 * that to the smart and beautiful people. I'm simple and stupid.2674 */2675 backwards =try;2676 backwards_lno = line;2677 forwards =try;2678 forwards_lno = line;2679 try_lno = line;26802681for(i =0; ; i++) {2682if(match_fragment(state, img, preimage, postimage,2683try, try_lno, ws_rule,2684 match_beginning, match_end))2685return try_lno;26862687 again:2688if(backwards_lno ==0&& forwards_lno == img->nr)2689break;26902691if(i &1) {2692if(backwards_lno ==0) {2693 i++;2694goto again;2695}2696 backwards_lno--;2697 backwards -= img->line[backwards_lno].len;2698try= backwards;2699 try_lno = backwards_lno;2700}else{2701if(forwards_lno == img->nr) {2702 i++;2703goto again;2704}2705 forwards += img->line[forwards_lno].len;2706 forwards_lno++;2707try= forwards;2708 try_lno = forwards_lno;2709}27102711}2712return-1;2713}27142715static voidremove_first_line(struct image *img)2716{2717 img->buf += img->line[0].len;2718 img->len -= img->line[0].len;2719 img->line++;2720 img->nr--;2721}27222723static voidremove_last_line(struct image *img)2724{2725 img->len -= img->line[--img->nr].len;2726}27272728/*2729 * The change from "preimage" and "postimage" has been found to2730 * apply at applied_pos (counts in line numbers) in "img".2731 * Update "img" to remove "preimage" and replace it with "postimage".2732 */2733static voidupdate_image(struct apply_state *state,2734struct image *img,2735int applied_pos,2736struct image *preimage,2737struct image *postimage)2738{2739/*2740 * remove the copy of preimage at offset in img2741 * and replace it with postimage2742 */2743int i, nr;2744size_t remove_count, insert_count, applied_at =0;2745char*result;2746int preimage_limit;27472748/*2749 * If we are removing blank lines at the end of img,2750 * the preimage may extend beyond the end.2751 * If that is the case, we must be careful only to2752 * remove the part of the preimage that falls within2753 * the boundaries of img. Initialize preimage_limit2754 * to the number of lines in the preimage that falls2755 * within the boundaries.2756 */2757 preimage_limit = preimage->nr;2758if(preimage_limit > img->nr - applied_pos)2759 preimage_limit = img->nr - applied_pos;27602761for(i =0; i < applied_pos; i++)2762 applied_at += img->line[i].len;27632764 remove_count =0;2765for(i =0; i < preimage_limit; i++)2766 remove_count += img->line[applied_pos + i].len;2767 insert_count = postimage->len;27682769/* Adjust the contents */2770 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2771memcpy(result, img->buf, applied_at);2772memcpy(result + applied_at, postimage->buf, postimage->len);2773memcpy(result + applied_at + postimage->len,2774 img->buf + (applied_at + remove_count),2775 img->len - (applied_at + remove_count));2776free(img->buf);2777 img->buf = result;2778 img->len += insert_count - remove_count;2779 result[img->len] ='\0';27802781/* Adjust the line table */2782 nr = img->nr + postimage->nr - preimage_limit;2783if(preimage_limit < postimage->nr) {2784/*2785 * NOTE: this knows that we never call remove_first_line()2786 * on anything other than pre/post image.2787 */2788REALLOC_ARRAY(img->line, nr);2789 img->line_allocated = img->line;2790}2791if(preimage_limit != postimage->nr)2792memmove(img->line + applied_pos + postimage->nr,2793 img->line + applied_pos + preimage_limit,2794(img->nr - (applied_pos + preimage_limit)) *2795sizeof(*img->line));2796memcpy(img->line + applied_pos,2797 postimage->line,2798 postimage->nr *sizeof(*img->line));2799if(!state->allow_overlap)2800for(i =0; i < postimage->nr; i++)2801 img->line[applied_pos + i].flag |= LINE_PATCHED;2802 img->nr = nr;2803}28042805/*2806 * Use the patch-hunk text in "frag" to prepare two images (preimage and2807 * postimage) for the hunk. Find lines that match "preimage" in "img" and2808 * replace the part of "img" with "postimage" text.2809 */2810static intapply_one_fragment(struct apply_state *state,2811struct image *img,struct fragment *frag,2812int inaccurate_eof,unsigned ws_rule,2813int nth_fragment)2814{2815int match_beginning, match_end;2816const char*patch = frag->patch;2817int size = frag->size;2818char*old, *oldlines;2819struct strbuf newlines;2820int new_blank_lines_at_end =0;2821int found_new_blank_lines_at_end =0;2822int hunk_linenr = frag->linenr;2823unsigned long leading, trailing;2824int pos, applied_pos;2825struct image preimage;2826struct image postimage;28272828memset(&preimage,0,sizeof(preimage));2829memset(&postimage,0,sizeof(postimage));2830 oldlines =xmalloc(size);2831strbuf_init(&newlines, size);28322833 old = oldlines;2834while(size >0) {2835char first;2836int len =linelen(patch, size);2837int plen;2838int added_blank_line =0;2839int is_blank_context =0;2840size_t start;28412842if(!len)2843break;28442845/*2846 * "plen" is how much of the line we should use for2847 * the actual patch data. Normally we just remove the2848 * first character on the line, but if the line is2849 * followed by "\ No newline", then we also remove the2850 * last one (which is the newline, of course).2851 */2852 plen = len -1;2853if(len < size && patch[len] =='\\')2854 plen--;2855 first = *patch;2856if(state->apply_in_reverse) {2857if(first =='-')2858 first ='+';2859else if(first =='+')2860 first ='-';2861}28622863switch(first) {2864case'\n':2865/* Newer GNU diff, empty context line */2866if(plen <0)2867/* ... followed by '\No newline'; nothing */2868break;2869*old++ ='\n';2870strbuf_addch(&newlines,'\n');2871add_line_info(&preimage,"\n",1, LINE_COMMON);2872add_line_info(&postimage,"\n",1, LINE_COMMON);2873 is_blank_context =1;2874break;2875case' ':2876if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2877ws_blank_line(patch +1, plen, ws_rule))2878 is_blank_context =1;2879case'-':2880memcpy(old, patch +1, plen);2881add_line_info(&preimage, old, plen,2882(first ==' '? LINE_COMMON :0));2883 old += plen;2884if(first =='-')2885break;2886/* Fall-through for ' ' */2887case'+':2888/* --no-add does not add new lines */2889if(first =='+'&& state->no_add)2890break;28912892 start = newlines.len;2893if(first !='+'||2894!state->whitespace_error ||2895 state->ws_error_action != correct_ws_error) {2896strbuf_add(&newlines, patch +1, plen);2897}2898else{2899ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2900}2901add_line_info(&postimage, newlines.buf + start, newlines.len - start,2902(first =='+'?0: LINE_COMMON));2903if(first =='+'&&2904(ws_rule & WS_BLANK_AT_EOF) &&2905ws_blank_line(patch +1, plen, ws_rule))2906 added_blank_line =1;2907break;2908case'@':case'\\':2909/* Ignore it, we already handled it */2910break;2911default:2912if(state->apply_verbosely)2913error(_("invalid start of line: '%c'"), first);2914 applied_pos = -1;2915goto out;2916}2917if(added_blank_line) {2918if(!new_blank_lines_at_end)2919 found_new_blank_lines_at_end = hunk_linenr;2920 new_blank_lines_at_end++;2921}2922else if(is_blank_context)2923;2924else2925 new_blank_lines_at_end =0;2926 patch += len;2927 size -= len;2928 hunk_linenr++;2929}2930if(inaccurate_eof &&2931 old > oldlines && old[-1] =='\n'&&2932 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2933 old--;2934strbuf_setlen(&newlines, newlines.len -1);2935}29362937 leading = frag->leading;2938 trailing = frag->trailing;29392940/*2941 * A hunk to change lines at the beginning would begin with2942 * @@ -1,L +N,M @@2943 * but we need to be careful. -U0 that inserts before the second2944 * line also has this pattern.2945 *2946 * And a hunk to add to an empty file would begin with2947 * @@ -0,0 +N,M @@2948 *2949 * In other words, a hunk that is (frag->oldpos <= 1) with or2950 * without leading context must match at the beginning.2951 */2952 match_beginning = (!frag->oldpos ||2953(frag->oldpos ==1&& !state->unidiff_zero));29542955/*2956 * A hunk without trailing lines must match at the end.2957 * However, we simply cannot tell if a hunk must match end2958 * from the lack of trailing lines if the patch was generated2959 * with unidiff without any context.2960 */2961 match_end = !state->unidiff_zero && !trailing;29622963 pos = frag->newpos ? (frag->newpos -1) :0;2964 preimage.buf = oldlines;2965 preimage.len = old - oldlines;2966 postimage.buf = newlines.buf;2967 postimage.len = newlines.len;2968 preimage.line = preimage.line_allocated;2969 postimage.line = postimage.line_allocated;29702971for(;;) {29722973 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2974 ws_rule, match_beginning, match_end);29752976if(applied_pos >=0)2977break;29782979/* Am I at my context limits? */2980if((leading <= state->p_context) && (trailing <= state->p_context))2981break;2982if(match_beginning || match_end) {2983 match_beginning = match_end =0;2984continue;2985}29862987/*2988 * Reduce the number of context lines; reduce both2989 * leading and trailing if they are equal otherwise2990 * just reduce the larger context.2991 */2992if(leading >= trailing) {2993remove_first_line(&preimage);2994remove_first_line(&postimage);2995 pos--;2996 leading--;2997}2998if(trailing > leading) {2999remove_last_line(&preimage);3000remove_last_line(&postimage);3001 trailing--;3002}3003}30043005if(applied_pos >=0) {3006if(new_blank_lines_at_end &&3007 preimage.nr + applied_pos >= img->nr &&3008(ws_rule & WS_BLANK_AT_EOF) &&3009 state->ws_error_action != nowarn_ws_error) {3010record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3011 found_new_blank_lines_at_end);3012if(state->ws_error_action == correct_ws_error) {3013while(new_blank_lines_at_end--)3014remove_last_line(&postimage);3015}3016/*3017 * We would want to prevent write_out_results()3018 * from taking place in apply_patch() that follows3019 * the callchain led us here, which is:3020 * apply_patch->check_patch_list->check_patch->3021 * apply_data->apply_fragments->apply_one_fragment3022 */3023if(state->ws_error_action == die_on_ws_error)3024 state->apply =0;3025}30263027if(state->apply_verbosely && applied_pos != pos) {3028int offset = applied_pos - pos;3029if(state->apply_in_reverse)3030 offset =0- offset;3031fprintf_ln(stderr,3032Q_("Hunk #%dsucceeded at%d(offset%dline).",3033"Hunk #%dsucceeded at%d(offset%dlines).",3034 offset),3035 nth_fragment, applied_pos +1, offset);3036}30373038/*3039 * Warn if it was necessary to reduce the number3040 * of context lines.3041 */3042if((leading != frag->leading) ||3043(trailing != frag->trailing))3044fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3045" to apply fragment at%d"),3046 leading, trailing, applied_pos+1);3047update_image(state, img, applied_pos, &preimage, &postimage);3048}else{3049if(state->apply_verbosely)3050error(_("while searching for:\n%.*s"),3051(int)(old - oldlines), oldlines);3052}30533054out:3055free(oldlines);3056strbuf_release(&newlines);3057free(preimage.line_allocated);3058free(postimage.line_allocated);30593060return(applied_pos <0);3061}30623063static intapply_binary_fragment(struct apply_state *state,3064struct image *img,3065struct patch *patch)3066{3067struct fragment *fragment = patch->fragments;3068unsigned long len;3069void*dst;30703071if(!fragment)3072returnerror(_("missing binary patch data for '%s'"),3073 patch->new_name ?3074 patch->new_name :3075 patch->old_name);30763077/* Binary patch is irreversible without the optional second hunk */3078if(state->apply_in_reverse) {3079if(!fragment->next)3080returnerror("cannot reverse-apply a binary patch "3081"without the reverse hunk to '%s'",3082 patch->new_name3083? patch->new_name : patch->old_name);3084 fragment = fragment->next;3085}3086switch(fragment->binary_patch_method) {3087case BINARY_DELTA_DEFLATED:3088 dst =patch_delta(img->buf, img->len, fragment->patch,3089 fragment->size, &len);3090if(!dst)3091return-1;3092clear_image(img);3093 img->buf = dst;3094 img->len = len;3095return0;3096case BINARY_LITERAL_DEFLATED:3097clear_image(img);3098 img->len = fragment->size;3099 img->buf =xmemdupz(fragment->patch, img->len);3100return0;3101}3102return-1;3103}31043105/*3106 * Replace "img" with the result of applying the binary patch.3107 * The binary patch data itself in patch->fragment is still kept3108 * but the preimage prepared by the caller in "img" is freed here3109 * or in the helper function apply_binary_fragment() this calls.3110 */3111static intapply_binary(struct apply_state *state,3112struct image *img,3113struct patch *patch)3114{3115const char*name = patch->old_name ? patch->old_name : patch->new_name;3116unsigned char sha1[20];31173118/*3119 * For safety, we require patch index line to contain3120 * full 40-byte textual SHA1 for old and new, at least for now.3121 */3122if(strlen(patch->old_sha1_prefix) !=40||3123strlen(patch->new_sha1_prefix) !=40||3124get_sha1_hex(patch->old_sha1_prefix, sha1) ||3125get_sha1_hex(patch->new_sha1_prefix, sha1))3126returnerror("cannot apply binary patch to '%s' "3127"without full index line", name);31283129if(patch->old_name) {3130/*3131 * See if the old one matches what the patch3132 * applies to.3133 */3134hash_sha1_file(img->buf, img->len, blob_type, sha1);3135if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))3136returnerror("the patch applies to '%s' (%s), "3137"which does not match the "3138"current contents.",3139 name,sha1_to_hex(sha1));3140}3141else{3142/* Otherwise, the old one must be empty. */3143if(img->len)3144returnerror("the patch applies to an empty "3145"'%s' but it is not empty", name);3146}31473148get_sha1_hex(patch->new_sha1_prefix, sha1);3149if(is_null_sha1(sha1)) {3150clear_image(img);3151return0;/* deletion patch */3152}31533154if(has_sha1_file(sha1)) {3155/* We already have the postimage */3156enum object_type type;3157unsigned long size;3158char*result;31593160 result =read_sha1_file(sha1, &type, &size);3161if(!result)3162returnerror("the necessary postimage%sfor "3163"'%s' cannot be read",3164 patch->new_sha1_prefix, name);3165clear_image(img);3166 img->buf = result;3167 img->len = size;3168}else{3169/*3170 * We have verified buf matches the preimage;3171 * apply the patch data to it, which is stored3172 * in the patch->fragments->{patch,size}.3173 */3174if(apply_binary_fragment(state, img, patch))3175returnerror(_("binary patch does not apply to '%s'"),3176 name);31773178/* verify that the result matches */3179hash_sha1_file(img->buf, img->len, blob_type, sha1);3180if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))3181returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3182 name, patch->new_sha1_prefix,sha1_to_hex(sha1));3183}31843185return0;3186}31873188static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3189{3190struct fragment *frag = patch->fragments;3191const char*name = patch->old_name ? patch->old_name : patch->new_name;3192unsigned ws_rule = patch->ws_rule;3193unsigned inaccurate_eof = patch->inaccurate_eof;3194int nth =0;31953196if(patch->is_binary)3197returnapply_binary(state, img, patch);31983199while(frag) {3200 nth++;3201if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3202error(_("patch failed:%s:%ld"), name, frag->oldpos);3203if(!state->apply_with_reject)3204return-1;3205 frag->rejected =1;3206}3207 frag = frag->next;3208}3209return0;3210}32113212static intread_blob_object(struct strbuf *buf,const unsigned char*sha1,unsigned mode)3213{3214if(S_ISGITLINK(mode)) {3215strbuf_grow(buf,100);3216strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(sha1));3217}else{3218enum object_type type;3219unsigned long sz;3220char*result;32213222 result =read_sha1_file(sha1, &type, &sz);3223if(!result)3224return-1;3225/* XXX read_sha1_file NUL-terminates */3226strbuf_attach(buf, result, sz, sz +1);3227}3228return0;3229}32303231static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3232{3233if(!ce)3234return0;3235returnread_blob_object(buf, ce->sha1, ce->ce_mode);3236}32373238static struct patch *in_fn_table(struct apply_state *state,const char*name)3239{3240struct string_list_item *item;32413242if(name == NULL)3243return NULL;32443245 item =string_list_lookup(&state->fn_table, name);3246if(item != NULL)3247return(struct patch *)item->util;32483249return NULL;3250}32513252/*3253 * item->util in the filename table records the status of the path.3254 * Usually it points at a patch (whose result records the contents3255 * of it after applying it), but it could be PATH_WAS_DELETED for a3256 * path that a previously applied patch has already removed, or3257 * PATH_TO_BE_DELETED for a path that a later patch would remove.3258 *3259 * The latter is needed to deal with a case where two paths A and B3260 * are swapped by first renaming A to B and then renaming B to A;3261 * moving A to B should not be prevented due to presence of B as we3262 * will remove it in a later patch.3263 */3264#define PATH_TO_BE_DELETED ((struct patch *) -2)3265#define PATH_WAS_DELETED ((struct patch *) -1)32663267static intto_be_deleted(struct patch *patch)3268{3269return patch == PATH_TO_BE_DELETED;3270}32713272static intwas_deleted(struct patch *patch)3273{3274return patch == PATH_WAS_DELETED;3275}32763277static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3278{3279struct string_list_item *item;32803281/*3282 * Always add new_name unless patch is a deletion3283 * This should cover the cases for normal diffs,3284 * file creations and copies3285 */3286if(patch->new_name != NULL) {3287 item =string_list_insert(&state->fn_table, patch->new_name);3288 item->util = patch;3289}32903291/*3292 * store a failure on rename/deletion cases because3293 * later chunks shouldn't patch old names3294 */3295if((patch->new_name == NULL) || (patch->is_rename)) {3296 item =string_list_insert(&state->fn_table, patch->old_name);3297 item->util = PATH_WAS_DELETED;3298}3299}33003301static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3302{3303/*3304 * store information about incoming file deletion3305 */3306while(patch) {3307if((patch->new_name == NULL) || (patch->is_rename)) {3308struct string_list_item *item;3309 item =string_list_insert(&state->fn_table, patch->old_name);3310 item->util = PATH_TO_BE_DELETED;3311}3312 patch = patch->next;3313}3314}33153316static intcheckout_target(struct index_state *istate,3317struct cache_entry *ce,struct stat *st)3318{3319struct checkout costate;33203321memset(&costate,0,sizeof(costate));3322 costate.base_dir ="";3323 costate.refresh_cache =1;3324 costate.istate = istate;3325if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3326returnerror(_("cannot checkout%s"), ce->name);3327return0;3328}33293330static struct patch *previous_patch(struct apply_state *state,3331struct patch *patch,3332int*gone)3333{3334struct patch *previous;33353336*gone =0;3337if(patch->is_copy || patch->is_rename)3338return NULL;/* "git" patches do not depend on the order */33393340 previous =in_fn_table(state, patch->old_name);3341if(!previous)3342return NULL;33433344if(to_be_deleted(previous))3345return NULL;/* the deletion hasn't happened yet */33463347if(was_deleted(previous))3348*gone =1;33493350return previous;3351}33523353static intverify_index_match(const struct cache_entry *ce,struct stat *st)3354{3355if(S_ISGITLINK(ce->ce_mode)) {3356if(!S_ISDIR(st->st_mode))3357return-1;3358return0;3359}3360returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3361}33623363#define SUBMODULE_PATCH_WITHOUT_INDEX 133643365static intload_patch_target(struct apply_state *state,3366struct strbuf *buf,3367const struct cache_entry *ce,3368struct stat *st,3369const char*name,3370unsigned expected_mode)3371{3372if(state->cached || state->check_index) {3373if(read_file_or_gitlink(ce, buf))3374returnerror(_("failed to read%s"), name);3375}else if(name) {3376if(S_ISGITLINK(expected_mode)) {3377if(ce)3378returnread_file_or_gitlink(ce, buf);3379else3380return SUBMODULE_PATCH_WITHOUT_INDEX;3381}else if(has_symlink_leading_path(name,strlen(name))) {3382returnerror(_("reading from '%s' beyond a symbolic link"), name);3383}else{3384if(read_old_data(st, name, buf))3385returnerror(_("failed to read%s"), name);3386}3387}3388return0;3389}33903391/*3392 * We are about to apply "patch"; populate the "image" with the3393 * current version we have, from the working tree or from the index,3394 * depending on the situation e.g. --cached/--index. If we are3395 * applying a non-git patch that incrementally updates the tree,3396 * we read from the result of a previous diff.3397 */3398static intload_preimage(struct apply_state *state,3399struct image *image,3400struct patch *patch,struct stat *st,3401const struct cache_entry *ce)3402{3403struct strbuf buf = STRBUF_INIT;3404size_t len;3405char*img;3406struct patch *previous;3407int status;34083409 previous =previous_patch(state, patch, &status);3410if(status)3411returnerror(_("path%shas been renamed/deleted"),3412 patch->old_name);3413if(previous) {3414/* We have a patched copy in memory; use that. */3415strbuf_add(&buf, previous->result, previous->resultsize);3416}else{3417 status =load_patch_target(state, &buf, ce, st,3418 patch->old_name, patch->old_mode);3419if(status <0)3420return status;3421else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3422/*3423 * There is no way to apply subproject3424 * patch without looking at the index.3425 * NEEDSWORK: shouldn't this be flagged3426 * as an error???3427 */3428free_fragment_list(patch->fragments);3429 patch->fragments = NULL;3430}else if(status) {3431returnerror(_("failed to read%s"), patch->old_name);3432}3433}34343435 img =strbuf_detach(&buf, &len);3436prepare_image(image, img, len, !patch->is_binary);3437return0;3438}34393440static intthree_way_merge(struct image *image,3441char*path,3442const unsigned char*base,3443const unsigned char*ours,3444const unsigned char*theirs)3445{3446 mmfile_t base_file, our_file, their_file;3447 mmbuffer_t result = { NULL };3448int status;34493450read_mmblob(&base_file, base);3451read_mmblob(&our_file, ours);3452read_mmblob(&their_file, theirs);3453 status =ll_merge(&result, path,3454&base_file,"base",3455&our_file,"ours",3456&their_file,"theirs", NULL);3457free(base_file.ptr);3458free(our_file.ptr);3459free(their_file.ptr);3460if(status <0|| !result.ptr) {3461free(result.ptr);3462return-1;3463}3464clear_image(image);3465 image->buf = result.ptr;3466 image->len = result.size;34673468return status;3469}34703471/*3472 * When directly falling back to add/add three-way merge, we read from3473 * the current contents of the new_name. In no cases other than that3474 * this function will be called.3475 */3476static intload_current(struct apply_state *state,3477struct image *image,3478struct patch *patch)3479{3480struct strbuf buf = STRBUF_INIT;3481int status, pos;3482size_t len;3483char*img;3484struct stat st;3485struct cache_entry *ce;3486char*name = patch->new_name;3487unsigned mode = patch->new_mode;34883489if(!patch->is_new)3490die("BUG: patch to%sis not a creation", patch->old_name);34913492 pos =cache_name_pos(name,strlen(name));3493if(pos <0)3494returnerror(_("%s: does not exist in index"), name);3495 ce = active_cache[pos];3496if(lstat(name, &st)) {3497if(errno != ENOENT)3498returnerror(_("%s:%s"), name,strerror(errno));3499if(checkout_target(&the_index, ce, &st))3500return-1;3501}3502if(verify_index_match(ce, &st))3503returnerror(_("%s: does not match index"), name);35043505 status =load_patch_target(state, &buf, ce, &st, name, mode);3506if(status <0)3507return status;3508else if(status)3509return-1;3510 img =strbuf_detach(&buf, &len);3511prepare_image(image, img, len, !patch->is_binary);3512return0;3513}35143515static inttry_threeway(struct apply_state *state,3516struct image *image,3517struct patch *patch,3518struct stat *st,3519const struct cache_entry *ce)3520{3521unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];3522struct strbuf buf = STRBUF_INIT;3523size_t len;3524int status;3525char*img;3526struct image tmp_image;35273528/* No point falling back to 3-way merge in these cases */3529if(patch->is_delete ||3530S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3531return-1;35323533/* Preimage the patch was prepared for */3534if(patch->is_new)3535write_sha1_file("",0, blob_type, pre_sha1);3536else if(get_sha1(patch->old_sha1_prefix, pre_sha1) ||3537read_blob_object(&buf, pre_sha1, patch->old_mode))3538returnerror("repository lacks the necessary blob to fall back on 3-way merge.");35393540fprintf(stderr,"Falling back to three-way merge...\n");35413542 img =strbuf_detach(&buf, &len);3543prepare_image(&tmp_image, img, len,1);3544/* Apply the patch to get the post image */3545if(apply_fragments(state, &tmp_image, patch) <0) {3546clear_image(&tmp_image);3547return-1;3548}3549/* post_sha1[] is theirs */3550write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);3551clear_image(&tmp_image);35523553/* our_sha1[] is ours */3554if(patch->is_new) {3555if(load_current(state, &tmp_image, patch))3556returnerror("cannot read the current contents of '%s'",3557 patch->new_name);3558}else{3559if(load_preimage(state, &tmp_image, patch, st, ce))3560returnerror("cannot read the current contents of '%s'",3561 patch->old_name);3562}3563write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);3564clear_image(&tmp_image);35653566/* in-core three-way merge between post and our using pre as base */3567 status =three_way_merge(image, patch->new_name,3568 pre_sha1, our_sha1, post_sha1);3569if(status <0) {3570fprintf(stderr,"Failed to fall back on three-way merge...\n");3571return status;3572}35733574if(status) {3575 patch->conflicted_threeway =1;3576if(patch->is_new)3577oidclr(&patch->threeway_stage[0]);3578else3579hashcpy(patch->threeway_stage[0].hash, pre_sha1);3580hashcpy(patch->threeway_stage[1].hash, our_sha1);3581hashcpy(patch->threeway_stage[2].hash, post_sha1);3582fprintf(stderr,"Applied patch to '%s' with conflicts.\n", patch->new_name);3583}else{3584fprintf(stderr,"Applied patch to '%s' cleanly.\n", patch->new_name);3585}3586return0;3587}35883589static intapply_data(struct apply_state *state,struct patch *patch,3590struct stat *st,const struct cache_entry *ce)3591{3592struct image image;35933594if(load_preimage(state, &image, patch, st, ce) <0)3595return-1;35963597if(patch->direct_to_threeway ||3598apply_fragments(state, &image, patch) <0) {3599/* Note: with --reject, apply_fragments() returns 0 */3600if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3601return-1;3602}3603 patch->result = image.buf;3604 patch->resultsize = image.len;3605add_to_fn_table(state, patch);3606free(image.line_allocated);36073608if(0< patch->is_delete && patch->resultsize)3609returnerror(_("removal patch leaves file contents"));36103611return0;3612}36133614/*3615 * If "patch" that we are looking at modifies or deletes what we have,3616 * we would want it not to lose any local modification we have, either3617 * in the working tree or in the index.3618 *3619 * This also decides if a non-git patch is a creation patch or a3620 * modification to an existing empty file. We do not check the state3621 * of the current tree for a creation patch in this function; the caller3622 * check_patch() separately makes sure (and errors out otherwise) that3623 * the path the patch creates does not exist in the current tree.3624 */3625static intcheck_preimage(struct apply_state *state,3626struct patch *patch,3627struct cache_entry **ce,3628struct stat *st)3629{3630const char*old_name = patch->old_name;3631struct patch *previous = NULL;3632int stat_ret =0, status;3633unsigned st_mode =0;36343635if(!old_name)3636return0;36373638assert(patch->is_new <=0);3639 previous =previous_patch(state, patch, &status);36403641if(status)3642returnerror(_("path%shas been renamed/deleted"), old_name);3643if(previous) {3644 st_mode = previous->new_mode;3645}else if(!state->cached) {3646 stat_ret =lstat(old_name, st);3647if(stat_ret && errno != ENOENT)3648returnerror(_("%s:%s"), old_name,strerror(errno));3649}36503651if(state->check_index && !previous) {3652int pos =cache_name_pos(old_name,strlen(old_name));3653if(pos <0) {3654if(patch->is_new <0)3655goto is_new;3656returnerror(_("%s: does not exist in index"), old_name);3657}3658*ce = active_cache[pos];3659if(stat_ret <0) {3660if(checkout_target(&the_index, *ce, st))3661return-1;3662}3663if(!state->cached &&verify_index_match(*ce, st))3664returnerror(_("%s: does not match index"), old_name);3665if(state->cached)3666 st_mode = (*ce)->ce_mode;3667}else if(stat_ret <0) {3668if(patch->is_new <0)3669goto is_new;3670returnerror(_("%s:%s"), old_name,strerror(errno));3671}36723673if(!state->cached && !previous)3674 st_mode =ce_mode_from_stat(*ce, st->st_mode);36753676if(patch->is_new <0)3677 patch->is_new =0;3678if(!patch->old_mode)3679 patch->old_mode = st_mode;3680if((st_mode ^ patch->old_mode) & S_IFMT)3681returnerror(_("%s: wrong type"), old_name);3682if(st_mode != patch->old_mode)3683warning(_("%shas type%o, expected%o"),3684 old_name, st_mode, patch->old_mode);3685if(!patch->new_mode && !patch->is_delete)3686 patch->new_mode = st_mode;3687return0;36883689 is_new:3690 patch->is_new =1;3691 patch->is_delete =0;3692free(patch->old_name);3693 patch->old_name = NULL;3694return0;3695}369636973698#define EXISTS_IN_INDEX 13699#define EXISTS_IN_WORKTREE 237003701static intcheck_to_create(struct apply_state *state,3702const char*new_name,3703int ok_if_exists)3704{3705struct stat nst;37063707if(state->check_index &&3708cache_name_pos(new_name,strlen(new_name)) >=0&&3709!ok_if_exists)3710return EXISTS_IN_INDEX;3711if(state->cached)3712return0;37133714if(!lstat(new_name, &nst)) {3715if(S_ISDIR(nst.st_mode) || ok_if_exists)3716return0;3717/*3718 * A leading component of new_name might be a symlink3719 * that is going to be removed with this patch, but3720 * still pointing at somewhere that has the path.3721 * In such a case, path "new_name" does not exist as3722 * far as git is concerned.3723 */3724if(has_symlink_leading_path(new_name,strlen(new_name)))3725return0;37263727return EXISTS_IN_WORKTREE;3728}else if((errno != ENOENT) && (errno != ENOTDIR)) {3729returnerror("%s:%s", new_name,strerror(errno));3730}3731return0;3732}37333734static uintptr_tregister_symlink_changes(struct apply_state *state,3735const char*path,3736uintptr_t what)3737{3738struct string_list_item *ent;37393740 ent =string_list_lookup(&state->symlink_changes, path);3741if(!ent) {3742 ent =string_list_insert(&state->symlink_changes, path);3743 ent->util = (void*)0;3744}3745 ent->util = (void*)(what | ((uintptr_t)ent->util));3746return(uintptr_t)ent->util;3747}37483749static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3750{3751struct string_list_item *ent;37523753 ent =string_list_lookup(&state->symlink_changes, path);3754if(!ent)3755return0;3756return(uintptr_t)ent->util;3757}37583759static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3760{3761for( ; patch; patch = patch->next) {3762if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3763(patch->is_rename || patch->is_delete))3764/* the symlink at patch->old_name is removed */3765register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37663767if(patch->new_name &&S_ISLNK(patch->new_mode))3768/* the symlink at patch->new_name is created or remains */3769register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3770}3771}37723773static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3774{3775do{3776unsigned int change;37773778while(--name->len && name->buf[name->len] !='/')3779;/* scan backwards */3780if(!name->len)3781break;3782 name->buf[name->len] ='\0';3783 change =check_symlink_changes(state, name->buf);3784if(change & APPLY_SYMLINK_IN_RESULT)3785return1;3786if(change & APPLY_SYMLINK_GOES_AWAY)3787/*3788 * This cannot be "return 0", because we may3789 * see a new one created at a higher level.3790 */3791continue;37923793/* otherwise, check the preimage */3794if(state->check_index) {3795struct cache_entry *ce;37963797 ce =cache_file_exists(name->buf, name->len, ignore_case);3798if(ce &&S_ISLNK(ce->ce_mode))3799return1;3800}else{3801struct stat st;3802if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3803return1;3804}3805}while(1);3806return0;3807}38083809static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3810{3811int ret;3812struct strbuf name = STRBUF_INIT;38133814assert(*name_ !='\0');3815strbuf_addstr(&name, name_);3816 ret =path_is_beyond_symlink_1(state, &name);3817strbuf_release(&name);38183819return ret;3820}38213822static intcheck_unsafe_path(struct patch *patch)3823{3824const char*old_name = NULL;3825const char*new_name = NULL;3826if(patch->is_delete)3827 old_name = patch->old_name;3828else if(!patch->is_new && !patch->is_copy)3829 old_name = patch->old_name;3830if(!patch->is_delete)3831 new_name = patch->new_name;38323833if(old_name && !verify_path(old_name))3834returnerror(_("invalid path '%s'"), old_name);3835if(new_name && !verify_path(new_name))3836returnerror(_("invalid path '%s'"), new_name);3837return0;3838}38393840/*3841 * Check and apply the patch in-core; leave the result in patch->result3842 * for the caller to write it out to the final destination.3843 */3844static intcheck_patch(struct apply_state *state,struct patch *patch)3845{3846struct stat st;3847const char*old_name = patch->old_name;3848const char*new_name = patch->new_name;3849const char*name = old_name ? old_name : new_name;3850struct cache_entry *ce = NULL;3851struct patch *tpatch;3852int ok_if_exists;3853int status;38543855 patch->rejected =1;/* we will drop this after we succeed */38563857 status =check_preimage(state, patch, &ce, &st);3858if(status)3859return status;3860 old_name = patch->old_name;38613862/*3863 * A type-change diff is always split into a patch to delete3864 * old, immediately followed by a patch to create new (see3865 * diff.c::run_diff()); in such a case it is Ok that the entry3866 * to be deleted by the previous patch is still in the working3867 * tree and in the index.3868 *3869 * A patch to swap-rename between A and B would first rename A3870 * to B and then rename B to A. While applying the first one,3871 * the presence of B should not stop A from getting renamed to3872 * B; ask to_be_deleted() about the later rename. Removal of3873 * B and rename from A to B is handled the same way by asking3874 * was_deleted().3875 */3876if((tpatch =in_fn_table(state, new_name)) &&3877(was_deleted(tpatch) ||to_be_deleted(tpatch)))3878 ok_if_exists =1;3879else3880 ok_if_exists =0;38813882if(new_name &&3883((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3884int err =check_to_create(state, new_name, ok_if_exists);38853886if(err && state->threeway) {3887 patch->direct_to_threeway =1;3888}else switch(err) {3889case0:3890break;/* happy */3891case EXISTS_IN_INDEX:3892returnerror(_("%s: already exists in index"), new_name);3893break;3894case EXISTS_IN_WORKTREE:3895returnerror(_("%s: already exists in working directory"),3896 new_name);3897default:3898return err;3899}39003901if(!patch->new_mode) {3902if(0< patch->is_new)3903 patch->new_mode = S_IFREG |0644;3904else3905 patch->new_mode = patch->old_mode;3906}3907}39083909if(new_name && old_name) {3910int same = !strcmp(old_name, new_name);3911if(!patch->new_mode)3912 patch->new_mode = patch->old_mode;3913if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3914if(same)3915returnerror(_("new mode (%o) of%sdoes not "3916"match old mode (%o)"),3917 patch->new_mode, new_name,3918 patch->old_mode);3919else3920returnerror(_("new mode (%o) of%sdoes not "3921"match old mode (%o) of%s"),3922 patch->new_mode, new_name,3923 patch->old_mode, old_name);3924}3925}39263927if(!state->unsafe_paths &&check_unsafe_path(patch))3928return-128;39293930/*3931 * An attempt to read from or delete a path that is beyond a3932 * symbolic link will be prevented by load_patch_target() that3933 * is called at the beginning of apply_data() so we do not3934 * have to worry about a patch marked with "is_delete" bit3935 * here. We however need to make sure that the patch result3936 * is not deposited to a path that is beyond a symbolic link3937 * here.3938 */3939if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3940returnerror(_("affected file '%s' is beyond a symbolic link"),3941 patch->new_name);39423943if(apply_data(state, patch, &st, ce) <0)3944returnerror(_("%s: patch does not apply"), name);3945 patch->rejected =0;3946return0;3947}39483949static intcheck_patch_list(struct apply_state *state,struct patch *patch)3950{3951int err =0;39523953prepare_symlink_changes(state, patch);3954prepare_fn_table(state, patch);3955while(patch) {3956int res;3957if(state->apply_verbosely)3958say_patch_name(stderr,3959_("Checking patch%s..."), patch);3960 res =check_patch(state, patch);3961if(res == -128)3962return-128;3963 err |= res;3964 patch = patch->next;3965}3966return err;3967}39683969/* This function tries to read the sha1 from the current index */3970static intget_current_sha1(const char*path,unsigned char*sha1)3971{3972int pos;39733974if(read_cache() <0)3975return-1;3976 pos =cache_name_pos(path,strlen(path));3977if(pos <0)3978return-1;3979hashcpy(sha1, active_cache[pos]->sha1);3980return0;3981}39823983static intpreimage_sha1_in_gitlink_patch(struct patch *p,unsigned char sha1[20])3984{3985/*3986 * A usable gitlink patch has only one fragment (hunk) that looks like:3987 * @@ -1 +1 @@3988 * -Subproject commit <old sha1>3989 * +Subproject commit <new sha1>3990 * or3991 * @@ -1 +0,0 @@3992 * -Subproject commit <old sha1>3993 * for a removal patch.3994 */3995struct fragment *hunk = p->fragments;3996static const char heading[] ="-Subproject commit ";3997char*preimage;39983999if(/* does the patch have only one hunk? */4000 hunk && !hunk->next &&4001/* is its preimage one line? */4002 hunk->oldpos ==1&& hunk->oldlines ==1&&4003/* does preimage begin with the heading? */4004(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4005starts_with(++preimage, heading) &&4006/* does it record full SHA-1? */4007!get_sha1_hex(preimage +sizeof(heading) -1, sha1) &&4008 preimage[sizeof(heading) +40-1] =='\n'&&4009/* does the abbreviated name on the index line agree with it? */4010starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4011return0;/* it all looks fine */40124013/* we may have full object name on the index line */4014returnget_sha1_hex(p->old_sha1_prefix, sha1);4015}40164017/* Build an index that contains the just the files needed for a 3way merge */4018static intbuild_fake_ancestor(struct patch *list,const char*filename)4019{4020struct patch *patch;4021struct index_state result = { NULL };4022static struct lock_file lock;4023int res;40244025/* Once we start supporting the reverse patch, it may be4026 * worth showing the new sha1 prefix, but until then...4027 */4028for(patch = list; patch; patch = patch->next) {4029unsigned char sha1[20];4030struct cache_entry *ce;4031const char*name;40324033 name = patch->old_name ? patch->old_name : patch->new_name;4034if(0< patch->is_new)4035continue;40364037if(S_ISGITLINK(patch->old_mode)) {4038if(!preimage_sha1_in_gitlink_patch(patch, sha1))4039;/* ok, the textual part looks sane */4040else4041returnerror("sha1 information is lacking or "4042"useless for submodule%s", name);4043}else if(!get_sha1_blob(patch->old_sha1_prefix, sha1)) {4044;/* ok */4045}else if(!patch->lines_added && !patch->lines_deleted) {4046/* mode-only change: update the current */4047if(get_current_sha1(patch->old_name, sha1))4048returnerror("mode change for%s, which is not "4049"in current HEAD", name);4050}else4051returnerror("sha1 information is lacking or useless "4052"(%s).", name);40534054 ce =make_cache_entry(patch->old_mode, sha1, name,0,0);4055if(!ce)4056returnerror(_("make_cache_entry failed for path '%s'"),4057 name);4058if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4059free(ce);4060returnerror("Could not add%sto temporary index",4061 name);4062}4063}40644065hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);4066 res =write_locked_index(&result, &lock, COMMIT_LOCK);4067discard_index(&result);40684069if(res)4070returnerror("Could not write temporary index to%s", filename);40714072return0;4073}40744075static voidstat_patch_list(struct apply_state *state,struct patch *patch)4076{4077int files, adds, dels;40784079for(files = adds = dels =0; patch ; patch = patch->next) {4080 files++;4081 adds += patch->lines_added;4082 dels += patch->lines_deleted;4083show_stats(state, patch);4084}40854086print_stat_summary(stdout, files, adds, dels);4087}40884089static voidnumstat_patch_list(struct apply_state *state,4090struct patch *patch)4091{4092for( ; patch; patch = patch->next) {4093const char*name;4094 name = patch->new_name ? patch->new_name : patch->old_name;4095if(patch->is_binary)4096printf("-\t-\t");4097else4098printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4099write_name_quoted(name, stdout, state->line_termination);4100}4101}41024103static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4104{4105if(mode)4106printf("%smode%06o%s\n", newdelete, mode, name);4107else4108printf("%s %s\n", newdelete, name);4109}41104111static voidshow_mode_change(struct patch *p,int show_name)4112{4113if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4114if(show_name)4115printf(" mode change%06o =>%06o%s\n",4116 p->old_mode, p->new_mode, p->new_name);4117else4118printf(" mode change%06o =>%06o\n",4119 p->old_mode, p->new_mode);4120}4121}41224123static voidshow_rename_copy(struct patch *p)4124{4125const char*renamecopy = p->is_rename ?"rename":"copy";4126const char*old, *new;41274128/* Find common prefix */4129 old = p->old_name;4130new= p->new_name;4131while(1) {4132const char*slash_old, *slash_new;4133 slash_old =strchr(old,'/');4134 slash_new =strchr(new,'/');4135if(!slash_old ||4136!slash_new ||4137 slash_old - old != slash_new -new||4138memcmp(old,new, slash_new -new))4139break;4140 old = slash_old +1;4141new= slash_new +1;4142}4143/* p->old_name thru old is the common prefix, and old and new4144 * through the end of names are renames4145 */4146if(old != p->old_name)4147printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4148(int)(old - p->old_name), p->old_name,4149 old,new, p->score);4150else4151printf("%s %s=>%s(%d%%)\n", renamecopy,4152 p->old_name, p->new_name, p->score);4153show_mode_change(p,0);4154}41554156static voidsummary_patch_list(struct patch *patch)4157{4158struct patch *p;41594160for(p = patch; p; p = p->next) {4161if(p->is_new)4162show_file_mode_name("create", p->new_mode, p->new_name);4163else if(p->is_delete)4164show_file_mode_name("delete", p->old_mode, p->old_name);4165else{4166if(p->is_rename || p->is_copy)4167show_rename_copy(p);4168else{4169if(p->score) {4170printf(" rewrite%s(%d%%)\n",4171 p->new_name, p->score);4172show_mode_change(p,0);4173}4174else4175show_mode_change(p,1);4176}4177}4178}4179}41804181static voidpatch_stats(struct apply_state *state,struct patch *patch)4182{4183int lines = patch->lines_added + patch->lines_deleted;41844185if(lines > state->max_change)4186 state->max_change = lines;4187if(patch->old_name) {4188int len =quote_c_style(patch->old_name, NULL, NULL,0);4189if(!len)4190 len =strlen(patch->old_name);4191if(len > state->max_len)4192 state->max_len = len;4193}4194if(patch->new_name) {4195int len =quote_c_style(patch->new_name, NULL, NULL,0);4196if(!len)4197 len =strlen(patch->new_name);4198if(len > state->max_len)4199 state->max_len = len;4200}4201}42024203static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4204{4205if(state->update_index) {4206if(remove_file_from_cache(patch->old_name) <0)4207returnerror(_("unable to remove%sfrom index"), patch->old_name);4208}4209if(!state->cached) {4210if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4211remove_path(patch->old_name);4212}4213}4214return0;4215}42164217static intadd_index_file(struct apply_state *state,4218const char*path,4219unsigned mode,4220void*buf,4221unsigned long size)4222{4223struct stat st;4224struct cache_entry *ce;4225int namelen =strlen(path);4226unsigned ce_size =cache_entry_size(namelen);42274228if(!state->update_index)4229return0;42304231 ce =xcalloc(1, ce_size);4232memcpy(ce->name, path, namelen);4233 ce->ce_mode =create_ce_mode(mode);4234 ce->ce_flags =create_ce_flags(0);4235 ce->ce_namelen = namelen;4236if(S_ISGITLINK(mode)) {4237const char*s;42384239if(!skip_prefix(buf,"Subproject commit ", &s) ||4240get_sha1_hex(s, ce->sha1)) {4241free(ce);4242returnerror(_("corrupt patch for submodule%s"), path);4243}4244}else{4245if(!state->cached) {4246if(lstat(path, &st) <0) {4247free(ce);4248returnerror(_("unable to stat newly "4249"created file '%s':%s"),4250 path,strerror(errno));4251}4252fill_stat_cache_info(ce, &st);4253}4254if(write_sha1_file(buf, size, blob_type, ce->sha1) <0) {4255free(ce);4256returnerror(_("unable to create backing store "4257"for newly created file%s"), path);4258}4259}4260if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4261free(ce);4262returnerror(_("unable to add cache entry for%s"), path);4263}42644265return0;4266}42674268/*4269 * Returns:4270 * -1 if an unrecoverable error happened4271 * 0 if everything went well4272 * 1 if a recoverable error happened4273 */4274static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4275{4276int fd, res;4277struct strbuf nbuf = STRBUF_INIT;42784279if(S_ISGITLINK(mode)) {4280struct stat st;4281if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4282return0;4283return!!mkdir(path,0777);4284}42854286if(has_symlinks &&S_ISLNK(mode))4287/* Although buf:size is counted string, it also is NUL4288 * terminated.4289 */4290return!!symlink(buf, path);42914292 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4293if(fd <0)4294return1;42954296if(convert_to_working_tree(path, buf, size, &nbuf)) {4297 size = nbuf.len;4298 buf = nbuf.buf;4299}43004301 res =write_in_full(fd, buf, size) <0;4302if(res)4303error_errno(_("failed to write to '%s'"), path);4304strbuf_release(&nbuf);43054306if(close(fd) <0&& !res)4307returnerror_errno(_("closing file '%s'"), path);43084309return res ? -1:0;4310}43114312/*4313 * We optimistically assume that the directories exist,4314 * which is true 99% of the time anyway. If they don't,4315 * we create them and try again.4316 *4317 * Returns:4318 * -1 on error4319 * 0 otherwise4320 */4321static intcreate_one_file(struct apply_state *state,4322char*path,4323unsigned mode,4324const char*buf,4325unsigned long size)4326{4327int res;43284329if(state->cached)4330return0;43314332 res =try_create_file(path, mode, buf, size);4333if(res <0)4334return-1;4335if(!res)4336return0;43374338if(errno == ENOENT) {4339if(safe_create_leading_directories(path))4340return0;4341 res =try_create_file(path, mode, buf, size);4342if(res <0)4343return-1;4344if(!res)4345return0;4346}43474348if(errno == EEXIST || errno == EACCES) {4349/* We may be trying to create a file where a directory4350 * used to be.4351 */4352struct stat st;4353if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4354 errno = EEXIST;4355}43564357if(errno == EEXIST) {4358unsigned int nr =getpid();43594360for(;;) {4361char newpath[PATH_MAX];4362mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4363 res =try_create_file(newpath, mode, buf, size);4364if(res <0)4365return-1;4366if(!res) {4367if(!rename(newpath, path))4368return0;4369unlink_or_warn(newpath);4370break;4371}4372if(errno != EEXIST)4373break;4374++nr;4375}4376}4377returnerror_errno(_("unable to write file '%s' mode%o"),4378 path, mode);4379}43804381static intadd_conflicted_stages_file(struct apply_state *state,4382struct patch *patch)4383{4384int stage, namelen;4385unsigned ce_size, mode;4386struct cache_entry *ce;43874388if(!state->update_index)4389return0;4390 namelen =strlen(patch->new_name);4391 ce_size =cache_entry_size(namelen);4392 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);43934394remove_file_from_cache(patch->new_name);4395for(stage =1; stage <4; stage++) {4396if(is_null_oid(&patch->threeway_stage[stage -1]))4397continue;4398 ce =xcalloc(1, ce_size);4399memcpy(ce->name, patch->new_name, namelen);4400 ce->ce_mode =create_ce_mode(mode);4401 ce->ce_flags =create_ce_flags(stage);4402 ce->ce_namelen = namelen;4403hashcpy(ce->sha1, patch->threeway_stage[stage -1].hash);4404if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4405free(ce);4406returnerror(_("unable to add cache entry for%s"),4407 patch->new_name);4408}4409}44104411return0;4412}44134414static intcreate_file(struct apply_state *state,struct patch *patch)4415{4416char*path = patch->new_name;4417unsigned mode = patch->new_mode;4418unsigned long size = patch->resultsize;4419char*buf = patch->result;44204421if(!mode)4422 mode = S_IFREG |0644;4423if(create_one_file(state, path, mode, buf, size))4424return-1;44254426if(patch->conflicted_threeway)4427returnadd_conflicted_stages_file(state, patch);4428else4429returnadd_index_file(state, path, mode, buf, size);4430}44314432/* phase zero is to remove, phase one is to create */4433static intwrite_out_one_result(struct apply_state *state,4434struct patch *patch,4435int phase)4436{4437if(patch->is_delete >0) {4438if(phase ==0)4439returnremove_file(state, patch,1);4440return0;4441}4442if(patch->is_new >0|| patch->is_copy) {4443if(phase ==1)4444returncreate_file(state, patch);4445return0;4446}4447/*4448 * Rename or modification boils down to the same4449 * thing: remove the old, write the new4450 */4451if(phase ==0)4452returnremove_file(state, patch, patch->is_rename);4453if(phase ==1)4454returncreate_file(state, patch);4455return0;4456}44574458static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4459{4460FILE*rej;4461char namebuf[PATH_MAX];4462struct fragment *frag;4463int cnt =0;4464struct strbuf sb = STRBUF_INIT;44654466for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4467if(!frag->rejected)4468continue;4469 cnt++;4470}44714472if(!cnt) {4473if(state->apply_verbosely)4474say_patch_name(stderr,4475_("Applied patch%scleanly."), patch);4476return0;4477}44784479/* This should not happen, because a removal patch that leaves4480 * contents are marked "rejected" at the patch level.4481 */4482if(!patch->new_name)4483die(_("internal error"));44844485/* Say this even without --verbose */4486strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4487"Applying patch %%swith%drejects...",4488 cnt),4489 cnt);4490say_patch_name(stderr, sb.buf, patch);4491strbuf_release(&sb);44924493 cnt =strlen(patch->new_name);4494if(ARRAY_SIZE(namebuf) <= cnt +5) {4495 cnt =ARRAY_SIZE(namebuf) -5;4496warning(_("truncating .rej filename to %.*s.rej"),4497 cnt -1, patch->new_name);4498}4499memcpy(namebuf, patch->new_name, cnt);4500memcpy(namebuf + cnt,".rej",5);45014502 rej =fopen(namebuf,"w");4503if(!rej)4504returnerror(_("cannot open%s:%s"), namebuf,strerror(errno));45054506/* Normal git tools never deal with .rej, so do not pretend4507 * this is a git patch by saying --git or giving extended4508 * headers. While at it, maybe please "kompare" that wants4509 * the trailing TAB and some garbage at the end of line ;-).4510 */4511fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4512 patch->new_name, patch->new_name);4513for(cnt =1, frag = patch->fragments;4514 frag;4515 cnt++, frag = frag->next) {4516if(!frag->rejected) {4517fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4518continue;4519}4520fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4521fprintf(rej,"%.*s", frag->size, frag->patch);4522if(frag->patch[frag->size-1] !='\n')4523fputc('\n', rej);4524}4525fclose(rej);4526return-1;4527}45284529/*4530 * Returns:4531 * -1 if an error happened4532 * 0 if the patch applied cleanly4533 * 1 if the patch did not apply cleanly4534 */4535static intwrite_out_results(struct apply_state *state,struct patch *list)4536{4537int phase;4538int errs =0;4539struct patch *l;4540struct string_list cpath = STRING_LIST_INIT_DUP;45414542for(phase =0; phase <2; phase++) {4543 l = list;4544while(l) {4545if(l->rejected)4546 errs =1;4547else{4548if(write_out_one_result(state, l, phase)) {4549string_list_clear(&cpath,0);4550return-1;4551}4552if(phase ==1) {4553if(write_out_one_reject(state, l))4554 errs =1;4555if(l->conflicted_threeway) {4556string_list_append(&cpath, l->new_name);4557 errs =1;4558}4559}4560}4561 l = l->next;4562}4563}45644565if(cpath.nr) {4566struct string_list_item *item;45674568string_list_sort(&cpath);4569for_each_string_list_item(item, &cpath)4570fprintf(stderr,"U%s\n", item->string);4571string_list_clear(&cpath,0);45724573rerere(0);4574}45754576return errs;4577}45784579/*4580 * Try to apply a patch.4581 *4582 * Returns:4583 * -128 if a bad error happened (like patch unreadable)4584 * -1 if patch did not apply and user cannot deal with it4585 * 0 if the patch applied4586 * 1 if the patch did not apply but user might fix it4587 */4588static intapply_patch(struct apply_state *state,4589int fd,4590const char*filename,4591int options)4592{4593size_t offset;4594struct strbuf buf = STRBUF_INIT;/* owns the patch text */4595struct patch *list = NULL, **listp = &list;4596int skipped_patch =0;4597int res =0;45984599 state->patch_input_file = filename;4600if(read_patch_file(&buf, fd) <0)4601return-128;4602 offset =0;4603while(offset < buf.len) {4604struct patch *patch;4605int nr;46064607 patch =xcalloc(1,sizeof(*patch));4608 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4609 patch->recount = !!(options & APPLY_OPT_RECOUNT);4610 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4611if(nr <0) {4612free_patch(patch);4613if(nr == -128) {4614 res = -128;4615goto end;4616}4617break;4618}4619if(state->apply_in_reverse)4620reverse_patches(patch);4621if(use_patch(state, patch)) {4622patch_stats(state, patch);4623*listp = patch;4624 listp = &patch->next;4625}4626else{4627if(state->apply_verbosely)4628say_patch_name(stderr,_("Skipped patch '%s'."), patch);4629free_patch(patch);4630 skipped_patch++;4631}4632 offset += nr;4633}46344635if(!list && !skipped_patch) {4636error(_("unrecognized input"));4637 res = -128;4638goto end;4639}46404641if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4642 state->apply =0;46434644 state->update_index = state->check_index && state->apply;4645if(state->update_index && state->newfd <0)4646 state->newfd =hold_locked_index(state->lock_file,1);46474648if(state->check_index &&read_cache() <0) {4649error(_("unable to read index file"));4650 res = -128;4651goto end;4652}46534654if(state->check || state->apply) {4655int r =check_patch_list(state, list);4656if(r == -128) {4657 res = -128;4658goto end;4659}4660if(r <0&& !state->apply_with_reject) {4661 res = -1;4662goto end;4663}4664}46654666if(state->apply) {4667int write_res =write_out_results(state, list);4668if(write_res <0) {4669 res = -128;4670goto end;4671}4672if(write_res >0) {4673/* with --3way, we still need to write the index out */4674 res = state->apply_with_reject ? -1:1;4675goto end;4676}4677}46784679if(state->fake_ancestor &&4680build_fake_ancestor(list, state->fake_ancestor)) {4681 res = -128;4682goto end;4683}46844685if(state->diffstat)4686stat_patch_list(state, list);46874688if(state->numstat)4689numstat_patch_list(state, list);46904691if(state->summary)4692summary_patch_list(list);46934694end:4695free_patch_list(list);4696strbuf_release(&buf);4697string_list_clear(&state->fn_table,0);4698return res;4699}47004701intapply_option_parse_exclude(const struct option *opt,4702const char*arg,int unset)4703{4704struct apply_state *state = opt->value;4705add_name_limit(state, arg,1);4706return0;4707}47084709intapply_option_parse_include(const struct option *opt,4710const char*arg,int unset)4711{4712struct apply_state *state = opt->value;4713add_name_limit(state, arg,0);4714 state->has_include =1;4715return0;4716}47174718intapply_option_parse_p(const struct option *opt,4719const char*arg,4720int unset)4721{4722struct apply_state *state = opt->value;4723 state->p_value =atoi(arg);4724 state->p_value_known =1;4725return0;4726}47274728intapply_option_parse_space_change(const struct option *opt,4729const char*arg,int unset)4730{4731struct apply_state *state = opt->value;4732if(unset)4733 state->ws_ignore_action = ignore_ws_none;4734else4735 state->ws_ignore_action = ignore_ws_change;4736return0;4737}47384739intapply_option_parse_whitespace(const struct option *opt,4740const char*arg,int unset)4741{4742struct apply_state *state = opt->value;4743 state->whitespace_option = arg;4744if(parse_whitespace_option(state, arg))4745exit(1);4746return0;4747}47484749intapply_option_parse_directory(const struct option *opt,4750const char*arg,int unset)4751{4752struct apply_state *state = opt->value;4753strbuf_reset(&state->root);4754strbuf_addstr(&state->root, arg);4755strbuf_complete(&state->root,'/');4756return0;4757}47584759intapply_all_patches(struct apply_state *state,4760int argc,4761const char**argv,4762int options)4763{4764int i;4765int res;4766int errs =0;4767int read_stdin =1;47684769for(i =0; i < argc; i++) {4770const char*arg = argv[i];4771int fd;47724773if(!strcmp(arg,"-")) {4774 res =apply_patch(state,0,"<stdin>", options);4775if(res <0)4776goto end;4777 errs |= res;4778 read_stdin =0;4779continue;4780}else if(0< state->prefix_length)4781 arg =prefix_filename(state->prefix,4782 state->prefix_length,4783 arg);47844785 fd =open(arg, O_RDONLY);4786if(fd <0) {4787error(_("can't open patch '%s':%s"), arg,strerror(errno));4788 res = -128;4789goto end;4790}4791 read_stdin =0;4792set_default_whitespace_mode(state);4793 res =apply_patch(state, fd, arg, options);4794close(fd);4795if(res <0)4796goto end;4797 errs |= res;4798}4799set_default_whitespace_mode(state);4800if(read_stdin) {4801 res =apply_patch(state,0,"<stdin>", options);4802if(res <0)4803goto end;4804 errs |= res;4805}48064807if(state->whitespace_error) {4808if(state->squelch_whitespace_errors &&4809 state->squelch_whitespace_errors < state->whitespace_error) {4810int squelched =4811 state->whitespace_error - state->squelch_whitespace_errors;4812warning(Q_("squelched%dwhitespace error",4813"squelched%dwhitespace errors",4814 squelched),4815 squelched);4816}4817if(state->ws_error_action == die_on_ws_error) {4818error(Q_("%dline adds whitespace errors.",4819"%dlines add whitespace errors.",4820 state->whitespace_error),4821 state->whitespace_error);4822 res = -128;4823goto end;4824}4825if(state->applied_after_fixing_ws && state->apply)4826warning("%dline%sapplied after"4827" fixing whitespace errors.",4828 state->applied_after_fixing_ws,4829 state->applied_after_fixing_ws ==1?"":"s");4830else if(state->whitespace_error)4831warning(Q_("%dline adds whitespace errors.",4832"%dlines add whitespace errors.",4833 state->whitespace_error),4834 state->whitespace_error);4835}48364837if(state->update_index) {4838 res =write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);4839if(res) {4840error(_("Unable to write new index file"));4841 res = -128;4842goto end;4843}4844 state->newfd = -1;4845}48464847return!!errs;48484849end:4850if(state->newfd >=0) {4851rollback_lock_file(state->lock_file);4852 state->newfd = -1;4853}48544855return(res == -1?1:128);4856}