1 /* $OpenBSD: diffreg.c,v 1.91 2016/03/01 20:57:35 natano 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
64 * @(#)diffreg.c 8.1 (Berkeley) 6/6/93
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
70 #include <sys/capsicum.h>
71 #include <sys/procdesc.h>
73 #include <sys/types.h>
74 #include <sys/event.h>
77 #include <capsicum_helpers.h>
97 #define _PATH_PR "/usr/bin/pr"
100 * diff - compare two files.
104 * Uses an algorithm due to Harold Stone, which finds
105 * a pair of longest identical subsequences in the two
108 * The major goal is to generate the match vector J.
109 * J[i] is the index of the line in file1 corresponding
110 * to line i file0. J[i] = 0 if there is no
111 * such line in file1.
113 * Lines are hashed so as to work in core. All potential
114 * matches are located by sorting the lines of each file
115 * on the hash (called ``value''). In particular, this
116 * collects the equivalence classes in file1 together.
117 * Subroutine equiv replaces the value of each line in
118 * file0 by the index of the first element of its
119 * matching equivalence in (the reordered) file1.
120 * To save space equiv squeezes file1 into a single
121 * array member in which the equivalence classes
122 * are simply concatenated, except that their first
123 * members are flagged by changing sign.
125 * Next the indices that point into member are unsorted into
126 * array class according to the original order of file0.
128 * The cleverness lies in routine stone. This marches
129 * through the lines of file0, developing a vector klist
130 * of "k-candidates". At step i a k-candidate is a matched
131 * pair of lines x,y (x in file0 y in file1) such that
132 * there is a common subsequence of length k
133 * between the first i lines of file0 and the first y
134 * lines of file1, but there is no such subsequence for
135 * any smaller y. x is the earliest possible mate to y
136 * that occurs in such a subsequence.
138 * Whenever any of the members of the equivalence class of
139 * lines in file1 matable to a line in file0 has serial number
140 * less than the y of some k-candidate, that k-candidate
141 * with the smallest such y is replaced. The new
142 * k-candidate is chained (via pred) to the current
143 * k-1 candidate so that the actual subsequence can
144 * be recovered. When a member has serial number greater
145 * that the y of all k-candidates, the klist is extended.
146 * At the end, the longest subsequence is pulled out
147 * and placed in the array J by unravel
149 * With J in hand, the matches there recorded are
150 * check'ed against reality to assure that no spurious
151 * matches have crept in due to hashing. If they have,
152 * they are broken, and "jackpot" is recorded--a harmless
153 * matter except that a true match for a spuriously
154 * mated line may now be unnecessarily reported as a change.
156 * Much of the complexity of the program comes simply
157 * from trying to minimize core utilization and
158 * maximize the range of doable problems by dynamically
159 * allocating what is needed and reusing what is not.
160 * The core requirements for problems larger than somewhat
161 * are (in words) 2*length(file0) + length(file1) +
162 * 3*(number of k-candidates installed), typically about
163 * 6n words for files of length n.
178 * The following struct is used to record change information when
179 * doing a "context" or "unified" diff. (see routine "change" to
180 * understand the highly mnemonic field names)
183 int a; /* start line in old file */
184 int b; /* end line in old file */
185 int c; /* start line in new file */
186 int d; /* end line in new file */
189 #define diff_output printf
190 static FILE *opentemp(const char *);
191 static void output(char *, FILE *, char *, FILE *, int);
192 static void check(FILE *, FILE *, int);
193 static void range(int, int, const char *);
194 static void uni_range(int, int);
195 static void dump_context_vec(FILE *, FILE *, int);
196 static void dump_unified_vec(FILE *, FILE *, int);
197 static void prepare(int, FILE *, size_t, int);
198 static void prune(void);
199 static void equiv(struct line *, int, struct line *, int, int *);
200 static void unravel(int);
201 static void unsort(struct line *, int, int *);
202 static void change(char *, FILE *, char *, FILE *, int, int, int, int, int *);
203 static void sort(struct line *, int);
204 static void print_header(const char *, const char *);
205 static bool ignoreline_pattern(char *);
206 static bool ignoreline(char *, bool);
207 static int asciifile(FILE *);
208 static int fetch(long *, int, int, FILE *, int, int, int);
209 static int newcand(int, int, int);
210 static int search(int *, int, int);
211 static int skipline(FILE *);
212 static int isqrt(int);
213 static int stone(int *, int, int *, int *, int);
214 static int readhash(FILE *, int);
215 static int files_differ(FILE *, FILE *, int);
216 static char *match_function(const long *, int, FILE *);
217 static char *preadline(int, size_t, off_t);
219 static int *J; /* will be overlaid on class */
220 static int *class; /* will be overlaid on file[0] */
221 static int *klist; /* will be overlaid on file[0] after class */
222 static int *member; /* will be overlaid on file[1] */
224 static int inifdef; /* whether or not we are in a #ifdef block */
226 static int pref, suff; /* length of prefix and suffix */
228 static int anychange;
229 static long *ixnew; /* will be overlaid on file[1] */
230 static long *ixold; /* will be overlaid on klist */
231 static struct cand *clist; /* merely a free storage pot for candidates */
232 static int clistlen; /* the length of clist */
233 static struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
234 static int (*chrtran)(int); /* translation table for case-folding */
235 static struct context_vec *context_vec_start;
236 static struct context_vec *context_vec_end;
237 static struct context_vec *context_vec_ptr;
239 #define FUNCTION_CONTEXT_SIZE 55
240 static char lastbuf[FUNCTION_CONTEXT_SIZE];
242 static int lastmatchline;
259 diffreg(char *file1, char *file2, int flags, int capsicum)
266 cap_rights_t rights_ro;
275 context_vec_ptr = context_vec_start - 1;
276 if (flags & D_IGNORECASE)
280 if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
281 return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
282 if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
285 if (flags & D_EMPTY1)
286 f1 = fopen(_PATH_DEVNULL, "r");
288 if (!S_ISREG(stb1.st_mode)) {
289 if ((f1 = opentemp(file1)) == NULL ||
290 fstat(fileno(f1), &stb1) < 0) {
295 } else if (strcmp(file1, "-") == 0)
298 f1 = fopen(file1, "r");
306 if (flags & D_EMPTY2)
307 f2 = fopen(_PATH_DEVNULL, "r");
309 if (!S_ISREG(stb2.st_mode)) {
310 if ((f2 = opentemp(file2)) == NULL ||
311 fstat(fileno(f2), &stb2) < 0) {
316 } else if (strcmp(file2, "-") == 0)
319 f2 = fopen(file2, "r");
328 /* redirect stdout to pr */
333 xasprintf(&header, "%s %s %s", diffargs, file1, file2);
334 signal(SIGPIPE, SIG_IGN);
338 switch ((pid = pdfork(&pr_pd, PD_CLOEXEC))) {
342 err(2, "No more processes");
345 if (pfd[0] != STDIN_FILENO) {
346 dup2(pfd[0], STDIN_FILENO);
350 execl(_PATH_PR, _PATH_PR, "-h", header, (char *)0);
355 if (pfd[1] != STDOUT_FILENO) {
356 ostdout = dup(STDOUT_FILENO);
357 dup2(pfd[1], STDOUT_FILENO);
366 e = xmalloc(sizeof(struct kevent));
367 EV_SET(e, pr_pd, EVFILT_PROCDESC, EV_ADD, NOTE_EXIT, 0,
369 if (kevent(kq, e, 1, NULL, 0, NULL) == -1)
375 cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
376 if (cap_rights_limit(fileno(f1), &rights_ro) < 0
378 err(2, "unable to limit rights on: %s", file1);
379 if (cap_rights_limit(fileno(f2), &rights_ro) < 0 &&
381 err(2, "unable to limit rights on: %s", file2);
382 if (fileno(f1) == STDIN_FILENO || fileno(f2) == STDIN_FILENO) {
383 /* stding has already been limited */
384 if (caph_limit_stderr() == -1)
385 err(2, "unable to limit stderr");
386 if (caph_limit_stdout() == -1)
387 err(2, "unable to limit stdout");
388 } else if (caph_limit_stdio() == -1)
389 err(2, "unable to limit stdio");
391 caph_cache_catpages();
393 if (cap_enter() < 0 && errno != ENOSYS)
394 err(2, "unable to enter capability mode");
397 switch (files_differ(f1, f2, flags)) {
408 if ((flags & D_FORCEASCII) == 0 &&
409 (!asciifile(f1) || !asciifile(f2))) {
414 prepare(0, f1, stb1.st_size, flags);
415 prepare(1, f2, stb2.st_size, flags);
418 sort(sfile[0], slen[0]);
419 sort(sfile[1], slen[1]);
421 member = (int *)file[1];
422 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
423 member = xreallocarray(member, slen[1] + 2, sizeof(*member));
425 class = (int *)file[0];
426 unsort(sfile[0], slen[0], class);
427 class = xreallocarray(class, slen[0] + 2, sizeof(*class));
429 klist = xcalloc(slen[0] + 2, sizeof(*klist));
432 clist = xcalloc(clistlen, sizeof(*clist));
433 i = stone(class, slen[0], member, klist, flags);
437 J = xreallocarray(J, len[0] + 2, sizeof(*J));
442 ixold = xreallocarray(ixold, len[0] + 2, sizeof(*ixold));
443 ixnew = xreallocarray(ixnew, len[1] + 2, sizeof(*ixnew));
444 check(f1, f2, flags);
445 output(file1, f1, file2, f2, flags);
446 if (ostdout != -1 && e != NULL) {
447 /* close the pipe to pr and restore stdout */
451 if (ostdout != STDOUT_FILENO) {
452 close(STDOUT_FILENO);
453 dup2(ostdout, STDOUT_FILENO);
456 if (kevent(kq, NULL, 0, e, 1, NULL) == -1)
460 if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0)
461 errx(2, "pr exited abnormally");
462 else if (WIFSIGNALED(wstatus))
463 errx(2, "pr killed by signal %d",
482 * Check to see if the given files differ.
483 * Returns 0 if they are the same, 1 if different, and -1 on error.
484 * XXX - could use code from cmp(1) [faster]
487 files_differ(FILE *f1, FILE *f2, int flags)
489 char buf1[BUFSIZ], buf2[BUFSIZ];
492 if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
493 (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
496 i = fread(buf1, 1, sizeof(buf1), f1);
497 j = fread(buf2, 1, sizeof(buf2), f2);
498 if ((!i && ferror(f1)) || (!j && ferror(f2)))
504 if (memcmp(buf1, buf2, i) != 0)
510 opentemp(const char *f)
512 char buf[BUFSIZ], tempfile[PATH_MAX];
516 if (strcmp(f, "-") == 0)
518 else if ((ifd = open(f, O_RDONLY, 0644)) < 0)
521 (void)strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile));
523 if ((ofd = mkstemp(tempfile)) < 0) {
528 while ((nread = read(ifd, buf, BUFSIZ)) > 0) {
529 if (write(ofd, buf, nread) != nread) {
536 lseek(ofd, (off_t)0, SEEK_SET);
537 return (fdopen(ofd, "r"));
541 splice(char *dir, char *path)
546 dirlen = strlen(dir);
547 while (dirlen != 0 && dir[dirlen - 1] == '/')
549 if ((tail = strrchr(path, '/')) == NULL)
553 xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);
558 prepare(int i, FILE *fd, size_t filesize, int flags)
566 sz = MIN(filesize, SIZE_MAX) / 25;
570 p = xcalloc(sz + 3, sizeof(*p));
571 for (j = 0; (h = readhash(fd, flags));) {
574 p = xreallocarray(p, sz + 3, sizeof(*p));
587 for (pref = 0; pref < len[0] && pref < len[1] &&
588 file[0][pref + 1].value == file[1][pref + 1].value;
591 for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
592 file[0][len[0] - suff].value == file[1][len[1] - suff].value;
595 for (j = 0; j < 2; j++) {
596 sfile[j] = file[j] + pref;
597 slen[j] = len[j] - pref - suff;
598 for (i = 0; i <= slen[j]; i++)
599 sfile[j][i].serial = i;
604 equiv(struct line *a, int n, struct line *b, int m, int *c)
609 while (i <= n && j <= m) {
610 if (a[i].value < b[j].value)
612 else if (a[i].value == b[j].value)
623 while (b[j + 1].value == b[j].value) {
631 /* Code taken from ping.c */
640 do { /* newton was a stinker */
645 } while ((x - y) > 1 || (x - y) < -1);
651 stone(int *a, int n, int *b, int *c, int flags)
654 int oldc, tc, oldl, sq;
655 u_int numtries, bound;
657 if (flags & D_MINIMAL)
661 bound = MAX(256, sq);
665 c[0] = newcand(0, 0, 0);
666 for (i = 1; i <= n; i++) {
675 if (y <= clist[oldc].y)
681 if (clist[c[l]].y <= y)
684 c[l] = newcand(i, y, oldc);
689 c[l] = newcand(i, y, oldc);
693 } while ((y = b[++j]) > 0 && numtries < bound);
699 newcand(int x, int y, int pred)
703 if (clen == clistlen) {
704 clistlen = clistlen * 11 / 10;
705 clist = xreallocarray(clist, clistlen, sizeof(*clist));
715 search(int *c, int k, int y)
719 if (clist[c[k]].y < y) /* quick look for typical case */
744 for (i = 0; i <= len[0]; i++)
745 J[i] = i <= pref ? i :
746 i > len[0] - suff ? i + len[1] - len[0] : 0;
747 for (q = clist + p; q->y != 0; q = clist + q->pred)
748 J[q->x + pref] = q->y + pref;
752 * Check does double duty:
753 * 1. ferret out any fortuitous correspondences due
754 * to confounding by hashing (which result in "jackpot")
755 * 2. collect random access indexes to the two files
758 check(FILE *f1, FILE *f2, int flags)
760 int i, j, jackpot, c, d;
766 ixold[0] = ixnew[0] = 0;
769 for (i = 1; i <= len[0]; i++) {
771 ixold[i] = ctold += skipline(f1);
775 ixnew[j] = ctnew += skipline(f2);
778 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_STRIPCR)) {
783 * GNU diff ignores a missing newline
784 * in one file for -b or -w.
786 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) {
787 if (c == EOF && d == '\n') {
790 } else if (c == '\n' && d == EOF) {
797 if (flags & D_STRIPCR && (c == '\r' || d == '\r')) {
799 if ((c = getc(f1)) == '\n') {
806 if ((d = getc(f2)) == '\n') {
814 if ((flags & D_FOLDBLANKS) && isspace(c) &&
820 } while (isspace(c = getc(f1)));
825 } while (isspace(d = getc(f2)));
826 } else if ((flags & D_IGNOREBLANKS)) {
827 while (isspace(c) && c != '\n') {
831 while (isspace(d) && d != '\n') {
836 if (chrtran(c) != chrtran(d)) {
839 if (c != '\n' && c != EOF)
840 ctold += skipline(f1);
841 if (d != '\n' && c != EOF)
842 ctnew += skipline(f2);
845 if (c == '\n' || c == EOF)
852 if ((c = getc(f1)) != (d = getc(f2))) {
855 if (c != '\n' && c != EOF)
856 ctold += skipline(f1);
857 if (d != '\n' && c != EOF)
858 ctnew += skipline(f2);
861 if (c == '\n' || c == EOF)
869 for (; j <= len[1]; j++) {
870 ixnew[j] = ctnew += skipline(f2);
874 * fprintf(stderr, "jackpot\n");
878 /* shellsort CACM #201 */
880 sort(struct line *a, int n)
882 struct line *ai, *aim, w;
887 for (j = 1; j <= n; j *= 2)
889 for (m /= 2; m != 0; m /= 2) {
891 for (j = 1; j <= k; j++) {
892 for (ai = &a[j]; ai > a; ai -= m) {
895 break; /* wraparound */
896 if (aim->value > ai[0].value ||
897 (aim->value == ai[0].value &&
898 aim->serial > ai[0].serial))
900 w.value = ai[0].value;
901 ai[0].value = aim->value;
902 aim->value = w.value;
903 w.serial = ai[0].serial;
904 ai[0].serial = aim->serial;
905 aim->serial = w.serial;
912 unsort(struct line *f, int l, int *b)
916 a = xcalloc(l + 1, sizeof(*a));
917 for (i = 1; i <= l; i++)
918 a[f[i].serial] = f[i].value;
919 for (i = 1; i <= l; i++)
929 for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
935 output(char *file1, FILE *f1, char *file2, FILE *f2, int flags)
937 int m, i0, i1, j0, j1;
943 J[m + 1] = len[1] + 1;
944 if (diff_format != D_EDIT) {
945 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
946 while (i0 <= m && J[i0] == J[i0 - 1] + 1)
950 while (i1 < m && J[i1 + 1] == 0)
954 change(file1, f1, file2, f2, i0, i1, j0, j1, &flags);
957 for (i0 = m; i0 >= 1; i0 = i1 - 1) {
958 while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0)
962 while (i1 > 1 && J[i1 - 1] == 0)
966 change(file1, f1, file2, f2, i1, i0, j1, j0, &flags);
970 change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags);
971 if (diff_format == D_IFDEF || diff_format == D_GFORMAT) {
974 if ((c = getc(f1)) == EOF)
976 diff_output("%c", c);
980 if (anychange != 0) {
981 if (diff_format == D_CONTEXT)
982 dump_context_vec(f1, f2, flags);
983 else if (diff_format == D_UNIFIED)
984 dump_unified_vec(f1, f2, flags);
989 range(int a, int b, const char *separator)
991 diff_output("%d", a > b ? b : a);
993 diff_output("%s%d", separator, b);
997 uni_range(int a, int b)
1000 diff_output("%d,%d", a, b - a + 1);
1002 diff_output("%d", b);
1004 diff_output("%d,0", b);
1008 preadline(int fd, size_t rlen, off_t off)
1013 line = xmalloc(rlen + 1);
1014 if ((nr = pread(fd, line, rlen, off)) < 0)
1015 err(2, "preadline");
1016 if (nr > 0 && line[nr-1] == '\n')
1023 ignoreline_pattern(char *line)
1027 ret = regexec(&ignore_re, line, 0, NULL, 0);
1029 return (ret == 0); /* if it matched, it should be ignored. */
1033 ignoreline(char *line, bool skip_blanks)
1036 if (ignore_pats != NULL && skip_blanks)
1037 return (ignoreline_pattern(line) || *line == '\0');
1038 if (ignore_pats != NULL)
1039 return (ignoreline_pattern(line));
1041 return (*line == '\0');
1042 /* No ignore criteria specified */
1047 * Indicate that there is a difference between lines a and b of the from file
1048 * to get to lines c to d of the to file. If a is greater then b then there
1049 * are no lines in the from file involved and this means that there were
1050 * lines appended (beginning at b). If c is greater than d then there are
1051 * lines missing from the to file.
1054 change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d,
1057 static size_t max_context = 64;
1063 skip_blanks = (*pflags & D_SKIPBLANKLINES);
1065 if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) &&
1068 if (ignore_pats != NULL || skip_blanks) {
1071 * All lines in the change, insert, or delete must
1072 * match an ignore pattern for the change to be
1075 if (a <= b) { /* Changes and deletes. */
1076 for (i = a; i <= b; i++) {
1077 line = preadline(fileno(f1),
1078 ixold[i] - ixold[i - 1], ixold[i - 1]);
1079 if (!ignoreline(line, skip_blanks))
1083 if (a > b || c <= d) { /* Changes and inserts. */
1084 for (i = c; i <= d; i++) {
1085 line = preadline(fileno(f2),
1086 ixnew[i] - ixnew[i - 1], ixnew[i - 1]);
1087 if (!ignoreline(line, skip_blanks))
1094 if (*pflags & D_HEADER && diff_format != D_BRIEF) {
1095 diff_output("%s %s %s\n", diffargs, file1, file2);
1096 *pflags &= ~D_HEADER;
1098 if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) {
1100 * Allocate change records as needed.
1102 if (context_vec_ptr == context_vec_end - 1) {
1103 ptrdiff_t offset = context_vec_ptr - context_vec_start;
1105 context_vec_start = xreallocarray(context_vec_start,
1106 max_context, sizeof(*context_vec_start));
1107 context_vec_end = context_vec_start + max_context;
1108 context_vec_ptr = context_vec_start + offset;
1110 if (anychange == 0) {
1112 * Print the context/unidiff header first time through.
1114 print_header(file1, file2);
1116 } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 &&
1117 c > context_vec_ptr->d + (2 * diff_context) + 1) {
1119 * If this change is more than 'diff_context' lines from the
1120 * previous change, dump the record and reset it.
1122 if (diff_format == D_CONTEXT)
1123 dump_context_vec(f1, f2, *pflags);
1125 dump_unified_vec(f1, f2, *pflags);
1128 context_vec_ptr->a = a;
1129 context_vec_ptr->b = b;
1130 context_vec_ptr->c = c;
1131 context_vec_ptr->d = d;
1136 switch (diff_format) {
1142 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1143 if (diff_format == D_NORMAL)
1148 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1154 diff_output("a%d %d\n", b, d - c + 1);
1156 diff_output("d%d %d\n", a, b - a + 1);
1158 /* add changed lines */
1159 diff_output("a%d %d\n", b, d - c + 1);
1163 if (diff_format == D_GFORMAT) {
1165 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1166 nc = ixold[a > b ? b : a - 1] - curpos;
1167 for (i = 0; i < nc; i++)
1168 diff_output("%c", getc(f1));
1169 for (walk = group_format; *walk != '\0'; walk++) {
1174 fetch(ixold, a, b, f1, '<', 1, *pflags);
1177 fetch(ixnew, c, d, f2, '>', 0, *pflags);
1180 diff_output("%%%c", *walk);
1185 diff_output("%c", *walk);
1188 if (diff_format == D_NORMAL || diff_format == D_IFDEF) {
1189 fetch(ixold, a, b, f1, '<', 1, *pflags);
1190 if (a <= b && c <= d && diff_format == D_NORMAL)
1191 diff_output("---\n");
1194 if (diff_format != D_GFORMAT)
1195 f = fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags);
1196 if (f != 0 && diff_format == D_EDIT) {
1198 * A non-zero return value for D_EDIT indicates that the
1199 * last line printed was a bare dot (".") that has been
1200 * escaped as ".." to prevent ed(1) from misinterpreting
1201 * it. We have to add a substitute command to change this
1202 * back and restart where we left off.
1205 diff_output("%ds/.//\n", a + f - 1);
1211 if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d)
1214 diff_output("#endif /* %s */\n", ifdefname);
1220 fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags)
1222 int i, j, c, lastc, col, nc;
1226 * When doing #ifdef's, copy down to current line
1227 * if this is the first file, so that stuff makes it to output.
1229 if ((diff_format == D_IFDEF) && oldfile) {
1230 long curpos = ftell(lb);
1231 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1232 nc = f[a > b ? b : a - 1] - curpos;
1233 for (i = 0; i < nc; i++)
1234 diff_output("%c", getc(lb));
1238 if (diff_format == D_IFDEF) {
1240 diff_output("#else /* %s%s */\n",
1241 oldfile == 1 ? "!" : "", ifdefname);
1244 diff_output("#ifndef %s\n", ifdefname);
1246 diff_output("#ifdef %s\n", ifdefname);
1248 inifdef = 1 + oldfile;
1250 for (i = a; i <= b; i++) {
1251 fseek(lb, f[i - 1], SEEK_SET);
1252 nc = f[i] - f[i - 1];
1253 if ((diff_format != D_IFDEF && diff_format != D_GFORMAT) &&
1255 diff_output("%c", ch);
1256 if (Tflag && (diff_format == D_NORMAL || diff_format == D_CONTEXT
1257 || diff_format == D_UNIFIED))
1259 else if (diff_format != D_UNIFIED)
1263 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
1264 if ((c = getc(lb)) == EOF) {
1265 if (diff_format == D_EDIT || diff_format == D_REVERSE ||
1266 diff_format == D_NREVERSE)
1267 warnx("No newline at end of file");
1269 diff_output("\n\\ No newline at end of "
1273 if (c == '\t' && (flags & D_EXPANDTABS)) {
1274 newcol = ((col/tabsize)+1)*tabsize;
1277 } while (++col < newcol);
1279 if (diff_format == D_EDIT && j == 1 && c == '\n'
1282 * Don't print a bare "." line
1283 * since that will confuse ed(1).
1284 * Print ".." instead and return,
1285 * giving the caller an offset
1286 * from which to restart.
1291 diff_output("%c", c);
1300 * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
1303 readhash(FILE *f, int flags)
1310 if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) == 0) {
1311 if (flags & D_IGNORECASE)
1312 for (i = 0; (t = getc(f)) != '\n'; i++) {
1313 if (flags & D_STRIPCR && t == '\r') {
1324 sum = sum * 127 + chrtran(t);
1327 for (i = 0; (t = getc(f)) != '\n'; i++) {
1328 if (flags & D_STRIPCR && t == '\r') {
1339 sum = sum * 127 + t;
1343 switch (t = getc(f)) {
1352 if (space && (flags & D_IGNOREBLANKS) == 0) {
1356 sum = sum * 127 + chrtran(t);
1370 * There is a remote possibility that we end up with a zero sum.
1371 * Zero is used as an EOF marker, so return 1 instead.
1373 return (sum == 0 ? 1 : sum);
1379 unsigned char buf[BUFSIZ];
1386 cnt = fread(buf, 1, sizeof(buf), f);
1387 return (memchr(buf, '\0', cnt) == NULL);
1390 #define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
1393 match_function(const long *f, int pos, FILE *fp)
1395 unsigned char buf[FUNCTION_CONTEXT_SIZE];
1397 int last = lastline;
1398 const char *state = NULL;
1401 while (pos > last) {
1402 fseek(fp, f[pos - 1], SEEK_SET);
1403 nc = f[pos] - f[pos - 1];
1404 if (nc >= sizeof(buf))
1405 nc = sizeof(buf) - 1;
1406 nc = fread(buf, 1, nc, fp);
1409 buf[strcspn(buf, "\n")] = '\0';
1410 if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$') {
1411 if (begins_with(buf, "private:")) {
1413 state = " (private)";
1414 } else if (begins_with(buf, "protected:")) {
1416 state = " (protected)";
1417 } else if (begins_with(buf, "public:")) {
1419 state = " (public)";
1421 strlcpy(lastbuf, buf, sizeof lastbuf);
1423 strlcat(lastbuf, state,
1425 lastmatchline = pos;
1432 return lastmatchline > 0 ? lastbuf : NULL;
1435 /* dump accumulated "context" diff changes */
1437 dump_context_vec(FILE *f1, FILE *f2, int flags)
1439 struct context_vec *cvp = context_vec_start;
1440 int lowa, upb, lowc, upd, do_output;
1444 if (context_vec_start > context_vec_ptr)
1447 b = d = 0; /* gcc */
1448 lowa = MAX(1, cvp->a - diff_context);
1449 upb = MIN(len[0], context_vec_ptr->b + diff_context);
1450 lowc = MAX(1, cvp->c - diff_context);
1451 upd = MIN(len[1], context_vec_ptr->d + diff_context);
1453 diff_output("***************");
1454 if ((flags & D_PROTOTYPE)) {
1455 f = match_function(ixold, lowa-1, f1);
1457 diff_output(" %s", f);
1459 diff_output("\n*** ");
1460 range(lowa, upb, ",");
1461 diff_output(" ****\n");
1464 * Output changes to the "old" file. The first loop suppresses
1465 * output if there were no changes to the "old" file (we'll see
1466 * the "old" lines as context in the "new" list).
1469 for (; cvp <= context_vec_ptr; cvp++)
1470 if (cvp->a <= cvp->b) {
1471 cvp = context_vec_start;
1476 while (cvp <= context_vec_ptr) {
1482 if (a <= b && c <= d)
1485 ch = (a <= b) ? 'd' : 'a';
1488 fetch(ixold, lowa, b, f1, ' ', 0, flags);
1490 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1491 fetch(ixold, a, b, f1,
1492 ch == 'c' ? '!' : '-', 0, flags);
1497 fetch(ixold, b + 1, upb, f1, ' ', 0, flags);
1499 /* output changes to the "new" file */
1500 diff_output("--- ");
1501 range(lowc, upd, ",");
1502 diff_output(" ----\n");
1505 for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++)
1506 if (cvp->c <= cvp->d) {
1507 cvp = context_vec_start;
1512 while (cvp <= context_vec_ptr) {
1518 if (a <= b && c <= d)
1521 ch = (a <= b) ? 'd' : 'a';
1524 fetch(ixnew, lowc, d, f2, ' ', 0, flags);
1526 fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1527 fetch(ixnew, c, d, f2,
1528 ch == 'c' ? '!' : '+', 0, flags);
1533 fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1535 context_vec_ptr = context_vec_start - 1;
1538 /* dump accumulated "unified" diff changes */
1540 dump_unified_vec(FILE *f1, FILE *f2, int flags)
1542 struct context_vec *cvp = context_vec_start;
1543 int lowa, upb, lowc, upd;
1547 if (context_vec_start > context_vec_ptr)
1550 b = d = 0; /* gcc */
1551 lowa = MAX(1, cvp->a - diff_context);
1552 upb = MIN(len[0], context_vec_ptr->b + diff_context);
1553 lowc = MAX(1, cvp->c - diff_context);
1554 upd = MIN(len[1], context_vec_ptr->d + diff_context);
1556 diff_output("@@ -");
1557 uni_range(lowa, upb);
1559 uni_range(lowc, upd);
1561 if ((flags & D_PROTOTYPE)) {
1562 f = match_function(ixold, lowa-1, f1);
1564 diff_output(" %s", f);
1569 * Output changes in "unified" diff format--the old and new lines
1570 * are printed together.
1572 for (; cvp <= context_vec_ptr; cvp++) {
1579 * c: both new and old changes
1580 * d: only changes in the old file
1581 * a: only changes in the new file
1583 if (a <= b && c <= d)
1586 ch = (a <= b) ? 'd' : 'a';
1590 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1591 fetch(ixold, a, b, f1, '-', 0, flags);
1592 fetch(ixnew, c, d, f2, '+', 0, flags);
1595 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1596 fetch(ixold, a, b, f1, '-', 0, flags);
1599 fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1600 fetch(ixnew, c, d, f2, '+', 0, flags);
1606 fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1608 context_vec_ptr = context_vec_start - 1;
1612 print_header(const char *file1, const char *file2)
1614 const char *time_format;
1619 struct tm tm1, tm2, *tm_ptr1, *tm_ptr2;
1620 int nsec1 = stb1.st_mtim.tv_nsec;
1621 int nsec2 = stb2.st_mtim.tv_nsec;
1623 time_format = "%Y-%m-%d %H:%M:%S";
1627 tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1);
1628 tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2);
1629 strftime(buf1, 256, time_format, tm_ptr1);
1630 strftime(buf2, 256, time_format, tm_ptr2);
1632 strftime(end1, 10, "%z", tm_ptr1);
1633 strftime(end2, 10, "%z", tm_ptr2);
1634 sprintf(buf1, "%s.%.9d %s", buf1, nsec1, end1);
1635 sprintf(buf2, "%s.%.9d %s", buf2, nsec2, end2);
1637 if (label[0] != NULL)
1638 diff_output("%s %s\n", diff_format == D_CONTEXT ? "***" : "---",
1641 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "***" : "---",
1643 if (label[1] != NULL)
1644 diff_output("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++",
1647 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "---" : "+++",