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