Home | History | Annotate | Line # | Download | only in patch
patch.c revision 1.32
      1  1.27     joerg /*
      2  1.27     joerg  * $OpenBSD: patch.c,v 1.45 2007/04/18 21:52:24 sobrado Exp $
      3  1.27     joerg  * $DragonFly: src/usr.bin/patch/patch.c,v 1.10 2008/08/10 23:39:56 joerg Exp $
      4  1.32      cjep  * $NetBSD: patch.c,v 1.32 2021/05/25 11:25:59 cjep Exp $
      5  1.27     joerg  */
      6   1.4   thorpej 
      7  1.27     joerg /*
      8  1.27     joerg  * patch - a program to apply diffs to original files
      9  1.27     joerg  *
     10   1.1       cgd  * Copyright 1986, Larry Wall
     11  1.27     joerg  *
     12   1.9     ragge  * Redistribution and use in source and binary forms, with or without
     13  1.27     joerg  * modification, are permitted provided that the following condition is met:
     14  1.27     joerg  * 1. Redistributions of source code must retain the above copyright notice,
     15  1.27     joerg  * this condition and the following disclaimer.
     16   1.9     ragge  *
     17  1.27     joerg  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
     18  1.27     joerg  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     19  1.27     joerg  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     20  1.27     joerg  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
     21  1.27     joerg  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     22  1.27     joerg  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     23  1.27     joerg  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     24  1.27     joerg  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     25   1.9     ragge  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     26   1.9     ragge  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     27   1.9     ragge  * SUCH DAMAGE.
     28  1.27     joerg  *
     29  1.27     joerg  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
     30  1.27     joerg  * behaviour
     31   1.1       cgd  */
     32   1.2   mycroft 
     33   1.6  christos #include <sys/cdefs.h>
     34  1.32      cjep __RCSID("$NetBSD: patch.c,v 1.32 2021/05/25 11:25:59 cjep Exp $");
     35  1.27     joerg 
     36  1.27     joerg #include <sys/types.h>
     37  1.27     joerg #include <sys/stat.h>
     38  1.27     joerg 
     39  1.27     joerg #include <ctype.h>
     40  1.27     joerg #include <getopt.h>
     41  1.27     joerg #include <limits.h>
     42  1.27     joerg #include <stdio.h>
     43  1.27     joerg #include <string.h>
     44  1.27     joerg #include <stdlib.h>
     45  1.27     joerg #include <unistd.h>
     46   1.1       cgd 
     47   1.1       cgd #include "common.h"
     48   1.1       cgd #include "util.h"
     49   1.1       cgd #include "pch.h"
     50   1.1       cgd #include "inp.h"
     51   1.1       cgd #include "backupfile.h"
     52  1.27     joerg #include "pathnames.h"
     53  1.27     joerg 
     54  1.27     joerg mode_t		filemode = 0644;
     55   1.1       cgd 
     56  1.32      cjep char		*buf;			/* general purpose buffer */
     57  1.32      cjep size_t		bufsz;			/* general purpose buffer size */
     58  1.27     joerg 
     59  1.27     joerg bool		using_plan_a = true;	/* try to keep everything in memory */
     60  1.27     joerg bool		out_of_mem = false;	/* ran out of memory in plan a */
     61  1.27     joerg 
     62  1.27     joerg #define MAXFILEC 2
     63  1.27     joerg 
     64  1.27     joerg char		*filearg[MAXFILEC];
     65  1.27     joerg bool		ok_to_create_file = false;
     66  1.27     joerg char		*outname = NULL;
     67  1.27     joerg char		*origprae = NULL;
     68  1.27     joerg char		*TMPOUTNAME;
     69  1.27     joerg char		*TMPINNAME;
     70  1.27     joerg char		*TMPREJNAME;
     71  1.27     joerg char		*TMPPATNAME;
     72  1.27     joerg bool		toutkeep = false;
     73  1.27     joerg bool		trejkeep = false;
     74  1.27     joerg bool		warn_on_invalid_line;
     75  1.27     joerg bool		last_line_missing_eol;
     76   1.6  christos 
     77  1.27     joerg #ifdef DEBUGGING
     78  1.27     joerg int		debug = 0;
     79  1.27     joerg #endif
     80   1.1       cgd 
     81  1.27     joerg bool		force = false;
     82  1.27     joerg bool		batch = false;
     83  1.27     joerg bool		verbose = true;
     84  1.27     joerg bool		reverse = false;
     85  1.27     joerg bool		noreverse = false;
     86  1.27     joerg bool		skip_rest_of_patch = false;
     87  1.27     joerg int		strippath = 957;
     88  1.27     joerg bool		canonicalize = false;
     89  1.27     joerg bool		check_only = false;
     90  1.27     joerg int		diff_type = 0;
     91  1.27     joerg char		*revision = NULL;	/* prerequisite revision, if any */
     92  1.27     joerg LINENUM		input_lines = 0;	/* how long is input file in lines */
     93  1.27     joerg int		posix = 0;		/* strict POSIX mode? */
     94  1.27     joerg 
     95  1.27     joerg static void	reinitialize_almost_everything(void);
     96  1.27     joerg static void	get_some_switches(void);
     97  1.27     joerg static LINENUM	locate_hunk(LINENUM);
     98  1.27     joerg static void	abort_context_hunk(void);
     99  1.27     joerg static void	rej_line(int, LINENUM);
    100  1.27     joerg static void	abort_hunk(void);
    101  1.27     joerg static void	apply_hunk(LINENUM);
    102  1.27     joerg static void	init_output(const char *);
    103  1.27     joerg static void	init_reject(const char *);
    104  1.27     joerg static void	copy_till(LINENUM, bool);
    105  1.27     joerg static bool	spew_output(void);
    106  1.27     joerg static void	dump_line(LINENUM, bool);
    107  1.27     joerg static bool	patch_match(LINENUM, LINENUM, LINENUM);
    108  1.27     joerg static bool	similar(const char *, const char *, int);
    109  1.29     joerg __dead static void	usage(void);
    110  1.27     joerg 
    111  1.27     joerg /* true if -E was specified on command line.  */
    112  1.27     joerg static bool	remove_empty_files = false;
    113  1.27     joerg 
    114  1.27     joerg /* true if -R was specified on command line.  */
    115  1.27     joerg static bool	reverse_flag_specified = false;
    116  1.27     joerg 
    117  1.27     joerg /* buffer holding the name of the rejected patch file. */
    118  1.31       nia static char	rejname[PATH_MAX];
    119  1.27     joerg 
    120  1.27     joerg /* buffer for stderr */
    121  1.27     joerg static char	serrbuf[BUFSIZ];
    122  1.27     joerg 
    123  1.27     joerg /* how many input lines have been irretractibly output */
    124  1.27     joerg static LINENUM	last_frozen_line = 0;
    125  1.27     joerg 
    126  1.27     joerg static int	Argc;		/* guess */
    127  1.27     joerg static char	**Argv;
    128  1.27     joerg static int	Argc_last;	/* for restarting plan_b */
    129  1.27     joerg static char	**Argv_last;
    130  1.27     joerg 
    131  1.27     joerg static FILE	*ofp = NULL;	/* output file pointer */
    132  1.27     joerg static FILE	*rejfp = NULL;	/* reject file pointer */
    133  1.27     joerg 
    134  1.27     joerg static int	filec = 0;	/* how many file arguments? */
    135  1.27     joerg static LINENUM	last_offset = 0;
    136  1.27     joerg static LINENUM	maxfuzz = 2;
    137  1.27     joerg 
    138  1.27     joerg /* patch using ifdef, ifndef, etc. */
    139  1.27     joerg static bool		do_defines = false;
    140  1.27     joerg /* #ifdef xyzzy */
    141  1.27     joerg static char		if_defined[128];
    142  1.27     joerg /* #ifndef xyzzy */
    143  1.27     joerg static char		not_defined[128];
    144  1.27     joerg /* #else */
    145  1.27     joerg static const char	else_defined[] = "#else\n";
    146  1.27     joerg /* #endif xyzzy */
    147  1.27     joerg static char		end_defined[128];
    148   1.1       cgd 
    149   1.1       cgd 
    150   1.1       cgd /* Apply a set of diffs as appropriate. */
    151   1.1       cgd 
    152   1.1       cgd int
    153  1.10  kristerw main(int argc, char *argv[])
    154   1.1       cgd {
    155  1.27     joerg 	int	error = 0, hunk, failed, i, fd;
    156  1.27     joerg 	LINENUM	where = 0, newwhere, fuzz, mymaxfuzz;
    157  1.27     joerg 	const	char *tmpdir;
    158  1.27     joerg 	char	*v;
    159  1.27     joerg 
    160  1.32      cjep 	bufsz = INITLINELEN;
    161  1.32      cjep 	if ((buf = malloc(bufsz)) == NULL)
    162  1.32      cjep 		pfatal("allocating input buffer");
    163  1.32      cjep 	buf[0] = '\0';
    164  1.32      cjep 
    165  1.27     joerg 	setbuf(stderr, serrbuf);
    166  1.27     joerg 	for (i = 0; i < MAXFILEC; i++)
    167  1.27     joerg 		filearg[i] = NULL;
    168  1.27     joerg 
    169  1.27     joerg 	/* Cons up the names of the temporary files.  */
    170  1.27     joerg 	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
    171  1.27     joerg 		tmpdir = _PATH_TMP;
    172  1.27     joerg 	for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
    173  1.27     joerg 		;
    174  1.27     joerg 	i++;
    175  1.27     joerg 	if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
    176  1.27     joerg 		fatal("cannot allocate memory");
    177  1.27     joerg 	if ((fd = mkstemp(TMPOUTNAME)) < 0)
    178  1.27     joerg 		pfatal("can't create %s", TMPOUTNAME);
    179  1.27     joerg 	close(fd);
    180  1.27     joerg 
    181  1.27     joerg 	if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
    182  1.27     joerg 		fatal("cannot allocate memory");
    183  1.27     joerg 	if ((fd = mkstemp(TMPINNAME)) < 0)
    184  1.27     joerg 		pfatal("can't create %s", TMPINNAME);
    185  1.27     joerg 	close(fd);
    186  1.27     joerg 
    187  1.27     joerg 	if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
    188  1.27     joerg 		fatal("cannot allocate memory");
    189  1.27     joerg 	if ((fd = mkstemp(TMPREJNAME)) < 0)
    190  1.27     joerg 		pfatal("can't create %s", TMPREJNAME);
    191  1.27     joerg 	close(fd);
    192  1.27     joerg 
    193  1.27     joerg 	if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
    194  1.27     joerg 		fatal("cannot allocate memory");
    195  1.27     joerg 	if ((fd = mkstemp(TMPPATNAME)) < 0)
    196  1.27     joerg 		pfatal("can't create %s", TMPPATNAME);
    197  1.27     joerg 	close(fd);
    198  1.27     joerg 
    199  1.27     joerg 	v = getenv("SIMPLE_BACKUP_SUFFIX");
    200  1.27     joerg 	if (v)
    201  1.27     joerg 		simple_backup_suffix = v;
    202  1.27     joerg 	else
    203  1.27     joerg 		simple_backup_suffix = ORIGEXT;
    204  1.27     joerg 
    205  1.30       nia 	if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
    206  1.30       nia 		v = getenv("VERSION_CONTROL");
    207  1.30       nia 	if (v != NULL)
    208  1.30       nia 		backup_type = get_version(v);
    209  1.30       nia 
    210  1.27     joerg 	/* parse switches */
    211  1.27     joerg 	Argc = argc;
    212  1.27     joerg 	Argv = argv;
    213  1.27     joerg 	get_some_switches();
    214  1.27     joerg 
    215  1.30       nia 	if (backup_type == undefined)
    216  1.30       nia 		backup_type = posix ? none : numbered_existing;
    217  1.27     joerg 
    218  1.27     joerg 	/* make sure we clean up /tmp in case of disaster */
    219  1.27     joerg 	set_signals(0);
    220   1.1       cgd 
    221  1.27     joerg 	for (open_patch_file(filearg[1]); there_is_another_patch();
    222  1.27     joerg 	    reinitialize_almost_everything()) {
    223  1.27     joerg 		/* for each patch in patch file */
    224  1.27     joerg 
    225  1.27     joerg 		warn_on_invalid_line = true;
    226  1.27     joerg 
    227  1.27     joerg 		if (outname == NULL)
    228  1.27     joerg 			outname = savestr(filearg[0]);
    229  1.27     joerg 
    230  1.27     joerg 		/* for ed script just up and do it and exit */
    231  1.27     joerg 		if (diff_type == ED_DIFF) {
    232  1.27     joerg 			do_ed_script();
    233  1.27     joerg 			continue;
    234  1.27     joerg 		}
    235  1.27     joerg 		/* initialize the patched file */
    236  1.27     joerg 		if (!skip_rest_of_patch)
    237  1.27     joerg 			init_output(TMPOUTNAME);
    238  1.27     joerg 
    239  1.27     joerg 		/* initialize reject file */
    240  1.27     joerg 		init_reject(TMPREJNAME);
    241  1.27     joerg 
    242  1.27     joerg 		/* find out where all the lines are */
    243  1.27     joerg 		if (!skip_rest_of_patch)
    244  1.27     joerg 			scan_input(filearg[0]);
    245  1.27     joerg 
    246  1.27     joerg 		/* from here on, open no standard i/o files, because malloc */
    247  1.27     joerg 		/* might misfire and we can't catch it easily */
    248  1.27     joerg 
    249  1.27     joerg 		/* apply each hunk of patch */
    250  1.27     joerg 		hunk = 0;
    251  1.27     joerg 		failed = 0;
    252  1.27     joerg 		out_of_mem = false;
    253  1.27     joerg 		while (another_hunk()) {
    254  1.27     joerg 			hunk++;
    255  1.27     joerg 			fuzz = 0;
    256  1.27     joerg 			mymaxfuzz = pch_context();
    257  1.27     joerg 			if (maxfuzz < mymaxfuzz)
    258  1.27     joerg 				mymaxfuzz = maxfuzz;
    259  1.27     joerg 			if (!skip_rest_of_patch) {
    260  1.27     joerg 				do {
    261  1.27     joerg 					where = locate_hunk(fuzz);
    262  1.27     joerg 					if (hunk == 1 && where == 0 && !force) {
    263   1.1       cgd 						/* dwim for reversed patch? */
    264  1.27     joerg 						if (!pch_swap()) {
    265  1.27     joerg 							if (fuzz == 0)
    266  1.27     joerg 								say("Not enough memory to try swapped hunk!  Assuming unswapped.\n");
    267  1.27     joerg 							continue;
    268  1.27     joerg 						}
    269  1.27     joerg 						reverse = !reverse;
    270  1.27     joerg 						/* try again */
    271  1.27     joerg 						where = locate_hunk(fuzz);
    272  1.27     joerg 						if (where == 0) {
    273  1.27     joerg 							/* didn't find it swapped */
    274  1.27     joerg 							if (!pch_swap())
    275  1.27     joerg 								/* put it back to normal */
    276  1.27     joerg 								fatal("lost hunk on alloc error!\n");
    277  1.27     joerg 							reverse = !reverse;
    278  1.27     joerg 						} else if (noreverse) {
    279  1.27     joerg 							if (!pch_swap())
    280  1.27     joerg 								/* put it back to normal */
    281  1.27     joerg 								fatal("lost hunk on alloc error!\n");
    282  1.27     joerg 							reverse = !reverse;
    283  1.27     joerg 							say("Ignoring previously applied (or reversed) patch.\n");
    284  1.27     joerg 							skip_rest_of_patch = true;
    285  1.27     joerg 						} else if (batch) {
    286  1.27     joerg 							if (verbose)
    287  1.27     joerg 								say("%seversed (or previously applied) patch detected!  %s -R.",
    288  1.27     joerg 								    reverse ? "R" : "Unr",
    289  1.27     joerg 								    reverse ? "Assuming" : "Ignoring");
    290  1.27     joerg 						} else {
    291  1.27     joerg 							ask("%seversed (or previously applied) patch detected!  %s -R? [y] ",
    292  1.27     joerg 							    reverse ? "R" : "Unr",
    293  1.27     joerg 							    reverse ? "Assume" : "Ignore");
    294  1.27     joerg 							if (*buf == 'n') {
    295  1.27     joerg 								ask("Apply anyway? [n] ");
    296  1.27     joerg 								if (*buf != 'y')
    297  1.27     joerg 									skip_rest_of_patch = true;
    298  1.27     joerg 								where = 0;
    299  1.27     joerg 								reverse = !reverse;
    300  1.27     joerg 								if (!pch_swap())
    301  1.27     joerg 									/* put it back to normal */
    302  1.27     joerg 									fatal("lost hunk on alloc error!\n");
    303  1.27     joerg 							}
    304  1.27     joerg 						}
    305  1.27     joerg 					}
    306  1.27     joerg 				} while (!skip_rest_of_patch && where == 0 &&
    307  1.27     joerg 				    ++fuzz <= mymaxfuzz);
    308  1.27     joerg 
    309  1.27     joerg 				if (skip_rest_of_patch) {	/* just got decided */
    310  1.27     joerg 					if (ferror(ofp) || fclose(ofp)) {
    311  1.27     joerg 						say("Error writing %s\n",
    312  1.27     joerg 						    TMPOUTNAME);
    313  1.27     joerg 						error = 1;
    314  1.27     joerg 					}
    315  1.27     joerg 					ofp = NULL;
    316  1.27     joerg 				}
    317  1.27     joerg 			}
    318  1.27     joerg 			newwhere = pch_newfirst() + last_offset;
    319  1.27     joerg 			if (skip_rest_of_patch) {
    320  1.27     joerg 				abort_hunk();
    321  1.27     joerg 				failed++;
    322  1.27     joerg 				if (verbose)
    323  1.27     joerg 					say("Hunk #%d ignored at %ld.\n",
    324  1.27     joerg 					    hunk, newwhere);
    325  1.27     joerg 			} else if (where == 0) {
    326  1.27     joerg 				abort_hunk();
    327  1.27     joerg 				failed++;
    328  1.27     joerg 				if (verbose)
    329  1.27     joerg 					say("Hunk #%d failed at %ld.\n",
    330  1.27     joerg 					    hunk, newwhere);
    331  1.27     joerg 			} else {
    332  1.27     joerg 				apply_hunk(where);
    333  1.27     joerg 				if (verbose) {
    334  1.27     joerg 					say("Hunk #%d succeeded at %ld",
    335  1.27     joerg 					    hunk, newwhere);
    336  1.27     joerg 					if (fuzz != 0)
    337  1.27     joerg 						say(" with fuzz %ld", fuzz);
    338  1.27     joerg 					if (last_offset)
    339  1.27     joerg 						say(" (offset %ld line%s)",
    340  1.27     joerg 						    last_offset,
    341  1.27     joerg 						    last_offset == 1L ? "" : "s");
    342  1.27     joerg 					say(".\n");
    343  1.27     joerg 				}
    344  1.27     joerg 			}
    345  1.27     joerg 		}
    346  1.27     joerg 
    347  1.27     joerg 		if (out_of_mem && using_plan_a) {
    348  1.27     joerg 			Argc = Argc_last;
    349  1.27     joerg 			Argv = Argv_last;
    350  1.27     joerg 			say("\n\nRan out of memory using Plan A--trying again...\n\n");
    351  1.27     joerg 			if (ofp)
    352  1.27     joerg 				fclose(ofp);
    353  1.27     joerg 			ofp = NULL;
    354  1.27     joerg 			if (rejfp)
    355  1.27     joerg 				fclose(rejfp);
    356  1.27     joerg 			rejfp = NULL;
    357  1.27     joerg 			continue;
    358  1.27     joerg 		}
    359  1.27     joerg 		if (hunk == 0)
    360  1.27     joerg 			fatal("Internal error: hunk should not be 0\n");
    361  1.27     joerg 
    362  1.27     joerg 		/* finish spewing out the new file */
    363  1.27     joerg 		if (!skip_rest_of_patch && !spew_output()) {
    364  1.27     joerg 			say("Can't write %s\n", TMPOUTNAME);
    365  1.27     joerg 			error = 1;
    366  1.27     joerg 		}
    367  1.27     joerg 
    368  1.27     joerg 		/* and put the output where desired */
    369  1.27     joerg 		ignore_signals();
    370  1.27     joerg 		if (!skip_rest_of_patch) {
    371  1.27     joerg 			struct stat	statbuf;
    372  1.27     joerg 			char	*realout = outname;
    373  1.27     joerg 
    374  1.27     joerg 			if (!check_only) {
    375  1.27     joerg 				if (move_file(TMPOUTNAME, outname) < 0) {
    376  1.27     joerg 					toutkeep = true;
    377  1.27     joerg 					realout = TMPOUTNAME;
    378  1.27     joerg 					chmod(TMPOUTNAME, filemode);
    379  1.27     joerg 				} else
    380  1.27     joerg 					chmod(outname, filemode);
    381  1.27     joerg 
    382  1.27     joerg 				if (remove_empty_files &&
    383  1.27     joerg 				    stat(realout, &statbuf) == 0 &&
    384  1.27     joerg 				    statbuf.st_size == 0) {
    385  1.27     joerg 					if (verbose)
    386  1.27     joerg 						say("Removing %s (empty after patching).\n",
    387  1.27     joerg 						    realout);
    388  1.27     joerg 					unlink(realout);
    389  1.27     joerg 				}
    390  1.27     joerg 			}
    391  1.27     joerg 		}
    392  1.27     joerg 		if (ferror(rejfp) || fclose(rejfp)) {
    393  1.27     joerg 			say("Error writing %s\n", rejname);
    394  1.27     joerg 			error = 1;
    395  1.27     joerg 		}
    396  1.27     joerg 		rejfp = NULL;
    397  1.27     joerg 		if (failed) {
    398  1.27     joerg 			error = 1;
    399  1.27     joerg 			if (*rejname == '\0') {
    400  1.27     joerg 				if (strlcpy(rejname, outname,
    401  1.27     joerg 				    sizeof(rejname)) >= sizeof(rejname))
    402  1.27     joerg 					fatal("filename %s is too long\n", outname);
    403  1.27     joerg 				if (strlcat(rejname, REJEXT,
    404  1.27     joerg 				    sizeof(rejname)) >= sizeof(rejname))
    405  1.27     joerg 					fatal("filename %s is too long\n", outname);
    406  1.27     joerg 			}
    407  1.27     joerg 			if (skip_rest_of_patch) {
    408  1.27     joerg 				say("%d out of %d hunks ignored--saving rejects to %s\n",
    409  1.27     joerg 				    failed, hunk, rejname);
    410  1.27     joerg 			} else {
    411  1.27     joerg 				say("%d out of %d hunks failed--saving rejects to %s\n",
    412  1.27     joerg 				    failed, hunk, rejname);
    413  1.27     joerg 			}
    414  1.27     joerg 			if (!check_only && move_file(TMPREJNAME, rejname) < 0)
    415  1.27     joerg 				trejkeep = true;
    416  1.27     joerg 		}
    417  1.27     joerg 		set_signals(1);
    418  1.27     joerg 	}
    419  1.27     joerg 	my_exit(error);
    420  1.27     joerg 	/* NOTREACHED */
    421   1.1       cgd }
    422   1.1       cgd 
    423   1.1       cgd /* Prepare to find the next patch to do in the patch file. */
    424   1.1       cgd 
    425   1.6  christos static void
    426  1.10  kristerw reinitialize_almost_everything(void)
    427   1.1       cgd {
    428  1.27     joerg 	re_patch();
    429  1.27     joerg 	re_input();
    430   1.1       cgd 
    431  1.27     joerg 	input_lines = 0;
    432  1.27     joerg 	last_frozen_line = 0;
    433   1.1       cgd 
    434  1.27     joerg 	filec = 0;
    435  1.27     joerg 	if (!out_of_mem) {
    436  1.27     joerg 		free(filearg[0]);
    437  1.27     joerg 		filearg[0] = NULL;
    438  1.27     joerg 	}
    439   1.1       cgd 
    440   1.1       cgd 	free(outname);
    441  1.11  kristerw 	outname = NULL;
    442   1.1       cgd 
    443  1.27     joerg 	last_offset = 0;
    444  1.27     joerg 	diff_type = 0;
    445   1.1       cgd 
    446   1.1       cgd 	free(revision);
    447  1.11  kristerw 	revision = NULL;
    448   1.1       cgd 
    449  1.27     joerg 	reverse = reverse_flag_specified;
    450  1.27     joerg 	skip_rest_of_patch = false;
    451   1.1       cgd 
    452  1.27     joerg 	get_some_switches();
    453   1.3   thorpej }
    454   1.3   thorpej 
    455  1.27     joerg /* Process switches and filenames. */
    456   1.1       cgd 
    457   1.6  christos static void
    458  1.10  kristerw get_some_switches(void)
    459   1.1       cgd {
    460  1.27     joerg 	const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
    461  1.27     joerg 	static struct option longopts[] = {
    462  1.27     joerg 		{"backup",		no_argument,		0,	'b'},
    463  1.27     joerg 		{"batch",		no_argument,		0,	't'},
    464  1.27     joerg 		{"check",		no_argument,		0,	'C'},
    465  1.27     joerg 		{"context",		no_argument,		0,	'c'},
    466  1.27     joerg 		{"debug",		required_argument,	0,	'x'},
    467  1.27     joerg 		{"directory",		required_argument,	0,	'd'},
    468  1.27     joerg 		{"ed",			no_argument,		0,	'e'},
    469  1.27     joerg 		{"force",		no_argument,		0,	'f'},
    470  1.27     joerg 		{"forward",		no_argument,		0,	'N'},
    471  1.27     joerg 		{"fuzz",		required_argument,	0,	'F'},
    472  1.27     joerg 		{"ifdef",		required_argument,	0,	'D'},
    473  1.27     joerg 		{"input",		required_argument,	0,	'i'},
    474  1.27     joerg 		{"ignore-whitespace",	no_argument,		0,	'l'},
    475  1.27     joerg 		{"normal",		no_argument,		0,	'n'},
    476  1.27     joerg 		{"output",		required_argument,	0,	'o'},
    477  1.27     joerg 		{"prefix",		required_argument,	0,	'B'},
    478  1.27     joerg 		{"quiet",		no_argument,		0,	's'},
    479  1.27     joerg 		{"reject-file",		required_argument,	0,	'r'},
    480  1.27     joerg 		{"remove-empty-files",	no_argument,		0,	'E'},
    481  1.27     joerg 		{"reverse",		no_argument,		0,	'R'},
    482  1.27     joerg 		{"silent",		no_argument,		0,	's'},
    483  1.27     joerg 		{"strip",		required_argument,	0,	'p'},
    484  1.27     joerg 		{"suffix",		required_argument,	0,	'z'},
    485  1.27     joerg 		{"unified",		no_argument,		0,	'u'},
    486  1.27     joerg 		{"version",		no_argument,		0,	'v'},
    487  1.27     joerg 		{"version-control",	required_argument,	0,	'V'},
    488  1.27     joerg 		{"posix",		no_argument,		&posix,	1},
    489  1.27     joerg 		{NULL,			0,			0,	0}
    490  1.27     joerg 	};
    491  1.27     joerg 	int ch;
    492  1.27     joerg 
    493  1.27     joerg 	rejname[0] = '\0';
    494  1.27     joerg 	Argc_last = Argc;
    495  1.27     joerg 	Argv_last = Argv;
    496  1.27     joerg 	if (!Argc)
    497  1.27     joerg 		return;
    498  1.27     joerg 	optreset = optind = 1;
    499  1.27     joerg 	while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
    500  1.27     joerg 		switch (ch) {
    501  1.20   mycroft 		case 'b':
    502  1.30       nia 			if (backup_type == undefined)
    503  1.27     joerg 				backup_type = numbered_existing;
    504  1.27     joerg 			if (optarg == NULL)
    505  1.27     joerg 				break;
    506  1.27     joerg 			if (verbose)
    507  1.27     joerg 				say("Warning, the ``-b suffix'' option has been"
    508  1.27     joerg 				    " obsoleted by the -z option.\n");
    509  1.27     joerg 			/* FALLTHROUGH */
    510  1.27     joerg 		case 'z':
    511  1.27     joerg 			/* must directly follow 'b' case for backwards compat */
    512  1.27     joerg 			simple_backup_suffix = savestr(optarg);
    513  1.27     joerg 			break;
    514  1.20   mycroft 		case 'B':
    515  1.27     joerg 			origprae = savestr(optarg);
    516  1.27     joerg 			break;
    517  1.20   mycroft 		case 'c':
    518  1.27     joerg 			diff_type = CONTEXT_DIFF;
    519  1.27     joerg 			break;
    520  1.23       skd 		case 'C':
    521  1.27     joerg 			check_only = true;
    522  1.27     joerg 			break;
    523  1.20   mycroft 		case 'd':
    524  1.27     joerg 			if (chdir(optarg) < 0)
    525  1.27     joerg 				pfatal("can't cd to %s", optarg);
    526  1.27     joerg 			break;
    527  1.20   mycroft 		case 'D':
    528  1.27     joerg 			do_defines = true;
    529  1.27     joerg 			if (!isalpha((unsigned char)*optarg) && *optarg != '_')
    530  1.27     joerg 				fatal("argument to -D is not an identifier\n");
    531  1.27     joerg 			snprintf(if_defined, sizeof if_defined,
    532  1.27     joerg 			    "#ifdef %s\n", optarg);
    533  1.27     joerg 			snprintf(not_defined, sizeof not_defined,
    534  1.27     joerg 			    "#ifndef %s\n", optarg);
    535  1.27     joerg 			snprintf(end_defined, sizeof end_defined,
    536  1.27     joerg 			    "#endif /* %s */\n", optarg);
    537  1.27     joerg 			break;
    538  1.20   mycroft 		case 'e':
    539  1.27     joerg 			diff_type = ED_DIFF;
    540  1.27     joerg 			break;
    541  1.20   mycroft 		case 'E':
    542  1.27     joerg 			remove_empty_files = true;
    543  1.27     joerg 			break;
    544  1.20   mycroft 		case 'f':
    545  1.27     joerg 			force = true;
    546  1.27     joerg 			break;
    547  1.20   mycroft 		case 'F':
    548  1.27     joerg 			maxfuzz = atoi(optarg);
    549  1.27     joerg 			break;
    550  1.20   mycroft 		case 'i':
    551  1.27     joerg 			if (++filec == MAXFILEC)
    552  1.27     joerg 				fatal("too many file arguments\n");
    553  1.27     joerg 			filearg[filec] = savestr(optarg);
    554  1.27     joerg 			break;
    555  1.20   mycroft 		case 'l':
    556  1.27     joerg 			canonicalize = true;
    557  1.27     joerg 			break;
    558  1.20   mycroft 		case 'n':
    559  1.27     joerg 			diff_type = NORMAL_DIFF;
    560  1.27     joerg 			break;
    561  1.20   mycroft 		case 'N':
    562  1.27     joerg 			noreverse = true;
    563  1.27     joerg 			break;
    564  1.20   mycroft 		case 'o':
    565  1.27     joerg 			outname = savestr(optarg);
    566  1.27     joerg 			break;
    567  1.20   mycroft 		case 'p':
    568  1.27     joerg 			strippath = atoi(optarg);
    569  1.27     joerg 			break;
    570  1.20   mycroft 		case 'r':
    571  1.27     joerg 			if (strlcpy(rejname, optarg,
    572  1.27     joerg 			    sizeof(rejname)) >= sizeof(rejname))
    573  1.27     joerg 				fatal("argument for -r is too long\n");
    574  1.27     joerg 			break;
    575  1.20   mycroft 		case 'R':
    576  1.27     joerg 			reverse = true;
    577  1.27     joerg 			reverse_flag_specified = true;
    578  1.27     joerg 			break;
    579  1.20   mycroft 		case 's':
    580  1.27     joerg 			verbose = false;
    581  1.27     joerg 			break;
    582  1.20   mycroft 		case 't':
    583  1.27     joerg 			batch = true;
    584  1.27     joerg 			break;
    585  1.20   mycroft 		case 'u':
    586  1.27     joerg 			diff_type = UNI_DIFF;
    587  1.27     joerg 			break;
    588  1.20   mycroft 		case 'v':
    589  1.27     joerg 			version();
    590  1.27     joerg 			break;
    591  1.20   mycroft 		case 'V':
    592  1.27     joerg 			backup_type = get_version(optarg);
    593  1.27     joerg 			break;
    594   1.1       cgd #ifdef DEBUGGING
    595  1.20   mycroft 		case 'x':
    596  1.27     joerg 			debug = atoi(optarg);
    597  1.27     joerg 			break;
    598   1.1       cgd #endif
    599  1.20   mycroft 		default:
    600  1.27     joerg 			if (ch != '\0')
    601  1.27     joerg 				usage();
    602  1.27     joerg 			break;
    603  1.27     joerg 		}
    604  1.27     joerg 	}
    605  1.27     joerg 	Argc -= optind;
    606  1.27     joerg 	Argv += optind;
    607  1.27     joerg 
    608  1.27     joerg 	if (Argc > 0) {
    609  1.27     joerg 		filearg[0] = savestr(*Argv++);
    610  1.27     joerg 		Argc--;
    611  1.27     joerg 		while (Argc > 0) {
    612  1.27     joerg 			if (++filec == MAXFILEC)
    613  1.27     joerg 				fatal("too many file arguments\n");
    614  1.27     joerg 			filearg[filec] = savestr(*Argv++);
    615  1.27     joerg 			Argc--;
    616  1.20   mycroft 		}
    617   1.1       cgd 	}
    618  1.27     joerg 
    619  1.27     joerg 	if (getenv("POSIXLY_CORRECT") != NULL)
    620  1.27     joerg 		posix = 1;
    621   1.1       cgd }
    622   1.1       cgd 
    623  1.27     joerg static void
    624  1.27     joerg usage(void)
    625  1.27     joerg {
    626  1.27     joerg 	fprintf(stderr,
    627  1.27     joerg "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
    628  1.27     joerg "             [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
    629  1.27     joerg "             [-r rej-name] [-V t | nil | never] [-x number] [-z backup-ext]\n"
    630  1.27     joerg "             [--posix] [origfile [patchfile]]\n"
    631  1.27     joerg "       patch <patchfile\n");
    632  1.28  dholland 	my_exit(EXIT_FAILURE);
    633  1.27     joerg }
    634   1.1       cgd 
    635  1.27     joerg /*
    636  1.27     joerg  * Attempt to find the right place to apply this hunk of patch.
    637  1.27     joerg  */
    638   1.6  christos static LINENUM
    639  1.10  kristerw locate_hunk(LINENUM fuzz)
    640   1.1       cgd {
    641  1.27     joerg 	LINENUM	first_guess = pch_first() + last_offset;
    642  1.27     joerg 	LINENUM	offset;
    643  1.27     joerg 	LINENUM	pat_lines = pch_ptrn_lines();
    644  1.27     joerg 	LINENUM	max_pos_offset = input_lines - first_guess - pat_lines + 1;
    645  1.27     joerg 	LINENUM	max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
    646  1.27     joerg 
    647  1.27     joerg 	if (pat_lines == 0) {		/* null range matches always */
    648  1.27     joerg 		if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
    649  1.27     joerg 		    || diff_type == NEW_CONTEXT_DIFF
    650  1.27     joerg 		    || diff_type == UNI_DIFF)) {
    651  1.27     joerg 			say("Empty context always matches.\n");
    652  1.27     joerg 		}
    653  1.27     joerg 		return (first_guess);
    654  1.27     joerg 	}
    655  1.27     joerg 	if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
    656  1.27     joerg 		max_neg_offset = first_guess - 1;
    657  1.27     joerg 	if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
    658  1.27     joerg 		return first_guess;
    659  1.27     joerg 	for (offset = 1; ; offset++) {
    660  1.27     joerg 		bool	check_after = (offset <= max_pos_offset);
    661  1.27     joerg 		bool	check_before = (offset <= max_neg_offset);
    662   1.1       cgd 
    663  1.27     joerg 		if (check_after && patch_match(first_guess, offset, fuzz)) {
    664   1.1       cgd #ifdef DEBUGGING
    665  1.27     joerg 			if (debug & 1)
    666  1.27     joerg 				say("Offset changing from %ld to %ld\n",
    667  1.27     joerg 				    last_offset, offset);
    668   1.1       cgd #endif
    669  1.27     joerg 			last_offset = offset;
    670  1.27     joerg 			return first_guess + offset;
    671  1.27     joerg 		} else if (check_before && patch_match(first_guess, -offset, fuzz)) {
    672   1.1       cgd #ifdef DEBUGGING
    673  1.27     joerg 			if (debug & 1)
    674  1.27     joerg 				say("Offset changing from %ld to %ld\n",
    675  1.27     joerg 				    last_offset, -offset);
    676   1.1       cgd #endif
    677  1.27     joerg 			last_offset = -offset;
    678  1.27     joerg 			return first_guess - offset;
    679  1.27     joerg 		} else if (!check_before && !check_after)
    680  1.27     joerg 			return 0;
    681   1.1       cgd 	}
    682   1.1       cgd }
    683   1.1       cgd 
    684   1.1       cgd /* We did not find the pattern, dump out the hunk so they can handle it. */
    685   1.1       cgd 
    686   1.6  christos static void
    687  1.27     joerg abort_context_hunk(void)
    688   1.1       cgd {
    689  1.27     joerg 	LINENUM	i;
    690  1.27     joerg 	const LINENUM	pat_end = pch_end();
    691  1.27     joerg 	/*
    692  1.27     joerg 	 * add in last_offset to guess the same as the previous successful
    693  1.27     joerg 	 * hunk
    694  1.27     joerg 	 */
    695  1.27     joerg 	const LINENUM	oldfirst = pch_first() + last_offset;
    696  1.27     joerg 	const LINENUM	newfirst = pch_newfirst() + last_offset;
    697  1.27     joerg 	const LINENUM	oldlast = oldfirst + pch_ptrn_lines() - 1;
    698  1.27     joerg 	const LINENUM	newlast = newfirst + pch_repl_lines() - 1;
    699  1.27     joerg 	const char	*stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
    700  1.27     joerg 	const char	*minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
    701  1.27     joerg 
    702  1.27     joerg 	fprintf(rejfp, "***************\n");
    703  1.27     joerg 	for (i = 0; i <= pat_end; i++) {
    704  1.27     joerg 		switch (pch_char(i)) {
    705  1.27     joerg 		case '*':
    706  1.27     joerg 			if (oldlast < oldfirst)
    707  1.27     joerg 				fprintf(rejfp, "*** 0%s\n", stars);
    708  1.27     joerg 			else if (oldlast == oldfirst)
    709  1.27     joerg 				fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
    710  1.27     joerg 			else
    711  1.27     joerg 				fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
    712  1.27     joerg 				    oldlast, stars);
    713  1.27     joerg 			break;
    714  1.27     joerg 		case '=':
    715  1.27     joerg 			if (newlast < newfirst)
    716  1.27     joerg 				fprintf(rejfp, "--- 0%s\n", minuses);
    717  1.27     joerg 			else if (newlast == newfirst)
    718  1.27     joerg 				fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
    719  1.27     joerg 			else
    720  1.27     joerg 				fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
    721  1.27     joerg 				    newlast, minuses);
    722  1.27     joerg 			break;
    723  1.27     joerg 		case '\n':
    724  1.27     joerg 			fprintf(rejfp, "%s", pfetch(i));
    725  1.27     joerg 			break;
    726  1.27     joerg 		case ' ':
    727  1.27     joerg 		case '-':
    728  1.27     joerg 		case '+':
    729  1.27     joerg 		case '!':
    730  1.27     joerg 			fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
    731  1.27     joerg 			break;
    732  1.27     joerg 		default:
    733  1.27     joerg 			fatal("fatal internal error in abort_context_hunk\n");
    734  1.27     joerg 		}
    735   1.1       cgd 	}
    736   1.1       cgd }
    737   1.1       cgd 
    738  1.27     joerg static void
    739  1.27     joerg rej_line(int ch, LINENUM i)
    740  1.27     joerg {
    741  1.27     joerg 	size_t len;
    742  1.27     joerg 	const char *line = pfetch(i);
    743  1.27     joerg 
    744  1.27     joerg 	len = strlen(line);
    745  1.26       gdt 
    746  1.27     joerg 	fprintf(rejfp, "%c%s", ch, line);
    747  1.27     joerg 	if (len == 0 || line[len-1] != '\n')
    748  1.27     joerg 		fprintf(rejfp, "\n\\ No newline at end of file\n");
    749  1.27     joerg }
    750  1.26       gdt 
    751  1.27     joerg static void
    752  1.27     joerg abort_hunk(void)
    753  1.26       gdt {
    754  1.27     joerg 	LINENUM		i, j, split;
    755  1.27     joerg 	int		ch1, ch2;
    756  1.27     joerg 	const LINENUM	pat_end = pch_end();
    757  1.27     joerg 	const LINENUM	oldfirst = pch_first() + last_offset;
    758  1.27     joerg 	const LINENUM	newfirst = pch_newfirst() + last_offset;
    759  1.27     joerg 
    760  1.27     joerg 	if (diff_type != UNI_DIFF) {
    761  1.27     joerg 		abort_context_hunk();
    762  1.27     joerg 		return;
    763  1.27     joerg 	}
    764  1.27     joerg 	split = -1;
    765  1.27     joerg 	for (i = 0; i <= pat_end; i++) {
    766  1.27     joerg 		if (pch_char(i) == '=') {
    767  1.27     joerg 			split = i;
    768  1.27     joerg 			break;
    769  1.27     joerg 		}
    770  1.27     joerg 	}
    771  1.27     joerg 	if (split == -1) {
    772  1.27     joerg 		fprintf(rejfp, "malformed hunk: no split found\n");
    773  1.27     joerg 		return;
    774  1.27     joerg 	}
    775  1.27     joerg 	i = 0;
    776  1.27     joerg 	j = split + 1;
    777  1.27     joerg 	fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
    778  1.27     joerg 	    pch_ptrn_lines() ? oldfirst : 0,
    779  1.27     joerg 	    pch_ptrn_lines(), newfirst, pch_repl_lines());
    780  1.27     joerg 	while (i < split || j <= pat_end) {
    781  1.27     joerg 		ch1 = i < split ? pch_char(i) : -1;
    782  1.27     joerg 		ch2 = j <= pat_end ? pch_char(j) : -1;
    783  1.27     joerg 		if (ch1 == '-') {
    784  1.27     joerg 			rej_line('-', i);
    785  1.27     joerg 			i++;
    786  1.27     joerg 		} else if (ch1 == ' ' && ch2 == ' ') {
    787  1.27     joerg 			rej_line(' ', i);
    788  1.27     joerg 			i++;
    789  1.27     joerg 			j++;
    790  1.27     joerg 		} else if (ch1 == '!' && ch2 == '!') {
    791  1.27     joerg 			while (i < split && ch1 == '!') {
    792  1.27     joerg 				rej_line('-', i);
    793  1.27     joerg 				i++;
    794  1.27     joerg 				ch1 = i < split ? pch_char(i) : -1;
    795  1.27     joerg 			}
    796  1.27     joerg 			while (j <= pat_end && ch2 == '!') {
    797  1.27     joerg 				rej_line('+', j);
    798  1.27     joerg 				j++;
    799  1.27     joerg 				ch2 = j <= pat_end ? pch_char(j) : -1;
    800  1.27     joerg 			}
    801  1.27     joerg 		} else if (ch1 == '*') {
    802  1.27     joerg 			i++;
    803  1.27     joerg 		} else if (ch2 == '+' || ch2 == ' ') {
    804  1.27     joerg 			rej_line(ch2, j);
    805  1.27     joerg 			j++;
    806  1.27     joerg 		} else {
    807  1.27     joerg 			fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
    808  1.27     joerg 			    i, split, j);
    809  1.27     joerg 			rej_line(ch1, i);
    810  1.27     joerg 			rej_line(ch2, j);
    811  1.27     joerg 			return;
    812  1.27     joerg 		}
    813  1.27     joerg 	}
    814  1.26       gdt }
    815  1.26       gdt 
    816   1.1       cgd /* We found where to apply it (we hope), so do it. */
    817   1.1       cgd 
    818   1.6  christos static void
    819  1.10  kristerw apply_hunk(LINENUM where)
    820   1.1       cgd {
    821  1.27     joerg 	LINENUM		old = 1;
    822  1.27     joerg 	const LINENUM	lastline = pch_ptrn_lines();
    823  1.27     joerg 	LINENUM		new = lastline + 1;
    824   1.1       cgd #define OUTSIDE 0
    825   1.1       cgd #define IN_IFNDEF 1
    826   1.1       cgd #define IN_IFDEF 2
    827   1.1       cgd #define IN_ELSE 3
    828  1.27     joerg 	int		def_state = OUTSIDE;
    829  1.27     joerg 	const LINENUM	pat_end = pch_end();
    830  1.27     joerg 
    831  1.27     joerg 	where--;
    832  1.27     joerg 	while (pch_char(new) == '=' || pch_char(new) == '\n')
    833  1.27     joerg 		new++;
    834  1.27     joerg 
    835  1.27     joerg 	while (old <= lastline) {
    836  1.27     joerg 		if (pch_char(old) == '-') {
    837  1.27     joerg 			copy_till(where + old - 1, false);
    838  1.27     joerg 			if (do_defines) {
    839  1.27     joerg 				if (def_state == OUTSIDE) {
    840  1.27     joerg 					fputs(not_defined, ofp);
    841  1.27     joerg 					def_state = IN_IFNDEF;
    842  1.27     joerg 				} else if (def_state == IN_IFDEF) {
    843  1.27     joerg 					fputs(else_defined, ofp);
    844  1.27     joerg 					def_state = IN_ELSE;
    845  1.27     joerg 				}
    846  1.27     joerg 				fputs(pfetch(old), ofp);
    847  1.27     joerg 			}
    848  1.27     joerg 			last_frozen_line++;
    849  1.27     joerg 			old++;
    850  1.27     joerg 		} else if (new > pat_end) {
    851  1.27     joerg 			break;
    852  1.27     joerg 		} else if (pch_char(new) == '+') {
    853  1.27     joerg 			copy_till(where + old - 1, false);
    854  1.27     joerg 			if (do_defines) {
    855  1.27     joerg 				if (def_state == IN_IFNDEF) {
    856  1.27     joerg 					fputs(else_defined, ofp);
    857  1.27     joerg 					def_state = IN_ELSE;
    858  1.27     joerg 				} else if (def_state == OUTSIDE) {
    859  1.27     joerg 					fputs(if_defined, ofp);
    860  1.27     joerg 					def_state = IN_IFDEF;
    861  1.27     joerg 				}
    862  1.27     joerg 			}
    863  1.27     joerg 			fputs(pfetch(new), ofp);
    864  1.27     joerg 			new++;
    865  1.27     joerg 		} else if (pch_char(new) != pch_char(old)) {
    866  1.27     joerg 			say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
    867  1.27     joerg 			    pch_hunk_beg() + old,
    868  1.27     joerg 			    pch_hunk_beg() + new);
    869   1.1       cgd #ifdef DEBUGGING
    870  1.27     joerg 			say("oldchar = '%c', newchar = '%c'\n",
    871  1.27     joerg 			    pch_char(old), pch_char(new));
    872   1.1       cgd #endif
    873  1.27     joerg 			my_exit(2);
    874  1.27     joerg 		} else if (pch_char(new) == '!') {
    875  1.27     joerg 			copy_till(where + old - 1, false);
    876  1.27     joerg 			if (do_defines) {
    877  1.27     joerg 				fputs(not_defined, ofp);
    878  1.27     joerg 				def_state = IN_IFNDEF;
    879  1.27     joerg 			}
    880  1.27     joerg 			while (pch_char(old) == '!') {
    881  1.27     joerg 				if (do_defines) {
    882  1.27     joerg 					fputs(pfetch(old), ofp);
    883  1.27     joerg 				}
    884  1.27     joerg 				last_frozen_line++;
    885  1.27     joerg 				old++;
    886  1.27     joerg 			}
    887  1.27     joerg 			if (do_defines) {
    888  1.27     joerg 				fputs(else_defined, ofp);
    889  1.27     joerg 				def_state = IN_ELSE;
    890  1.27     joerg 			}
    891  1.27     joerg 			while (pch_char(new) == '!') {
    892  1.27     joerg 				fputs(pfetch(new), ofp);
    893  1.27     joerg 				new++;
    894  1.27     joerg 			}
    895  1.27     joerg 		} else {
    896  1.27     joerg 			if (pch_char(new) != ' ')
    897  1.27     joerg 				fatal("Internal error: expected ' '\n");
    898  1.27     joerg 			old++;
    899  1.27     joerg 			new++;
    900  1.27     joerg 			if (do_defines && def_state != OUTSIDE) {
    901  1.27     joerg 				fputs(end_defined, ofp);
    902  1.27     joerg 				def_state = OUTSIDE;
    903  1.27     joerg 			}
    904  1.27     joerg 		}
    905   1.1       cgd 	}
    906  1.27     joerg 	if (new <= pat_end && pch_char(new) == '+') {
    907  1.27     joerg 		copy_till(where + old - 1, false);
    908  1.27     joerg 		if (do_defines) {
    909  1.27     joerg 			if (def_state == OUTSIDE) {
    910  1.27     joerg 				fputs(if_defined, ofp);
    911  1.27     joerg 				def_state = IN_IFDEF;
    912  1.27     joerg 			} else if (def_state == IN_IFNDEF) {
    913  1.27     joerg 				fputs(else_defined, ofp);
    914  1.27     joerg 				def_state = IN_ELSE;
    915  1.27     joerg 			}
    916  1.27     joerg 		}
    917  1.27     joerg 		while (new <= pat_end && pch_char(new) == '+') {
    918  1.27     joerg 			fputs(pfetch(new), ofp);
    919  1.27     joerg 			new++;
    920  1.27     joerg 		}
    921   1.1       cgd 	}
    922  1.27     joerg 	if (do_defines && def_state != OUTSIDE) {
    923   1.1       cgd 		fputs(end_defined, ofp);
    924   1.1       cgd 	}
    925   1.1       cgd }
    926   1.1       cgd 
    927  1.27     joerg /*
    928  1.27     joerg  * Open the new file.
    929  1.27     joerg  */
    930   1.6  christos static void
    931  1.27     joerg init_output(const char *name)
    932   1.1       cgd {
    933  1.27     joerg 	ofp = fopen(name, "w");
    934  1.27     joerg 	if (ofp == NULL)
    935  1.27     joerg 		pfatal("can't create %s", name);
    936   1.1       cgd }
    937   1.1       cgd 
    938  1.27     joerg /*
    939  1.27     joerg  * Open a file to put hunks we can't locate.
    940  1.27     joerg  */
    941   1.6  christos static void
    942  1.27     joerg init_reject(const char *name)
    943   1.1       cgd {
    944  1.27     joerg 	rejfp = fopen(name, "w");
    945  1.27     joerg 	if (rejfp == NULL)
    946  1.27     joerg 		pfatal("can't create %s", name);
    947   1.1       cgd }
    948   1.1       cgd 
    949  1.27     joerg /*
    950  1.27     joerg  * Copy input file to output, up to wherever hunk is to be applied.
    951  1.27     joerg  * If endoffile is true, treat the last line specially since it may
    952  1.27     joerg  * lack a newline.
    953  1.27     joerg  */
    954   1.6  christos static void
    955  1.27     joerg copy_till(LINENUM lastline, bool endoffile)
    956   1.1       cgd {
    957  1.27     joerg 	if (last_frozen_line > lastline)
    958  1.27     joerg 		fatal("misordered hunks! output would be garbled\n");
    959  1.27     joerg 	while (last_frozen_line < lastline) {
    960  1.27     joerg 		if (++last_frozen_line == lastline && endoffile)
    961  1.27     joerg 			dump_line(last_frozen_line, !last_line_missing_eol);
    962  1.27     joerg 		else
    963  1.27     joerg 			dump_line(last_frozen_line, true);
    964  1.27     joerg 	}
    965   1.1       cgd }
    966   1.1       cgd 
    967  1.27     joerg /*
    968  1.27     joerg  * Finish copying the input file to the output file.
    969  1.27     joerg  */
    970  1.27     joerg static bool
    971  1.10  kristerw spew_output(void)
    972   1.1       cgd {
    973  1.27     joerg 	int rv;
    974  1.27     joerg 
    975   1.1       cgd #ifdef DEBUGGING
    976  1.27     joerg 	if (debug & 256)
    977  1.27     joerg 		say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
    978   1.1       cgd #endif
    979  1.27     joerg 	if (input_lines)
    980  1.27     joerg 		copy_till(input_lines, true);	/* dump remainder of file */
    981  1.27     joerg 	rv = ferror(ofp) == 0 && fclose(ofp) == 0;
    982  1.27     joerg 	ofp = NULL;
    983  1.27     joerg 	return rv;
    984   1.1       cgd }
    985   1.1       cgd 
    986  1.27     joerg /*
    987  1.27     joerg  * Copy one line from input to output.
    988  1.27     joerg  */
    989   1.6  christos static void
    990  1.27     joerg dump_line(LINENUM line, bool write_newline)
    991   1.1       cgd {
    992  1.27     joerg 	char	*s;
    993   1.1       cgd 
    994  1.27     joerg 	s = ifetch(line, 0);
    995  1.27     joerg 	if (s == NULL)
    996  1.27     joerg 		return;
    997  1.27     joerg 	/* Note: string is not NUL terminated. */
    998  1.27     joerg 	for (; *s != '\n'; s++)
    999  1.27     joerg 		putc(*s, ofp);
   1000  1.27     joerg 	if (write_newline)
   1001  1.27     joerg 		putc('\n', ofp);
   1002   1.1       cgd }
   1003   1.1       cgd 
   1004  1.27     joerg /*
   1005  1.27     joerg  * Does the patch pattern match at line base+offset?
   1006  1.27     joerg  */
   1007   1.6  christos static bool
   1008  1.10  kristerw patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
   1009  1.10  kristerw {
   1010  1.27     joerg 	LINENUM		pline = 1 + fuzz;
   1011  1.27     joerg 	LINENUM		iline;
   1012  1.27     joerg 	LINENUM		pat_lines = pch_ptrn_lines() - fuzz;
   1013  1.27     joerg 	const char	*ilineptr;
   1014  1.27     joerg 	const char	*plineptr;
   1015  1.27     joerg 	short		plinelen;
   1016  1.27     joerg 
   1017  1.27     joerg 	for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
   1018  1.27     joerg 		ilineptr = ifetch(iline, offset >= 0);
   1019  1.27     joerg 		if (ilineptr == NULL)
   1020  1.27     joerg 			return false;
   1021  1.27     joerg 		plineptr = pfetch(pline);
   1022  1.27     joerg 		plinelen = pch_line_len(pline);
   1023  1.27     joerg 		if (canonicalize) {
   1024  1.27     joerg 			if (!similar(ilineptr, plineptr, plinelen))
   1025  1.27     joerg 				return false;
   1026  1.27     joerg 		} else if (strnNE(ilineptr, plineptr, plinelen))
   1027  1.27     joerg 			return false;
   1028  1.27     joerg 		if (iline == input_lines) {
   1029  1.27     joerg 			/*
   1030  1.27     joerg 			 * We are looking at the last line of the file.
   1031  1.27     joerg 			 * If the file has no eol, the patch line should
   1032  1.27     joerg 			 * not have one either and vice-versa. Note that
   1033  1.27     joerg 			 * plinelen > 0.
   1034  1.27     joerg 			 */
   1035  1.27     joerg 			if (last_line_missing_eol) {
   1036  1.27     joerg 				if (plineptr[plinelen - 1] == '\n')
   1037  1.27     joerg 					return false;
   1038  1.27     joerg 			} else {
   1039  1.27     joerg 				if (plineptr[plinelen - 1] != '\n')
   1040  1.27     joerg 					return false;
   1041  1.27     joerg 			}
   1042  1.27     joerg 		}
   1043  1.27     joerg 	}
   1044  1.27     joerg 	return true;
   1045   1.1       cgd }
   1046   1.1       cgd 
   1047  1.27     joerg /*
   1048  1.27     joerg  * Do two lines match with canonicalized white space?
   1049  1.27     joerg  */
   1050   1.6  christos static bool
   1051  1.27     joerg similar(const char *a, const char *b, int len)
   1052   1.1       cgd {
   1053  1.27     joerg 	while (len) {
   1054  1.27     joerg 		if (isspace((unsigned char)*b)) {	/* whitespace (or \n) to match? */
   1055  1.27     joerg 			if (!isspace((unsigned char)*a))	/* no corresponding whitespace? */
   1056  1.27     joerg 				return false;
   1057  1.27     joerg 			while (len && isspace((unsigned char)*b) && *b != '\n')
   1058  1.27     joerg 				b++, len--;	/* skip pattern whitespace */
   1059  1.27     joerg 			while (isspace((unsigned char)*a) && *a != '\n')
   1060  1.27     joerg 				a++;	/* skip target whitespace */
   1061  1.27     joerg 			if (*a == '\n' || *b == '\n')
   1062  1.27     joerg 				return (*a == *b);	/* should end in sync */
   1063  1.27     joerg 		} else if (*a++ != *b++)	/* match non-whitespace chars */
   1064  1.27     joerg 			return false;
   1065  1.27     joerg 		else
   1066  1.27     joerg 			len--;	/* probably not necessary */
   1067   1.1       cgd 	}
   1068  1.27     joerg 	return true;		/* actually, this is not reached */
   1069  1.27     joerg 	/* since there is always a \n */
   1070  1.25     lukem }
   1071