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