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