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