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