Home | History | Annotate | Line # | Download | only in patch
pch.c revision 1.25
      1 /*
      2  * $OpenBSD: pch.c,v 1.37 2007/09/02 15:19:33 deraadt Exp $
      3  * $DragonFly: src/usr.bin/patch/pch.c,v 1.6 2008/08/10 23:35:40 joerg Exp $
      4  * $NetBSD: pch.c,v 1.25 2013/01/29 09:30:11 wiz Exp $
      5  */
      6 
      7 /*
      8  * patch - a program to apply diffs to original files
      9  *
     10  * Copyright 1986, Larry Wall
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following condition is met:
     14  * 1. Redistributions of source code must retain the above copyright notice,
     15  * this condition and the following disclaimer.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
     18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     20  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
     21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     23  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
     24  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     27  * SUCH DAMAGE.
     28  *
     29  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
     30  * behaviour
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 __RCSID("$NetBSD: pch.c,v 1.25 2013/01/29 09:30:11 wiz Exp $");
     35 
     36 #include <sys/types.h>
     37 #include <sys/stat.h>
     38 
     39 #include <ctype.h>
     40 #include <libgen.h>
     41 #include <limits.h>
     42 #include <stdio.h>
     43 #include <stdlib.h>
     44 #include <string.h>
     45 #include <unistd.h>
     46 
     47 #include "common.h"
     48 #include "util.h"
     49 #include "pch.h"
     50 #include "pathnames.h"
     51 
     52 /* Patch (diff listing) abstract type. */
     53 
     54 static long	p_filesize;	/* size of the patch file */
     55 static LINENUM	p_first;	/* 1st line number */
     56 static LINENUM	p_newfirst;	/* 1st line number of replacement */
     57 static LINENUM	p_ptrn_lines;	/* # lines in pattern */
     58 static LINENUM	p_repl_lines;	/* # lines in replacement text */
     59 static LINENUM	p_end = -1;	/* last line in hunk */
     60 static LINENUM	p_max;		/* max allowed value of p_end */
     61 static LINENUM	p_context = 3;	/* # of context lines */
     62 static LINENUM	p_input_line = 0;	/* current line # from patch file */
     63 static char	**p_line = NULL;/* the text of the hunk */
     64 static short	*p_len = NULL;	/* length of each line */
     65 static char	*p_char = NULL;	/* +, -, and ! */
     66 static int	hunkmax = INITHUNKMAX;	/* size of above arrays to begin with */
     67 static int	p_indent;	/* indent to patch */
     68 static LINENUM	p_base;		/* where to intuit this time */
     69 static LINENUM	p_bline;	/* line # of p_base */
     70 static LINENUM	p_start;	/* where intuit found a patch */
     71 static LINENUM	p_sline;	/* and the line number for it */
     72 static LINENUM	p_hunk_beg;	/* line number of current hunk */
     73 static LINENUM	p_efake = -1;	/* end of faked up lines--don't free */
     74 static LINENUM	p_bfake = -1;	/* beg of faked up lines */
     75 static FILE	*pfp = NULL;	/* patch file pointer */
     76 static char	*bestguess = NULL;	/* guess at correct filename */
     77 
     78 static void	grow_hunkmax(void);
     79 static int	intuit_diff_type(void);
     80 static void	next_intuit_at(LINENUM, LINENUM);
     81 static void	skip_to(LINENUM, LINENUM);
     82 static char	*pgets(char *, int, FILE *);
     83 static char	*best_name(const struct file_name *, bool);
     84 static char	*posix_name(const struct file_name *, bool);
     85 static size_t	num_components(const char *);
     86 
     87 /*
     88  * Prepare to look for the next patch in the patch file.
     89  */
     90 void
     91 re_patch(void)
     92 {
     93 	p_first = 0;
     94 	p_newfirst = 0;
     95 	p_ptrn_lines = 0;
     96 	p_repl_lines = 0;
     97 	p_end = (LINENUM) - 1;
     98 	p_max = 0;
     99 	p_indent = 0;
    100 }
    101 
    102 /*
    103  * Open the patch file at the beginning of time.
    104  */
    105 void
    106 open_patch_file(const char *filename)
    107 {
    108 	struct stat filestat;
    109 
    110 	if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
    111 		pfp = fopen(TMPPATNAME, "w");
    112 		if (pfp == NULL)
    113 			pfatal("can't create %s", TMPPATNAME);
    114 		while (fgets(buf, buf_len, stdin) != NULL)
    115 			fputs(buf, pfp);
    116 		if (ferror(pfp) || fclose(pfp))
    117 			pfatal("can't write %s", TMPPATNAME);
    118 		filename = TMPPATNAME;
    119 	}
    120 	pfp = fopen(filename, "r");
    121 	if (pfp == NULL)
    122 		pfatal("patch file %s not found", filename);
    123 	fstat(fileno(pfp), &filestat);
    124 	p_filesize = filestat.st_size;
    125 	next_intuit_at(0L, 1L);	/* start at the beginning */
    126 	set_hunkmax();
    127 }
    128 
    129 /*
    130  * Make sure our dynamically realloced tables are malloced to begin with.
    131  */
    132 void
    133 set_hunkmax(void)
    134 {
    135 	if (p_line == NULL)
    136 		p_line = calloc((size_t) hunkmax, sizeof(char *));
    137 	if (p_len == NULL)
    138 		p_len = calloc((size_t) hunkmax, sizeof(short));
    139 	if (p_char == NULL)
    140 		p_char = calloc((size_t) hunkmax, sizeof(char));
    141 }
    142 
    143 /*
    144  * Enlarge the arrays containing the current hunk of patch.
    145  */
    146 static void
    147 grow_hunkmax(void)
    148 {
    149 	int		new_hunkmax;
    150 	char		**new_p_line;
    151 	short		*new_p_len;
    152 	char		*new_p_char;
    153 
    154 	new_hunkmax = hunkmax * 2;
    155 
    156 	if (p_line == NULL || p_len == NULL || p_char == NULL)
    157 		fatal("Internal memory allocation error\n");
    158 
    159 	new_p_line = realloc(p_line, new_hunkmax * sizeof(char *));
    160 	if (new_p_line == NULL)
    161 		free(p_line);
    162 
    163 	new_p_len = realloc(p_len, new_hunkmax * sizeof(short));
    164 	if (new_p_len == NULL)
    165 		free(p_len);
    166 
    167 	new_p_char = realloc(p_char, new_hunkmax * sizeof(char));
    168 	if (new_p_char == NULL)
    169 		free(p_char);
    170 
    171 	p_char = new_p_char;
    172 	p_len = new_p_len;
    173 	p_line = new_p_line;
    174 
    175 	if (p_line != NULL && p_len != NULL && p_char != NULL) {
    176 		hunkmax = new_hunkmax;
    177 		return;
    178 	}
    179 
    180 	if (!using_plan_a)
    181 		fatal("out of memory\n");
    182 	out_of_mem = true;	/* whatever is null will be allocated again */
    183 				/* from within plan_a(), of all places */
    184 }
    185 
    186 /* True if the remainder of the patch file contains a diff of some sort. */
    187 
    188 bool
    189 there_is_another_patch(void)
    190 {
    191 	bool exists = false;
    192 
    193 	if (p_base != 0L && p_base >= p_filesize) {
    194 		if (verbose)
    195 			say("done\n");
    196 		return false;
    197 	}
    198 	if (verbose)
    199 		say("Hmm...");
    200 	diff_type = intuit_diff_type();
    201 	if (!diff_type) {
    202 		if (p_base != 0L) {
    203 			if (verbose)
    204 				say("  Ignoring the trailing garbage.\ndone\n");
    205 		} else
    206 			say("  I can't seem to find a patch in there anywhere.\n");
    207 		return false;
    208 	}
    209 	if (verbose)
    210 		say("  %sooks like %s to me...\n",
    211 		    (p_base == 0L ? "L" : "The next patch l"),
    212 		    diff_type == UNI_DIFF ? "a unified diff" :
    213 		    diff_type == CONTEXT_DIFF ? "a context diff" :
    214 		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
    215 		    diff_type == NORMAL_DIFF ? "a normal diff" :
    216 		    "an ed script");
    217 	if (p_indent && verbose)
    218 		say("(Patch is indented %d space%s.)\n", p_indent,
    219 		    p_indent == 1 ? "" : "s");
    220 	skip_to(p_start, p_sline);
    221 	while (filearg[0] == NULL) {
    222 		if (force || batch) {
    223 			say("No file to patch.  Skipping...\n");
    224 			filearg[0] = savestr(bestguess);
    225 			skip_rest_of_patch = true;
    226 			return true;
    227 		}
    228 		ask("File to patch: ");
    229 		if (*buf != '\n') {
    230 			free(bestguess);
    231 			bestguess = savestr(buf);
    232 			filearg[0] = fetchname(buf, &exists, 0);
    233 		}
    234 		if (!exists) {
    235 			ask("No file found--skip this patch? [n] ");
    236 			if (*buf != 'y')
    237 				continue;
    238 			if (verbose)
    239 				say("Skipping patch...\n");
    240 			free(filearg[0]);
    241 			filearg[0] = fetchname(bestguess, &exists, 0);
    242 			skip_rest_of_patch = true;
    243 			return true;
    244 		}
    245 	}
    246 	return true;
    247 }
    248 
    249 /* Determine what kind of diff is in the remaining part of the patch file. */
    250 
    251 static int
    252 intuit_diff_type(void)
    253 {
    254 	long	this_line = 0, previous_line;
    255 	long	first_command_line = -1;
    256 	LINENUM	fcl_line = -1;
    257 	bool	last_line_was_command = false, this_is_a_command = false;
    258 	bool	stars_last_line = false, stars_this_line = false;
    259 	char	*s, *t;
    260 	int	indent, retval;
    261 	struct file_name names[MAX_FILE];
    262 
    263 	memset(names, 0, sizeof(names));
    264 	ok_to_create_file = false;
    265 	fseek(pfp, p_base, SEEK_SET);
    266 	p_input_line = p_bline - 1;
    267 	for (;;) {
    268 		previous_line = this_line;
    269 		last_line_was_command = this_is_a_command;
    270 		stars_last_line = stars_this_line;
    271 		this_line = ftell(pfp);
    272 		indent = 0;
    273 		p_input_line++;
    274 		if (fgets(buf, buf_len, pfp) == NULL) {
    275 			if (first_command_line >= 0L) {
    276 				/* nothing but deletes!? */
    277 				p_start = first_command_line;
    278 				p_sline = fcl_line;
    279 				retval = ED_DIFF;
    280 				goto scan_exit;
    281 			} else {
    282 				p_start = this_line;
    283 				p_sline = p_input_line;
    284 				retval = 0;
    285 				goto scan_exit;
    286 			}
    287 		}
    288 		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
    289 			if (*s == '\t')
    290 				indent += 8 - (indent % 8);
    291 			else
    292 				indent++;
    293 		}
    294 		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
    295 			;
    296 		this_is_a_command = (isdigit((unsigned char)*s) &&
    297 		    (*t == 'd' || *t == 'c' || *t == 'a'));
    298 		if (first_command_line < 0L && this_is_a_command) {
    299 			first_command_line = this_line;
    300 			fcl_line = p_input_line;
    301 			p_indent = indent;	/* assume this for now */
    302 		}
    303 		if (!stars_last_line && strnEQ(s, "*** ", 4))
    304 			names[OLD_FILE].path = fetchname(s + 4,
    305 			    &names[OLD_FILE].exists, strippath);
    306 		else if (strnEQ(s, "--- ", 4))
    307 			names[NEW_FILE].path = fetchname(s + 4,
    308 			    &names[NEW_FILE].exists, strippath);
    309 		else if (strnEQ(s, "+++ ", 4))
    310 			/* pretend it is the old name */
    311 			names[OLD_FILE].path = fetchname(s + 4,
    312 			    &names[OLD_FILE].exists, strippath);
    313 		else if (strnEQ(s, "Index:", 6))
    314 			names[INDEX_FILE].path = fetchname(s + 6,
    315 			    &names[INDEX_FILE].exists, strippath);
    316 		else if (strnEQ(s, "Prereq:", 7)) {
    317 			for (t = s + 7; isspace((unsigned char)*t); t++)
    318 				;
    319 			revision = savestr(t);
    320 			for (t = revision; *t && !isspace((unsigned char)*t); t++)
    321 				;
    322 			*t = '\0';
    323 			if (*revision == '\0') {
    324 				free(revision);
    325 				revision = NULL;
    326 			}
    327 		}
    328 		if ((!diff_type || diff_type == ED_DIFF) &&
    329 		    first_command_line >= 0L &&
    330 		    strEQ(s, ".\n")) {
    331 			p_indent = indent;
    332 			p_start = first_command_line;
    333 			p_sline = fcl_line;
    334 			retval = ED_DIFF;
    335 			goto scan_exit;
    336 		}
    337 		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
    338 			if (strnEQ(s + 4, "0,0", 3))
    339 				ok_to_create_file = true;
    340 			p_indent = indent;
    341 			p_start = this_line;
    342 			p_sline = p_input_line;
    343 			retval = UNI_DIFF;
    344 			goto scan_exit;
    345 		}
    346 		stars_this_line = strnEQ(s, "********", 8);
    347 		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
    348 		    strnEQ(s, "*** ", 4)) {
    349 			if (atol(s + 4) == 0)
    350 				ok_to_create_file = true;
    351 			/*
    352 			 * If this is a new context diff the character just
    353 			 * before the newline is a '*'.
    354 			 */
    355 			while (*s != '\n')
    356 				s++;
    357 			p_indent = indent;
    358 			p_start = previous_line;
    359 			p_sline = p_input_line - 1;
    360 			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
    361 			goto scan_exit;
    362 		}
    363 		if ((!diff_type || diff_type == NORMAL_DIFF) &&
    364 		    last_line_was_command &&
    365 		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
    366 			p_start = previous_line;
    367 			p_sline = p_input_line - 1;
    368 			p_indent = indent;
    369 			retval = NORMAL_DIFF;
    370 			goto scan_exit;
    371 		}
    372 	}
    373 scan_exit:
    374 	if (retval == UNI_DIFF) {
    375 		/* unswap old and new */
    376 		struct file_name tmp = names[OLD_FILE];
    377 		names[OLD_FILE] = names[NEW_FILE];
    378 		names[NEW_FILE] = tmp;
    379 	}
    380 	if (filearg[0] == NULL) {
    381 		if (posix)
    382 			filearg[0] = posix_name(names, ok_to_create_file);
    383 		else {
    384 			/* Ignore the Index: name for context diffs, like GNU */
    385 			if (names[OLD_FILE].path != NULL ||
    386 			    names[NEW_FILE].path != NULL) {
    387 				free(names[INDEX_FILE].path);
    388 				names[INDEX_FILE].path = NULL;
    389 			}
    390 			filearg[0] = best_name(names, ok_to_create_file);
    391 		}
    392 	}
    393 
    394 	free(bestguess);
    395 	bestguess = NULL;
    396 	if (filearg[0] != NULL)
    397 		bestguess = savestr(filearg[0]);
    398 	else if (!ok_to_create_file) {
    399 		/*
    400 		 * We don't want to create a new file but we need a
    401 		 * filename to set bestguess.  Avoid setting filearg[0]
    402 		 * so the file is not created automatically.
    403 		 */
    404 		if (posix)
    405 			bestguess = posix_name(names, true);
    406 		else
    407 			bestguess = best_name(names, true);
    408 	}
    409 	free(names[OLD_FILE].path);
    410 	free(names[NEW_FILE].path);
    411 	free(names[INDEX_FILE].path);
    412 	return retval;
    413 }
    414 
    415 /*
    416  * Remember where this patch ends so we know where to start up again.
    417  */
    418 static void
    419 next_intuit_at(LINENUM file_pos, LINENUM file_line)
    420 {
    421 	p_base = file_pos;
    422 	p_bline = file_line;
    423 }
    424 
    425 /*
    426  * Basically a verbose fseek() to the actual diff listing.
    427  */
    428 static void
    429 skip_to(LINENUM file_pos, LINENUM file_line)
    430 {
    431 	char	*ret;
    432 
    433 	if (p_base > file_pos)
    434 		fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
    435 	if (verbose && p_base < file_pos) {
    436 		fseek(pfp, p_base, SEEK_SET);
    437 		say("The text leading up to this was:\n--------------------------\n");
    438 		while (ftell(pfp) < file_pos) {
    439 			ret = fgets(buf, buf_len, pfp);
    440 			if (ret == NULL)
    441 				fatal("Unexpected end of file\n");
    442 			say("|%s", buf);
    443 		}
    444 		say("--------------------------\n");
    445 	} else
    446 		fseek(pfp, file_pos, SEEK_SET);
    447 	p_input_line = file_line - 1;
    448 }
    449 
    450 /* Make this a function for better debugging.  */
    451 __dead static void
    452 malformed(void)
    453 {
    454 	fatal("malformed patch at line %ld: %s", p_input_line, buf);
    455 	/* about as informative as "Syntax error" in C */
    456 }
    457 
    458 /*
    459  * True if the line has been discarded (i.e., it is a line saying
    460  *  "\ No newline at end of file".)
    461  */
    462 static bool
    463 remove_special_line(void)
    464 {
    465 	int	c;
    466 
    467 	c = fgetc(pfp);
    468 	if (c == '\\') {
    469 		do {
    470 			c = fgetc(pfp);
    471 		} while (c != EOF && c != '\n');
    472 
    473 		return true;
    474 	}
    475 	if (c != EOF)
    476 		fseek(pfp, -1L, SEEK_CUR);
    477 
    478 	return false;
    479 }
    480 
    481 /*
    482  * True if there is more of the current diff listing to process.
    483  */
    484 bool
    485 another_hunk(void)
    486 {
    487 	long	line_beginning;			/* file pos of the current line */
    488 	LINENUM	repl_beginning;			/* index of --- line */
    489 	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
    490 	LINENUM	fillsrc;			/* index of first line to copy */
    491 	LINENUM	filldst;			/* index of first missing line */
    492 	bool	ptrn_spaces_eaten;		/* ptrn was slightly misformed */
    493 	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
    494 	bool	repl_missing;			/* we are now backtracking */
    495 	long	repl_backtrack_position;	/* file pos of first repl line */
    496 	LINENUM	repl_patch_line;		/* input line number for same */
    497 	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
    498 	char	*s, *ret;
    499 	int	context = 0;
    500 
    501 	while (p_end >= 0) {
    502 		if (p_end == p_efake)
    503 			p_end = p_bfake;	/* don't free twice */
    504 		else
    505 			free(p_line[p_end]);
    506 		p_end--;
    507 	}
    508 	p_efake = -1;
    509 
    510 	p_max = hunkmax;	/* gets reduced when --- found */
    511 	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
    512 		line_beginning = ftell(pfp);
    513 		repl_beginning = 0;
    514 		fillcnt = 0;
    515 		fillsrc = 0;
    516 		filldst = 0;
    517 		ptrn_spaces_eaten = false;
    518 		repl_could_be_missing = true;
    519 		repl_missing = false;
    520 		repl_backtrack_position = 0;
    521 		repl_patch_line = 0;
    522 		ptrn_copiable = 0;
    523 
    524 		ret = pgets(buf, buf_len, pfp);
    525 		p_input_line++;
    526 		if (ret == NULL || strnNE(buf, "********", 8)) {
    527 			next_intuit_at(line_beginning, p_input_line);
    528 			return false;
    529 		}
    530 		p_context = 100;
    531 		p_hunk_beg = p_input_line + 1;
    532 		while (p_end < p_max) {
    533 			line_beginning = ftell(pfp);
    534 			ret = pgets(buf, buf_len, pfp);
    535 			p_input_line++;
    536 			if (ret == NULL) {
    537 				if (p_max - p_end < 4) {
    538 					/* assume blank lines got chopped */
    539 					strlcpy(buf, "  \n", buf_len);
    540 				} else {
    541 					if (repl_beginning && repl_could_be_missing) {
    542 						repl_missing = true;
    543 						goto hunk_done;
    544 					}
    545 					fatal("unexpected end of file in patch\n");
    546 				}
    547 			}
    548 			p_end++;
    549 			if (p_end >= hunkmax)
    550 				fatal("Internal error: hunk larger than hunk "
    551 				    "buffer size");
    552 			p_char[p_end] = *buf;
    553 			p_line[p_end] = NULL;
    554 			switch (*buf) {
    555 			case '*':
    556 				if (strnEQ(buf, "********", 8)) {
    557 					if (repl_beginning && repl_could_be_missing) {
    558 						repl_missing = true;
    559 						goto hunk_done;
    560 					} else
    561 						fatal("unexpected end of hunk "
    562 						    "at line %ld\n",
    563 						    p_input_line);
    564 				}
    565 				if (p_end != 0) {
    566 					if (repl_beginning && repl_could_be_missing) {
    567 						repl_missing = true;
    568 						goto hunk_done;
    569 					}
    570 					fatal("unexpected *** at line %ld: %s",
    571 					    p_input_line, buf);
    572 				}
    573 				context = 0;
    574 				p_line[p_end] = savestr(buf);
    575 				if (out_of_mem) {
    576 					p_end--;
    577 					return false;
    578 				}
    579 				for (s = buf; *s && !isdigit((unsigned char)*s); s++)
    580 					;
    581 				if (!*s)
    582 					malformed();
    583 				if (strnEQ(s, "0,0", 3))
    584 					memmove(s, s + 2, strlen(s + 2) + 1);
    585 				p_first = (LINENUM) atol(s);
    586 				while (isdigit((unsigned char)*s))
    587 					s++;
    588 				if (*s == ',') {
    589 					for (; *s && !isdigit((unsigned char)*s); s++)
    590 						;
    591 					if (!*s)
    592 						malformed();
    593 					p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
    594 				} else if (p_first)
    595 					p_ptrn_lines = 1;
    596 				else {
    597 					p_ptrn_lines = 0;
    598 					p_first = 1;
    599 				}
    600 
    601 				/* we need this much at least */
    602 				p_max = p_ptrn_lines + 6;
    603 				while (p_max >= hunkmax)
    604 					grow_hunkmax();
    605 				p_max = hunkmax;
    606 				break;
    607 			case '-':
    608 				if (buf[1] == '-') {
    609 					if (repl_beginning ||
    610 					    (p_end != p_ptrn_lines + 1 +
    611 					    (p_char[p_end - 1] == '\n'))) {
    612 						if (p_end == 1) {
    613 							/*
    614 							 * `old' lines were omitted;
    615 							 * set up to fill them in
    616 							 * from 'new' context lines.
    617 							 */
    618 							p_end = p_ptrn_lines + 1;
    619 							fillsrc = p_end + 1;
    620 							filldst = 1;
    621 							fillcnt = p_ptrn_lines;
    622 						} else {
    623 							if (repl_beginning) {
    624 								if (repl_could_be_missing) {
    625 									repl_missing = true;
    626 									goto hunk_done;
    627 								}
    628 								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
    629 								    p_input_line, p_hunk_beg + repl_beginning);
    630 							} else {
    631 								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
    632 								    (p_end <= p_ptrn_lines
    633 								    ? "Premature"
    634 								    : "Overdue"),
    635 								    p_input_line, p_hunk_beg);
    636 							}
    637 						}
    638 					}
    639 					repl_beginning = p_end;
    640 					repl_backtrack_position = ftell(pfp);
    641 					repl_patch_line = p_input_line;
    642 					p_line[p_end] = savestr(buf);
    643 					if (out_of_mem) {
    644 						p_end--;
    645 						return false;
    646 					}
    647 					p_char[p_end] = '=';
    648 					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
    649 						;
    650 					if (!*s)
    651 						malformed();
    652 					p_newfirst = (LINENUM) atol(s);
    653 					while (isdigit((unsigned char)*s))
    654 						s++;
    655 					if (*s == ',') {
    656 						for (; *s && !isdigit((unsigned char)*s); s++)
    657 							;
    658 						if (!*s)
    659 							malformed();
    660 						p_repl_lines = ((LINENUM) atol(s)) -
    661 						    p_newfirst + 1;
    662 					} else if (p_newfirst)
    663 						p_repl_lines = 1;
    664 					else {
    665 						p_repl_lines = 0;
    666 						p_newfirst = 1;
    667 					}
    668 					p_max = p_repl_lines + p_end;
    669 					if (p_max > MAXHUNKSIZE)
    670 						fatal("hunk too large (%ld lines) at line %ld: %s",
    671 						    p_max, p_input_line, buf);
    672 					while (p_max >= hunkmax)
    673 						grow_hunkmax();
    674 					if (p_repl_lines != ptrn_copiable &&
    675 					    (p_context != 0 || p_repl_lines != 1))
    676 						repl_could_be_missing = false;
    677 					break;
    678 				}
    679 				goto change_line;
    680 			case '+':
    681 			case '!':
    682 				repl_could_be_missing = false;
    683 		change_line:
    684 				if (buf[1] == '\n' && canonicalize)
    685 					strlcpy(buf + 1, " \n", buf_len - 1);
    686 				if (!isspace((unsigned char)buf[1]) && buf[1] != '>' &&
    687 				    buf[1] != '<' &&
    688 				    repl_beginning && repl_could_be_missing) {
    689 					repl_missing = true;
    690 					goto hunk_done;
    691 				}
    692 				if (context >= 0) {
    693 					if (context < p_context)
    694 						p_context = context;
    695 					context = -1000;
    696 				}
    697 				p_line[p_end] = savestr(buf + 2);
    698 				if (out_of_mem) {
    699 					p_end--;
    700 					return false;
    701 				}
    702 				if (p_end == p_ptrn_lines) {
    703 					if (remove_special_line()) {
    704 						int	len;
    705 
    706 						len = strlen(p_line[p_end]) - 1;
    707 						(p_line[p_end])[len] = 0;
    708 					}
    709 				}
    710 				break;
    711 			case '\t':
    712 			case '\n':	/* assume the 2 spaces got eaten */
    713 				if (repl_beginning && repl_could_be_missing &&
    714 				    (!ptrn_spaces_eaten ||
    715 				    diff_type == NEW_CONTEXT_DIFF)) {
    716 					repl_missing = true;
    717 					goto hunk_done;
    718 				}
    719 				p_line[p_end] = savestr(buf);
    720 				if (out_of_mem) {
    721 					p_end--;
    722 					return false;
    723 				}
    724 				if (p_end != p_ptrn_lines + 1) {
    725 					ptrn_spaces_eaten |= (repl_beginning != 0);
    726 					context++;
    727 					if (!repl_beginning)
    728 						ptrn_copiable++;
    729 					p_char[p_end] = ' ';
    730 				}
    731 				break;
    732 			case ' ':
    733 				if (!isspace((unsigned char)buf[1]) &&
    734 				    repl_beginning && repl_could_be_missing) {
    735 					repl_missing = true;
    736 					goto hunk_done;
    737 				}
    738 				context++;
    739 				if (!repl_beginning)
    740 					ptrn_copiable++;
    741 				p_line[p_end] = savestr(buf + 2);
    742 				if (out_of_mem) {
    743 					p_end--;
    744 					return false;
    745 				}
    746 				break;
    747 			default:
    748 				if (repl_beginning && repl_could_be_missing) {
    749 					repl_missing = true;
    750 					goto hunk_done;
    751 				}
    752 				malformed();
    753 			}
    754 			/* set up p_len for strncmp() so we don't have to */
    755 			/* assume null termination */
    756 			if (p_line[p_end])
    757 				p_len[p_end] = strlen(p_line[p_end]);
    758 			else
    759 				p_len[p_end] = 0;
    760 		}
    761 
    762 hunk_done:
    763 		if (p_end >= 0 && !repl_beginning)
    764 			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
    765 
    766 		if (repl_missing) {
    767 
    768 			/* reset state back to just after --- */
    769 			p_input_line = repl_patch_line;
    770 			for (p_end--; p_end > repl_beginning; p_end--)
    771 				free(p_line[p_end]);
    772 			fseek(pfp, repl_backtrack_position, SEEK_SET);
    773 
    774 			/* redundant 'new' context lines were omitted - set */
    775 			/* up to fill them in from the old file context */
    776 			if (!p_context && p_repl_lines == 1) {
    777 				p_repl_lines = 0;
    778 				p_max--;
    779 			}
    780 			fillsrc = 1;
    781 			filldst = repl_beginning + 1;
    782 			fillcnt = p_repl_lines;
    783 			p_end = p_max;
    784 		} else if (!p_context && fillcnt == 1) {
    785 			/* the first hunk was a null hunk with no context */
    786 			/* and we were expecting one line -- fix it up. */
    787 			while (filldst < p_end) {
    788 				p_line[filldst] = p_line[filldst + 1];
    789 				p_char[filldst] = p_char[filldst + 1];
    790 				p_len[filldst] = p_len[filldst + 1];
    791 				filldst++;
    792 			}
    793 #if 0
    794 			repl_beginning--;	/* this doesn't need to be fixed */
    795 #endif
    796 			p_end--;
    797 			p_first++;	/* do append rather than insert */
    798 			fillcnt = 0;
    799 			p_ptrn_lines = 0;
    800 		}
    801 		if (diff_type == CONTEXT_DIFF &&
    802 		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
    803 			if (verbose)
    804 				say("%s\n%s\n%s\n",
    805 				    "(Fascinating--this is really a new-style context diff but without",
    806 				    "the telltale extra asterisks on the *** line that usually indicate",
    807 				    "the new style...)");
    808 			diff_type = NEW_CONTEXT_DIFF;
    809 		}
    810 		/* if there were omitted context lines, fill them in now */
    811 		if (fillcnt) {
    812 			p_bfake = filldst;	/* remember where not to free() */
    813 			p_efake = filldst + fillcnt - 1;
    814 			while (fillcnt-- > 0) {
    815 				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
    816 					fillsrc++;
    817 				if (fillsrc > p_end)
    818 					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
    819 					    p_hunk_beg);
    820 				p_line[filldst] = p_line[fillsrc];
    821 				p_char[filldst] = p_char[fillsrc];
    822 				p_len[filldst] = p_len[fillsrc];
    823 				fillsrc++;
    824 				filldst++;
    825 			}
    826 			while (fillsrc <= p_end && fillsrc != repl_beginning &&
    827 			    p_char[fillsrc] != ' ')
    828 				fillsrc++;
    829 #ifdef DEBUGGING
    830 			if (debug & 64)
    831 				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
    832 				fillsrc, filldst, repl_beginning, p_end + 1);
    833 #endif
    834 			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
    835 				malformed();
    836 			if (filldst != p_end + 1 && filldst != repl_beginning)
    837 				malformed();
    838 		}
    839 		if (p_line[p_end] != NULL) {
    840 			if (remove_special_line()) {
    841 				p_len[p_end] -= 1;
    842 				(p_line[p_end])[p_len[p_end]] = 0;
    843 			}
    844 		}
    845 	} else if (diff_type == UNI_DIFF) {
    846 		LINENUM	fillold;	/* index of old lines */
    847 		LINENUM	fillnew;	/* index of new lines */
    848 		char	ch;
    849 
    850 		line_beginning = ftell(pfp); /* file pos of the current line */
    851 		ret = pgets(buf, buf_len, pfp);
    852 		p_input_line++;
    853 		if (ret == NULL || strnNE(buf, "@@ -", 4)) {
    854 			next_intuit_at(line_beginning, p_input_line);
    855 			return false;
    856 		}
    857 		s = buf + 4;
    858 		if (!*s)
    859 			malformed();
    860 		p_first = (LINENUM) atol(s);
    861 		while (isdigit((unsigned char)*s))
    862 			s++;
    863 		if (*s == ',') {
    864 			p_ptrn_lines = (LINENUM) atol(++s);
    865 			while (isdigit((unsigned char)*s))
    866 				s++;
    867 		} else
    868 			p_ptrn_lines = 1;
    869 		if (*s == ' ')
    870 			s++;
    871 		if (*s != '+' || !*++s)
    872 			malformed();
    873 		p_newfirst = (LINENUM) atol(s);
    874 		while (isdigit((unsigned char)*s))
    875 			s++;
    876 		if (*s == ',') {
    877 			p_repl_lines = (LINENUM) atol(++s);
    878 			while (isdigit((unsigned char)*s))
    879 				s++;
    880 		} else
    881 			p_repl_lines = 1;
    882 		if (*s == ' ')
    883 			s++;
    884 		if (*s != '@')
    885 			malformed();
    886 		if (!p_ptrn_lines)
    887 			p_first++;	/* do append rather than insert */
    888 		p_max = p_ptrn_lines + p_repl_lines + 1;
    889 		while (p_max >= hunkmax)
    890 			grow_hunkmax();
    891 		fillold = 1;
    892 		fillnew = fillold + p_ptrn_lines;
    893 		p_end = fillnew + p_repl_lines;
    894 		snprintf(buf, buf_len, "*** %ld,%ld ****\n", p_first,
    895 		    p_first + p_ptrn_lines - 1);
    896 		p_line[0] = savestr(buf);
    897 		if (out_of_mem) {
    898 			p_end = -1;
    899 			return false;
    900 		}
    901 		p_char[0] = '*';
    902 		snprintf(buf, buf_len, "--- %ld,%ld ----\n", p_newfirst,
    903 		    p_newfirst + p_repl_lines - 1);
    904 		p_line[fillnew] = savestr(buf);
    905 		if (out_of_mem) {
    906 			p_end = 0;
    907 			return false;
    908 		}
    909 		p_char[fillnew++] = '=';
    910 		p_context = 100;
    911 		context = 0;
    912 		p_hunk_beg = p_input_line + 1;
    913 		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
    914 			line_beginning = ftell(pfp);
    915 			ret = pgets(buf, buf_len, pfp);
    916 			p_input_line++;
    917 			if (ret == NULL) {
    918 				if (p_max - fillnew < 3) {
    919 					/* assume blank lines got chopped */
    920 					strlcpy(buf, " \n", buf_len);
    921 				} else {
    922 					fatal("unexpected end of file in patch\n");
    923 				}
    924 			}
    925 			if (*buf == '\t' || *buf == '\n') {
    926 				ch = ' ';	/* assume the space got eaten */
    927 				s = savestr(buf);
    928 			} else {
    929 				ch = *buf;
    930 				s = savestr(buf + 1);
    931 			}
    932 			if (out_of_mem) {
    933 				while (--fillnew > p_ptrn_lines)
    934 					free(p_line[fillnew]);
    935 				p_end = fillold - 1;
    936 				return false;
    937 			}
    938 			switch (ch) {
    939 			case '-':
    940 				if (fillold > p_ptrn_lines) {
    941 					free(s);
    942 					p_end = fillnew - 1;
    943 					malformed();
    944 				}
    945 				p_char[fillold] = ch;
    946 				p_line[fillold] = s;
    947 				p_len[fillold++] = strlen(s);
    948 				if (fillold > p_ptrn_lines) {
    949 					if (remove_special_line()) {
    950 						p_len[fillold - 1] -= 1;
    951 						s[p_len[fillold - 1]] = 0;
    952 					}
    953 				}
    954 				break;
    955 			case '=':
    956 				ch = ' ';
    957 				/* FALL THROUGH */
    958 			case ' ':
    959 				if (fillold > p_ptrn_lines) {
    960 					free(s);
    961 					while (--fillnew > p_ptrn_lines)
    962 						free(p_line[fillnew]);
    963 					p_end = fillold - 1;
    964 					malformed();
    965 				}
    966 				context++;
    967 				p_char[fillold] = ch;
    968 				p_line[fillold] = s;
    969 				p_len[fillold++] = strlen(s);
    970 				s = savestr(s);
    971 				if (out_of_mem) {
    972 					while (--fillnew > p_ptrn_lines)
    973 						free(p_line[fillnew]);
    974 					p_end = fillold - 1;
    975 					return false;
    976 				}
    977 				if (fillold > p_ptrn_lines) {
    978 					if (remove_special_line()) {
    979 						p_len[fillold - 1] -= 1;
    980 						s[p_len[fillold - 1]] = 0;
    981 					}
    982 				}
    983 				/* FALL THROUGH */
    984 			case '+':
    985 				if (fillnew > p_end) {
    986 					free(s);
    987 					while (--fillnew > p_ptrn_lines)
    988 						free(p_line[fillnew]);
    989 					p_end = fillold - 1;
    990 					malformed();
    991 				}
    992 				p_char[fillnew] = ch;
    993 				p_line[fillnew] = s;
    994 				p_len[fillnew++] = strlen(s);
    995 				if (fillold > p_ptrn_lines) {
    996 					if (remove_special_line()) {
    997 						p_len[fillnew - 1] -= 1;
    998 						s[p_len[fillnew - 1]] = 0;
    999 					}
   1000 				}
   1001 				break;
   1002 			default:
   1003 				p_end = fillnew;
   1004 				malformed();
   1005 			}
   1006 			if (ch != ' ' && context > 0) {
   1007 				if (context < p_context)
   1008 					p_context = context;
   1009 				context = -1000;
   1010 			}
   1011 		}		/* while */
   1012 	} else {		/* normal diff--fake it up */
   1013 		char	hunk_type;
   1014 		int	i;
   1015 		LINENUM	min, max;
   1016 
   1017 		line_beginning = ftell(pfp);
   1018 		p_context = 0;
   1019 		ret = pgets(buf, buf_len, pfp);
   1020 		p_input_line++;
   1021 		if (ret == NULL || !isdigit((unsigned char)*buf)) {
   1022 			next_intuit_at(line_beginning, p_input_line);
   1023 			return false;
   1024 		}
   1025 		p_first = (LINENUM) atol(buf);
   1026 		for (s = buf; isdigit((unsigned char)*s); s++)
   1027 			;
   1028 		if (*s == ',') {
   1029 			p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
   1030 			while (isdigit((unsigned char)*s))
   1031 				s++;
   1032 		} else
   1033 			p_ptrn_lines = (*s != 'a');
   1034 		hunk_type = *s;
   1035 		if (hunk_type == 'a')
   1036 			p_first++;	/* do append rather than insert */
   1037 		min = (LINENUM) atol(++s);
   1038 		for (; isdigit((unsigned char)*s); s++)
   1039 			;
   1040 		if (*s == ',')
   1041 			max = (LINENUM) atol(++s);
   1042 		else
   1043 			max = min;
   1044 		if (hunk_type == 'd')
   1045 			min++;
   1046 		p_end = p_ptrn_lines + 1 + max - min + 1;
   1047 		if (p_end > MAXHUNKSIZE)
   1048 			fatal("hunk too large (%ld lines) at line %ld: %s",
   1049 			    p_end, p_input_line, buf);
   1050 		while (p_end >= hunkmax)
   1051 			grow_hunkmax();
   1052 		p_newfirst = min;
   1053 		p_repl_lines = max - min + 1;
   1054 		snprintf(buf, buf_len, "*** %ld,%ld\n", p_first,
   1055 		    p_first + p_ptrn_lines - 1);
   1056 		p_line[0] = savestr(buf);
   1057 		if (out_of_mem) {
   1058 			p_end = -1;
   1059 			return false;
   1060 		}
   1061 		p_char[0] = '*';
   1062 		for (i = 1; i <= p_ptrn_lines; i++) {
   1063 			ret = pgets(buf, buf_len, pfp);
   1064 			p_input_line++;
   1065 			if (ret == NULL)
   1066 				fatal("unexpected end of file in patch at line %ld\n",
   1067 				    p_input_line);
   1068 			if (*buf != '<')
   1069 				fatal("< expected at line %ld of patch\n",
   1070 				    p_input_line);
   1071 			p_line[i] = savestr(buf + 2);
   1072 			if (out_of_mem) {
   1073 				p_end = i - 1;
   1074 				return false;
   1075 			}
   1076 			p_len[i] = strlen(p_line[i]);
   1077 			p_char[i] = '-';
   1078 		}
   1079 
   1080 		if (remove_special_line()) {
   1081 			p_len[i - 1] -= 1;
   1082 			(p_line[i - 1])[p_len[i - 1]] = 0;
   1083 		}
   1084 		if (hunk_type == 'c') {
   1085 			ret = pgets(buf, buf_len, pfp);
   1086 			p_input_line++;
   1087 			if (ret == NULL)
   1088 				fatal("unexpected end of file in patch at line %ld\n",
   1089 				    p_input_line);
   1090 			if (*buf != '-')
   1091 				fatal("--- expected at line %ld of patch\n",
   1092 				    p_input_line);
   1093 		}
   1094 		snprintf(buf, buf_len, "--- %ld,%ld\n", min, max);
   1095 		p_line[i] = savestr(buf);
   1096 		if (out_of_mem) {
   1097 			p_end = i - 1;
   1098 			return false;
   1099 		}
   1100 		p_char[i] = '=';
   1101 		for (i++; i <= p_end; i++) {
   1102 			ret = pgets(buf, buf_len, pfp);
   1103 			p_input_line++;
   1104 			if (ret == NULL)
   1105 				fatal("unexpected end of file in patch at line %ld\n",
   1106 				    p_input_line);
   1107 			if (*buf != '>')
   1108 				fatal("> expected at line %ld of patch\n",
   1109 				    p_input_line);
   1110 			p_line[i] = savestr(buf + 2);
   1111 			if (out_of_mem) {
   1112 				p_end = i - 1;
   1113 				return false;
   1114 			}
   1115 			p_len[i] = strlen(p_line[i]);
   1116 			p_char[i] = '+';
   1117 		}
   1118 
   1119 		if (remove_special_line()) {
   1120 			p_len[i - 1] -= 1;
   1121 			(p_line[i - 1])[p_len[i - 1]] = 0;
   1122 		}
   1123 	}
   1124 	if (reverse)		/* backwards patch? */
   1125 		if (!pch_swap())
   1126 			say("Not enough memory to swap next hunk!\n");
   1127 #ifdef DEBUGGING
   1128 	if (debug & 2) {
   1129 		int	i;
   1130 		char	special;
   1131 
   1132 		for (i = 0; i <= p_end; i++) {
   1133 			if (i == p_ptrn_lines)
   1134 				special = '^';
   1135 			else
   1136 				special = ' ';
   1137 			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
   1138 			    special, p_line[i]);
   1139 			fflush(stderr);
   1140 		}
   1141 	}
   1142 #endif
   1143 	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
   1144 		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
   1145 	return true;
   1146 }
   1147 
   1148 /*
   1149  * Input a line from the patch file, worrying about indentation.
   1150  */
   1151 static char *
   1152 pgets(char *bf, int sz, FILE *fp)
   1153 {
   1154 	char	*s, *ret = fgets(bf, sz, fp);
   1155 	int	indent = 0;
   1156 
   1157 	if (p_indent && ret != NULL) {
   1158 		for (s = buf;
   1159 		    indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
   1160 		    s++) {
   1161 			if (*s == '\t')
   1162 				indent += 8 - (indent % 7);
   1163 			else
   1164 				indent++;
   1165 		}
   1166 		if (buf != s && strlcpy(buf, s, buf_len) >= buf_len)
   1167 			fatal("buffer too small in pgets()\n");
   1168 	}
   1169 	return ret;
   1170 }
   1171 
   1172 /*
   1173  * Reverse the old and new portions of the current hunk.
   1174  */
   1175 bool
   1176 pch_swap(void)
   1177 {
   1178 	char	**tp_line;	/* the text of the hunk */
   1179 	short	*tp_len;	/* length of each line */
   1180 	char	*tp_char;	/* +, -, and ! */
   1181 	LINENUM	i;
   1182 	LINENUM	n;
   1183 	bool	blankline = false;
   1184 	char	*s;
   1185 
   1186 	i = p_first;
   1187 	p_first = p_newfirst;
   1188 	p_newfirst = i;
   1189 
   1190 	/* make a scratch copy */
   1191 
   1192 	tp_line = p_line;
   1193 	tp_len = p_len;
   1194 	tp_char = p_char;
   1195 	p_line = NULL;	/* force set_hunkmax to allocate again */
   1196 	p_len = NULL;
   1197 	p_char = NULL;
   1198 	set_hunkmax();
   1199 	if (p_line == NULL || p_len == NULL || p_char == NULL) {
   1200 
   1201 		free(p_line);
   1202 		p_line = tp_line;
   1203 		free(p_len);
   1204 		p_len = tp_len;
   1205 		free(p_char);
   1206 		p_char = tp_char;
   1207 		return false;	/* not enough memory to swap hunk! */
   1208 	}
   1209 	/* now turn the new into the old */
   1210 
   1211 	i = p_ptrn_lines + 1;
   1212 	if (tp_char[i] == '\n') {	/* account for possible blank line */
   1213 		blankline = true;
   1214 		i++;
   1215 	}
   1216 	if (p_efake >= 0) {	/* fix non-freeable ptr range */
   1217 		if (p_efake <= i)
   1218 			n = p_end - i + 1;
   1219 		else
   1220 			n = -i;
   1221 		p_efake += n;
   1222 		p_bfake += n;
   1223 	}
   1224 	for (n = 0; i <= p_end; i++, n++) {
   1225 		p_line[n] = tp_line[i];
   1226 		p_char[n] = tp_char[i];
   1227 		if (p_char[n] == '+')
   1228 			p_char[n] = '-';
   1229 		p_len[n] = tp_len[i];
   1230 	}
   1231 	if (blankline) {
   1232 		i = p_ptrn_lines + 1;
   1233 		p_line[n] = tp_line[i];
   1234 		p_char[n] = tp_char[i];
   1235 		p_len[n] = tp_len[i];
   1236 		n++;
   1237 	}
   1238 	if (p_char[0] != '=')
   1239 		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
   1240 		    p_input_line, p_char[0]);
   1241 	p_char[0] = '*';
   1242 	for (s = p_line[0]; *s; s++)
   1243 		if (*s == '-')
   1244 			*s = '*';
   1245 
   1246 	/* now turn the old into the new */
   1247 
   1248 	if (p_char[0] != '*')
   1249 		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
   1250 		    p_input_line, p_char[0]);
   1251 	tp_char[0] = '=';
   1252 	for (s = tp_line[0]; *s; s++)
   1253 		if (*s == '*')
   1254 			*s = '-';
   1255 	for (i = 0; n <= p_end; i++, n++) {
   1256 		p_line[n] = tp_line[i];
   1257 		p_char[n] = tp_char[i];
   1258 		if (p_char[n] == '-')
   1259 			p_char[n] = '+';
   1260 		p_len[n] = tp_len[i];
   1261 	}
   1262 
   1263 	if (i != p_ptrn_lines + 1)
   1264 		fatal("Malformed patch at line %ld: expected %ld lines, "
   1265 		    "got %ld\n",
   1266 		    p_input_line, p_ptrn_lines + 1, i);
   1267 
   1268 	i = p_ptrn_lines;
   1269 	p_ptrn_lines = p_repl_lines;
   1270 	p_repl_lines = i;
   1271 
   1272 	free(tp_line);
   1273 	free(tp_len);
   1274 	free(tp_char);
   1275 
   1276 	return true;
   1277 }
   1278 
   1279 /*
   1280  * Return the specified line position in the old file of the old context.
   1281  */
   1282 LINENUM
   1283 pch_first(void)
   1284 {
   1285 	return p_first;
   1286 }
   1287 
   1288 /*
   1289  * Return the number of lines of old context.
   1290  */
   1291 LINENUM
   1292 pch_ptrn_lines(void)
   1293 {
   1294 	return p_ptrn_lines;
   1295 }
   1296 
   1297 /*
   1298  * Return the probable line position in the new file of the first line.
   1299  */
   1300 LINENUM
   1301 pch_newfirst(void)
   1302 {
   1303 	return p_newfirst;
   1304 }
   1305 
   1306 /*
   1307  * Return the number of lines in the replacement text including context.
   1308  */
   1309 LINENUM
   1310 pch_repl_lines(void)
   1311 {
   1312 	return p_repl_lines;
   1313 }
   1314 
   1315 /*
   1316  * Return the number of lines in the whole hunk.
   1317  */
   1318 LINENUM
   1319 pch_end(void)
   1320 {
   1321 	return p_end;
   1322 }
   1323 
   1324 /*
   1325  * Return the number of context lines before the first changed line.
   1326  */
   1327 LINENUM
   1328 pch_context(void)
   1329 {
   1330 	return p_context;
   1331 }
   1332 
   1333 /*
   1334  * Return the length of a particular patch line.
   1335  */
   1336 short
   1337 pch_line_len(LINENUM line)
   1338 {
   1339 	return p_len[line];
   1340 }
   1341 
   1342 /*
   1343  * Return the control character (+, -, *, !, etc) for a patch line.
   1344  */
   1345 char
   1346 pch_char(LINENUM line)
   1347 {
   1348 	return p_char[line];
   1349 }
   1350 
   1351 /*
   1352  * Return a pointer to a particular patch line.
   1353  */
   1354 char *
   1355 pfetch(LINENUM line)
   1356 {
   1357 	return p_line[line];
   1358 }
   1359 
   1360 /*
   1361  * Return where in the patch file this hunk began, for error messages.
   1362  */
   1363 LINENUM
   1364 pch_hunk_beg(void)
   1365 {
   1366 	return p_hunk_beg;
   1367 }
   1368 
   1369 /*
   1370  * Apply an ed script by feeding ed itself.
   1371  */
   1372 void
   1373 do_ed_script(void)
   1374 {
   1375 	char	*t;
   1376 	long	beginning_of_this_line;
   1377 	FILE	*pipefp = NULL;
   1378 
   1379 	if (!skip_rest_of_patch) {
   1380 		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
   1381 			unlink(TMPOUTNAME);
   1382 			fatal("can't create temp file %s", TMPOUTNAME);
   1383 		}
   1384 		snprintf(buf, buf_len, "%s%s%s", _PATH_ED,
   1385 		    verbose ? " " : " -s ", TMPOUTNAME);
   1386 		pipefp = popen(buf, "w");
   1387 	}
   1388 	for (;;) {
   1389 		beginning_of_this_line = ftell(pfp);
   1390 		if (pgets(buf, buf_len, pfp) == NULL) {
   1391 			next_intuit_at(beginning_of_this_line, p_input_line);
   1392 			break;
   1393 		}
   1394 		p_input_line++;
   1395 		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
   1396 			;
   1397 		/* POSIX defines allowed commands as {a,c,d,i,s} */
   1398 		if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' ||
   1399 		    *t == 'd' || *t == 'i' || *t == 's')) {
   1400 			if (pipefp != NULL)
   1401 				fputs(buf, pipefp);
   1402 			if (*t != 'd') {
   1403 				while (pgets(buf, buf_len, pfp) != NULL) {
   1404 					p_input_line++;
   1405 					if (pipefp != NULL)
   1406 						fputs(buf, pipefp);
   1407 					if (strEQ(buf, ".\n"))
   1408 						break;
   1409 				}
   1410 			}
   1411 		} else {
   1412 			next_intuit_at(beginning_of_this_line, p_input_line);
   1413 			break;
   1414 		}
   1415 	}
   1416 	if (pipefp == NULL)
   1417 		return;
   1418 	fprintf(pipefp, "w\n");
   1419 	fprintf(pipefp, "q\n");
   1420 	fflush(pipefp);
   1421 	pclose(pipefp);
   1422 	ignore_signals();
   1423 	if (!check_only) {
   1424 		if (move_file(TMPOUTNAME, outname) < 0) {
   1425 			toutkeep = true;
   1426 			chmod(TMPOUTNAME, filemode);
   1427 		} else
   1428 			chmod(outname, filemode);
   1429 	}
   1430 	set_signals(1);
   1431 }
   1432 
   1433 /*
   1434  * Choose the name of the file to be patched based on POSIX rules.
   1435  * NOTE: the POSIX rules are amazingly stupid and we only follow them
   1436  *       if the user specified --posix or set POSIXLY_CORRECT.
   1437  */
   1438 static char *
   1439 posix_name(const struct file_name *names, bool assume_exists)
   1440 {
   1441 	char *path = NULL;
   1442 	int i;
   1443 
   1444 	/*
   1445 	 * POSIX states that the filename will be chosen from one
   1446 	 * of the old, new and index names (in that order) if
   1447 	 * the file exists relative to CWD after -p stripping.
   1448 	 */
   1449 	for (i = 0; i < MAX_FILE; i++) {
   1450 		if (names[i].path != NULL && names[i].exists) {
   1451 			path = names[i].path;
   1452 			break;
   1453 		}
   1454 	}
   1455 	if (path == NULL && !assume_exists) {
   1456 		/*
   1457 		 * No files found, look for something we can checkout from
   1458 		 * RCS/SCCS dirs.  Same order as above.
   1459 		 */
   1460 		for (i = 0; i < MAX_FILE; i++) {
   1461 			if (names[i].path != NULL &&
   1462 			    (path = checked_in(names[i].path)) != NULL)
   1463 				break;
   1464 		}
   1465 		/*
   1466 		 * Still no match?  Check to see if the diff could be creating
   1467 		 * a new file.
   1468 		 */
   1469 		if (path == NULL && ok_to_create_file &&
   1470 		    names[NEW_FILE].path != NULL)
   1471 			path = names[NEW_FILE].path;
   1472 	}
   1473 
   1474 	return path ? savestr(path) : NULL;
   1475 }
   1476 
   1477 /*
   1478  * Choose the name of the file to be patched based the "best" one
   1479  * available.
   1480  */
   1481 static char *
   1482 best_name(const struct file_name *names, bool assume_exists)
   1483 {
   1484 	size_t min_components, min_baselen, min_len, tmp;
   1485 	char *best = NULL;
   1486 	int i;
   1487 
   1488 	/*
   1489 	 * The "best" name is the one with the fewest number of path
   1490 	 * components, the shortest basename length, and the shortest
   1491 	 * overall length (in that order).  We only use the Index: file
   1492 	 * if neither of the old or new files could be intuited from
   1493 	 * the diff header.
   1494 	 */
   1495 	min_components = min_baselen = min_len = SIZE_MAX;
   1496 	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
   1497 		if (names[i].path == NULL ||
   1498 		    (!names[i].exists && !assume_exists))
   1499 			continue;
   1500 		if ((tmp = num_components(names[i].path)) > min_components)
   1501 			continue;
   1502 		min_components = tmp;
   1503 		if ((tmp = strlen(basename(names[i].path))) > min_baselen)
   1504 			continue;
   1505 		min_baselen = tmp;
   1506 		if ((tmp = strlen(names[i].path)) > min_len)
   1507 			continue;
   1508 		min_len = tmp;
   1509 		best = names[i].path;
   1510 	}
   1511 	if (best == NULL) {
   1512 		/*
   1513 		 * No files found, look for something we can checkout from
   1514 		 * RCS/SCCS dirs.  Logic is identical to that above...
   1515 		 */
   1516 		min_components = min_baselen = min_len = SIZE_MAX;
   1517 		for (i = INDEX_FILE; i >= OLD_FILE; i--) {
   1518 			if (names[i].path == NULL ||
   1519 			    checked_in(names[i].path) == NULL)
   1520 				continue;
   1521 			if ((tmp = num_components(names[i].path)) > min_components)
   1522 				continue;
   1523 			min_components = tmp;
   1524 			if ((tmp = strlen(basename(names[i].path))) > min_baselen)
   1525 				continue;
   1526 			min_baselen = tmp;
   1527 			if ((tmp = strlen(names[i].path)) > min_len)
   1528 				continue;
   1529 			min_len = tmp;
   1530 			best = names[i].path;
   1531 		}
   1532 		/*
   1533 		 * Still no match?  Check to see if the diff could be creating
   1534 		 * a new file.
   1535 		 */
   1536 		if (best == NULL && ok_to_create_file &&
   1537 		    names[NEW_FILE].path != NULL)
   1538 			best = names[NEW_FILE].path;
   1539 	}
   1540 
   1541 	return best ? savestr(best) : NULL;
   1542 }
   1543 
   1544 static size_t
   1545 num_components(const char *path)
   1546 {
   1547 	size_t n;
   1548 	const char *cp;
   1549 
   1550 	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
   1551 		while (*cp == '/')
   1552 			cp++;		/* skip consecutive slashes */
   1553 	}
   1554 	return n;
   1555 }
   1556