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