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