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"config.h" 12#include"blob.h" 13#include"delta.h" 14#include"diff.h" 15#include"dir.h" 16#include"xdiff-interface.h" 17#include"ll-merge.h" 18#include"lockfile.h" 19#include"parse-options.h" 20#include"quote.h" 21#include"rerere.h" 22#include"apply.h" 23 24static voidgit_apply_config(void) 25{ 26git_config_get_string_const("apply.whitespace", &apply_default_whitespace); 27git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace); 28git_config(git_default_config, NULL); 29} 30 31static intparse_whitespace_option(struct apply_state *state,const char*option) 32{ 33if(!option) { 34 state->ws_error_action = warn_on_ws_error; 35return0; 36} 37if(!strcmp(option,"warn")) { 38 state->ws_error_action = warn_on_ws_error; 39return0; 40} 41if(!strcmp(option,"nowarn")) { 42 state->ws_error_action = nowarn_ws_error; 43return0; 44} 45if(!strcmp(option,"error")) { 46 state->ws_error_action = die_on_ws_error; 47return0; 48} 49if(!strcmp(option,"error-all")) { 50 state->ws_error_action = die_on_ws_error; 51 state->squelch_whitespace_errors =0; 52return0; 53} 54if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 55 state->ws_error_action = correct_ws_error; 56return0; 57} 58returnerror(_("unrecognized whitespace option '%s'"), option); 59} 60 61static intparse_ignorewhitespace_option(struct apply_state *state, 62const char*option) 63{ 64if(!option || !strcmp(option,"no") || 65!strcmp(option,"false") || !strcmp(option,"never") || 66!strcmp(option,"none")) { 67 state->ws_ignore_action = ignore_ws_none; 68return0; 69} 70if(!strcmp(option,"change")) { 71 state->ws_ignore_action = ignore_ws_change; 72return0; 73} 74returnerror(_("unrecognized whitespace ignore option '%s'"), option); 75} 76 77intinit_apply_state(struct apply_state *state, 78const char*prefix) 79{ 80memset(state,0,sizeof(*state)); 81 state->prefix = prefix; 82 state->apply =1; 83 state->line_termination ='\n'; 84 state->p_value =1; 85 state->p_context = UINT_MAX; 86 state->squelch_whitespace_errors =5; 87 state->ws_error_action = warn_on_ws_error; 88 state->ws_ignore_action = ignore_ws_none; 89 state->linenr =1; 90string_list_init(&state->fn_table,0); 91string_list_init(&state->limit_by_name,0); 92string_list_init(&state->symlink_changes,0); 93strbuf_init(&state->root,0); 94 95git_apply_config(); 96if(apply_default_whitespace &&parse_whitespace_option(state, apply_default_whitespace)) 97return-1; 98if(apply_default_ignorewhitespace &&parse_ignorewhitespace_option(state, apply_default_ignorewhitespace)) 99return-1; 100return0; 101} 102 103voidclear_apply_state(struct apply_state *state) 104{ 105string_list_clear(&state->limit_by_name,0); 106string_list_clear(&state->symlink_changes,0); 107strbuf_release(&state->root); 108 109/* &state->fn_table is cleared at the end of apply_patch() */ 110} 111 112static voidmute_routine(const char*msg,va_list params) 113{ 114/* do nothing */ 115} 116 117intcheck_apply_state(struct apply_state *state,int force_apply) 118{ 119int is_not_gitdir = !startup_info->have_repository; 120 121if(state->apply_with_reject && state->threeway) 122returnerror(_("--reject and --3way cannot be used together.")); 123if(state->cached && state->threeway) 124returnerror(_("--cached and --3way cannot be used together.")); 125if(state->threeway) { 126if(is_not_gitdir) 127returnerror(_("--3way outside a repository")); 128 state->check_index =1; 129} 130if(state->apply_with_reject) { 131 state->apply =1; 132if(state->apply_verbosity == verbosity_normal) 133 state->apply_verbosity = verbosity_verbose; 134} 135if(!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor)) 136 state->apply =0; 137if(state->check_index && is_not_gitdir) 138returnerror(_("--index outside a repository")); 139if(state->cached) { 140if(is_not_gitdir) 141returnerror(_("--cached outside a repository")); 142 state->check_index =1; 143} 144if(state->check_index) 145 state->unsafe_paths =0; 146 147if(state->apply_verbosity <= verbosity_silent) { 148 state->saved_error_routine =get_error_routine(); 149 state->saved_warn_routine =get_warn_routine(); 150set_error_routine(mute_routine); 151set_warn_routine(mute_routine); 152} 153 154return0; 155} 156 157static voidset_default_whitespace_mode(struct apply_state *state) 158{ 159if(!state->whitespace_option && !apply_default_whitespace) 160 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error); 161} 162 163/* 164 * This represents one "hunk" from a patch, starting with 165 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 166 * patch text is pointed at by patch, and its byte length 167 * is stored in size. leading and trailing are the number 168 * of context lines. 169 */ 170struct fragment { 171unsigned long leading, trailing; 172unsigned long oldpos, oldlines; 173unsigned long newpos, newlines; 174/* 175 * 'patch' is usually borrowed from buf in apply_patch(), 176 * but some codepaths store an allocated buffer. 177 */ 178const char*patch; 179unsigned free_patch:1, 180 rejected:1; 181int size; 182int linenr; 183struct fragment *next; 184}; 185 186/* 187 * When dealing with a binary patch, we reuse "leading" field 188 * to store the type of the binary hunk, either deflated "delta" 189 * or deflated "literal". 190 */ 191#define binary_patch_method leading 192#define BINARY_DELTA_DEFLATED 1 193#define BINARY_LITERAL_DEFLATED 2 194 195/* 196 * This represents a "patch" to a file, both metainfo changes 197 * such as creation/deletion, filemode and content changes represented 198 * as a series of fragments. 199 */ 200struct patch { 201char*new_name, *old_name, *def_name; 202unsigned int old_mode, new_mode; 203int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 204int rejected; 205unsigned ws_rule; 206int lines_added, lines_deleted; 207int score; 208int extension_linenr;/* first line specifying delete/new/rename/copy */ 209unsigned int is_toplevel_relative:1; 210unsigned int inaccurate_eof:1; 211unsigned int is_binary:1; 212unsigned int is_copy:1; 213unsigned int is_rename:1; 214unsigned int recount:1; 215unsigned int conflicted_threeway:1; 216unsigned int direct_to_threeway:1; 217unsigned int crlf_in_old:1; 218struct fragment *fragments; 219char*result; 220size_t resultsize; 221char old_sha1_prefix[41]; 222char new_sha1_prefix[41]; 223struct patch *next; 224 225/* three-way fallback result */ 226struct object_id threeway_stage[3]; 227}; 228 229static voidfree_fragment_list(struct fragment *list) 230{ 231while(list) { 232struct fragment *next = list->next; 233if(list->free_patch) 234free((char*)list->patch); 235free(list); 236 list = next; 237} 238} 239 240static voidfree_patch(struct patch *patch) 241{ 242free_fragment_list(patch->fragments); 243free(patch->def_name); 244free(patch->old_name); 245free(patch->new_name); 246free(patch->result); 247free(patch); 248} 249 250static voidfree_patch_list(struct patch *list) 251{ 252while(list) { 253struct patch *next = list->next; 254free_patch(list); 255 list = next; 256} 257} 258 259/* 260 * A line in a file, len-bytes long (includes the terminating LF, 261 * except for an incomplete line at the end if the file ends with 262 * one), and its contents hashes to 'hash'. 263 */ 264struct line { 265size_t len; 266unsigned hash :24; 267unsigned flag :8; 268#define LINE_COMMON 1 269#define LINE_PATCHED 2 270}; 271 272/* 273 * This represents a "file", which is an array of "lines". 274 */ 275struct image { 276char*buf; 277size_t len; 278size_t nr; 279size_t alloc; 280struct line *line_allocated; 281struct line *line; 282}; 283 284static uint32_thash_line(const char*cp,size_t len) 285{ 286size_t i; 287uint32_t h; 288for(i =0, h =0; i < len; i++) { 289if(!isspace(cp[i])) { 290 h = h *3+ (cp[i] &0xff); 291} 292} 293return h; 294} 295 296/* 297 * Compare lines s1 of length n1 and s2 of length n2, ignoring 298 * whitespace difference. Returns 1 if they match, 0 otherwise 299 */ 300static intfuzzy_matchlines(const char*s1,size_t n1, 301const char*s2,size_t n2) 302{ 303const char*end1 = s1 + n1; 304const char*end2 = s2 + n2; 305 306/* ignore line endings */ 307while(s1 < end1 && (end1[-1] =='\r'|| end1[-1] =='\n')) 308 end1--; 309while(s2 < end2 && (end2[-1] =='\r'|| end2[-1] =='\n')) 310 end2--; 311 312while(s1 < end1 && s2 < end2) { 313if(isspace(*s1)) { 314/* 315 * Skip whitespace. We check on both buffers 316 * because we don't want "a b" to match "ab". 317 */ 318if(!isspace(*s2)) 319return0; 320while(s1 < end1 &&isspace(*s1)) 321 s1++; 322while(s2 < end2 &&isspace(*s2)) 323 s2++; 324}else if(*s1++ != *s2++) 325return0; 326} 327 328/* If we reached the end on one side only, lines don't match. */ 329return s1 == end1 && s2 == end2; 330} 331 332static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 333{ 334ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 335 img->line_allocated[img->nr].len = len; 336 img->line_allocated[img->nr].hash =hash_line(bol, len); 337 img->line_allocated[img->nr].flag = flag; 338 img->nr++; 339} 340 341/* 342 * "buf" has the file contents to be patched (read from various sources). 343 * attach it to "image" and add line-based index to it. 344 * "image" now owns the "buf". 345 */ 346static voidprepare_image(struct image *image,char*buf,size_t len, 347int prepare_linetable) 348{ 349const char*cp, *ep; 350 351memset(image,0,sizeof(*image)); 352 image->buf = buf; 353 image->len = len; 354 355if(!prepare_linetable) 356return; 357 358 ep = image->buf + image->len; 359 cp = image->buf; 360while(cp < ep) { 361const char*next; 362for(next = cp; next < ep && *next !='\n'; next++) 363; 364if(next < ep) 365 next++; 366add_line_info(image, cp, next - cp,0); 367 cp = next; 368} 369 image->line = image->line_allocated; 370} 371 372static voidclear_image(struct image *image) 373{ 374free(image->buf); 375free(image->line_allocated); 376memset(image,0,sizeof(*image)); 377} 378 379/* fmt must contain _one_ %s and no other substitution */ 380static voidsay_patch_name(FILE*output,const char*fmt,struct patch *patch) 381{ 382struct strbuf sb = STRBUF_INIT; 383 384if(patch->old_name && patch->new_name && 385strcmp(patch->old_name, patch->new_name)) { 386quote_c_style(patch->old_name, &sb, NULL,0); 387strbuf_addstr(&sb," => "); 388quote_c_style(patch->new_name, &sb, NULL,0); 389}else{ 390const char*n = patch->new_name; 391if(!n) 392 n = patch->old_name; 393quote_c_style(n, &sb, NULL,0); 394} 395fprintf(output, fmt, sb.buf); 396fputc('\n', output); 397strbuf_release(&sb); 398} 399 400#define SLOP (16) 401 402static intread_patch_file(struct strbuf *sb,int fd) 403{ 404if(strbuf_read(sb, fd,0) <0) 405returnerror_errno("git apply: failed to read"); 406 407/* 408 * Make sure that we have some slop in the buffer 409 * so that we can do speculative "memcmp" etc, and 410 * see to it that it is NUL-filled. 411 */ 412strbuf_grow(sb, SLOP); 413memset(sb->buf + sb->len,0, SLOP); 414return0; 415} 416 417static unsigned longlinelen(const char*buffer,unsigned long size) 418{ 419unsigned long len =0; 420while(size--) { 421 len++; 422if(*buffer++ =='\n') 423break; 424} 425return len; 426} 427 428static intis_dev_null(const char*str) 429{ 430returnskip_prefix(str,"/dev/null", &str) &&isspace(*str); 431} 432 433#define TERM_SPACE 1 434#define TERM_TAB 2 435 436static intname_terminate(int c,int terminate) 437{ 438if(c ==' '&& !(terminate & TERM_SPACE)) 439return0; 440if(c =='\t'&& !(terminate & TERM_TAB)) 441return0; 442 443return1; 444} 445 446/* remove double slashes to make --index work with such filenames */ 447static char*squash_slash(char*name) 448{ 449int i =0, j =0; 450 451if(!name) 452return NULL; 453 454while(name[i]) { 455if((name[j++] = name[i++]) =='/') 456while(name[i] =='/') 457 i++; 458} 459 name[j] ='\0'; 460return name; 461} 462 463static char*find_name_gnu(struct apply_state *state, 464const char*line, 465const char*def, 466int p_value) 467{ 468struct strbuf name = STRBUF_INIT; 469char*cp; 470 471/* 472 * Proposed "new-style" GNU patch/diff format; see 473 * http://marc.info/?l=git&m=112927316408690&w=2 474 */ 475if(unquote_c_style(&name, line, NULL)) { 476strbuf_release(&name); 477return NULL; 478} 479 480for(cp = name.buf; p_value; p_value--) { 481 cp =strchr(cp,'/'); 482if(!cp) { 483strbuf_release(&name); 484return NULL; 485} 486 cp++; 487} 488 489strbuf_remove(&name,0, cp - name.buf); 490if(state->root.len) 491strbuf_insert(&name,0, state->root.buf, state->root.len); 492returnsquash_slash(strbuf_detach(&name, NULL)); 493} 494 495static size_tsane_tz_len(const char*line,size_t len) 496{ 497const char*tz, *p; 498 499if(len <strlen(" +0500") || line[len-strlen(" +0500")] !=' ') 500return0; 501 tz = line + len -strlen(" +0500"); 502 503if(tz[1] !='+'&& tz[1] !='-') 504return0; 505 506for(p = tz +2; p != line + len; p++) 507if(!isdigit(*p)) 508return0; 509 510return line + len - tz; 511} 512 513static size_ttz_with_colon_len(const char*line,size_t len) 514{ 515const char*tz, *p; 516 517if(len <strlen(" +08:00") || line[len -strlen(":00")] !=':') 518return0; 519 tz = line + len -strlen(" +08:00"); 520 521if(tz[0] !=' '|| (tz[1] !='+'&& tz[1] !='-')) 522return0; 523 p = tz +2; 524if(!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 525!isdigit(*p++) || !isdigit(*p++)) 526return0; 527 528return line + len - tz; 529} 530 531static size_tdate_len(const char*line,size_t len) 532{ 533const char*date, *p; 534 535if(len <strlen("72-02-05") || line[len-strlen("-05")] !='-') 536return0; 537 p = date = line + len -strlen("72-02-05"); 538 539if(!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 540!isdigit(*p++) || !isdigit(*p++) || *p++ !='-'|| 541!isdigit(*p++) || !isdigit(*p++))/* Not a date. */ 542return0; 543 544if(date - line >=strlen("19") && 545isdigit(date[-1]) &&isdigit(date[-2]))/* 4-digit year */ 546 date -=strlen("19"); 547 548return line + len - date; 549} 550 551static size_tshort_time_len(const char*line,size_t len) 552{ 553const char*time, *p; 554 555if(len <strlen(" 07:01:32") || line[len-strlen(":32")] !=':') 556return0; 557 p = time = line + len -strlen(" 07:01:32"); 558 559/* Permit 1-digit hours? */ 560if(*p++ !=' '|| 561!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 562!isdigit(*p++) || !isdigit(*p++) || *p++ !=':'|| 563!isdigit(*p++) || !isdigit(*p++))/* Not a time. */ 564return0; 565 566return line + len - time; 567} 568 569static size_tfractional_time_len(const char*line,size_t len) 570{ 571const char*p; 572size_t n; 573 574/* Expected format: 19:41:17.620000023 */ 575if(!len || !isdigit(line[len -1])) 576return0; 577 p = line + len -1; 578 579/* Fractional seconds. */ 580while(p > line &&isdigit(*p)) 581 p--; 582if(*p !='.') 583return0; 584 585/* Hours, minutes, and whole seconds. */ 586 n =short_time_len(line, p - line); 587if(!n) 588return0; 589 590return line + len - p + n; 591} 592 593static size_ttrailing_spaces_len(const char*line,size_t len) 594{ 595const char*p; 596 597/* Expected format: ' ' x (1 or more) */ 598if(!len || line[len -1] !=' ') 599return0; 600 601 p = line + len; 602while(p != line) { 603 p--; 604if(*p !=' ') 605return line + len - (p +1); 606} 607 608/* All spaces! */ 609return len; 610} 611 612static size_tdiff_timestamp_len(const char*line,size_t len) 613{ 614const char*end = line + len; 615size_t n; 616 617/* 618 * Posix: 2010-07-05 19:41:17 619 * GNU: 2010-07-05 19:41:17.620000023 -0500 620 */ 621 622if(!isdigit(end[-1])) 623return0; 624 625 n =sane_tz_len(line, end - line); 626if(!n) 627 n =tz_with_colon_len(line, end - line); 628 end -= n; 629 630 n =short_time_len(line, end - line); 631if(!n) 632 n =fractional_time_len(line, end - line); 633 end -= n; 634 635 n =date_len(line, end - line); 636if(!n)/* No date. Too bad. */ 637return0; 638 end -= n; 639 640if(end == line)/* No space before date. */ 641return0; 642if(end[-1] =='\t') {/* Success! */ 643 end--; 644return line + len - end; 645} 646if(end[-1] !=' ')/* No space before date. */ 647return0; 648 649/* Whitespace damage. */ 650 end -=trailing_spaces_len(line, end - line); 651return line + len - end; 652} 653 654static char*find_name_common(struct apply_state *state, 655const char*line, 656const char*def, 657int p_value, 658const char*end, 659int terminate) 660{ 661int len; 662const char*start = NULL; 663 664if(p_value ==0) 665 start = line; 666while(line != end) { 667char c = *line; 668 669if(!end &&isspace(c)) { 670if(c =='\n') 671break; 672if(name_terminate(c, terminate)) 673break; 674} 675 line++; 676if(c =='/'&& !--p_value) 677 start = line; 678} 679if(!start) 680returnsquash_slash(xstrdup_or_null(def)); 681 len = line - start; 682if(!len) 683returnsquash_slash(xstrdup_or_null(def)); 684 685/* 686 * Generally we prefer the shorter name, especially 687 * if the other one is just a variation of that with 688 * something else tacked on to the end (ie "file.orig" 689 * or "file~"). 690 */ 691if(def) { 692int deflen =strlen(def); 693if(deflen < len && !strncmp(start, def, deflen)) 694returnsquash_slash(xstrdup(def)); 695} 696 697if(state->root.len) { 698char*ret =xstrfmt("%s%.*s", state->root.buf, len, start); 699returnsquash_slash(ret); 700} 701 702returnsquash_slash(xmemdupz(start, len)); 703} 704 705static char*find_name(struct apply_state *state, 706const char*line, 707char*def, 708int p_value, 709int terminate) 710{ 711if(*line =='"') { 712char*name =find_name_gnu(state, line, def, p_value); 713if(name) 714return name; 715} 716 717returnfind_name_common(state, line, def, p_value, NULL, terminate); 718} 719 720static char*find_name_traditional(struct apply_state *state, 721const char*line, 722char*def, 723int p_value) 724{ 725size_t len; 726size_t date_len; 727 728if(*line =='"') { 729char*name =find_name_gnu(state, line, def, p_value); 730if(name) 731return name; 732} 733 734 len =strchrnul(line,'\n') - line; 735 date_len =diff_timestamp_len(line, len); 736if(!date_len) 737returnfind_name_common(state, line, def, p_value, NULL, TERM_TAB); 738 len -= date_len; 739 740returnfind_name_common(state, line, def, p_value, line + len,0); 741} 742 743/* 744 * Given the string after "--- " or "+++ ", guess the appropriate 745 * p_value for the given patch. 746 */ 747static intguess_p_value(struct apply_state *state,const char*nameline) 748{ 749char*name, *cp; 750int val = -1; 751 752if(is_dev_null(nameline)) 753return-1; 754 name =find_name_traditional(state, nameline, NULL,0); 755if(!name) 756return-1; 757 cp =strchr(name,'/'); 758if(!cp) 759 val =0; 760else if(state->prefix) { 761/* 762 * Does it begin with "a/$our-prefix" and such? Then this is 763 * very likely to apply to our directory. 764 */ 765if(starts_with(name, state->prefix)) 766 val =count_slashes(state->prefix); 767else{ 768 cp++; 769if(starts_with(cp, state->prefix)) 770 val =count_slashes(state->prefix) +1; 771} 772} 773free(name); 774return val; 775} 776 777/* 778 * Does the ---/+++ line have the POSIX timestamp after the last HT? 779 * GNU diff puts epoch there to signal a creation/deletion event. Is 780 * this such a timestamp? 781 */ 782static inthas_epoch_timestamp(const char*nameline) 783{ 784/* 785 * We are only interested in epoch timestamp; any non-zero 786 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 787 * For the same reason, the date must be either 1969-12-31 or 788 * 1970-01-01, and the seconds part must be "00". 789 */ 790const char stamp_regexp[] = 791"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?" 792" " 793"([-+][0-2][0-9]:?[0-5][0-9])\n"; 794const char*timestamp = NULL, *cp, *colon; 795static regex_t *stamp; 796 regmatch_t m[10]; 797int zoneoffset, epoch_hour, hour, minute; 798int status; 799 800for(cp = nameline; *cp !='\n'; cp++) { 801if(*cp =='\t') 802 timestamp = cp +1; 803} 804if(!timestamp) 805return0; 806 807/* 808 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 809 * (west of GMT) or 1970-01-01 (east of GMT) 810 */ 811if(skip_prefix(timestamp,"1969-12-31 ", ×tamp)) 812 epoch_hour =24; 813else if(skip_prefix(timestamp,"1970-01-01 ", ×tamp)) 814 epoch_hour =0; 815else 816return0; 817 818if(!stamp) { 819 stamp =xmalloc(sizeof(*stamp)); 820if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 821warning(_("Cannot prepare timestamp regexp%s"), 822 stamp_regexp); 823return0; 824} 825} 826 827 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 828if(status) { 829if(status != REG_NOMATCH) 830warning(_("regexec returned%dfor input:%s"), 831 status, timestamp); 832return0; 833} 834 835 hour =strtol(timestamp, NULL,10); 836 minute =strtol(timestamp + m[1].rm_so, NULL,10); 837 838 zoneoffset =strtol(timestamp + m[3].rm_so +1, (char**) &colon,10); 839if(*colon ==':') 840 zoneoffset = zoneoffset *60+strtol(colon +1, NULL,10); 841else 842 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 843if(timestamp[m[3].rm_so] =='-') 844 zoneoffset = -zoneoffset; 845 846return hour *60+ minute - zoneoffset == epoch_hour *60; 847} 848 849/* 850 * Get the name etc info from the ---/+++ lines of a traditional patch header 851 * 852 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 853 * files, we can happily check the index for a match, but for creating a 854 * new file we should try to match whatever "patch" does. I have no idea. 855 */ 856static intparse_traditional_patch(struct apply_state *state, 857const char*first, 858const char*second, 859struct patch *patch) 860{ 861char*name; 862 863 first +=4;/* skip "--- " */ 864 second +=4;/* skip "+++ " */ 865if(!state->p_value_known) { 866int p, q; 867 p =guess_p_value(state, first); 868 q =guess_p_value(state, second); 869if(p <0) p = q; 870if(0<= p && p == q) { 871 state->p_value = p; 872 state->p_value_known =1; 873} 874} 875if(is_dev_null(first)) { 876 patch->is_new =1; 877 patch->is_delete =0; 878 name =find_name_traditional(state, second, NULL, state->p_value); 879 patch->new_name = name; 880}else if(is_dev_null(second)) { 881 patch->is_new =0; 882 patch->is_delete =1; 883 name =find_name_traditional(state, first, NULL, state->p_value); 884 patch->old_name = name; 885}else{ 886char*first_name; 887 first_name =find_name_traditional(state, first, NULL, state->p_value); 888 name =find_name_traditional(state, second, first_name, state->p_value); 889free(first_name); 890if(has_epoch_timestamp(first)) { 891 patch->is_new =1; 892 patch->is_delete =0; 893 patch->new_name = name; 894}else if(has_epoch_timestamp(second)) { 895 patch->is_new =0; 896 patch->is_delete =1; 897 patch->old_name = name; 898}else{ 899 patch->old_name = name; 900 patch->new_name =xstrdup_or_null(name); 901} 902} 903if(!name) 904returnerror(_("unable to find filename in patch at line%d"), state->linenr); 905 906return0; 907} 908 909static intgitdiff_hdrend(struct apply_state *state, 910const char*line, 911struct patch *patch) 912{ 913return1; 914} 915 916/* 917 * We're anal about diff header consistency, to make 918 * sure that we don't end up having strange ambiguous 919 * patches floating around. 920 * 921 * As a result, gitdiff_{old|new}name() will check 922 * their names against any previous information, just 923 * to make sure.. 924 */ 925#define DIFF_OLD_NAME 0 926#define DIFF_NEW_NAME 1 927 928static intgitdiff_verify_name(struct apply_state *state, 929const char*line, 930int isnull, 931char**name, 932int side) 933{ 934if(!*name && !isnull) { 935*name =find_name(state, line, NULL, state->p_value, TERM_TAB); 936return0; 937} 938 939if(*name) { 940char*another; 941if(isnull) 942returnerror(_("git apply: bad git-diff - expected /dev/null, got%son line%d"), 943*name, state->linenr); 944 another =find_name(state, line, NULL, state->p_value, TERM_TAB); 945if(!another ||strcmp(another, *name)) { 946free(another); 947returnerror((side == DIFF_NEW_NAME) ? 948_("git apply: bad git-diff - inconsistent new filename on line%d") : 949_("git apply: bad git-diff - inconsistent old filename on line%d"), state->linenr); 950} 951free(another); 952}else{ 953if(!starts_with(line,"/dev/null\n")) 954returnerror(_("git apply: bad git-diff - expected /dev/null on line%d"), state->linenr); 955} 956 957return0; 958} 959 960static intgitdiff_oldname(struct apply_state *state, 961const char*line, 962struct patch *patch) 963{ 964returngitdiff_verify_name(state, line, 965 patch->is_new, &patch->old_name, 966 DIFF_OLD_NAME); 967} 968 969static intgitdiff_newname(struct apply_state *state, 970const char*line, 971struct patch *patch) 972{ 973returngitdiff_verify_name(state, line, 974 patch->is_delete, &patch->new_name, 975 DIFF_NEW_NAME); 976} 977 978static intparse_mode_line(const char*line,int linenr,unsigned int*mode) 979{ 980char*end; 981*mode =strtoul(line, &end,8); 982if(end == line || !isspace(*end)) 983returnerror(_("invalid mode on line%d:%s"), linenr, line); 984return0; 985} 986 987static intgitdiff_oldmode(struct apply_state *state, 988const char*line, 989struct patch *patch) 990{ 991returnparse_mode_line(line, state->linenr, &patch->old_mode); 992} 993 994static intgitdiff_newmode(struct apply_state *state, 995const char*line, 996struct patch *patch) 997{ 998returnparse_mode_line(line, state->linenr, &patch->new_mode); 999}10001001static intgitdiff_delete(struct apply_state *state,1002const char*line,1003struct patch *patch)1004{1005 patch->is_delete =1;1006free(patch->old_name);1007 patch->old_name =xstrdup_or_null(patch->def_name);1008returngitdiff_oldmode(state, line, patch);1009}10101011static intgitdiff_newfile(struct apply_state *state,1012const char*line,1013struct patch *patch)1014{1015 patch->is_new =1;1016free(patch->new_name);1017 patch->new_name =xstrdup_or_null(patch->def_name);1018returngitdiff_newmode(state, line, patch);1019}10201021static intgitdiff_copysrc(struct apply_state *state,1022const char*line,1023struct patch *patch)1024{1025 patch->is_copy =1;1026free(patch->old_name);1027 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1028return0;1029}10301031static intgitdiff_copydst(struct apply_state *state,1032const char*line,1033struct patch *patch)1034{1035 patch->is_copy =1;1036free(patch->new_name);1037 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1038return0;1039}10401041static intgitdiff_renamesrc(struct apply_state *state,1042const char*line,1043struct patch *patch)1044{1045 patch->is_rename =1;1046free(patch->old_name);1047 patch->old_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1048return0;1049}10501051static intgitdiff_renamedst(struct apply_state *state,1052const char*line,1053struct patch *patch)1054{1055 patch->is_rename =1;1056free(patch->new_name);1057 patch->new_name =find_name(state, line, NULL, state->p_value ? state->p_value -1:0,0);1058return0;1059}10601061static intgitdiff_similarity(struct apply_state *state,1062const char*line,1063struct patch *patch)1064{1065unsigned long val =strtoul(line, NULL,10);1066if(val <=100)1067 patch->score = val;1068return0;1069}10701071static intgitdiff_dissimilarity(struct apply_state *state,1072const char*line,1073struct patch *patch)1074{1075unsigned long val =strtoul(line, NULL,10);1076if(val <=100)1077 patch->score = val;1078return0;1079}10801081static intgitdiff_index(struct apply_state *state,1082const char*line,1083struct patch *patch)1084{1085/*1086 * index line is N hexadecimal, "..", N hexadecimal,1087 * and optional space with octal mode.1088 */1089const char*ptr, *eol;1090int len;10911092 ptr =strchr(line,'.');1093if(!ptr || ptr[1] !='.'||40< ptr - line)1094return0;1095 len = ptr - line;1096memcpy(patch->old_sha1_prefix, line, len);1097 patch->old_sha1_prefix[len] =0;10981099 line = ptr +2;1100 ptr =strchr(line,' ');1101 eol =strchrnul(line,'\n');11021103if(!ptr || eol < ptr)1104 ptr = eol;1105 len = ptr - line;11061107if(40< len)1108return0;1109memcpy(patch->new_sha1_prefix, line, len);1110 patch->new_sha1_prefix[len] =0;1111if(*ptr ==' ')1112returngitdiff_oldmode(state, ptr +1, patch);1113return0;1114}11151116/*1117 * This is normal for a diff that doesn't change anything: we'll fall through1118 * into the next diff. Tell the parser to break out.1119 */1120static intgitdiff_unrecognized(struct apply_state *state,1121const char*line,1122struct patch *patch)1123{1124return1;1125}11261127/*1128 * Skip p_value leading components from "line"; as we do not accept1129 * absolute paths, return NULL in that case.1130 */1131static const char*skip_tree_prefix(struct apply_state *state,1132const char*line,1133int llen)1134{1135int nslash;1136int i;11371138if(!state->p_value)1139return(llen && line[0] =='/') ? NULL : line;11401141 nslash = state->p_value;1142for(i =0; i < llen; i++) {1143int ch = line[i];1144if(ch =='/'&& --nslash <=0)1145return(i ==0) ? NULL : &line[i +1];1146}1147return NULL;1148}11491150/*1151 * This is to extract the same name that appears on "diff --git"1152 * line. We do not find and return anything if it is a rename1153 * patch, and it is OK because we will find the name elsewhere.1154 * We need to reliably find name only when it is mode-change only,1155 * creation or deletion of an empty file. In any of these cases,1156 * both sides are the same name under a/ and b/ respectively.1157 */1158static char*git_header_name(struct apply_state *state,1159const char*line,1160int llen)1161{1162const char*name;1163const char*second = NULL;1164size_t len, line_len;11651166 line +=strlen("diff --git ");1167 llen -=strlen("diff --git ");11681169if(*line =='"') {1170const char*cp;1171struct strbuf first = STRBUF_INIT;1172struct strbuf sp = STRBUF_INIT;11731174if(unquote_c_style(&first, line, &second))1175goto free_and_fail1;11761177/* strip the a/b prefix including trailing slash */1178 cp =skip_tree_prefix(state, first.buf, first.len);1179if(!cp)1180goto free_and_fail1;1181strbuf_remove(&first,0, cp - first.buf);11821183/*1184 * second points at one past closing dq of name.1185 * find the second name.1186 */1187while((second < line + llen) &&isspace(*second))1188 second++;11891190if(line + llen <= second)1191goto free_and_fail1;1192if(*second =='"') {1193if(unquote_c_style(&sp, second, NULL))1194goto free_and_fail1;1195 cp =skip_tree_prefix(state, sp.buf, sp.len);1196if(!cp)1197goto free_and_fail1;1198/* They must match, otherwise ignore */1199if(strcmp(cp, first.buf))1200goto free_and_fail1;1201strbuf_release(&sp);1202returnstrbuf_detach(&first, NULL);1203}12041205/* unquoted second */1206 cp =skip_tree_prefix(state, second, line + llen - second);1207if(!cp)1208goto free_and_fail1;1209if(line + llen - cp != first.len ||1210memcmp(first.buf, cp, first.len))1211goto free_and_fail1;1212returnstrbuf_detach(&first, NULL);12131214 free_and_fail1:1215strbuf_release(&first);1216strbuf_release(&sp);1217return NULL;1218}12191220/* unquoted first name */1221 name =skip_tree_prefix(state, line, llen);1222if(!name)1223return NULL;12241225/*1226 * since the first name is unquoted, a dq if exists must be1227 * the beginning of the second name.1228 */1229for(second = name; second < line + llen; second++) {1230if(*second =='"') {1231struct strbuf sp = STRBUF_INIT;1232const char*np;12331234if(unquote_c_style(&sp, second, NULL))1235goto free_and_fail2;12361237 np =skip_tree_prefix(state, sp.buf, sp.len);1238if(!np)1239goto free_and_fail2;12401241 len = sp.buf + sp.len - np;1242if(len < second - name &&1243!strncmp(np, name, len) &&1244isspace(name[len])) {1245/* Good */1246strbuf_remove(&sp,0, np - sp.buf);1247returnstrbuf_detach(&sp, NULL);1248}12491250 free_and_fail2:1251strbuf_release(&sp);1252return NULL;1253}1254}12551256/*1257 * Accept a name only if it shows up twice, exactly the same1258 * form.1259 */1260 second =strchr(name,'\n');1261if(!second)1262return NULL;1263 line_len = second - name;1264for(len =0; ; len++) {1265switch(name[len]) {1266default:1267continue;1268case'\n':1269return NULL;1270case'\t':case' ':1271/*1272 * Is this the separator between the preimage1273 * and the postimage pathname? Again, we are1274 * only interested in the case where there is1275 * no rename, as this is only to set def_name1276 * and a rename patch has the names elsewhere1277 * in an unambiguous form.1278 */1279if(!name[len +1])1280return NULL;/* no postimage name */1281 second =skip_tree_prefix(state, name + len +1,1282 line_len - (len +1));1283if(!second)1284return NULL;1285/*1286 * Does len bytes starting at "name" and "second"1287 * (that are separated by one HT or SP we just1288 * found) exactly match?1289 */1290if(second[len] =='\n'&& !strncmp(name, second, len))1291returnxmemdupz(name, len);1292}1293}1294}12951296static intcheck_header_line(struct apply_state *state,struct patch *patch)1297{1298int extensions = (patch->is_delete ==1) + (patch->is_new ==1) +1299(patch->is_rename ==1) + (patch->is_copy ==1);1300if(extensions >1)1301returnerror(_("inconsistent header lines%dand%d"),1302 patch->extension_linenr, state->linenr);1303if(extensions && !patch->extension_linenr)1304 patch->extension_linenr = state->linenr;1305return0;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(check_header_line(state, patch))1375return-1;1376if(res >0)1377return offset;1378break;1379}1380}13811382return offset;1383}13841385static intparse_num(const char*line,unsigned long*p)1386{1387char*ptr;13881389if(!isdigit(*line))1390return0;1391*p =strtoul(line, &ptr,10);1392return ptr - line;1393}13941395static intparse_range(const char*line,int len,int offset,const char*expect,1396unsigned long*p1,unsigned long*p2)1397{1398int digits, ex;13991400if(offset <0|| offset >= len)1401return-1;1402 line += offset;1403 len -= offset;14041405 digits =parse_num(line, p1);1406if(!digits)1407return-1;14081409 offset += digits;1410 line += digits;1411 len -= digits;14121413*p2 =1;1414if(*line ==',') {1415 digits =parse_num(line+1, p2);1416if(!digits)1417return-1;14181419 offset += digits+1;1420 line += digits+1;1421 len -= digits+1;1422}14231424 ex =strlen(expect);1425if(ex > len)1426return-1;1427if(memcmp(line, expect, ex))1428return-1;14291430return offset + ex;1431}14321433static voidrecount_diff(const char*line,int size,struct fragment *fragment)1434{1435int oldlines =0, newlines =0, ret =0;14361437if(size <1) {1438warning("recount: ignore empty hunk");1439return;1440}14411442for(;;) {1443int len =linelen(line, size);1444 size -= len;1445 line += len;14461447if(size <1)1448break;14491450switch(*line) {1451case' ':case'\n':1452 newlines++;1453/* fall through */1454case'-':1455 oldlines++;1456continue;1457case'+':1458 newlines++;1459continue;1460case'\\':1461continue;1462case'@':1463 ret = size <3|| !starts_with(line,"@@ ");1464break;1465case'd':1466 ret = size <5|| !starts_with(line,"diff ");1467break;1468default:1469 ret = -1;1470break;1471}1472if(ret) {1473warning(_("recount: unexpected line: %.*s"),1474(int)linelen(line, size), line);1475return;1476}1477break;1478}1479 fragment->oldlines = oldlines;1480 fragment->newlines = newlines;1481}14821483/*1484 * Parse a unified diff fragment header of the1485 * form "@@ -a,b +c,d @@"1486 */1487static intparse_fragment_header(const char*line,int len,struct fragment *fragment)1488{1489int offset;14901491if(!len || line[len-1] !='\n')1492return-1;14931494/* Figure out the number of lines in a fragment */1495 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1496 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);14971498return offset;1499}15001501/*1502 * Find file diff header1503 *1504 * Returns:1505 * -1 if no header was found1506 * -128 in case of error1507 * the size of the header in bytes (called "offset") otherwise1508 */1509static intfind_header(struct apply_state *state,1510const char*line,1511unsigned long size,1512int*hdrsize,1513struct patch *patch)1514{1515unsigned long offset, len;15161517 patch->is_toplevel_relative =0;1518 patch->is_rename = patch->is_copy =0;1519 patch->is_new = patch->is_delete = -1;1520 patch->old_mode = patch->new_mode =0;1521 patch->old_name = patch->new_name = NULL;1522for(offset =0; size >0; offset += len, size -= len, line += len, state->linenr++) {1523unsigned long nextlen;15241525 len =linelen(line, size);1526if(!len)1527break;15281529/* Testing this early allows us to take a few shortcuts.. */1530if(len <6)1531continue;15321533/*1534 * Make sure we don't find any unconnected patch fragments.1535 * That's a sign that we didn't find a header, and that a1536 * patch has become corrupted/broken up.1537 */1538if(!memcmp("@@ -", line,4)) {1539struct fragment dummy;1540if(parse_fragment_header(line, len, &dummy) <0)1541continue;1542error(_("patch fragment without header at line%d: %.*s"),1543 state->linenr, (int)len-1, line);1544return-128;1545}15461547if(size < len +6)1548break;15491550/*1551 * Git patch? It might not have a real patch, just a rename1552 * or mode change, so we handle that specially1553 */1554if(!memcmp("diff --git ", line,11)) {1555int git_hdr_len =parse_git_header(state, line, len, size, patch);1556if(git_hdr_len <0)1557return-128;1558if(git_hdr_len <= len)1559continue;1560if(!patch->old_name && !patch->new_name) {1561if(!patch->def_name) {1562error(Q_("git diff header lacks filename information when removing "1563"%dleading pathname component (line%d)",1564"git diff header lacks filename information when removing "1565"%dleading pathname components (line%d)",1566 state->p_value),1567 state->p_value, state->linenr);1568return-128;1569}1570 patch->old_name =xstrdup(patch->def_name);1571 patch->new_name =xstrdup(patch->def_name);1572}1573if((!patch->new_name && !patch->is_delete) ||1574(!patch->old_name && !patch->is_new)) {1575error(_("git diff header lacks filename information "1576"(line%d)"), state->linenr);1577return-128;1578}1579 patch->is_toplevel_relative =1;1580*hdrsize = git_hdr_len;1581return offset;1582}15831584/* --- followed by +++ ? */1585if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1586continue;15871588/*1589 * We only accept unified patches, so we want it to1590 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1591 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1592 */1593 nextlen =linelen(line + len, size - len);1594if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1595continue;15961597/* Ok, we'll consider it a patch */1598if(parse_traditional_patch(state, line, line+len, patch))1599return-128;1600*hdrsize = len + nextlen;1601 state->linenr +=2;1602return offset;1603}1604return-1;1605}16061607static voidrecord_ws_error(struct apply_state *state,1608unsigned result,1609const char*line,1610int len,1611int linenr)1612{1613char*err;16141615if(!result)1616return;16171618 state->whitespace_error++;1619if(state->squelch_whitespace_errors &&1620 state->squelch_whitespace_errors < state->whitespace_error)1621return;16221623 err =whitespace_error_string(result);1624if(state->apply_verbosity > verbosity_silent)1625fprintf(stderr,"%s:%d:%s.\n%.*s\n",1626 state->patch_input_file, linenr, err, len, line);1627free(err);1628}16291630static voidcheck_whitespace(struct apply_state *state,1631const char*line,1632int len,1633unsigned ws_rule)1634{1635unsigned result =ws_check(line +1, len -1, ws_rule);16361637record_ws_error(state, result, line +1, len -2, state->linenr);1638}16391640/*1641 * Check if the patch has context lines with CRLF or1642 * the patch wants to remove lines with CRLF.1643 */1644static voidcheck_old_for_crlf(struct patch *patch,const char*line,int len)1645{1646if(len >=2&& line[len-1] =='\n'&& line[len-2] =='\r') {1647 patch->ws_rule |= WS_CR_AT_EOL;1648 patch->crlf_in_old =1;1649}1650}165116521653/*1654 * Parse a unified diff. Note that this really needs to parse each1655 * fragment separately, since the only way to know the difference1656 * between a "---" that is part of a patch, and a "---" that starts1657 * the next patch is to look at the line counts..1658 */1659static intparse_fragment(struct apply_state *state,1660const char*line,1661unsigned long size,1662struct patch *patch,1663struct fragment *fragment)1664{1665int added, deleted;1666int len =linelen(line, size), offset;1667unsigned long oldlines, newlines;1668unsigned long leading, trailing;16691670 offset =parse_fragment_header(line, len, fragment);1671if(offset <0)1672return-1;1673if(offset >0&& patch->recount)1674recount_diff(line + offset, size - offset, fragment);1675 oldlines = fragment->oldlines;1676 newlines = fragment->newlines;1677 leading =0;1678 trailing =0;16791680/* Parse the thing.. */1681 line += len;1682 size -= len;1683 state->linenr++;1684 added = deleted =0;1685for(offset = len;16860< size;1687 offset += len, size -= len, line += len, state->linenr++) {1688if(!oldlines && !newlines)1689break;1690 len =linelen(line, size);1691if(!len || line[len-1] !='\n')1692return-1;1693switch(*line) {1694default:1695return-1;1696case'\n':/* newer GNU diff, an empty context line */1697case' ':1698 oldlines--;1699 newlines--;1700if(!deleted && !added)1701 leading++;1702 trailing++;1703check_old_for_crlf(patch, line, len);1704if(!state->apply_in_reverse &&1705 state->ws_error_action == correct_ws_error)1706check_whitespace(state, line, len, patch->ws_rule);1707break;1708case'-':1709if(!state->apply_in_reverse)1710check_old_for_crlf(patch, line, len);1711if(state->apply_in_reverse &&1712 state->ws_error_action != nowarn_ws_error)1713check_whitespace(state, line, len, patch->ws_rule);1714 deleted++;1715 oldlines--;1716 trailing =0;1717break;1718case'+':1719if(state->apply_in_reverse)1720check_old_for_crlf(patch, line, len);1721if(!state->apply_in_reverse &&1722 state->ws_error_action != nowarn_ws_error)1723check_whitespace(state, line, len, patch->ws_rule);1724 added++;1725 newlines--;1726 trailing =0;1727break;17281729/*1730 * We allow "\ No newline at end of file". Depending1731 * on locale settings when the patch was produced we1732 * don't know what this line looks like. The only1733 * thing we do know is that it begins with "\ ".1734 * Checking for 12 is just for sanity check -- any1735 * l10n of "\ No newline..." is at least that long.1736 */1737case'\\':1738if(len <12||memcmp(line,"\\",2))1739return-1;1740break;1741}1742}1743if(oldlines || newlines)1744return-1;1745if(!deleted && !added)1746return-1;17471748 fragment->leading = leading;1749 fragment->trailing = trailing;17501751/*1752 * If a fragment ends with an incomplete line, we failed to include1753 * it in the above loop because we hit oldlines == newlines == 01754 * before seeing it.1755 */1756if(12< size && !memcmp(line,"\\",2))1757 offset +=linelen(line, size);17581759 patch->lines_added += added;1760 patch->lines_deleted += deleted;17611762if(0< patch->is_new && oldlines)1763returnerror(_("new file depends on old contents"));1764if(0< patch->is_delete && newlines)1765returnerror(_("deleted file still has contents"));1766return offset;1767}17681769/*1770 * We have seen "diff --git a/... b/..." header (or a traditional patch1771 * header). Read hunks that belong to this patch into fragments and hang1772 * them to the given patch structure.1773 *1774 * The (fragment->patch, fragment->size) pair points into the memory given1775 * by the caller, not a copy, when we return.1776 *1777 * Returns:1778 * -1 in case of error,1779 * the number of bytes in the patch otherwise.1780 */1781static intparse_single_patch(struct apply_state *state,1782const char*line,1783unsigned long size,1784struct patch *patch)1785{1786unsigned long offset =0;1787unsigned long oldlines =0, newlines =0, context =0;1788struct fragment **fragp = &patch->fragments;17891790while(size >4&& !memcmp(line,"@@ -",4)) {1791struct fragment *fragment;1792int len;17931794 fragment =xcalloc(1,sizeof(*fragment));1795 fragment->linenr = state->linenr;1796 len =parse_fragment(state, line, size, patch, fragment);1797if(len <=0) {1798free(fragment);1799returnerror(_("corrupt patch at line%d"), state->linenr);1800}1801 fragment->patch = line;1802 fragment->size = len;1803 oldlines += fragment->oldlines;1804 newlines += fragment->newlines;1805 context += fragment->leading + fragment->trailing;18061807*fragp = fragment;1808 fragp = &fragment->next;18091810 offset += len;1811 line += len;1812 size -= len;1813}18141815/*1816 * If something was removed (i.e. we have old-lines) it cannot1817 * be creation, and if something was added it cannot be1818 * deletion. However, the reverse is not true; --unified=01819 * patches that only add are not necessarily creation even1820 * though they do not have any old lines, and ones that only1821 * delete are not necessarily deletion.1822 *1823 * Unfortunately, a real creation/deletion patch do _not_ have1824 * any context line by definition, so we cannot safely tell it1825 * apart with --unified=0 insanity. At least if the patch has1826 * more than one hunk it is not creation or deletion.1827 */1828if(patch->is_new <0&&1829(oldlines || (patch->fragments && patch->fragments->next)))1830 patch->is_new =0;1831if(patch->is_delete <0&&1832(newlines || (patch->fragments && patch->fragments->next)))1833 patch->is_delete =0;18341835if(0< patch->is_new && oldlines)1836returnerror(_("new file%sdepends on old contents"), patch->new_name);1837if(0< patch->is_delete && newlines)1838returnerror(_("deleted file%sstill has contents"), patch->old_name);1839if(!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)1840fprintf_ln(stderr,1841_("** warning: "1842"file%sbecomes empty but is not deleted"),1843 patch->new_name);18441845return offset;1846}18471848staticinlineintmetadata_changes(struct patch *patch)1849{1850return patch->is_rename >0||1851 patch->is_copy >0||1852 patch->is_new >0||1853 patch->is_delete ||1854(patch->old_mode && patch->new_mode &&1855 patch->old_mode != patch->new_mode);1856}18571858static char*inflate_it(const void*data,unsigned long size,1859unsigned long inflated_size)1860{1861 git_zstream stream;1862void*out;1863int st;18641865memset(&stream,0,sizeof(stream));18661867 stream.next_in = (unsigned char*)data;1868 stream.avail_in = size;1869 stream.next_out = out =xmalloc(inflated_size);1870 stream.avail_out = inflated_size;1871git_inflate_init(&stream);1872 st =git_inflate(&stream, Z_FINISH);1873git_inflate_end(&stream);1874if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1875free(out);1876return NULL;1877}1878return out;1879}18801881/*1882 * Read a binary hunk and return a new fragment; fragment->patch1883 * points at an allocated memory that the caller must free, so1884 * it is marked as "->free_patch = 1".1885 */1886static struct fragment *parse_binary_hunk(struct apply_state *state,1887char**buf_p,1888unsigned long*sz_p,1889int*status_p,1890int*used_p)1891{1892/*1893 * Expect a line that begins with binary patch method ("literal"1894 * or "delta"), followed by the length of data before deflating.1895 * a sequence of 'length-byte' followed by base-85 encoded data1896 * should follow, terminated by a newline.1897 *1898 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1899 * and we would limit the patch line to 66 characters,1900 * so one line can fit up to 13 groups that would decode1901 * to 52 bytes max. The length byte 'A'-'Z' corresponds1902 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1903 */1904int llen, used;1905unsigned long size = *sz_p;1906char*buffer = *buf_p;1907int patch_method;1908unsigned long origlen;1909char*data = NULL;1910int hunk_size =0;1911struct fragment *frag;19121913 llen =linelen(buffer, size);1914 used = llen;19151916*status_p =0;19171918if(starts_with(buffer,"delta ")) {1919 patch_method = BINARY_DELTA_DEFLATED;1920 origlen =strtoul(buffer +6, NULL,10);1921}1922else if(starts_with(buffer,"literal ")) {1923 patch_method = BINARY_LITERAL_DEFLATED;1924 origlen =strtoul(buffer +8, NULL,10);1925}1926else1927return NULL;19281929 state->linenr++;1930 buffer += llen;1931while(1) {1932int byte_length, max_byte_length, newsize;1933 llen =linelen(buffer, size);1934 used += llen;1935 state->linenr++;1936if(llen ==1) {1937/* consume the blank line */1938 buffer++;1939 size--;1940break;1941}1942/*1943 * Minimum line is "A00000\n" which is 7-byte long,1944 * and the line length must be multiple of 5 plus 2.1945 */1946if((llen <7) || (llen-2) %5)1947goto corrupt;1948 max_byte_length = (llen -2) /5*4;1949 byte_length = *buffer;1950if('A'<= byte_length && byte_length <='Z')1951 byte_length = byte_length -'A'+1;1952else if('a'<= byte_length && byte_length <='z')1953 byte_length = byte_length -'a'+27;1954else1955goto corrupt;1956/* if the input length was not multiple of 4, we would1957 * have filler at the end but the filler should never1958 * exceed 3 bytes1959 */1960if(max_byte_length < byte_length ||1961 byte_length <= max_byte_length -4)1962goto corrupt;1963 newsize = hunk_size + byte_length;1964 data =xrealloc(data, newsize);1965if(decode_85(data + hunk_size, buffer +1, byte_length))1966goto corrupt;1967 hunk_size = newsize;1968 buffer += llen;1969 size -= llen;1970}19711972 frag =xcalloc(1,sizeof(*frag));1973 frag->patch =inflate_it(data, hunk_size, origlen);1974 frag->free_patch =1;1975if(!frag->patch)1976goto corrupt;1977free(data);1978 frag->size = origlen;1979*buf_p = buffer;1980*sz_p = size;1981*used_p = used;1982 frag->binary_patch_method = patch_method;1983return frag;19841985 corrupt:1986free(data);1987*status_p = -1;1988error(_("corrupt binary patch at line%d: %.*s"),1989 state->linenr-1, llen-1, buffer);1990return NULL;1991}19921993/*1994 * Returns:1995 * -1 in case of error,1996 * the length of the parsed binary patch otherwise1997 */1998static intparse_binary(struct apply_state *state,1999char*buffer,2000unsigned long size,2001struct patch *patch)2002{2003/*2004 * We have read "GIT binary patch\n"; what follows is a line2005 * that says the patch method (currently, either "literal" or2006 * "delta") and the length of data before deflating; a2007 * sequence of 'length-byte' followed by base-85 encoded data2008 * follows.2009 *2010 * When a binary patch is reversible, there is another binary2011 * hunk in the same format, starting with patch method (either2012 * "literal" or "delta") with the length of data, and a sequence2013 * of length-byte + base-85 encoded data, terminated with another2014 * empty line. This data, when applied to the postimage, produces2015 * the preimage.2016 */2017struct fragment *forward;2018struct fragment *reverse;2019int status;2020int used, used_1;20212022 forward =parse_binary_hunk(state, &buffer, &size, &status, &used);2023if(!forward && !status)2024/* there has to be one hunk (forward hunk) */2025returnerror(_("unrecognized binary patch at line%d"), state->linenr-1);2026if(status)2027/* otherwise we already gave an error message */2028return status;20292030 reverse =parse_binary_hunk(state, &buffer, &size, &status, &used_1);2031if(reverse)2032 used += used_1;2033else if(status) {2034/*2035 * Not having reverse hunk is not an error, but having2036 * a corrupt reverse hunk is.2037 */2038free((void*) forward->patch);2039free(forward);2040return status;2041}2042 forward->next = reverse;2043 patch->fragments = forward;2044 patch->is_binary =1;2045return used;2046}20472048static voidprefix_one(struct apply_state *state,char**name)2049{2050char*old_name = *name;2051if(!old_name)2052return;2053*name =prefix_filename(state->prefix, *name);2054free(old_name);2055}20562057static voidprefix_patch(struct apply_state *state,struct patch *p)2058{2059if(!state->prefix || p->is_toplevel_relative)2060return;2061prefix_one(state, &p->new_name);2062prefix_one(state, &p->old_name);2063}20642065/*2066 * include/exclude2067 */20682069static voidadd_name_limit(struct apply_state *state,2070const char*name,2071int exclude)2072{2073struct string_list_item *it;20742075 it =string_list_append(&state->limit_by_name, name);2076 it->util = exclude ? NULL : (void*)1;2077}20782079static intuse_patch(struct apply_state *state,struct patch *p)2080{2081const char*pathname = p->new_name ? p->new_name : p->old_name;2082int i;20832084/* Paths outside are not touched regardless of "--include" */2085if(state->prefix && *state->prefix) {2086const char*rest;2087if(!skip_prefix(pathname, state->prefix, &rest) || !*rest)2088return0;2089}20902091/* See if it matches any of exclude/include rule */2092for(i =0; i < state->limit_by_name.nr; i++) {2093struct string_list_item *it = &state->limit_by_name.items[i];2094if(!wildmatch(it->string, pathname,0))2095return(it->util != NULL);2096}20972098/*2099 * If we had any include, a path that does not match any rule is2100 * not used. Otherwise, we saw bunch of exclude rules (or none)2101 * and such a path is used.2102 */2103return!state->has_include;2104}21052106/*2107 * Read the patch text in "buffer" that extends for "size" bytes; stop2108 * reading after seeing a single patch (i.e. changes to a single file).2109 * Create fragments (i.e. patch hunks) and hang them to the given patch.2110 *2111 * Returns:2112 * -1 if no header was found or parse_binary() failed,2113 * -128 on another error,2114 * the number of bytes consumed otherwise,2115 * so that the caller can call us again for the next patch.2116 */2117static intparse_chunk(struct apply_state *state,char*buffer,unsigned long size,struct patch *patch)2118{2119int hdrsize, patchsize;2120int offset =find_header(state, buffer, size, &hdrsize, patch);21212122if(offset <0)2123return offset;21242125prefix_patch(state, patch);21262127if(!use_patch(state, patch))2128 patch->ws_rule =0;2129else2130 patch->ws_rule =whitespace_rule(patch->new_name2131? patch->new_name2132: patch->old_name);21332134 patchsize =parse_single_patch(state,2135 buffer + offset + hdrsize,2136 size - offset - hdrsize,2137 patch);21382139if(patchsize <0)2140return-128;21412142if(!patchsize) {2143static const char git_binary[] ="GIT binary patch\n";2144int hd = hdrsize + offset;2145unsigned long llen =linelen(buffer + hd, size - hd);21462147if(llen ==sizeof(git_binary) -1&&2148!memcmp(git_binary, buffer + hd, llen)) {2149int used;2150 state->linenr++;2151 used =parse_binary(state, buffer + hd + llen,2152 size - hd - llen, patch);2153if(used <0)2154return-1;2155if(used)2156 patchsize = used + llen;2157else2158 patchsize =0;2159}2160else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {2161static const char*binhdr[] = {2162"Binary files ",2163"Files ",2164 NULL,2165};2166int i;2167for(i =0; binhdr[i]; i++) {2168int len =strlen(binhdr[i]);2169if(len < size - hd &&2170!memcmp(binhdr[i], buffer + hd, len)) {2171 state->linenr++;2172 patch->is_binary =1;2173 patchsize = llen;2174break;2175}2176}2177}21782179/* Empty patch cannot be applied if it is a text patch2180 * without metadata change. A binary patch appears2181 * empty to us here.2182 */2183if((state->apply || state->check) &&2184(!patch->is_binary && !metadata_changes(patch))) {2185error(_("patch with only garbage at line%d"), state->linenr);2186return-128;2187}2188}21892190return offset + hdrsize + patchsize;2191}21922193static voidreverse_patches(struct patch *p)2194{2195for(; p; p = p->next) {2196struct fragment *frag = p->fragments;21972198SWAP(p->new_name, p->old_name);2199SWAP(p->new_mode, p->old_mode);2200SWAP(p->is_new, p->is_delete);2201SWAP(p->lines_added, p->lines_deleted);2202SWAP(p->old_sha1_prefix, p->new_sha1_prefix);22032204for(; frag; frag = frag->next) {2205SWAP(frag->newpos, frag->oldpos);2206SWAP(frag->newlines, frag->oldlines);2207}2208}2209}22102211static const char pluses[] =2212"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";2213static const char minuses[]=2214"----------------------------------------------------------------------";22152216static voidshow_stats(struct apply_state *state,struct patch *patch)2217{2218struct strbuf qname = STRBUF_INIT;2219char*cp = patch->new_name ? patch->new_name : patch->old_name;2220int max, add, del;22212222quote_c_style(cp, &qname, NULL,0);22232224/*2225 * "scale" the filename2226 */2227 max = state->max_len;2228if(max >50)2229 max =50;22302231if(qname.len > max) {2232 cp =strchr(qname.buf + qname.len +3- max,'/');2233if(!cp)2234 cp = qname.buf + qname.len +3- max;2235strbuf_splice(&qname,0, cp - qname.buf,"...",3);2236}22372238if(patch->is_binary) {2239printf(" %-*s | Bin\n", max, qname.buf);2240strbuf_release(&qname);2241return;2242}22432244printf(" %-*s |", max, qname.buf);2245strbuf_release(&qname);22462247/*2248 * scale the add/delete2249 */2250 max = max + state->max_change >70?70- max : state->max_change;2251 add = patch->lines_added;2252 del = patch->lines_deleted;22532254if(state->max_change >0) {2255int total = ((add + del) * max + state->max_change /2) / state->max_change;2256 add = (add * max + state->max_change /2) / state->max_change;2257 del = total - add;2258}2259printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,2260 add, pluses, del, minuses);2261}22622263static intread_old_data(struct stat *st,struct patch *patch,2264const char*path,struct strbuf *buf)2265{2266int conv_flags = patch->crlf_in_old ?2267 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;2268switch(st->st_mode & S_IFMT) {2269case S_IFLNK:2270if(strbuf_readlink(buf, path, st->st_size) <0)2271returnerror(_("unable to read symlink%s"), path);2272return0;2273case S_IFREG:2274if(strbuf_read_file(buf, path, st->st_size) != st->st_size)2275returnerror(_("unable to open or read%s"), path);2276/*2277 * "git apply" without "--index/--cached" should never look2278 * at the index; the target file may not have been added to2279 * the index yet, and we may not even be in any Git repository.2280 * Pass NULL to convert_to_git() to stress this; the function2281 * should never look at the index when explicit crlf option2282 * is given.2283 */2284convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);2285return0;2286default:2287return-1;2288}2289}22902291/*2292 * Update the preimage, and the common lines in postimage,2293 * from buffer buf of length len. If postlen is 0 the postimage2294 * is updated in place, otherwise it's updated on a new buffer2295 * of length postlen2296 */22972298static voidupdate_pre_post_images(struct image *preimage,2299struct image *postimage,2300char*buf,2301size_t len,size_t postlen)2302{2303int i, ctx, reduced;2304char*new_buf, *old_buf, *fixed;2305struct image fixed_preimage;23062307/*2308 * Update the preimage with whitespace fixes. Note that we2309 * are not losing preimage->buf -- apply_one_fragment() will2310 * free "oldlines".2311 */2312prepare_image(&fixed_preimage, buf, len,1);2313assert(postlen2314? fixed_preimage.nr == preimage->nr2315: fixed_preimage.nr <= preimage->nr);2316for(i =0; i < fixed_preimage.nr; i++)2317 fixed_preimage.line[i].flag = preimage->line[i].flag;2318free(preimage->line_allocated);2319*preimage = fixed_preimage;23202321/*2322 * Adjust the common context lines in postimage. This can be2323 * done in-place when we are shrinking it with whitespace2324 * fixing, but needs a new buffer when ignoring whitespace or2325 * expanding leading tabs to spaces.2326 *2327 * We trust the caller to tell us if the update can be done2328 * in place (postlen==0) or not.2329 */2330 old_buf = postimage->buf;2331if(postlen)2332 new_buf = postimage->buf =xmalloc(postlen);2333else2334 new_buf = old_buf;2335 fixed = preimage->buf;23362337for(i = reduced = ctx =0; i < postimage->nr; i++) {2338size_t l_len = postimage->line[i].len;2339if(!(postimage->line[i].flag & LINE_COMMON)) {2340/* an added line -- no counterparts in preimage */2341memmove(new_buf, old_buf, l_len);2342 old_buf += l_len;2343 new_buf += l_len;2344continue;2345}23462347/* a common context -- skip it in the original postimage */2348 old_buf += l_len;23492350/* and find the corresponding one in the fixed preimage */2351while(ctx < preimage->nr &&2352!(preimage->line[ctx].flag & LINE_COMMON)) {2353 fixed += preimage->line[ctx].len;2354 ctx++;2355}23562357/*2358 * preimage is expected to run out, if the caller2359 * fixed addition of trailing blank lines.2360 */2361if(preimage->nr <= ctx) {2362 reduced++;2363continue;2364}23652366/* and copy it in, while fixing the line length */2367 l_len = preimage->line[ctx].len;2368memcpy(new_buf, fixed, l_len);2369 new_buf += l_len;2370 fixed += l_len;2371 postimage->line[i].len = l_len;2372 ctx++;2373}23742375if(postlen2376? postlen < new_buf - postimage->buf2377: postimage->len < new_buf - postimage->buf)2378die("BUG: caller miscounted postlen: asked%d, orig =%d, used =%d",2379(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));23802381/* Fix the length of the whole thing */2382 postimage->len = new_buf - postimage->buf;2383 postimage->nr -= reduced;2384}23852386static intline_by_line_fuzzy_match(struct image *img,2387struct image *preimage,2388struct image *postimage,2389unsigned long current,2390int current_lno,2391int preimage_limit)2392{2393int i;2394size_t imgoff =0;2395size_t preoff =0;2396size_t postlen = postimage->len;2397size_t extra_chars;2398char*buf;2399char*preimage_eof;2400char*preimage_end;2401struct strbuf fixed;2402char*fixed_buf;2403size_t fixed_len;24042405for(i =0; i < preimage_limit; i++) {2406size_t prelen = preimage->line[i].len;2407size_t imglen = img->line[current_lno+i].len;24082409if(!fuzzy_matchlines(img->buf + current + imgoff, imglen,2410 preimage->buf + preoff, prelen))2411return0;2412if(preimage->line[i].flag & LINE_COMMON)2413 postlen += imglen - prelen;2414 imgoff += imglen;2415 preoff += prelen;2416}24172418/*2419 * Ok, the preimage matches with whitespace fuzz.2420 *2421 * imgoff now holds the true length of the target that2422 * matches the preimage before the end of the file.2423 *2424 * Count the number of characters in the preimage that fall2425 * beyond the end of the file and make sure that all of them2426 * are whitespace characters. (This can only happen if2427 * we are removing blank lines at the end of the file.)2428 */2429 buf = preimage_eof = preimage->buf + preoff;2430for( ; i < preimage->nr; i++)2431 preoff += preimage->line[i].len;2432 preimage_end = preimage->buf + preoff;2433for( ; buf < preimage_end; buf++)2434if(!isspace(*buf))2435return0;24362437/*2438 * Update the preimage and the common postimage context2439 * lines to use the same whitespace as the target.2440 * If whitespace is missing in the target (i.e.2441 * if the preimage extends beyond the end of the file),2442 * use the whitespace from the preimage.2443 */2444 extra_chars = preimage_end - preimage_eof;2445strbuf_init(&fixed, imgoff + extra_chars);2446strbuf_add(&fixed, img->buf + current, imgoff);2447strbuf_add(&fixed, preimage_eof, extra_chars);2448 fixed_buf =strbuf_detach(&fixed, &fixed_len);2449update_pre_post_images(preimage, postimage,2450 fixed_buf, fixed_len, postlen);2451return1;2452}24532454static intmatch_fragment(struct apply_state *state,2455struct image *img,2456struct image *preimage,2457struct image *postimage,2458unsigned long current,2459int current_lno,2460unsigned ws_rule,2461int match_beginning,int match_end)2462{2463int i;2464char*fixed_buf, *buf, *orig, *target;2465struct strbuf fixed;2466size_t fixed_len, postlen;2467int preimage_limit;24682469if(preimage->nr + current_lno <= img->nr) {2470/*2471 * The hunk falls within the boundaries of img.2472 */2473 preimage_limit = preimage->nr;2474if(match_end && (preimage->nr + current_lno != img->nr))2475return0;2476}else if(state->ws_error_action == correct_ws_error &&2477(ws_rule & WS_BLANK_AT_EOF)) {2478/*2479 * This hunk extends beyond the end of img, and we are2480 * removing blank lines at the end of the file. This2481 * many lines from the beginning of the preimage must2482 * match with img, and the remainder of the preimage2483 * must be blank.2484 */2485 preimage_limit = img->nr - current_lno;2486}else{2487/*2488 * The hunk extends beyond the end of the img and2489 * we are not removing blanks at the end, so we2490 * should reject the hunk at this position.2491 */2492return0;2493}24942495if(match_beginning && current_lno)2496return0;24972498/* Quick hash check */2499for(i =0; i < preimage_limit; i++)2500if((img->line[current_lno + i].flag & LINE_PATCHED) ||2501(preimage->line[i].hash != img->line[current_lno + i].hash))2502return0;25032504if(preimage_limit == preimage->nr) {2505/*2506 * Do we have an exact match? If we were told to match2507 * at the end, size must be exactly at current+fragsize,2508 * otherwise current+fragsize must be still within the preimage,2509 * and either case, the old piece should match the preimage2510 * exactly.2511 */2512if((match_end2513? (current + preimage->len == img->len)2514: (current + preimage->len <= img->len)) &&2515!memcmp(img->buf + current, preimage->buf, preimage->len))2516return1;2517}else{2518/*2519 * The preimage extends beyond the end of img, so2520 * there cannot be an exact match.2521 *2522 * There must be one non-blank context line that match2523 * a line before the end of img.2524 */2525char*buf_end;25262527 buf = preimage->buf;2528 buf_end = buf;2529for(i =0; i < preimage_limit; i++)2530 buf_end += preimage->line[i].len;25312532for( ; buf < buf_end; buf++)2533if(!isspace(*buf))2534break;2535if(buf == buf_end)2536return0;2537}25382539/*2540 * No exact match. If we are ignoring whitespace, run a line-by-line2541 * fuzzy matching. We collect all the line length information because2542 * we need it to adjust whitespace if we match.2543 */2544if(state->ws_ignore_action == ignore_ws_change)2545returnline_by_line_fuzzy_match(img, preimage, postimage,2546 current, current_lno, preimage_limit);25472548if(state->ws_error_action != correct_ws_error)2549return0;25502551/*2552 * The hunk does not apply byte-by-byte, but the hash says2553 * it might with whitespace fuzz. We weren't asked to2554 * ignore whitespace, we were asked to correct whitespace2555 * errors, so let's try matching after whitespace correction.2556 *2557 * While checking the preimage against the target, whitespace2558 * errors in both fixed, we count how large the corresponding2559 * postimage needs to be. The postimage prepared by2560 * apply_one_fragment() has whitespace errors fixed on added2561 * lines already, but the common lines were propagated as-is,2562 * which may become longer when their whitespace errors are2563 * fixed.2564 */25652566/* First count added lines in postimage */2567 postlen =0;2568for(i =0; i < postimage->nr; i++) {2569if(!(postimage->line[i].flag & LINE_COMMON))2570 postlen += postimage->line[i].len;2571}25722573/*2574 * The preimage may extend beyond the end of the file,2575 * but in this loop we will only handle the part of the2576 * preimage that falls within the file.2577 */2578strbuf_init(&fixed, preimage->len +1);2579 orig = preimage->buf;2580 target = img->buf + current;2581for(i =0; i < preimage_limit; i++) {2582size_t oldlen = preimage->line[i].len;2583size_t tgtlen = img->line[current_lno + i].len;2584size_t fixstart = fixed.len;2585struct strbuf tgtfix;2586int match;25872588/* Try fixing the line in the preimage */2589ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);25902591/* Try fixing the line in the target */2592strbuf_init(&tgtfix, tgtlen);2593ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);25942595/*2596 * If they match, either the preimage was based on2597 * a version before our tree fixed whitespace breakage,2598 * or we are lacking a whitespace-fix patch the tree2599 * the preimage was based on already had (i.e. target2600 * has whitespace breakage, the preimage doesn't).2601 * In either case, we are fixing the whitespace breakages2602 * so we might as well take the fix together with their2603 * real change.2604 */2605 match = (tgtfix.len == fixed.len - fixstart &&2606!memcmp(tgtfix.buf, fixed.buf + fixstart,2607 fixed.len - fixstart));26082609/* Add the length if this is common with the postimage */2610if(preimage->line[i].flag & LINE_COMMON)2611 postlen += tgtfix.len;26122613strbuf_release(&tgtfix);2614if(!match)2615goto unmatch_exit;26162617 orig += oldlen;2618 target += tgtlen;2619}262026212622/*2623 * Now handle the lines in the preimage that falls beyond the2624 * end of the file (if any). They will only match if they are2625 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2626 * false).2627 */2628for( ; i < preimage->nr; i++) {2629size_t fixstart = fixed.len;/* start of the fixed preimage */2630size_t oldlen = preimage->line[i].len;2631int j;26322633/* Try fixing the line in the preimage */2634ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);26352636for(j = fixstart; j < fixed.len; j++)2637if(!isspace(fixed.buf[j]))2638goto unmatch_exit;26392640 orig += oldlen;2641}26422643/*2644 * Yes, the preimage is based on an older version that still2645 * has whitespace breakages unfixed, and fixing them makes the2646 * hunk match. Update the context lines in the postimage.2647 */2648 fixed_buf =strbuf_detach(&fixed, &fixed_len);2649if(postlen < postimage->len)2650 postlen =0;2651update_pre_post_images(preimage, postimage,2652 fixed_buf, fixed_len, postlen);2653return1;26542655 unmatch_exit:2656strbuf_release(&fixed);2657return0;2658}26592660static intfind_pos(struct apply_state *state,2661struct image *img,2662struct image *preimage,2663struct image *postimage,2664int line,2665unsigned ws_rule,2666int match_beginning,int match_end)2667{2668int i;2669unsigned long backwards, forwards, current;2670int backwards_lno, forwards_lno, current_lno;26712672/*2673 * If match_beginning or match_end is specified, there is no2674 * point starting from a wrong line that will never match and2675 * wander around and wait for a match at the specified end.2676 */2677if(match_beginning)2678 line =0;2679else if(match_end)2680 line = img->nr - preimage->nr;26812682/*2683 * Because the comparison is unsigned, the following test2684 * will also take care of a negative line number that can2685 * result when match_end and preimage is larger than the target.2686 */2687if((size_t) line > img->nr)2688 line = img->nr;26892690 current =0;2691for(i =0; i < line; i++)2692 current += img->line[i].len;26932694/*2695 * There's probably some smart way to do this, but I'll leave2696 * that to the smart and beautiful people. I'm simple and stupid.2697 */2698 backwards = current;2699 backwards_lno = line;2700 forwards = current;2701 forwards_lno = line;2702 current_lno = line;27032704for(i =0; ; i++) {2705if(match_fragment(state, img, preimage, postimage,2706 current, current_lno, ws_rule,2707 match_beginning, match_end))2708return current_lno;27092710 again:2711if(backwards_lno ==0&& forwards_lno == img->nr)2712break;27132714if(i &1) {2715if(backwards_lno ==0) {2716 i++;2717goto again;2718}2719 backwards_lno--;2720 backwards -= img->line[backwards_lno].len;2721 current = backwards;2722 current_lno = backwards_lno;2723}else{2724if(forwards_lno == img->nr) {2725 i++;2726goto again;2727}2728 forwards += img->line[forwards_lno].len;2729 forwards_lno++;2730 current = forwards;2731 current_lno = forwards_lno;2732}27332734}2735return-1;2736}27372738static voidremove_first_line(struct image *img)2739{2740 img->buf += img->line[0].len;2741 img->len -= img->line[0].len;2742 img->line++;2743 img->nr--;2744}27452746static voidremove_last_line(struct image *img)2747{2748 img->len -= img->line[--img->nr].len;2749}27502751/*2752 * The change from "preimage" and "postimage" has been found to2753 * apply at applied_pos (counts in line numbers) in "img".2754 * Update "img" to remove "preimage" and replace it with "postimage".2755 */2756static voidupdate_image(struct apply_state *state,2757struct image *img,2758int applied_pos,2759struct image *preimage,2760struct image *postimage)2761{2762/*2763 * remove the copy of preimage at offset in img2764 * and replace it with postimage2765 */2766int i, nr;2767size_t remove_count, insert_count, applied_at =0;2768char*result;2769int preimage_limit;27702771/*2772 * If we are removing blank lines at the end of img,2773 * the preimage may extend beyond the end.2774 * If that is the case, we must be careful only to2775 * remove the part of the preimage that falls within2776 * the boundaries of img. Initialize preimage_limit2777 * to the number of lines in the preimage that falls2778 * within the boundaries.2779 */2780 preimage_limit = preimage->nr;2781if(preimage_limit > img->nr - applied_pos)2782 preimage_limit = img->nr - applied_pos;27832784for(i =0; i < applied_pos; i++)2785 applied_at += img->line[i].len;27862787 remove_count =0;2788for(i =0; i < preimage_limit; i++)2789 remove_count += img->line[applied_pos + i].len;2790 insert_count = postimage->len;27912792/* Adjust the contents */2793 result =xmalloc(st_add3(st_sub(img->len, remove_count), insert_count,1));2794memcpy(result, img->buf, applied_at);2795memcpy(result + applied_at, postimage->buf, postimage->len);2796memcpy(result + applied_at + postimage->len,2797 img->buf + (applied_at + remove_count),2798 img->len - (applied_at + remove_count));2799free(img->buf);2800 img->buf = result;2801 img->len += insert_count - remove_count;2802 result[img->len] ='\0';28032804/* Adjust the line table */2805 nr = img->nr + postimage->nr - preimage_limit;2806if(preimage_limit < postimage->nr) {2807/*2808 * NOTE: this knows that we never call remove_first_line()2809 * on anything other than pre/post image.2810 */2811REALLOC_ARRAY(img->line, nr);2812 img->line_allocated = img->line;2813}2814if(preimage_limit != postimage->nr)2815MOVE_ARRAY(img->line + applied_pos + postimage->nr,2816 img->line + applied_pos + preimage_limit,2817 img->nr - (applied_pos + preimage_limit));2818COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);2819if(!state->allow_overlap)2820for(i =0; i < postimage->nr; i++)2821 img->line[applied_pos + i].flag |= LINE_PATCHED;2822 img->nr = nr;2823}28242825/*2826 * Use the patch-hunk text in "frag" to prepare two images (preimage and2827 * postimage) for the hunk. Find lines that match "preimage" in "img" and2828 * replace the part of "img" with "postimage" text.2829 */2830static intapply_one_fragment(struct apply_state *state,2831struct image *img,struct fragment *frag,2832int inaccurate_eof,unsigned ws_rule,2833int nth_fragment)2834{2835int match_beginning, match_end;2836const char*patch = frag->patch;2837int size = frag->size;2838char*old, *oldlines;2839struct strbuf newlines;2840int new_blank_lines_at_end =0;2841int found_new_blank_lines_at_end =0;2842int hunk_linenr = frag->linenr;2843unsigned long leading, trailing;2844int pos, applied_pos;2845struct image preimage;2846struct image postimage;28472848memset(&preimage,0,sizeof(preimage));2849memset(&postimage,0,sizeof(postimage));2850 oldlines =xmalloc(size);2851strbuf_init(&newlines, size);28522853 old = oldlines;2854while(size >0) {2855char first;2856int len =linelen(patch, size);2857int plen;2858int added_blank_line =0;2859int is_blank_context =0;2860size_t start;28612862if(!len)2863break;28642865/*2866 * "plen" is how much of the line we should use for2867 * the actual patch data. Normally we just remove the2868 * first character on the line, but if the line is2869 * followed by "\ No newline", then we also remove the2870 * last one (which is the newline, of course).2871 */2872 plen = len -1;2873if(len < size && patch[len] =='\\')2874 plen--;2875 first = *patch;2876if(state->apply_in_reverse) {2877if(first =='-')2878 first ='+';2879else if(first =='+')2880 first ='-';2881}28822883switch(first) {2884case'\n':2885/* Newer GNU diff, empty context line */2886if(plen <0)2887/* ... followed by '\No newline'; nothing */2888break;2889*old++ ='\n';2890strbuf_addch(&newlines,'\n');2891add_line_info(&preimage,"\n",1, LINE_COMMON);2892add_line_info(&postimage,"\n",1, LINE_COMMON);2893 is_blank_context =1;2894break;2895case' ':2896if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2897ws_blank_line(patch +1, plen, ws_rule))2898 is_blank_context =1;2899/* fallthrough */2900case'-':2901memcpy(old, patch +1, plen);2902add_line_info(&preimage, old, plen,2903(first ==' '? LINE_COMMON :0));2904 old += plen;2905if(first =='-')2906break;2907/* fallthrough */2908case'+':2909/* --no-add does not add new lines */2910if(first =='+'&& state->no_add)2911break;29122913 start = newlines.len;2914if(first !='+'||2915!state->whitespace_error ||2916 state->ws_error_action != correct_ws_error) {2917strbuf_add(&newlines, patch +1, plen);2918}2919else{2920ws_fix_copy(&newlines, patch +1, plen, ws_rule, &state->applied_after_fixing_ws);2921}2922add_line_info(&postimage, newlines.buf + start, newlines.len - start,2923(first =='+'?0: LINE_COMMON));2924if(first =='+'&&2925(ws_rule & WS_BLANK_AT_EOF) &&2926ws_blank_line(patch +1, plen, ws_rule))2927 added_blank_line =1;2928break;2929case'@':case'\\':2930/* Ignore it, we already handled it */2931break;2932default:2933if(state->apply_verbosity > verbosity_normal)2934error(_("invalid start of line: '%c'"), first);2935 applied_pos = -1;2936goto out;2937}2938if(added_blank_line) {2939if(!new_blank_lines_at_end)2940 found_new_blank_lines_at_end = hunk_linenr;2941 new_blank_lines_at_end++;2942}2943else if(is_blank_context)2944;2945else2946 new_blank_lines_at_end =0;2947 patch += len;2948 size -= len;2949 hunk_linenr++;2950}2951if(inaccurate_eof &&2952 old > oldlines && old[-1] =='\n'&&2953 newlines.len >0&& newlines.buf[newlines.len -1] =='\n') {2954 old--;2955strbuf_setlen(&newlines, newlines.len -1);2956 preimage.line_allocated[preimage.nr -1].len--;2957 postimage.line_allocated[postimage.nr -1].len--;2958}29592960 leading = frag->leading;2961 trailing = frag->trailing;29622963/*2964 * A hunk to change lines at the beginning would begin with2965 * @@ -1,L +N,M @@2966 * but we need to be careful. -U0 that inserts before the second2967 * line also has this pattern.2968 *2969 * And a hunk to add to an empty file would begin with2970 * @@ -0,0 +N,M @@2971 *2972 * In other words, a hunk that is (frag->oldpos <= 1) with or2973 * without leading context must match at the beginning.2974 */2975 match_beginning = (!frag->oldpos ||2976(frag->oldpos ==1&& !state->unidiff_zero));29772978/*2979 * A hunk without trailing lines must match at the end.2980 * However, we simply cannot tell if a hunk must match end2981 * from the lack of trailing lines if the patch was generated2982 * with unidiff without any context.2983 */2984 match_end = !state->unidiff_zero && !trailing;29852986 pos = frag->newpos ? (frag->newpos -1) :0;2987 preimage.buf = oldlines;2988 preimage.len = old - oldlines;2989 postimage.buf = newlines.buf;2990 postimage.len = newlines.len;2991 preimage.line = preimage.line_allocated;2992 postimage.line = postimage.line_allocated;29932994for(;;) {29952996 applied_pos =find_pos(state, img, &preimage, &postimage, pos,2997 ws_rule, match_beginning, match_end);29982999if(applied_pos >=0)3000break;30013002/* Am I at my context limits? */3003if((leading <= state->p_context) && (trailing <= state->p_context))3004break;3005if(match_beginning || match_end) {3006 match_beginning = match_end =0;3007continue;3008}30093010/*3011 * Reduce the number of context lines; reduce both3012 * leading and trailing if they are equal otherwise3013 * just reduce the larger context.3014 */3015if(leading >= trailing) {3016remove_first_line(&preimage);3017remove_first_line(&postimage);3018 pos--;3019 leading--;3020}3021if(trailing > leading) {3022remove_last_line(&preimage);3023remove_last_line(&postimage);3024 trailing--;3025}3026}30273028if(applied_pos >=0) {3029if(new_blank_lines_at_end &&3030 preimage.nr + applied_pos >= img->nr &&3031(ws_rule & WS_BLANK_AT_EOF) &&3032 state->ws_error_action != nowarn_ws_error) {3033record_ws_error(state, WS_BLANK_AT_EOF,"+",1,3034 found_new_blank_lines_at_end);3035if(state->ws_error_action == correct_ws_error) {3036while(new_blank_lines_at_end--)3037remove_last_line(&postimage);3038}3039/*3040 * We would want to prevent write_out_results()3041 * from taking place in apply_patch() that follows3042 * the callchain led us here, which is:3043 * apply_patch->check_patch_list->check_patch->3044 * apply_data->apply_fragments->apply_one_fragment3045 */3046if(state->ws_error_action == die_on_ws_error)3047 state->apply =0;3048}30493050if(state->apply_verbosity > verbosity_normal && applied_pos != pos) {3051int offset = applied_pos - pos;3052if(state->apply_in_reverse)3053 offset =0- offset;3054fprintf_ln(stderr,3055Q_("Hunk #%dsucceeded at%d(offset%dline).",3056"Hunk #%dsucceeded at%d(offset%dlines).",3057 offset),3058 nth_fragment, applied_pos +1, offset);3059}30603061/*3062 * Warn if it was necessary to reduce the number3063 * of context lines.3064 */3065if((leading != frag->leading ||3066 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)3067fprintf_ln(stderr,_("Context reduced to (%ld/%ld)"3068" to apply fragment at%d"),3069 leading, trailing, applied_pos+1);3070update_image(state, img, applied_pos, &preimage, &postimage);3071}else{3072if(state->apply_verbosity > verbosity_normal)3073error(_("while searching for:\n%.*s"),3074(int)(old - oldlines), oldlines);3075}30763077out:3078free(oldlines);3079strbuf_release(&newlines);3080free(preimage.line_allocated);3081free(postimage.line_allocated);30823083return(applied_pos <0);3084}30853086static intapply_binary_fragment(struct apply_state *state,3087struct image *img,3088struct patch *patch)3089{3090struct fragment *fragment = patch->fragments;3091unsigned long len;3092void*dst;30933094if(!fragment)3095returnerror(_("missing binary patch data for '%s'"),3096 patch->new_name ?3097 patch->new_name :3098 patch->old_name);30993100/* Binary patch is irreversible without the optional second hunk */3101if(state->apply_in_reverse) {3102if(!fragment->next)3103returnerror(_("cannot reverse-apply a binary patch "3104"without the reverse hunk to '%s'"),3105 patch->new_name3106? patch->new_name : patch->old_name);3107 fragment = fragment->next;3108}3109switch(fragment->binary_patch_method) {3110case BINARY_DELTA_DEFLATED:3111 dst =patch_delta(img->buf, img->len, fragment->patch,3112 fragment->size, &len);3113if(!dst)3114return-1;3115clear_image(img);3116 img->buf = dst;3117 img->len = len;3118return0;3119case BINARY_LITERAL_DEFLATED:3120clear_image(img);3121 img->len = fragment->size;3122 img->buf =xmemdupz(fragment->patch, img->len);3123return0;3124}3125return-1;3126}31273128/*3129 * Replace "img" with the result of applying the binary patch.3130 * The binary patch data itself in patch->fragment is still kept3131 * but the preimage prepared by the caller in "img" is freed here3132 * or in the helper function apply_binary_fragment() this calls.3133 */3134static intapply_binary(struct apply_state *state,3135struct image *img,3136struct patch *patch)3137{3138const char*name = patch->old_name ? patch->old_name : patch->new_name;3139struct object_id oid;31403141/*3142 * For safety, we require patch index line to contain3143 * full 40-byte textual SHA1 for old and new, at least for now.3144 */3145if(strlen(patch->old_sha1_prefix) !=40||3146strlen(patch->new_sha1_prefix) !=40||3147get_oid_hex(patch->old_sha1_prefix, &oid) ||3148get_oid_hex(patch->new_sha1_prefix, &oid))3149returnerror(_("cannot apply binary patch to '%s' "3150"without full index line"), name);31513152if(patch->old_name) {3153/*3154 * See if the old one matches what the patch3155 * applies to.3156 */3157hash_object_file(img->buf, img->len, blob_type, &oid);3158if(strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))3159returnerror(_("the patch applies to '%s' (%s), "3160"which does not match the "3161"current contents."),3162 name,oid_to_hex(&oid));3163}3164else{3165/* Otherwise, the old one must be empty. */3166if(img->len)3167returnerror(_("the patch applies to an empty "3168"'%s' but it is not empty"), name);3169}31703171get_oid_hex(patch->new_sha1_prefix, &oid);3172if(is_null_oid(&oid)) {3173clear_image(img);3174return0;/* deletion patch */3175}31763177if(has_sha1_file(oid.hash)) {3178/* We already have the postimage */3179enum object_type type;3180unsigned long size;3181char*result;31823183 result =read_sha1_file(oid.hash, &type, &size);3184if(!result)3185returnerror(_("the necessary postimage%sfor "3186"'%s' cannot be read"),3187 patch->new_sha1_prefix, name);3188clear_image(img);3189 img->buf = result;3190 img->len = size;3191}else{3192/*3193 * We have verified buf matches the preimage;3194 * apply the patch data to it, which is stored3195 * in the patch->fragments->{patch,size}.3196 */3197if(apply_binary_fragment(state, img, patch))3198returnerror(_("binary patch does not apply to '%s'"),3199 name);32003201/* verify that the result matches */3202hash_object_file(img->buf, img->len, blob_type, &oid);3203if(strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))3204returnerror(_("binary patch to '%s' creates incorrect result (expecting%s, got%s)"),3205 name, patch->new_sha1_prefix,oid_to_hex(&oid));3206}32073208return0;3209}32103211static intapply_fragments(struct apply_state *state,struct image *img,struct patch *patch)3212{3213struct fragment *frag = patch->fragments;3214const char*name = patch->old_name ? patch->old_name : patch->new_name;3215unsigned ws_rule = patch->ws_rule;3216unsigned inaccurate_eof = patch->inaccurate_eof;3217int nth =0;32183219if(patch->is_binary)3220returnapply_binary(state, img, patch);32213222while(frag) {3223 nth++;3224if(apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {3225error(_("patch failed:%s:%ld"), name, frag->oldpos);3226if(!state->apply_with_reject)3227return-1;3228 frag->rejected =1;3229}3230 frag = frag->next;3231}3232return0;3233}32343235static intread_blob_object(struct strbuf *buf,const struct object_id *oid,unsigned mode)3236{3237if(S_ISGITLINK(mode)) {3238strbuf_grow(buf,100);3239strbuf_addf(buf,"Subproject commit%s\n",oid_to_hex(oid));3240}else{3241enum object_type type;3242unsigned long sz;3243char*result;32443245 result =read_sha1_file(oid->hash, &type, &sz);3246if(!result)3247return-1;3248/* XXX read_sha1_file NUL-terminates */3249strbuf_attach(buf, result, sz, sz +1);3250}3251return0;3252}32533254static intread_file_or_gitlink(const struct cache_entry *ce,struct strbuf *buf)3255{3256if(!ce)3257return0;3258returnread_blob_object(buf, &ce->oid, ce->ce_mode);3259}32603261static struct patch *in_fn_table(struct apply_state *state,const char*name)3262{3263struct string_list_item *item;32643265if(name == NULL)3266return NULL;32673268 item =string_list_lookup(&state->fn_table, name);3269if(item != NULL)3270return(struct patch *)item->util;32713272return NULL;3273}32743275/*3276 * item->util in the filename table records the status of the path.3277 * Usually it points at a patch (whose result records the contents3278 * of it after applying it), but it could be PATH_WAS_DELETED for a3279 * path that a previously applied patch has already removed, or3280 * PATH_TO_BE_DELETED for a path that a later patch would remove.3281 *3282 * The latter is needed to deal with a case where two paths A and B3283 * are swapped by first renaming A to B and then renaming B to A;3284 * moving A to B should not be prevented due to presence of B as we3285 * will remove it in a later patch.3286 */3287#define PATH_TO_BE_DELETED ((struct patch *) -2)3288#define PATH_WAS_DELETED ((struct patch *) -1)32893290static intto_be_deleted(struct patch *patch)3291{3292return patch == PATH_TO_BE_DELETED;3293}32943295static intwas_deleted(struct patch *patch)3296{3297return patch == PATH_WAS_DELETED;3298}32993300static voidadd_to_fn_table(struct apply_state *state,struct patch *patch)3301{3302struct string_list_item *item;33033304/*3305 * Always add new_name unless patch is a deletion3306 * This should cover the cases for normal diffs,3307 * file creations and copies3308 */3309if(patch->new_name != NULL) {3310 item =string_list_insert(&state->fn_table, patch->new_name);3311 item->util = patch;3312}33133314/*3315 * store a failure on rename/deletion cases because3316 * later chunks shouldn't patch old names3317 */3318if((patch->new_name == NULL) || (patch->is_rename)) {3319 item =string_list_insert(&state->fn_table, patch->old_name);3320 item->util = PATH_WAS_DELETED;3321}3322}33233324static voidprepare_fn_table(struct apply_state *state,struct patch *patch)3325{3326/*3327 * store information about incoming file deletion3328 */3329while(patch) {3330if((patch->new_name == NULL) || (patch->is_rename)) {3331struct string_list_item *item;3332 item =string_list_insert(&state->fn_table, patch->old_name);3333 item->util = PATH_TO_BE_DELETED;3334}3335 patch = patch->next;3336}3337}33383339static intcheckout_target(struct index_state *istate,3340struct cache_entry *ce,struct stat *st)3341{3342struct checkout costate = CHECKOUT_INIT;33433344 costate.refresh_cache =1;3345 costate.istate = istate;3346if(checkout_entry(ce, &costate, NULL) ||lstat(ce->name, st))3347returnerror(_("cannot checkout%s"), ce->name);3348return0;3349}33503351static struct patch *previous_patch(struct apply_state *state,3352struct patch *patch,3353int*gone)3354{3355struct patch *previous;33563357*gone =0;3358if(patch->is_copy || patch->is_rename)3359return NULL;/* "git" patches do not depend on the order */33603361 previous =in_fn_table(state, patch->old_name);3362if(!previous)3363return NULL;33643365if(to_be_deleted(previous))3366return NULL;/* the deletion hasn't happened yet */33673368if(was_deleted(previous))3369*gone =1;33703371return previous;3372}33733374static intverify_index_match(const struct cache_entry *ce,struct stat *st)3375{3376if(S_ISGITLINK(ce->ce_mode)) {3377if(!S_ISDIR(st->st_mode))3378return-1;3379return0;3380}3381returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3382}33833384#define SUBMODULE_PATCH_WITHOUT_INDEX 133853386static intload_patch_target(struct apply_state *state,3387struct strbuf *buf,3388const struct cache_entry *ce,3389struct stat *st,3390struct patch *patch,3391const char*name,3392unsigned expected_mode)3393{3394if(state->cached || state->check_index) {3395if(read_file_or_gitlink(ce, buf))3396returnerror(_("failed to read%s"), name);3397}else if(name) {3398if(S_ISGITLINK(expected_mode)) {3399if(ce)3400returnread_file_or_gitlink(ce, buf);3401else3402return SUBMODULE_PATCH_WITHOUT_INDEX;3403}else if(has_symlink_leading_path(name,strlen(name))) {3404returnerror(_("reading from '%s' beyond a symbolic link"), name);3405}else{3406if(read_old_data(st, patch, name, buf))3407returnerror(_("failed to read%s"), name);3408}3409}3410return0;3411}34123413/*3414 * We are about to apply "patch"; populate the "image" with the3415 * current version we have, from the working tree or from the index,3416 * depending on the situation e.g. --cached/--index. If we are3417 * applying a non-git patch that incrementally updates the tree,3418 * we read from the result of a previous diff.3419 */3420static intload_preimage(struct apply_state *state,3421struct image *image,3422struct patch *patch,struct stat *st,3423const struct cache_entry *ce)3424{3425struct strbuf buf = STRBUF_INIT;3426size_t len;3427char*img;3428struct patch *previous;3429int status;34303431 previous =previous_patch(state, patch, &status);3432if(status)3433returnerror(_("path%shas been renamed/deleted"),3434 patch->old_name);3435if(previous) {3436/* We have a patched copy in memory; use that. */3437strbuf_add(&buf, previous->result, previous->resultsize);3438}else{3439 status =load_patch_target(state, &buf, ce, st, patch,3440 patch->old_name, patch->old_mode);3441if(status <0)3442return status;3443else if(status == SUBMODULE_PATCH_WITHOUT_INDEX) {3444/*3445 * There is no way to apply subproject3446 * patch without looking at the index.3447 * NEEDSWORK: shouldn't this be flagged3448 * as an error???3449 */3450free_fragment_list(patch->fragments);3451 patch->fragments = NULL;3452}else if(status) {3453returnerror(_("failed to read%s"), patch->old_name);3454}3455}34563457 img =strbuf_detach(&buf, &len);3458prepare_image(image, img, len, !patch->is_binary);3459return0;3460}34613462static intthree_way_merge(struct image *image,3463char*path,3464const struct object_id *base,3465const struct object_id *ours,3466const struct object_id *theirs)3467{3468 mmfile_t base_file, our_file, their_file;3469 mmbuffer_t result = { NULL };3470int status;34713472read_mmblob(&base_file, base);3473read_mmblob(&our_file, ours);3474read_mmblob(&their_file, theirs);3475 status =ll_merge(&result, path,3476&base_file,"base",3477&our_file,"ours",3478&their_file,"theirs", NULL);3479free(base_file.ptr);3480free(our_file.ptr);3481free(their_file.ptr);3482if(status <0|| !result.ptr) {3483free(result.ptr);3484return-1;3485}3486clear_image(image);3487 image->buf = result.ptr;3488 image->len = result.size;34893490return status;3491}34923493/*3494 * When directly falling back to add/add three-way merge, we read from3495 * the current contents of the new_name. In no cases other than that3496 * this function will be called.3497 */3498static intload_current(struct apply_state *state,3499struct image *image,3500struct patch *patch)3501{3502struct strbuf buf = STRBUF_INIT;3503int status, pos;3504size_t len;3505char*img;3506struct stat st;3507struct cache_entry *ce;3508char*name = patch->new_name;3509unsigned mode = patch->new_mode;35103511if(!patch->is_new)3512die("BUG: patch to%sis not a creation", patch->old_name);35133514 pos =cache_name_pos(name,strlen(name));3515if(pos <0)3516returnerror(_("%s: does not exist in index"), name);3517 ce = active_cache[pos];3518if(lstat(name, &st)) {3519if(errno != ENOENT)3520returnerror_errno("%s", name);3521if(checkout_target(&the_index, ce, &st))3522return-1;3523}3524if(verify_index_match(ce, &st))3525returnerror(_("%s: does not match index"), name);35263527 status =load_patch_target(state, &buf, ce, &st, patch, name, mode);3528if(status <0)3529return status;3530else if(status)3531return-1;3532 img =strbuf_detach(&buf, &len);3533prepare_image(image, img, len, !patch->is_binary);3534return0;3535}35363537static inttry_threeway(struct apply_state *state,3538struct image *image,3539struct patch *patch,3540struct stat *st,3541const struct cache_entry *ce)3542{3543struct object_id pre_oid, post_oid, our_oid;3544struct strbuf buf = STRBUF_INIT;3545size_t len;3546int status;3547char*img;3548struct image tmp_image;35493550/* No point falling back to 3-way merge in these cases */3551if(patch->is_delete ||3552S_ISGITLINK(patch->old_mode) ||S_ISGITLINK(patch->new_mode))3553return-1;35543555/* Preimage the patch was prepared for */3556if(patch->is_new)3557write_object_file("",0, blob_type, &pre_oid);3558else if(get_oid(patch->old_sha1_prefix, &pre_oid) ||3559read_blob_object(&buf, &pre_oid, patch->old_mode))3560returnerror(_("repository lacks the necessary blob to fall back on 3-way merge."));35613562if(state->apply_verbosity > verbosity_silent)3563fprintf(stderr,_("Falling back to three-way merge...\n"));35643565 img =strbuf_detach(&buf, &len);3566prepare_image(&tmp_image, img, len,1);3567/* Apply the patch to get the post image */3568if(apply_fragments(state, &tmp_image, patch) <0) {3569clear_image(&tmp_image);3570return-1;3571}3572/* post_oid is theirs */3573write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);3574clear_image(&tmp_image);35753576/* our_oid is ours */3577if(patch->is_new) {3578if(load_current(state, &tmp_image, patch))3579returnerror(_("cannot read the current contents of '%s'"),3580 patch->new_name);3581}else{3582if(load_preimage(state, &tmp_image, patch, st, ce))3583returnerror(_("cannot read the current contents of '%s'"),3584 patch->old_name);3585}3586write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);3587clear_image(&tmp_image);35883589/* in-core three-way merge between post and our using pre as base */3590 status =three_way_merge(image, patch->new_name,3591&pre_oid, &our_oid, &post_oid);3592if(status <0) {3593if(state->apply_verbosity > verbosity_silent)3594fprintf(stderr,3595_("Failed to fall back on three-way merge...\n"));3596return status;3597}35983599if(status) {3600 patch->conflicted_threeway =1;3601if(patch->is_new)3602oidclr(&patch->threeway_stage[0]);3603else3604oidcpy(&patch->threeway_stage[0], &pre_oid);3605oidcpy(&patch->threeway_stage[1], &our_oid);3606oidcpy(&patch->threeway_stage[2], &post_oid);3607if(state->apply_verbosity > verbosity_silent)3608fprintf(stderr,3609_("Applied patch to '%s' with conflicts.\n"),3610 patch->new_name);3611}else{3612if(state->apply_verbosity > verbosity_silent)3613fprintf(stderr,3614_("Applied patch to '%s' cleanly.\n"),3615 patch->new_name);3616}3617return0;3618}36193620static intapply_data(struct apply_state *state,struct patch *patch,3621struct stat *st,const struct cache_entry *ce)3622{3623struct image image;36243625if(load_preimage(state, &image, patch, st, ce) <0)3626return-1;36273628if(patch->direct_to_threeway ||3629apply_fragments(state, &image, patch) <0) {3630/* Note: with --reject, apply_fragments() returns 0 */3631if(!state->threeway ||try_threeway(state, &image, patch, st, ce) <0)3632return-1;3633}3634 patch->result = image.buf;3635 patch->resultsize = image.len;3636add_to_fn_table(state, patch);3637free(image.line_allocated);36383639if(0< patch->is_delete && patch->resultsize)3640returnerror(_("removal patch leaves file contents"));36413642return0;3643}36443645/*3646 * If "patch" that we are looking at modifies or deletes what we have,3647 * we would want it not to lose any local modification we have, either3648 * in the working tree or in the index.3649 *3650 * This also decides if a non-git patch is a creation patch or a3651 * modification to an existing empty file. We do not check the state3652 * of the current tree for a creation patch in this function; the caller3653 * check_patch() separately makes sure (and errors out otherwise) that3654 * the path the patch creates does not exist in the current tree.3655 */3656static intcheck_preimage(struct apply_state *state,3657struct patch *patch,3658struct cache_entry **ce,3659struct stat *st)3660{3661const char*old_name = patch->old_name;3662struct patch *previous = NULL;3663int stat_ret =0, status;3664unsigned st_mode =0;36653666if(!old_name)3667return0;36683669assert(patch->is_new <=0);3670 previous =previous_patch(state, patch, &status);36713672if(status)3673returnerror(_("path%shas been renamed/deleted"), old_name);3674if(previous) {3675 st_mode = previous->new_mode;3676}else if(!state->cached) {3677 stat_ret =lstat(old_name, st);3678if(stat_ret && errno != ENOENT)3679returnerror_errno("%s", old_name);3680}36813682if(state->check_index && !previous) {3683int pos =cache_name_pos(old_name,strlen(old_name));3684if(pos <0) {3685if(patch->is_new <0)3686goto is_new;3687returnerror(_("%s: does not exist in index"), old_name);3688}3689*ce = active_cache[pos];3690if(stat_ret <0) {3691if(checkout_target(&the_index, *ce, st))3692return-1;3693}3694if(!state->cached &&verify_index_match(*ce, st))3695returnerror(_("%s: does not match index"), old_name);3696if(state->cached)3697 st_mode = (*ce)->ce_mode;3698}else if(stat_ret <0) {3699if(patch->is_new <0)3700goto is_new;3701returnerror_errno("%s", old_name);3702}37033704if(!state->cached && !previous)3705 st_mode =ce_mode_from_stat(*ce, st->st_mode);37063707if(patch->is_new <0)3708 patch->is_new =0;3709if(!patch->old_mode)3710 patch->old_mode = st_mode;3711if((st_mode ^ patch->old_mode) & S_IFMT)3712returnerror(_("%s: wrong type"), old_name);3713if(st_mode != patch->old_mode)3714warning(_("%shas type%o, expected%o"),3715 old_name, st_mode, patch->old_mode);3716if(!patch->new_mode && !patch->is_delete)3717 patch->new_mode = st_mode;3718return0;37193720 is_new:3721 patch->is_new =1;3722 patch->is_delete =0;3723FREE_AND_NULL(patch->old_name);3724return0;3725}372637273728#define EXISTS_IN_INDEX 13729#define EXISTS_IN_WORKTREE 237303731static intcheck_to_create(struct apply_state *state,3732const char*new_name,3733int ok_if_exists)3734{3735struct stat nst;37363737if(state->check_index &&3738cache_name_pos(new_name,strlen(new_name)) >=0&&3739!ok_if_exists)3740return EXISTS_IN_INDEX;3741if(state->cached)3742return0;37433744if(!lstat(new_name, &nst)) {3745if(S_ISDIR(nst.st_mode) || ok_if_exists)3746return0;3747/*3748 * A leading component of new_name might be a symlink3749 * that is going to be removed with this patch, but3750 * still pointing at somewhere that has the path.3751 * In such a case, path "new_name" does not exist as3752 * far as git is concerned.3753 */3754if(has_symlink_leading_path(new_name,strlen(new_name)))3755return0;37563757return EXISTS_IN_WORKTREE;3758}else if(!is_missing_file_error(errno)) {3759returnerror_errno("%s", new_name);3760}3761return0;3762}37633764static uintptr_tregister_symlink_changes(struct apply_state *state,3765const char*path,3766uintptr_t what)3767{3768struct string_list_item *ent;37693770 ent =string_list_lookup(&state->symlink_changes, path);3771if(!ent) {3772 ent =string_list_insert(&state->symlink_changes, path);3773 ent->util = (void*)0;3774}3775 ent->util = (void*)(what | ((uintptr_t)ent->util));3776return(uintptr_t)ent->util;3777}37783779static uintptr_tcheck_symlink_changes(struct apply_state *state,const char*path)3780{3781struct string_list_item *ent;37823783 ent =string_list_lookup(&state->symlink_changes, path);3784if(!ent)3785return0;3786return(uintptr_t)ent->util;3787}37883789static voidprepare_symlink_changes(struct apply_state *state,struct patch *patch)3790{3791for( ; patch; patch = patch->next) {3792if((patch->old_name &&S_ISLNK(patch->old_mode)) &&3793(patch->is_rename || patch->is_delete))3794/* the symlink at patch->old_name is removed */3795register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);37963797if(patch->new_name &&S_ISLNK(patch->new_mode))3798/* the symlink at patch->new_name is created or remains */3799register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);3800}3801}38023803static intpath_is_beyond_symlink_1(struct apply_state *state,struct strbuf *name)3804{3805do{3806unsigned int change;38073808while(--name->len && name->buf[name->len] !='/')3809;/* scan backwards */3810if(!name->len)3811break;3812 name->buf[name->len] ='\0';3813 change =check_symlink_changes(state, name->buf);3814if(change & APPLY_SYMLINK_IN_RESULT)3815return1;3816if(change & APPLY_SYMLINK_GOES_AWAY)3817/*3818 * This cannot be "return 0", because we may3819 * see a new one created at a higher level.3820 */3821continue;38223823/* otherwise, check the preimage */3824if(state->check_index) {3825struct cache_entry *ce;38263827 ce =cache_file_exists(name->buf, name->len, ignore_case);3828if(ce &&S_ISLNK(ce->ce_mode))3829return1;3830}else{3831struct stat st;3832if(!lstat(name->buf, &st) &&S_ISLNK(st.st_mode))3833return1;3834}3835}while(1);3836return0;3837}38383839static intpath_is_beyond_symlink(struct apply_state *state,const char*name_)3840{3841int ret;3842struct strbuf name = STRBUF_INIT;38433844assert(*name_ !='\0');3845strbuf_addstr(&name, name_);3846 ret =path_is_beyond_symlink_1(state, &name);3847strbuf_release(&name);38483849return ret;3850}38513852static intcheck_unsafe_path(struct patch *patch)3853{3854const char*old_name = NULL;3855const char*new_name = NULL;3856if(patch->is_delete)3857 old_name = patch->old_name;3858else if(!patch->is_new && !patch->is_copy)3859 old_name = patch->old_name;3860if(!patch->is_delete)3861 new_name = patch->new_name;38623863if(old_name && !verify_path(old_name))3864returnerror(_("invalid path '%s'"), old_name);3865if(new_name && !verify_path(new_name))3866returnerror(_("invalid path '%s'"), new_name);3867return0;3868}38693870/*3871 * Check and apply the patch in-core; leave the result in patch->result3872 * for the caller to write it out to the final destination.3873 */3874static intcheck_patch(struct apply_state *state,struct patch *patch)3875{3876struct stat st;3877const char*old_name = patch->old_name;3878const char*new_name = patch->new_name;3879const char*name = old_name ? old_name : new_name;3880struct cache_entry *ce = NULL;3881struct patch *tpatch;3882int ok_if_exists;3883int status;38843885 patch->rejected =1;/* we will drop this after we succeed */38863887 status =check_preimage(state, patch, &ce, &st);3888if(status)3889return status;3890 old_name = patch->old_name;38913892/*3893 * A type-change diff is always split into a patch to delete3894 * old, immediately followed by a patch to create new (see3895 * diff.c::run_diff()); in such a case it is Ok that the entry3896 * to be deleted by the previous patch is still in the working3897 * tree and in the index.3898 *3899 * A patch to swap-rename between A and B would first rename A3900 * to B and then rename B to A. While applying the first one,3901 * the presence of B should not stop A from getting renamed to3902 * B; ask to_be_deleted() about the later rename. Removal of3903 * B and rename from A to B is handled the same way by asking3904 * was_deleted().3905 */3906if((tpatch =in_fn_table(state, new_name)) &&3907(was_deleted(tpatch) ||to_be_deleted(tpatch)))3908 ok_if_exists =1;3909else3910 ok_if_exists =0;39113912if(new_name &&3913((0< patch->is_new) || patch->is_rename || patch->is_copy)) {3914int err =check_to_create(state, new_name, ok_if_exists);39153916if(err && state->threeway) {3917 patch->direct_to_threeway =1;3918}else switch(err) {3919case0:3920break;/* happy */3921case EXISTS_IN_INDEX:3922returnerror(_("%s: already exists in index"), new_name);3923break;3924case EXISTS_IN_WORKTREE:3925returnerror(_("%s: already exists in working directory"),3926 new_name);3927default:3928return err;3929}39303931if(!patch->new_mode) {3932if(0< patch->is_new)3933 patch->new_mode = S_IFREG |0644;3934else3935 patch->new_mode = patch->old_mode;3936}3937}39383939if(new_name && old_name) {3940int same = !strcmp(old_name, new_name);3941if(!patch->new_mode)3942 patch->new_mode = patch->old_mode;3943if((patch->old_mode ^ patch->new_mode) & S_IFMT) {3944if(same)3945returnerror(_("new mode (%o) of%sdoes not "3946"match old mode (%o)"),3947 patch->new_mode, new_name,3948 patch->old_mode);3949else3950returnerror(_("new mode (%o) of%sdoes not "3951"match old mode (%o) of%s"),3952 patch->new_mode, new_name,3953 patch->old_mode, old_name);3954}3955}39563957if(!state->unsafe_paths &&check_unsafe_path(patch))3958return-128;39593960/*3961 * An attempt to read from or delete a path that is beyond a3962 * symbolic link will be prevented by load_patch_target() that3963 * is called at the beginning of apply_data() so we do not3964 * have to worry about a patch marked with "is_delete" bit3965 * here. We however need to make sure that the patch result3966 * is not deposited to a path that is beyond a symbolic link3967 * here.3968 */3969if(!patch->is_delete &&path_is_beyond_symlink(state, patch->new_name))3970returnerror(_("affected file '%s' is beyond a symbolic link"),3971 patch->new_name);39723973if(apply_data(state, patch, &st, ce) <0)3974returnerror(_("%s: patch does not apply"), name);3975 patch->rejected =0;3976return0;3977}39783979static intcheck_patch_list(struct apply_state *state,struct patch *patch)3980{3981int err =0;39823983prepare_symlink_changes(state, patch);3984prepare_fn_table(state, patch);3985while(patch) {3986int res;3987if(state->apply_verbosity > verbosity_normal)3988say_patch_name(stderr,3989_("Checking patch%s..."), patch);3990 res =check_patch(state, patch);3991if(res == -128)3992return-128;3993 err |= res;3994 patch = patch->next;3995}3996return err;3997}39983999static intread_apply_cache(struct apply_state *state)4000{4001if(state->index_file)4002returnread_cache_from(state->index_file);4003else4004returnread_cache();4005}40064007/* This function tries to read the object name from the current index */4008static intget_current_oid(struct apply_state *state,const char*path,4009struct object_id *oid)4010{4011int pos;40124013if(read_apply_cache(state) <0)4014return-1;4015 pos =cache_name_pos(path,strlen(path));4016if(pos <0)4017return-1;4018oidcpy(oid, &active_cache[pos]->oid);4019return0;4020}40214022static intpreimage_oid_in_gitlink_patch(struct patch *p,struct object_id *oid)4023{4024/*4025 * A usable gitlink patch has only one fragment (hunk) that looks like:4026 * @@ -1 +1 @@4027 * -Subproject commit <old sha1>4028 * +Subproject commit <new sha1>4029 * or4030 * @@ -1 +0,0 @@4031 * -Subproject commit <old sha1>4032 * for a removal patch.4033 */4034struct fragment *hunk = p->fragments;4035static const char heading[] ="-Subproject commit ";4036char*preimage;40374038if(/* does the patch have only one hunk? */4039 hunk && !hunk->next &&4040/* is its preimage one line? */4041 hunk->oldpos ==1&& hunk->oldlines ==1&&4042/* does preimage begin with the heading? */4043(preimage =memchr(hunk->patch,'\n', hunk->size)) != NULL &&4044starts_with(++preimage, heading) &&4045/* does it record full SHA-1? */4046!get_oid_hex(preimage +sizeof(heading) -1, oid) &&4047 preimage[sizeof(heading) + GIT_SHA1_HEXSZ -1] =='\n'&&4048/* does the abbreviated name on the index line agree with it? */4049starts_with(preimage +sizeof(heading) -1, p->old_sha1_prefix))4050return0;/* it all looks fine */40514052/* we may have full object name on the index line */4053returnget_oid_hex(p->old_sha1_prefix, oid);4054}40554056/* Build an index that contains the just the files needed for a 3way merge */4057static intbuild_fake_ancestor(struct apply_state *state,struct patch *list)4058{4059struct patch *patch;4060struct index_state result = { NULL };4061static struct lock_file lock;4062int res;40634064/* Once we start supporting the reverse patch, it may be4065 * worth showing the new sha1 prefix, but until then...4066 */4067for(patch = list; patch; patch = patch->next) {4068struct object_id oid;4069struct cache_entry *ce;4070const char*name;40714072 name = patch->old_name ? patch->old_name : patch->new_name;4073if(0< patch->is_new)4074continue;40754076if(S_ISGITLINK(patch->old_mode)) {4077if(!preimage_oid_in_gitlink_patch(patch, &oid))4078;/* ok, the textual part looks sane */4079else4080returnerror(_("sha1 information is lacking or "4081"useless for submodule%s"), name);4082}else if(!get_oid_blob(patch->old_sha1_prefix, &oid)) {4083;/* ok */4084}else if(!patch->lines_added && !patch->lines_deleted) {4085/* mode-only change: update the current */4086if(get_current_oid(state, patch->old_name, &oid))4087returnerror(_("mode change for%s, which is not "4088"in current HEAD"), name);4089}else4090returnerror(_("sha1 information is lacking or useless "4091"(%s)."), name);40924093 ce =make_cache_entry(patch->old_mode, oid.hash, name,0,0);4094if(!ce)4095returnerror(_("make_cache_entry failed for path '%s'"),4096 name);4097if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {4098free(ce);4099returnerror(_("could not add%sto temporary index"),4100 name);4101}4102}41034104hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);4105 res =write_locked_index(&result, &lock, COMMIT_LOCK);4106discard_index(&result);41074108if(res)4109returnerror(_("could not write temporary index to%s"),4110 state->fake_ancestor);41114112return0;4113}41144115static voidstat_patch_list(struct apply_state *state,struct patch *patch)4116{4117int files, adds, dels;41184119for(files = adds = dels =0; patch ; patch = patch->next) {4120 files++;4121 adds += patch->lines_added;4122 dels += patch->lines_deleted;4123show_stats(state, patch);4124}41254126print_stat_summary(stdout, files, adds, dels);4127}41284129static voidnumstat_patch_list(struct apply_state *state,4130struct patch *patch)4131{4132for( ; patch; patch = patch->next) {4133const char*name;4134 name = patch->new_name ? patch->new_name : patch->old_name;4135if(patch->is_binary)4136printf("-\t-\t");4137else4138printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);4139write_name_quoted(name, stdout, state->line_termination);4140}4141}41424143static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)4144{4145if(mode)4146printf("%smode%06o%s\n", newdelete, mode, name);4147else4148printf("%s %s\n", newdelete, name);4149}41504151static voidshow_mode_change(struct patch *p,int show_name)4152{4153if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {4154if(show_name)4155printf(" mode change%06o =>%06o%s\n",4156 p->old_mode, p->new_mode, p->new_name);4157else4158printf(" mode change%06o =>%06o\n",4159 p->old_mode, p->new_mode);4160}4161}41624163static voidshow_rename_copy(struct patch *p)4164{4165const char*renamecopy = p->is_rename ?"rename":"copy";4166const char*old_name, *new_name;41674168/* Find common prefix */4169 old_name = p->old_name;4170 new_name = p->new_name;4171while(1) {4172const char*slash_old, *slash_new;4173 slash_old =strchr(old_name,'/');4174 slash_new =strchr(new_name,'/');4175if(!slash_old ||4176!slash_new ||4177 slash_old - old_name != slash_new - new_name ||4178memcmp(old_name, new_name, slash_new - new_name))4179break;4180 old_name = slash_old +1;4181 new_name = slash_new +1;4182}4183/* p->old_name thru old_name is the common prefix, and old_name and new_name4184 * through the end of names are renames4185 */4186if(old_name != p->old_name)4187printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,4188(int)(old_name - p->old_name), p->old_name,4189 old_name, new_name, p->score);4190else4191printf("%s %s=>%s(%d%%)\n", renamecopy,4192 p->old_name, p->new_name, p->score);4193show_mode_change(p,0);4194}41954196static voidsummary_patch_list(struct patch *patch)4197{4198struct patch *p;41994200for(p = patch; p; p = p->next) {4201if(p->is_new)4202show_file_mode_name("create", p->new_mode, p->new_name);4203else if(p->is_delete)4204show_file_mode_name("delete", p->old_mode, p->old_name);4205else{4206if(p->is_rename || p->is_copy)4207show_rename_copy(p);4208else{4209if(p->score) {4210printf(" rewrite%s(%d%%)\n",4211 p->new_name, p->score);4212show_mode_change(p,0);4213}4214else4215show_mode_change(p,1);4216}4217}4218}4219}42204221static voidpatch_stats(struct apply_state *state,struct patch *patch)4222{4223int lines = patch->lines_added + patch->lines_deleted;42244225if(lines > state->max_change)4226 state->max_change = lines;4227if(patch->old_name) {4228int len =quote_c_style(patch->old_name, NULL, NULL,0);4229if(!len)4230 len =strlen(patch->old_name);4231if(len > state->max_len)4232 state->max_len = len;4233}4234if(patch->new_name) {4235int len =quote_c_style(patch->new_name, NULL, NULL,0);4236if(!len)4237 len =strlen(patch->new_name);4238if(len > state->max_len)4239 state->max_len = len;4240}4241}42424243static intremove_file(struct apply_state *state,struct patch *patch,int rmdir_empty)4244{4245if(state->update_index) {4246if(remove_file_from_cache(patch->old_name) <0)4247returnerror(_("unable to remove%sfrom index"), patch->old_name);4248}4249if(!state->cached) {4250if(!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {4251remove_path(patch->old_name);4252}4253}4254return0;4255}42564257static intadd_index_file(struct apply_state *state,4258const char*path,4259unsigned mode,4260void*buf,4261unsigned long size)4262{4263struct stat st;4264struct cache_entry *ce;4265int namelen =strlen(path);4266unsigned ce_size =cache_entry_size(namelen);42674268if(!state->update_index)4269return0;42704271 ce =xcalloc(1, ce_size);4272memcpy(ce->name, path, namelen);4273 ce->ce_mode =create_ce_mode(mode);4274 ce->ce_flags =create_ce_flags(0);4275 ce->ce_namelen = namelen;4276if(S_ISGITLINK(mode)) {4277const char*s;42784279if(!skip_prefix(buf,"Subproject commit ", &s) ||4280get_oid_hex(s, &ce->oid)) {4281free(ce);4282returnerror(_("corrupt patch for submodule%s"), path);4283}4284}else{4285if(!state->cached) {4286if(lstat(path, &st) <0) {4287free(ce);4288returnerror_errno(_("unable to stat newly "4289"created file '%s'"),4290 path);4291}4292fill_stat_cache_info(ce, &st);4293}4294if(write_object_file(buf, size, blob_type, &ce->oid) <0) {4295free(ce);4296returnerror(_("unable to create backing store "4297"for newly created file%s"), path);4298}4299}4300if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4301free(ce);4302returnerror(_("unable to add cache entry for%s"), path);4303}43044305return0;4306}43074308/*4309 * Returns:4310 * -1 if an unrecoverable error happened4311 * 0 if everything went well4312 * 1 if a recoverable error happened4313 */4314static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)4315{4316int fd, res;4317struct strbuf nbuf = STRBUF_INIT;43184319if(S_ISGITLINK(mode)) {4320struct stat st;4321if(!lstat(path, &st) &&S_ISDIR(st.st_mode))4322return0;4323return!!mkdir(path,0777);4324}43254326if(has_symlinks &&S_ISLNK(mode))4327/* Although buf:size is counted string, it also is NUL4328 * terminated.4329 */4330return!!symlink(buf, path);43314332 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);4333if(fd <0)4334return1;43354336if(convert_to_working_tree(path, buf, size, &nbuf)) {4337 size = nbuf.len;4338 buf = nbuf.buf;4339}43404341 res =write_in_full(fd, buf, size) <0;4342if(res)4343error_errno(_("failed to write to '%s'"), path);4344strbuf_release(&nbuf);43454346if(close(fd) <0&& !res)4347returnerror_errno(_("closing file '%s'"), path);43484349return res ? -1:0;4350}43514352/*4353 * We optimistically assume that the directories exist,4354 * which is true 99% of the time anyway. If they don't,4355 * we create them and try again.4356 *4357 * Returns:4358 * -1 on error4359 * 0 otherwise4360 */4361static intcreate_one_file(struct apply_state *state,4362char*path,4363unsigned mode,4364const char*buf,4365unsigned long size)4366{4367int res;43684369if(state->cached)4370return0;43714372 res =try_create_file(path, mode, buf, size);4373if(res <0)4374return-1;4375if(!res)4376return0;43774378if(errno == ENOENT) {4379if(safe_create_leading_directories(path))4380return0;4381 res =try_create_file(path, mode, buf, size);4382if(res <0)4383return-1;4384if(!res)4385return0;4386}43874388if(errno == EEXIST || errno == EACCES) {4389/* We may be trying to create a file where a directory4390 * used to be.4391 */4392struct stat st;4393if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))4394 errno = EEXIST;4395}43964397if(errno == EEXIST) {4398unsigned int nr =getpid();43994400for(;;) {4401char newpath[PATH_MAX];4402mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);4403 res =try_create_file(newpath, mode, buf, size);4404if(res <0)4405return-1;4406if(!res) {4407if(!rename(newpath, path))4408return0;4409unlink_or_warn(newpath);4410break;4411}4412if(errno != EEXIST)4413break;4414++nr;4415}4416}4417returnerror_errno(_("unable to write file '%s' mode%o"),4418 path, mode);4419}44204421static intadd_conflicted_stages_file(struct apply_state *state,4422struct patch *patch)4423{4424int stage, namelen;4425unsigned ce_size, mode;4426struct cache_entry *ce;44274428if(!state->update_index)4429return0;4430 namelen =strlen(patch->new_name);4431 ce_size =cache_entry_size(namelen);4432 mode = patch->new_mode ? patch->new_mode : (S_IFREG |0644);44334434remove_file_from_cache(patch->new_name);4435for(stage =1; stage <4; stage++) {4436if(is_null_oid(&patch->threeway_stage[stage -1]))4437continue;4438 ce =xcalloc(1, ce_size);4439memcpy(ce->name, patch->new_name, namelen);4440 ce->ce_mode =create_ce_mode(mode);4441 ce->ce_flags =create_ce_flags(stage);4442 ce->ce_namelen = namelen;4443oidcpy(&ce->oid, &patch->threeway_stage[stage -1]);4444if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0) {4445free(ce);4446returnerror(_("unable to add cache entry for%s"),4447 patch->new_name);4448}4449}44504451return0;4452}44534454static intcreate_file(struct apply_state *state,struct patch *patch)4455{4456char*path = patch->new_name;4457unsigned mode = patch->new_mode;4458unsigned long size = patch->resultsize;4459char*buf = patch->result;44604461if(!mode)4462 mode = S_IFREG |0644;4463if(create_one_file(state, path, mode, buf, size))4464return-1;44654466if(patch->conflicted_threeway)4467returnadd_conflicted_stages_file(state, patch);4468else4469returnadd_index_file(state, path, mode, buf, size);4470}44714472/* phase zero is to remove, phase one is to create */4473static intwrite_out_one_result(struct apply_state *state,4474struct patch *patch,4475int phase)4476{4477if(patch->is_delete >0) {4478if(phase ==0)4479returnremove_file(state, patch,1);4480return0;4481}4482if(patch->is_new >0|| patch->is_copy) {4483if(phase ==1)4484returncreate_file(state, patch);4485return0;4486}4487/*4488 * Rename or modification boils down to the same4489 * thing: remove the old, write the new4490 */4491if(phase ==0)4492returnremove_file(state, patch, patch->is_rename);4493if(phase ==1)4494returncreate_file(state, patch);4495return0;4496}44974498static intwrite_out_one_reject(struct apply_state *state,struct patch *patch)4499{4500FILE*rej;4501char namebuf[PATH_MAX];4502struct fragment *frag;4503int cnt =0;4504struct strbuf sb = STRBUF_INIT;45054506for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {4507if(!frag->rejected)4508continue;4509 cnt++;4510}45114512if(!cnt) {4513if(state->apply_verbosity > verbosity_normal)4514say_patch_name(stderr,4515_("Applied patch%scleanly."), patch);4516return0;4517}45184519/* This should not happen, because a removal patch that leaves4520 * contents are marked "rejected" at the patch level.4521 */4522if(!patch->new_name)4523die(_("internal error"));45244525/* Say this even without --verbose */4526strbuf_addf(&sb,Q_("Applying patch %%swith%dreject...",4527"Applying patch %%swith%drejects...",4528 cnt),4529 cnt);4530if(state->apply_verbosity > verbosity_silent)4531say_patch_name(stderr, sb.buf, patch);4532strbuf_release(&sb);45334534 cnt =strlen(patch->new_name);4535if(ARRAY_SIZE(namebuf) <= cnt +5) {4536 cnt =ARRAY_SIZE(namebuf) -5;4537warning(_("truncating .rej filename to %.*s.rej"),4538 cnt -1, patch->new_name);4539}4540memcpy(namebuf, patch->new_name, cnt);4541memcpy(namebuf + cnt,".rej",5);45424543 rej =fopen(namebuf,"w");4544if(!rej)4545returnerror_errno(_("cannot open%s"), namebuf);45464547/* Normal git tools never deal with .rej, so do not pretend4548 * this is a git patch by saying --git or giving extended4549 * headers. While at it, maybe please "kompare" that wants4550 * the trailing TAB and some garbage at the end of line ;-).4551 */4552fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",4553 patch->new_name, patch->new_name);4554for(cnt =1, frag = patch->fragments;4555 frag;4556 cnt++, frag = frag->next) {4557if(!frag->rejected) {4558if(state->apply_verbosity > verbosity_silent)4559fprintf_ln(stderr,_("Hunk #%dapplied cleanly."), cnt);4560continue;4561}4562if(state->apply_verbosity > verbosity_silent)4563fprintf_ln(stderr,_("Rejected hunk #%d."), cnt);4564fprintf(rej,"%.*s", frag->size, frag->patch);4565if(frag->patch[frag->size-1] !='\n')4566fputc('\n', rej);4567}4568fclose(rej);4569return-1;4570}45714572/*4573 * Returns:4574 * -1 if an error happened4575 * 0 if the patch applied cleanly4576 * 1 if the patch did not apply cleanly4577 */4578static intwrite_out_results(struct apply_state *state,struct patch *list)4579{4580int phase;4581int errs =0;4582struct patch *l;4583struct string_list cpath = STRING_LIST_INIT_DUP;45844585for(phase =0; phase <2; phase++) {4586 l = list;4587while(l) {4588if(l->rejected)4589 errs =1;4590else{4591if(write_out_one_result(state, l, phase)) {4592string_list_clear(&cpath,0);4593return-1;4594}4595if(phase ==1) {4596if(write_out_one_reject(state, l))4597 errs =1;4598if(l->conflicted_threeway) {4599string_list_append(&cpath, l->new_name);4600 errs =1;4601}4602}4603}4604 l = l->next;4605}4606}46074608if(cpath.nr) {4609struct string_list_item *item;46104611string_list_sort(&cpath);4612if(state->apply_verbosity > verbosity_silent) {4613for_each_string_list_item(item, &cpath)4614fprintf(stderr,"U%s\n", item->string);4615}4616string_list_clear(&cpath,0);46174618rerere(0);4619}46204621return errs;4622}46234624/*4625 * Try to apply a patch.4626 *4627 * Returns:4628 * -128 if a bad error happened (like patch unreadable)4629 * -1 if patch did not apply and user cannot deal with it4630 * 0 if the patch applied4631 * 1 if the patch did not apply but user might fix it4632 */4633static intapply_patch(struct apply_state *state,4634int fd,4635const char*filename,4636int options)4637{4638size_t offset;4639struct strbuf buf = STRBUF_INIT;/* owns the patch text */4640struct patch *list = NULL, **listp = &list;4641int skipped_patch =0;4642int res =0;46434644 state->patch_input_file = filename;4645if(read_patch_file(&buf, fd) <0)4646return-128;4647 offset =0;4648while(offset < buf.len) {4649struct patch *patch;4650int nr;46514652 patch =xcalloc(1,sizeof(*patch));4653 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);4654 patch->recount = !!(options & APPLY_OPT_RECOUNT);4655 nr =parse_chunk(state, buf.buf + offset, buf.len - offset, patch);4656if(nr <0) {4657free_patch(patch);4658if(nr == -128) {4659 res = -128;4660goto end;4661}4662break;4663}4664if(state->apply_in_reverse)4665reverse_patches(patch);4666if(use_patch(state, patch)) {4667patch_stats(state, patch);4668*listp = patch;4669 listp = &patch->next;4670}4671else{4672if(state->apply_verbosity > verbosity_normal)4673say_patch_name(stderr,_("Skipped patch '%s'."), patch);4674free_patch(patch);4675 skipped_patch++;4676}4677 offset += nr;4678}46794680if(!list && !skipped_patch) {4681error(_("unrecognized input"));4682 res = -128;4683goto end;4684}46854686if(state->whitespace_error && (state->ws_error_action == die_on_ws_error))4687 state->apply =0;46884689 state->update_index = state->check_index && state->apply;4690if(state->update_index && !is_lock_file_locked(&state->lock_file)) {4691if(state->index_file)4692hold_lock_file_for_update(&state->lock_file,4693 state->index_file,4694 LOCK_DIE_ON_ERROR);4695else4696hold_locked_index(&state->lock_file, LOCK_DIE_ON_ERROR);4697}46984699if(state->check_index &&read_apply_cache(state) <0) {4700error(_("unable to read index file"));4701 res = -128;4702goto end;4703}47044705if(state->check || state->apply) {4706int r =check_patch_list(state, list);4707if(r == -128) {4708 res = -128;4709goto end;4710}4711if(r <0&& !state->apply_with_reject) {4712 res = -1;4713goto end;4714}4715}47164717if(state->apply) {4718int write_res =write_out_results(state, list);4719if(write_res <0) {4720 res = -128;4721goto end;4722}4723if(write_res >0) {4724/* with --3way, we still need to write the index out */4725 res = state->apply_with_reject ? -1:1;4726goto end;4727}4728}47294730if(state->fake_ancestor &&4731build_fake_ancestor(state, list)) {4732 res = -128;4733goto end;4734}47354736if(state->diffstat && state->apply_verbosity > verbosity_silent)4737stat_patch_list(state, list);47384739if(state->numstat && state->apply_verbosity > verbosity_silent)4740numstat_patch_list(state, list);47414742if(state->summary && state->apply_verbosity > verbosity_silent)4743summary_patch_list(list);47444745end:4746free_patch_list(list);4747strbuf_release(&buf);4748string_list_clear(&state->fn_table,0);4749return res;4750}47514752static intapply_option_parse_exclude(const struct option *opt,4753const char*arg,int unset)4754{4755struct apply_state *state = opt->value;4756add_name_limit(state, arg,1);4757return0;4758}47594760static intapply_option_parse_include(const struct option *opt,4761const char*arg,int unset)4762{4763struct apply_state *state = opt->value;4764add_name_limit(state, arg,0);4765 state->has_include =1;4766return0;4767}47684769static intapply_option_parse_p(const struct option *opt,4770const char*arg,4771int unset)4772{4773struct apply_state *state = opt->value;4774 state->p_value =atoi(arg);4775 state->p_value_known =1;4776return0;4777}47784779static intapply_option_parse_space_change(const struct option *opt,4780const char*arg,int unset)4781{4782struct apply_state *state = opt->value;4783if(unset)4784 state->ws_ignore_action = ignore_ws_none;4785else4786 state->ws_ignore_action = ignore_ws_change;4787return0;4788}47894790static intapply_option_parse_whitespace(const struct option *opt,4791const char*arg,int unset)4792{4793struct apply_state *state = opt->value;4794 state->whitespace_option = arg;4795if(parse_whitespace_option(state, arg))4796exit(1);4797return0;4798}47994800static intapply_option_parse_directory(const struct option *opt,4801const char*arg,int unset)4802{4803struct apply_state *state = opt->value;4804strbuf_reset(&state->root);4805strbuf_addstr(&state->root, arg);4806strbuf_complete(&state->root,'/');4807return0;4808}48094810intapply_all_patches(struct apply_state *state,4811int argc,4812const char**argv,4813int options)4814{4815int i;4816int res;4817int errs =0;4818int read_stdin =1;48194820for(i =0; i < argc; i++) {4821const char*arg = argv[i];4822char*to_free = NULL;4823int fd;48244825if(!strcmp(arg,"-")) {4826 res =apply_patch(state,0,"<stdin>", options);4827if(res <0)4828goto end;4829 errs |= res;4830 read_stdin =0;4831continue;4832}else4833 arg = to_free =prefix_filename(state->prefix, arg);48344835 fd =open(arg, O_RDONLY);4836if(fd <0) {4837error(_("can't open patch '%s':%s"), arg,strerror(errno));4838 res = -128;4839free(to_free);4840goto end;4841}4842 read_stdin =0;4843set_default_whitespace_mode(state);4844 res =apply_patch(state, fd, arg, options);4845close(fd);4846free(to_free);4847if(res <0)4848goto end;4849 errs |= res;4850}4851set_default_whitespace_mode(state);4852if(read_stdin) {4853 res =apply_patch(state,0,"<stdin>", options);4854if(res <0)4855goto end;4856 errs |= res;4857}48584859if(state->whitespace_error) {4860if(state->squelch_whitespace_errors &&4861 state->squelch_whitespace_errors < state->whitespace_error) {4862int squelched =4863 state->whitespace_error - state->squelch_whitespace_errors;4864warning(Q_("squelched%dwhitespace error",4865"squelched%dwhitespace errors",4866 squelched),4867 squelched);4868}4869if(state->ws_error_action == die_on_ws_error) {4870error(Q_("%dline adds whitespace errors.",4871"%dlines add whitespace errors.",4872 state->whitespace_error),4873 state->whitespace_error);4874 res = -128;4875goto end;4876}4877if(state->applied_after_fixing_ws && state->apply)4878warning(Q_("%dline applied after"4879" fixing whitespace errors.",4880"%dlines applied after"4881" fixing whitespace errors.",4882 state->applied_after_fixing_ws),4883 state->applied_after_fixing_ws);4884else if(state->whitespace_error)4885warning(Q_("%dline adds whitespace errors.",4886"%dlines add whitespace errors.",4887 state->whitespace_error),4888 state->whitespace_error);4889}48904891if(state->update_index) {4892 res =write_locked_index(&the_index, &state->lock_file, COMMIT_LOCK);4893if(res) {4894error(_("Unable to write new index file"));4895 res = -128;4896goto end;4897}4898}48994900 res = !!errs;49014902end:4903rollback_lock_file(&state->lock_file);49044905if(state->apply_verbosity <= verbosity_silent) {4906set_error_routine(state->saved_error_routine);4907set_warn_routine(state->saved_warn_routine);4908}49094910if(res > -1)4911return res;4912return(res == -1?1:128);4913}49144915intapply_parse_options(int argc,const char**argv,4916struct apply_state *state,4917int*force_apply,int*options,4918const char*const*apply_usage)4919{4920struct option builtin_apply_options[] = {4921{ OPTION_CALLBACK,0,"exclude", state,N_("path"),4922N_("don't apply changes matching the given path"),49230, apply_option_parse_exclude },4924{ OPTION_CALLBACK,0,"include", state,N_("path"),4925N_("apply changes matching the given path"),49260, apply_option_parse_include },4927{ OPTION_CALLBACK,'p', NULL, state,N_("num"),4928N_("remove <num> leading slashes from traditional diff paths"),49290, apply_option_parse_p },4930OPT_BOOL(0,"no-add", &state->no_add,4931N_("ignore additions made by the patch")),4932OPT_BOOL(0,"stat", &state->diffstat,4933N_("instead of applying the patch, output diffstat for the input")),4934OPT_NOOP_NOARG(0,"allow-binary-replacement"),4935OPT_NOOP_NOARG(0,"binary"),4936OPT_BOOL(0,"numstat", &state->numstat,4937N_("show number of added and deleted lines in decimal notation")),4938OPT_BOOL(0,"summary", &state->summary,4939N_("instead of applying the patch, output a summary for the input")),4940OPT_BOOL(0,"check", &state->check,4941N_("instead of applying the patch, see if the patch is applicable")),4942OPT_BOOL(0,"index", &state->check_index,4943N_("make sure the patch is applicable to the current index")),4944OPT_BOOL(0,"cached", &state->cached,4945N_("apply a patch without touching the working tree")),4946OPT_BOOL(0,"unsafe-paths", &state->unsafe_paths,4947N_("accept a patch that touches outside the working area")),4948OPT_BOOL(0,"apply", force_apply,4949N_("also apply the patch (use with --stat/--summary/--check)")),4950OPT_BOOL('3',"3way", &state->threeway,4951N_("attempt three-way merge if a patch does not apply")),4952OPT_FILENAME(0,"build-fake-ancestor", &state->fake_ancestor,4953N_("build a temporary index based on embedded index information")),4954/* Think twice before adding "--nul" synonym to this */4955OPT_SET_INT('z', NULL, &state->line_termination,4956N_("paths are separated with NUL character"),'\0'),4957OPT_INTEGER('C', NULL, &state->p_context,4958N_("ensure at least <n> lines of context match")),4959{ OPTION_CALLBACK,0,"whitespace", state,N_("action"),4960N_("detect new or modified lines that have whitespace errors"),49610, apply_option_parse_whitespace },4962{ OPTION_CALLBACK,0,"ignore-space-change", state, NULL,4963N_("ignore changes in whitespace when finding context"),4964 PARSE_OPT_NOARG, apply_option_parse_space_change },4965{ OPTION_CALLBACK,0,"ignore-whitespace", state, NULL,4966N_("ignore changes in whitespace when finding context"),4967 PARSE_OPT_NOARG, apply_option_parse_space_change },4968OPT_BOOL('R',"reverse", &state->apply_in_reverse,4969N_("apply the patch in reverse")),4970OPT_BOOL(0,"unidiff-zero", &state->unidiff_zero,4971N_("don't expect at least one line of context")),4972OPT_BOOL(0,"reject", &state->apply_with_reject,4973N_("leave the rejected hunks in corresponding *.rej files")),4974OPT_BOOL(0,"allow-overlap", &state->allow_overlap,4975N_("allow overlapping hunks")),4976OPT__VERBOSE(&state->apply_verbosity,N_("be verbose")),4977OPT_BIT(0,"inaccurate-eof", options,4978N_("tolerate incorrectly detected missing new-line at the end of file"),4979 APPLY_OPT_INACCURATE_EOF),4980OPT_BIT(0,"recount", options,4981N_("do not trust the line counts in the hunk headers"),4982 APPLY_OPT_RECOUNT),4983{ OPTION_CALLBACK,0,"directory", state,N_("root"),4984N_("prepend <root> to all filenames"),49850, apply_option_parse_directory },4986OPT_END()4987};49884989returnparse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage,0);4990}