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