coverity appeasement
[minix.git] / commands / patch / pch.c
blobd8d354d127a5facb6530e3948188067c511fcf20
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.23 2008/09/19 18:33:34 joerg Exp $
5 */
7 /*
8 * patch - a program to apply diffs to original files
9 *
10 * Copyright 1986, Larry Wall
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.
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.
29 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
30 * behaviour
33 #include <sys/cdefs.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
38 #include <ctype.h>
39 #include <libgen.h>
40 #include <limits.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
46 #include "common.h"
47 #include "util.h"
48 #include "pch.h"
49 #include "pathnames.h"
51 /* Patch (diff listing) abstract type. */
53 static long p_filesize; /* size of the patch file */
54 static LINENUM p_first; /* 1st line number */
55 static LINENUM p_newfirst; /* 1st line number of replacement */
56 static LINENUM p_ptrn_lines; /* # lines in pattern */
57 static LINENUM p_repl_lines; /* # lines in replacement text */
58 static LINENUM p_end = -1; /* last line in hunk */
59 static LINENUM p_max; /* max allowed value of p_end */
60 static LINENUM p_context = 3; /* # of context lines */
61 static LINENUM p_input_line = 0; /* current line # from patch file */
62 static char **p_line = NULL;/* the text of the hunk */
63 static short *p_len = NULL; /* length of each line */
64 static char *p_char = NULL; /* +, -, and ! */
65 static int hunkmax = INITHUNKMAX; /* size of above arrays to begin with */
66 static int p_indent; /* indent to patch */
67 static LINENUM p_base; /* where to intuit this time */
68 static LINENUM p_bline; /* line # of p_base */
69 static LINENUM p_start; /* where intuit found a patch */
70 static LINENUM p_sline; /* and the line number for it */
71 static LINENUM p_hunk_beg; /* line number of current hunk */
72 static LINENUM p_efake = -1; /* end of faked up lines--don't free */
73 static LINENUM p_bfake = -1; /* beg of faked up lines */
74 static FILE *pfp = NULL; /* patch file pointer */
75 static char *bestguess = NULL; /* guess at correct filename */
77 static void grow_hunkmax(void);
78 static int intuit_diff_type(void);
79 static void next_intuit_at(LINENUM, LINENUM);
80 static void skip_to(LINENUM, LINENUM);
81 static char *pgets(char *, int, FILE *);
82 static char *best_name(const struct file_name *, bool);
83 static char *posix_name(const struct file_name *, bool);
84 static size_t num_components(const char *);
87 * Prepare to look for the next patch in the patch file.
89 void
90 re_patch(void)
92 p_first = 0;
93 p_newfirst = 0;
94 p_ptrn_lines = 0;
95 p_repl_lines = 0;
96 p_end = (LINENUM) - 1;
97 p_max = 0;
98 p_indent = 0;
102 * Open the patch file at the beginning of time.
104 void
105 open_patch_file(const char *filename)
107 struct stat filestat;
109 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
110 pfp = fopen(TMPPATNAME, "w");
111 if (pfp == NULL)
112 pfatal("can't create %s", TMPPATNAME);
113 while (fgets(buf, buf_len, stdin) != NULL)
114 fputs(buf, pfp);
115 if (ferror(pfp) || fclose(pfp))
116 pfatal("can't write %s", TMPPATNAME);
117 filename = TMPPATNAME;
119 pfp = fopen(filename, "r");
120 if (pfp == NULL)
121 pfatal("patch file %s not found", filename);
122 fstat(fileno(pfp), &filestat);
123 p_filesize = filestat.st_size;
124 next_intuit_at(0L, 1L); /* start at the beginning */
125 set_hunkmax();
129 * Make sure our dynamically realloced tables are malloced to begin with.
131 void
132 set_hunkmax(void)
134 if (p_line == NULL)
135 p_line = calloc((size_t) hunkmax, sizeof(char *));
136 if (p_len == NULL)
137 p_len = calloc((size_t) hunkmax, sizeof(short));
138 if (p_char == NULL)
139 p_char = calloc((size_t) hunkmax, sizeof(char));
143 * Enlarge the arrays containing the current hunk of patch.
145 static void
146 grow_hunkmax(void)
148 int new_hunkmax;
149 char **new_p_line;
150 short *new_p_len;
151 char *new_p_char;
153 new_hunkmax = hunkmax * 2;
155 if (p_line == NULL || p_len == NULL || p_char == NULL)
156 fatal("Internal memory allocation error\n");
158 new_p_line = realloc(p_line, new_hunkmax * sizeof(char *));
159 if (new_p_line == NULL)
160 free(p_line);
162 new_p_len = realloc(p_len, new_hunkmax * sizeof(short));
163 if (new_p_len == NULL)
164 free(p_len);
166 new_p_char = realloc(p_char, new_hunkmax * sizeof(char));
167 if (new_p_char == NULL)
168 free(p_char);
170 p_char = new_p_char;
171 p_len = new_p_len;
172 p_line = new_p_line;
174 if (p_line != NULL && p_len != NULL && p_char != NULL) {
175 hunkmax = new_hunkmax;
176 return;
179 if (!using_plan_a)
180 fatal("out of memory\n");
181 out_of_mem = true; /* whatever is null will be allocated again */
182 /* from within plan_a(), of all places */
185 /* True if the remainder of the patch file contains a diff of some sort. */
187 bool
188 there_is_another_patch(void)
190 bool exists = false;
192 if (p_base != 0L && p_base >= p_filesize) {
193 if (verbose)
194 say("done\n");
195 return false;
197 if (verbose)
198 say("Hmm...");
199 diff_type = intuit_diff_type();
200 if (!diff_type) {
201 if (p_base != 0L) {
202 if (verbose)
203 say(" Ignoring the trailing garbage.\ndone\n");
204 } else
205 say(" I can't seem to find a patch in there anywhere.\n");
206 return false;
208 if (verbose)
209 say(" %sooks like %s to me...\n",
210 (p_base == 0L ? "L" : "The next patch l"),
211 diff_type == UNI_DIFF ? "a unified diff" :
212 diff_type == CONTEXT_DIFF ? "a context diff" :
213 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
214 diff_type == NORMAL_DIFF ? "a normal diff" :
215 "an ed script");
216 if (p_indent && verbose)
217 say("(Patch is indented %d space%s.)\n", p_indent,
218 p_indent == 1 ? "" : "s");
219 skip_to(p_start, p_sline);
220 while (filearg[0] == NULL) {
221 if (force || batch) {
222 say("No file to patch. Skipping...\n");
223 filearg[0] = savestr(bestguess);
224 skip_rest_of_patch = true;
225 return true;
227 ask("File to patch: ");
228 if (*buf != '\n') {
229 free(bestguess);
230 bestguess = savestr(buf);
231 filearg[0] = fetchname(buf, &exists, 0);
233 if (!exists) {
234 ask("No file found--skip this patch? [n] ");
235 if (*buf != 'y')
236 continue;
237 if (verbose)
238 say("Skipping patch...\n");
239 free(filearg[0]);
240 filearg[0] = fetchname(bestguess, &exists, 0);
241 skip_rest_of_patch = true;
242 return true;
245 return true;
248 /* Determine what kind of diff is in the remaining part of the patch file. */
250 static int
251 intuit_diff_type(void)
253 long this_line = 0, previous_line;
254 long first_command_line = -1;
255 LINENUM fcl_line = -1;
256 bool last_line_was_command = false, this_is_a_command = false;
257 bool stars_last_line = false, stars_this_line = false;
258 char *s, *t;
259 int indent, retval;
260 struct file_name names[MAX_FILE];
262 memset(names, 0, sizeof(names));
263 ok_to_create_file = false;
264 fseek(pfp, p_base, SEEK_SET);
265 p_input_line = p_bline - 1;
266 for (;;) {
267 previous_line = this_line;
268 last_line_was_command = this_is_a_command;
269 stars_last_line = stars_this_line;
270 this_line = ftell(pfp);
271 indent = 0;
272 p_input_line++;
273 if (fgets(buf, buf_len, pfp) == NULL) {
274 if (first_command_line >= 0L) {
275 /* nothing but deletes!? */
276 p_start = first_command_line;
277 p_sline = fcl_line;
278 retval = ED_DIFF;
279 goto scan_exit;
280 } else {
281 p_start = this_line;
282 p_sline = p_input_line;
283 retval = 0;
284 goto scan_exit;
287 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
288 if (*s == '\t')
289 indent += 8 - (indent % 8);
290 else
291 indent++;
293 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
295 this_is_a_command = (isdigit((unsigned char)*s) &&
296 (*t == 'd' || *t == 'c' || *t == 'a'));
297 if (first_command_line < 0L && this_is_a_command) {
298 first_command_line = this_line;
299 fcl_line = p_input_line;
300 p_indent = indent; /* assume this for now */
302 if (!stars_last_line && strnEQ(s, "*** ", 4))
303 names[OLD_FILE].path = fetchname(s + 4,
304 &names[OLD_FILE].exists, strippath);
305 else if (strnEQ(s, "--- ", 4))
306 names[NEW_FILE].path = fetchname(s + 4,
307 &names[NEW_FILE].exists, strippath);
308 else if (strnEQ(s, "+++ ", 4))
309 /* pretend it is the old name */
310 names[OLD_FILE].path = fetchname(s + 4,
311 &names[OLD_FILE].exists, strippath);
312 else if (strnEQ(s, "Index:", 6))
313 names[INDEX_FILE].path = fetchname(s + 6,
314 &names[INDEX_FILE].exists, strippath);
315 else if (strnEQ(s, "Prereq:", 7)) {
316 for (t = s + 7; isspace((unsigned char)*t); t++)
318 revision = savestr(t);
319 for (t = revision; *t && !isspace((unsigned char)*t); t++)
321 *t = '\0';
322 if (*revision == '\0') {
323 free(revision);
324 revision = NULL;
327 if ((!diff_type || diff_type == ED_DIFF) &&
328 first_command_line >= 0L &&
329 strEQ(s, ".\n")) {
330 p_indent = indent;
331 p_start = first_command_line;
332 p_sline = fcl_line;
333 retval = ED_DIFF;
334 goto scan_exit;
336 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
337 if (strnEQ(s + 4, "0,0", 3))
338 ok_to_create_file = true;
339 p_indent = indent;
340 p_start = this_line;
341 p_sline = p_input_line;
342 retval = UNI_DIFF;
343 goto scan_exit;
345 stars_this_line = strnEQ(s, "********", 8);
346 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
347 strnEQ(s, "*** ", 4)) {
348 if (atol(s + 4) == 0)
349 ok_to_create_file = true;
351 * If this is a new context diff the character just
352 * before the newline is a '*'.
354 while (*s != '\n')
355 s++;
356 p_indent = indent;
357 p_start = previous_line;
358 p_sline = p_input_line - 1;
359 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
360 goto scan_exit;
362 if ((!diff_type || diff_type == NORMAL_DIFF) &&
363 last_line_was_command &&
364 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
365 p_start = previous_line;
366 p_sline = p_input_line - 1;
367 p_indent = indent;
368 retval = NORMAL_DIFF;
369 goto scan_exit;
372 scan_exit:
373 if (retval == UNI_DIFF) {
374 /* unswap old and new */
375 struct file_name tmp = names[OLD_FILE];
376 names[OLD_FILE] = names[NEW_FILE];
377 names[NEW_FILE] = tmp;
379 if (filearg[0] == NULL) {
380 if (posix)
381 filearg[0] = posix_name(names, ok_to_create_file);
382 else {
383 /* Ignore the Index: name for context diffs, like GNU */
384 if (names[OLD_FILE].path != NULL ||
385 names[NEW_FILE].path != NULL) {
386 free(names[INDEX_FILE].path);
387 names[INDEX_FILE].path = NULL;
389 filearg[0] = best_name(names, ok_to_create_file);
393 free(bestguess);
394 bestguess = NULL;
395 if (filearg[0] != NULL)
396 bestguess = savestr(filearg[0]);
397 else if (!ok_to_create_file) {
399 * We don't want to create a new file but we need a
400 * filename to set bestguess. Avoid setting filearg[0]
401 * so the file is not created automatically.
403 if (posix)
404 bestguess = posix_name(names, true);
405 else
406 bestguess = best_name(names, true);
408 free(names[OLD_FILE].path);
409 free(names[NEW_FILE].path);
410 free(names[INDEX_FILE].path);
411 return retval;
415 * Remember where this patch ends so we know where to start up again.
417 static void
418 next_intuit_at(LINENUM file_pos, LINENUM file_line)
420 p_base = file_pos;
421 p_bline = file_line;
425 * Basically a verbose fseek() to the actual diff listing.
427 static void
428 skip_to(LINENUM file_pos, LINENUM file_line)
430 char *ret;
432 if (p_base > file_pos)
433 fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
434 if (verbose && p_base < file_pos) {
435 fseek(pfp, p_base, SEEK_SET);
436 say("The text leading up to this was:\n--------------------------\n");
437 while (ftell(pfp) < file_pos) {
438 ret = fgets(buf, buf_len, pfp);
439 if (ret == NULL)
440 fatal("Unexpected end of file\n");
441 say("|%s", buf);
443 say("--------------------------\n");
444 } else
445 fseek(pfp, file_pos, SEEK_SET);
446 p_input_line = file_line - 1;
449 /* Make this a function for better debugging. */
450 static void
451 malformed(void)
453 fatal("malformed patch at line %ld: %s", p_input_line, buf);
454 /* about as informative as "Syntax error" in C */
458 * True if the line has been discarded (i.e. it is a line saying
459 * "\ No newline at end of file".)
461 static bool
462 remove_special_line(void)
464 int c;
466 c = fgetc(pfp);
467 if (c == '\\') {
468 do {
469 c = fgetc(pfp);
470 } while (c != EOF && c != '\n');
472 return true;
474 if (c != EOF)
475 fseek(pfp, -1L, SEEK_CUR);
477 return false;
481 * True if there is more of the current diff listing to process.
483 bool
484 another_hunk(void)
486 long line_beginning; /* file pos of the current line */
487 LINENUM repl_beginning; /* index of --- line */
488 LINENUM fillcnt; /* #lines of missing ptrn or repl */
489 LINENUM fillsrc; /* index of first line to copy */
490 LINENUM filldst; /* index of first missing line */
491 bool ptrn_spaces_eaten; /* ptrn was slightly misformed */
492 bool repl_could_be_missing; /* no + or ! lines in this hunk */
493 bool repl_missing; /* we are now backtracking */
494 long repl_backtrack_position; /* file pos of first repl line */
495 LINENUM repl_patch_line; /* input line number for same */
496 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
497 char *s, *ret;
498 int context = 0;
500 while (p_end >= 0) {
501 if (p_end == p_efake)
502 p_end = p_bfake; /* don't free twice */
503 else
504 free(p_line[p_end]);
505 p_end--;
507 p_efake = -1;
509 p_max = hunkmax; /* gets reduced when --- found */
510 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
511 line_beginning = ftell(pfp);
512 repl_beginning = 0;
513 fillcnt = 0;
514 fillsrc = 0;
515 filldst = 0;
516 ptrn_spaces_eaten = false;
517 repl_could_be_missing = true;
518 repl_missing = false;
519 repl_backtrack_position = 0;
520 repl_patch_line = 0;
521 ptrn_copiable = 0;
523 ret = pgets(buf, buf_len, pfp);
524 p_input_line++;
525 if (ret == NULL || strnNE(buf, "********", 8)) {
526 next_intuit_at(line_beginning, p_input_line);
527 return false;
529 p_context = 100;
530 p_hunk_beg = p_input_line + 1;
531 while (p_end < p_max) {
532 line_beginning = ftell(pfp);
533 ret = pgets(buf, buf_len, pfp);
534 p_input_line++;
535 if (ret == NULL) {
536 if (p_max - p_end < 4) {
537 /* assume blank lines got chopped */
538 strlcpy(buf, " \n", buf_len);
539 } else {
540 if (repl_beginning && repl_could_be_missing) {
541 repl_missing = true;
542 goto hunk_done;
544 fatal("unexpected end of file in patch\n");
547 p_end++;
548 if (p_end >= hunkmax)
549 fatal("Internal error: hunk larger than hunk "
550 "buffer size");
551 p_char[p_end] = *buf;
552 p_line[p_end] = NULL;
553 switch (*buf) {
554 case '*':
555 if (strnEQ(buf, "********", 8)) {
556 if (repl_beginning && repl_could_be_missing) {
557 repl_missing = true;
558 goto hunk_done;
559 } else
560 fatal("unexpected end of hunk "
561 "at line %ld\n",
562 p_input_line);
564 if (p_end != 0) {
565 if (repl_beginning && repl_could_be_missing) {
566 repl_missing = true;
567 goto hunk_done;
569 fatal("unexpected *** at line %ld: %s",
570 p_input_line, buf);
572 context = 0;
573 p_line[p_end] = savestr(buf);
574 if (out_of_mem) {
575 p_end--;
576 return false;
578 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
580 if (!*s)
581 malformed();
582 if (strnEQ(s, "0,0", 3))
583 memmove(s, s + 2, strlen(s + 2) + 1);
584 p_first = (LINENUM) atol(s);
585 while (isdigit((unsigned char)*s))
586 s++;
587 if (*s == ',') {
588 for (; *s && !isdigit((unsigned char)*s); s++)
590 if (!*s)
591 malformed();
592 p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
593 } else if (p_first)
594 p_ptrn_lines = 1;
595 else {
596 p_ptrn_lines = 0;
597 p_first = 1;
600 /* we need this much at least */
601 p_max = p_ptrn_lines + 6;
602 while (p_max >= hunkmax)
603 grow_hunkmax();
604 p_max = hunkmax;
605 break;
606 case '-':
607 if (buf[1] == '-') {
608 if (repl_beginning ||
609 (p_end != p_ptrn_lines + 1 +
610 (p_char[p_end - 1] == '\n'))) {
611 if (p_end == 1) {
613 * `old' lines were omitted;
614 * set up to fill them in
615 * from 'new' context lines.
617 p_end = p_ptrn_lines + 1;
618 fillsrc = p_end + 1;
619 filldst = 1;
620 fillcnt = p_ptrn_lines;
621 } else {
622 if (repl_beginning) {
623 if (repl_could_be_missing) {
624 repl_missing = true;
625 goto hunk_done;
627 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
628 p_input_line, p_hunk_beg + repl_beginning);
629 } else {
630 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
631 (p_end <= p_ptrn_lines
632 ? "Premature"
633 : "Overdue"),
634 p_input_line, p_hunk_beg);
638 repl_beginning = p_end;
639 repl_backtrack_position = ftell(pfp);
640 repl_patch_line = p_input_line;
641 p_line[p_end] = savestr(buf);
642 if (out_of_mem) {
643 p_end--;
644 return false;
646 p_char[p_end] = '=';
647 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
649 if (!*s)
650 malformed();
651 p_newfirst = (LINENUM) atol(s);
652 while (isdigit((unsigned char)*s))
653 s++;
654 if (*s == ',') {
655 for (; *s && !isdigit((unsigned char)*s); s++)
657 if (!*s)
658 malformed();
659 p_repl_lines = ((LINENUM) atol(s)) -
660 p_newfirst + 1;
661 } else if (p_newfirst)
662 p_repl_lines = 1;
663 else {
664 p_repl_lines = 0;
665 p_newfirst = 1;
667 p_max = p_repl_lines + p_end;
668 if (p_max > MAXHUNKSIZE)
669 fatal("hunk too large (%ld lines) at line %ld: %s",
670 p_max, p_input_line, buf);
671 while (p_max >= hunkmax)
672 grow_hunkmax();
673 if (p_repl_lines != ptrn_copiable &&
674 (p_context != 0 || p_repl_lines != 1))
675 repl_could_be_missing = false;
676 break;
678 goto change_line;
679 case '+':
680 case '!':
681 repl_could_be_missing = false;
682 change_line:
683 if (buf[1] == '\n' && canonicalize)
684 strlcpy(buf + 1, " \n", buf_len - 1);
685 if (!isspace((unsigned char)buf[1]) && buf[1] != '>' &&
686 buf[1] != '<' &&
687 repl_beginning && repl_could_be_missing) {
688 repl_missing = true;
689 goto hunk_done;
691 if (context >= 0) {
692 if (context < p_context)
693 p_context = context;
694 context = -1000;
696 p_line[p_end] = savestr(buf + 2);
697 if (out_of_mem) {
698 p_end--;
699 return false;
701 if (p_end == p_ptrn_lines) {
702 if (remove_special_line()) {
703 int len;
705 len = strlen(p_line[p_end]) - 1;
706 (p_line[p_end])[len] = 0;
709 break;
710 case '\t':
711 case '\n': /* assume the 2 spaces got eaten */
712 if (repl_beginning && repl_could_be_missing &&
713 (!ptrn_spaces_eaten ||
714 diff_type == NEW_CONTEXT_DIFF)) {
715 repl_missing = true;
716 goto hunk_done;
718 p_line[p_end] = savestr(buf);
719 if (out_of_mem) {
720 p_end--;
721 return false;
723 if (p_end != p_ptrn_lines + 1) {
724 ptrn_spaces_eaten |= (repl_beginning != 0);
725 context++;
726 if (!repl_beginning)
727 ptrn_copiable++;
728 p_char[p_end] = ' ';
730 break;
731 case ' ':
732 if (!isspace((unsigned char)buf[1]) &&
733 repl_beginning && repl_could_be_missing) {
734 repl_missing = true;
735 goto hunk_done;
737 context++;
738 if (!repl_beginning)
739 ptrn_copiable++;
740 p_line[p_end] = savestr(buf + 2);
741 if (out_of_mem) {
742 p_end--;
743 return false;
745 break;
746 default:
747 if (repl_beginning && repl_could_be_missing) {
748 repl_missing = true;
749 goto hunk_done;
751 malformed();
753 /* set up p_len for strncmp() so we don't have to */
754 /* assume null termination */
755 if (p_line[p_end])
756 p_len[p_end] = strlen(p_line[p_end]);
757 else
758 p_len[p_end] = 0;
761 hunk_done:
762 if (p_end >= 0 && !repl_beginning)
763 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
765 if (repl_missing) {
767 /* reset state back to just after --- */
768 p_input_line = repl_patch_line;
769 for (p_end--; p_end > repl_beginning; p_end--)
770 free(p_line[p_end]);
771 fseek(pfp, repl_backtrack_position, SEEK_SET);
773 /* redundant 'new' context lines were omitted - set */
774 /* up to fill them in from the old file context */
775 if (!p_context && p_repl_lines == 1) {
776 p_repl_lines = 0;
777 p_max--;
779 fillsrc = 1;
780 filldst = repl_beginning + 1;
781 fillcnt = p_repl_lines;
782 p_end = p_max;
783 } else if (!p_context && fillcnt == 1) {
784 /* the first hunk was a null hunk with no context */
785 /* and we were expecting one line -- fix it up. */
786 while (filldst < p_end) {
787 p_line[filldst] = p_line[filldst + 1];
788 p_char[filldst] = p_char[filldst + 1];
789 p_len[filldst] = p_len[filldst + 1];
790 filldst++;
792 #if 0
793 repl_beginning--; /* this doesn't need to be fixed */
794 #endif
795 p_end--;
796 p_first++; /* do append rather than insert */
797 fillcnt = 0;
798 p_ptrn_lines = 0;
800 if (diff_type == CONTEXT_DIFF &&
801 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
802 if (verbose)
803 say("%s\n%s\n%s\n",
804 "(Fascinating--this is really a new-style context diff but without",
805 "the telltale extra asterisks on the *** line that usually indicate",
806 "the new style...)");
807 diff_type = NEW_CONTEXT_DIFF;
809 /* if there were omitted context lines, fill them in now */
810 if (fillcnt) {
811 p_bfake = filldst; /* remember where not to free() */
812 p_efake = filldst + fillcnt - 1;
813 while (fillcnt-- > 0) {
814 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
815 fillsrc++;
816 if (fillsrc > p_end)
817 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
818 p_hunk_beg);
819 p_line[filldst] = p_line[fillsrc];
820 p_char[filldst] = p_char[fillsrc];
821 p_len[filldst] = p_len[fillsrc];
822 fillsrc++;
823 filldst++;
825 while (fillsrc <= p_end && fillsrc != repl_beginning &&
826 p_char[fillsrc] != ' ')
827 fillsrc++;
828 #ifdef DEBUGGING
829 if (debug & 64)
830 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
831 fillsrc, filldst, repl_beginning, p_end + 1);
832 #endif
833 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
834 malformed();
835 if (filldst != p_end + 1 && filldst != repl_beginning)
836 malformed();
838 if (p_line[p_end] != NULL) {
839 if (remove_special_line()) {
840 p_len[p_end] -= 1;
841 (p_line[p_end])[p_len[p_end]] = 0;
844 } else if (diff_type == UNI_DIFF) {
845 LINENUM fillold; /* index of old lines */
846 LINENUM fillnew; /* index of new lines */
847 char ch;
849 line_beginning = ftell(pfp); /* file pos of the current line */
850 ret = pgets(buf, buf_len, pfp);
851 p_input_line++;
852 if (ret == NULL || strnNE(buf, "@@ -", 4)) {
853 next_intuit_at(line_beginning, p_input_line);
854 return false;
856 s = buf + 4;
857 if (!*s)
858 malformed();
859 p_first = (LINENUM) atol(s);
860 while (isdigit((unsigned char)*s))
861 s++;
862 if (*s == ',') {
863 p_ptrn_lines = (LINENUM) atol(++s);
864 while (isdigit((unsigned char)*s))
865 s++;
866 } else
867 p_ptrn_lines = 1;
868 if (*s == ' ')
869 s++;
870 if (*s != '+' || !*++s)
871 malformed();
872 p_newfirst = (LINENUM) atol(s);
873 while (isdigit((unsigned char)*s))
874 s++;
875 if (*s == ',') {
876 p_repl_lines = (LINENUM) atol(++s);
877 while (isdigit((unsigned char)*s))
878 s++;
879 } else
880 p_repl_lines = 1;
881 if (*s == ' ')
882 s++;
883 if (*s != '@')
884 malformed();
885 if (!p_ptrn_lines)
886 p_first++; /* do append rather than insert */
887 p_max = p_ptrn_lines + p_repl_lines + 1;
888 while (p_max >= hunkmax)
889 grow_hunkmax();
890 fillold = 1;
891 fillnew = fillold + p_ptrn_lines;
892 p_end = fillnew + p_repl_lines;
893 snprintf(buf, buf_len, "*** %ld,%ld ****\n", p_first,
894 p_first + p_ptrn_lines - 1);
895 p_line[0] = savestr(buf);
896 if (out_of_mem) {
897 p_end = -1;
898 return false;
900 p_char[0] = '*';
901 snprintf(buf, buf_len, "--- %ld,%ld ----\n", p_newfirst,
902 p_newfirst + p_repl_lines - 1);
903 p_line[fillnew] = savestr(buf);
904 if (out_of_mem) {
905 p_end = 0;
906 return false;
908 p_char[fillnew++] = '=';
909 p_context = 100;
910 context = 0;
911 p_hunk_beg = p_input_line + 1;
912 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
913 line_beginning = ftell(pfp);
914 ret = pgets(buf, buf_len, pfp);
915 p_input_line++;
916 if (ret == NULL) {
917 if (p_max - fillnew < 3) {
918 /* assume blank lines got chopped */
919 strlcpy(buf, " \n", buf_len);
920 } else {
921 fatal("unexpected end of file in patch\n");
924 if (*buf == '\t' || *buf == '\n') {
925 ch = ' '; /* assume the space got eaten */
926 s = savestr(buf);
927 } else {
928 ch = *buf;
929 s = savestr(buf + 1);
931 if (out_of_mem) {
932 while (--fillnew > p_ptrn_lines)
933 free(p_line[fillnew]);
934 p_end = fillold - 1;
935 return false;
937 switch (ch) {
938 case '-':
939 if (fillold > p_ptrn_lines) {
940 free(s);
941 p_end = fillnew - 1;
942 malformed();
944 p_char[fillold] = ch;
945 p_line[fillold] = s;
946 p_len[fillold++] = strlen(s);
947 if (fillold > p_ptrn_lines) {
948 if (remove_special_line()) {
949 p_len[fillold - 1] -= 1;
950 s[p_len[fillold - 1]] = 0;
953 break;
954 case '=':
955 ch = ' ';
956 /* FALL THROUGH */
957 case ' ':
958 if (fillold > p_ptrn_lines) {
959 free(s);
960 while (--fillnew > p_ptrn_lines)
961 free(p_line[fillnew]);
962 p_end = fillold - 1;
963 malformed();
965 context++;
966 p_char[fillold] = ch;
967 p_line[fillold] = s;
968 p_len[fillold++] = strlen(s);
969 s = savestr(s);
970 if (out_of_mem) {
971 while (--fillnew > p_ptrn_lines)
972 free(p_line[fillnew]);
973 p_end = fillold - 1;
974 return false;
976 if (fillold > p_ptrn_lines) {
977 if (remove_special_line()) {
978 p_len[fillold - 1] -= 1;
979 s[p_len[fillold - 1]] = 0;
982 /* FALL THROUGH */
983 case '+':
984 if (fillnew > p_end) {
985 free(s);
986 while (--fillnew > p_ptrn_lines)
987 free(p_line[fillnew]);
988 p_end = fillold - 1;
989 malformed();
991 p_char[fillnew] = ch;
992 p_line[fillnew] = s;
993 p_len[fillnew++] = strlen(s);
994 if (fillold > p_ptrn_lines) {
995 if (remove_special_line()) {
996 p_len[fillnew - 1] -= 1;
997 s[p_len[fillnew - 1]] = 0;
1000 break;
1001 default:
1002 p_end = fillnew;
1003 malformed();
1005 if (ch != ' ' && context > 0) {
1006 if (context < p_context)
1007 p_context = context;
1008 context = -1000;
1010 } /* while */
1011 } else { /* normal diff--fake it up */
1012 char hunk_type;
1013 int i;
1014 LINENUM min, max;
1016 line_beginning = ftell(pfp);
1017 p_context = 0;
1018 ret = pgets(buf, buf_len, pfp);
1019 p_input_line++;
1020 if (ret == NULL || !isdigit((unsigned char)*buf)) {
1021 next_intuit_at(line_beginning, p_input_line);
1022 return false;
1024 p_first = (LINENUM) atol(buf);
1025 for (s = buf; isdigit((unsigned char)*s); s++)
1027 if (*s == ',') {
1028 p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
1029 while (isdigit((unsigned char)*s))
1030 s++;
1031 } else
1032 p_ptrn_lines = (*s != 'a');
1033 hunk_type = *s;
1034 if (hunk_type == 'a')
1035 p_first++; /* do append rather than insert */
1036 min = (LINENUM) atol(++s);
1037 for (; isdigit((unsigned char)*s); s++)
1039 if (*s == ',')
1040 max = (LINENUM) atol(++s);
1041 else
1042 max = min;
1043 if (hunk_type == 'd')
1044 min++;
1045 p_end = p_ptrn_lines + 1 + max - min + 1;
1046 if (p_end > MAXHUNKSIZE)
1047 fatal("hunk too large (%ld lines) at line %ld: %s",
1048 p_end, p_input_line, buf);
1049 while (p_end >= hunkmax)
1050 grow_hunkmax();
1051 p_newfirst = min;
1052 p_repl_lines = max - min + 1;
1053 snprintf(buf, buf_len, "*** %ld,%ld\n", p_first,
1054 p_first + p_ptrn_lines - 1);
1055 p_line[0] = savestr(buf);
1056 if (out_of_mem) {
1057 p_end = -1;
1058 return false;
1060 p_char[0] = '*';
1061 for (i = 1; i <= p_ptrn_lines; i++) {
1062 ret = pgets(buf, buf_len, pfp);
1063 p_input_line++;
1064 if (ret == NULL)
1065 fatal("unexpected end of file in patch at line %ld\n",
1066 p_input_line);
1067 if (*buf != '<')
1068 fatal("< expected at line %ld of patch\n",
1069 p_input_line);
1070 p_line[i] = savestr(buf + 2);
1071 if (out_of_mem) {
1072 p_end = i - 1;
1073 return false;
1075 p_len[i] = strlen(p_line[i]);
1076 p_char[i] = '-';
1079 if (remove_special_line()) {
1080 p_len[i - 1] -= 1;
1081 (p_line[i - 1])[p_len[i - 1]] = 0;
1083 if (hunk_type == 'c') {
1084 ret = pgets(buf, buf_len, pfp);
1085 p_input_line++;
1086 if (ret == NULL)
1087 fatal("unexpected end of file in patch at line %ld\n",
1088 p_input_line);
1089 if (*buf != '-')
1090 fatal("--- expected at line %ld of patch\n",
1091 p_input_line);
1093 snprintf(buf, buf_len, "--- %ld,%ld\n", min, max);
1094 p_line[i] = savestr(buf);
1095 if (out_of_mem) {
1096 p_end = i - 1;
1097 return false;
1099 p_char[i] = '=';
1100 for (i++; i <= p_end; i++) {
1101 ret = pgets(buf, buf_len, pfp);
1102 p_input_line++;
1103 if (ret == NULL)
1104 fatal("unexpected end of file in patch at line %ld\n",
1105 p_input_line);
1106 if (*buf != '>')
1107 fatal("> expected at line %ld of patch\n",
1108 p_input_line);
1109 p_line[i] = savestr(buf + 2);
1110 if (out_of_mem) {
1111 p_end = i - 1;
1112 return false;
1114 p_len[i] = strlen(p_line[i]);
1115 p_char[i] = '+';
1118 if (remove_special_line()) {
1119 p_len[i - 1] -= 1;
1120 (p_line[i - 1])[p_len[i - 1]] = 0;
1123 if (reverse) /* backwards patch? */
1124 if (!pch_swap())
1125 say("Not enough memory to swap next hunk!\n");
1126 #ifdef DEBUGGING
1127 if (debug & 2) {
1128 int i;
1129 char special;
1131 for (i = 0; i <= p_end; i++) {
1132 if (i == p_ptrn_lines)
1133 special = '^';
1134 else
1135 special = ' ';
1136 fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1137 special, p_line[i]);
1138 fflush(stderr);
1141 #endif
1142 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1143 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1144 return true;
1148 * Input a line from the patch file, worrying about indentation.
1150 static char *
1151 pgets(char *bf, int sz, FILE *fp)
1153 char *s, *ret = fgets(bf, sz, fp);
1154 int indent = 0;
1156 if (p_indent && ret != NULL) {
1157 for (s = buf;
1158 indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
1159 s++) {
1160 if (*s == '\t')
1161 indent += 8 - (indent % 7);
1162 else
1163 indent++;
1165 if (buf != s && strlcpy(buf, s, buf_len) >= buf_len)
1166 fatal("buffer too small in pgets()\n");
1168 return ret;
1172 * Reverse the old and new portions of the current hunk.
1174 bool
1175 pch_swap(void)
1177 char **tp_line; /* the text of the hunk */
1178 short *tp_len; /* length of each line */
1179 char *tp_char; /* +, -, and ! */
1180 LINENUM i;
1181 LINENUM n;
1182 bool blankline = false;
1183 char *s;
1185 i = p_first;
1186 p_first = p_newfirst;
1187 p_newfirst = i;
1189 /* make a scratch copy */
1191 tp_line = p_line;
1192 tp_len = p_len;
1193 tp_char = p_char;
1194 p_line = NULL; /* force set_hunkmax to allocate again */
1195 p_len = NULL;
1196 p_char = NULL;
1197 set_hunkmax();
1198 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1200 free(p_line);
1201 p_line = tp_line;
1202 free(p_len);
1203 p_len = tp_len;
1204 free(p_char);
1205 p_char = tp_char;
1206 return false; /* not enough memory to swap hunk! */
1208 /* now turn the new into the old */
1210 i = p_ptrn_lines + 1;
1211 if (tp_char[i] == '\n') { /* account for possible blank line */
1212 blankline = true;
1213 i++;
1215 if (p_efake >= 0) { /* fix non-freeable ptr range */
1216 if (p_efake <= i)
1217 n = p_end - i + 1;
1218 else
1219 n = -i;
1220 p_efake += n;
1221 p_bfake += n;
1223 for (n = 0; i <= p_end; i++, n++) {
1224 p_line[n] = tp_line[i];
1225 p_char[n] = tp_char[i];
1226 if (p_char[n] == '+')
1227 p_char[n] = '-';
1228 p_len[n] = tp_len[i];
1230 if (blankline) {
1231 i = p_ptrn_lines + 1;
1232 p_line[n] = tp_line[i];
1233 p_char[n] = tp_char[i];
1234 p_len[n] = tp_len[i];
1235 n++;
1237 if (p_char[0] != '=')
1238 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1239 p_input_line, p_char[0]);
1240 p_char[0] = '*';
1241 for (s = p_line[0]; *s; s++)
1242 if (*s == '-')
1243 *s = '*';
1245 /* now turn the old into the new */
1247 if (p_char[0] != '*')
1248 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1249 p_input_line, p_char[0]);
1250 tp_char[0] = '=';
1251 for (s = tp_line[0]; *s; s++)
1252 if (*s == '*')
1253 *s = '-';
1254 for (i = 0; n <= p_end; i++, n++) {
1255 p_line[n] = tp_line[i];
1256 p_char[n] = tp_char[i];
1257 if (p_char[n] == '-')
1258 p_char[n] = '+';
1259 p_len[n] = tp_len[i];
1262 if (i != p_ptrn_lines + 1)
1263 fatal("Malformed patch at line %ld: expected %ld lines, "
1264 "got %ld\n",
1265 p_input_line, p_ptrn_lines + 1, i);
1267 i = p_ptrn_lines;
1268 p_ptrn_lines = p_repl_lines;
1269 p_repl_lines = i;
1271 free(tp_line);
1272 free(tp_len);
1273 free(tp_char);
1275 return true;
1279 * Return the specified line position in the old file of the old context.
1281 LINENUM
1282 pch_first(void)
1284 return p_first;
1288 * Return the number of lines of old context.
1290 LINENUM
1291 pch_ptrn_lines(void)
1293 return p_ptrn_lines;
1297 * Return the probable line position in the new file of the first line.
1299 LINENUM
1300 pch_newfirst(void)
1302 return p_newfirst;
1306 * Return the number of lines in the replacement text including context.
1308 LINENUM
1309 pch_repl_lines(void)
1311 return p_repl_lines;
1315 * Return the number of lines in the whole hunk.
1317 LINENUM
1318 pch_end(void)
1320 return p_end;
1324 * Return the number of context lines before the first changed line.
1326 LINENUM
1327 pch_context(void)
1329 return p_context;
1333 * Return the length of a particular patch line.
1335 short
1336 pch_line_len(LINENUM line)
1338 return p_len[line];
1342 * Return the control character (+, -, *, !, etc) for a patch line.
1344 char
1345 pch_char(LINENUM line)
1347 return p_char[line];
1351 * Return a pointer to a particular patch line.
1353 char *
1354 pfetch(LINENUM line)
1356 return p_line[line];
1360 * Return where in the patch file this hunk began, for error messages.
1362 LINENUM
1363 pch_hunk_beg(void)
1365 return p_hunk_beg;
1369 * Apply an ed script by feeding ed itself.
1371 void
1372 do_ed_script(void)
1374 char *t;
1375 long beginning_of_this_line;
1376 FILE *pipefp = NULL;
1378 if (!skip_rest_of_patch) {
1379 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1380 unlink(TMPOUTNAME);
1381 fatal("can't create temp file %s", TMPOUTNAME);
1383 snprintf(buf, buf_len, "%s%s%s", _PATH_ED,
1384 verbose ? " " : " -s ", TMPOUTNAME);
1385 pipefp = popen(buf, "w");
1387 for (;;) {
1388 beginning_of_this_line = ftell(pfp);
1389 if (pgets(buf, buf_len, pfp) == NULL) {
1390 next_intuit_at(beginning_of_this_line, p_input_line);
1391 break;
1393 p_input_line++;
1394 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1396 /* POSIX defines allowed commands as {a,c,d,i,s} */
1397 if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' ||
1398 *t == 'd' || *t == 'i' || *t == 's')) {
1399 if (pipefp != NULL)
1400 fputs(buf, pipefp);
1401 if (*t != 'd') {
1402 while (pgets(buf, buf_len, pfp) != NULL) {
1403 p_input_line++;
1404 if (pipefp != NULL)
1405 fputs(buf, pipefp);
1406 if (strEQ(buf, ".\n"))
1407 break;
1410 } else {
1411 next_intuit_at(beginning_of_this_line, p_input_line);
1412 break;
1415 if (pipefp == NULL)
1416 return;
1417 fprintf(pipefp, "w\n");
1418 fprintf(pipefp, "q\n");
1419 fflush(pipefp);
1420 pclose(pipefp);
1421 ignore_signals();
1422 if (!check_only) {
1423 if (move_file(TMPOUTNAME, outname) < 0) {
1424 toutkeep = true;
1425 chmod(TMPOUTNAME, filemode);
1426 } else
1427 chmod(outname, filemode);
1429 set_signals(1);
1433 * Choose the name of the file to be patched based on POSIX rules.
1434 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1435 * if the user specified --posix or set POSIXLY_CORRECT.
1437 static char *
1438 posix_name(const struct file_name *names, bool assume_exists)
1440 char *path = NULL;
1441 int i;
1444 * POSIX states that the filename will be chosen from one
1445 * of the old, new and index names (in that order) if
1446 * the file exists relative to CWD after -p stripping.
1448 for (i = 0; i < MAX_FILE; i++) {
1449 if (names[i].path != NULL && names[i].exists) {
1450 path = names[i].path;
1451 break;
1454 if (path == NULL && !assume_exists) {
1456 * No files found, look for something we can checkout from
1457 * RCS/SCCS dirs. Same order as above.
1459 for (i = 0; i < MAX_FILE; i++) {
1460 if (names[i].path != NULL &&
1461 (path = checked_in(names[i].path)) != NULL)
1462 break;
1465 * Still no match? Check to see if the diff could be creating
1466 * a new file.
1468 if (path == NULL && ok_to_create_file &&
1469 names[NEW_FILE].path != NULL)
1470 path = names[NEW_FILE].path;
1473 return path ? savestr(path) : NULL;
1477 * Choose the name of the file to be patched based the "best" one
1478 * available.
1480 static char *
1481 best_name(const struct file_name *names, bool assume_exists)
1483 size_t min_components, min_baselen, min_len, tmp;
1484 char *best = NULL;
1485 int i;
1488 * The "best" name is the one with the fewest number of path
1489 * components, the shortest basename length, and the shortest
1490 * overall length (in that order). We only use the Index: file
1491 * if neither of the old or new files could be intuited from
1492 * the diff header.
1494 min_components = min_baselen = min_len = SIZE_MAX;
1495 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1496 if (names[i].path == NULL ||
1497 (!names[i].exists && !assume_exists))
1498 continue;
1499 if ((tmp = num_components(names[i].path)) > min_components)
1500 continue;
1501 min_components = tmp;
1502 if ((tmp = strlen(basename(names[i].path))) > min_baselen)
1503 continue;
1504 min_baselen = tmp;
1505 if ((tmp = strlen(names[i].path)) > min_len)
1506 continue;
1507 min_len = tmp;
1508 best = names[i].path;
1510 if (best == NULL) {
1512 * No files found, look for something we can checkout from
1513 * RCS/SCCS dirs. Logic is identical to that above...
1515 min_components = min_baselen = min_len = SIZE_MAX;
1516 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1517 if (names[i].path == NULL ||
1518 checked_in(names[i].path) == NULL)
1519 continue;
1520 if ((tmp = num_components(names[i].path)) > min_components)
1521 continue;
1522 min_components = tmp;
1523 if ((tmp = strlen(basename(names[i].path))) > min_baselen)
1524 continue;
1525 min_baselen = tmp;
1526 if ((tmp = strlen(names[i].path)) > min_len)
1527 continue;
1528 min_len = tmp;
1529 best = names[i].path;
1532 * Still no match? Check to see if the diff could be creating
1533 * a new file.
1535 if (best == NULL && ok_to_create_file &&
1536 names[NEW_FILE].path != NULL)
1537 best = names[NEW_FILE].path;
1540 return best ? savestr(best) : NULL;
1543 static size_t
1544 num_components(const char *path)
1546 size_t n;
1547 const char *cp;
1549 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1550 while (*cp == '/')
1551 cp++; /* skip consecutive slashes */
1553 return n;