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