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