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