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