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