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