1 /* $OpenBSD: diffreg.c,v 1.91 2016/03/01 20:57:35 natano Exp $ */
4 * SPDX-License-Identifier: BSD-4-Clause
6 * Copyright (C) Caldera International Inc. 2001-2002.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code and documentation must retain the above
13 * copyright notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed or owned by Caldera
21 * 4. Neither the name of Caldera International, Inc. nor the names of other
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
25 * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
26 * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR ANY DIRECT,
30 * INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
31 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
35 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
39 * Copyright (c) 1991, 1993
40 * The Regents of the University of California. All rights reserved.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)diffreg.c 8.1 (Berkeley) 6/6/93
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
72 #include <sys/capsicum.h>
75 #include <capsicum_helpers.h>
93 * diff - compare two files.
97 * Uses an algorithm due to Harold Stone, which finds
98 * a pair of longest identical subsequences in the two
101 * The major goal is to generate the match vector J.
102 * J[i] is the index of the line in file1 corresponding
103 * to line i file0. J[i] = 0 if there is no
104 * such line in file1.
106 * Lines are hashed so as to work in core. All potential
107 * matches are located by sorting the lines of each file
108 * on the hash (called ``value''). In particular, this
109 * collects the equivalence classes in file1 together.
110 * Subroutine equiv replaces the value of each line in
111 * file0 by the index of the first element of its
112 * matching equivalence in (the reordered) file1.
113 * To save space equiv squeezes file1 into a single
114 * array member in which the equivalence classes
115 * are simply concatenated, except that their first
116 * members are flagged by changing sign.
118 * Next the indices that point into member are unsorted into
119 * array class according to the original order of file0.
121 * The cleverness lies in routine stone. This marches
122 * through the lines of file0, developing a vector klist
123 * of "k-candidates". At step i a k-candidate is a matched
124 * pair of lines x,y (x in file0 y in file1) such that
125 * there is a common subsequence of length k
126 * between the first i lines of file0 and the first y
127 * lines of file1, but there is no such subsequence for
128 * any smaller y. x is the earliest possible mate to y
129 * that occurs in such a subsequence.
131 * Whenever any of the members of the equivalence class of
132 * lines in file1 matable to a line in file0 has serial number
133 * less than the y of some k-candidate, that k-candidate
134 * with the smallest such y is replaced. The new
135 * k-candidate is chained (via pred) to the current
136 * k-1 candidate so that the actual subsequence can
137 * be recovered. When a member has serial number greater
138 * that the y of all k-candidates, the klist is extended.
139 * At the end, the longest subsequence is pulled out
140 * and placed in the array J by unravel
142 * With J in hand, the matches there recorded are
143 * check'ed against reality to assure that no spurious
144 * matches have crept in due to hashing. If they have,
145 * they are broken, and "jackpot" is recorded--a harmless
146 * matter except that a true match for a spuriously
147 * mated line may now be unnecessarily reported as a change.
149 * Much of the complexity of the program comes simply
150 * from trying to minimize core utilization and
151 * maximize the range of doable problems by dynamically
152 * allocating what is needed and reusing what is not.
153 * The core requirements for problems larger than somewhat
154 * are (in words) 2*length(file0) + length(file1) +
155 * 3*(number of k-candidates installed), typically about
156 * 6n words for files of length n.
171 * The following struct is used to record change information when
172 * doing a "context" or "unified" diff. (see routine "change" to
173 * understand the highly mnemonic field names)
176 int a; /* start line in old file */
177 int b; /* end line in old file */
178 int c; /* start line in new file */
179 int d; /* end line in new file */
182 #define diff_output printf
183 static FILE *opentemp(const char *);
184 static void output(char *, FILE *, char *, FILE *, int);
185 static void check(FILE *, FILE *, int);
186 static void range(int, int, const char *);
187 static void uni_range(int, int);
188 static void dump_context_vec(FILE *, FILE *, int);
189 static void dump_unified_vec(FILE *, FILE *, int);
190 static void prepare(int, FILE *, size_t, int);
191 static void prune(void);
192 static void equiv(struct line *, int, struct line *, int, int *);
193 static void unravel(int);
194 static void unsort(struct line *, int, int *);
195 static void change(char *, FILE *, char *, FILE *, int, int, int, int, int *);
196 static void sort(struct line *, int);
197 static void print_header(const char *, const char *);
198 static int ignoreline(char *);
199 static int asciifile(FILE *);
200 static int fetch(long *, int, int, FILE *, int, int, int);
201 static int newcand(int, int, int);
202 static int search(int *, int, int);
203 static int skipline(FILE *);
204 static int isqrt(int);
205 static int stone(int *, int, int *, int *, int);
206 static int readhash(FILE *, int);
207 static int files_differ(FILE *, FILE *, int);
208 static char *match_function(const long *, int, FILE *);
209 static char *preadline(int, size_t, off_t);
211 static int *J; /* will be overlaid on class */
212 static int *class; /* will be overlaid on file[0] */
213 static int *klist; /* will be overlaid on file[0] after class */
214 static int *member; /* will be overlaid on file[1] */
216 static int inifdef; /* whether or not we are in a #ifdef block */
218 static int pref, suff; /* length of prefix and suffix */
220 static int anychange;
221 static long *ixnew; /* will be overlaid on file[1] */
222 static long *ixold; /* will be overlaid on klist */
223 static struct cand *clist; /* merely a free storage pot for candidates */
224 static int clistlen; /* the length of clist */
225 static struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
226 static int (*chrtran)(int); /* translation table for case-folding */
227 static struct context_vec *context_vec_start;
228 static struct context_vec *context_vec_end;
229 static struct context_vec *context_vec_ptr;
231 #define FUNCTION_CONTEXT_SIZE 55
232 static char lastbuf[FUNCTION_CONTEXT_SIZE];
234 static int lastmatchline;
251 diffreg(char *file1, char *file2, int flags, int capsicum)
255 struct pr *pr = NULL;
256 cap_rights_t rights_ro;
263 context_vec_ptr = context_vec_start - 1;
264 if (flags & D_IGNORECASE)
268 if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
269 return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
270 if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
273 if (flags & D_EMPTY1)
274 f1 = fopen(_PATH_DEVNULL, "r");
276 if (!S_ISREG(stb1.st_mode)) {
277 if ((f1 = opentemp(file1)) == NULL ||
278 fstat(fileno(f1), &stb1) < 0) {
283 } else if (strcmp(file1, "-") == 0)
286 f1 = fopen(file1, "r");
294 if (flags & D_EMPTY2)
295 f2 = fopen(_PATH_DEVNULL, "r");
297 if (!S_ISREG(stb2.st_mode)) {
298 if ((f2 = opentemp(file2)) == NULL ||
299 fstat(fileno(f2), &stb2) < 0) {
304 } else if (strcmp(file2, "-") == 0)
307 f2 = fopen(file2, "r");
316 pr = start_pr(file1, file2);
319 cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
320 if (cap_rights_limit(fileno(f1), &rights_ro) < 0
322 err(2, "unable to limit rights on: %s", file1);
323 if (cap_rights_limit(fileno(f2), &rights_ro) < 0 &&
325 err(2, "unable to limit rights on: %s", file2);
326 if (fileno(f1) == STDIN_FILENO || fileno(f2) == STDIN_FILENO) {
327 /* stding has already been limited */
328 if (caph_limit_stderr() == -1)
329 err(2, "unable to limit stderr");
330 if (caph_limit_stdout() == -1)
331 err(2, "unable to limit stdout");
332 } else if (caph_limit_stdio() == -1)
333 err(2, "unable to limit stdio");
335 caph_cache_catpages();
337 if (caph_enter() < 0)
338 err(2, "unable to enter capability mode");
341 switch (files_differ(f1, f2, flags)) {
352 if ((flags & D_FORCEASCII) == 0 &&
353 (!asciifile(f1) || !asciifile(f2))) {
358 prepare(0, f1, stb1.st_size, flags);
359 prepare(1, f2, stb2.st_size, flags);
362 sort(sfile[0], slen[0]);
363 sort(sfile[1], slen[1]);
365 member = (int *)file[1];
366 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
367 member = xreallocarray(member, slen[1] + 2, sizeof(*member));
369 class = (int *)file[0];
370 unsort(sfile[0], slen[0], class);
371 class = xreallocarray(class, slen[0] + 2, sizeof(*class));
373 klist = xcalloc(slen[0] + 2, sizeof(*klist));
376 clist = xcalloc(clistlen, sizeof(*clist));
377 i = stone(class, slen[0], member, klist, flags);
381 J = xreallocarray(J, len[0] + 2, sizeof(*J));
386 ixold = xreallocarray(ixold, len[0] + 2, sizeof(*ixold));
387 ixnew = xreallocarray(ixnew, len[1] + 2, sizeof(*ixnew));
388 check(f1, f2, flags);
389 output(file1, f1, file2, f2, flags);
408 * Check to see if the given files differ.
409 * Returns 0 if they are the same, 1 if different, and -1 on error.
410 * XXX - could use code from cmp(1) [faster]
413 files_differ(FILE *f1, FILE *f2, int flags)
415 char buf1[BUFSIZ], buf2[BUFSIZ];
418 if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
419 (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
422 i = fread(buf1, 1, sizeof(buf1), f1);
423 j = fread(buf2, 1, sizeof(buf2), f2);
424 if ((!i && ferror(f1)) || (!j && ferror(f2)))
430 if (memcmp(buf1, buf2, i) != 0)
436 opentemp(const char *f)
438 char buf[BUFSIZ], tempfile[PATH_MAX];
442 if (strcmp(f, "-") == 0)
444 else if ((ifd = open(f, O_RDONLY, 0644)) < 0)
447 (void)strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile));
449 if ((ofd = mkstemp(tempfile)) < 0) {
454 while ((nread = read(ifd, buf, BUFSIZ)) > 0) {
455 if (write(ofd, buf, nread) != nread) {
462 lseek(ofd, (off_t)0, SEEK_SET);
463 return (fdopen(ofd, "r"));
467 splice(char *dir, char *path)
472 dirlen = strlen(dir);
473 while (dirlen != 0 && dir[dirlen - 1] == '/')
475 if ((tail = strrchr(path, '/')) == NULL)
479 xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);
484 prepare(int i, FILE *fd, size_t filesize, int flags)
492 sz = MIN(filesize, SIZE_MAX) / 25;
496 p = xcalloc(sz + 3, sizeof(*p));
497 for (j = 0; (h = readhash(fd, flags));) {
500 p = xreallocarray(p, sz + 3, sizeof(*p));
513 for (pref = 0; pref < len[0] && pref < len[1] &&
514 file[0][pref + 1].value == file[1][pref + 1].value;
517 for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
518 file[0][len[0] - suff].value == file[1][len[1] - suff].value;
521 for (j = 0; j < 2; j++) {
522 sfile[j] = file[j] + pref;
523 slen[j] = len[j] - pref - suff;
524 for (i = 0; i <= slen[j]; i++)
525 sfile[j][i].serial = i;
530 equiv(struct line *a, int n, struct line *b, int m, int *c)
535 while (i <= n && j <= m) {
536 if (a[i].value < b[j].value)
538 else if (a[i].value == b[j].value)
549 while (b[j + 1].value == b[j].value) {
557 /* Code taken from ping.c */
566 do { /* newton was a stinker */
571 } while ((x - y) > 1 || (x - y) < -1);
577 stone(int *a, int n, int *b, int *c, int flags)
580 int oldc, tc, oldl, sq;
581 u_int numtries, bound;
583 if (flags & D_MINIMAL)
587 bound = MAX(256, sq);
591 c[0] = newcand(0, 0, 0);
592 for (i = 1; i <= n; i++) {
601 if (y <= clist[oldc].y)
607 if (clist[c[l]].y <= y)
610 c[l] = newcand(i, y, oldc);
615 c[l] = newcand(i, y, oldc);
619 } while ((y = b[++j]) > 0 && numtries < bound);
625 newcand(int x, int y, int pred)
629 if (clen == clistlen) {
630 clistlen = clistlen * 11 / 10;
631 clist = xreallocarray(clist, clistlen, sizeof(*clist));
641 search(int *c, int k, int y)
645 if (clist[c[k]].y < y) /* quick look for typical case */
670 for (i = 0; i <= len[0]; i++)
671 J[i] = i <= pref ? i :
672 i > len[0] - suff ? i + len[1] - len[0] : 0;
673 for (q = clist + p; q->y != 0; q = clist + q->pred)
674 J[q->x + pref] = q->y + pref;
678 * Check does double duty:
679 * 1. ferret out any fortuitous correspondences due
680 * to confounding by hashing (which result in "jackpot")
681 * 2. collect random access indexes to the two files
684 check(FILE *f1, FILE *f2, int flags)
686 int i, j, jackpot, c, d;
692 ixold[0] = ixnew[0] = 0;
695 for (i = 1; i <= len[0]; i++) {
697 ixold[i] = ctold += skipline(f1);
701 ixnew[j] = ctnew += skipline(f2);
704 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_STRIPCR)) {
709 * GNU diff ignores a missing newline
710 * in one file for -b or -w.
712 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) {
713 if (c == EOF && d == '\n') {
716 } else if (c == '\n' && d == EOF) {
723 if (flags & D_STRIPCR && (c == '\r' || d == '\r')) {
725 if ((c = getc(f1)) == '\n') {
732 if ((d = getc(f2)) == '\n') {
740 if ((flags & D_FOLDBLANKS) && isspace(c) &&
746 } while (isspace(c = getc(f1)));
751 } while (isspace(d = getc(f2)));
752 } else if ((flags & D_IGNOREBLANKS)) {
753 while (isspace(c) && c != '\n') {
757 while (isspace(d) && d != '\n') {
762 if (chrtran(c) != chrtran(d)) {
765 if (c != '\n' && c != EOF)
766 ctold += skipline(f1);
767 if (d != '\n' && c != EOF)
768 ctnew += skipline(f2);
771 if (c == '\n' || c == EOF)
778 if ((c = getc(f1)) != (d = getc(f2))) {
781 if (c != '\n' && c != EOF)
782 ctold += skipline(f1);
783 if (d != '\n' && c != EOF)
784 ctnew += skipline(f2);
787 if (c == '\n' || c == EOF)
795 for (; j <= len[1]; j++) {
796 ixnew[j] = ctnew += skipline(f2);
800 * fprintf(stderr, "jackpot\n");
804 /* shellsort CACM #201 */
806 sort(struct line *a, int n)
808 struct line *ai, *aim, w;
813 for (j = 1; j <= n; j *= 2)
815 for (m /= 2; m != 0; m /= 2) {
817 for (j = 1; j <= k; j++) {
818 for (ai = &a[j]; ai > a; ai -= m) {
821 break; /* wraparound */
822 if (aim->value > ai[0].value ||
823 (aim->value == ai[0].value &&
824 aim->serial > ai[0].serial))
826 w.value = ai[0].value;
827 ai[0].value = aim->value;
828 aim->value = w.value;
829 w.serial = ai[0].serial;
830 ai[0].serial = aim->serial;
831 aim->serial = w.serial;
838 unsort(struct line *f, int l, int *b)
842 a = xcalloc(l + 1, sizeof(*a));
843 for (i = 1; i <= l; i++)
844 a[f[i].serial] = f[i].value;
845 for (i = 1; i <= l; i++)
855 for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
861 output(char *file1, FILE *f1, char *file2, FILE *f2, int flags)
863 int m, i0, i1, j0, j1;
869 J[m + 1] = len[1] + 1;
870 if (diff_format != D_EDIT) {
871 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
872 while (i0 <= m && J[i0] == J[i0 - 1] + 1)
876 while (i1 < m && J[i1 + 1] == 0)
880 change(file1, f1, file2, f2, i0, i1, j0, j1, &flags);
883 for (i0 = m; i0 >= 1; i0 = i1 - 1) {
884 while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0)
888 while (i1 > 1 && J[i1 - 1] == 0)
892 change(file1, f1, file2, f2, i1, i0, j1, j0, &flags);
896 change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags);
897 if (diff_format == D_IFDEF || diff_format == D_GFORMAT) {
900 if ((c = getc(f1)) == EOF)
902 diff_output("%c", c);
906 if (anychange != 0) {
907 if (diff_format == D_CONTEXT)
908 dump_context_vec(f1, f2, flags);
909 else if (diff_format == D_UNIFIED)
910 dump_unified_vec(f1, f2, flags);
915 range(int a, int b, const char *separator)
917 diff_output("%d", a > b ? b : a);
919 diff_output("%s%d", separator, b);
923 uni_range(int a, int b)
926 diff_output("%d,%d", a, b - a + 1);
928 diff_output("%d", b);
930 diff_output("%d,0", b);
934 preadline(int fd, size_t rlen, off_t off)
939 line = xmalloc(rlen + 1);
940 if ((nr = pread(fd, line, rlen, off)) < 0)
942 if (nr > 0 && line[nr-1] == '\n')
949 ignoreline(char *line)
953 ret = regexec(&ignore_re, line, 0, NULL, 0);
955 return (ret == 0); /* if it matched, it should be ignored. */
959 * Indicate that there is a difference between lines a and b of the from file
960 * to get to lines c to d of the to file. If a is greater then b then there
961 * are no lines in the from file involved and this means that there were
962 * lines appended (beginning at b). If c is greater than d then there are
963 * lines missing from the to file.
966 change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d,
969 static size_t max_context = 64;
975 if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) &&
978 if (ignore_pats != NULL) {
981 * All lines in the change, insert, or delete must
982 * match an ignore pattern for the change to be
985 if (a <= b) { /* Changes and deletes. */
986 for (i = a; i <= b; i++) {
987 line = preadline(fileno(f1),
988 ixold[i] - ixold[i - 1], ixold[i - 1]);
989 if (!ignoreline(line))
993 if (a > b || c <= d) { /* Changes and inserts. */
994 for (i = c; i <= d; i++) {
995 line = preadline(fileno(f2),
996 ixnew[i] - ixnew[i - 1], ixnew[i - 1]);
997 if (!ignoreline(line))
1004 if (*pflags & D_HEADER && diff_format != D_BRIEF) {
1005 diff_output("%s %s %s\n", diffargs, file1, file2);
1006 *pflags &= ~D_HEADER;
1008 if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) {
1010 * Allocate change records as needed.
1012 if (context_vec_ptr == context_vec_end - 1) {
1013 ptrdiff_t offset = context_vec_ptr - context_vec_start;
1015 context_vec_start = xreallocarray(context_vec_start,
1016 max_context, sizeof(*context_vec_start));
1017 context_vec_end = context_vec_start + max_context;
1018 context_vec_ptr = context_vec_start + offset;
1020 if (anychange == 0) {
1022 * Print the context/unidiff header first time through.
1024 print_header(file1, file2);
1026 } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 &&
1027 c > context_vec_ptr->d + (2 * diff_context) + 1) {
1029 * If this change is more than 'diff_context' lines from the
1030 * previous change, dump the record and reset it.
1032 if (diff_format == D_CONTEXT)
1033 dump_context_vec(f1, f2, *pflags);
1035 dump_unified_vec(f1, f2, *pflags);
1038 context_vec_ptr->a = a;
1039 context_vec_ptr->b = b;
1040 context_vec_ptr->c = c;
1041 context_vec_ptr->d = d;
1046 switch (diff_format) {
1052 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1053 if (diff_format == D_NORMAL)
1058 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1064 diff_output("a%d %d\n", b, d - c + 1);
1066 diff_output("d%d %d\n", a, b - a + 1);
1068 /* add changed lines */
1069 diff_output("a%d %d\n", b, d - c + 1);
1073 if (diff_format == D_GFORMAT) {
1075 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1076 nc = ixold[a > b ? b : a - 1] - curpos;
1077 for (i = 0; i < nc; i++)
1078 diff_output("%c", getc(f1));
1079 for (walk = group_format; *walk != '\0'; walk++) {
1084 fetch(ixold, a, b, f1, '<', 1, *pflags);
1087 fetch(ixnew, c, d, f2, '>', 0, *pflags);
1090 diff_output("%%%c", *walk);
1095 diff_output("%c", *walk);
1098 if (diff_format == D_NORMAL || diff_format == D_IFDEF) {
1099 fetch(ixold, a, b, f1, '<', 1, *pflags);
1100 if (a <= b && c <= d && diff_format == D_NORMAL)
1101 diff_output("---\n");
1104 if (diff_format != D_GFORMAT)
1105 f = fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags);
1106 if (f != 0 && diff_format == D_EDIT) {
1108 * A non-zero return value for D_EDIT indicates that the
1109 * last line printed was a bare dot (".") that has been
1110 * escaped as ".." to prevent ed(1) from misinterpreting
1111 * it. We have to add a substitute command to change this
1112 * back and restart where we left off.
1115 diff_output("%ds/.//\n", a + f - 1);
1121 if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d)
1124 diff_output("#endif /* %s */\n", ifdefname);
1130 fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags)
1132 int i, j, c, lastc, col, nc;
1136 * When doing #ifdef's, copy down to current line
1137 * if this is the first file, so that stuff makes it to output.
1139 if ((diff_format == D_IFDEF) && oldfile) {
1140 long curpos = ftell(lb);
1141 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1142 nc = f[a > b ? b : a - 1] - curpos;
1143 for (i = 0; i < nc; i++)
1144 diff_output("%c", getc(lb));
1148 if (diff_format == D_IFDEF) {
1150 diff_output("#else /* %s%s */\n",
1151 oldfile == 1 ? "!" : "", ifdefname);
1154 diff_output("#ifndef %s\n", ifdefname);
1156 diff_output("#ifdef %s\n", ifdefname);
1158 inifdef = 1 + oldfile;
1160 for (i = a; i <= b; i++) {
1161 fseek(lb, f[i - 1], SEEK_SET);
1162 nc = f[i] - f[i - 1];
1163 if ((diff_format != D_IFDEF && diff_format != D_GFORMAT) &&
1165 diff_output("%c", ch);
1166 if (Tflag && (diff_format == D_NORMAL || diff_format == D_CONTEXT
1167 || diff_format == D_UNIFIED))
1169 else if (diff_format != D_UNIFIED)
1173 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
1174 if ((c = getc(lb)) == EOF) {
1175 if (diff_format == D_EDIT || diff_format == D_REVERSE ||
1176 diff_format == D_NREVERSE)
1177 warnx("No newline at end of file");
1179 diff_output("\n\\ No newline at end of "
1183 if (c == '\t' && (flags & D_EXPANDTABS)) {
1184 newcol = ((col/tabsize)+1)*tabsize;
1187 } while (++col < newcol);
1189 if (diff_format == D_EDIT && j == 1 && c == '\n'
1192 * Don't print a bare "." line
1193 * since that will confuse ed(1).
1194 * Print ".." instead and return,
1195 * giving the caller an offset
1196 * from which to restart.
1201 diff_output("%c", c);
1210 * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
1213 readhash(FILE *f, int flags)
1220 if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) == 0) {
1221 if (flags & D_IGNORECASE)
1222 for (i = 0; (t = getc(f)) != '\n'; i++) {
1223 if (flags & D_STRIPCR && t == '\r') {
1234 sum = sum * 127 + chrtran(t);
1237 for (i = 0; (t = getc(f)) != '\n'; i++) {
1238 if (flags & D_STRIPCR && t == '\r') {
1249 sum = sum * 127 + t;
1253 switch (t = getc(f)) {
1262 if (space && (flags & D_IGNOREBLANKS) == 0) {
1266 sum = sum * 127 + chrtran(t);
1280 * There is a remote possibility that we end up with a zero sum.
1281 * Zero is used as an EOF marker, so return 1 instead.
1283 return (sum == 0 ? 1 : sum);
1289 unsigned char buf[BUFSIZ];
1296 cnt = fread(buf, 1, sizeof(buf), f);
1297 return (memchr(buf, '\0', cnt) == NULL);
1300 #define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
1303 match_function(const long *f, int pos, FILE *fp)
1305 unsigned char buf[FUNCTION_CONTEXT_SIZE];
1307 int last = lastline;
1308 const char *state = NULL;
1311 while (pos > last) {
1312 fseek(fp, f[pos - 1], SEEK_SET);
1313 nc = f[pos] - f[pos - 1];
1314 if (nc >= sizeof(buf))
1315 nc = sizeof(buf) - 1;
1316 nc = fread(buf, 1, nc, fp);
1319 buf[strcspn(buf, "\n")] = '\0';
1320 if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$') {
1321 if (begins_with(buf, "private:")) {
1323 state = " (private)";
1324 } else if (begins_with(buf, "protected:")) {
1326 state = " (protected)";
1327 } else if (begins_with(buf, "public:")) {
1329 state = " (public)";
1331 strlcpy(lastbuf, buf, sizeof lastbuf);
1333 strlcat(lastbuf, state,
1335 lastmatchline = pos;
1342 return lastmatchline > 0 ? lastbuf : NULL;
1345 /* dump accumulated "context" diff changes */
1347 dump_context_vec(FILE *f1, FILE *f2, int flags)
1349 struct context_vec *cvp = context_vec_start;
1350 int lowa, upb, lowc, upd, do_output;
1354 if (context_vec_start > context_vec_ptr)
1357 b = d = 0; /* gcc */
1358 lowa = MAX(1, cvp->a - diff_context);
1359 upb = MIN(len[0], context_vec_ptr->b + diff_context);
1360 lowc = MAX(1, cvp->c - diff_context);
1361 upd = MIN(len[1], context_vec_ptr->d + diff_context);
1363 diff_output("***************");
1364 if ((flags & D_PROTOTYPE)) {
1365 f = match_function(ixold, lowa-1, f1);
1367 diff_output(" %s", f);
1369 diff_output("\n*** ");
1370 range(lowa, upb, ",");
1371 diff_output(" ****\n");
1374 * Output changes to the "old" file. The first loop suppresses
1375 * output if there were no changes to the "old" file (we'll see
1376 * the "old" lines as context in the "new" list).
1379 for (; cvp <= context_vec_ptr; cvp++)
1380 if (cvp->a <= cvp->b) {
1381 cvp = context_vec_start;
1386 while (cvp <= context_vec_ptr) {
1392 if (a <= b && c <= d)
1395 ch = (a <= b) ? 'd' : 'a';
1398 fetch(ixold, lowa, b, f1, ' ', 0, flags);
1400 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1401 fetch(ixold, a, b, f1,
1402 ch == 'c' ? '!' : '-', 0, flags);
1407 fetch(ixold, b + 1, upb, f1, ' ', 0, flags);
1409 /* output changes to the "new" file */
1410 diff_output("--- ");
1411 range(lowc, upd, ",");
1412 diff_output(" ----\n");
1415 for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++)
1416 if (cvp->c <= cvp->d) {
1417 cvp = context_vec_start;
1422 while (cvp <= context_vec_ptr) {
1428 if (a <= b && c <= d)
1431 ch = (a <= b) ? 'd' : 'a';
1434 fetch(ixnew, lowc, d, f2, ' ', 0, flags);
1436 fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1437 fetch(ixnew, c, d, f2,
1438 ch == 'c' ? '!' : '+', 0, flags);
1443 fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1445 context_vec_ptr = context_vec_start - 1;
1448 /* dump accumulated "unified" diff changes */
1450 dump_unified_vec(FILE *f1, FILE *f2, int flags)
1452 struct context_vec *cvp = context_vec_start;
1453 int lowa, upb, lowc, upd;
1457 if (context_vec_start > context_vec_ptr)
1460 b = d = 0; /* gcc */
1461 lowa = MAX(1, cvp->a - diff_context);
1462 upb = MIN(len[0], context_vec_ptr->b + diff_context);
1463 lowc = MAX(1, cvp->c - diff_context);
1464 upd = MIN(len[1], context_vec_ptr->d + diff_context);
1466 diff_output("@@ -");
1467 uni_range(lowa, upb);
1469 uni_range(lowc, upd);
1471 if ((flags & D_PROTOTYPE)) {
1472 f = match_function(ixold, lowa-1, f1);
1474 diff_output(" %s", f);
1479 * Output changes in "unified" diff format--the old and new lines
1480 * are printed together.
1482 for (; cvp <= context_vec_ptr; cvp++) {
1489 * c: both new and old changes
1490 * d: only changes in the old file
1491 * a: only changes in the new file
1493 if (a <= b && c <= d)
1496 ch = (a <= b) ? 'd' : 'a';
1500 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1501 fetch(ixold, a, b, f1, '-', 0, flags);
1502 fetch(ixnew, c, d, f2, '+', 0, flags);
1505 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1506 fetch(ixold, a, b, f1, '-', 0, flags);
1509 fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1510 fetch(ixnew, c, d, f2, '+', 0, flags);
1516 fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1518 context_vec_ptr = context_vec_start - 1;
1522 print_header(const char *file1, const char *file2)
1524 const char *time_format;
1529 struct tm tm1, tm2, *tm_ptr1, *tm_ptr2;
1530 int nsec1 = stb1.st_mtim.tv_nsec;
1531 int nsec2 = stb2.st_mtim.tv_nsec;
1533 time_format = "%Y-%m-%d %H:%M:%S";
1537 tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1);
1538 tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2);
1539 strftime(buf1, 256, time_format, tm_ptr1);
1540 strftime(buf2, 256, time_format, tm_ptr2);
1542 strftime(end1, 10, "%z", tm_ptr1);
1543 strftime(end2, 10, "%z", tm_ptr2);
1544 sprintf(buf1, "%s.%.9d %s", buf1, nsec1, end1);
1545 sprintf(buf2, "%s.%.9d %s", buf2, nsec2, end2);
1547 if (label[0] != NULL)
1548 diff_output("%s %s\n", diff_format == D_CONTEXT ? "***" : "---",
1551 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "***" : "---",
1553 if (label[1] != NULL)
1554 diff_output("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++",
1557 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "---" : "+++",