xref: /freebsd/usr.bin/diff3/diff3.c (revision bdcbfde31e8e9b343f113a1956384bdf30d1ed62)
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 #if 0
66 #endif /* not lint */
67 #include <sys/cdefs.h>
68 #include <sys/capsicum.h>
69 #include <sys/procdesc.h>
70 #include <sys/types.h>
71 #include <sys/event.h>
72 #include <sys/wait.h>
73 
74 #include <capsicum_helpers.h>
75 #include <ctype.h>
76 #include <err.h>
77 #include <getopt.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <limits.h>
81 #include <inttypes.h>
82 #include <string.h>
83 #include <unistd.h>
84 
85 
86 /*
87  * "from" is first in range of changed lines; "to" is last+1
88  * from=to=line after point of insertion for added lines.
89  */
90 struct range {
91 	int from;
92 	int to;
93 };
94 
95 struct diff {
96 #define DIFF_TYPE2 2
97 #define DIFF_TYPE3 3
98 	int type;
99 #if DEBUG
100 	char *line;
101 #endif	/* DEBUG */
102 
103 	/* Ranges as lines */
104 	struct range old;
105 	struct range new;
106 };
107 
108 #define EFLAG_NONE 	0
109 #define EFLAG_OVERLAP 	1
110 #define EFLAG_NOOVERLAP	2
111 #define EFLAG_UNMERGED	3
112 
113 static size_t szchanges;
114 
115 static struct diff *d13;
116 static struct diff *d23;
117 /*
118  * "de" is used to gather editing scripts.  These are later spewed out in
119  * reverse order.  Its first element must be all zero, the "old" and "new"
120  * components of "de" contain line positions. Array overlap indicates which
121  * sections in "de" correspond to lines that are different in all three files.
122  */
123 static struct diff *de;
124 static char *overlap;
125 static int  overlapcnt;
126 static FILE *fp[3];
127 static int cline[3];		/* # of the last-read line in each file (0-2) */
128 /*
129  * The latest known correspondence between line numbers of the 3 files
130  * is stored in last[1-3];
131  */
132 static int last[4];
133 static int Aflag, eflag, iflag, mflag, Tflag;
134 static int oflag;		/* indicates whether to mark overlaps (-E or -X) */
135 static int strip_cr;
136 static char *f1mark, *f2mark, *f3mark;
137 static const char *oldmark = "<<<<<<<";
138 static const char *orgmark = "|||||||";
139 static const char *newmark = ">>>>>>>";
140 static const char *divider = "=======";
141 
142 static bool duplicate(struct range *, struct range *);
143 static int edit(struct diff *, bool, int, int);
144 static char *getchange(FILE *);
145 static char *get_line(FILE *, size_t *);
146 static int readin(int fd, struct diff **);
147 static int skip(int, int, const char *);
148 static void change(int, struct range *, bool);
149 static void keep(int, struct range *);
150 static void merge(int, int);
151 static void prange(struct range *, bool);
152 static void repos(int);
153 static void edscript(int) __dead2;
154 static void Ascript(int) __dead2;
155 static void mergescript(int) __dead2;
156 static void increase(void);
157 static void usage(void);
158 static void printrange(FILE *, struct range *);
159 
160 static const char diff3_version[] = "FreeBSD diff3 20220517";
161 
162 enum {
163 	DIFFPROG_OPT,
164 	STRIPCR_OPT,
165 	HELP_OPT,
166 	VERSION_OPT
167 };
168 
169 #define DIFF_PATH "/usr/bin/diff"
170 
171 #define OPTIONS "3aAeEiL:mTxX"
172 static struct option longopts[] = {
173 	{ "ed",			no_argument,		NULL,	'e' },
174 	{ "show-overlap",	no_argument,		NULL,	'E' },
175 	{ "overlap-only",	no_argument,		NULL,	'x' },
176 	{ "initial-tab",	no_argument,		NULL,	'T' },
177 	{ "text",		no_argument,		NULL,	'a' },
178 	{ "strip-trailing-cr",	no_argument,		NULL,	STRIPCR_OPT },
179 	{ "show-all",		no_argument,		NULL,	'A' },
180 	{ "easy-only",		no_argument,		NULL,	'3' },
181 	{ "merge",		no_argument,		NULL,	'm' },
182 	{ "label",		required_argument,	NULL,	'L' },
183 	{ "diff-program",	required_argument,	NULL,	DIFFPROG_OPT },
184 	{ "help",		no_argument,		NULL,	HELP_OPT},
185 	{ "version",		no_argument,		NULL,	VERSION_OPT}
186 };
187 
188 static void
189 usage(void)
190 {
191 	fprintf(stderr, "usage: diff3 [-3aAeEimTxX] [-L label1] [-L label2] "
192 	    "[-L label3] file1 file2 file3\n");
193 }
194 
195 static int
196 readin(int fd, struct diff **dd)
197 {
198 	int a, b, c, d;
199 	size_t i;
200 	char kind, *p;
201 	FILE *f;
202 
203 	f = fdopen(fd, "r");
204 	if (f == NULL)
205 		err(2, "fdopen");
206 	for (i = 0; (p = getchange(f)); i++) {
207 #if DEBUG
208 		(*dd)[i].line = strdup(p);
209 #endif	/* DEBUG */
210 
211 		if (i >= szchanges - 1)
212 			increase();
213 		a = b = (int)strtoimax(p, &p, 10);
214 		if (*p == ',') {
215 			p++;
216 			b = (int)strtoimax(p, &p, 10);
217 		}
218 		kind = *p++;
219 		c = d = (int)strtoimax(p, &p, 10);
220 		if (*p == ',') {
221 			p++;
222 			d = (int)strtoimax(p, &p, 10);
223 		}
224 		if (kind == 'a')
225 			a++;
226 		if (kind == 'd')
227 			c++;
228 		b++;
229 		d++;
230 		(*dd)[i].old.from = a;
231 		(*dd)[i].old.to = b;
232 		(*dd)[i].new.from = c;
233 		(*dd)[i].new.to = d;
234 	}
235 	if (i) {
236 		(*dd)[i].old.from = (*dd)[i - 1].old.to;
237 		(*dd)[i].new.from = (*dd)[i - 1].new.to;
238 	}
239 	fclose(f);
240 	return (i);
241 }
242 
243 static int
244 diffexec(const char *diffprog, char **diffargv, int fd[])
245 {
246 	int pd;
247 
248 	switch (pdfork(&pd, PD_CLOEXEC)) {
249 	case 0:
250 		close(fd[0]);
251 		if (dup2(fd[1], STDOUT_FILENO) == -1)
252 			err(2, "child could not duplicate descriptor");
253 		close(fd[1]);
254 		execvp(diffprog, diffargv);
255 		err(2, "could not execute diff: %s", diffprog);
256 		break;
257 	case -1:
258 		err(2, "could not fork");
259 		break;
260 	}
261 	close(fd[1]);
262 	return (pd);
263 }
264 
265 static char *
266 getchange(FILE *b)
267 {
268 	char *line;
269 
270 	while ((line = get_line(b, NULL))) {
271 		if (isdigit((unsigned char)line[0]))
272 			return (line);
273 	}
274 	return (NULL);
275 }
276 
277 
278 static char *
279 get_line(FILE *b, size_t *n)
280 {
281 	ssize_t len;
282 	static char *buf = NULL;
283 	static size_t bufsize = 0;
284 
285 	if ((len = getline(&buf, &bufsize, b)) < 0)
286 		return (NULL);
287 
288 	if (strip_cr && len >= 2 && strcmp("\r\n", &(buf[len - 2])) == 0) {
289 		buf[len - 2] = '\n';
290 		buf[len - 1] = '\0';
291 		len--;
292 	}
293 
294 	if (n != NULL)
295 		*n = len;
296 
297 	return (buf);
298 }
299 
300 static void
301 merge(int m1, int m2)
302 {
303 	struct diff *d1, *d2, *d3;
304 	int j, t1, t2;
305 	bool dup = false;
306 
307 	d1 = d13;
308 	d2 = d23;
309 	j = 0;
310 
311 	while (t1 = d1 < d13 + m1, t2 = d2 < d23 + m2, t1 || t2) {
312 		/* first file is different from the others */
313 		if (!t2 || (t1 && d1->new.to < d2->new.from)) {
314 			/* stuff peculiar to 1st file */
315 			if (eflag == EFLAG_NONE) {
316 				printf("====1\n");
317 				change(1, &d1->old, false);
318 				keep(2, &d1->new);
319 				change(3, &d1->new, false);
320 			}
321 			d1++;
322 			continue;
323 		}
324 		/* second file is different from others */
325 		if (!t1 || (t2 && d2->new.to < d1->new.from)) {
326 			if (eflag == EFLAG_NONE) {
327 				printf("====2\n");
328 				keep(1, &d2->new);
329 				change(3, &d2->new, false);
330 				change(2, &d2->old, false);
331 			} else if (Aflag || mflag) {
332 				// XXX-THJ: What does it mean for the second file to differ?
333 				if (eflag == EFLAG_UNMERGED)
334 					j = edit(d2, dup, j, DIFF_TYPE2);
335 			}
336 			d2++;
337 			continue;
338 		}
339 		/*
340 		 * Merge overlapping changes in first file
341 		 * this happens after extension (see below).
342 		 */
343 		if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
344 			d1[1].old.from = d1->old.from;
345 			d1[1].new.from = d1->new.from;
346 			d1++;
347 			continue;
348 		}
349 
350 		/* merge overlapping changes in second */
351 		if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
352 			d2[1].old.from = d2->old.from;
353 			d2[1].new.from = d2->new.from;
354 			d2++;
355 			continue;
356 		}
357 		/* stuff peculiar to third file or different in all */
358 		if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
359 			dup = duplicate(&d1->old, &d2->old);
360 			/*
361 			 * dup = 0 means all files differ
362 			 * dup = 1 means files 1 and 2 identical
363 			 */
364 			if (eflag == EFLAG_NONE) {
365 				printf("====%s\n", dup ? "3" : "");
366 				change(1, &d1->old, dup);
367 				change(2, &d2->old, false);
368 				d3 = d1->old.to > d1->old.from ? d1 : d2;
369 				change(3, &d3->new, false);
370 			} else {
371 				j = edit(d1, dup, j, DIFF_TYPE3);
372 			}
373 			dup = false;
374 			d1++;
375 			d2++;
376 			continue;
377 		}
378 		/*
379 		 * Overlapping changes from file 1 and 2; extend changes
380 		 * appropriately to make them coincide.
381 		 */
382 		if (d1->new.from < d2->new.from) {
383 			d2->old.from -= d2->new.from - d1->new.from;
384 			d2->new.from = d1->new.from;
385 		} else if (d2->new.from < d1->new.from) {
386 			d1->old.from -= d1->new.from - d2->new.from;
387 			d1->new.from = d2->new.from;
388 		}
389 		if (d1->new.to > d2->new.to) {
390 			d2->old.to += d1->new.to - d2->new.to;
391 			d2->new.to = d1->new.to;
392 		} else if (d2->new.to > d1->new.to) {
393 			d1->old.to += d2->new.to - d1->new.to;
394 			d1->new.to = d2->new.to;
395 		}
396 	}
397 
398 	if (mflag)
399 		mergescript(j);
400 	else if (Aflag)
401 		Ascript(j);
402 	else if (eflag)
403 		edscript(j);
404 }
405 
406 /*
407  * The range of lines rold.from thru rold.to in file i is to be changed.
408  * It is to be printed only if it does not duplicate something to be
409  * printed later.
410  */
411 static void
412 change(int i, struct range *rold, bool dup)
413 {
414 
415 	printf("%d:", i);
416 	last[i] = rold->to;
417 	prange(rold, false);
418 	if (dup)
419 		return;
420 	i--;
421 	skip(i, rold->from, NULL);
422 	skip(i, rold->to, "  ");
423 }
424 
425 /*
426  * Print the range of line numbers, rold.from thru rold.to, as n1,n2 or
427  * n1.
428  */
429 static void
430 prange(struct range *rold, bool delete)
431 {
432 
433 	if (rold->to <= rold->from)
434 		printf("%da\n", rold->from - 1);
435 	else {
436 		printf("%d", rold->from);
437 		if (rold->to > rold->from + 1)
438 			printf(",%d", rold->to - 1);
439 		if (delete)
440 			printf("d\n");
441 		else
442 			printf("c\n");
443 	}
444 }
445 
446 /*
447  * No difference was reported by diff between file 1 (or 2) and file 3,
448  * and an artificial dummy difference (trange) must be ginned up to
449  * correspond to the change reported in the other file.
450  */
451 static void
452 keep(int i, struct range *rnew)
453 {
454 	int delta;
455 	struct range trange;
456 
457 	delta = last[3] - last[i];
458 	trange.from = rnew->from - delta;
459 	trange.to = rnew->to - delta;
460 	change(i, &trange, true);
461 }
462 
463 /*
464  * skip to just before line number from in file "i".  If "pr" is non-NULL,
465  * print all skipped stuff with string pr as a prefix.
466  */
467 static int
468 skip(int i, int from, const char *pr)
469 {
470 	size_t j, n;
471 	char *line;
472 
473 	for (n = 0; cline[i] < from - 1; n += j) {
474 		if ((line = get_line(fp[i], &j)) == NULL)
475 			errx(EXIT_FAILURE, "logic error");
476 		if (pr != NULL)
477 			printf("%s%s", Tflag == 1 ? "\t" : pr, line);
478 		cline[i]++;
479 	}
480 	return ((int) n);
481 }
482 
483 /*
484  * Return 1 or 0 according as the old range (in file 1) contains exactly
485  * the same data as the new range (in file 2).
486  */
487 static bool
488 duplicate(struct range *r1, struct range *r2)
489 {
490 	int c, d;
491 	int nchar;
492 	int nline;
493 
494 	if (r1->to-r1->from != r2->to-r2->from)
495 		return (0);
496 	skip(0, r1->from, NULL);
497 	skip(1, r2->from, NULL);
498 	nchar = 0;
499 	for (nline = 0; nline < r1->to - r1->from; nline++) {
500 		do {
501 			c = getc(fp[0]);
502 			d = getc(fp[1]);
503 			if (c == -1 && d == -1)
504 				break;
505 			if (c == -1 || d == -1)
506 				errx(EXIT_FAILURE, "logic error");
507 			nchar++;
508 			if (c != d) {
509 				repos(nchar);
510 				return (0);
511 			}
512 		} while (c != '\n');
513 	}
514 	repos(nchar);
515 	return (1);
516 }
517 
518 static void
519 repos(int nchar)
520 {
521 	int i;
522 
523 	for (i = 0; i < 2; i++)
524 		(void)fseek(fp[i], (long)-nchar, SEEK_CUR);
525 }
526 
527 /*
528  * collect an editing script for later regurgitation
529  */
530 static int
531 edit(struct diff *diff, bool dup, int j, int difftype)
532 {
533 	if (!(eflag == EFLAG_UNMERGED ||
534 		(!dup && eflag == EFLAG_OVERLAP ) ||
535 		(dup && eflag == EFLAG_NOOVERLAP))) {
536 		return (j);
537 	}
538 	j++;
539 	overlap[j] = !dup;
540 	if (!dup)
541 		overlapcnt++;
542 
543 	de[j].type = difftype;
544 #if DEBUG
545 	de[j].line = strdup(diff->line);
546 #endif	/* DEBUG */
547 
548 	de[j].old.from = diff->old.from;
549 	de[j].old.to = diff->old.to;
550 	de[j].new.from = diff->new.from;
551 	de[j].new.to = diff->new.to;
552 	return (j);
553 }
554 
555 static void
556 printrange(FILE *p, struct range *r)
557 {
558 	char *line = NULL;
559 	size_t len = 0;
560 	int i = 1;
561 	ssize_t rlen = 0;
562 
563 	/* We haven't been asked to print anything */
564 	if (r->from == r->to)
565 		return;
566 
567 	if (r->from > r->to)
568 		errx(EXIT_FAILURE, "invalid print range");
569 
570 	/*
571 	 * XXX-THJ: We read through all of the file for each range printed.
572 	 * This duplicates work and will probably impact performance on large
573 	 * files with lots of ranges.
574 	 */
575 	fseek(p, 0L, SEEK_SET);
576 	while ((rlen = getline(&line, &len, p)) > 0) {
577 		if (i >= r->from)
578 			printf("%s", line);
579 		if (++i > r->to - 1)
580 			break;
581 	}
582 	free(line);
583 }
584 
585 /* regurgitate */
586 static void
587 edscript(int n)
588 {
589 	bool delete;
590 	struct range *new, *old;
591 
592 	for (; n > 0; n--) {
593 		new = &de[n].new;
594 		old = &de[n].old;
595 
596 		delete = (new->from == new->to);
597 		if (!oflag || !overlap[n]) {
598 			prange(old, delete);
599 		} else {
600 			printf("%da\n", old->to - 1);
601 			printf("%s\n", divider);
602 		}
603 		printrange(fp[2], new);
604 		if (!oflag || !overlap[n]) {
605 			if (!delete)
606 				printf(".\n");
607 		} else {
608 			printf("%s %s\n.\n", newmark, f3mark);
609 			printf("%da\n%s %s\n.\n", old->from - 1,
610 				oldmark, f1mark);
611 		}
612 	}
613 	if (iflag)
614 		printf("w\nq\n");
615 
616 	exit(eflag == EFLAG_NONE ? overlapcnt : 0);
617 }
618 
619 /*
620  * Output an edit script to turn mine into yours, when there is a conflict
621  * between the 3 files bracket the changes. Regurgitate the diffs in reverse
622  * order to allow the ed script to track down where the lines are as changes
623  * are made.
624  */
625 static void
626 Ascript(int n)
627 {
628 	int startmark;
629 	bool deletenew;
630 	bool deleteold;
631 
632 	struct range *new, *old;
633 
634 	for (; n > 0; n--) {
635 		new = &de[n].new;
636 		old = &de[n].old;
637 		deletenew = (new->from == new->to);
638 		deleteold = (old->from == old->to);
639 
640 		if (de[n].type == DIFF_TYPE2) {
641 			if (!oflag || !overlap[n]) {
642 				prange(old, deletenew);
643 				printrange(fp[2], new);
644 			} else {
645 				startmark = new->to;
646 
647 				if (!deletenew)
648 					startmark--;
649 
650 				printf("%da\n", startmark);
651 				printf("%s %s\n", newmark, f3mark);
652 
653 				printf(".\n");
654 
655 				printf("%da\n", startmark -
656 					(new->to - new->from));
657 				printf("%s %s\n", oldmark, f2mark);
658 				if (!deleteold)
659 					printrange(fp[1], old);
660 				printf("%s\n.\n", divider);
661 			}
662 
663 		} else if (de[n].type == DIFF_TYPE3) {
664 			startmark = old->to - 1;
665 
666 			if (!oflag || !overlap[n]) {
667 				prange(old, deletenew);
668 				printrange(fp[2], new);
669 			} else {
670 				printf("%da\n", startmark);
671 				printf("%s %s\n", orgmark, f2mark);
672 
673 				if (deleteold) {
674 					struct range r;
675 					r.from = old->from-1;
676 					r.to = new->to;
677 					printrange(fp[1], &r);
678 				} else
679 					printrange(fp[1], old);
680 
681 				printf("%s\n", divider);
682 				printrange(fp[2], new);
683 			}
684 
685 			if (!oflag || !overlap[n]) {
686 				if (!deletenew)
687 					printf(".\n");
688 			} else {
689 				printf("%s %s\n.\n", newmark, f3mark);
690 
691 				/*
692 				 * Go to the start of the conflict in original
693 				 * file and append lines
694 				 */
695 				printf("%da\n%s %s\n.\n",
696 					startmark - (old->to - old->from),
697 					oldmark, f1mark);
698 			}
699 		}
700 	}
701 	if (iflag)
702 		printf("w\nq\n");
703 
704 	exit(overlapcnt > 0);
705 }
706 
707 /*
708  * Output the merged file directly (don't generate an ed script). When
709  * regurgitating diffs we need to walk forward through the file and print any
710  * inbetween lines.
711  */
712 static void
713 mergescript(int i)
714 {
715 	struct range r, *new, *old;
716 	int n;
717 
718 	r.from = 1;
719 	r.to = 1;
720 
721 	for (n = 1; n < i+1; n++) {
722 		new = &de[n].new;
723 		old = &de[n].old;
724 
725 		/* print any lines leading up to here */
726 		r.to = old->from;
727 		printrange(fp[0], &r);
728 
729 		if (de[n].type == DIFF_TYPE2) {
730 			printf("%s %s\n", oldmark, f2mark);
731 			printrange(fp[1], old);
732 			printf("%s\n", divider);
733 			printrange(fp[2], new);
734 			printf("%s %s\n", newmark, f3mark);
735 		} else if (de[n].type == DIFF_TYPE3) {
736 			if (!oflag || !overlap[n]) {
737 				printrange(fp[2], new);
738 			} else {
739 
740 				printf("%s %s\n", oldmark, f1mark);
741 				printrange(fp[0], old);
742 
743 				printf("%s %s\n", orgmark, f2mark);
744 				if (old->from == old->to) {
745 					struct range or;
746 					or.from = old->from - 1;
747 					or.to = new->to;
748 					printrange(fp[1], &or);
749 				} else
750 					printrange(fp[1], old);
751 
752 				printf("%s\n", divider);
753 
754 				printrange(fp[2], new);
755 				printf("%s %s\n", newmark, f3mark);
756 			}
757 		}
758 
759 		if (old->from == old->to)
760 			r.from = new->to;
761 		else
762 			r.from = old->to;
763 	}
764 	/*
765 	 * Print from the final range to the end of 'myfile'. Any deletions or
766 	 * additions to this file should have been handled by now.
767 	 *
768 	 * If the ranges are the same we need to rewind a line.
769 	 * If the new range is 0 length (from == to), we need to use the old
770 	 * range.
771 	 */
772 	new = &de[n-1].new;
773 	old = &de[n-1].old;
774 	if ((old->from == new->from) &&
775 		(old->to == new->to))
776 		r.from--;
777 	else if (new->from == new->to)
778 		r.from = old->from;
779 
780 	/*
781 	 * If the range is a 3 way merge then we need to skip a line in the
782 	 * trailing output.
783 	 */
784 	if (de[n-1].type == DIFF_TYPE3)
785 		r.from++;
786 
787 	r.to = INT_MAX;
788 	printrange(fp[0], &r);
789 	exit(overlapcnt > 0);
790 }
791 
792 static void
793 increase(void)
794 {
795 	struct diff *p;
796 	char *q;
797 	size_t newsz, incr;
798 
799 	/* are the memset(3) calls needed? */
800 	newsz = szchanges == 0 ? 64 : 2 * szchanges;
801 	incr = newsz - szchanges;
802 
803 	p = reallocarray(d13, newsz, sizeof(struct diff));
804 	if (p == NULL)
805 		err(1, NULL);
806 	memset(p + szchanges, 0, incr * sizeof(struct diff));
807 	d13 = p;
808 	p = reallocarray(d23, newsz, sizeof(struct diff));
809 	if (p == NULL)
810 		err(1, NULL);
811 	memset(p + szchanges, 0, incr * sizeof(struct diff));
812 	d23 = p;
813 	p = reallocarray(de, newsz, sizeof(struct diff));
814 	if (p == NULL)
815 		err(1, NULL);
816 	memset(p + szchanges, 0, incr * sizeof(struct diff));
817 	de = p;
818 	q = reallocarray(overlap, newsz, sizeof(char));
819 	if (q == NULL)
820 		err(1, NULL);
821 	memset(q + szchanges, 0, incr * sizeof(char));
822 	overlap = q;
823 	szchanges = newsz;
824 }
825 
826 
827 int
828 main(int argc, char **argv)
829 {
830 	int ch, nblabels, status, m, n, kq, nke, nleft, i;
831 	char *labels[] = { NULL, NULL, NULL };
832 	const char *diffprog = DIFF_PATH;
833 	char *file1, *file2, *file3;
834 	char *diffargv[7];
835 	int diffargc = 0;
836 	int fd13[2], fd23[2];
837 	int pd13, pd23;
838 	cap_rights_t rights_ro;
839 	struct kevent *e;
840 
841 	nblabels = 0;
842 	eflag = EFLAG_NONE;
843 	oflag = 0;
844 	diffargv[diffargc++] = __DECONST(char *, diffprog);
845 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
846 		switch (ch) {
847 		case '3':
848 			eflag = EFLAG_NOOVERLAP;
849 			break;
850 		case 'a':
851 			diffargv[diffargc++] = __DECONST(char *, "-a");
852 			break;
853 		case 'A':
854 			Aflag = 1;
855 			break;
856 		case 'e':
857 			eflag = EFLAG_UNMERGED;
858 			break;
859 		case 'E':
860 			eflag = EFLAG_OVERLAP;
861 			oflag = 1;
862 			break;
863 		case 'i':
864 			iflag = 1;
865 			break;
866 		case 'L':
867 			oflag = 1;
868 			if (nblabels >= 3)
869 				errx(2, "too many file label options");
870 			labels[nblabels++] = optarg;
871 			break;
872 		case 'm':
873 			Aflag = 1;
874 			oflag = 1;
875 			mflag = 1;
876 			break;
877 		case 'T':
878 			Tflag = 1;
879 			break;
880 		case 'x':
881 			eflag = EFLAG_OVERLAP;
882 			break;
883 		case 'X':
884 			oflag = 1;
885 			eflag = EFLAG_OVERLAP;
886 			break;
887 		case DIFFPROG_OPT:
888 			diffprog = optarg;
889 			break;
890 		case STRIPCR_OPT:
891 			strip_cr = 1;
892 			diffargv[diffargc++] = __DECONST(char *, "--strip-trailing-cr");
893 			break;
894 		case HELP_OPT:
895 			usage();
896 			exit(0);
897 		case VERSION_OPT:
898 			printf("%s\n", diff3_version);
899 			exit(0);
900 		}
901 	}
902 	argc -= optind;
903 	argv += optind;
904 
905 	if (Aflag) {
906 		if (eflag == EFLAG_NONE)
907 			eflag = EFLAG_UNMERGED;
908 		oflag = 1;
909 	}
910 
911 	if (argc != 3) {
912 		usage();
913 		exit(2);
914 	}
915 
916 	if (caph_limit_stdio() == -1)
917 		err(2, "unable to limit stdio");
918 
919 	cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
920 
921 	kq = kqueue();
922 	if (kq == -1)
923 		err(2, "kqueue");
924 
925 	e = malloc(2 * sizeof(struct kevent));
926 	if (e == NULL)
927 		err(2, "malloc");
928 
929 	/* TODO stdio */
930 	file1 = argv[0];
931 	file2 = argv[1];
932 	file3 = argv[2];
933 
934 	if (oflag) {
935 		asprintf(&f1mark, "%s",
936 		    labels[0] != NULL ? labels[0] : file1);
937 		if (f1mark == NULL)
938 			err(2, "asprintf");
939 		asprintf(&f2mark, "%s",
940 		    labels[1] != NULL ? labels[1] : file2);
941 		if (f2mark == NULL)
942 			err(2, "asprintf");
943 		asprintf(&f3mark, "%s",
944 		    labels[2] != NULL ? labels[2] : file3);
945 		if (f3mark == NULL)
946 			err(2, "asprintf");
947 	}
948 	fp[0] = fopen(file1, "r");
949 	if (fp[0] == NULL)
950 		err(2, "Can't open %s", file1);
951 	if (caph_rights_limit(fileno(fp[0]), &rights_ro) < 0)
952 		err(2, "unable to limit rights on: %s", file1);
953 
954 	fp[1] = fopen(file2, "r");
955 	if (fp[1] == NULL)
956 		err(2, "Can't open %s", file2);
957 	if (caph_rights_limit(fileno(fp[1]), &rights_ro) < 0)
958 		err(2, "unable to limit rights on: %s", file2);
959 
960 	fp[2] = fopen(file3, "r");
961 	if (fp[2] == NULL)
962 		err(2, "Can't open %s", file3);
963 	if (caph_rights_limit(fileno(fp[2]), &rights_ro) < 0)
964 		err(2, "unable to limit rights on: %s", file3);
965 
966 	if (pipe(fd13))
967 		err(2, "pipe");
968 	if (pipe(fd23))
969 		err(2, "pipe");
970 
971 	diffargv[diffargc] = file1;
972 	diffargv[diffargc + 1] = file3;
973 	diffargv[diffargc + 2] = NULL;
974 
975 	nleft = 0;
976 	pd13 = diffexec(diffprog, diffargv, fd13);
977 	EV_SET(e + nleft , pd13, EVFILT_PROCDESC, EV_ADD, NOTE_EXIT, 0, NULL);
978 	if (kevent(kq, e + nleft, 1, NULL, 0, NULL) == -1)
979 		err(2, "kevent1");
980 	nleft++;
981 
982 	diffargv[diffargc] = file2;
983 	pd23 = diffexec(diffprog, diffargv, fd23);
984 	EV_SET(e + nleft , pd23, EVFILT_PROCDESC, EV_ADD, NOTE_EXIT, 0, NULL);
985 	if (kevent(kq, e + nleft, 1, NULL, 0, NULL) == -1)
986 		err(2, "kevent2");
987 	nleft++;
988 
989 	caph_cache_catpages();
990 	if (caph_enter() < 0)
991 		err(2, "unable to enter capability mode");
992 
993 	/* parse diffs */
994 	increase();
995 	m = readin(fd13[0], &d13);
996 	n = readin(fd23[0], &d23);
997 
998 	/* waitpid cooked over pdforks */
999 	while (nleft > 0) {
1000 		nke = kevent(kq, NULL, 0, e, nleft, NULL);
1001 		if (nke == -1)
1002 			err(2, "kevent");
1003 		for (i = 0; i < nke; i++) {
1004 			status = e[i].data;
1005 			if (WIFEXITED(status) && WEXITSTATUS(status) >= 2)
1006 				errx(2, "diff exited abnormally");
1007 			else if (WIFSIGNALED(status))
1008 				errx(2, "diff killed by signal %d",
1009 				    WTERMSIG(status));
1010 		}
1011 		nleft -= nke;
1012 	}
1013 	merge(m, n);
1014 
1015 	return (EXIT_SUCCESS);
1016 }
1017