]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/diff/diffreg.c
MFS r354090:
[FreeBSD/FreeBSD.git] / usr.bin / diff / diffreg.c
1 /*      $OpenBSD: diffreg.c,v 1.91 2016/03/01 20:57:35 natano Exp $     */
2
3 /*-
4  * SPDX-License-Identifier: BSD-4-Clause
5  *
6  * Copyright (C) Caldera International Inc.  2001-2002.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
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
20  *      International, Inc.
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.
24  *
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.
37  */
38 /*-
39  * Copyright (c) 1991, 1993
40  *      The Regents of the University of California.  All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
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.
53  *
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
64  * SUCH DAMAGE.
65  *
66  *      @(#)diffreg.c   8.1 (Berkeley) 6/6/93
67  */
68
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
71
72 #include <sys/capsicum.h>
73 #include <sys/stat.h>
74
75 #include <capsicum_helpers.h>
76 #include <ctype.h>
77 #include <err.h>
78 #include <errno.h>
79 #include <fcntl.h>
80 #include <paths.h>
81 #include <regex.h>
82 #include <stdbool.h>
83 #include <stddef.h>
84 #include <stdint.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88
89 #include "pr.h"
90 #include "diff.h"
91 #include "xmalloc.h"
92
93 /*
94  * diff - compare two files.
95  */
96
97 /*
98  *      Uses an algorithm due to Harold Stone, which finds
99  *      a pair of longest identical subsequences in the two
100  *      files.
101  *
102  *      The major goal is to generate the match vector J.
103  *      J[i] is the index of the line in file1 corresponding
104  *      to line i file0. J[i] = 0 if there is no
105  *      such line in file1.
106  *
107  *      Lines are hashed so as to work in core. All potential
108  *      matches are located by sorting the lines of each file
109  *      on the hash (called ``value''). In particular, this
110  *      collects the equivalence classes in file1 together.
111  *      Subroutine equiv replaces the value of each line in
112  *      file0 by the index of the first element of its
113  *      matching equivalence in (the reordered) file1.
114  *      To save space equiv squeezes file1 into a single
115  *      array member in which the equivalence classes
116  *      are simply concatenated, except that their first
117  *      members are flagged by changing sign.
118  *
119  *      Next the indices that point into member are unsorted into
120  *      array class according to the original order of file0.
121  *
122  *      The cleverness lies in routine stone. This marches
123  *      through the lines of file0, developing a vector klist
124  *      of "k-candidates". At step i a k-candidate is a matched
125  *      pair of lines x,y (x in file0 y in file1) such that
126  *      there is a common subsequence of length k
127  *      between the first i lines of file0 and the first y
128  *      lines of file1, but there is no such subsequence for
129  *      any smaller y. x is the earliest possible mate to y
130  *      that occurs in such a subsequence.
131  *
132  *      Whenever any of the members of the equivalence class of
133  *      lines in file1 matable to a line in file0 has serial number
134  *      less than the y of some k-candidate, that k-candidate
135  *      with the smallest such y is replaced. The new
136  *      k-candidate is chained (via pred) to the current
137  *      k-1 candidate so that the actual subsequence can
138  *      be recovered. When a member has serial number greater
139  *      that the y of all k-candidates, the klist is extended.
140  *      At the end, the longest subsequence is pulled out
141  *      and placed in the array J by unravel
142  *
143  *      With J in hand, the matches there recorded are
144  *      check'ed against reality to assure that no spurious
145  *      matches have crept in due to hashing. If they have,
146  *      they are broken, and "jackpot" is recorded--a harmless
147  *      matter except that a true match for a spuriously
148  *      mated line may now be unnecessarily reported as a change.
149  *
150  *      Much of the complexity of the program comes simply
151  *      from trying to minimize core utilization and
152  *      maximize the range of doable problems by dynamically
153  *      allocating what is needed and reusing what is not.
154  *      The core requirements for problems larger than somewhat
155  *      are (in words) 2*length(file0) + length(file1) +
156  *      3*(number of k-candidates installed),  typically about
157  *      6n words for files of length n.
158  */
159
160 struct cand {
161         int     x;
162         int     y;
163         int     pred;
164 };
165
166 static struct line {
167         int     serial;
168         int     value;
169 } *file[2];
170
171 /*
172  * The following struct is used to record change information when
173  * doing a "context" or "unified" diff.  (see routine "change" to
174  * understand the highly mnemonic field names)
175  */
176 struct context_vec {
177         int     a;              /* start line in old file */
178         int     b;              /* end line in old file */
179         int     c;              /* start line in new file */
180         int     d;              /* end line in new file */
181 };
182
183 #define diff_output     printf
184 static FILE     *opentemp(const char *);
185 static void      output(char *, FILE *, char *, FILE *, int);
186 static void      check(FILE *, FILE *, int);
187 static void      range(int, int, const char *);
188 static void      uni_range(int, int);
189 static void      dump_context_vec(FILE *, FILE *, int);
190 static void      dump_unified_vec(FILE *, FILE *, int);
191 static void      prepare(int, FILE *, size_t, int);
192 static void      prune(void);
193 static void      equiv(struct line *, int, struct line *, int, int *);
194 static void      unravel(int);
195 static void      unsort(struct line *, int, int *);
196 static void      change(char *, FILE *, char *, FILE *, int, int, int, int, int *);
197 static void      sort(struct line *, int);
198 static void      print_header(const char *, const char *);
199 static bool      ignoreline_pattern(char *);
200 static bool      ignoreline(char *, bool);
201 static int       asciifile(FILE *);
202 static int       fetch(long *, int, int, FILE *, int, int, int);
203 static int       newcand(int, int, int);
204 static int       search(int *, int, int);
205 static int       skipline(FILE *);
206 static int       isqrt(int);
207 static int       stone(int *, int, int *, int *, int);
208 static int       readhash(FILE *, int);
209 static int       files_differ(FILE *, FILE *, int);
210 static char     *match_function(const long *, int, FILE *);
211 static char     *preadline(int, size_t, off_t);
212
213 static int  *J;                 /* will be overlaid on class */
214 static int  *class;             /* will be overlaid on file[0] */
215 static int  *klist;             /* will be overlaid on file[0] after class */
216 static int  *member;            /* will be overlaid on file[1] */
217 static int   clen;
218 static int   inifdef;           /* whether or not we are in a #ifdef block */
219 static int   len[2];
220 static int   pref, suff;        /* length of prefix and suffix */
221 static int   slen[2];
222 static int   anychange;
223 static long *ixnew;             /* will be overlaid on file[1] */
224 static long *ixold;             /* will be overlaid on klist */
225 static struct cand *clist;      /* merely a free storage pot for candidates */
226 static int   clistlen;          /* the length of clist */
227 static struct line *sfile[2];   /* shortened by pruning common prefix/suffix */
228 static int (*chrtran)(int);     /* translation table for case-folding */
229 static struct context_vec *context_vec_start;
230 static struct context_vec *context_vec_end;
231 static struct context_vec *context_vec_ptr;
232
233 #define FUNCTION_CONTEXT_SIZE   55
234 static char lastbuf[FUNCTION_CONTEXT_SIZE];
235 static int lastline;
236 static int lastmatchline;
237
238 static int
239 clow2low(int c)
240 {
241
242         return (c);
243 }
244
245 static int
246 cup2low(int c)
247 {
248
249         return tolower(c);
250 }
251
252 int
253 diffreg(char *file1, char *file2, int flags, int capsicum)
254 {
255         FILE *f1, *f2;
256         int i, rval;
257         struct pr *pr = NULL;
258         cap_rights_t rights_ro;
259
260         f1 = f2 = NULL;
261         rval = D_SAME;
262         anychange = 0;
263         lastline = 0;
264         lastmatchline = 0;
265         context_vec_ptr = context_vec_start - 1;
266         if (flags & D_IGNORECASE)
267                 chrtran = cup2low;
268         else
269                 chrtran = clow2low;
270         if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
271                 return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
272         if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
273                 goto closem;
274
275         if (flags & D_EMPTY1)
276                 f1 = fopen(_PATH_DEVNULL, "r");
277         else {
278                 if (!S_ISREG(stb1.st_mode)) {
279                         if ((f1 = opentemp(file1)) == NULL ||
280                             fstat(fileno(f1), &stb1) < 0) {
281                                 warn("%s", file1);
282                                 status |= 2;
283                                 goto closem;
284                         }
285                 } else if (strcmp(file1, "-") == 0)
286                         f1 = stdin;
287                 else
288                         f1 = fopen(file1, "r");
289         }
290         if (f1 == NULL) {
291                 warn("%s", file1);
292                 status |= 2;
293                 goto closem;
294         }
295
296         if (flags & D_EMPTY2)
297                 f2 = fopen(_PATH_DEVNULL, "r");
298         else {
299                 if (!S_ISREG(stb2.st_mode)) {
300                         if ((f2 = opentemp(file2)) == NULL ||
301                             fstat(fileno(f2), &stb2) < 0) {
302                                 warn("%s", file2);
303                                 status |= 2;
304                                 goto closem;
305                         }
306                 } else if (strcmp(file2, "-") == 0)
307                         f2 = stdin;
308                 else
309                         f2 = fopen(file2, "r");
310         }
311         if (f2 == NULL) {
312                 warn("%s", file2);
313                 status |= 2;
314                 goto closem;
315         }
316
317         if (lflag)
318                 pr = start_pr(file1, file2);
319
320         if (capsicum) {
321                 cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
322                 if (cap_rights_limit(fileno(f1), &rights_ro) < 0
323                     && errno != ENOSYS)
324                         err(2, "unable to limit rights on: %s", file1);
325                 if (cap_rights_limit(fileno(f2), &rights_ro) < 0 &&
326                     errno != ENOSYS)
327                         err(2, "unable to limit rights on: %s", file2);
328                 if (fileno(f1) == STDIN_FILENO || fileno(f2) == STDIN_FILENO) {
329                         /* stding has already been limited */
330                         if (caph_limit_stderr() == -1)
331                                 err(2, "unable to limit stderr");
332                         if (caph_limit_stdout() == -1)
333                                 err(2, "unable to limit stdout");
334                 } else if (caph_limit_stdio() == -1)
335                                 err(2, "unable to limit stdio");
336
337                 caph_cache_catpages();
338                 caph_cache_tzdata();
339                 if (caph_enter() < 0)
340                         err(2, "unable to enter capability mode");
341         }
342
343         switch (files_differ(f1, f2, flags)) {
344         case 0:
345                 goto closem;
346         case 1:
347                 break;
348         default:
349                 /* error */
350                 status |= 2;
351                 goto closem;
352         }
353
354         if ((flags & D_FORCEASCII) == 0 &&
355             (!asciifile(f1) || !asciifile(f2))) {
356                 rval = D_BINARY;
357                 status |= 1;
358                 goto closem;
359         }
360         prepare(0, f1, stb1.st_size, flags);
361         prepare(1, f2, stb2.st_size, flags);
362
363         prune();
364         sort(sfile[0], slen[0]);
365         sort(sfile[1], slen[1]);
366
367         member = (int *)file[1];
368         equiv(sfile[0], slen[0], sfile[1], slen[1], member);
369         member = xreallocarray(member, slen[1] + 2, sizeof(*member));
370
371         class = (int *)file[0];
372         unsort(sfile[0], slen[0], class);
373         class = xreallocarray(class, slen[0] + 2, sizeof(*class));
374
375         klist = xcalloc(slen[0] + 2, sizeof(*klist));
376         clen = 0;
377         clistlen = 100;
378         clist = xcalloc(clistlen, sizeof(*clist));
379         i = stone(class, slen[0], member, klist, flags);
380         free(member);
381         free(class);
382
383         J = xreallocarray(J, len[0] + 2, sizeof(*J));
384         unravel(klist[i]);
385         free(clist);
386         free(klist);
387
388         ixold = xreallocarray(ixold, len[0] + 2, sizeof(*ixold));
389         ixnew = xreallocarray(ixnew, len[1] + 2, sizeof(*ixnew));
390         check(f1, f2, flags);
391         output(file1, f1, file2, f2, flags);
392         if (pr != NULL)
393                 stop_pr(pr);
394
395 closem:
396         if (anychange) {
397                 status |= 1;
398                 if (rval == D_SAME)
399                         rval = D_DIFFER;
400         }
401         if (f1 != NULL)
402                 fclose(f1);
403         if (f2 != NULL)
404                 fclose(f2);
405
406         return (rval);
407 }
408
409 /*
410  * Check to see if the given files differ.
411  * Returns 0 if they are the same, 1 if different, and -1 on error.
412  * XXX - could use code from cmp(1) [faster]
413  */
414 static int
415 files_differ(FILE *f1, FILE *f2, int flags)
416 {
417         char buf1[BUFSIZ], buf2[BUFSIZ];
418         size_t i, j;
419
420         if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
421             (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
422                 return (1);
423         for (;;) {
424                 i = fread(buf1, 1, sizeof(buf1), f1);
425                 j = fread(buf2, 1, sizeof(buf2), f2);
426                 if ((!i && ferror(f1)) || (!j && ferror(f2)))
427                         return (-1);
428                 if (i != j)
429                         return (1);
430                 if (i == 0)
431                         return (0);
432                 if (memcmp(buf1, buf2, i) != 0)
433                         return (1);
434         }
435 }
436
437 static FILE *
438 opentemp(const char *f)
439 {
440         char buf[BUFSIZ], tempfile[PATH_MAX];
441         ssize_t nread;
442         int ifd, ofd;
443
444         if (strcmp(f, "-") == 0)
445                 ifd = STDIN_FILENO;
446         else if ((ifd = open(f, O_RDONLY, 0644)) < 0)
447                 return (NULL);
448
449         (void)strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile));
450
451         if ((ofd = mkstemp(tempfile)) < 0) {
452                 close(ifd);
453                 return (NULL);
454         }
455         unlink(tempfile);
456         while ((nread = read(ifd, buf, BUFSIZ)) > 0) {
457                 if (write(ofd, buf, nread) != nread) {
458                         close(ifd);
459                         close(ofd);
460                         return (NULL);
461                 }
462         }
463         close(ifd);
464         lseek(ofd, (off_t)0, SEEK_SET);
465         return (fdopen(ofd, "r"));
466 }
467
468 char *
469 splice(char *dir, char *path)
470 {
471         char *tail, *buf;
472         size_t dirlen;
473
474         dirlen = strlen(dir);
475         while (dirlen != 0 && dir[dirlen - 1] == '/')
476             dirlen--;
477         if ((tail = strrchr(path, '/')) == NULL)
478                 tail = path;
479         else
480                 tail++;
481         xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);
482         return (buf);
483 }
484
485 static void
486 prepare(int i, FILE *fd, size_t filesize, int flags)
487 {
488         struct line *p;
489         int h;
490         size_t sz, j;
491
492         rewind(fd);
493
494         sz = MIN(filesize, SIZE_MAX) / 25;
495         if (sz < 100)
496                 sz = 100;
497
498         p = xcalloc(sz + 3, sizeof(*p));
499         for (j = 0; (h = readhash(fd, flags));) {
500                 if (j == sz) {
501                         sz = sz * 3 / 2;
502                         p = xreallocarray(p, sz + 3, sizeof(*p));
503                 }
504                 p[++j].value = h;
505         }
506         len[i] = j;
507         file[i] = p;
508 }
509
510 static void
511 prune(void)
512 {
513         int i, j;
514
515         for (pref = 0; pref < len[0] && pref < len[1] &&
516             file[0][pref + 1].value == file[1][pref + 1].value;
517             pref++)
518                 ;
519         for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
520             file[0][len[0] - suff].value == file[1][len[1] - suff].value;
521             suff++)
522                 ;
523         for (j = 0; j < 2; j++) {
524                 sfile[j] = file[j] + pref;
525                 slen[j] = len[j] - pref - suff;
526                 for (i = 0; i <= slen[j]; i++)
527                         sfile[j][i].serial = i;
528         }
529 }
530
531 static void
532 equiv(struct line *a, int n, struct line *b, int m, int *c)
533 {
534         int i, j;
535
536         i = j = 1;
537         while (i <= n && j <= m) {
538                 if (a[i].value < b[j].value)
539                         a[i++].value = 0;
540                 else if (a[i].value == b[j].value)
541                         a[i++].value = j;
542                 else
543                         j++;
544         }
545         while (i <= n)
546                 a[i++].value = 0;
547         b[m + 1].value = 0;
548         j = 0;
549         while (++j <= m) {
550                 c[j] = -b[j].serial;
551                 while (b[j + 1].value == b[j].value) {
552                         j++;
553                         c[j] = b[j].serial;
554                 }
555         }
556         c[j] = -1;
557 }
558
559 /* Code taken from ping.c */
560 static int
561 isqrt(int n)
562 {
563         int y, x = 1;
564
565         if (n == 0)
566                 return (0);
567
568         do { /* newton was a stinker */
569                 y = x;
570                 x = n / x;
571                 x += y;
572                 x /= 2;
573         } while ((x - y) > 1 || (x - y) < -1);
574
575         return (x);
576 }
577
578 static int
579 stone(int *a, int n, int *b, int *c, int flags)
580 {
581         int i, k, y, j, l;
582         int oldc, tc, oldl, sq;
583         u_int numtries, bound;
584
585         if (flags & D_MINIMAL)
586                 bound = UINT_MAX;
587         else {
588                 sq = isqrt(n);
589                 bound = MAX(256, sq);
590         }
591
592         k = 0;
593         c[0] = newcand(0, 0, 0);
594         for (i = 1; i <= n; i++) {
595                 j = a[i];
596                 if (j == 0)
597                         continue;
598                 y = -b[j];
599                 oldl = 0;
600                 oldc = c[0];
601                 numtries = 0;
602                 do {
603                         if (y <= clist[oldc].y)
604                                 continue;
605                         l = search(c, k, y);
606                         if (l != oldl + 1)
607                                 oldc = c[l - 1];
608                         if (l <= k) {
609                                 if (clist[c[l]].y <= y)
610                                         continue;
611                                 tc = c[l];
612                                 c[l] = newcand(i, y, oldc);
613                                 oldc = tc;
614                                 oldl = l;
615                                 numtries++;
616                         } else {
617                                 c[l] = newcand(i, y, oldc);
618                                 k++;
619                                 break;
620                         }
621                 } while ((y = b[++j]) > 0 && numtries < bound);
622         }
623         return (k);
624 }
625
626 static int
627 newcand(int x, int y, int pred)
628 {
629         struct cand *q;
630
631         if (clen == clistlen) {
632                 clistlen = clistlen * 11 / 10;
633                 clist = xreallocarray(clist, clistlen, sizeof(*clist));
634         }
635         q = clist + clen;
636         q->x = x;
637         q->y = y;
638         q->pred = pred;
639         return (clen++);
640 }
641
642 static int
643 search(int *c, int k, int y)
644 {
645         int i, j, l, t;
646
647         if (clist[c[k]].y < y)  /* quick look for typical case */
648                 return (k + 1);
649         i = 0;
650         j = k + 1;
651         for (;;) {
652                 l = (i + j) / 2;
653                 if (l <= i)
654                         break;
655                 t = clist[c[l]].y;
656                 if (t > y)
657                         j = l;
658                 else if (t < y)
659                         i = l;
660                 else
661                         return (l);
662         }
663         return (l + 1);
664 }
665
666 static void
667 unravel(int p)
668 {
669         struct cand *q;
670         int i;
671
672         for (i = 0; i <= len[0]; i++)
673                 J[i] = i <= pref ? i :
674                     i > len[0] - suff ? i + len[1] - len[0] : 0;
675         for (q = clist + p; q->y != 0; q = clist + q->pred)
676                 J[q->x + pref] = q->y + pref;
677 }
678
679 /*
680  * Check does double duty:
681  *  1.  ferret out any fortuitous correspondences due
682  *      to confounding by hashing (which result in "jackpot")
683  *  2.  collect random access indexes to the two files
684  */
685 static void
686 check(FILE *f1, FILE *f2, int flags)
687 {
688         int i, j, jackpot, c, d;
689         long ctold, ctnew;
690
691         rewind(f1);
692         rewind(f2);
693         j = 1;
694         ixold[0] = ixnew[0] = 0;
695         jackpot = 0;
696         ctold = ctnew = 0;
697         for (i = 1; i <= len[0]; i++) {
698                 if (J[i] == 0) {
699                         ixold[i] = ctold += skipline(f1);
700                         continue;
701                 }
702                 while (j < J[i]) {
703                         ixnew[j] = ctnew += skipline(f2);
704                         j++;
705                 }
706                 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_STRIPCR)) {
707                         for (;;) {
708                                 c = getc(f1);
709                                 d = getc(f2);
710                                 /*
711                                  * GNU diff ignores a missing newline
712                                  * in one file for -b or -w.
713                                  */
714                                 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) {
715                                         if (c == EOF && d == '\n') {
716                                                 ctnew++;
717                                                 break;
718                                         } else if (c == '\n' && d == EOF) {
719                                                 ctold++;
720                                                 break;
721                                         }
722                                 }
723                                 ctold++;
724                                 ctnew++;
725                                 if (flags & D_STRIPCR && (c == '\r' || d == '\r')) {
726                                         if (c == '\r') {
727                                                 if ((c = getc(f1)) == '\n') {
728                                                         ctold++;
729                                                 } else {
730                                                         ungetc(c, f1);
731                                                 }
732                                         }
733                                         if (d == '\r') {
734                                                 if ((d = getc(f2)) == '\n') {
735                                                         ctnew++;
736                                                 } else {
737                                                         ungetc(d, f2);
738                                                 }
739                                         }
740                                         break;
741                                 }
742                                 if ((flags & D_FOLDBLANKS) && isspace(c) &&
743                                     isspace(d)) {
744                                         do {
745                                                 if (c == '\n')
746                                                         break;
747                                                 ctold++;
748                                         } while (isspace(c = getc(f1)));
749                                         do {
750                                                 if (d == '\n')
751                                                         break;
752                                                 ctnew++;
753                                         } while (isspace(d = getc(f2)));
754                                 } else if ((flags & D_IGNOREBLANKS)) {
755                                         while (isspace(c) && c != '\n') {
756                                                 c = getc(f1);
757                                                 ctold++;
758                                         }
759                                         while (isspace(d) && d != '\n') {
760                                                 d = getc(f2);
761                                                 ctnew++;
762                                         }
763                                 }
764                                 if (chrtran(c) != chrtran(d)) {
765                                         jackpot++;
766                                         J[i] = 0;
767                                         if (c != '\n' && c != EOF)
768                                                 ctold += skipline(f1);
769                                         if (d != '\n' && c != EOF)
770                                                 ctnew += skipline(f2);
771                                         break;
772                                 }
773                                 if (c == '\n' || c == EOF)
774                                         break;
775                         }
776                 } else {
777                         for (;;) {
778                                 ctold++;
779                                 ctnew++;
780                                 if ((c = getc(f1)) != (d = getc(f2))) {
781                                         /* jackpot++; */
782                                         J[i] = 0;
783                                         if (c != '\n' && c != EOF)
784                                                 ctold += skipline(f1);
785                                         if (d != '\n' && c != EOF)
786                                                 ctnew += skipline(f2);
787                                         break;
788                                 }
789                                 if (c == '\n' || c == EOF)
790                                         break;
791                         }
792                 }
793                 ixold[i] = ctold;
794                 ixnew[j] = ctnew;
795                 j++;
796         }
797         for (; j <= len[1]; j++) {
798                 ixnew[j] = ctnew += skipline(f2);
799         }
800         /*
801          * if (jackpot)
802          *      fprintf(stderr, "jackpot\n");
803          */
804 }
805
806 /* shellsort CACM #201 */
807 static void
808 sort(struct line *a, int n)
809 {
810         struct line *ai, *aim, w;
811         int j, m = 0, k;
812
813         if (n == 0)
814                 return;
815         for (j = 1; j <= n; j *= 2)
816                 m = 2 * j - 1;
817         for (m /= 2; m != 0; m /= 2) {
818                 k = n - m;
819                 for (j = 1; j <= k; j++) {
820                         for (ai = &a[j]; ai > a; ai -= m) {
821                                 aim = &ai[m];
822                                 if (aim < ai)
823                                         break;  /* wraparound */
824                                 if (aim->value > ai[0].value ||
825                                     (aim->value == ai[0].value &&
826                                         aim->serial > ai[0].serial))
827                                         break;
828                                 w.value = ai[0].value;
829                                 ai[0].value = aim->value;
830                                 aim->value = w.value;
831                                 w.serial = ai[0].serial;
832                                 ai[0].serial = aim->serial;
833                                 aim->serial = w.serial;
834                         }
835                 }
836         }
837 }
838
839 static void
840 unsort(struct line *f, int l, int *b)
841 {
842         int *a, i;
843
844         a = xcalloc(l + 1, sizeof(*a));
845         for (i = 1; i <= l; i++)
846                 a[f[i].serial] = f[i].value;
847         for (i = 1; i <= l; i++)
848                 b[i] = a[i];
849         free(a);
850 }
851
852 static int
853 skipline(FILE *f)
854 {
855         int i, c;
856
857         for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
858                 continue;
859         return (i);
860 }
861
862 static void
863 output(char *file1, FILE *f1, char *file2, FILE *f2, int flags)
864 {
865         int m, i0, i1, j0, j1;
866
867         rewind(f1);
868         rewind(f2);
869         m = len[0];
870         J[0] = 0;
871         J[m + 1] = len[1] + 1;
872         if (diff_format != D_EDIT) {
873                 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
874                         while (i0 <= m && J[i0] == J[i0 - 1] + 1)
875                                 i0++;
876                         j0 = J[i0 - 1] + 1;
877                         i1 = i0 - 1;
878                         while (i1 < m && J[i1 + 1] == 0)
879                                 i1++;
880                         j1 = J[i1 + 1] - 1;
881                         J[i1] = j1;
882                         change(file1, f1, file2, f2, i0, i1, j0, j1, &flags);
883                 }
884         } else {
885                 for (i0 = m; i0 >= 1; i0 = i1 - 1) {
886                         while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0)
887                                 i0--;
888                         j0 = J[i0 + 1] - 1;
889                         i1 = i0 + 1;
890                         while (i1 > 1 && J[i1 - 1] == 0)
891                                 i1--;
892                         j1 = J[i1 - 1] + 1;
893                         J[i1] = j1;
894                         change(file1, f1, file2, f2, i1, i0, j1, j0, &flags);
895                 }
896         }
897         if (m == 0)
898                 change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags);
899         if (diff_format == D_IFDEF || diff_format == D_GFORMAT) {
900                 for (;;) {
901 #define c i0
902                         if ((c = getc(f1)) == EOF)
903                                 return;
904                         diff_output("%c", c);
905                 }
906 #undef c
907         }
908         if (anychange != 0) {
909                 if (diff_format == D_CONTEXT)
910                         dump_context_vec(f1, f2, flags);
911                 else if (diff_format == D_UNIFIED)
912                         dump_unified_vec(f1, f2, flags);
913         }
914 }
915
916 static void
917 range(int a, int b, const char *separator)
918 {
919         diff_output("%d", a > b ? b : a);
920         if (a < b)
921                 diff_output("%s%d", separator, b);
922 }
923
924 static void
925 uni_range(int a, int b)
926 {
927         if (a < b)
928                 diff_output("%d,%d", a, b - a + 1);
929         else if (a == b)
930                 diff_output("%d", b);
931         else
932                 diff_output("%d,0", b);
933 }
934
935 static char *
936 preadline(int fd, size_t rlen, off_t off)
937 {
938         char *line;
939         ssize_t nr;
940
941         line = xmalloc(rlen + 1);
942         if ((nr = pread(fd, line, rlen, off)) < 0)
943                 err(2, "preadline");
944         if (nr > 0 && line[nr-1] == '\n')
945                 nr--;
946         line[nr] = '\0';
947         return (line);
948 }
949
950 static bool
951 ignoreline_pattern(char *line)
952 {
953         int ret;
954
955         ret = regexec(&ignore_re, line, 0, NULL, 0);
956         free(line);
957         return (ret == 0);      /* if it matched, it should be ignored. */
958 }
959
960 static bool
961 ignoreline(char *line, bool skip_blanks)
962 {
963
964         if (ignore_pats != NULL && skip_blanks)
965                 return (ignoreline_pattern(line) || *line == '\0');
966         if (ignore_pats != NULL)
967                 return (ignoreline_pattern(line));
968         if (skip_blanks)
969                 return (*line == '\0');
970         /* No ignore criteria specified */
971         return (false);
972 }
973
974 /*
975  * Indicate that there is a difference between lines a and b of the from file
976  * to get to lines c to d of the to file.  If a is greater then b then there
977  * are no lines in the from file involved and this means that there were
978  * lines appended (beginning at b).  If c is greater than d then there are
979  * lines missing from the to file.
980  */
981 static void
982 change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d,
983     int *pflags)
984 {
985         static size_t max_context = 64;
986         long curpos;
987         int i, nc, f;
988         const char *walk;
989         bool skip_blanks;
990
991         skip_blanks = (*pflags & D_SKIPBLANKLINES);
992 restart:
993         if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) &&
994             a > b && c > d)
995                 return;
996         if (ignore_pats != NULL || skip_blanks) {
997                 char *line;
998                 /*
999                  * All lines in the change, insert, or delete must
1000                  * match an ignore pattern for the change to be
1001                  * ignored.
1002                  */
1003                 if (a <= b) {           /* Changes and deletes. */
1004                         for (i = a; i <= b; i++) {
1005                                 line = preadline(fileno(f1),
1006                                     ixold[i] - ixold[i - 1], ixold[i - 1]);
1007                                 if (!ignoreline(line, skip_blanks))
1008                                         goto proceed;
1009                         }
1010                 }
1011                 if (a > b || c <= d) {  /* Changes and inserts. */
1012                         for (i = c; i <= d; i++) {
1013                                 line = preadline(fileno(f2),
1014                                     ixnew[i] - ixnew[i - 1], ixnew[i - 1]);
1015                                 if (!ignoreline(line, skip_blanks))
1016                                         goto proceed;
1017                         }
1018                 }
1019                 return;
1020         }
1021 proceed:
1022         if (*pflags & D_HEADER && diff_format != D_BRIEF) {
1023                 diff_output("%s %s %s\n", diffargs, file1, file2);
1024                 *pflags &= ~D_HEADER;
1025         }
1026         if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) {
1027                 /*
1028                  * Allocate change records as needed.
1029                  */
1030                 if (context_vec_ptr == context_vec_end - 1) {
1031                         ptrdiff_t offset = context_vec_ptr - context_vec_start;
1032                         max_context <<= 1;
1033                         context_vec_start = xreallocarray(context_vec_start,
1034                             max_context, sizeof(*context_vec_start));
1035                         context_vec_end = context_vec_start + max_context;
1036                         context_vec_ptr = context_vec_start + offset;
1037                 }
1038                 if (anychange == 0) {
1039                         /*
1040                          * Print the context/unidiff header first time through.
1041                          */
1042                         print_header(file1, file2);
1043                         anychange = 1;
1044                 } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 &&
1045                     c > context_vec_ptr->d + (2 * diff_context) + 1) {
1046                         /*
1047                          * If this change is more than 'diff_context' lines from the
1048                          * previous change, dump the record and reset it.
1049                          */
1050                         if (diff_format == D_CONTEXT)
1051                                 dump_context_vec(f1, f2, *pflags);
1052                         else
1053                                 dump_unified_vec(f1, f2, *pflags);
1054                 }
1055                 context_vec_ptr++;
1056                 context_vec_ptr->a = a;
1057                 context_vec_ptr->b = b;
1058                 context_vec_ptr->c = c;
1059                 context_vec_ptr->d = d;
1060                 return;
1061         }
1062         if (anychange == 0)
1063                 anychange = 1;
1064         switch (diff_format) {
1065         case D_BRIEF:
1066                 return;
1067         case D_NORMAL:
1068         case D_EDIT:
1069                 range(a, b, ",");
1070                 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1071                 if (diff_format == D_NORMAL)
1072                         range(c, d, ",");
1073                 diff_output("\n");
1074                 break;
1075         case D_REVERSE:
1076                 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1077                 range(a, b, " ");
1078                 diff_output("\n");
1079                 break;
1080         case D_NREVERSE:
1081                 if (a > b)
1082                         diff_output("a%d %d\n", b, d - c + 1);
1083                 else {
1084                         diff_output("d%d %d\n", a, b - a + 1);
1085                         if (!(c > d))
1086                                 /* add changed lines */
1087                                 diff_output("a%d %d\n", b, d - c + 1);
1088                 }
1089                 break;
1090         }
1091         if (diff_format == D_GFORMAT) {
1092                 curpos = ftell(f1);
1093                 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1094                 nc = ixold[a > b ? b : a - 1] - curpos;
1095                 for (i = 0; i < nc; i++)
1096                         diff_output("%c", getc(f1));
1097                 for (walk = group_format; *walk != '\0'; walk++) {
1098                         if (*walk == '%') {
1099                                 walk++;
1100                                 switch (*walk) {
1101                                 case '<':
1102                                         fetch(ixold, a, b, f1, '<', 1, *pflags);
1103                                         break;
1104                                 case '>':
1105                                         fetch(ixnew, c, d, f2, '>', 0, *pflags);
1106                                         break;
1107                                 default:
1108                                         diff_output("%%%c", *walk);
1109                                         break;
1110                                 }
1111                                 continue;
1112                         }
1113                         diff_output("%c", *walk);
1114                 }
1115         }
1116         if (diff_format == D_NORMAL || diff_format == D_IFDEF) {
1117                 fetch(ixold, a, b, f1, '<', 1, *pflags);
1118                 if (a <= b && c <= d && diff_format == D_NORMAL)
1119                         diff_output("---\n");
1120         }
1121         f = 0;
1122         if (diff_format != D_GFORMAT)
1123                 f = fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags);
1124         if (f != 0 && diff_format == D_EDIT) {
1125                 /*
1126                  * A non-zero return value for D_EDIT indicates that the
1127                  * last line printed was a bare dot (".") that has been
1128                  * escaped as ".." to prevent ed(1) from misinterpreting
1129                  * it.  We have to add a substitute command to change this
1130                  * back and restart where we left off.
1131                  */
1132                 diff_output(".\n");
1133                 diff_output("%ds/.//\n", a + f - 1);
1134                 b = a + f - 1;
1135                 a = b + 1;
1136                 c += f;
1137                 goto restart;
1138         }
1139         if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d)
1140                 diff_output(".\n");
1141         if (inifdef) {
1142                 diff_output("#endif /* %s */\n", ifdefname);
1143                 inifdef = 0;
1144         }
1145 }
1146
1147 static int
1148 fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags)
1149 {
1150         int i, j, c, lastc, col, nc;
1151         int     newcol;
1152
1153         /*
1154          * When doing #ifdef's, copy down to current line
1155          * if this is the first file, so that stuff makes it to output.
1156          */
1157         if ((diff_format == D_IFDEF) && oldfile) {
1158                 long curpos = ftell(lb);
1159                 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1160                 nc = f[a > b ? b : a - 1] - curpos;
1161                 for (i = 0; i < nc; i++)
1162                         diff_output("%c", getc(lb));
1163         }
1164         if (a > b)
1165                 return (0);
1166         if (diff_format == D_IFDEF) {
1167                 if (inifdef) {
1168                         diff_output("#else /* %s%s */\n",
1169                             oldfile == 1 ? "!" : "", ifdefname);
1170                 } else {
1171                         if (oldfile)
1172                                 diff_output("#ifndef %s\n", ifdefname);
1173                         else
1174                                 diff_output("#ifdef %s\n", ifdefname);
1175                 }
1176                 inifdef = 1 + oldfile;
1177         }
1178         for (i = a; i <= b; i++) {
1179                 fseek(lb, f[i - 1], SEEK_SET);
1180                 nc = f[i] - f[i - 1];
1181                 if ((diff_format != D_IFDEF && diff_format != D_GFORMAT) &&
1182                     ch != '\0') {
1183                         diff_output("%c", ch);
1184                         if (Tflag && (diff_format == D_NORMAL || diff_format == D_CONTEXT
1185                             || diff_format == D_UNIFIED))
1186                                 diff_output("\t");
1187                         else if (diff_format != D_UNIFIED)
1188                                 diff_output(" ");
1189                 }
1190                 col = 0;
1191                 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
1192                         if ((c = getc(lb)) == EOF) {
1193                                 if (diff_format == D_EDIT || diff_format == D_REVERSE ||
1194                                     diff_format == D_NREVERSE)
1195                                         warnx("No newline at end of file");
1196                                 else
1197                                         diff_output("\n\\ No newline at end of "
1198                                             "file\n");
1199                                 return (0);
1200                         }
1201                         if (c == '\t' && (flags & D_EXPANDTABS)) {
1202                                 newcol = ((col/tabsize)+1)*tabsize;
1203                                 do {
1204                                         diff_output(" ");
1205                                 } while (++col < newcol);
1206                         } else {
1207                                 if (diff_format == D_EDIT && j == 1 && c == '\n'
1208                                     && lastc == '.') {
1209                                         /*
1210                                          * Don't print a bare "." line
1211                                          * since that will confuse ed(1).
1212                                          * Print ".." instead and return,
1213                                          * giving the caller an offset
1214                                          * from which to restart.
1215                                          */
1216                                         diff_output(".\n");
1217                                         return (i - a + 1);
1218                                 }
1219                                 diff_output("%c", c);
1220                                 col++;
1221                         }
1222                 }
1223         }
1224         return (0);
1225 }
1226
1227 /*
1228  * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
1229  */
1230 static int
1231 readhash(FILE *f, int flags)
1232 {
1233         int i, t, space;
1234         int sum;
1235
1236         sum = 1;
1237         space = 0;
1238         if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) == 0) {
1239                 if (flags & D_IGNORECASE)
1240                         for (i = 0; (t = getc(f)) != '\n'; i++) {
1241                                 if (flags & D_STRIPCR && t == '\r') {
1242                                         t = getc(f);
1243                                         if (t == '\n')
1244                                                 break;
1245                                         ungetc(t, f);
1246                                 }
1247                                 if (t == EOF) {
1248                                         if (i == 0)
1249                                                 return (0);
1250                                         break;
1251                                 }
1252                                 sum = sum * 127 + chrtran(t);
1253                         }
1254                 else
1255                         for (i = 0; (t = getc(f)) != '\n'; i++) {
1256                                 if (flags & D_STRIPCR && t == '\r') {
1257                                         t = getc(f);
1258                                         if (t == '\n')
1259                                                 break;
1260                                         ungetc(t, f);
1261                                 }
1262                                 if (t == EOF) {
1263                                         if (i == 0)
1264                                                 return (0);
1265                                         break;
1266                                 }
1267                                 sum = sum * 127 + t;
1268                         }
1269         } else {
1270                 for (i = 0;;) {
1271                         switch (t = getc(f)) {
1272                         case '\r':
1273                         case '\t':
1274                         case '\v':
1275                         case '\f':
1276                         case ' ':
1277                                 space++;
1278                                 continue;
1279                         default:
1280                                 if (space && (flags & D_IGNOREBLANKS) == 0) {
1281                                         i++;
1282                                         space = 0;
1283                                 }
1284                                 sum = sum * 127 + chrtran(t);
1285                                 i++;
1286                                 continue;
1287                         case EOF:
1288                                 if (i == 0)
1289                                         return (0);
1290                                 /* FALLTHROUGH */
1291                         case '\n':
1292                                 break;
1293                         }
1294                         break;
1295                 }
1296         }
1297         /*
1298          * There is a remote possibility that we end up with a zero sum.
1299          * Zero is used as an EOF marker, so return 1 instead.
1300          */
1301         return (sum == 0 ? 1 : sum);
1302 }
1303
1304 static int
1305 asciifile(FILE *f)
1306 {
1307         unsigned char buf[BUFSIZ];
1308         size_t cnt;
1309
1310         if (f == NULL)
1311                 return (1);
1312
1313         rewind(f);
1314         cnt = fread(buf, 1, sizeof(buf), f);
1315         return (memchr(buf, '\0', cnt) == NULL);
1316 }
1317
1318 #define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
1319
1320 static char *
1321 match_function(const long *f, int pos, FILE *fp)
1322 {
1323         unsigned char buf[FUNCTION_CONTEXT_SIZE];
1324         size_t nc;
1325         int last = lastline;
1326         const char *state = NULL;
1327
1328         lastline = pos;
1329         while (pos > last) {
1330                 fseek(fp, f[pos - 1], SEEK_SET);
1331                 nc = f[pos] - f[pos - 1];
1332                 if (nc >= sizeof(buf))
1333                         nc = sizeof(buf) - 1;
1334                 nc = fread(buf, 1, nc, fp);
1335                 if (nc > 0) {
1336                         buf[nc] = '\0';
1337                         buf[strcspn(buf, "\n")] = '\0';
1338                         if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$') {
1339                                 if (begins_with(buf, "private:")) {
1340                                         if (!state)
1341                                                 state = " (private)";
1342                                 } else if (begins_with(buf, "protected:")) {
1343                                         if (!state)
1344                                                 state = " (protected)";
1345                                 } else if (begins_with(buf, "public:")) {
1346                                         if (!state)
1347                                                 state = " (public)";
1348                                 } else {
1349                                         strlcpy(lastbuf, buf, sizeof lastbuf);
1350                                         if (state)
1351                                                 strlcat(lastbuf, state,
1352                                                     sizeof lastbuf);
1353                                         lastmatchline = pos;
1354                                         return lastbuf;
1355                                 }
1356                         }
1357                 }
1358                 pos--;
1359         }
1360         return lastmatchline > 0 ? lastbuf : NULL;
1361 }
1362
1363 /* dump accumulated "context" diff changes */
1364 static void
1365 dump_context_vec(FILE *f1, FILE *f2, int flags)
1366 {
1367         struct context_vec *cvp = context_vec_start;
1368         int lowa, upb, lowc, upd, do_output;
1369         int a, b, c, d;
1370         char ch, *f;
1371
1372         if (context_vec_start > context_vec_ptr)
1373                 return;
1374
1375         b = d = 0;              /* gcc */
1376         lowa = MAX(1, cvp->a - diff_context);
1377         upb = MIN(len[0], context_vec_ptr->b + diff_context);
1378         lowc = MAX(1, cvp->c - diff_context);
1379         upd = MIN(len[1], context_vec_ptr->d + diff_context);
1380
1381         diff_output("***************");
1382         if ((flags & D_PROTOTYPE)) {
1383                 f = match_function(ixold, lowa-1, f1);
1384                 if (f != NULL)
1385                         diff_output(" %s", f);
1386         }
1387         diff_output("\n*** ");
1388         range(lowa, upb, ",");
1389         diff_output(" ****\n");
1390
1391         /*
1392          * Output changes to the "old" file.  The first loop suppresses
1393          * output if there were no changes to the "old" file (we'll see
1394          * the "old" lines as context in the "new" list).
1395          */
1396         do_output = 0;
1397         for (; cvp <= context_vec_ptr; cvp++)
1398                 if (cvp->a <= cvp->b) {
1399                         cvp = context_vec_start;
1400                         do_output++;
1401                         break;
1402                 }
1403         if (do_output) {
1404                 while (cvp <= context_vec_ptr) {
1405                         a = cvp->a;
1406                         b = cvp->b;
1407                         c = cvp->c;
1408                         d = cvp->d;
1409
1410                         if (a <= b && c <= d)
1411                                 ch = 'c';
1412                         else
1413                                 ch = (a <= b) ? 'd' : 'a';
1414
1415                         if (ch == 'a')
1416                                 fetch(ixold, lowa, b, f1, ' ', 0, flags);
1417                         else {
1418                                 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1419                                 fetch(ixold, a, b, f1,
1420                                     ch == 'c' ? '!' : '-', 0, flags);
1421                         }
1422                         lowa = b + 1;
1423                         cvp++;
1424                 }
1425                 fetch(ixold, b + 1, upb, f1, ' ', 0, flags);
1426         }
1427         /* output changes to the "new" file */
1428         diff_output("--- ");
1429         range(lowc, upd, ",");
1430         diff_output(" ----\n");
1431
1432         do_output = 0;
1433         for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++)
1434                 if (cvp->c <= cvp->d) {
1435                         cvp = context_vec_start;
1436                         do_output++;
1437                         break;
1438                 }
1439         if (do_output) {
1440                 while (cvp <= context_vec_ptr) {
1441                         a = cvp->a;
1442                         b = cvp->b;
1443                         c = cvp->c;
1444                         d = cvp->d;
1445
1446                         if (a <= b && c <= d)
1447                                 ch = 'c';
1448                         else
1449                                 ch = (a <= b) ? 'd' : 'a';
1450
1451                         if (ch == 'd')
1452                                 fetch(ixnew, lowc, d, f2, ' ', 0, flags);
1453                         else {
1454                                 fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1455                                 fetch(ixnew, c, d, f2,
1456                                     ch == 'c' ? '!' : '+', 0, flags);
1457                         }
1458                         lowc = d + 1;
1459                         cvp++;
1460                 }
1461                 fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1462         }
1463         context_vec_ptr = context_vec_start - 1;
1464 }
1465
1466 /* dump accumulated "unified" diff changes */
1467 static void
1468 dump_unified_vec(FILE *f1, FILE *f2, int flags)
1469 {
1470         struct context_vec *cvp = context_vec_start;
1471         int lowa, upb, lowc, upd;
1472         int a, b, c, d;
1473         char ch, *f;
1474
1475         if (context_vec_start > context_vec_ptr)
1476                 return;
1477
1478         b = d = 0;              /* gcc */
1479         lowa = MAX(1, cvp->a - diff_context);
1480         upb = MIN(len[0], context_vec_ptr->b + diff_context);
1481         lowc = MAX(1, cvp->c - diff_context);
1482         upd = MIN(len[1], context_vec_ptr->d + diff_context);
1483
1484         diff_output("@@ -");
1485         uni_range(lowa, upb);
1486         diff_output(" +");
1487         uni_range(lowc, upd);
1488         diff_output(" @@");
1489         if ((flags & D_PROTOTYPE)) {
1490                 f = match_function(ixold, lowa-1, f1);
1491                 if (f != NULL)
1492                         diff_output(" %s", f);
1493         }
1494         diff_output("\n");
1495
1496         /*
1497          * Output changes in "unified" diff format--the old and new lines
1498          * are printed together.
1499          */
1500         for (; cvp <= context_vec_ptr; cvp++) {
1501                 a = cvp->a;
1502                 b = cvp->b;
1503                 c = cvp->c;
1504                 d = cvp->d;
1505
1506                 /*
1507                  * c: both new and old changes
1508                  * d: only changes in the old file
1509                  * a: only changes in the new file
1510                  */
1511                 if (a <= b && c <= d)
1512                         ch = 'c';
1513                 else
1514                         ch = (a <= b) ? 'd' : 'a';
1515
1516                 switch (ch) {
1517                 case 'c':
1518                         fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1519                         fetch(ixold, a, b, f1, '-', 0, flags);
1520                         fetch(ixnew, c, d, f2, '+', 0, flags);
1521                         break;
1522                 case 'd':
1523                         fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1524                         fetch(ixold, a, b, f1, '-', 0, flags);
1525                         break;
1526                 case 'a':
1527                         fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1528                         fetch(ixnew, c, d, f2, '+', 0, flags);
1529                         break;
1530                 }
1531                 lowa = b + 1;
1532                 lowc = d + 1;
1533         }
1534         fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1535
1536         context_vec_ptr = context_vec_start - 1;
1537 }
1538
1539 static void
1540 print_header(const char *file1, const char *file2)
1541 {
1542         const char *time_format;
1543         char buf1[256];
1544         char buf2[256];
1545         char end1[10];
1546         char end2[10];
1547         struct tm tm1, tm2, *tm_ptr1, *tm_ptr2;
1548         int nsec1 = stb1.st_mtim.tv_nsec;
1549         int nsec2 = stb2.st_mtim.tv_nsec;
1550
1551         time_format = "%Y-%m-%d %H:%M:%S";
1552
1553         if (cflag)
1554                 time_format = "%c";
1555         tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1);
1556         tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2);
1557         strftime(buf1, 256, time_format, tm_ptr1);
1558         strftime(buf2, 256, time_format, tm_ptr2);
1559         if (!cflag) {
1560                 strftime(end1, 10, "%z", tm_ptr1);
1561                 strftime(end2, 10, "%z", tm_ptr2);
1562                 sprintf(buf1, "%s.%.9d %s", buf1, nsec1, end1);
1563                 sprintf(buf2, "%s.%.9d %s", buf2, nsec2, end2);
1564         }
1565         if (label[0] != NULL)
1566                 diff_output("%s %s\n", diff_format == D_CONTEXT ? "***" : "---",
1567                     label[0]);
1568         else
1569                 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "***" : "---",
1570                     file1, buf1);
1571         if (label[1] != NULL)
1572                 diff_output("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++",
1573                     label[1]);
1574         else
1575                 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "---" : "+++",
1576                     file2, buf2);
1577 }