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