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