]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/diff/diffreg.c
diff: eliminate space at end of line
[FreeBSD/FreeBSD.git] / usr.bin / diff / diffreg.c
1 /*      $OpenBSD: diffreg.c,v 1.93 2019/06/28 13:35:00 deraadt 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 #define MIN_PAD         1
185 static FILE     *opentemp(const char *);
186 static void      output(char *, FILE *, char *, FILE *, int);
187 static void      check(FILE *, FILE *, int);
188 static void      range(int, int, const char *);
189 static void      uni_range(int, int);
190 static void      dump_context_vec(FILE *, FILE *, int);
191 static void      dump_unified_vec(FILE *, FILE *, int);
192 static void      prepare(int, FILE *, size_t, int);
193 static void      prune(void);
194 static void      equiv(struct line *, int, struct line *, int, int *);
195 static void      unravel(int);
196 static void      unsort(struct line *, int, int *);
197 static void      change(char *, FILE *, char *, FILE *, int, int, int, int, int *);
198 static void      sort(struct line *, int);
199 static void      print_header(const char *, const char *);
200 static void      print_space(int, int, int);
201 static bool      ignoreline_pattern(char *);
202 static bool      ignoreline(char *, bool);
203 static int       asciifile(FILE *);
204 static int       fetch(long *, int, int, FILE *, int, int, int);
205 static int       newcand(int, int, int);
206 static int       search(int *, int, int);
207 static int       skipline(FILE *);
208 static int       isqrt(int);
209 static int       stone(int *, int, int *, int *, int);
210 static int       readhash(FILE *, int);
211 static int       files_differ(FILE *, FILE *, int);
212 static char     *match_function(const long *, int, FILE *);
213 static char     *preadline(int, size_t, off_t);
214
215 static int  *J;                 /* will be overlaid on class */
216 static int  *class;             /* will be overlaid on file[0] */
217 static int  *klist;             /* will be overlaid on file[0] after class */
218 static int  *member;            /* will be overlaid on file[1] */
219 static int   clen;
220 static int   inifdef;           /* whether or not we are in a #ifdef block */
221 static int   len[2];
222 static int   pref, suff;        /* length of prefix and suffix */
223 static int   slen[2];
224 static int   anychange;
225 static int   hw, padding;       /* half width and padding */
226 static int   edoffset;
227 static long *ixnew;             /* will be overlaid on file[1] */
228 static long *ixold;             /* will be overlaid on klist */
229 static struct cand *clist;      /* merely a free storage pot for candidates */
230 static int   clistlen;          /* the length of clist */
231 static struct line *sfile[2];   /* shortened by pruning common prefix/suffix */
232 static int (*chrtran)(int);     /* translation table for case-folding */
233 static struct context_vec *context_vec_start;
234 static struct context_vec *context_vec_end;
235 static struct context_vec *context_vec_ptr;
236
237 #define FUNCTION_CONTEXT_SIZE   55
238 static char lastbuf[FUNCTION_CONTEXT_SIZE];
239 static int lastline;
240 static int lastmatchline;
241
242 static int
243 clow2low(int c)
244 {
245
246         return (c);
247 }
248
249 static int
250 cup2low(int c)
251 {
252
253         return tolower(c);
254 }
255
256 int
257 diffreg(char *file1, char *file2, int flags, int capsicum)
258 {
259         FILE *f1, *f2;
260         int i, rval;
261         struct pr *pr = NULL;
262         cap_rights_t rights_ro;
263
264         f1 = f2 = NULL;
265         rval = D_SAME;
266         anychange = 0;
267         lastline = 0;
268         lastmatchline = 0;
269         context_vec_ptr = context_vec_start - 1;
270
271          /*
272           * hw excludes padding and make sure when -t is not used,
273           * the second column always starts from the closest tab stop
274           */
275         if (diff_format == D_SIDEBYSIDE) {
276                 hw = width >> 1;
277                 padding = tabsize - (hw % tabsize);
278                 if ((flags & D_EXPANDTABS) != 0 || (padding % tabsize == 0))
279                         padding = MIN_PAD;
280         
281                 hw = (width >> 1) -
282                     ((padding == MIN_PAD) ? (padding << 1) : padding) - 1;
283         }
284         
285
286         if (flags & D_IGNORECASE)
287                 chrtran = cup2low;
288         else
289                 chrtran = clow2low;
290         if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
291                 return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
292         if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
293                 goto closem;
294
295         if (flags & D_EMPTY1)
296                 f1 = fopen(_PATH_DEVNULL, "r");
297         else {
298                 if (!S_ISREG(stb1.st_mode)) {
299                         if ((f1 = opentemp(file1)) == NULL ||
300                             fstat(fileno(f1), &stb1) == -1) {
301                                 warn("%s", file1);
302                                 rval = D_ERROR;
303                                 status |= 2;
304                                 goto closem;
305                         }
306                 } else if (strcmp(file1, "-") == 0)
307                         f1 = stdin;
308                 else
309                         f1 = fopen(file1, "r");
310         }
311         if (f1 == NULL) {
312                 warn("%s", file1);
313                 rval = D_ERROR;
314                 status |= 2;
315                 goto closem;
316         }
317
318         if (flags & D_EMPTY2)
319                 f2 = fopen(_PATH_DEVNULL, "r");
320         else {
321                 if (!S_ISREG(stb2.st_mode)) {
322                         if ((f2 = opentemp(file2)) == NULL ||
323                             fstat(fileno(f2), &stb2) == -1) {
324                                 warn("%s", file2);
325                                 rval = D_ERROR;
326                                 status |= 2;
327                                 goto closem;
328                         }
329                 } else if (strcmp(file2, "-") == 0)
330                         f2 = stdin;
331                 else
332                         f2 = fopen(file2, "r");
333         }
334         if (f2 == NULL) {
335                 warn("%s", file2);
336                 rval = D_ERROR;
337                 status |= 2;
338                 goto closem;
339         }
340
341         if (lflag)
342                 pr = start_pr(file1, file2);
343
344         if (capsicum) {
345                 cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
346                 if (caph_rights_limit(fileno(f1), &rights_ro) < 0)
347                         err(2, "unable to limit rights on: %s", file1);
348                 if (caph_rights_limit(fileno(f2), &rights_ro) < 0)
349                         err(2, "unable to limit rights on: %s", file2);
350                 if (fileno(f1) == STDIN_FILENO || fileno(f2) == STDIN_FILENO) {
351                         /* stding has already been limited */
352                         if (caph_limit_stderr() == -1)
353                                 err(2, "unable to limit stderr");
354                         if (caph_limit_stdout() == -1)
355                                 err(2, "unable to limit stdout");
356                 } else if (caph_limit_stdio() == -1)
357                                 err(2, "unable to limit stdio");
358
359                 caph_cache_catpages();
360                 caph_cache_tzdata();
361                 if (caph_enter() < 0)
362                         err(2, "unable to enter capability mode");
363         }
364
365         switch (files_differ(f1, f2, flags)) {
366         case 0:
367                 goto closem;
368         case 1:
369                 break;
370         default:
371                 /* error */
372                 rval = D_ERROR;
373                 status |= 2;
374                 goto closem;
375         }
376
377         if (diff_format == D_BRIEF && ignore_pats == NULL &&
378             (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_STRIPCR)) == 0)
379         {
380                 rval = D_DIFFER;
381                 status |= 1;
382                 goto closem;
383         }
384         if ((flags & D_FORCEASCII) == 0 &&
385             (!asciifile(f1) || !asciifile(f2))) {
386                 rval = D_BINARY;
387                 status |= 1;
388                 goto closem;
389         }
390         prepare(0, f1, stb1.st_size, flags);
391         prepare(1, f2, stb2.st_size, flags);
392
393         prune();
394         sort(sfile[0], slen[0]);
395         sort(sfile[1], slen[1]);
396
397         member = (int *)file[1];
398         equiv(sfile[0], slen[0], sfile[1], slen[1], member);
399         member = xreallocarray(member, slen[1] + 2, sizeof(*member));
400
401         class = (int *)file[0];
402         unsort(sfile[0], slen[0], class);
403         class = xreallocarray(class, slen[0] + 2, sizeof(*class));
404
405         klist = xcalloc(slen[0] + 2, sizeof(*klist));
406         clen = 0;
407         clistlen = 100;
408         clist = xcalloc(clistlen, sizeof(*clist));
409         i = stone(class, slen[0], member, klist, flags);
410         free(member);
411         free(class);
412
413         J = xreallocarray(J, len[0] + 2, sizeof(*J));
414         unravel(klist[i]);
415         free(clist);
416         free(klist);
417
418         ixold = xreallocarray(ixold, len[0] + 2, sizeof(*ixold));
419         ixnew = xreallocarray(ixnew, len[1] + 2, sizeof(*ixnew));
420         check(f1, f2, flags);
421         output(file1, f1, file2, f2, flags);
422
423 closem:
424         if (pr != NULL)
425                 stop_pr(pr);
426         if (anychange) {
427                 status |= 1;
428                 if (rval == D_SAME)
429                         rval = D_DIFFER;
430         }
431         if (f1 != NULL)
432                 fclose(f1);
433         if (f2 != NULL)
434                 fclose(f2);
435
436         return (rval);
437 }
438
439 /*
440  * Check to see if the given files differ.
441  * Returns 0 if they are the same, 1 if different, and -1 on error.
442  * XXX - could use code from cmp(1) [faster]
443  */
444 static int
445 files_differ(FILE *f1, FILE *f2, int flags)
446 {
447         char buf1[BUFSIZ], buf2[BUFSIZ];
448         size_t i, j;
449
450         if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
451             (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
452                 return (1);
453         for (;;) {
454                 i = fread(buf1, 1, sizeof(buf1), f1);
455                 j = fread(buf2, 1, sizeof(buf2), f2);
456                 if ((!i && ferror(f1)) || (!j && ferror(f2)))
457                         return (-1);
458                 if (i != j)
459                         return (1);
460                 if (i == 0)
461                         return (0);
462                 if (memcmp(buf1, buf2, i) != 0)
463                         return (1);
464         }
465 }
466
467 static FILE *
468 opentemp(const char *f)
469 {
470         char buf[BUFSIZ], tempfile[PATH_MAX];
471         ssize_t nread;
472         int ifd, ofd;
473
474         if (strcmp(f, "-") == 0)
475                 ifd = STDIN_FILENO;
476         else if ((ifd = open(f, O_RDONLY, 0644)) == -1)
477                 return (NULL);
478
479         (void)strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile));
480
481         if ((ofd = mkstemp(tempfile)) == -1) {
482                 close(ifd);
483                 return (NULL);
484         }
485         unlink(tempfile);
486         while ((nread = read(ifd, buf, BUFSIZ)) > 0) {
487                 if (write(ofd, buf, nread) != nread) {
488                         close(ifd);
489                         close(ofd);
490                         return (NULL);
491                 }
492         }
493         close(ifd);
494         lseek(ofd, (off_t)0, SEEK_SET);
495         return (fdopen(ofd, "r"));
496 }
497
498 char *
499 splice(char *dir, char *path)
500 {
501         char *tail, *buf;
502         size_t dirlen;
503
504         dirlen = strlen(dir);
505         while (dirlen != 0 && dir[dirlen - 1] == '/')
506             dirlen--;
507         if ((tail = strrchr(path, '/')) == NULL)
508                 tail = path;
509         else
510                 tail++;
511         xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);
512         return (buf);
513 }
514
515 static void
516 prepare(int i, FILE *fd, size_t filesize, int flags)
517 {
518         struct line *p;
519         int h;
520         size_t sz, j;
521
522         rewind(fd);
523
524         sz = MIN(filesize, SIZE_MAX) / 25;
525         if (sz < 100)
526                 sz = 100;
527
528         p = xcalloc(sz + 3, sizeof(*p));
529         for (j = 0; (h = readhash(fd, flags));) {
530                 if (j == sz) {
531                         sz = sz * 3 / 2;
532                         p = xreallocarray(p, sz + 3, sizeof(*p));
533                 }
534                 p[++j].value = h;
535         }
536         len[i] = j;
537         file[i] = p;
538 }
539
540 static void
541 prune(void)
542 {
543         int i, j;
544
545         for (pref = 0; pref < len[0] && pref < len[1] &&
546             file[0][pref + 1].value == file[1][pref + 1].value;
547             pref++)
548                 ;
549         for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
550             file[0][len[0] - suff].value == file[1][len[1] - suff].value;
551             suff++)
552                 ;
553         for (j = 0; j < 2; j++) {
554                 sfile[j] = file[j] + pref;
555                 slen[j] = len[j] - pref - suff;
556                 for (i = 0; i <= slen[j]; i++)
557                         sfile[j][i].serial = i;
558         }
559 }
560
561 static void
562 equiv(struct line *a, int n, struct line *b, int m, int *c)
563 {
564         int i, j;
565
566         i = j = 1;
567         while (i <= n && j <= m) {
568                 if (a[i].value < b[j].value)
569                         a[i++].value = 0;
570                 else if (a[i].value == b[j].value)
571                         a[i++].value = j;
572                 else
573                         j++;
574         }
575         while (i <= n)
576                 a[i++].value = 0;
577         b[m + 1].value = 0;
578         j = 0;
579         while (++j <= m) {
580                 c[j] = -b[j].serial;
581                 while (b[j + 1].value == b[j].value) {
582                         j++;
583                         c[j] = b[j].serial;
584                 }
585         }
586         c[j] = -1;
587 }
588
589 /* Code taken from ping.c */
590 static int
591 isqrt(int n)
592 {
593         int y, x = 1;
594
595         if (n == 0)
596                 return (0);
597
598         do { /* newton was a stinker */
599                 y = x;
600                 x = n / x;
601                 x += y;
602                 x /= 2;
603         } while ((x - y) > 1 || (x - y) < -1);
604
605         return (x);
606 }
607
608 static int
609 stone(int *a, int n, int *b, int *c, int flags)
610 {
611         int i, k, y, j, l;
612         int oldc, tc, oldl, sq;
613         u_int numtries, bound;
614
615         if (flags & D_MINIMAL)
616                 bound = UINT_MAX;
617         else {
618                 sq = isqrt(n);
619                 bound = MAX(256, sq);
620         }
621
622         k = 0;
623         c[0] = newcand(0, 0, 0);
624         for (i = 1; i <= n; i++) {
625                 j = a[i];
626                 if (j == 0)
627                         continue;
628                 y = -b[j];
629                 oldl = 0;
630                 oldc = c[0];
631                 numtries = 0;
632                 do {
633                         if (y <= clist[oldc].y)
634                                 continue;
635                         l = search(c, k, y);
636                         if (l != oldl + 1)
637                                 oldc = c[l - 1];
638                         if (l <= k) {
639                                 if (clist[c[l]].y <= y)
640                                         continue;
641                                 tc = c[l];
642                                 c[l] = newcand(i, y, oldc);
643                                 oldc = tc;
644                                 oldl = l;
645                                 numtries++;
646                         } else {
647                                 c[l] = newcand(i, y, oldc);
648                                 k++;
649                                 break;
650                         }
651                 } while ((y = b[++j]) > 0 && numtries < bound);
652         }
653         return (k);
654 }
655
656 static int
657 newcand(int x, int y, int pred)
658 {
659         struct cand *q;
660
661         if (clen == clistlen) {
662                 clistlen = clistlen * 11 / 10;
663                 clist = xreallocarray(clist, clistlen, sizeof(*clist));
664         }
665         q = clist + clen;
666         q->x = x;
667         q->y = y;
668         q->pred = pred;
669         return (clen++);
670 }
671
672 static int
673 search(int *c, int k, int y)
674 {
675         int i, j, l, t;
676
677         if (clist[c[k]].y < y)  /* quick look for typical case */
678                 return (k + 1);
679         i = 0;
680         j = k + 1;
681         for (;;) {
682                 l = (i + j) / 2;
683                 if (l <= i)
684                         break;
685                 t = clist[c[l]].y;
686                 if (t > y)
687                         j = l;
688                 else if (t < y)
689                         i = l;
690                 else
691                         return (l);
692         }
693         return (l + 1);
694 }
695
696 static void
697 unravel(int p)
698 {
699         struct cand *q;
700         int i;
701
702         for (i = 0; i <= len[0]; i++)
703                 J[i] = i <= pref ? i :
704                     i > len[0] - suff ? i + len[1] - len[0] : 0;
705         for (q = clist + p; q->y != 0; q = clist + q->pred)
706                 J[q->x + pref] = q->y + pref;
707 }
708
709 /*
710  * Check does double duty:
711  *  1.  ferret out any fortuitous correspondences due
712  *      to confounding by hashing (which result in "jackpot")
713  *  2.  collect random access indexes to the two files
714  */
715 static void
716 check(FILE *f1, FILE *f2, int flags)
717 {
718         int i, j, jackpot, c, d;
719         long ctold, ctnew;
720
721         rewind(f1);
722         rewind(f2);
723         j = 1;
724         ixold[0] = ixnew[0] = 0;
725         jackpot = 0;
726         ctold = ctnew = 0;
727         for (i = 1; i <= len[0]; i++) {
728                 if (J[i] == 0) {
729                         ixold[i] = ctold += skipline(f1);
730                         continue;
731                 }
732                 while (j < J[i]) {
733                         ixnew[j] = ctnew += skipline(f2);
734                         j++;
735                 }
736                 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_STRIPCR)) {
737                         for (;;) {
738                                 c = getc(f1);
739                                 d = getc(f2);
740                                 /*
741                                  * GNU diff ignores a missing newline
742                                  * in one file for -b or -w.
743                                  */
744                                 if (flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) {
745                                         if (c == EOF && d == '\n') {
746                                                 ctnew++;
747                                                 break;
748                                         } else if (c == '\n' && d == EOF) {
749                                                 ctold++;
750                                                 break;
751                                         }
752                                 }
753                                 ctold++;
754                                 ctnew++;
755                                 if (flags & D_STRIPCR && (c == '\r' || d == '\r')) {
756                                         if (c == '\r') {
757                                                 if ((c = getc(f1)) == '\n') {
758                                                         ctold++;
759                                                 } else {
760                                                         ungetc(c, f1);
761                                                 }
762                                         }
763                                         if (d == '\r') {
764                                                 if ((d = getc(f2)) == '\n') {
765                                                         ctnew++;
766                                                 } else {
767                                                         ungetc(d, f2);
768                                                 }
769                                         }
770                                         break;
771                                 }
772                                 if ((flags & D_FOLDBLANKS) && isspace(c) &&
773                                     isspace(d)) {
774                                         do {
775                                                 if (c == '\n')
776                                                         break;
777                                                 ctold++;
778                                         } while (isspace(c = getc(f1)));
779                                         do {
780                                                 if (d == '\n')
781                                                         break;
782                                                 ctnew++;
783                                         } while (isspace(d = getc(f2)));
784                                 } else if ((flags & D_IGNOREBLANKS)) {
785                                         while (isspace(c) && c != '\n') {
786                                                 c = getc(f1);
787                                                 ctold++;
788                                         }
789                                         while (isspace(d) && d != '\n') {
790                                                 d = getc(f2);
791                                                 ctnew++;
792                                         }
793                                 }
794                                 if (chrtran(c) != chrtran(d)) {
795                                         jackpot++;
796                                         J[i] = 0;
797                                         if (c != '\n' && c != EOF)
798                                                 ctold += skipline(f1);
799                                         if (d != '\n' && c != EOF)
800                                                 ctnew += skipline(f2);
801                                         break;
802                                 }
803                                 if (c == '\n' || c == EOF)
804                                         break;
805                         }
806                 } else {
807                         for (;;) {
808                                 ctold++;
809                                 ctnew++;
810                                 if ((c = getc(f1)) != (d = getc(f2))) {
811                                         /* jackpot++; */
812                                         J[i] = 0;
813                                         if (c != '\n' && c != EOF)
814                                                 ctold += skipline(f1);
815                                         if (d != '\n' && c != EOF)
816                                                 ctnew += skipline(f2);
817                                         break;
818                                 }
819                                 if (c == '\n' || c == EOF)
820                                         break;
821                         }
822                 }
823                 ixold[i] = ctold;
824                 ixnew[j] = ctnew;
825                 j++;
826         }
827         for (; j <= len[1]; j++) {
828                 ixnew[j] = ctnew += skipline(f2);
829         }
830         /*
831          * if (jackpot)
832          *      fprintf(stderr, "jackpot\n");
833          */
834 }
835
836 /* shellsort CACM #201 */
837 static void
838 sort(struct line *a, int n)
839 {
840         struct line *ai, *aim, w;
841         int j, m = 0, k;
842
843         if (n == 0)
844                 return;
845         for (j = 1; j <= n; j *= 2)
846                 m = 2 * j - 1;
847         for (m /= 2; m != 0; m /= 2) {
848                 k = n - m;
849                 for (j = 1; j <= k; j++) {
850                         for (ai = &a[j]; ai > a; ai -= m) {
851                                 aim = &ai[m];
852                                 if (aim < ai)
853                                         break;  /* wraparound */
854                                 if (aim->value > ai[0].value ||
855                                     (aim->value == ai[0].value &&
856                                         aim->serial > ai[0].serial))
857                                         break;
858                                 w.value = ai[0].value;
859                                 ai[0].value = aim->value;
860                                 aim->value = w.value;
861                                 w.serial = ai[0].serial;
862                                 ai[0].serial = aim->serial;
863                                 aim->serial = w.serial;
864                         }
865                 }
866         }
867 }
868
869 static void
870 unsort(struct line *f, int l, int *b)
871 {
872         int *a, i;
873
874         a = xcalloc(l + 1, sizeof(*a));
875         for (i = 1; i <= l; i++)
876                 a[f[i].serial] = f[i].value;
877         for (i = 1; i <= l; i++)
878                 b[i] = a[i];
879         free(a);
880 }
881
882 static int
883 skipline(FILE *f)
884 {
885         int i, c;
886
887         for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
888                 continue;
889         return (i);
890 }
891
892 static void
893 output(char *file1, FILE *f1, char *file2, FILE *f2, int flags)
894 {
895         int i, j, m, i0, i1, j0, j1, nc;
896
897         rewind(f1);
898         rewind(f2);
899         m = len[0];
900         J[0] = 0;
901         J[m + 1] = len[1] + 1;
902         if (diff_format != D_EDIT) {
903                 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
904                         while (i0 <= m && J[i0] == J[i0 - 1] + 1){
905                                 if (diff_format == D_SIDEBYSIDE &&
906                                     suppress_common != 1) {
907                                         nc = fetch(ixold, i0, i0, f1, '\0',
908                                             1, flags);
909                                         print_space(nc,
910                                             (hw - nc) + (padding << 1) + 1,
911                                             flags);
912                                         fetch(ixnew, J[i0], J[i0], f2, '\0',
913                                             0, flags);
914                                         diff_output("\n");
915                                 }
916                                 i0++;
917                         }
918                         j0 = J[i0 - 1] + 1;
919                         i1 = i0 - 1;
920                         while (i1 < m && J[i1 + 1] == 0)
921                                 i1++;
922                         j1 = J[i1 + 1] - 1;
923                         J[i1] = j1;
924
925                         /*
926                          * When using side-by-side, lines from both of the
927                          * files are printed. The algorithm used by diff(1)
928                          * identifies the ranges in which two files differ.
929                          * See the change() function below.
930                          * The for loop below consumes the shorter range,
931                          * whereas one of the while loops deals with the
932                          * longer one.
933                          */
934                         if (diff_format == D_SIDEBYSIDE) {
935                                 for (i=i0, j=j0; i<=i1 && j<=j1; i++, j++)
936                                         change(file1, f1, file2, f2, i, i,
937                                             j, j, &flags);
938
939                                 while (i <= i1) {
940                                         change(file1, f1, file2, f2,
941                                             i, i, j+1, j, &flags);
942                                         i++;
943                                 }
944
945                                 while (j <= j1) {
946                                         change(file1, f1, file2, f2,
947                                             i+1, i, j, j, &flags);
948                                         j++;
949                                 }
950                         } else
951                                 change(file1, f1, file2, f2, i0, i1, j0,
952                                     j1, &flags);
953                 }
954         } else {
955                 for (i0 = m; i0 >= 1; i0 = i1 - 1) {
956                         while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0)
957                                 i0--;
958                         j0 = J[i0 + 1] - 1;
959                         i1 = i0 + 1;
960                         while (i1 > 1 && J[i1 - 1] == 0)
961                                 i1--;
962                         j1 = J[i1 - 1] + 1;
963                         J[i1] = j1;
964                         change(file1, f1, file2, f2, i1, i0, j1, j0, &flags);
965                 }
966         }
967         if (m == 0)
968                 change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags);
969         if (diff_format == D_IFDEF || diff_format == D_GFORMAT) {
970                 for (;;) {
971 #define c i0
972                         if ((c = getc(f1)) == EOF)
973                                 return;
974                         diff_output("%c", c);
975                 }
976 #undef c
977         }
978         if (anychange != 0) {
979                 if (diff_format == D_CONTEXT)
980                         dump_context_vec(f1, f2, flags);
981                 else if (diff_format == D_UNIFIED)
982                         dump_unified_vec(f1, f2, flags);
983         }
984 }
985
986 static void
987 range(int a, int b, const char *separator)
988 {
989         diff_output("%d", a > b ? b : a);
990         if (a < b)
991                 diff_output("%s%d", separator, b);
992 }
993
994 static void
995 uni_range(int a, int b)
996 {
997         if (a < b)
998                 diff_output("%d,%d", a, b - a + 1);
999         else if (a == b)
1000                 diff_output("%d", b);
1001         else
1002                 diff_output("%d,0", b);
1003 }
1004
1005 static char *
1006 preadline(int fd, size_t rlen, off_t off)
1007 {
1008         char *line;
1009         ssize_t nr;
1010
1011         line = xmalloc(rlen + 1);
1012         if ((nr = pread(fd, line, rlen, off)) == -1)
1013                 err(2, "preadline");
1014         if (nr > 0 && line[nr-1] == '\n')
1015                 nr--;
1016         line[nr] = '\0';
1017         return (line);
1018 }
1019
1020 static bool
1021 ignoreline_pattern(char *line)
1022 {
1023         int ret;
1024
1025         ret = regexec(&ignore_re, line, 0, NULL, 0);
1026         free(line);
1027         return (ret == 0);      /* if it matched, it should be ignored. */
1028 }
1029
1030 static bool
1031 ignoreline(char *line, bool skip_blanks)
1032 {
1033
1034         if (ignore_pats != NULL && skip_blanks)
1035                 return (ignoreline_pattern(line) || *line == '\0');
1036         if (ignore_pats != NULL)
1037                 return (ignoreline_pattern(line));
1038         if (skip_blanks)
1039                 return (*line == '\0');
1040         /* No ignore criteria specified */
1041         return (false);
1042 }
1043
1044 /*
1045  * Indicate that there is a difference between lines a and b of the from file
1046  * to get to lines c to d of the to file.  If a is greater then b then there
1047  * are no lines in the from file involved and this means that there were
1048  * lines appended (beginning at b).  If c is greater than d then there are
1049  * lines missing from the to file.
1050  */
1051 static void
1052 change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d,
1053     int *pflags)
1054 {
1055         static size_t max_context = 64;
1056         long curpos;
1057         int i, nc;
1058         const char *walk;
1059         bool skip_blanks;
1060
1061         skip_blanks = (*pflags & D_SKIPBLANKLINES);
1062 restart:
1063         if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) &&
1064             a > b && c > d)
1065                 return;
1066         if (ignore_pats != NULL || skip_blanks) {
1067                 char *line;
1068                 /*
1069                  * All lines in the change, insert, or delete must
1070                  * match an ignore pattern for the change to be
1071                  * ignored.
1072                  */
1073                 if (a <= b) {           /* Changes and deletes. */
1074                         for (i = a; i <= b; i++) {
1075                                 line = preadline(fileno(f1),
1076                                     ixold[i] - ixold[i - 1], ixold[i - 1]);
1077                                 if (!ignoreline(line, skip_blanks))
1078                                         goto proceed;
1079                         }
1080                 }
1081                 if (a > b || c <= d) {  /* Changes and inserts. */
1082                         for (i = c; i <= d; i++) {
1083                                 line = preadline(fileno(f2),
1084                                     ixnew[i] - ixnew[i - 1], ixnew[i - 1]);
1085                                 if (!ignoreline(line, skip_blanks))
1086                                         goto proceed;
1087                         }
1088                 }
1089                 return;
1090         }
1091 proceed:
1092         if (*pflags & D_HEADER && diff_format != D_BRIEF) {
1093                 diff_output("%s %s %s\n", diffargs, file1, file2);
1094                 *pflags &= ~D_HEADER;
1095         }
1096         if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) {
1097                 /*
1098                  * Allocate change records as needed.
1099                  */
1100                 if (context_vec_ptr == context_vec_end - 1) {
1101                         ptrdiff_t offset = context_vec_ptr - context_vec_start;
1102                         max_context <<= 1;
1103                         context_vec_start = xreallocarray(context_vec_start,
1104                             max_context, sizeof(*context_vec_start));
1105                         context_vec_end = context_vec_start + max_context;
1106                         context_vec_ptr = context_vec_start + offset;
1107                 }
1108                 if (anychange == 0) {
1109                         /*
1110                          * Print the context/unidiff header first time through.
1111                          */
1112                         print_header(file1, file2);
1113                         anychange = 1;
1114                 } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 &&
1115                     c > context_vec_ptr->d + (2 * diff_context) + 1) {
1116                         /*
1117                          * If this change is more than 'diff_context' lines from the
1118                          * previous change, dump the record and reset it.
1119                          */
1120                         if (diff_format == D_CONTEXT)
1121                                 dump_context_vec(f1, f2, *pflags);
1122                         else
1123                                 dump_unified_vec(f1, f2, *pflags);
1124                 }
1125                 context_vec_ptr++;
1126                 context_vec_ptr->a = a;
1127                 context_vec_ptr->b = b;
1128                 context_vec_ptr->c = c;
1129                 context_vec_ptr->d = d;
1130                 return;
1131         }
1132         if (anychange == 0)
1133                 anychange = 1;
1134         switch (diff_format) {
1135         case D_BRIEF:
1136                 return;
1137         case D_NORMAL:
1138         case D_EDIT:
1139                 range(a, b, ",");
1140                 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1141                 if (diff_format == D_NORMAL)
1142                         range(c, d, ",");
1143                 diff_output("\n");
1144                 break;
1145         case D_REVERSE:
1146                 diff_output("%c", a > b ? 'a' : c > d ? 'd' : 'c');
1147                 range(a, b, " ");
1148                 diff_output("\n");
1149                 break;
1150         case D_NREVERSE:
1151                 if (a > b)
1152                         diff_output("a%d %d\n", b, d - c + 1);
1153                 else {
1154                         diff_output("d%d %d\n", a, b - a + 1);
1155                         if (!(c > d))
1156                                 /* add changed lines */
1157                                 diff_output("a%d %d\n", b, d - c + 1);
1158                 }
1159                 break;
1160         }
1161         if (diff_format == D_GFORMAT) {
1162                 curpos = ftell(f1);
1163                 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1164                 nc = ixold[a > b ? b : a - 1] - curpos;
1165                 for (i = 0; i < nc; i++)
1166                         diff_output("%c", getc(f1));
1167                 for (walk = group_format; *walk != '\0'; walk++) {
1168                         if (*walk == '%') {
1169                                 walk++;
1170                                 switch (*walk) {
1171                                 case '<':
1172                                         fetch(ixold, a, b, f1, '<', 1, *pflags);
1173                                         break;
1174                                 case '>':
1175                                         fetch(ixnew, c, d, f2, '>', 0, *pflags);
1176                                         break;
1177                                 default:
1178                                         diff_output("%%%c", *walk);
1179                                         break;
1180                                 }
1181                                 continue;
1182                         }
1183                         diff_output("%c", *walk);
1184                 }
1185         }
1186         if (diff_format == D_SIDEBYSIDE) {
1187                 if (a > b) {
1188                         print_space(0, hw + padding , *pflags);
1189                 } else {
1190                         nc = fetch(ixold, a, b, f1, '\0', 1, *pflags);
1191                         print_space(nc, hw - nc + padding, *pflags);
1192                 }
1193                 diff_output("%c", (a>b)? '>' : ((c>d)? '<' : '|'));
1194                 print_space(hw + padding + 1 , padding, *pflags);
1195                 fetch(ixnew, c, d, f2, '\0', 0, *pflags);
1196                 diff_output("\n");
1197         }
1198         if (diff_format == D_NORMAL || diff_format == D_IFDEF) {
1199                 fetch(ixold, a, b, f1, '<', 1, *pflags);
1200                 if (a <= b && c <= d && diff_format == D_NORMAL)
1201                         diff_output("---\n");
1202         }
1203         if (diff_format != D_GFORMAT && diff_format != D_SIDEBYSIDE)
1204                 fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags);
1205         if (edoffset != 0 && diff_format == D_EDIT) {
1206                 /*
1207                  * A non-zero edoffset value for D_EDIT indicates that the
1208                  * last line printed was a bare dot (".") that has been
1209                  * escaped as ".." to prevent ed(1) from misinterpreting
1210                  * it.  We have to add a substitute command to change this
1211                  * back and restart where we left off.
1212                  */
1213                 diff_output(".\n");
1214                 diff_output("%ds/.//\n", a + edoffset - 1);
1215                 b = a + edoffset - 1;
1216                 a = b + 1;
1217                 c += edoffset;
1218                 goto restart;
1219         }
1220         if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d)
1221                 diff_output(".\n");
1222         if (inifdef) {
1223                 diff_output("#endif /* %s */\n", ifdefname);
1224                 inifdef = 0;
1225         }
1226 }
1227
1228 static int
1229 fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags)
1230 {
1231         int i, j, c, lastc, col, nc, newcol;
1232
1233         edoffset = 0;
1234         nc = 0;
1235         /*
1236          * When doing #ifdef's, copy down to current line
1237          * if this is the first file, so that stuff makes it to output.
1238          */
1239         if ((diff_format == D_IFDEF) && oldfile) {
1240                 long curpos = ftell(lb);
1241                 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
1242                 nc = f[a > b ? b : a - 1] - curpos;
1243                 for (i = 0; i < nc; i++)
1244                         diff_output("%c", getc(lb));
1245         }
1246         if (a > b)
1247                 return (0);
1248         if (diff_format == D_IFDEF) {
1249                 if (inifdef) {
1250                         diff_output("#else /* %s%s */\n",
1251                             oldfile == 1 ? "!" : "", ifdefname);
1252                 } else {
1253                         if (oldfile)
1254                                 diff_output("#ifndef %s\n", ifdefname);
1255                         else
1256                                 diff_output("#ifdef %s\n", ifdefname);
1257                 }
1258                 inifdef = 1 + oldfile;
1259         }
1260         for (i = a; i <= b; i++) {
1261                 fseek(lb, f[i - 1], SEEK_SET);
1262                 nc = (f[i] - f[i - 1]);
1263                 if (diff_format == D_SIDEBYSIDE && hw < nc)
1264                         nc = hw;
1265                 if ((diff_format != D_IFDEF && diff_format != D_GFORMAT) &&
1266                     ch != '\0') {
1267                         diff_output("%c", ch);
1268                         if (Tflag && (diff_format == D_NORMAL ||
1269                             diff_format == D_CONTEXT ||
1270                             diff_format == D_UNIFIED))
1271                                 diff_output("\t");
1272                         else if (diff_format != D_UNIFIED)
1273                                 diff_output(" ");
1274                 }
1275                 col = 0;
1276                 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
1277                         if ((c = getc(lb)) == EOF) {
1278                                 if (diff_format == D_EDIT ||
1279                                     diff_format == D_REVERSE ||
1280                                     diff_format == D_NREVERSE)
1281                                         warnx("No newline at end of file");
1282                                 else
1283                                         diff_output("\n\\ No newline at end of "
1284                                             "file\n");
1285                                 return col;
1286                         }
1287                         /*
1288                          * when using --side-by-side, col needs to be increased
1289                          * in any case to keep the columns aligned
1290                          */
1291                         if (c == '\t') {
1292                                 if (flags & D_EXPANDTABS) {
1293                                         newcol = ((col/tabsize)+1)*tabsize;
1294                                         do {    
1295                                                 if (diff_format == D_SIDEBYSIDE)
1296                                                         j++;
1297                                                 diff_output(" ");
1298                                         } while (++col < newcol && j < nc);
1299                                 } else {
1300                                         if (diff_format == D_SIDEBYSIDE) {
1301                                                 if ((j + tabsize) > nc) {
1302                                                         diff_output("%*s",
1303                                                         nc - j,"");
1304                                                         j = col = nc;
1305                                                 } else {
1306                                                         diff_output("\t");
1307                                                         col += tabsize - 1;
1308                                                         j += tabsize - 1;
1309                                                 }
1310                                         } else {
1311                                                 diff_output("\t");
1312                                                 col++;
1313                                         }
1314                                 }
1315                         } else {
1316                                 if (diff_format == D_EDIT && j == 1 && c == '\n'
1317                                     && lastc == '.') {
1318                                         /*
1319                                          * Don't print a bare "." line
1320                                          * since that will confuse ed(1).
1321                                          * Print ".." instead and set the,
1322                                          * global variable edoffset to an
1323                                          * offset from which to restart.
1324                                          * The caller must check the value
1325                                          * of edoffset
1326                                          */
1327                                         diff_output(".\n");
1328                                         edoffset = i - a + 1;
1329                                         return edoffset;
1330                                 }
1331                                 /* when side-by-side, do not print a newline */
1332                                 if (diff_format != D_SIDEBYSIDE || c != '\n') {
1333                                         diff_output("%c", c);
1334                                         col++;
1335                                 }
1336                         }
1337                 }
1338         }
1339         return col;
1340 }
1341
1342 /*
1343  * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
1344  */
1345 static int
1346 readhash(FILE *f, int flags)
1347 {
1348         int i, t, space;
1349         int sum;
1350
1351         sum = 1;
1352         space = 0;
1353         if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) == 0) {
1354                 if (flags & D_IGNORECASE)
1355                         for (i = 0; (t = getc(f)) != '\n'; i++) {
1356                                 if (flags & D_STRIPCR && t == '\r') {
1357                                         t = getc(f);
1358                                         if (t == '\n')
1359                                                 break;
1360                                         ungetc(t, f);
1361                                 }
1362                                 if (t == EOF) {
1363                                         if (i == 0)
1364                                                 return (0);
1365                                         break;
1366                                 }
1367                                 sum = sum * 127 + chrtran(t);
1368                         }
1369                 else
1370                         for (i = 0; (t = getc(f)) != '\n'; i++) {
1371                                 if (flags & D_STRIPCR && t == '\r') {
1372                                         t = getc(f);
1373                                         if (t == '\n')
1374                                                 break;
1375                                         ungetc(t, f);
1376                                 }
1377                                 if (t == EOF) {
1378                                         if (i == 0)
1379                                                 return (0);
1380                                         break;
1381                                 }
1382                                 sum = sum * 127 + t;
1383                         }
1384         } else {
1385                 for (i = 0;;) {
1386                         switch (t = getc(f)) {
1387                         case '\r':
1388                         case '\t':
1389                         case '\v':
1390                         case '\f':
1391                         case ' ':
1392                                 space++;
1393                                 continue;
1394                         default:
1395                                 if (space && (flags & D_IGNOREBLANKS) == 0) {
1396                                         i++;
1397                                         space = 0;
1398                                 }
1399                                 sum = sum * 127 + chrtran(t);
1400                                 i++;
1401                                 continue;
1402                         case EOF:
1403                                 if (i == 0)
1404                                         return (0);
1405                                 /* FALLTHROUGH */
1406                         case '\n':
1407                                 break;
1408                         }
1409                         break;
1410                 }
1411         }
1412         /*
1413          * There is a remote possibility that we end up with a zero sum.
1414          * Zero is used as an EOF marker, so return 1 instead.
1415          */
1416         return (sum == 0 ? 1 : sum);
1417 }
1418
1419 static int
1420 asciifile(FILE *f)
1421 {
1422         unsigned char buf[BUFSIZ];
1423         size_t cnt;
1424
1425         if (f == NULL)
1426                 return (1);
1427
1428         rewind(f);
1429         cnt = fread(buf, 1, sizeof(buf), f);
1430         return (memchr(buf, '\0', cnt) == NULL);
1431 }
1432
1433 #define begins_with(s, pre) (strncmp(s, pre, sizeof(pre)-1) == 0)
1434
1435 static char *
1436 match_function(const long *f, int pos, FILE *fp)
1437 {
1438         unsigned char buf[FUNCTION_CONTEXT_SIZE];
1439         size_t nc;
1440         int last = lastline;
1441         const char *state = NULL;
1442
1443         lastline = pos;
1444         while (pos > last) {
1445                 fseek(fp, f[pos - 1], SEEK_SET);
1446                 nc = f[pos] - f[pos - 1];
1447                 if (nc >= sizeof(buf))
1448                         nc = sizeof(buf) - 1;
1449                 nc = fread(buf, 1, nc, fp);
1450                 if (nc > 0) {
1451                         buf[nc] = '\0';
1452                         buf[strcspn(buf, "\n")] = '\0';
1453                         if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$') {
1454                                 if (begins_with(buf, "private:")) {
1455                                         if (!state)
1456                                                 state = " (private)";
1457                                 } else if (begins_with(buf, "protected:")) {
1458                                         if (!state)
1459                                                 state = " (protected)";
1460                                 } else if (begins_with(buf, "public:")) {
1461                                         if (!state)
1462                                                 state = " (public)";
1463                                 } else {
1464                                         strlcpy(lastbuf, buf, sizeof lastbuf);
1465                                         if (state)
1466                                                 strlcat(lastbuf, state,
1467                                                     sizeof lastbuf);
1468                                         lastmatchline = pos;
1469                                         return lastbuf;
1470                                 }
1471                         }
1472                 }
1473                 pos--;
1474         }
1475         return lastmatchline > 0 ? lastbuf : NULL;
1476 }
1477
1478 /* dump accumulated "context" diff changes */
1479 static void
1480 dump_context_vec(FILE *f1, FILE *f2, int flags)
1481 {
1482         struct context_vec *cvp = context_vec_start;
1483         int lowa, upb, lowc, upd, do_output;
1484         int a, b, c, d;
1485         char ch, *f;
1486
1487         if (context_vec_start > context_vec_ptr)
1488                 return;
1489
1490         b = d = 0;              /* gcc */
1491         lowa = MAX(1, cvp->a - diff_context);
1492         upb = MIN(len[0], context_vec_ptr->b + diff_context);
1493         lowc = MAX(1, cvp->c - diff_context);
1494         upd = MIN(len[1], context_vec_ptr->d + diff_context);
1495
1496         diff_output("***************");
1497         if ((flags & D_PROTOTYPE)) {
1498                 f = match_function(ixold, lowa-1, f1);
1499                 if (f != NULL)
1500                         diff_output(" %s", f);
1501         }
1502         diff_output("\n*** ");
1503         range(lowa, upb, ",");
1504         diff_output(" ****\n");
1505
1506         /*
1507          * Output changes to the "old" file.  The first loop suppresses
1508          * output if there were no changes to the "old" file (we'll see
1509          * the "old" lines as context in the "new" list).
1510          */
1511         do_output = 0;
1512         for (; cvp <= context_vec_ptr; cvp++)
1513                 if (cvp->a <= cvp->b) {
1514                         cvp = context_vec_start;
1515                         do_output++;
1516                         break;
1517                 }
1518         if (do_output) {
1519                 while (cvp <= context_vec_ptr) {
1520                         a = cvp->a;
1521                         b = cvp->b;
1522                         c = cvp->c;
1523                         d = cvp->d;
1524
1525                         if (a <= b && c <= d)
1526                                 ch = 'c';
1527                         else
1528                                 ch = (a <= b) ? 'd' : 'a';
1529
1530                         if (ch == 'a')
1531                                 fetch(ixold, lowa, b, f1, ' ', 0, flags);
1532                         else {
1533                                 fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1534                                 fetch(ixold, a, b, f1,
1535                                     ch == 'c' ? '!' : '-', 0, flags);
1536                         }
1537                         lowa = b + 1;
1538                         cvp++;
1539                 }
1540                 fetch(ixold, b + 1, upb, f1, ' ', 0, flags);
1541         }
1542         /* output changes to the "new" file */
1543         diff_output("--- ");
1544         range(lowc, upd, ",");
1545         diff_output(" ----\n");
1546
1547         do_output = 0;
1548         for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++)
1549                 if (cvp->c <= cvp->d) {
1550                         cvp = context_vec_start;
1551                         do_output++;
1552                         break;
1553                 }
1554         if (do_output) {
1555                 while (cvp <= context_vec_ptr) {
1556                         a = cvp->a;
1557                         b = cvp->b;
1558                         c = cvp->c;
1559                         d = cvp->d;
1560
1561                         if (a <= b && c <= d)
1562                                 ch = 'c';
1563                         else
1564                                 ch = (a <= b) ? 'd' : 'a';
1565
1566                         if (ch == 'd')
1567                                 fetch(ixnew, lowc, d, f2, ' ', 0, flags);
1568                         else {
1569                                 fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1570                                 fetch(ixnew, c, d, f2,
1571                                     ch == 'c' ? '!' : '+', 0, flags);
1572                         }
1573                         lowc = d + 1;
1574                         cvp++;
1575                 }
1576                 fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1577         }
1578         context_vec_ptr = context_vec_start - 1;
1579 }
1580
1581 /* dump accumulated "unified" diff changes */
1582 static void
1583 dump_unified_vec(FILE *f1, FILE *f2, int flags)
1584 {
1585         struct context_vec *cvp = context_vec_start;
1586         int lowa, upb, lowc, upd;
1587         int a, b, c, d;
1588         char ch, *f;
1589
1590         if (context_vec_start > context_vec_ptr)
1591                 return;
1592
1593         b = d = 0;              /* gcc */
1594         lowa = MAX(1, cvp->a - diff_context);
1595         upb = MIN(len[0], context_vec_ptr->b + diff_context);
1596         lowc = MAX(1, cvp->c - diff_context);
1597         upd = MIN(len[1], context_vec_ptr->d + diff_context);
1598
1599         diff_output("@@ -");
1600         uni_range(lowa, upb);
1601         diff_output(" +");
1602         uni_range(lowc, upd);
1603         diff_output(" @@");
1604         if ((flags & D_PROTOTYPE)) {
1605                 f = match_function(ixold, lowa-1, f1);
1606                 if (f != NULL)
1607                         diff_output(" %s", f);
1608         }
1609         diff_output("\n");
1610
1611         /*
1612          * Output changes in "unified" diff format--the old and new lines
1613          * are printed together.
1614          */
1615         for (; cvp <= context_vec_ptr; cvp++) {
1616                 a = cvp->a;
1617                 b = cvp->b;
1618                 c = cvp->c;
1619                 d = cvp->d;
1620
1621                 /*
1622                  * c: both new and old changes
1623                  * d: only changes in the old file
1624                  * a: only changes in the new file
1625                  */
1626                 if (a <= b && c <= d)
1627                         ch = 'c';
1628                 else
1629                         ch = (a <= b) ? 'd' : 'a';
1630
1631                 switch (ch) {
1632                 case 'c':
1633                         fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1634                         fetch(ixold, a, b, f1, '-', 0, flags);
1635                         fetch(ixnew, c, d, f2, '+', 0, flags);
1636                         break;
1637                 case 'd':
1638                         fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
1639                         fetch(ixold, a, b, f1, '-', 0, flags);
1640                         break;
1641                 case 'a':
1642                         fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
1643                         fetch(ixnew, c, d, f2, '+', 0, flags);
1644                         break;
1645                 }
1646                 lowa = b + 1;
1647                 lowc = d + 1;
1648         }
1649         fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
1650
1651         context_vec_ptr = context_vec_start - 1;
1652 }
1653
1654 static void
1655 print_header(const char *file1, const char *file2)
1656 {
1657         const char *time_format;
1658         char buf1[256];
1659         char buf2[256];
1660         char end1[10];
1661         char end2[10];
1662         struct tm tm1, tm2, *tm_ptr1, *tm_ptr2;
1663         int nsec1 = stb1.st_mtim.tv_nsec;
1664         int nsec2 = stb2.st_mtim.tv_nsec;
1665
1666         time_format = "%Y-%m-%d %H:%M:%S";
1667
1668         if (cflag)
1669                 time_format = "%c";
1670         tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1);
1671         tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2);
1672         strftime(buf1, 256, time_format, tm_ptr1);
1673         strftime(buf2, 256, time_format, tm_ptr2);
1674         if (!cflag) {
1675                 strftime(end1, 10, "%z", tm_ptr1);
1676                 strftime(end2, 10, "%z", tm_ptr2);
1677                 sprintf(buf1, "%s.%.9d %s", buf1, nsec1, end1);
1678                 sprintf(buf2, "%s.%.9d %s", buf2, nsec2, end2);
1679         }
1680         if (label[0] != NULL)
1681                 diff_output("%s %s\n", diff_format == D_CONTEXT ? "***" : "---",
1682                     label[0]);
1683         else
1684                 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "***" : "---",
1685                     file1, buf1);
1686         if (label[1] != NULL)
1687                 diff_output("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++",
1688                     label[1]);
1689         else
1690                 diff_output("%s %s\t%s\n", diff_format == D_CONTEXT ? "---" : "+++",
1691                     file2, buf2);
1692 }
1693
1694 /*
1695  * Prints n number of space characters either by using tab
1696  * or single space characters.
1697  * nc is the preceding number of characters
1698  */
1699 static void
1700 print_space(int nc, int n, int flags) {
1701         int i, col;
1702
1703         col = n;
1704         if ((flags & D_EXPANDTABS) == 0) {
1705                 /* first tabstop may be closer than tabsize */
1706                 i = tabsize - (nc % tabsize);
1707                 while (col >= tabsize) {
1708                         diff_output("\t");
1709                         col -= i;
1710                         i = tabsize;
1711                 }
1712         }
1713         diff_output("%*s", col, "");
1714 }