Home | History | Annotate | Line # | Download | only in patch
patch.c revision 1.18
      1 /*	$NetBSD: patch.c,v 1.18 2003/07/08 01:55:35 kristerw Exp $	*/
      2 
      3 /* patch - a program to apply diffs to original files
      4  *
      5  * Copyright 1986, Larry Wall
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following condition
      9  * is met:
     10  *  1. Redistributions of source code must retain the above copyright
     11  *     notice, this condition and the following disclaimer.
     12  *
     13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     23  * SUCH DAMAGE.
     24  */
     25 
     26 #include <sys/cdefs.h>
     27 #ifndef lint
     28 __RCSID("$NetBSD: patch.c,v 1.18 2003/07/08 01:55:35 kristerw Exp $");
     29 #endif /* not lint */
     30 
     31 #include "INTERN.h"
     32 #include "common.h"
     33 #include "EXTERN.h"
     34 #include "version.h"
     35 #include "util.h"
     36 #include "pch.h"
     37 #include "inp.h"
     38 #include "backupfile.h"
     39 
     40 #include <stdlib.h>
     41 #include <unistd.h>
     42 
     43 /* procedures */
     44 static void reinitialize_almost_everything(void);
     45 static char *nextarg(void);
     46 static int optcmp(const void *, const void *);
     47 static char decode_long_option(char *);
     48 static void get_some_switches(void);
     49 static LINENUM locate_hunk(LINENUM);
     50 static void abort_hunk(void);
     51 static void apply_hunk(LINENUM);
     52 static void init_output(char *);
     53 static void init_reject(char *);
     54 static void copy_till(LINENUM);
     55 static void spew_output(void);
     56 static void dump_line(LINENUM);
     57 static bool patch_match(LINENUM, LINENUM, LINENUM);
     58 static bool similar(const char *, const char *, size_t);
     59 int main(int, char *[]);
     60 
     61 /* TRUE if -E was specified on command line.  */
     62 static int remove_empty_files = FALSE;
     63 
     64 /* TRUE if -R was specified on command line.  */
     65 static int reverse_flag_specified = FALSE;
     66 
     67 /* Apply a set of diffs as appropriate. */
     68 
     69 int
     70 main(int argc, char *argv[])
     71 {
     72     LINENUM where = 0;
     73     LINENUM newwhere;
     74     LINENUM fuzz;
     75     LINENUM mymaxfuzz;
     76     int hunk = 0;
     77     int failed = 0;
     78     int failtotal = 0;
     79     int i;
     80 
     81     for (i = 0; i<MAXFILEC; i++)
     82 	filearg[i] = NULL;
     83 
     84     myuid = getuid();
     85 
     86     /* Cons up the names of the temporary files.  */
     87     {
     88       /* Directory for temporary files.  */
     89       const char *tmpdir;
     90       size_t tmpname_len;
     91 
     92       tmpdir = getenv ("TMPDIR");
     93       if (tmpdir == NULL) {
     94 	tmpdir = "/tmp";
     95       }
     96       tmpname_len = strlen (tmpdir) + 20;
     97 
     98       TMPOUTNAME = xmalloc(tmpname_len);
     99       strcpy (TMPOUTNAME, tmpdir);
    100       strcat (TMPOUTNAME, "/patchoXXXXXX");
    101       if ((i = mkstemp(TMPOUTNAME)) < 0)
    102         pfatal("can't create %s", TMPOUTNAME);
    103       Close(i);
    104 
    105       TMPINNAME = xmalloc(tmpname_len);
    106       strcpy (TMPINNAME, tmpdir);
    107       strcat (TMPINNAME, "/patchiXXXXXX");
    108       if ((i = mkstemp(TMPINNAME)) < 0)
    109         pfatal("can't create %s", TMPINNAME);
    110       Close(i);
    111 
    112       TMPREJNAME = xmalloc(tmpname_len);
    113       strcpy (TMPREJNAME, tmpdir);
    114       strcat (TMPREJNAME, "/patchrXXXXXX");
    115       if ((i = mkstemp(TMPREJNAME)) < 0)
    116         pfatal("can't create %s", TMPREJNAME);
    117       Close(i);
    118 
    119       TMPPATNAME = xmalloc(tmpname_len);
    120       strcpy (TMPPATNAME, tmpdir);
    121       strcat (TMPPATNAME, "/patchpXXXXXX");
    122       if ((i = mkstemp(TMPPATNAME)) < 0)
    123         pfatal("can't create %s", TMPPATNAME);
    124       Close(i);
    125     }
    126 
    127     {
    128       char *v;
    129 
    130       v = getenv ("SIMPLE_BACKUP_SUFFIX");
    131       if (v)
    132 	simple_backup_suffix = v;
    133       else
    134 	simple_backup_suffix = ORIGEXT;
    135 #ifndef NODIR
    136       v = getenv ("VERSION_CONTROL");
    137       backup_type = get_version (v); /* OK to pass NULL. */
    138 #endif
    139     }
    140 
    141     /* parse switches */
    142     Argc = argc;
    143     Argv = argv;
    144     get_some_switches();
    145 
    146     /* make sure we clean up /tmp in case of disaster */
    147     set_signals(0);
    148 
    149     for (
    150 	open_patch_file(filearg[1]);
    151 	there_is_another_patch();
    152 	reinitialize_almost_everything()
    153     ) {					/* for each patch in patch file */
    154 
    155 	if (!skip_rest_of_patch && outname == NULL)
    156 	    outname = xstrdup(filearg[0]);
    157 
    158 	/* for ed script just up and do it and exit */
    159 	if (diff_type == ED_DIFF) {
    160 	    do_ed_script();
    161 	    continue;
    162 	}
    163 
    164 	/* initialize the patched file */
    165 	if (!skip_rest_of_patch)
    166 	    init_output(TMPOUTNAME);
    167 
    168 	/* initialize reject file */
    169 	init_reject(TMPREJNAME);
    170 
    171 	/* find out where all the lines are */
    172 	if (!skip_rest_of_patch)
    173 	    scan_input(filearg[0]);
    174 
    175 	/* from here on, open no standard i/o files, because malloc */
    176 	/* might misfire and we can't catch it easily */
    177 
    178 	/* apply each hunk of patch */
    179 	hunk = 0;
    180 	failed = 0;
    181 	while (another_hunk()) {
    182 	    hunk++;
    183 	    fuzz = Nulline;
    184 	    mymaxfuzz = pch_context();
    185 	    if (maxfuzz < mymaxfuzz)
    186 		mymaxfuzz = maxfuzz;
    187 	    if (!skip_rest_of_patch) {
    188 		do {
    189 		    where = locate_hunk(fuzz);
    190 		    if (hunk == 1 && where == Nulline && !force) {
    191 						/* dwim for reversed patch? */
    192 			if (!pch_swap()) {
    193 			    if (fuzz == Nulline)
    194 				say(
    195 "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
    196 			    continue;
    197 			}
    198 			reverse = !reverse;
    199 			where = locate_hunk(fuzz);  /* try again */
    200 			if (where == Nulline) {	    /* didn't find it swapped */
    201 			    if (!pch_swap())         /* put it back to normal */
    202 				fatal("lost hunk on alloc error!\n");
    203 			    reverse = !reverse;
    204 			}
    205 			else if (noreverse) {
    206 			    if (!pch_swap())         /* put it back to normal */
    207 				fatal("lost hunk on alloc error!\n");
    208 			    reverse = !reverse;
    209 			    say(
    210 "Ignoring previously applied (or reversed) patch.\n");
    211 			    skip_rest_of_patch = TRUE;
    212 			}
    213 			else if (batch) {
    214 			    if (verbose)
    215 				say(
    216 "%seversed (or previously applied) patch detected!  %s -R.",
    217 				reverse ? "R" : "Unr",
    218 				reverse ? "Assuming" : "Ignoring");
    219 			}
    220 			else {
    221 			    ask(
    222 "%seversed (or previously applied) patch detected!  %s -R? [y] ",
    223 				reverse ? "R" : "Unr",
    224 				reverse ? "Assume" : "Ignore");
    225 			    if (*buf == 'n') {
    226 				ask("Apply anyway? [n] ");
    227 				if (*buf != 'y')
    228 				    skip_rest_of_patch = TRUE;
    229 				where = Nulline;
    230 				reverse = !reverse;
    231 				if (!pch_swap())  /* put it back to normal */
    232 				    fatal("lost hunk on alloc error!\n");
    233 			    }
    234 			}
    235 		    }
    236 		} while (!skip_rest_of_patch && where == Nulline &&
    237 		    ++fuzz <= mymaxfuzz);
    238 
    239 		if (skip_rest_of_patch) {		/* just got decided */
    240 		    Fclose(ofp);
    241 		    ofp = NULL;
    242 		}
    243 	    }
    244 
    245 	    newwhere = pch_newfirst() + last_offset;
    246 	    if (skip_rest_of_patch) {
    247 		abort_hunk();
    248 		failed++;
    249 		if (verbose)
    250 		    say("Hunk #%d ignored at %d.\n", hunk, newwhere);
    251 	    }
    252 	    else if (where == Nulline) {
    253 		abort_hunk();
    254 		failed++;
    255 		if (verbose)
    256 		    say("Hunk #%d failed at %d.\n", hunk, newwhere);
    257 	    }
    258 	    else {
    259 		apply_hunk(where);
    260 		if (verbose) {
    261 		    say("Hunk #%d succeeded at %d", hunk, newwhere);
    262 		    if (fuzz)
    263 			say(" with fuzz %d", fuzz);
    264 		    if (last_offset)
    265 			say(" (offset %d line%s)",
    266 			    last_offset, last_offset==1?"":"s");
    267 		    say(".\n");
    268 		}
    269 	    }
    270 	}
    271 
    272 	assert(hunk);
    273 
    274 	/* finish spewing out the new file */
    275 	if (!skip_rest_of_patch)
    276 	    spew_output();
    277 
    278 	/* and put the output where desired */
    279 	ignore_signals();
    280 	if (!skip_rest_of_patch) {
    281 	    struct stat statbuf;
    282 	    char *realout = outname;
    283 
    284 	    if (move_file(TMPOUTNAME, outname) < 0) {
    285 		toutkeep = TRUE;
    286 		realout = TMPOUTNAME;
    287 		chmod(TMPOUTNAME, filemode);
    288 	    }
    289 	    else
    290 		chmod(outname, filemode);
    291 
    292 	    if (remove_empty_files && stat(realout, &statbuf) == 0
    293 		&& statbuf.st_size == 0) {
    294 		if (verbose)
    295 		    say("Removing %s (empty after patching).\n", realout);
    296 	        while (unlink(realout) >= 0) ; /* while is for Eunice.  */
    297 	    }
    298 	}
    299 	Fclose(rejfp);
    300 	rejfp = NULL;
    301 	if (failed) {
    302 	    failtotal += failed;
    303 	    if (outname != NULL) {
    304 		    if (!*rejname) {
    305 			    Strcpy(rejname, outname);
    306 			    Strcat(rejname, REJEXT);
    307 		    }
    308 		    if (skip_rest_of_patch)
    309 			    say("%d out of %d hunks ignored"
    310 				"--saving rejects to %s\n",
    311 				failed, hunk, rejname);
    312 		    else
    313 			    say("%d out of %d hunks failed"
    314 				"--saving rejects to %s\n",
    315 				failed, hunk, rejname);
    316 		    if (move_file(TMPREJNAME, rejname) < 0)
    317 			    trejkeep = TRUE;
    318 	    } else
    319 		    say("%d out of %d hunks ignored\n", failed, hunk);
    320 	}
    321 	set_signals(1);
    322     }
    323     my_exit(failtotal);
    324     /* NOTREACHED */
    325 }
    326 
    327 /* Prepare to find the next patch to do in the patch file. */
    328 
    329 static void
    330 reinitialize_almost_everything(void)
    331 {
    332     re_patch();
    333     re_input();
    334 
    335     input_lines = 0;
    336     last_frozen_line = 0;
    337 
    338     filec = 0;
    339     if (filearg[0] != NULL) {
    340 	free(filearg[0]);
    341 	filearg[0] = NULL;
    342     }
    343 
    344     if (outname != NULL) {
    345 	free(outname);
    346 	outname = NULL;
    347     }
    348 
    349     last_offset = 0;
    350 
    351     diff_type = 0;
    352 
    353     if (revision != NULL) {
    354 	free(revision);
    355 	revision = NULL;
    356     }
    357 
    358     reverse = reverse_flag_specified;
    359     skip_rest_of_patch = FALSE;
    360 
    361     get_some_switches();
    362 
    363     if (filec >= 2)
    364 	fatal("you may not change to a different patch file\n");
    365 }
    366 
    367 static char *
    368 nextarg(void)
    369 {
    370     if (!--Argc)
    371 	fatal("missing argument after `%s'\n", *Argv);
    372     return *++Argv;
    373 }
    374 
    375 /* Module for handling of long options. */
    376 
    377 struct option {
    378     const char *long_opt;
    379     char short_opt;
    380 };
    381 
    382 static int
    383 optcmp(const void *va, const void *vb)
    384 {
    385     const struct option *a = va, *b = vb;
    386     return strcmp (a->long_opt, b->long_opt);
    387 }
    388 
    389 /* Decode Long options beginning with "--" to their short equivalents. */
    390 
    391 static char
    392 decode_long_option(char *opt)
    393 {
    394     /*
    395      * This table must be sorted on the first field.  We also decode
    396      * unimplemented options as those will probably be dealt with
    397      * later, anyhow.
    398      */
    399     static struct option options[] = {
    400       { "batch",		't' },
    401       { "check",		'C' },
    402       { "context",		'c' },
    403       { "debug",		'x' },
    404       { "directory",		'd' },
    405       { "ed",			'e' },
    406       { "force",		'f' },
    407       { "forward",		'N' },
    408       { "fuzz",			'F' },
    409       { "ifdef",		'D' },
    410       { "ignore-whitespace",	'l' },
    411       { "normal",		'n' },
    412       { "output",		'o' },
    413       { "patchfile",		'i' },
    414       { "prefix",		'B' },
    415       { "quiet",		's' },
    416       { "reject-file",		'r' },
    417       { "remove-empty-files",	'E' },
    418       { "reverse",		'R' },
    419       { "silent",		's' },
    420       { "skip",			'S' },
    421       { "strip",		'p' },
    422       { "suffix",		'b' },
    423       { "unified",		'u' },
    424       { "version",		'v' },
    425       { "version-control",	'V' },
    426     };
    427     struct option key, *found;
    428 
    429     key.long_opt = opt;
    430     found = bsearch(&key, options,
    431 	sizeof(options) / sizeof(options[0]), sizeof(options[0]), optcmp);
    432 
    433     return found ? found->short_opt : '\0';
    434 }
    435 
    436 /* Process switches and filenames up to next '+' or end of list. */
    437 
    438 static void
    439 get_some_switches(void)
    440 {
    441     char *s;
    442 
    443     rejname[0] = '\0';
    444     if (!Argc)
    445 	return;
    446     for (Argc--,Argv++; Argc; Argc--,Argv++) {
    447 	s = Argv[0];
    448 	if (strEQ(s, "+")) {
    449 	    return;			/* + will be skipped by for loop */
    450 	}
    451 	if (*s != '-' || !s[1]) {
    452 	    if (filec == MAXFILEC)
    453 		fatal("too many file arguments\n");
    454 	    if (filec == 1 && filearg[filec] != NULL)
    455 		fatal("-i option and patchfile argument are mutually\
    456 exclusive\n");
    457 	    filearg[filec++] = xstrdup(s);
    458 	}
    459 	else {
    460 	    char opt;
    461 
    462 	    if (*(s + 1) == '-') {
    463 		opt = decode_long_option(s + 2);
    464 		s += strlen(s) - 1;
    465 	    }
    466 	    else
    467 		opt = *++s;
    468 
    469 	    switch (opt) {
    470 	    case 'b':
    471 		simple_backup_suffix = xstrdup(nextarg());
    472 		break;
    473 	    case 'B':
    474 		origprae = xstrdup(nextarg());
    475 		break;
    476 	    case 'c':
    477 		diff_type = CONTEXT_DIFF;
    478 		break;
    479 	    case 'd':
    480 		if (!*++s)
    481 		    s = nextarg();
    482 		if (chdir(s) < 0)
    483 		    pfatal("can't cd to %s", s);
    484 		break;
    485 	    case 'D':
    486 	    	do_defines = TRUE;
    487 		if (!*++s)
    488 		    s = nextarg();
    489 		if (!isalpha((unsigned char)*s) && '_' != *s)
    490 		    fatal("argument to -D is not an identifier\n");
    491 		Sprintf(if_defined, "#ifdef %s\n", s);
    492 		Sprintf(not_defined, "#ifndef %s\n", s);
    493 		Sprintf(end_defined, "#endif /* %s */\n", s);
    494 		break;
    495 	    case 'e':
    496 		diff_type = ED_DIFF;
    497 		break;
    498 	    case 'E':
    499 		remove_empty_files = TRUE;
    500 		break;
    501 	    case 'f':
    502 		force = TRUE;
    503 		break;
    504 	    case 'F':
    505 		if (*++s == '=')
    506 		    s++;
    507 		maxfuzz = atoi(s);
    508 		break;
    509 	    case 'i':
    510 		if (filearg[1] != NULL)
    511 		    free(filearg[1]);
    512 		filearg[1] = xstrdup(nextarg());
    513 		break;
    514 	    case 'l':
    515 		canonicalize = TRUE;
    516 		break;
    517 	    case 'n':
    518 		diff_type = NORMAL_DIFF;
    519 		break;
    520 	    case 'N':
    521 		noreverse = TRUE;
    522 		break;
    523 	    case 'o':
    524 		outname = xstrdup(nextarg());
    525 		break;
    526 	    case 'p':
    527 		if (*++s == '=')
    528 		    s++;
    529 		strippath = atoi(s);
    530 		break;
    531 	    case 'r':
    532 		Strcpy(rejname, nextarg());
    533 		break;
    534 	    case 'R':
    535 		reverse = TRUE;
    536 		reverse_flag_specified = TRUE;
    537 		break;
    538 	    case 's':
    539 		verbose = FALSE;
    540 		break;
    541 	    case 'S':
    542 		skip_rest_of_patch = TRUE;
    543 		break;
    544 	    case 't':
    545 		batch = TRUE;
    546 		break;
    547 	    case 'u':
    548 		diff_type = UNI_DIFF;
    549 		break;
    550 	    case 'v':
    551 		version();
    552 		break;
    553 	    case 'V':
    554 #ifndef NODIR
    555 		backup_type = get_version (nextarg ());
    556 #endif
    557 		break;
    558 #ifdef DEBUGGING
    559 	    case 'x':
    560 		debug = atoi(s+1);
    561 		break;
    562 #endif
    563 	    default:
    564 		fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
    565 		fprintf(stderr, "\
    566 Usage: patch [options] [origfile [patchfile]] [+ [options] [origfile]]...\n\
    567 Options:\n\
    568        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
    569        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
    570        [-r rej-name] [-V {numbered,existing,simple}]\n");
    571 		my_exit(1);
    572 	    }
    573 	}
    574     }
    575 }
    576 
    577 /* Attempt to find the right place to apply this hunk of patch. */
    578 
    579 static LINENUM
    580 locate_hunk(LINENUM fuzz)
    581 {
    582     LINENUM first_guess = pch_first() + last_offset;
    583     LINENUM offset;
    584     LINENUM pat_lines = pch_ptrn_lines();
    585     LINENUM max_pos_offset = input_lines - first_guess
    586 				- pat_lines + 1;
    587     LINENUM max_neg_offset = first_guess - last_frozen_line - 1
    588 				+ pch_context();
    589 
    590     if (!pat_lines)			/* null range matches always */
    591 	return first_guess;
    592     if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
    593 	max_neg_offset = first_guess - 1;
    594     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
    595 	return first_guess;
    596     for (offset = 1; ; offset++) {
    597 	bool check_after = (offset <= max_pos_offset);
    598 	bool check_before = (offset <= max_neg_offset);
    599 
    600 	if (check_after && patch_match(first_guess, offset, fuzz)) {
    601 #ifdef DEBUGGING
    602 	    if (debug & 1)
    603 		say("Offset changing from %d to %d\n", last_offset, offset);
    604 #endif
    605 	    last_offset = offset;
    606 	    return first_guess+offset;
    607 	}
    608 	else if (check_before && patch_match(first_guess, -offset, fuzz)) {
    609 #ifdef DEBUGGING
    610 	    if (debug & 1)
    611 		say("Offset changing from %d to %d\n", last_offset, -offset);
    612 #endif
    613 	    last_offset = -offset;
    614 	    return first_guess-offset;
    615 	}
    616 	else if (!check_before && !check_after)
    617 	    return Nulline;
    618     }
    619 }
    620 
    621 /* We did not find the pattern, dump out the hunk so they can handle it. */
    622 
    623 static void
    624 abort_hunk(void)
    625 {
    626     LINENUM i;
    627     LINENUM pat_end = pch_end();
    628     /* add in last_offset to guess the same as the previous successful hunk */
    629     LINENUM oldfirst = pch_first() + last_offset;
    630     LINENUM newfirst = pch_newfirst() + last_offset;
    631     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
    632     LINENUM newlast = newfirst + pch_repl_lines() - 1;
    633     const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
    634     const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
    635 
    636     fprintf(rejfp, "***************\n");
    637     for (i=0; i<=pat_end; i++) {
    638 	switch (pch_char(i)) {
    639 	case '*':
    640 	    if (oldlast < oldfirst)
    641 		fprintf(rejfp, "*** 0%s\n", stars);
    642 	    else if (oldlast == oldfirst)
    643 		fprintf(rejfp, "*** %d%s\n", oldfirst, stars);
    644 	    else
    645 		fprintf(rejfp, "*** %d,%d%s\n", oldfirst, oldlast, stars);
    646 	    break;
    647 	case '=':
    648 	    if (newlast < newfirst)
    649 		fprintf(rejfp, "--- 0%s\n", minuses);
    650 	    else if (newlast == newfirst)
    651 		fprintf(rejfp, "--- %d%s\n", newfirst, minuses);
    652 	    else
    653 		fprintf(rejfp, "--- %d,%d%s\n", newfirst, newlast, minuses);
    654 	    break;
    655 	case '\n':
    656 	    fprintf(rejfp, "%s", pfetch(i));
    657 	    break;
    658 	case ' ': case '-': case '+': case '!':
    659 	    fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
    660 	    break;
    661 	default:
    662 	    fatal("fatal internal error in abort_hunk\n");
    663 	}
    664     }
    665 }
    666 
    667 /* We found where to apply it (we hope), so do it. */
    668 
    669 static void
    670 apply_hunk(LINENUM where)
    671 {
    672     LINENUM old = 1;
    673     LINENUM lastline = pch_ptrn_lines();
    674     LINENUM new = lastline+1;
    675 #define OUTSIDE 0
    676 #define IN_IFNDEF 1
    677 #define IN_IFDEF 2
    678 #define IN_ELSE 3
    679     int def_state = OUTSIDE;
    680     bool R_do_defines = do_defines;
    681     LINENUM pat_end = pch_end();
    682 
    683     where--;
    684     while (pch_char(new) == '=' || pch_char(new) == '\n')
    685 	new++;
    686 
    687     while (old <= lastline) {
    688 	if (pch_char(old) == '-') {
    689 	    copy_till(where + old - 1);
    690 	    if (R_do_defines) {
    691 		if (def_state == OUTSIDE) {
    692 		    fputs(not_defined, ofp);
    693 		    def_state = IN_IFNDEF;
    694 		}
    695 		else if (def_state == IN_IFDEF) {
    696 		    fputs(else_defined, ofp);
    697 		    def_state = IN_ELSE;
    698 		}
    699 		fputs(pfetch(old), ofp);
    700 	    }
    701 	    last_frozen_line++;
    702 	    old++;
    703 	}
    704 	else if (new > pat_end) {
    705 	    break;
    706 	}
    707 	else if (pch_char(new) == '+') {
    708 	    copy_till(where + old - 1);
    709 	    if (R_do_defines) {
    710 		if (def_state == IN_IFNDEF) {
    711 		    fputs(else_defined, ofp);
    712 		    def_state = IN_ELSE;
    713 		}
    714 		else if (def_state == OUTSIDE) {
    715 		    fputs(if_defined, ofp);
    716 		    def_state = IN_IFDEF;
    717 		}
    718 	    }
    719 	    fputs(pfetch(new), ofp);
    720 	    new++;
    721 	}
    722 	else if (pch_char(new) != pch_char(old)) {
    723 	    say("Out-of-sync patch, lines %d,%d--mangled text or line numbers, maybe?\n",
    724 		pch_hunk_beg() + old,
    725 		pch_hunk_beg() + new);
    726 #ifdef DEBUGGING
    727 	    say("oldchar = '%c', newchar = '%c'\n",
    728 		pch_char(old), pch_char(new));
    729 #endif
    730 	    my_exit(1);
    731 	}
    732 	else if (pch_char(new) == '!') {
    733 	    copy_till(where + old - 1);
    734 	    if (R_do_defines) {
    735 	       fputs(not_defined, ofp);
    736 	       def_state = IN_IFNDEF;
    737 	    }
    738 	    while (pch_char(old) == '!') {
    739 		if (R_do_defines) {
    740 		    fputs(pfetch(old), ofp);
    741 		}
    742 		last_frozen_line++;
    743 		old++;
    744 	    }
    745 	    if (R_do_defines) {
    746 		fputs(else_defined, ofp);
    747 		def_state = IN_ELSE;
    748 	    }
    749 	    while (pch_char(new) == '!') {
    750 		fputs(pfetch(new), ofp);
    751 		new++;
    752 	    }
    753 	}
    754 	else {
    755 	    assert(pch_char(new) == ' ');
    756 	    old++;
    757 	    new++;
    758 	    if (R_do_defines && def_state != OUTSIDE) {
    759 		fputs(end_defined, ofp);
    760 		def_state = OUTSIDE;
    761 	    }
    762 	}
    763     }
    764     if (new <= pat_end && pch_char(new) == '+') {
    765 	copy_till(where + old - 1);
    766 	if (R_do_defines) {
    767 	    if (def_state == OUTSIDE) {
    768 	    	fputs(if_defined, ofp);
    769 		def_state = IN_IFDEF;
    770 	    }
    771 	    else if (def_state == IN_IFNDEF) {
    772 		fputs(else_defined, ofp);
    773 		def_state = IN_ELSE;
    774 	    }
    775 	}
    776 	while (new <= pat_end && pch_char(new) == '+') {
    777 	    fputs(pfetch(new), ofp);
    778 	    new++;
    779 	}
    780     }
    781     if (R_do_defines && def_state != OUTSIDE) {
    782 	fputs(end_defined, ofp);
    783     }
    784 }
    785 
    786 /* Open the new file. */
    787 
    788 static void
    789 init_output(char *name)
    790 {
    791     ofp = fopen(name, "w");
    792     if (ofp == NULL)
    793 	pfatal("can't create %s", name);
    794 }
    795 
    796 /* Open a file to put hunks we can't locate. */
    797 
    798 static void
    799 init_reject(char *name)
    800 {
    801     rejfp = fopen(name, "w");
    802     if (rejfp == NULL)
    803 	pfatal("can't create %s", name);
    804 }
    805 
    806 /* Copy input file to output, up to wherever hunk is to be applied. */
    807 
    808 static void
    809 copy_till(LINENUM lastline)
    810 {
    811     LINENUM R_last_frozen_line = last_frozen_line;
    812 
    813     if (R_last_frozen_line > lastline)
    814 	fatal("misordered hunks! output would be garbled\n");
    815     while (R_last_frozen_line < lastline) {
    816 	dump_line(++R_last_frozen_line);
    817     }
    818     last_frozen_line = R_last_frozen_line;
    819 }
    820 
    821 /* Finish copying the input file to the output file. */
    822 
    823 static void
    824 spew_output(void)
    825 {
    826 #ifdef DEBUGGING
    827     if (debug & 256)
    828 	say("il=%d lfl=%d\n",input_lines,last_frozen_line);
    829 #endif
    830     if (input_lines)
    831 	copy_till(input_lines);		/* dump remainder of file */
    832     Fclose(ofp);
    833     ofp = NULL;
    834 }
    835 
    836 /* Copy one line from input to output. */
    837 
    838 static void
    839 dump_line(LINENUM line)
    840 {
    841     const char *s;
    842     char R_newline = '\n';
    843 
    844     /* Note: string is not null terminated. */
    845     for (s=ifetch(line); putc(*s, ofp) != R_newline; s++) ;
    846 }
    847 
    848 /* Does the patch pattern match at line base+offset? */
    849 
    850 static bool
    851 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
    852 {
    853     LINENUM pline = 1 + fuzz;
    854     LINENUM iline;
    855     LINENUM pat_lines = pch_ptrn_lines() - fuzz;
    856 
    857     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
    858 	if (canonicalize) {
    859 	    if (!similar(ifetch(iline),
    860 			 pfetch(pline),
    861 			 pch_line_len(pline) ))
    862 		return FALSE;
    863 	}
    864 	else if (strnNE(ifetch(iline),
    865 		   pfetch(pline),
    866 		   pch_line_len(pline) ))
    867 	    return FALSE;
    868     }
    869     return TRUE;
    870 }
    871 
    872 /* Do two lines match with canonicalized white space? */
    873 
    874 static bool
    875 similar(const char *a, const char *b, size_t len)
    876 {
    877     while (len) {
    878 	if (isspace((unsigned char)*b)) {/* whitespace (or \n) to match? */
    879 	    if (!isspace((unsigned char)*a))/* no corresponding whitespace? */
    880 		return FALSE;
    881 	    while (len && isspace((unsigned char)*b) && *b != '\n')
    882 		b++,len--;		/* skip pattern whitespace */
    883 	    while (isspace((unsigned char)*a) && *a != '\n')
    884 		a++;			/* skip target whitespace */
    885 	    if (*a == '\n' || *b == '\n')
    886 		return (*a == *b);	/* should end in sync */
    887 	}
    888 	else if (*a++ != *b++)		/* match non-whitespace chars */
    889 	    return FALSE;
    890 	else
    891 	    len--;			/* probably not necessary */
    892     }
    893     return TRUE;			/* actually, this is not reached */
    894 					/* since there is always a \n */
    895 }
    896 
    897 /* Exit with cleanup. */
    898 
    899 void
    900 my_exit(int status)
    901 {
    902     Unlink(TMPINNAME);
    903     if (!toutkeep) {
    904 	Unlink(TMPOUTNAME);
    905     }
    906     if (!trejkeep) {
    907 	Unlink(TMPREJNAME);
    908     }
    909     Unlink(TMPPATNAME);
    910     exit(status);
    911 }
    912