xref: /openbsd-src/usr.bin/rcs/diff3.c (revision 9b9d2a55a62c8e82206c25f94fcc7f4e2765250e)
1 /*	$OpenBSD: diff3.c,v 1.36 2015/06/13 20:15:21 nicm Exp $	*/
2 
3 /*
4  * Copyright (C) Caldera International Inc.  2001-2002.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code and documentation must retain the above
11  *    copyright notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed or owned by Caldera
18  *	International, Inc.
19  * 4. Neither the name of Caldera International, Inc. nor the names of other
20  *    contributors may be used to endorse or promote products derived from
21  *    this software without specific prior written permission.
22  *
23  * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
24  * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR ANY DIRECT,
28  * INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
32  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
33  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36 /*-
37  * Copyright (c) 1991, 1993
38  *	The Regents of the University of California.  All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  *
64  *	@(#)diff3.c	8.1 (Berkeley) 6/6/93
65  */
66 
67 #include <ctype.h>
68 #include <err.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 #include "diff.h"
75 #include "rcsprog.h"
76 
77 /* diff3 - 3-way differential file comparison */
78 
79 /* diff3 [-ex3EX] d13 d23 f1 f2 f3 [m1 m3]
80  *
81  * d13 = diff report on f1 vs f3
82  * d23 = diff report on f2 vs f3
83  * f1, f2, f3 the 3 files
84  * if changes in f1 overlap with changes in f3, m1 and m3 are used
85  * to mark the overlaps; otherwise, the file names f1 and f3 are used
86  * (only for options E and X).
87  */
88 
89 /*
90  * "from" is first in range of changed lines; "to" is last+1
91  * from=to=line after point of insertion for added lines.
92  */
93 struct range {
94 	int from;
95 	int to;
96 };
97 
98 struct diff {
99 	struct range old;
100 	struct range new;
101 };
102 
103 static size_t szchanges;
104 
105 static struct diff *d13;
106 static struct diff *d23;
107 
108 /*
109  * "de" is used to gather editing scripts.  These are later spewed out in
110  * reverse order.  Its first element must be all zero, the "new" component
111  * of "de" contains line positions or byte positions depending on when you
112  * look (!?).  Array overlap indicates which sections in "de" correspond to
113  * lines that are different in all three files.
114  */
115 static struct diff *de;
116 static char *overlap;
117 static int overlapcnt = 0;
118 static FILE *fp[3];
119 static int cline[3];		/* # of the last-read line in each file (0-2) */
120 
121 /*
122  * the latest known correspondence between line numbers of the 3 files
123  * is stored in last[1-3];
124  */
125 static int last[4];
126 static int eflag = 3;	/* default -E for compatibility with former RCS */
127 static int oflag = 1;	/* default -E for compatibility with former RCS */
128 static int debug  = 0;
129 static char f1mark[PATH_MAX], f3mark[PATH_MAX];	/* markers for -E and -X */
130 
131 static int duplicate(struct range *, struct range *);
132 static int edit(struct diff *, int, int);
133 static char *getchange(FILE *);
134 static char *get_line(FILE *, size_t *);
135 static int number(char **);
136 static ssize_t readin(char *, struct diff **);
137 static int skip(int, int, char *);
138 static int edscript(int);
139 static int merge(size_t, size_t);
140 static void change(int, struct range *, int);
141 static void keep(int, struct range *);
142 static void prange(struct range *);
143 static void repos(int);
144 static void separate(const char *);
145 static void increase(void);
146 static int diff3_internal(int, char **, const char *, const char *);
147 
148 int diff3_conflicts = 0;
149 
150 /*
151  * For merge(1).
152  */
153 BUF *
154 merge_diff3(char **av, int flags)
155 {
156 	int argc;
157 	char *argv[5], *dp13, *dp23, *path1, *path2, *path3;
158 	BUF *b1, *b2, *b3, *d1, *d2, *diffb;
159 	u_char *data, *patch;
160 	size_t dlen, plen;
161 
162 	b1 = b2 = b3 = d1 = d2 = diffb = NULL;
163 	dp13 = dp23 = path1 = path2 = path3 = NULL;
164 	data = patch = NULL;
165 
166 	if ((flags & MERGE_EFLAG) && !(flags & MERGE_OFLAG))
167 		oflag = 0;
168 
169 	if ((b1 = buf_load(av[0])) == NULL)
170 		goto out;
171 	if ((b2 = buf_load(av[1])) == NULL)
172 		goto out;
173 	if ((b3 = buf_load(av[2])) == NULL)
174 		goto out;
175 
176 	d1 = buf_alloc(128);
177 	d2 = buf_alloc(128);
178 	diffb = buf_alloc(128);
179 
180 	(void)xasprintf(&path1, "%s/diff1.XXXXXXXXXX", rcs_tmpdir);
181 	(void)xasprintf(&path2, "%s/diff2.XXXXXXXXXX", rcs_tmpdir);
182 	(void)xasprintf(&path3, "%s/diff3.XXXXXXXXXX", rcs_tmpdir);
183 
184 	buf_write_stmp(b1, path1);
185 	buf_write_stmp(b2, path2);
186 	buf_write_stmp(b3, path3);
187 
188 	buf_free(b2);
189 	b2 = NULL;
190 
191 	if ((diffreg(path1, path3, d1, D_FORCEASCII) == D_ERROR) ||
192 	    (diffreg(path2, path3, d2, D_FORCEASCII) == D_ERROR)) {
193 		buf_free(diffb);
194 		diffb = NULL;
195 		goto out;
196 	}
197 
198 	(void)xasprintf(&dp13, "%s/d13.XXXXXXXXXX", rcs_tmpdir);
199 	buf_write_stmp(d1, dp13);
200 
201 	buf_free(d1);
202 	d1 = NULL;
203 
204 	(void)xasprintf(&dp23, "%s/d23.XXXXXXXXXX", rcs_tmpdir);
205 	buf_write_stmp(d2, dp23);
206 
207 	buf_free(d2);
208 	d2 = NULL;
209 
210 	argc = 0;
211 	diffbuf = diffb;
212 	argv[argc++] = dp13;
213 	argv[argc++] = dp23;
214 	argv[argc++] = path1;
215 	argv[argc++] = path2;
216 	argv[argc++] = path3;
217 
218 	diff3_conflicts = diff3_internal(argc, argv, av[0], av[2]);
219 	if (diff3_conflicts < 0) {
220 		buf_free(diffb);
221 		diffb = NULL;
222 		goto out;
223 	}
224 
225 	plen = buf_len(diffb);
226 	patch = buf_release(diffb);
227 	dlen = buf_len(b1);
228 	data = buf_release(b1);
229 
230 	if ((diffb = rcs_patchfile(data, dlen, patch, plen, ed_patch_lines)) == NULL)
231 		goto out;
232 
233 	if (!(flags & QUIET) && diff3_conflicts != 0)
234 		warnx("warning: overlaps or other problems during merge");
235 
236 out:
237 	if (b2 != NULL)
238 		buf_free(b2);
239 	if (b3 != NULL)
240 		buf_free(b3);
241 	if (d1 != NULL)
242 		buf_free(d1);
243 	if (d2 != NULL)
244 		buf_free(d2);
245 
246 	(void)unlink(path1);
247 	(void)unlink(path2);
248 	(void)unlink(path3);
249 	(void)unlink(dp13);
250 	(void)unlink(dp23);
251 
252 	free(path1);
253 	free(path2);
254 	free(path3);
255 	free(dp13);
256 	free(dp23);
257 	free(data);
258 	free(patch);
259 
260 	return (diffb);
261 }
262 
263 BUF *
264 rcs_diff3(RCSFILE *rf, char *workfile, RCSNUM *rev1, RCSNUM *rev2, int flags)
265 {
266 	int argc;
267 	char *argv[5], r1[RCS_REV_BUFSZ], r2[RCS_REV_BUFSZ];
268 	char *dp13, *dp23, *path1, *path2, *path3;
269 	BUF *b1, *b2, *b3, *d1, *d2, *diffb;
270 	size_t dlen, plen;
271 	u_char *data, *patch;
272 
273 	b1 = b2 = b3 = d1 = d2 = diffb = NULL;
274 	dp13 = dp23 = path1 = path2 = path3 = NULL;
275 	data = patch = NULL;
276 
277 	if ((flags & MERGE_EFLAG) && !(flags & MERGE_OFLAG))
278 		oflag = 0;
279 
280 	rcsnum_tostr(rev1, r1, sizeof(r1));
281 	rcsnum_tostr(rev2, r2, sizeof(r2));
282 
283 	if ((b1 = buf_load(workfile)) == NULL)
284 		goto out;
285 
286 	if (!(flags & QUIET))
287 		(void)fprintf(stderr, "retrieving revision %s\n", r1);
288 	if ((b2 = rcs_getrev(rf, rev1)) == NULL)
289 		goto out;
290 
291 	if (!(flags & QUIET))
292 		(void)fprintf(stderr, "retrieving revision %s\n", r2);
293 	if ((b3 = rcs_getrev(rf, rev2)) == NULL)
294 		goto out;
295 
296 	d1 = buf_alloc(128);
297 	d2 = buf_alloc(128);
298 	diffb = buf_alloc(128);
299 
300 	(void)xasprintf(&path1, "%s/diff1.XXXXXXXXXX", rcs_tmpdir);
301 	(void)xasprintf(&path2, "%s/diff2.XXXXXXXXXX", rcs_tmpdir);
302 	(void)xasprintf(&path3, "%s/diff3.XXXXXXXXXX", rcs_tmpdir);
303 
304 	buf_write_stmp(b1, path1);
305 	buf_write_stmp(b2, path2);
306 	buf_write_stmp(b3, path3);
307 
308 	buf_free(b2);
309 	b2 = NULL;
310 
311 	if ((diffreg(path1, path3, d1, D_FORCEASCII) == D_ERROR) ||
312 	    (diffreg(path2, path3, d2, D_FORCEASCII) == D_ERROR)) {
313 		buf_free(diffb);
314 		diffb = NULL;
315 		goto out;
316 	}
317 
318 	(void)xasprintf(&dp13, "%s/d13.XXXXXXXXXX", rcs_tmpdir);
319 	buf_write_stmp(d1, dp13);
320 
321 	buf_free(d1);
322 	d1 = NULL;
323 
324 	(void)xasprintf(&dp23, "%s/d23.XXXXXXXXXX", rcs_tmpdir);
325 	buf_write_stmp(d2, dp23);
326 
327 	buf_free(d2);
328 	d2 = NULL;
329 
330 	argc = 0;
331 	diffbuf = diffb;
332 	argv[argc++] = dp13;
333 	argv[argc++] = dp23;
334 	argv[argc++] = path1;
335 	argv[argc++] = path2;
336 	argv[argc++] = path3;
337 
338 	diff3_conflicts = diff3_internal(argc, argv, workfile, r2);
339 	if (diff3_conflicts < 0) {
340 		buf_free(diffb);
341 		diffb = NULL;
342 		goto out;
343 	}
344 
345 	plen = buf_len(diffb);
346 	patch = buf_release(diffb);
347 	dlen = buf_len(b1);
348 	data = buf_release(b1);
349 
350 	if ((diffb = rcs_patchfile(data, dlen, patch, plen, ed_patch_lines)) == NULL)
351 		goto out;
352 
353 	if (!(flags & QUIET) && diff3_conflicts != 0)
354 		warnx("warning: overlaps or other problems during merge");
355 
356 out:
357 	if (b2 != NULL)
358 		buf_free(b2);
359 	if (b3 != NULL)
360 		buf_free(b3);
361 	if (d1 != NULL)
362 		buf_free(d1);
363 	if (d2 != NULL)
364 		buf_free(d2);
365 
366 	(void)unlink(path1);
367 	(void)unlink(path2);
368 	(void)unlink(path3);
369 	(void)unlink(dp13);
370 	(void)unlink(dp23);
371 
372 	free(path1);
373 	free(path2);
374 	free(path3);
375 	free(dp13);
376 	free(dp23);
377 	free(data);
378 	free(patch);
379 
380 	return (diffb);
381 }
382 
383 static int
384 diff3_internal(int argc, char **argv, const char *fmark, const char *rmark)
385 {
386 	ssize_t m, n;
387 	int i;
388 
389 	if (argc < 5)
390 		return (-1);
391 
392 	if (oflag) {
393 		i = snprintf(f1mark, sizeof(f1mark), "<<<<<<< %s", fmark);
394 		if (i < 0 || i >= (int)sizeof(f1mark))
395 			errx(1, "diff3_internal: string truncated");
396 
397 		i = snprintf(f3mark, sizeof(f3mark), ">>>>>>> %s", rmark);
398 		if (i < 0 || i >= (int)sizeof(f3mark))
399 			errx(1, "diff3_internal: string truncated");
400 	}
401 
402 	increase();
403 	if ((m = readin(argv[0], &d13)) < 0) {
404 		warn("%s", argv[0]);
405 		return (-1);
406 	}
407 	if ((n = readin(argv[1], &d23)) < 0) {
408 		warn("%s", argv[1]);
409 		return (-1);
410 	}
411 
412 	for (i = 0; i <= 2; i++)
413 		if ((fp[i] = fopen(argv[i + 2], "r")) == NULL) {
414 			warn("%s", argv[i + 2]);
415 			return (-1);
416 		}
417 
418 	return (merge(m, n));
419 }
420 
421 int
422 ed_patch_lines(struct rcs_lines *dlines, struct rcs_lines *plines)
423 {
424 	char op, *ep;
425 	struct rcs_line *sort, *lp, *dlp, *ndlp, *insert_after;
426 	int start, end, i, lineno;
427 	u_char tmp;
428 
429 	dlp = TAILQ_FIRST(&(dlines->l_lines));
430 	lp = TAILQ_FIRST(&(plines->l_lines));
431 
432 	end = 0;
433 	for (lp = TAILQ_NEXT(lp, l_list); lp != NULL;
434 	    lp = TAILQ_NEXT(lp, l_list)) {
435 		/* Skip blank lines */
436 		if (lp->l_len < 2)
437 			continue;
438 
439 		/* NUL-terminate line buffer for strtol() safety. */
440 		tmp = lp->l_line[lp->l_len - 1];
441 		lp->l_line[lp->l_len - 1] = '\0';
442 
443 		/* len - 1 is NUL terminator so we use len - 2 for 'op' */
444 		op = lp->l_line[lp->l_len - 2];
445 		start = (int)strtol(lp->l_line, &ep, 10);
446 
447 		/* Restore the last byte of the buffer */
448 		lp->l_line[lp->l_len - 1] = tmp;
449 
450 		if (op == 'a') {
451 			if (start > dlines->l_nblines ||
452 			    start < 0 || *ep != 'a')
453 				errx(1, "ed_patch_lines");
454 		} else if (op == 'c') {
455 			if (start > dlines->l_nblines ||
456 			    start < 0 || (*ep != ',' && *ep != 'c'))
457 				errx(1, "ed_patch_lines");
458 
459 			if (*ep == ',') {
460 				ep++;
461 				end = (int)strtol(ep, &ep, 10);
462 				if (end < 0 || *ep != 'c')
463 					errx(1, "ed_patch_lines");
464 			} else {
465 				end = start;
466 			}
467 		}
468 
469 
470 		for (;;) {
471 			if (dlp == NULL)
472 				break;
473 			if (dlp->l_lineno == start)
474 				break;
475 			if (dlp->l_lineno > start) {
476 				dlp = TAILQ_PREV(dlp, tqh, l_list);
477 			} else if (dlp->l_lineno < start) {
478 				ndlp = TAILQ_NEXT(dlp, l_list);
479 				if (ndlp->l_lineno > start)
480 					break;
481 				dlp = ndlp;
482 			}
483 		}
484 
485 		if (dlp == NULL)
486 			errx(1, "ed_patch_lines");
487 
488 
489 		if (op == 'c') {
490 			insert_after = TAILQ_PREV(dlp, tqh, l_list);
491 			for (i = 0; i <= (end - start); i++) {
492 				ndlp = TAILQ_NEXT(dlp, l_list);
493 				TAILQ_REMOVE(&(dlines->l_lines), dlp, l_list);
494 				dlp = ndlp;
495 			}
496 			dlp = insert_after;
497 		}
498 
499 		if (op == 'a' || op == 'c') {
500 			for (;;) {
501 				ndlp = lp;
502 				lp = TAILQ_NEXT(lp, l_list);
503 				if (lp == NULL)
504 					errx(1, "ed_patch_lines");
505 
506 				if (!memcmp(lp->l_line, ".", 1))
507 					break;
508 
509 				TAILQ_REMOVE(&(plines->l_lines), lp, l_list);
510 				TAILQ_INSERT_AFTER(&(dlines->l_lines), dlp,
511 				    lp, l_list);
512 				dlp = lp;
513 
514 				lp->l_lineno = start;
515 				lp = ndlp;
516 			}
517 		}
518 
519 		/*
520 		 * always resort lines as the markers might be put at the
521 		 * same line as we first started editing.
522 		 */
523 		lineno = 0;
524 		TAILQ_FOREACH(sort, &(dlines->l_lines), l_list)
525 			sort->l_lineno = lineno++;
526 		dlines->l_nblines = lineno - 1;
527 	}
528 
529 	return (0);
530 }
531 
532 /*
533  * Pick up the line numbers of all changes from one change file.
534  * (This puts the numbers in a vector, which is not strictly necessary,
535  * since the vector is processed in one sequential pass.
536  * The vector could be optimized out of existence)
537  */
538 static ssize_t
539 readin(char *name, struct diff **dd)
540 {
541 	int a, b, c, d;
542 	char kind, *p;
543 	size_t i;
544 
545 	fp[0] = fopen(name, "r");
546 	if (fp[0] == NULL)
547 		return (-1);
548 	for (i = 0; (p = getchange(fp[0])); i++) {
549 		if (i >= szchanges - 1)
550 			increase();
551 		a = b = number(&p);
552 		if (*p == ',') {
553 			p++;
554 			b = number(&p);
555 		}
556 		kind = *p++;
557 		c = d = number(&p);
558 		if (*p==',') {
559 			p++;
560 			d = number(&p);
561 		}
562 		if (kind == 'a')
563 			a++;
564 		if (kind == 'd')
565 			c++;
566 		b++;
567 		d++;
568 		(*dd)[i].old.from = a;
569 		(*dd)[i].old.to = b;
570 		(*dd)[i].new.from = c;
571 		(*dd)[i].new.to = d;
572 	}
573 
574 	if (i) {
575 		(*dd)[i].old.from = (*dd)[i-1].old.to;
576 		(*dd)[i].new.from = (*dd)[i-1].new.to;
577 	}
578 
579 	(void)fclose(fp[0]);
580 
581 	return (i);
582 }
583 
584 static int
585 number(char **lc)
586 {
587 	int nn;
588 
589 	nn = 0;
590 	while (isdigit((unsigned char)(**lc)))
591 		nn = nn*10 + *(*lc)++ - '0';
592 
593 	return (nn);
594 }
595 
596 static char *
597 getchange(FILE *b)
598 {
599 	char *line;
600 
601 	while ((line = get_line(b, NULL))) {
602 		if (isdigit((unsigned char)line[0]))
603 			return (line);
604 	}
605 
606 	return (NULL);
607 }
608 
609 static char *
610 get_line(FILE *b, size_t *n)
611 {
612 	char *cp;
613 	size_t len;
614 	static char *buf;
615 	static size_t bufsize;
616 
617 	if ((cp = fgetln(b, &len)) == NULL)
618 		return (NULL);
619 
620 	if (cp[len - 1] != '\n')
621 		len++;
622 	if (len + 1 > bufsize) {
623 		do {
624 			bufsize += 1024;
625 		} while (len + 1 > bufsize);
626 		buf = xreallocarray(buf, 1, bufsize);
627 	}
628 	memcpy(buf, cp, len - 1);
629 	buf[len - 1] = '\n';
630 	buf[len] = '\0';
631 	if (n != NULL)
632 		*n = len;
633 
634 	return (buf);
635 }
636 
637 static int
638 merge(size_t m1, size_t m2)
639 {
640 	struct diff *d1, *d2, *d3;
641 	int dpl, j, t1, t2;
642 
643 	d1 = d13;
644 	d2 = d23;
645 	j = 0;
646 	while ((t1 = d1 < d13 + m1) | (t2 = d2 < d23 + m2)) {
647 		if (debug) {
648 			printf("%d,%d=%d,%d %d,%d=%d,%d\n",
649 			d1->old.from, d1->old.to,
650 			d1->new.from, d1->new.to,
651 			d2->old.from, d2->old.to,
652 			d2->new.from, d2->new.to);
653 		}
654 
655 		/* first file is different from others */
656 		if (!t2 || (t1 && d1->new.to < d2->new.from)) {
657 			/* stuff peculiar to 1st file */
658 			if (eflag==0) {
659 				separate("1");
660 				change(1, &d1->old, 0);
661 				keep(2, &d1->new);
662 				change(3, &d1->new, 0);
663 			}
664 			d1++;
665 			continue;
666 		}
667 
668 		/* second file is different from others */
669 		if (!t1 || (t2 && d2->new.to < d1->new.from)) {
670 			if (eflag==0) {
671 				separate("2");
672 				keep(1, &d2->new);
673 				change(2, &d2->old, 0);
674 				change(3, &d2->new, 0);
675 			}
676 			d2++;
677 			continue;
678 		}
679 
680 		/*
681 		 * Merge overlapping changes in first file
682 		 * this happens after extension (see below).
683 		 */
684 		if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
685 			d1[1].old.from = d1->old.from;
686 			d1[1].new.from = d1->new.from;
687 			d1++;
688 			continue;
689 		}
690 
691 		/* merge overlapping changes in second */
692 		if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
693 			d2[1].old.from = d2->old.from;
694 			d2[1].new.from = d2->new.from;
695 			d2++;
696 			continue;
697 		}
698 		/* stuff peculiar to third file or different in all */
699 		if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
700 			dpl = duplicate(&d1->old,&d2->old);
701 			if (dpl == -1)
702 				return (-1);
703 
704 			/*
705 			 * dpl = 0 means all files differ
706 			 * dpl = 1 means files 1 and 2 identical
707 			 */
708 			if (eflag==0) {
709 				separate(dpl ? "3" : "");
710 				change(1, &d1->old, dpl);
711 				change(2, &d2->old, 0);
712 				d3 = d1->old.to > d1->old.from ? d1 : d2;
713 				change(3, &d3->new, 0);
714 			} else
715 				j = edit(d1, dpl, j);
716 			d1++;
717 			d2++;
718 			continue;
719 		}
720 
721 		/*
722 		 * Overlapping changes from file 1 and 2; extend changes
723 		 * appropriately to make them coincide.
724 		 */
725 		if (d1->new.from < d2->new.from) {
726 			d2->old.from -= d2->new.from-d1->new.from;
727 			d2->new.from = d1->new.from;
728 		} else if (d2->new.from < d1->new.from) {
729 			d1->old.from -= d1->new.from-d2->new.from;
730 			d1->new.from = d2->new.from;
731 		}
732 		if (d1->new.to > d2->new.to) {
733 			d2->old.to += d1->new.to - d2->new.to;
734 			d2->new.to = d1->new.to;
735 		} else if (d2->new.to > d1->new.to) {
736 			d1->old.to += d2->new.to - d1->new.to;
737 			d1->new.to = d2->new.to;
738 		}
739 	}
740 
741 	return (edscript(j));
742 }
743 
744 static void
745 separate(const char *s)
746 {
747 	diff_output("====%s\n", s);
748 }
749 
750 /*
751  * The range of lines rold.from thru rold.to in file i is to be changed.
752  * It is to be printed only if it does not duplicate something to be
753  * printed later.
754  */
755 static void
756 change(int i, struct range *rold, int fdup)
757 {
758 	diff_output("%d:", i);
759 	last[i] = rold->to;
760 	prange(rold);
761 	if (fdup || debug)
762 		return;
763 	i--;
764 	(void)skip(i, rold->from, NULL);
765 	(void)skip(i, rold->to, "  ");
766 }
767 
768 /*
769  * print the range of line numbers, rold.from thru rold.to, as n1,n2 or n1
770  */
771 static void
772 prange(struct range *rold)
773 {
774 	if (rold->to <= rold->from)
775 		diff_output("%da\n", rold->from - 1);
776 	else {
777 		diff_output("%d", rold->from);
778 		if (rold->to > rold->from+1)
779 			diff_output(",%d", rold->to - 1);
780 		diff_output("c\n");
781 	}
782 }
783 
784 /*
785  * No difference was reported by diff between file 1 (or 2) and file 3,
786  * and an artificial dummy difference (trange) must be ginned up to
787  * correspond to the change reported in the other file.
788  */
789 static void
790 keep(int i, struct range *rnew)
791 {
792 	int delta;
793 	struct range trange;
794 
795 	delta = last[3] - last[i];
796 	trange.from = rnew->from - delta;
797 	trange.to = rnew->to - delta;
798 	change(i, &trange, 1);
799 }
800 
801 /*
802  * skip to just before line number from in file "i".  If "pr" is non-NULL,
803  * print all skipped stuff with string pr as a prefix.
804  */
805 static int
806 skip(int i, int from, char *pr)
807 {
808 	size_t j, n;
809 	char *line;
810 
811 	for (n = 0; cline[i] < from - 1; n += j) {
812 		if ((line = get_line(fp[i], &j)) == NULL)
813 			return (-1);
814 		if (pr != NULL)
815 			diff_output("%s%s", pr, line);
816 		cline[i]++;
817 	}
818 	return ((int) n);
819 }
820 
821 /*
822  * Return 1 or 0 according as the old range (in file 1) contains exactly
823  * the same data as the new range (in file 2).
824  */
825 static int
826 duplicate(struct range *r1, struct range *r2)
827 {
828 	int c,d;
829 	int nchar;
830 	int nline;
831 
832 	if (r1->to-r1->from != r2->to-r2->from)
833 		return (0);
834 	(void)skip(0, r1->from, NULL);
835 	(void)skip(1, r2->from, NULL);
836 	nchar = 0;
837 	for (nline=0; nline < r1->to - r1->from; nline++) {
838 		do {
839 			c = getc(fp[0]);
840 			d = getc(fp[1]);
841 			if (c == -1 || d== -1)
842 				return (-1);
843 			nchar++;
844 			if (c != d) {
845 				repos(nchar);
846 				return (0);
847 			}
848 		} while (c != '\n');
849 	}
850 	repos(nchar);
851 	return (1);
852 }
853 
854 static void
855 repos(int nchar)
856 {
857 	int i;
858 
859 	for (i = 0; i < 2; i++)
860 		(void)fseek(fp[i], (long)-nchar, SEEK_CUR);
861 }
862 
863 /*
864  * collect an editing script for later regurgitation
865  */
866 static int
867 edit(struct diff *diff, int fdup, int j)
868 {
869 	if (((fdup + 1) & eflag) == 0)
870 		return (j);
871 	j++;
872 	overlap[j] = !fdup;
873 	if (!fdup)
874 		overlapcnt++;
875 	de[j].old.from = diff->old.from;
876 	de[j].old.to = diff->old.to;
877 	de[j].new.from = de[j-1].new.to + skip(2, diff->new.from, NULL);
878 	de[j].new.to = de[j].new.from + skip(2, diff->new.to, NULL);
879 	return (j);
880 }
881 
882 /* regurgitate */
883 static int
884 edscript(int n)
885 {
886 	int j, k;
887 	char block[BUFSIZ+1];
888 
889 	for (; n > 0; n--) {
890 		if (!oflag || !overlap[n])
891 			prange(&de[n].old);
892 		else
893 			diff_output("%da\n=======\n", de[n].old.to -1);
894 		(void)fseek(fp[2], (long)de[n].new.from, SEEK_SET);
895 		for (k = de[n].new.to-de[n].new.from; k > 0; k-= j) {
896 			j = k > BUFSIZ ? BUFSIZ : k;
897 			if (fread(block, 1, j, fp[2]) != j)
898 				return (-1);
899 			block[j] = '\0';
900 			diff_output("%s", block);
901 		}
902 
903 		if (!oflag || !overlap[n])
904 			diff_output(".\n");
905 		else {
906 			diff_output("%s\n.\n", f3mark);
907 			diff_output("%da\n%s\n.\n", de[n].old.from - 1, f1mark);
908 		}
909 	}
910 
911 	return (overlapcnt);
912 }
913 
914 static void
915 increase(void)
916 {
917 	size_t newsz, incr;
918 
919 	/* are the memset(3) calls needed? */
920 	newsz = szchanges == 0 ? 64 : 2 * szchanges;
921 	incr = newsz - szchanges;
922 
923 	d13 = xreallocarray(d13, newsz, sizeof(*d13));
924 	memset(d13 + szchanges, 0, incr * sizeof(*d13));
925 	d23 = xreallocarray(d23, newsz, sizeof(*d23));
926 	memset(d23 + szchanges, 0, incr * sizeof(*d23));
927 	de = xreallocarray(de, newsz, sizeof(*de));
928 	memset(de + szchanges, 0, incr * sizeof(*de));
929 	overlap = xreallocarray(overlap, newsz, sizeof(*overlap));
930 	memset(overlap + szchanges, 0, incr * sizeof(*overlap));
931 	szchanges = newsz;
932 }
933