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