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