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