xref: /freebsd/usr.bin/diff3/diff3.c (revision a8b8feced998c8c74f9a572f069bcb689cabd09d)
1 /*	$OpenBSD: diff3prog.c,v 1.11 2009/10/27 23:59:37 deraadt Exp $	*/
2 
3 /*
4  * Copyright (C) Caldera International Inc.  2001-2002.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code and documentation must retain the above
11  *    copyright notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed or owned by Caldera
18  *	International, Inc.
19  * 4. Neither the name of Caldera International, Inc. nor the names of other
20  *    contributors may be used to endorse or promote products derived from
21  *    this software without specific prior written permission.
22  *
23  * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
24  * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR ANY DIRECT,
28  * INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
32  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
33  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36 /*-
37  * Copyright (c) 1991, 1993
38  *	The Regents of the University of California.  All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  */
64 
65 #include <sys/capsicum.h>
66 #include <sys/procdesc.h>
67 #include <sys/types.h>
68 #include <sys/wait.h>
69 
70 #include <capsicum_helpers.h>
71 #include <ctype.h>
72 #include <err.h>
73 #include <getopt.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <limits.h>
77 #include <inttypes.h>
78 #include <string.h>
79 #include <unistd.h>
80 
81 /*
82  * "from" is first in range of changed lines; "to" is last+1
83  * from=to=line after point of insertion for added lines.
84  */
85 struct range {
86 	int from;
87 	int to;
88 };
89 
90 struct diff {
91 #define DIFF_TYPE1 1
92 #define DIFF_TYPE2 2
93 #define DIFF_TYPE3 3
94 	int type;
95 #if DEBUG
96 	char *line;
97 #endif	/* DEBUG */
98 
99 	/* Ranges as lines */
100 	struct range old;
101 	struct range new;
102 };
103 
104 #define EFLAG_NONE 	0
105 #define EFLAG_OVERLAP 	1
106 #define EFLAG_NOOVERLAP	2
107 #define EFLAG_UNMERGED	3
108 
109 static size_t szchanges;
110 
111 static struct diff *d13;
112 static struct diff *d23;
113 /*
114  * "de" is used to gather editing scripts.  These are later spewed out in
115  * reverse order.  Its first element must be all zero, the "old" and "new"
116  * components of "de" contain line positions. Array overlap indicates which
117  * sections in "de" correspond to lines that are different in all three files.
118  */
119 static struct diff *de;
120 static char *overlap;
121 static int  *de_delta;	/* file1-file3 line number delta per edit */
122 static int  overlapcnt;
123 static FILE *fp[3];
124 static int cline[3];		/* # of the last-read line in each file (0-2) */
125 /*
126  * The latest known correspondence between line numbers of the 3 files
127  * is stored in last[1-3];
128  */
129 static int last[4];
130 static int Aflag, eflag, iflag, mflag, Tflag;
131 static int oflag;		/* indicates whether to mark overlaps (-E or -X) */
132 static int strip_cr;
133 static char *f1mark, *f2mark, *f3mark;
134 static const char *oldmark = "<<<<<<<";
135 static const char *orgmark = "|||||||";
136 static const char *newmark = ">>>>>>>";
137 static const char *divider = "=======";
138 
139 static bool duplicate(struct range *, struct range *);
140 static int edit(struct diff *, bool, int, int);
141 static char *getchange(FILE *);
142 static char *get_line(FILE *, size_t *);
143 static int readin(int fd, struct diff **);
144 static int skip(int, int, const char *);
145 static void change(int, struct range *, bool);
146 static void keep(int, struct range *);
147 static void merge(int, int);
148 static void prange(struct range *, bool);
149 static void repos(int);
150 static void separate(const char *);
151 static void edscript(int) __dead2;
152 static void Ascript(int) __dead2;
153 static void mergescript(int) __dead2;
154 static void increase(void);
155 static void usage(void);
156 static void printrange(FILE *, struct range *);
157 
158 static const char diff3_version[] = "FreeBSD diff3 20240925";
159 
160 enum {
161 	DIFFPROG_OPT,
162 	STRIPCR_OPT,
163 	HELP_OPT,
164 	VERSION_OPT
165 };
166 
167 #define DIFF_PATH "/usr/bin/diff"
168 
169 #define OPTIONS "3aAeEiL:mTxX"
170 static struct option longopts[] = {
171 	{ "ed",			no_argument,		NULL,	'e' },
172 	{ "show-overlap",	no_argument,		NULL,	'E' },
173 	{ "overlap-only",	no_argument,		NULL,	'x' },
174 	{ "initial-tab",	no_argument,		NULL,	'T' },
175 	{ "text",		no_argument,		NULL,	'a' },
176 	{ "strip-trailing-cr",	no_argument,		NULL,	STRIPCR_OPT },
177 	{ "show-all",		no_argument,		NULL,	'A' },
178 	{ "easy-only",		no_argument,		NULL,	'3' },
179 	{ "merge",		no_argument,		NULL,	'm' },
180 	{ "label",		required_argument,	NULL,	'L' },
181 	{ "diff-program",	required_argument,	NULL,	DIFFPROG_OPT },
182 	{ "help",		no_argument,		NULL,	HELP_OPT},
183 	{ "version",		no_argument,		NULL,	VERSION_OPT}
184 };
185 
186 static void
187 usage(void)
188 {
189 	fprintf(stderr, "usage: diff3 [-3aAeEimTxX] [-L label1] [-L label2] "
190 	    "[-L label3] file1 file2 file3\n");
191 }
192 
193 static int
194 strtoi(char *str, char **end)
195 {
196 	intmax_t num;
197 
198 	errno = 0;
199 	num = strtoimax(str, end, 10);
200 	if ((end != NULL && *end == str) ||
201 	    num < 0 || num > INT_MAX ||
202 	    errno == EINVAL || errno == ERANGE)
203 		err(1, "error in diff output");
204 	return (int)num;
205 }
206 
207 /*
208  * Read diff hunks into the array pointed to by *dd.
209  *
210  * The output from `diff foo bar` consists of a series of hunks describing
211  * an addition (lines in bar not present in foo), change (lines in bar
212  * different from lines in foo), or deletion (lines in foo not present in
213  * bar).  Each record starts with a line of the form:
214  *
215  * a[,b]xc[,d]
216  *
217  * where a, b, c, and d are nonnegative integers (b and d are printed only
218  * if they differ from a and c, respectively), and x is either 'a' for an
219  * addition, 'c' for a change, or 'd' for a deletion.  This is then
220  * followed by a series of lines (which we ignore) giving the added,
221  * changed, or deleted text.
222  *
223  * For an addition, a == b is the last line in 'foo' before the addition,
224  * while c through d is the range of lines in 'bar' to be added to 'foo'.
225  *
226  * For a change, a through b is the range of lines in 'foo' to be replaced
227  * and c through d is the range of lines in 'bar' to replace them with.
228  *
229  * For a deletion, a through b is the range of lines in 'foo' to remove
230  * and c == d is the line in 'bar' which corresponds to the last line
231  * before the deletion.
232  *
233  * The observant reader will have noticed that x is not really needed and
234  * that we can fully describe any hunk using only a, b, c, and d:
235  *
236  * - an addition replaces a zero-length range in one file with a
237  *   non-zero-length range from the other
238  *
239  * - a change replaces a non-zero-length range in one file with a
240  *   non-zero-length range from the other
241  *
242  * - a deletion replaces a non-zero-length range in one file with a
243  *   zero-length range from the other
244  */
245 static int
246 readin(int fd, struct diff **dd)
247 {
248 	int a, b, c, d;
249 	int i;
250 	char kind, *p;
251 	FILE *f;
252 
253 	f = fdopen(fd, "r");
254 	if (f == NULL)
255 		err(2, "fdopen");
256 	for (i = 0; (p = getchange(f)) != NULL; i++) {
257 		if ((size_t)i >= szchanges - 1)
258 			increase();
259 #if DEBUG
260 		(*dd)[i].line = strdup(p);
261 #endif	/* DEBUG */
262 
263 		a = b = strtoi(p, &p);
264 		if (*p == ',')
265 			b = strtoi(p + 1, &p);
266 		kind = *p++;
267 		c = d = strtoi(p, &p);
268 		if (*p == ',')
269 			d = strtoi(p + 1, &p);
270 		if (*p != '\n')
271 			errx(1, "error in diff output");
272 		if (kind == 'a')
273 			a++;
274 		else if (kind == 'c')
275 			/* nothing */ ;
276 		else if (kind == 'd')
277 			c++;
278 		else
279 			errx(1, "error in diff output");
280 		b++;
281 		d++;
282 		if (b < a || d < c)
283 			errx(1, "error in diff output");
284 		(*dd)[i].old.from = a;
285 		(*dd)[i].old.to = b;
286 		(*dd)[i].new.from = c;
287 		(*dd)[i].new.to = d;
288 		if (i > 0) {
289 			if ((*dd)[i].old.from < (*dd)[i - 1].old.to ||
290 			    (*dd)[i].new.from < (*dd)[i - 1].new.to)
291 				errx(1, "diff output out of order");
292 		}
293 	}
294 	if (i > 0) {
295 		(*dd)[i].old.from = (*dd)[i].old.to = (*dd)[i - 1].old.to;
296 		(*dd)[i].new.from = (*dd)[i].new.to = (*dd)[i - 1].new.to;
297 	}
298 	fclose(f);
299 	return (i);
300 }
301 
302 static int
303 diffexec(const char *diffprog, char **diffargv, int fd[])
304 {
305 	int pd;
306 
307 	switch (pdfork(&pd, PD_CLOEXEC)) {
308 	case 0:
309 		close(fd[0]);
310 		if (dup2(fd[1], STDOUT_FILENO) == -1)
311 			err(2, "child could not duplicate descriptor");
312 		close(fd[1]);
313 		execvp(diffprog, diffargv);
314 		err(2, "could not execute diff: %s", diffprog);
315 		break;
316 	case -1:
317 		err(2, "could not fork");
318 		break;
319 	}
320 	close(fd[1]);
321 	return (pd);
322 }
323 
324 static char *
325 getchange(FILE *b)
326 {
327 	char *line;
328 
329 	while ((line = get_line(b, NULL)) != NULL) {
330 		if (isdigit((unsigned char)line[0]))
331 			return (line);
332 	}
333 	return (NULL);
334 }
335 
336 
337 static char *
338 get_line(FILE *b, size_t *n)
339 {
340 	ssize_t len;
341 	static char *buf = NULL;
342 	static size_t bufsize = 0;
343 
344 	if ((len = getline(&buf, &bufsize, b)) < 0)
345 		return (NULL);
346 
347 	if (strip_cr && len >= 2 && strcmp("\r\n", &(buf[len - 2])) == 0) {
348 		buf[len - 2] = '\n';
349 		buf[len - 1] = '\0';
350 		len--;
351 	}
352 
353 	if (n != NULL)
354 		*n = len;
355 
356 	return (buf);
357 }
358 
359 static void
360 merge(int m1, int m2)
361 {
362 	struct diff *d1, *d2, *d3;
363 	int j, t1, t2;
364 	bool dup = false;
365 
366 	d1 = d13;
367 	d2 = d23;
368 	j = 0;
369 	int f1f3delta = 0;
370 
371 	for (;;) {
372 		t1 = (d1 < d13 + m1);
373 		t2 = (d2 < d23 + m2);
374 		if (!t1 && !t2)
375 			break;
376 
377 		/* first file is different from the others */
378 		if (!t2 || (t1 && d1->new.to < d2->new.from)) {
379 			/* stuff peculiar to 1st file */
380 			if (eflag == EFLAG_NONE) {
381 				separate("1");
382 				change(1, &d1->old, false);
383 				keep(2, &d1->new);
384 				change(3, &d1->new, false);
385 			} else if (eflag == EFLAG_OVERLAP) {
386 				j = edit(d2, dup, j, DIFF_TYPE1);
387 			}
388 			f1f3delta += (d1->old.to - d1->old.from) -
389 			    (d1->new.to - d1->new.from);
390 			d1++;
391 			continue;
392 		}
393 		/* second file is different from others */
394 		if (!t1 || (t2 && d2->new.to < d1->new.from)) {
395 			if (eflag == EFLAG_NONE) {
396 				separate("2");
397 				keep(1, &d2->new);
398 				change(3, &d2->new, false);
399 				change(2, &d2->old, false);
400 			} else if (Aflag || mflag) {
401 				if (eflag == EFLAG_UNMERGED) {
402 					j = edit(d2, dup, j, DIFF_TYPE2);
403 					de_delta[j] = f1f3delta;
404 				}
405 			}
406 			d2++;
407 			continue;
408 		}
409 		/*
410 		 * Merge overlapping changes in first file
411 		 * this happens after extension (see below).
412 		 */
413 		if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
414 			d1[1].old.from = d1->old.from;
415 			d1[1].new.from = d1->new.from;
416 			d1++;
417 			continue;
418 		}
419 
420 		/* merge overlapping changes in second */
421 		if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
422 			d2[1].old.from = d2->old.from;
423 			d2[1].new.from = d2->new.from;
424 			d2++;
425 			continue;
426 		}
427 		/* stuff peculiar to third file or different in all */
428 		if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
429 			dup = duplicate(&d1->old, &d2->old);
430 			/*
431 			 * dup = 0 means all files differ
432 			 * dup = 1 means files 1 and 2 identical
433 			 */
434 			if (eflag == EFLAG_NONE) {
435 				separate(dup ? "3" : "");
436 				change(1, &d1->old, dup);
437 				change(2, &d2->old, false);
438 				d3 = d1->old.to > d1->old.from ? d1 : d2;
439 				change(3, &d3->new, false);
440 			} else {
441 				j = edit(d1, dup, j, DIFF_TYPE3);
442 			}
443 			dup = false;
444 			f1f3delta += (d1->old.to - d1->old.from) -
445 			    (d1->new.to - d1->new.from);
446 			d1++;
447 			d2++;
448 			continue;
449 		}
450 		/*
451 		 * Overlapping changes from file 1 and 2; extend changes
452 		 * appropriately to make them coincide.
453 		 */
454 		if (d1->new.from < d2->new.from) {
455 			d2->old.from -= d2->new.from - d1->new.from;
456 			d2->new.from = d1->new.from;
457 		} else if (d2->new.from < d1->new.from) {
458 			d1->old.from -= d1->new.from - d2->new.from;
459 			d1->new.from = d2->new.from;
460 		}
461 		if (d1->new.to > d2->new.to) {
462 			d2->old.to += d1->new.to - d2->new.to;
463 			d2->new.to = d1->new.to;
464 		} else if (d2->new.to > d1->new.to) {
465 			d1->old.to += d2->new.to - d1->new.to;
466 			d1->new.to = d2->new.to;
467 		}
468 	}
469 
470 	if (mflag)
471 		mergescript(j);
472 	else if (Aflag)
473 		Ascript(j);
474 	else if (eflag)
475 		edscript(j);
476 }
477 
478 static void
479 separate(const char *s)
480 {
481 	printf("====%s\n", s);
482 }
483 
484 /*
485  * The range of lines rold.from thru rold.to in file i is to be changed.
486  * It is to be printed only if it does not duplicate something to be
487  * printed later.
488  */
489 static void
490 change(int i, struct range *rold, bool dup)
491 {
492 
493 	printf("%d:", i);
494 	last[i] = rold->to;
495 	prange(rold, false);
496 	if (dup)
497 		return;
498 	i--;
499 	skip(i, rold->from, NULL);
500 	skip(i, rold->to, "  ");
501 }
502 
503 /*
504  * Print the range of line numbers, rold.from thru rold.to, as n1,n2 or
505  * n1.
506  */
507 static void
508 prange(struct range *rold, bool delete)
509 {
510 
511 	if (rold->to <= rold->from)
512 		printf("%da\n", rold->from - 1);
513 	else {
514 		printf("%d", rold->from);
515 		if (rold->to > rold->from + 1)
516 			printf(",%d", rold->to - 1);
517 		if (delete)
518 			printf("d\n");
519 		else
520 			printf("c\n");
521 	}
522 }
523 
524 /*
525  * No difference was reported by diff between file 1 (or 2) and file 3,
526  * and an artificial dummy difference (trange) must be ginned up to
527  * correspond to the change reported in the other file.
528  */
529 static void
530 keep(int i, struct range *rnew)
531 {
532 	int delta;
533 	struct range trange;
534 
535 	delta = last[3] - last[i];
536 	trange.from = rnew->from - delta;
537 	trange.to = rnew->to - delta;
538 	change(i, &trange, true);
539 }
540 
541 /*
542  * skip to just before line number from in file "i".  If "pr" is non-NULL,
543  * print all skipped stuff with string pr as a prefix.
544  */
545 static int
546 skip(int i, int from, const char *pr)
547 {
548 	size_t j, n;
549 	char *line;
550 
551 	for (n = 0; cline[i] < from - 1; n += j) {
552 		if ((line = get_line(fp[i], &j)) == NULL)
553 			errx(EXIT_FAILURE, "logic error");
554 		if (pr != NULL)
555 			printf("%s%s", Tflag == 1 ? "\t" : pr, line);
556 		cline[i]++;
557 	}
558 	return ((int) n);
559 }
560 
561 /*
562  * Return 1 or 0 according as the old range (in file 1) contains exactly
563  * the same data as the new range (in file 2).
564  */
565 static bool
566 duplicate(struct range *r1, struct range *r2)
567 {
568 	int c, d;
569 	int nchar;
570 	int nline;
571 
572 	if (r1->to-r1->from != r2->to-r2->from)
573 		return (0);
574 	skip(0, r1->from, NULL);
575 	skip(1, r2->from, NULL);
576 	nchar = 0;
577 	for (nline = 0; nline < r1->to - r1->from; nline++) {
578 		do {
579 			c = getc(fp[0]);
580 			d = getc(fp[1]);
581 			if (c == -1 && d == -1)
582 				break;
583 			if (c == -1 || d == -1)
584 				errx(EXIT_FAILURE, "logic error");
585 			nchar++;
586 			if (c != d) {
587 				repos(nchar);
588 				return (0);
589 			}
590 		} while (c != '\n');
591 	}
592 	repos(nchar);
593 	return (1);
594 }
595 
596 static void
597 repos(int nchar)
598 {
599 	int i;
600 
601 	for (i = 0; i < 2; i++)
602 		(void)fseek(fp[i], (long)-nchar, SEEK_CUR);
603 }
604 
605 /*
606  * collect an editing script for later regurgitation
607  */
608 static int
609 edit(struct diff *diff, bool dup, int j, int difftype)
610 {
611 	if (!(eflag == EFLAG_UNMERGED ||
612 		(!dup && eflag == EFLAG_OVERLAP ) ||
613 		(dup && eflag == EFLAG_NOOVERLAP))) {
614 		return (j);
615 	}
616 	j++;
617 	overlap[j] = !dup;
618 	if (!dup)
619 		overlapcnt++;
620 
621 	de[j].type = difftype;
622 #if DEBUG
623 	de[j].line = strdup(diff->line);
624 #endif	/* DEBUG */
625 
626 	de[j].old.from = diff->old.from;
627 	de[j].old.to = diff->old.to;
628 	de[j].new.from = diff->new.from;
629 	de[j].new.to = diff->new.to;
630 	return (j);
631 }
632 
633 static void
634 printrange(FILE *p, struct range *r)
635 {
636 	char *line = NULL;
637 	size_t len = 0;
638 	int i = 1;
639 
640 	/* We haven't been asked to print anything */
641 	if (r->from == r->to)
642 		return;
643 
644 	if (r->from > r->to)
645 		errx(EXIT_FAILURE, "invalid print range");
646 
647 	/*
648 	 * XXX-THJ: We read through all of the file for each range printed.
649 	 * This duplicates work and will probably impact performance on large
650 	 * files with lots of ranges.
651 	 */
652 	fseek(p, 0L, SEEK_SET);
653 	while (getline(&line, &len, p) > 0) {
654 		if (i >= r->from)
655 			printf("%s", line);
656 		if (++i > r->to - 1)
657 			break;
658 	}
659 	free(line);
660 }
661 
662 /* regurgitate */
663 static void
664 edscript(int n)
665 {
666 	bool delete;
667 	struct range *new, *old;
668 
669 	for (; n > 0; n--) {
670 		new = &de[n].new;
671 		old = &de[n].old;
672 
673 		delete = (new->from == new->to);
674 		if (de[n].type == DIFF_TYPE1) {
675 			if (delete)
676 				printf("%dd\n", new->from - 1);
677 			else if (old->from == new->from && old->to == new->to) {
678 				printf("%dc\n", old->from);
679 				printrange(fp[2], old);
680 				printf(".\n");
681 			}
682 			continue;
683 		} else {
684 			if (!oflag || !overlap[n]) {
685 				prange(old, delete);
686 			} else {
687 				printf("%da\n", old->to - 1);
688 				printf("%s\n", divider);
689 			}
690 			printrange(fp[2], new);
691 			if (!oflag || !overlap[n]) {
692 				if (!delete)
693 					printf(".\n");
694 			} else {
695 				printf("%s %s\n.\n", newmark, f3mark);
696 				printf("%da\n%s %s\n.\n", old->from - 1,
697 					oldmark, f1mark);
698 			}
699 		}
700 	}
701 	if (iflag)
702 		printf("w\nq\n");
703 
704 	exit(eflag == EFLAG_NONE ? overlapcnt : 0);
705 }
706 
707 /*
708  * Output an edit script to turn mine into yours, when there is a conflict
709  * between the 3 files bracket the changes. Regurgitate the diffs in reverse
710  * order to allow the ed script to track down where the lines are as changes
711  * are made.
712  */
713 static void
714 Ascript(int n)
715 {
716 	int startmark;
717 	bool deletenew;
718 	bool deleteold;
719 
720 	struct range *new, *old;
721 
722 	for (; n > 0; n--) {
723 		new = &de[n].new;
724 		old = &de[n].old;
725 		deletenew = (new->from == new->to);
726 		deleteold = (old->from == old->to);
727 
728 		if (de[n].type == DIFF_TYPE2) {
729 			if (!oflag || !overlap[n]) {
730 				prange(old, deletenew);
731 				printrange(fp[2], new);
732 			} else {
733 				startmark = new->to - 1 + de_delta[n];
734 
735 				printf("%da\n", startmark);
736 				printf("%s %s\n", newmark, f3mark);
737 
738 				printf(".\n");
739 
740 				printf("%da\n", startmark -
741 					(new->to - new->from));
742 				printf("%s %s\n", oldmark, f2mark);
743 				if (!deleteold)
744 					printrange(fp[1], old);
745 				printf("%s\n.\n", divider);
746 			}
747 
748 		} else if (de[n].type == DIFF_TYPE3) {
749 			startmark = old->to - 1;
750 
751 			if (!oflag || !overlap[n]) {
752 				prange(old, deletenew);
753 				printrange(fp[2], new);
754 			} else {
755 				printf("%da\n", startmark);
756 				printf("%s %s\n", orgmark, f2mark);
757 
758 				if (deleteold) {
759 					struct range r;
760 					r.from = old->from-1;
761 					r.to = new->to;
762 					printrange(fp[1], &r);
763 				} else
764 					printrange(fp[1], old);
765 
766 				printf("%s\n", divider);
767 				printrange(fp[2], new);
768 			}
769 
770 			if (!oflag || !overlap[n]) {
771 				if (!deletenew)
772 					printf(".\n");
773 			} else {
774 				printf("%s %s\n.\n", newmark, f3mark);
775 
776 				/*
777 				 * Go to the start of the conflict in original
778 				 * file and append lines
779 				 */
780 				printf("%da\n%s %s\n.\n",
781 					startmark - (old->to - old->from),
782 					oldmark, f1mark);
783 			}
784 		}
785 	}
786 	if (iflag)
787 		printf("w\nq\n");
788 
789 	exit(overlapcnt > 0);
790 }
791 
792 /*
793  * Output the merged file directly (don't generate an ed script). When
794  * regurgitating diffs we need to walk forward through the file and print any
795  * inbetween lines.
796  */
797 static void
798 mergescript(int i)
799 {
800 	struct range r, *new, *old;
801 	int n;
802 	bool delete = false;
803 
804 	r.from = 1;
805 	r.to = 1;
806 
807 	for (n = 1; n <= i; n++) {
808 		new = &de[n].new;
809 		old = &de[n].old;
810 
811 		/*
812 		 * Print any lines leading up to here. If we are merging don't
813 		 * print deleted ranges.
814 		 */
815 		delete = (new->from == new->to);
816 		if (de[n].type == DIFF_TYPE1 && delete)
817 			r.to = new->from - 1;
818 		else if (de[n].type == DIFF_TYPE3 && (old->from == old->to)) {
819 			r.from = old->from - 1;
820 			r.to = new->from;
821 		} else if (de[n].type == DIFF_TYPE2)
822 			r.to = new->from + de_delta[n];
823 		else
824 			r.to = old->from;
825 
826 		printrange(fp[0], &r);
827 		switch (de[n].type) {
828 		case DIFF_TYPE1:
829 			/* If this isn't a delete print it */
830 			if (!delete)
831 				printrange(fp[2], new);
832 			break;
833 		case DIFF_TYPE2:
834 			printf("%s %s\n", oldmark, f2mark);
835 			printrange(fp[1], old);
836 			printf("%s\n", divider);
837 			printrange(fp[2], new);
838 			printf("%s %s\n", newmark, f3mark);
839 			break;
840 		case DIFF_TYPE3:
841 			if (!oflag || !overlap[n]) {
842 				printrange(fp[2], new);
843 			} else {
844 
845 				printf("%s %s\n", oldmark, f1mark);
846 				printrange(fp[0], old);
847 
848 				if (eflag != EFLAG_OVERLAP) {
849 					printf("%s %s\n", orgmark, f2mark);
850 					if (old->from == old->to) {
851 						struct range or;
852 						or.from = old->from - 1;
853 						or.to = new->to;
854 						printrange(fp[1], &or);
855 					} else {
856 						printrange(fp[1], old);
857 					}
858 				}
859 
860 				printf("%s\n", divider);
861 
862 				printrange(fp[2], new);
863 				printf("%s %s\n", newmark, f3mark);
864 			}
865 			break;
866 		default:
867 			printf("Error: Unhandled diff type - exiting\n");
868 			exit(EXIT_FAILURE);
869 		}
870 
871 		if (de[n].type == DIFF_TYPE2)
872 			r.from = new->to + de_delta[n];
873 		else if (old->from == old->to)
874 			r.from = new->to;
875 		else
876 			r.from = old->to;
877 	}
878 
879 	/*
880 	 * Print from the final range to the end of 'myfile'. Any deletions or
881 	 * additions to this file should have been handled by now.
882 	 *
883 	 * If the ranges are the same we need to rewind a line.
884 	 * If the new range is 0 length (from == to), we need to use the new
885 	 * range.
886 	 */
887 	new = &de[n-1].new;
888 	old = &de[n-1].old;
889 
890 	if (old->from == new->from && old->to == new->to)
891 		r.from--;
892 	else if (new->from == new->to)
893 		r.from = new->from;
894 
895 	r.to = INT_MAX;
896 	printrange(fp[2], &r);
897 	exit(overlapcnt > 0);
898 }
899 
900 static void
901 increase(void)
902 {
903 	struct diff *p;
904 	char *q;
905 	int *s;
906 	size_t newsz, incr;
907 
908 	/* are the memset(3) calls needed? */
909 	newsz = szchanges == 0 ? 64 : 2 * szchanges;
910 	incr = newsz - szchanges;
911 
912 	p = reallocarray(d13, newsz, sizeof(*p));
913 	if (p == NULL)
914 		err(1, NULL);
915 	memset(p + szchanges, 0, incr * sizeof(*p));
916 	d13 = p;
917 	p = reallocarray(d23, newsz, sizeof(*p));
918 	if (p == NULL)
919 		err(1, NULL);
920 	memset(p + szchanges, 0, incr * sizeof(*p));
921 	d23 = p;
922 	p = reallocarray(de, newsz, sizeof(*p));
923 	if (p == NULL)
924 		err(1, NULL);
925 	memset(p + szchanges, 0, incr * sizeof(*p));
926 	de = p;
927 	q = reallocarray(overlap, newsz, 1);
928 	if (q == NULL)
929 		err(1, NULL);
930 	memset(q + szchanges, 0, incr * 1);
931 	overlap = q;
932 	s = reallocarray(de_delta, newsz, sizeof(*s));
933 	if (s == NULL)
934 		err(1, NULL);
935 	memset(s + szchanges, 0, incr * sizeof(*s));
936 	de_delta = s;
937 	szchanges = newsz;
938 }
939 
940 static void
941 wait_and_check(int pd)
942 {
943 	int status;
944 
945 	while (pdwait(pd, &status, WEXITED, NULL, NULL) == -1) {
946 		if (errno != EINTR)
947 			err(2, "pdwait");
948 	}
949 
950 	if (WIFEXITED(status) && WEXITSTATUS(status) >= 2)
951 		errx(2, "diff exited abnormally");
952 	if (WIFSIGNALED(status))
953 		errx(2, "diff killed by signal %d", WTERMSIG(status));
954 }
955 
956 int
957 main(int argc, char **argv)
958 {
959 	int ch, nblabels, m, n;
960 	char *labels[] = { NULL, NULL, NULL };
961 	const char *diffprog = DIFF_PATH;
962 	char *file1, *file2, *file3;
963 	char *diffargv[7];
964 	int diffargc = 0;
965 	int fd13[2], fd23[2];
966 	int pd13, pd23;
967 	cap_rights_t rights_ro;
968 
969 	nblabels = 0;
970 	eflag = EFLAG_NONE;
971 	oflag = 0;
972 	diffargv[diffargc++] = __DECONST(char *, diffprog);
973 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
974 		switch (ch) {
975 		case '3':
976 			eflag = EFLAG_NOOVERLAP;
977 			break;
978 		case 'a':
979 			diffargv[diffargc++] = __DECONST(char *, "-a");
980 			break;
981 		case 'A':
982 			Aflag = 1;
983 			break;
984 		case 'e':
985 			eflag = EFLAG_UNMERGED;
986 			break;
987 		case 'E':
988 			eflag = EFLAG_OVERLAP;
989 			oflag = 1;
990 			break;
991 		case 'i':
992 			iflag = 1;
993 			break;
994 		case 'L':
995 			oflag = 1;
996 			if (nblabels >= 3)
997 				errx(2, "too many file label options");
998 			labels[nblabels++] = optarg;
999 			break;
1000 		case 'm':
1001 			Aflag = 1;
1002 			oflag = 1;
1003 			mflag = 1;
1004 			break;
1005 		case 'T':
1006 			Tflag = 1;
1007 			break;
1008 		case 'x':
1009 			eflag = EFLAG_OVERLAP;
1010 			break;
1011 		case 'X':
1012 			oflag = 1;
1013 			eflag = EFLAG_OVERLAP;
1014 			break;
1015 		case DIFFPROG_OPT:
1016 			diffprog = optarg;
1017 			break;
1018 		case STRIPCR_OPT:
1019 			strip_cr = 1;
1020 			diffargv[diffargc++] = __DECONST(char *, "--strip-trailing-cr");
1021 			break;
1022 		case HELP_OPT:
1023 			usage();
1024 			exit(0);
1025 		case VERSION_OPT:
1026 			printf("%s\n", diff3_version);
1027 			exit(0);
1028 		}
1029 	}
1030 	argc -= optind;
1031 	argv += optind;
1032 
1033 	if (Aflag) {
1034 		if (eflag == EFLAG_NONE)
1035 			eflag = EFLAG_UNMERGED;
1036 		oflag = 1;
1037 	}
1038 
1039 	if (argc != 3) {
1040 		usage();
1041 		exit(2);
1042 	}
1043 
1044 	if (caph_limit_stdio() == -1)
1045 		err(2, "unable to limit stdio");
1046 
1047 	cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
1048 
1049 	/* TODO stdio */
1050 	file1 = argv[0];
1051 	file2 = argv[1];
1052 	file3 = argv[2];
1053 
1054 	if (oflag) {
1055 		asprintf(&f1mark, "%s",
1056 		    labels[0] != NULL ? labels[0] : file1);
1057 		if (f1mark == NULL)
1058 			err(2, "asprintf");
1059 		asprintf(&f2mark, "%s",
1060 		    labels[1] != NULL ? labels[1] : file2);
1061 		if (f2mark == NULL)
1062 			err(2, "asprintf");
1063 		asprintf(&f3mark, "%s",
1064 		    labels[2] != NULL ? labels[2] : file3);
1065 		if (f3mark == NULL)
1066 			err(2, "asprintf");
1067 	}
1068 	fp[0] = fopen(file1, "r");
1069 	if (fp[0] == NULL)
1070 		err(2, "Can't open %s", file1);
1071 	if (caph_rights_limit(fileno(fp[0]), &rights_ro) < 0)
1072 		err(2, "unable to limit rights on: %s", file1);
1073 
1074 	fp[1] = fopen(file2, "r");
1075 	if (fp[1] == NULL)
1076 		err(2, "Can't open %s", file2);
1077 	if (caph_rights_limit(fileno(fp[1]), &rights_ro) < 0)
1078 		err(2, "unable to limit rights on: %s", file2);
1079 
1080 	fp[2] = fopen(file3, "r");
1081 	if (fp[2] == NULL)
1082 		err(2, "Can't open %s", file3);
1083 	if (caph_rights_limit(fileno(fp[2]), &rights_ro) < 0)
1084 		err(2, "unable to limit rights on: %s", file3);
1085 
1086 	if (pipe(fd13))
1087 		err(2, "pipe");
1088 	if (pipe(fd23))
1089 		err(2, "pipe");
1090 
1091 	diffargv[diffargc] = file1;
1092 	diffargv[diffargc + 1] = file3;
1093 	diffargv[diffargc + 2] = NULL;
1094 	pd13 = diffexec(diffprog, diffargv, fd13);
1095 
1096 	diffargv[diffargc] = file2;
1097 	pd23 = diffexec(diffprog, diffargv, fd23);
1098 
1099 	caph_cache_catpages();
1100 	if (caph_enter() < 0)
1101 		err(2, "unable to enter capability mode");
1102 
1103 	/* parse diffs */
1104 	increase();
1105 	m = readin(fd13[0], &d13);
1106 	n = readin(fd23[0], &d23);
1107 
1108 	wait_and_check(pd13);
1109 	wait_and_check(pd23);
1110 
1111 	merge(m, n);
1112 
1113 	return (EXIT_SUCCESS);
1114 }
1115