xref: /openbsd/usr.bin/rcs/diff3.c (revision 8932bfb7)
1 /*	$OpenBSD: diff3.c,v 1.32 2011/04/20 19:34:16 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[MAXPATHLEN], f3mark[MAXPATHLEN];	/* 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 *getline(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 	if (path1 != NULL)
253 		xfree(path1);
254 	if (path2 != NULL)
255 		xfree(path2);
256 	if (path3 != NULL)
257 		xfree(path3);
258 	if (dp13 != NULL)
259 		xfree(dp13);
260 	if (dp23 != NULL)
261 		xfree(dp23);
262 	if (data != NULL)
263 		xfree(data);
264 	if (patch != NULL)
265 		xfree(patch);
266 
267 	return (diffb);
268 }
269 
270 BUF *
271 rcs_diff3(RCSFILE *rf, char *workfile, RCSNUM *rev1, RCSNUM *rev2, int flags)
272 {
273 	int argc;
274 	char *argv[5], r1[RCS_REV_BUFSZ], r2[RCS_REV_BUFSZ];
275 	char *dp13, *dp23, *path1, *path2, *path3;
276 	BUF *b1, *b2, *b3, *d1, *d2, *diffb;
277 	size_t dlen, plen;
278 	u_char *data, *patch;
279 
280 	b1 = b2 = b3 = d1 = d2 = diffb = NULL;
281 	dp13 = dp23 = path1 = path2 = path3 = NULL;
282 	data = patch = NULL;
283 
284 	if ((flags & MERGE_EFLAG) && !(flags & MERGE_OFLAG))
285 		oflag = 0;
286 
287 	rcsnum_tostr(rev1, r1, sizeof(r1));
288 	rcsnum_tostr(rev2, r2, sizeof(r2));
289 
290 	if ((b1 = buf_load(workfile)) == NULL)
291 		goto out;
292 
293 	if (!(flags & QUIET))
294 		(void)fprintf(stderr, "retrieving revision %s\n", r1);
295 	if ((b2 = rcs_getrev(rf, rev1)) == NULL)
296 		goto out;
297 
298 	if (!(flags & QUIET))
299 		(void)fprintf(stderr, "retrieving revision %s\n", r2);
300 	if ((b3 = rcs_getrev(rf, rev2)) == NULL)
301 		goto out;
302 
303 	d1 = buf_alloc(128);
304 	d2 = buf_alloc(128);
305 	diffb = buf_alloc(128);
306 
307 	(void)xasprintf(&path1, "%s/diff1.XXXXXXXXXX", rcs_tmpdir);
308 	(void)xasprintf(&path2, "%s/diff2.XXXXXXXXXX", rcs_tmpdir);
309 	(void)xasprintf(&path3, "%s/diff3.XXXXXXXXXX", rcs_tmpdir);
310 
311 	buf_write_stmp(b1, path1);
312 	buf_write_stmp(b2, path2);
313 	buf_write_stmp(b3, path3);
314 
315 	buf_free(b2);
316 	b2 = NULL;
317 
318 	if ((diffreg(path1, path3, d1, D_FORCEASCII) == D_ERROR) ||
319 	    (diffreg(path2, path3, d2, D_FORCEASCII) == D_ERROR)) {
320 		buf_free(diffb);
321 		diffb = NULL;
322 		goto out;
323 	}
324 
325 	(void)xasprintf(&dp13, "%s/d13.XXXXXXXXXX", rcs_tmpdir);
326 	buf_write_stmp(d1, dp13);
327 
328 	buf_free(d1);
329 	d1 = NULL;
330 
331 	(void)xasprintf(&dp23, "%s/d23.XXXXXXXXXX", rcs_tmpdir);
332 	buf_write_stmp(d2, dp23);
333 
334 	buf_free(d2);
335 	d2 = NULL;
336 
337 	argc = 0;
338 	diffbuf = diffb;
339 	argv[argc++] = dp13;
340 	argv[argc++] = dp23;
341 	argv[argc++] = path1;
342 	argv[argc++] = path2;
343 	argv[argc++] = path3;
344 
345 	diff3_conflicts = diff3_internal(argc, argv, workfile, r2);
346 	if (diff3_conflicts < 0) {
347 		buf_free(diffb);
348 		diffb = NULL;
349 		goto out;
350 	}
351 
352 	plen = buf_len(diffb);
353 	patch = buf_release(diffb);
354 	dlen = buf_len(b1);
355 	data = buf_release(b1);
356 
357 	if ((diffb = rcs_patchfile(data, dlen, patch, plen, ed_patch_lines)) == NULL)
358 		goto out;
359 
360 	if (!(flags & QUIET) && diff3_conflicts != 0)
361 		warnx("warning: overlaps or other problems during merge");
362 
363 out:
364 	if (b2 != NULL)
365 		buf_free(b2);
366 	if (b3 != NULL)
367 		buf_free(b3);
368 	if (d1 != NULL)
369 		buf_free(d1);
370 	if (d2 != NULL)
371 		buf_free(d2);
372 
373 	(void)unlink(path1);
374 	(void)unlink(path2);
375 	(void)unlink(path3);
376 	(void)unlink(dp13);
377 	(void)unlink(dp23);
378 
379 	if (path1 != NULL)
380 		xfree(path1);
381 	if (path2 != NULL)
382 		xfree(path2);
383 	if (path3 != NULL)
384 		xfree(path3);
385 	if (dp13 != NULL)
386 		xfree(dp13);
387 	if (dp23 != NULL)
388 		xfree(dp23);
389 	if (data != NULL)
390 		xfree(data);
391 	if (patch != NULL)
392 		xfree(patch);
393 
394 	return (diffb);
395 }
396 
397 static int
398 diff3_internal(int argc, char **argv, const char *fmark, const char *rmark)
399 {
400 	ssize_t m, n;
401 	int i;
402 
403 	if (argc < 5)
404 		return (-1);
405 
406 	if (oflag) {
407 		i = snprintf(f1mark, sizeof(f1mark), "<<<<<<< %s", fmark);
408 		if (i < 0 || i >= (int)sizeof(f1mark))
409 			errx(1, "diff3_internal: string truncated");
410 
411 		i = snprintf(f3mark, sizeof(f3mark), ">>>>>>> %s", rmark);
412 		if (i < 0 || i >= (int)sizeof(f3mark))
413 			errx(1, "diff3_internal: string truncated");
414 	}
415 
416 	increase();
417 	if ((m = readin(argv[0], &d13)) < 0) {
418 		warn("%s", argv[0]);
419 		return (-1);
420 	}
421 	if ((n = readin(argv[1], &d23)) < 0) {
422 		warn("%s", argv[1]);
423 		return (-1);
424 	}
425 
426 	for (i = 0; i <= 2; i++)
427 		if ((fp[i] = fopen(argv[i + 2], "r")) == NULL) {
428 			warn("%s", argv[i + 2]);
429 			return (-1);
430 		}
431 
432 	return (merge(m, n));
433 }
434 
435 int
436 ed_patch_lines(struct rcs_lines *dlines, struct rcs_lines *plines)
437 {
438 	char op, *ep;
439 	struct rcs_line *sort, *lp, *dlp, *ndlp, *insert_after;
440 	int start, end, i, lineno;
441 	u_char tmp;
442 
443 	dlp = TAILQ_FIRST(&(dlines->l_lines));
444 	lp = TAILQ_FIRST(&(plines->l_lines));
445 
446 	end = 0;
447 	for (lp = TAILQ_NEXT(lp, l_list); lp != NULL;
448 	    lp = TAILQ_NEXT(lp, l_list)) {
449 		/* Skip blank lines */
450 		if (lp->l_len < 2)
451 			continue;
452 
453 		/* NUL-terminate line buffer for strtol() safety. */
454 		tmp = lp->l_line[lp->l_len - 1];
455 		lp->l_line[lp->l_len - 1] = '\0';
456 
457 		/* len - 1 is NUL terminator so we use len - 2 for 'op' */
458 		op = lp->l_line[lp->l_len - 2];
459 		start = (int)strtol(lp->l_line, &ep, 10);
460 
461 		/* Restore the last byte of the buffer */
462 		lp->l_line[lp->l_len - 1] = tmp;
463 
464 		if (op == 'a') {
465 			if (start > dlines->l_nblines ||
466 			    start < 0 || *ep != 'a')
467 				errx(1, "ed_patch_lines");
468 		} else if (op == 'c') {
469 			if (start > dlines->l_nblines ||
470 			    start < 0 || (*ep != ',' && *ep != 'c'))
471 				errx(1, "ed_patch_lines");
472 
473 			if (*ep == ',') {
474 				ep++;
475 				end = (int)strtol(ep, &ep, 10);
476 				if (end < 0 || *ep != 'c')
477 					errx(1, "ed_patch_lines");
478 			} else {
479 				end = start;
480 			}
481 		}
482 
483 
484 		for (;;) {
485 			if (dlp == NULL)
486 				break;
487 			if (dlp->l_lineno == start)
488 				break;
489 			if (dlp->l_lineno > start) {
490 				dlp = TAILQ_PREV(dlp, tqh, l_list);
491 			} else if (dlp->l_lineno < start) {
492 				ndlp = TAILQ_NEXT(dlp, l_list);
493 				if (ndlp->l_lineno > start)
494 					break;
495 				dlp = ndlp;
496 			}
497 		}
498 
499 		if (dlp == NULL)
500 			errx(1, "ed_patch_lines");
501 
502 
503 		if (op == 'c') {
504 			insert_after = TAILQ_PREV(dlp, tqh, l_list);
505 			for (i = 0; i <= (end - start); i++) {
506 				ndlp = TAILQ_NEXT(dlp, l_list);
507 				TAILQ_REMOVE(&(dlines->l_lines), dlp, l_list);
508 				dlp = ndlp;
509 			}
510 			dlp = insert_after;
511 		}
512 
513 		if (op == 'a' || op == 'c') {
514 			for (;;) {
515 				ndlp = lp;
516 				lp = TAILQ_NEXT(lp, l_list);
517 				if (lp == NULL)
518 					errx(1, "ed_patch_lines");
519 
520 				if (!memcmp(lp->l_line, ".", 1))
521 					break;
522 
523 				TAILQ_REMOVE(&(plines->l_lines), lp, l_list);
524 				TAILQ_INSERT_AFTER(&(dlines->l_lines), dlp,
525 				    lp, l_list);
526 				dlp = lp;
527 
528 				lp->l_lineno = start;
529 				lp = ndlp;
530 			}
531 		}
532 
533 		/*
534 		 * always resort lines as the markers might be put at the
535 		 * same line as we first started editing.
536 		 */
537 		lineno = 0;
538 		TAILQ_FOREACH(sort, &(dlines->l_lines), l_list)
539 			sort->l_lineno = lineno++;
540 		dlines->l_nblines = lineno - 1;
541 	}
542 
543 	return (0);
544 }
545 
546 /*
547  * Pick up the line numbers of all changes from one change file.
548  * (This puts the numbers in a vector, which is not strictly necessary,
549  * since the vector is processed in one sequential pass.
550  * The vector could be optimized out of existence)
551  */
552 static ssize_t
553 readin(char *name, struct diff **dd)
554 {
555 	int a, b, c, d;
556 	char kind, *p;
557 	size_t i;
558 
559 	fp[0] = fopen(name, "r");
560 	if (fp[0] == NULL)
561 		return (-1);
562 	for (i = 0; (p = getchange(fp[0])); i++) {
563 		if (i >= szchanges - 1)
564 			increase();
565 		a = b = number(&p);
566 		if (*p == ',') {
567 			p++;
568 			b = number(&p);
569 		}
570 		kind = *p++;
571 		c = d = number(&p);
572 		if (*p==',') {
573 			p++;
574 			d = number(&p);
575 		}
576 		if (kind == 'a')
577 			a++;
578 		if (kind == 'd')
579 			c++;
580 		b++;
581 		d++;
582 		(*dd)[i].old.from = a;
583 		(*dd)[i].old.to = b;
584 		(*dd)[i].new.from = c;
585 		(*dd)[i].new.to = d;
586 	}
587 
588 	if (i) {
589 		(*dd)[i].old.from = (*dd)[i-1].old.to;
590 		(*dd)[i].new.from = (*dd)[i-1].new.to;
591 	}
592 
593 	(void)fclose(fp[0]);
594 
595 	return (i);
596 }
597 
598 static int
599 number(char **lc)
600 {
601 	int nn;
602 
603 	nn = 0;
604 	while (isdigit((unsigned char)(**lc)))
605 		nn = nn*10 + *(*lc)++ - '0';
606 
607 	return (nn);
608 }
609 
610 static char *
611 getchange(FILE *b)
612 {
613 	char *line;
614 
615 	while ((line = getline(b, NULL))) {
616 		if (isdigit((unsigned char)line[0]))
617 			return (line);
618 	}
619 
620 	return (NULL);
621 }
622 
623 static char *
624 getline(FILE *b, size_t *n)
625 {
626 	char *cp;
627 	size_t len;
628 	static char *buf;
629 	static size_t bufsize;
630 
631 	if ((cp = fgetln(b, &len)) == NULL)
632 		return (NULL);
633 
634 	if (cp[len - 1] != '\n')
635 		len++;
636 	if (len + 1 > bufsize) {
637 		do {
638 			bufsize += 1024;
639 		} while (len + 1 > bufsize);
640 		buf = xrealloc(buf, 1, bufsize);
641 	}
642 	memcpy(buf, cp, len - 1);
643 	buf[len - 1] = '\n';
644 	buf[len] = '\0';
645 	if (n != NULL)
646 		*n = len;
647 
648 	return (buf);
649 }
650 
651 static int
652 merge(size_t m1, size_t m2)
653 {
654 	struct diff *d1, *d2, *d3;
655 	int dpl, j, t1, t2;
656 
657 	d1 = d13;
658 	d2 = d23;
659 	j = 0;
660 	while ((t1 = d1 < d13 + m1) | (t2 = d2 < d23 + m2)) {
661 		if (debug) {
662 			printf("%d,%d=%d,%d %d,%d=%d,%d\n",
663 			d1->old.from, d1->old.to,
664 			d1->new.from, d1->new.to,
665 			d2->old.from, d2->old.to,
666 			d2->new.from, d2->new.to);
667 		}
668 
669 		/* first file is different from others */
670 		if (!t2 || (t1 && d1->new.to < d2->new.from)) {
671 			/* stuff peculiar to 1st file */
672 			if (eflag==0) {
673 				separate("1");
674 				change(1, &d1->old, 0);
675 				keep(2, &d1->new);
676 				change(3, &d1->new, 0);
677 			}
678 			d1++;
679 			continue;
680 		}
681 
682 		/* second file is different from others */
683 		if (!t1 || (t2 && d2->new.to < d1->new.from)) {
684 			if (eflag==0) {
685 				separate("2");
686 				keep(1, &d2->new);
687 				change(2, &d2->old, 0);
688 				change(3, &d2->new, 0);
689 			}
690 			d2++;
691 			continue;
692 		}
693 
694 		/*
695 		 * Merge overlapping changes in first file
696 		 * this happens after extension (see below).
697 		 */
698 		if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
699 			d1[1].old.from = d1->old.from;
700 			d1[1].new.from = d1->new.from;
701 			d1++;
702 			continue;
703 		}
704 
705 		/* merge overlapping changes in second */
706 		if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
707 			d2[1].old.from = d2->old.from;
708 			d2[1].new.from = d2->new.from;
709 			d2++;
710 			continue;
711 		}
712 		/* stuff peculiar to third file or different in all */
713 		if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
714 			dpl = duplicate(&d1->old,&d2->old);
715 			if (dpl == -1)
716 				return (-1);
717 
718 			/*
719 			 * dpl = 0 means all files differ
720 			 * dpl = 1 means files 1 and 2 identical
721 			 */
722 			if (eflag==0) {
723 				separate(dpl ? "3" : "");
724 				change(1, &d1->old, dpl);
725 				change(2, &d2->old, 0);
726 				d3 = d1->old.to > d1->old.from ? d1 : d2;
727 				change(3, &d3->new, 0);
728 			} else
729 				j = edit(d1, dpl, j);
730 			d1++;
731 			d2++;
732 			continue;
733 		}
734 
735 		/*
736 		 * Overlapping changes from file 1 and 2; extend changes
737 		 * appropriately to make them coincide.
738 		 */
739 		if (d1->new.from < d2->new.from) {
740 			d2->old.from -= d2->new.from-d1->new.from;
741 			d2->new.from = d1->new.from;
742 		} else if (d2->new.from < d1->new.from) {
743 			d1->old.from -= d1->new.from-d2->new.from;
744 			d1->new.from = d2->new.from;
745 		}
746 		if (d1->new.to > d2->new.to) {
747 			d2->old.to += d1->new.to - d2->new.to;
748 			d2->new.to = d1->new.to;
749 		} else if (d2->new.to > d1->new.to) {
750 			d1->old.to += d2->new.to - d1->new.to;
751 			d1->new.to = d2->new.to;
752 		}
753 	}
754 
755 	return (edscript(j));
756 }
757 
758 static void
759 separate(const char *s)
760 {
761 	diff_output("====%s\n", s);
762 }
763 
764 /*
765  * The range of lines rold.from thru rold.to in file i is to be changed.
766  * It is to be printed only if it does not duplicate something to be
767  * printed later.
768  */
769 static void
770 change(int i, struct range *rold, int fdup)
771 {
772 	diff_output("%d:", i);
773 	last[i] = rold->to;
774 	prange(rold);
775 	if (fdup || debug)
776 		return;
777 	i--;
778 	(void)skip(i, rold->from, NULL);
779 	(void)skip(i, rold->to, "  ");
780 }
781 
782 /*
783  * print the range of line numbers, rold.from thru rold.to, as n1,n2 or n1
784  */
785 static void
786 prange(struct range *rold)
787 {
788 	if (rold->to <= rold->from)
789 		diff_output("%da\n", rold->from - 1);
790 	else {
791 		diff_output("%d", rold->from);
792 		if (rold->to > rold->from+1)
793 			diff_output(",%d", rold->to - 1);
794 		diff_output("c\n");
795 	}
796 }
797 
798 /*
799  * No difference was reported by diff between file 1 (or 2) and file 3,
800  * and an artificial dummy difference (trange) must be ginned up to
801  * correspond to the change reported in the other file.
802  */
803 static void
804 keep(int i, struct range *rnew)
805 {
806 	int delta;
807 	struct range trange;
808 
809 	delta = last[3] - last[i];
810 	trange.from = rnew->from - delta;
811 	trange.to = rnew->to - delta;
812 	change(i, &trange, 1);
813 }
814 
815 /*
816  * skip to just before line number from in file "i".  If "pr" is non-NULL,
817  * print all skipped stuff with string pr as a prefix.
818  */
819 static int
820 skip(int i, int from, char *pr)
821 {
822 	size_t j, n;
823 	char *line;
824 
825 	for (n = 0; cline[i] < from - 1; n += j) {
826 		if ((line = getline(fp[i], &j)) == NULL)
827 			return (-1);
828 		if (pr != NULL)
829 			diff_output("%s%s", pr, line);
830 		cline[i]++;
831 	}
832 	return ((int) n);
833 }
834 
835 /*
836  * Return 1 or 0 according as the old range (in file 1) contains exactly
837  * the same data as the new range (in file 2).
838  */
839 static int
840 duplicate(struct range *r1, struct range *r2)
841 {
842 	int c,d;
843 	int nchar;
844 	int nline;
845 
846 	if (r1->to-r1->from != r2->to-r2->from)
847 		return (0);
848 	(void)skip(0, r1->from, NULL);
849 	(void)skip(1, r2->from, NULL);
850 	nchar = 0;
851 	for (nline=0; nline < r1->to - r1->from; nline++) {
852 		do {
853 			c = getc(fp[0]);
854 			d = getc(fp[1]);
855 			if (c == -1 || d== -1)
856 				return (-1);
857 			nchar++;
858 			if (c != d) {
859 				repos(nchar);
860 				return (0);
861 			}
862 		} while (c != '\n');
863 	}
864 	repos(nchar);
865 	return (1);
866 }
867 
868 static void
869 repos(int nchar)
870 {
871 	int i;
872 
873 	for (i = 0; i < 2; i++)
874 		(void)fseek(fp[i], (long)-nchar, SEEK_CUR);
875 }
876 
877 /*
878  * collect an editing script for later regurgitation
879  */
880 static int
881 edit(struct diff *diff, int fdup, int j)
882 {
883 	if (((fdup + 1) & eflag) == 0)
884 		return (j);
885 	j++;
886 	overlap[j] = !fdup;
887 	if (!fdup)
888 		overlapcnt++;
889 	de[j].old.from = diff->old.from;
890 	de[j].old.to = diff->old.to;
891 	de[j].new.from = de[j-1].new.to + skip(2, diff->new.from, NULL);
892 	de[j].new.to = de[j].new.from + skip(2, diff->new.to, NULL);
893 	return (j);
894 }
895 
896 /* regurgitate */
897 static int
898 edscript(int n)
899 {
900 	int j, k;
901 	char block[BUFSIZ+1];
902 
903 	for (; n > 0; n--) {
904 		if (!oflag || !overlap[n])
905 			prange(&de[n].old);
906 		else
907 			diff_output("%da\n=======\n", de[n].old.to -1);
908 		(void)fseek(fp[2], (long)de[n].new.from, SEEK_SET);
909 		for (k = de[n].new.to-de[n].new.from; k > 0; k-= j) {
910 			j = k > BUFSIZ ? BUFSIZ : k;
911 			if (fread(block, 1, j, fp[2]) != j)
912 				return (-1);
913 			block[j] = '\0';
914 			diff_output("%s", block);
915 		}
916 
917 		if (!oflag || !overlap[n])
918 			diff_output(".\n");
919 		else {
920 			diff_output("%s\n.\n", f3mark);
921 			diff_output("%da\n%s\n.\n", de[n].old.from - 1, f1mark);
922 		}
923 	}
924 
925 	return (overlapcnt);
926 }
927 
928 static void
929 increase(void)
930 {
931 	size_t newsz, incr;
932 
933 	/* are the memset(3) calls needed? */
934 	newsz = szchanges == 0 ? 64 : 2 * szchanges;
935 	incr = newsz - szchanges;
936 
937 	d13 = xrealloc(d13, newsz, sizeof(*d13));
938 	memset(d13 + szchanges, 0, incr * sizeof(*d13));
939 	d23 = xrealloc(d23, newsz, sizeof(*d23));
940 	memset(d23 + szchanges, 0, incr * sizeof(*d23));
941 	de = xrealloc(de, newsz, sizeof(*de));
942 	memset(de + szchanges, 0, incr * sizeof(*de));
943 	overlap = xrealloc(overlap, newsz, sizeof(*overlap));
944 	memset(overlap + szchanges, 0, incr * sizeof(*overlap));
945 	szchanges = newsz;
946 }
947