1 /* $OpenBSD: diff3prog.c,v 1.11 2009/10/27 23:59:37 deraadt Exp $ */
4 * Copyright (C) Caldera International Inc. 2001-2002.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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.
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.
37 * Copyright (c) 1991, 1993
38 * The Regents of the University of California. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
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.
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
65 #include <sys/capsicum.h>
66 #include <sys/procdesc.h>
67 #include <sys/types.h>
68 #include <sys/event.h>
71 #include <capsicum_helpers.h>
84 * "from" is first in range of changed lines; "to" is last+1
85 * from=to=line after point of insertion for added lines.
100 /* Ranges as lines */
106 #define EFLAG_OVERLAP 1
107 #define EFLAG_NOOVERLAP 2
108 #define EFLAG_UNMERGED 3
110 static size_t szchanges;
112 static struct diff *d13;
113 static struct diff *d23;
115 * "de" is used to gather editing scripts. These are later spewed out in
116 * reverse order. Its first element must be all zero, the "old" and "new"
117 * components of "de" contain line positions. Array overlap indicates which
118 * sections in "de" correspond to lines that are different in all three files.
120 static struct diff *de;
121 static char *overlap;
122 static int overlapcnt;
124 static int cline[3]; /* # of the last-read line in each file (0-2) */
126 * The latest known correspondence between line numbers of the 3 files
127 * is stored in last[1-3];
130 static int Aflag, eflag, iflag, mflag, Tflag;
131 static int oflag; /* indicates whether to mark overlaps (-E or -X) */
133 static char *f1mark, *f2mark, *f3mark;
134 static const char *oldmark = "<<<<<<<";
135 static const char *orgmark = "|||||||";
136 static const char *newmark = ">>>>>>>";
137 static const char *divider = "=======";
139 static bool duplicate(struct range *, struct range *);
140 static int edit(struct diff *, bool, int, int);
141 static char *getchange(FILE *);
142 static char *get_line(FILE *, size_t *);
143 static int readin(int fd, struct diff **);
144 static int skip(int, int, const char *);
145 static void change(int, struct range *, bool);
146 static void keep(int, struct range *);
147 static void merge(int, int);
148 static void prange(struct range *, bool);
149 static void repos(int);
150 static void edscript(int) __dead2;
151 static void Ascript(int) __dead2;
152 static void mergescript(int) __dead2;
153 static void increase(void);
154 static void usage(void);
155 static void printrange(FILE *, struct range *);
157 static const char diff3_version[] = "FreeBSD diff3 20220517";
166 #define DIFF_PATH "/usr/bin/diff"
168 #define OPTIONS "3aAeEiL:mTxX"
169 static struct option longopts[] = {
170 { "ed", no_argument, NULL, 'e' },
171 { "show-overlap", no_argument, NULL, 'E' },
172 { "overlap-only", no_argument, NULL, 'x' },
173 { "initial-tab", no_argument, NULL, 'T' },
174 { "text", no_argument, NULL, 'a' },
175 { "strip-trailing-cr", no_argument, NULL, STRIPCR_OPT },
176 { "show-all", no_argument, NULL, 'A' },
177 { "easy-only", no_argument, NULL, '3' },
178 { "merge", no_argument, NULL, 'm' },
179 { "label", required_argument, NULL, 'L' },
180 { "diff-program", required_argument, NULL, DIFFPROG_OPT },
181 { "help", no_argument, NULL, HELP_OPT},
182 { "version", no_argument, NULL, VERSION_OPT}
188 fprintf(stderr, "usage: diff3 [-3aAeEimTxX] [-L label1] [-L label2] "
189 "[-L label3] file1 file2 file3\n");
193 readin(int fd, struct diff **dd)
203 for (i = 0; (p = getchange(f)); i++) {
205 (*dd)[i].line = strdup(p);
208 if (i >= szchanges - 1)
210 a = b = (int)strtoimax(p, &p, 10);
213 b = (int)strtoimax(p, &p, 10);
216 c = d = (int)strtoimax(p, &p, 10);
219 d = (int)strtoimax(p, &p, 10);
227 (*dd)[i].old.from = a;
229 (*dd)[i].new.from = c;
233 (*dd)[i].old.from = (*dd)[i - 1].old.to;
234 (*dd)[i].new.from = (*dd)[i - 1].new.to;
241 diffexec(const char *diffprog, char **diffargv, int fd[])
245 switch (pdfork(&pd, PD_CLOEXEC)) {
248 if (dup2(fd[1], STDOUT_FILENO) == -1)
249 err(2, "child could not duplicate descriptor");
251 execvp(diffprog, diffargv);
252 err(2, "could not execute diff: %s", diffprog);
255 err(2, "could not fork");
267 while ((line = get_line(b, NULL))) {
268 if (isdigit((unsigned char)line[0]))
276 get_line(FILE *b, size_t *n)
279 static char *buf = NULL;
280 static size_t bufsize = 0;
282 if ((len = getline(&buf, &bufsize, b)) < 0)
285 if (strip_cr && len >= 2 && strcmp("\r\n", &(buf[len - 2])) == 0) {
298 merge(int m1, int m2)
300 struct diff *d1, *d2, *d3;
308 while (t1 = d1 < d13 + m1, t2 = d2 < d23 + m2, t1 || t2) {
309 /* first file is different from the others */
310 if (!t2 || (t1 && d1->new.to < d2->new.from)) {
311 /* stuff peculiar to 1st file */
312 if (eflag == EFLAG_NONE) {
314 change(1, &d1->old, false);
316 change(3, &d1->new, false);
321 /* second file is different from others */
322 if (!t1 || (t2 && d2->new.to < d1->new.from)) {
323 if (eflag == EFLAG_NONE) {
326 change(3, &d2->new, false);
327 change(2, &d2->old, false);
328 } else if (Aflag || mflag) {
329 // XXX-THJ: What does it mean for the second file to differ?
330 if (eflag == EFLAG_UNMERGED)
331 j = edit(d2, dup, j, DIFF_TYPE2);
337 * Merge overlapping changes in first file
338 * this happens after extension (see below).
340 if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
341 d1[1].old.from = d1->old.from;
342 d1[1].new.from = d1->new.from;
347 /* merge overlapping changes in second */
348 if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
349 d2[1].old.from = d2->old.from;
350 d2[1].new.from = d2->new.from;
354 /* stuff peculiar to third file or different in all */
355 if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
356 dup = duplicate(&d1->old, &d2->old);
358 * dup = 0 means all files differ
359 * dup = 1 means files 1 and 2 identical
361 if (eflag == EFLAG_NONE) {
362 printf("====%s\n", dup ? "3" : "");
363 change(1, &d1->old, dup);
364 change(2, &d2->old, false);
365 d3 = d1->old.to > d1->old.from ? d1 : d2;
366 change(3, &d3->new, false);
368 j = edit(d1, dup, j, DIFF_TYPE3);
376 * Overlapping changes from file 1 and 2; extend changes
377 * appropriately to make them coincide.
379 if (d1->new.from < d2->new.from) {
380 d2->old.from -= d2->new.from - d1->new.from;
381 d2->new.from = d1->new.from;
382 } else if (d2->new.from < d1->new.from) {
383 d1->old.from -= d1->new.from - d2->new.from;
384 d1->new.from = d2->new.from;
386 if (d1->new.to > d2->new.to) {
387 d2->old.to += d1->new.to - d2->new.to;
388 d2->new.to = d1->new.to;
389 } else if (d2->new.to > d1->new.to) {
390 d1->old.to += d2->new.to - d1->new.to;
391 d1->new.to = d2->new.to;
404 * The range of lines rold.from thru rold.to in file i is to be changed.
405 * It is to be printed only if it does not duplicate something to be
409 change(int i, struct range *rold, bool dup)
418 skip(i, rold->from, NULL);
419 skip(i, rold->to, " ");
423 * Print the range of line numbers, rold.from thru rold.to, as n1,n2 or
427 prange(struct range *rold, bool delete)
430 if (rold->to <= rold->from)
431 printf("%da\n", rold->from - 1);
433 printf("%d", rold->from);
434 if (rold->to > rold->from + 1)
435 printf(",%d", rold->to - 1);
444 * No difference was reported by diff between file 1 (or 2) and file 3,
445 * and an artificial dummy difference (trange) must be ginned up to
446 * correspond to the change reported in the other file.
449 keep(int i, struct range *rnew)
454 delta = last[3] - last[i];
455 trange.from = rnew->from - delta;
456 trange.to = rnew->to - delta;
457 change(i, &trange, true);
461 * skip to just before line number from in file "i". If "pr" is non-NULL,
462 * print all skipped stuff with string pr as a prefix.
465 skip(int i, int from, const char *pr)
470 for (n = 0; cline[i] < from - 1; n += j) {
471 if ((line = get_line(fp[i], &j)) == NULL)
472 errx(EXIT_FAILURE, "logic error");
474 printf("%s%s", Tflag == 1 ? "\t" : pr, line);
481 * Return 1 or 0 according as the old range (in file 1) contains exactly
482 * the same data as the new range (in file 2).
485 duplicate(struct range *r1, struct range *r2)
491 if (r1->to-r1->from != r2->to-r2->from)
493 skip(0, r1->from, NULL);
494 skip(1, r2->from, NULL);
496 for (nline = 0; nline < r1->to - r1->from; nline++) {
500 if (c == -1 && d == -1)
502 if (c == -1 || d == -1)
503 errx(EXIT_FAILURE, "logic error");
520 for (i = 0; i < 2; i++)
521 (void)fseek(fp[i], (long)-nchar, SEEK_CUR);
525 * collect an editing script for later regurgitation
528 edit(struct diff *diff, bool dup, int j, int difftype)
530 if (!(eflag == EFLAG_UNMERGED ||
531 (!dup && eflag == EFLAG_OVERLAP ) ||
532 (dup && eflag == EFLAG_NOOVERLAP))) {
540 de[j].type = difftype;
542 de[j].line = strdup(diff->line);
545 de[j].old.from = diff->old.from;
546 de[j].old.to = diff->old.to;
547 de[j].new.from = diff->new.from;
548 de[j].new.to = diff->new.to;
553 printrange(FILE *p, struct range *r)
560 /* We haven't been asked to print anything */
561 if (r->from == r->to)
565 errx(EXIT_FAILURE, "invalid print range");
568 * XXX-THJ: We read through all of the file for each range printed.
569 * This duplicates work and will probably impact performance on large
570 * files with lots of ranges.
572 fseek(p, 0L, SEEK_SET);
573 while ((rlen = getline(&line, &len, p)) > 0) {
587 struct range *new, *old;
593 delete = (new->from == new->to);
594 if (!oflag || !overlap[n]) {
597 printf("%da\n", old->to - 1);
598 printf("%s\n", divider);
600 printrange(fp[2], new);
601 if (!oflag || !overlap[n]) {
605 printf("%s %s\n.\n", newmark, f3mark);
606 printf("%da\n%s %s\n.\n", old->from - 1,
613 exit(eflag == EFLAG_NONE ? overlapcnt : 0);
617 * Output an edit script to turn mine into yours, when there is a conflict
618 * between the 3 files bracket the changes. Regurgitate the diffs in reverse
619 * order to allow the ed script to track down where the lines are as changes
629 struct range *new, *old;
634 deletenew = (new->from == new->to);
635 deleteold = (old->from == old->to);
637 if (de[n].type == DIFF_TYPE2) {
638 if (!oflag || !overlap[n]) {
639 prange(old, deletenew);
640 printrange(fp[2], new);
647 printf("%da\n", startmark);
648 printf("%s %s\n", newmark, f3mark);
652 printf("%da\n", startmark -
653 (new->to - new->from));
654 printf("%s %s\n", oldmark, f2mark);
656 printrange(fp[1], old);
657 printf("%s\n.\n", divider);
660 } else if (de[n].type == DIFF_TYPE3) {
661 startmark = old->to - 1;
663 if (!oflag || !overlap[n]) {
664 prange(old, deletenew);
665 printrange(fp[2], new);
667 printf("%da\n", startmark);
668 printf("%s %s\n", orgmark, f2mark);
672 r.from = old->from-1;
674 printrange(fp[1], &r);
676 printrange(fp[1], old);
678 printf("%s\n", divider);
679 printrange(fp[2], new);
682 if (!oflag || !overlap[n]) {
686 printf("%s %s\n.\n", newmark, f3mark);
689 * Go to the start of the conflict in original
690 * file and append lines
692 printf("%da\n%s %s\n.\n",
693 startmark - (old->to - old->from),
701 exit(overlapcnt > 0);
705 * Output the merged file directly (don't generate an ed script). When
706 * regurgitating diffs we need to walk forward through the file and print any
712 struct range r, *new, *old;
718 for (n = 1; n < i+1; n++) {
722 /* print any lines leading up to here */
724 printrange(fp[0], &r);
726 if (de[n].type == DIFF_TYPE2) {
727 printf("%s %s\n", oldmark, f2mark);
728 printrange(fp[1], old);
729 printf("%s\n", divider);
730 printrange(fp[2], new);
731 printf("%s %s\n", newmark, f3mark);
732 } else if (de[n].type == DIFF_TYPE3) {
733 if (!oflag || !overlap[n]) {
734 printrange(fp[2], new);
737 printf("%s %s\n", oldmark, f1mark);
738 printrange(fp[0], old);
740 printf("%s %s\n", orgmark, f2mark);
741 if (old->from == old->to) {
743 or.from = old->from - 1;
745 printrange(fp[1], &or);
747 printrange(fp[1], old);
749 printf("%s\n", divider);
751 printrange(fp[2], new);
752 printf("%s %s\n", newmark, f3mark);
756 if (old->from == old->to)
762 * Print from the final range to the end of 'myfile'. Any deletions or
763 * additions to this file should have been handled by now.
765 * If the ranges are the same we need to rewind a line.
766 * If the new range is 0 length (from == to), we need to use the old
771 if ((old->from == new->from) &&
772 (old->to == new->to))
774 else if (new->from == new->to)
778 * If the range is a 3 way merge then we need to skip a line in the
781 if (de[n-1].type == DIFF_TYPE3)
785 printrange(fp[0], &r);
786 exit(overlapcnt > 0);
796 /* are the memset(3) calls needed? */
797 newsz = szchanges == 0 ? 64 : 2 * szchanges;
798 incr = newsz - szchanges;
800 p = reallocarray(d13, newsz, sizeof(struct diff));
803 memset(p + szchanges, 0, incr * sizeof(struct diff));
805 p = reallocarray(d23, newsz, sizeof(struct diff));
808 memset(p + szchanges, 0, incr * sizeof(struct diff));
810 p = reallocarray(de, newsz, sizeof(struct diff));
813 memset(p + szchanges, 0, incr * sizeof(struct diff));
815 q = reallocarray(overlap, newsz, sizeof(char));
818 memset(q + szchanges, 0, incr * sizeof(char));
825 main(int argc, char **argv)
827 int ch, nblabels, status, m, n, kq, nke, nleft, i;
828 char *labels[] = { NULL, NULL, NULL };
829 const char *diffprog = DIFF_PATH;
830 char *file1, *file2, *file3;
833 int fd13[2], fd23[2];
835 cap_rights_t rights_ro;
841 diffargv[diffargc++] = __DECONST(char *, diffprog);
842 while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
845 eflag = EFLAG_NOOVERLAP;
848 diffargv[diffargc++] = __DECONST(char *, "-a");
854 eflag = EFLAG_UNMERGED;
857 eflag = EFLAG_OVERLAP;
866 errx(2, "too many file label options");
867 labels[nblabels++] = optarg;
878 eflag = EFLAG_OVERLAP;
882 eflag = EFLAG_OVERLAP;
889 diffargv[diffargc++] = __DECONST(char *, "--strip-trailing-cr");
895 printf("%s\n", diff3_version);
903 if (eflag == EFLAG_NONE)
904 eflag = EFLAG_UNMERGED;
913 if (caph_limit_stdio() == -1)
914 err(2, "unable to limit stdio");
916 cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
922 e = malloc(2 * sizeof(struct kevent));
932 asprintf(&f1mark, "%s",
933 labels[0] != NULL ? labels[0] : file1);
936 asprintf(&f2mark, "%s",
937 labels[1] != NULL ? labels[1] : file2);
940 asprintf(&f3mark, "%s",
941 labels[2] != NULL ? labels[2] : file3);
945 fp[0] = fopen(file1, "r");
947 err(2, "Can't open %s", file1);
948 if (caph_rights_limit(fileno(fp[0]), &rights_ro) < 0)
949 err(2, "unable to limit rights on: %s", file1);
951 fp[1] = fopen(file2, "r");
953 err(2, "Can't open %s", file2);
954 if (caph_rights_limit(fileno(fp[1]), &rights_ro) < 0)
955 err(2, "unable to limit rights on: %s", file2);
957 fp[2] = fopen(file3, "r");
959 err(2, "Can't open %s", file3);
960 if (caph_rights_limit(fileno(fp[2]), &rights_ro) < 0)
961 err(2, "unable to limit rights on: %s", file3);
968 diffargv[diffargc] = file1;
969 diffargv[diffargc + 1] = file3;
970 diffargv[diffargc + 2] = NULL;
973 pd13 = diffexec(diffprog, diffargv, fd13);
974 EV_SET(e + nleft , pd13, EVFILT_PROCDESC, EV_ADD, NOTE_EXIT, 0, NULL);
975 if (kevent(kq, e + nleft, 1, NULL, 0, NULL) == -1)
979 diffargv[diffargc] = file2;
980 pd23 = diffexec(diffprog, diffargv, fd23);
981 EV_SET(e + nleft , pd23, EVFILT_PROCDESC, EV_ADD, NOTE_EXIT, 0, NULL);
982 if (kevent(kq, e + nleft, 1, NULL, 0, NULL) == -1)
986 caph_cache_catpages();
987 if (caph_enter() < 0)
988 err(2, "unable to enter capability mode");
992 m = readin(fd13[0], &d13);
993 n = readin(fd23[0], &d23);
995 /* waitpid cooked over pdforks */
997 nke = kevent(kq, NULL, 0, e, nleft, NULL);
1000 for (i = 0; i < nke; i++) {
1002 if (WIFEXITED(status) && WEXITSTATUS(status) >= 2)
1003 errx(2, "diff exited abnormally");
1004 else if (WIFSIGNALED(status))
1005 errx(2, "diff killed by signal %d",
1012 return (EXIT_SUCCESS);