aboutsummaryrefslogtreecommitdiff
path: root/coreutils/diff.c
diff options
context:
space:
mode:
Diffstat (limited to 'coreutils/diff.c')
-rw-r--r--coreutils/diff.c1243
1 files changed, 1243 insertions, 0 deletions
diff --git a/coreutils/diff.c b/coreutils/diff.c
new file mode 100644
index 000000000..2ed26babe
--- /dev/null
+++ b/coreutils/diff.c
@@ -0,0 +1,1243 @@
1/* vi: set sw=4 ts=4: */
2/*
3 * Mini diff implementation for busybox, adapted from OpenBSD diff.
4 *
5 * Copyright (C) 2006 by Robert Sullivan <cogito.ergo.cogito@hotmail.com>
6 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
7 *
8 * Sponsored in part by the Defense Advanced Research Projects
9 * Agency (DARPA) and Air Force Research Laboratory, Air Force
10 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
11 *
12 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
13 */
14
15#include "busybox.h"
16
17#define FSIZE_MAX 32768
18
19/*
20 * Output flags
21 */
22#define D_HEADER 1 /* Print a header/footer between files */
23#define D_EMPTY1 2 /* Treat first file as empty (/dev/null) */
24#define D_EMPTY2 4 /* Treat second file as empty (/dev/null) */
25
26/*
27 * Status values for print_status() and diffreg() return values
28 * Guide:
29 * D_SAME - files are the same
30 * D_DIFFER - files differ
31 * D_BINARY - binary files differ
32 * D_COMMON - subdirectory common to both dirs
33 * D_ONLY - file only exists in one dir
34 * D_MISMATCH1 - path1 a dir, path2 a file
35 * D_MISMATCH2 - path1 a file, path2 a dir
36 * D_ERROR - error occurred
37 * D_SKIPPED1 - skipped path1 as it is a special file
38 * D_SKIPPED2 - skipped path2 as it is a special file
39 */
40
41#define D_SAME 0
42#define D_DIFFER (1<<0)
43#define D_BINARY (1<<1)
44#define D_COMMON (1<<2)
45#define D_ONLY (1<<3)
46#define D_MISMATCH1 (1<<4)
47#define D_MISMATCH2 (1<<5)
48#define D_ERROR (1<<6)
49#define D_SKIPPED1 (1<<7)
50#define D_SKIPPED2 (1<<8)
51
52/* Command line options */
53static unsigned long cmd_flags;
54
55#define FLAG_a (1<<0)
56#define FLAG_b (1<<1)
57#define FLAG_d (1<<2)
58#define FLAG_i (1<<3)
59#define FLAG_L (1<<4)
60#define FLAG_N (1<<5)
61#define FLAG_q (1<<6)
62#define FLAG_r (1<<7)
63#define FLAG_s (1<<8)
64#define FLAG_S (1<<9)
65#define FLAG_t (1<<10)
66#define FLAG_T (1<<11)
67#define FLAG_U (1<<12)
68#define FLAG_w (1<<13)
69
70/* XXX: FIXME: the following variables should be static, but gcc currently
71 * creates a much bigger object if we do this. */
72int context, status;
73char *start, *label[2];
74struct stat stb1, stb2;
75char **dl;
76static int dl_count = 0;
77
78struct cand {
79 int x;
80 int y;
81 int pred;
82};
83
84struct line {
85 int serial;
86 int value;
87} *file[2];
88
89/*
90 * The following struct is used to record change information
91 * doing a "context" or "unified" diff. (see routine "change" to
92 * understand the highly mnemonic field names)
93 */
94struct context_vec {
95 int a; /* start line in old file */
96 int b; /* end line in old file */
97 int c; /* start line in new file */
98 int d; /* end line in new file */
99};
100
101static int *J; /* will be overlaid on class */
102static int *class; /* will be overlaid on file[0] */
103static int *klist; /* will be overlaid on file[0] after class */
104static int *member; /* will be overlaid on file[1] */
105static int clen;
106static int len[2];
107static int pref, suff; /* length of prefix and suffix */
108static int slen[2];
109static int anychange;
110static long *ixnew; /* will be overlaid on file[1] */
111static long *ixold; /* will be overlaid on klist */
112static struct cand *clist; /* merely a free storage pot for candidates */
113static int clistlen; /* the length of clist */
114static struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
115static struct context_vec *context_vec_start;
116static struct context_vec *context_vec_end;
117static struct context_vec *context_vec_ptr;
118
119static void print_only(const char *path, size_t dirlen, const char *entry)
120{
121 if (dirlen > 1)
122 dirlen--;
123 printf("Only in %.*s: %s\n", (int) dirlen, path, entry);
124}
125
126static void print_status(int val, char *path1, char *path2, char *entry)
127{
128 const char *const _entry = entry ? entry : "";
129 char *_path1 = entry ? concat_path_file(path1, _entry) : path1;
130 char *_path2 = entry ? concat_path_file(path2, _entry) : path2;
131
132 switch (val) {
133 case D_ONLY:
134 print_only(path1, strlen(path1), entry);
135 break;
136 case D_COMMON:
137 printf("Common subdirectories: %s and %s\n", _path1, _path2);
138 break;
139 case D_BINARY:
140 printf("Binary files %s and %s differ\n", _path1, _path2);
141 break;
142 case D_DIFFER:
143 if (cmd_flags & FLAG_q)
144 printf("Files %s and %s differ\n", _path1, _path2);
145 break;
146 case D_SAME:
147 if (cmd_flags & FLAG_s)
148 printf("Files %s and %s are identical\n", _path1, _path2);
149 break;
150 case D_MISMATCH1:
151 printf("File %s is a directory while file %s is a regular file\n",
152 _path1, _path2);
153 break;
154 case D_MISMATCH2:
155 printf("File %s is a regular file while file %s is a directory\n",
156 _path1, _path2);
157 break;
158 case D_SKIPPED1:
159 printf("File %s is not a regular file or directory and was skipped\n",
160 _path1);
161 break;
162 case D_SKIPPED2:
163 printf("File %s is not a regular file or directory and was skipped\n",
164 _path2);
165 break;
166 }
167 if (entry) {
168 free(_path1);
169 free(_path2);
170 }
171}
172
173/*
174 * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
175 */
176static int readhash(FILE * f)
177{
178 int i, t, space;
179 int sum;
180
181 sum = 1;
182 space = 0;
183 if (!(cmd_flags & FLAG_b) && !(cmd_flags & FLAG_w)) {
184 if (FLAG_i)
185 for (i = 0; (t = getc(f)) != '\n'; i++) {
186 if (t == EOF) {
187 if (i == 0)
188 return 0;
189 break;
190 }
191 sum = sum * 127 + t;
192 } else
193 for (i = 0; (t = getc(f)) != '\n'; i++) {
194 if (t == EOF) {
195 if (i == 0)
196 return 0;
197 break;
198 }
199 sum = sum * 127 + t;
200 }
201 } else {
202 for (i = 0;;) {
203 switch (t = getc(f)) {
204 case '\t':
205 case '\r':
206 case '\v':
207 case '\f':
208 case ' ':
209 space++;
210 continue;
211 default:
212 if (space && !(cmd_flags & FLAG_w)) {
213 i++;
214 space = 0;
215 }
216 sum = sum * 127 + t;
217 i++;
218 continue;
219 case EOF:
220 if (i == 0)
221 return 0;
222 /* FALLTHROUGH */
223 case '\n':
224 break;
225 }
226 break;
227 }
228 }
229 /*
230 * There is a remote possibility that we end up with a zero sum.
231 * Zero is used as an EOF marker, so return 1 instead.
232 */
233 return (sum == 0 ? 1 : sum);
234}
235
236
237
238/*
239 * Check to see if the given files differ.
240 * Returns 0 if they are the same, 1 if different, and -1 on error.
241 */
242static int files_differ(FILE * f1, FILE * f2, int flags)
243{
244 char buf1[BUFSIZ], buf2[BUFSIZ];
245 size_t i, j;
246
247 if ((flags & (D_EMPTY1 | D_EMPTY2)) || stb1.st_size != stb2.st_size ||
248 (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
249 return 1;
250 while (1) {
251 i = fread(buf1, 1, sizeof(buf1), f1);
252 j = fread(buf2, 1, sizeof(buf2), f2);
253 if (i != j)
254 return 1;
255 if (i == 0 && j == 0) {
256 if (ferror(f1) || ferror(f2))
257 return 1;
258 return 0;
259 }
260 if (memcmp(buf1, buf2, i) != 0)
261 return 1;
262 }
263}
264
265static void prepare(int i, FILE * fd, off_t filesize)
266{
267 struct line *p;
268 int h;
269 size_t j, sz;
270
271 rewind(fd);
272
273 sz = (filesize <= FSIZE_MAX ? filesize : FSIZE_MAX) / 25;
274 if (sz < 100)
275 sz = 100;
276
277 p = xmalloc((sz + 3) * sizeof(struct line));
278 for (j = 0; (h = readhash(fd));) {
279 if (j == sz) {
280 sz = sz * 3 / 2;
281 p = xrealloc(p, (sz + 3) * sizeof(struct line));
282 }
283 p[++j].value = h;
284 }
285 len[i] = j;
286 file[i] = p;
287}
288
289static void prune(void)
290{
291 int i, j;
292
293 for (pref = 0; pref < len[0] && pref < len[1] &&
294 file[0][pref + 1].value == file[1][pref + 1].value; pref++);
295 for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
296 file[0][len[0] - suff].value == file[1][len[1] - suff].value;
297 suff++);
298 for (j = 0; j < 2; j++) {
299 sfile[j] = file[j] + pref;
300 slen[j] = len[j] - pref - suff;
301 for (i = 0; i <= slen[j]; i++)
302 sfile[j][i].serial = i;
303 }
304}
305
306static void equiv(struct line *a, int n, struct line *b, int m, int *c)
307{
308 int i, j;
309
310 i = j = 1;
311 while (i <= n && j <= m) {
312 if (a[i].value < b[j].value)
313 a[i++].value = 0;
314 else if (a[i].value == b[j].value)
315 a[i++].value = j;
316 else
317 j++;
318 }
319 while (i <= n)
320 a[i++].value = 0;
321 b[m + 1].value = 0;
322 j = 0;
323 while (++j <= m) {
324 c[j] = -b[j].serial;
325 while (b[j + 1].value == b[j].value) {
326 j++;
327 c[j] = b[j].serial;
328 }
329 }
330 c[j] = -1;
331}
332
333static int isqrt(int n)
334{
335 int y, x = 1;
336
337 if (n == 0)
338 return 0;
339
340 do {
341 y = x;
342 x = n / x;
343 x += y;
344 x /= 2;
345 } while ((x - y) > 1 || (x - y) < -1);
346
347 return x;
348}
349
350static int newcand(int x, int y, int pred)
351{
352 struct cand *q;
353
354 if (clen == clistlen) {
355 clistlen = clistlen * 11 / 10;
356 clist = xrealloc(clist, clistlen * sizeof(struct cand));
357 }
358 q = clist + clen;
359 q->x = x;
360 q->y = y;
361 q->pred = pred;
362 return clen++;
363}
364
365
366static int search(int *c, int k, int y)
367{
368 int i, j, l, t;
369
370 if (clist[c[k]].y < y) /* quick look for typical case */
371 return k + 1;
372 i = 0;
373 j = k + 1;
374 while (1) {
375 l = i + j;
376 if ((l >>= 1) <= i)
377 break;
378 t = clist[c[l]].y;
379 if (t > y)
380 j = l;
381 else if (t < y)
382 i = l;
383 else
384 return l;
385 }
386 return l + 1;
387}
388
389
390static int stone(int *a, int n, int *b, int *c)
391{
392 int i, k, y, j, l;
393 int oldc, tc, oldl;
394 unsigned int numtries;
395
396#if ENABLE_FEATURE_DIFF_MINIMAL
397 const unsigned int bound =
398 (cmd_flags & FLAG_d) ? UINT_MAX : MAX(256, isqrt(n));
399#else
400 const unsigned int bound = MAX(256, isqrt(n));
401#endif
402 k = 0;
403 c[0] = newcand(0, 0, 0);
404 for (i = 1; i <= n; i++) {
405 j = a[i];
406 if (j == 0)
407 continue;
408 y = -b[j];
409 oldl = 0;
410 oldc = c[0];
411 numtries = 0;
412 do {
413 if (y <= clist[oldc].y)
414 continue;
415 l = search(c, k, y);
416 if (l != oldl + 1)
417 oldc = c[l - 1];
418 if (l <= k) {
419 if (clist[c[l]].y <= y)
420 continue;
421 tc = c[l];
422 c[l] = newcand(i, y, oldc);
423 oldc = tc;
424 oldl = l;
425 numtries++;
426 } else {
427 c[l] = newcand(i, y, oldc);
428 k++;
429 break;
430 }
431 } while ((y = b[++j]) > 0 && numtries < bound);
432 }
433 return k;
434}
435
436static void unravel(int p)
437{
438 struct cand *q;
439 int i;
440
441 for (i = 0; i <= len[0]; i++)
442 J[i] = i <= pref ? i : i > len[0] - suff ? i + len[1] - len[0] : 0;
443 for (q = clist + p; q->y != 0; q = clist + q->pred)
444 J[q->x + pref] = q->y + pref;
445}
446
447
448static void unsort(struct line *f, int l, int *b)
449{
450 int *a, i;
451
452 a = xmalloc((l + 1) * sizeof(int));
453 for (i = 1; i <= l; i++)
454 a[f[i].serial] = f[i].value;
455 for (i = 1; i <= l; i++)
456 b[i] = a[i];
457 free(a);
458}
459
460static int skipline(FILE * f)
461{
462 int i, c;
463
464 for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
465 continue;
466 return i;
467}
468
469
470/*
471 * Check does double duty:
472 * 1. ferret out any fortuitous correspondences due
473 * to confounding by hashing (which result in "jackpot")
474 * 2. collect random access indexes to the two files
475 */
476static void check(FILE * f1, FILE * f2)
477{
478 int i, j, jackpot, c, d;
479 long ctold, ctnew;
480
481 rewind(f1);
482 rewind(f2);
483 j = 1;
484 ixold[0] = ixnew[0] = 0;
485 jackpot = 0;
486 ctold = ctnew = 0;
487 for (i = 1; i <= len[0]; i++) {
488 if (J[i] == 0) {
489 ixold[i] = ctold += skipline(f1);
490 continue;
491 }
492 while (j < J[i]) {
493 ixnew[j] = ctnew += skipline(f2);
494 j++;
495 }
496 if ((cmd_flags & FLAG_b) || (cmd_flags & FLAG_w)
497 || (cmd_flags & FLAG_i)) {
498 while (1) {
499 c = getc(f1);
500 d = getc(f2);
501 /*
502 * GNU diff ignores a missing newline
503 * in one file if bflag || wflag.
504 */
505 if (((cmd_flags & FLAG_b) || (cmd_flags & FLAG_w)) &&
506 ((c == EOF && d == '\n') || (c == '\n' && d == EOF))) {
507 break;
508 }
509 ctold++;
510 ctnew++;
511 if ((cmd_flags & FLAG_b) && isspace(c) && isspace(d)) {
512 do {
513 if (c == '\n')
514 break;
515 ctold++;
516 } while (isspace(c = getc(f1)));
517 do {
518 if (d == '\n')
519 break;
520 ctnew++;
521 } while (isspace(d = getc(f2)));
522 } else if (cmd_flags & FLAG_w) {
523 while (isspace(c) && c != '\n') {
524 c = getc(f1);
525 ctold++;
526 }
527 while (isspace(d) && d != '\n') {
528 d = getc(f2);
529 ctnew++;
530 }
531 }
532 if (c != d) {
533 jackpot++;
534 J[i] = 0;
535 if (c != '\n' && c != EOF)
536 ctold += skipline(f1);
537 if (d != '\n' && c != EOF)
538 ctnew += skipline(f2);
539 break;
540 }
541 if (c == '\n' || c == EOF)
542 break;
543 }
544 } else {
545 while (1) {
546 ctold++;
547 ctnew++;
548 if ((c = getc(f1)) != (d = getc(f2))) {
549 J[i] = 0;
550 if (c != '\n' && c != EOF)
551 ctold += skipline(f1);
552 if (d != '\n' && c != EOF)
553 ctnew += skipline(f2);
554 break;
555 }
556 if (c == '\n' || c == EOF)
557 break;
558 }
559 }
560 ixold[i] = ctold;
561 ixnew[j] = ctnew;
562 j++;
563 }
564 for (; j <= len[1]; j++)
565 ixnew[j] = ctnew += skipline(f2);
566}
567
568/* shellsort CACM #201 */
569static void sort(struct line *a, int n)
570{
571 struct line *ai, *aim, w;
572 int j, m = 0, k;
573
574 if (n == 0)
575 return;
576 for (j = 1; j <= n; j *= 2)
577 m = 2 * j - 1;
578 for (m /= 2; m != 0; m /= 2) {
579 k = n - m;
580 for (j = 1; j <= k; j++) {
581 for (ai = &a[j]; ai > a; ai -= m) {
582 aim = &ai[m];
583 if (aim < ai)
584 break; /* wraparound */
585 if (aim->value > ai[0].value ||
586 (aim->value == ai[0].value && aim->serial > ai[0].serial))
587 break;
588 w.value = ai[0].value;
589 ai[0].value = aim->value;
590 aim->value = w.value;
591 w.serial = ai[0].serial;
592 ai[0].serial = aim->serial;
593 aim->serial = w.serial;
594 }
595 }
596 }
597}
598
599
600static void uni_range(int a, int b)
601{
602 if (a < b)
603 printf("%d,%d", a, b - a + 1);
604 else if (a == b)
605 printf("%d", b);
606 else
607 printf("%d,0", b);
608}
609
610static int fetch(long *f, int a, int b, FILE * lb, int ch)
611{
612 int i, j, c, lastc, col, nc;
613
614 if (a > b)
615 return 0;
616 for (i = a; i <= b; i++) {
617 fseek(lb, f[i - 1], SEEK_SET);
618 nc = f[i] - f[i - 1];
619 if (ch != '\0') {
620 putchar(ch);
621 if (cmd_flags & FLAG_T)
622 putchar('\t');
623 }
624 col = 0;
625 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
626 if ((c = getc(lb)) == EOF) {
627 puts("\n\\ No newline at end of file");
628 return 0;
629 }
630 if (c == '\t' && (cmd_flags & FLAG_t)) {
631 do {
632 putchar(' ');
633 } while (++col & 7);
634 } else {
635 putchar(c);
636 col++;
637 }
638 }
639 }
640 return 0;
641}
642
643static int asciifile(FILE * f)
644{
645#if ENABLE_FEATURE_DIFF_BINARY
646 unsigned char buf[BUFSIZ];
647 int i, cnt;
648#endif
649
650 if ((cmd_flags & FLAG_a) || f == NULL)
651 return 1;
652
653#if ENABLE_FEATURE_DIFF_BINARY
654 rewind(f);
655 cnt = fread(buf, 1, sizeof(buf), f);
656 for (i = 0; i < cnt; i++) {
657 if (!isprint(buf[i]) && !isspace(buf[i])) {
658 return 0;
659 }
660 }
661#endif
662 return 1;
663}
664
665/* dump accumulated "unified" diff changes */
666static void dump_unified_vec(FILE * f1, FILE * f2)
667{
668 struct context_vec *cvp = context_vec_start;
669 int lowa, upb, lowc, upd;
670 int a, b, c, d;
671 char ch;
672
673 if (context_vec_start > context_vec_ptr)
674 return;
675
676 b = d = 0; /* gcc */
677 lowa = MAX(1, cvp->a - context);
678 upb = MIN(len[0], context_vec_ptr->b + context);
679 lowc = MAX(1, cvp->c - context);
680 upd = MIN(len[1], context_vec_ptr->d + context);
681
682 fputs("@@ -", stdout);
683 uni_range(lowa, upb);
684 fputs(" +", stdout);
685 uni_range(lowc, upd);
686 fputs(" @@", stdout);
687 putchar('\n');
688
689 /*
690 * Output changes in "unified" diff format--the old and new lines
691 * are printed together.
692 */
693 for (; cvp <= context_vec_ptr; cvp++) {
694 a = cvp->a;
695 b = cvp->b;
696 c = cvp->c;
697 d = cvp->d;
698
699 /*
700 * c: both new and old changes
701 * d: only changes in the old file
702 * a: only changes in the new file
703 */
704 if (a <= b && c <= d)
705 ch = 'c';
706 else
707 ch = (a <= b) ? 'd' : 'a';
708 if (ch == 'c' || ch == 'd') {
709 fetch(ixold, lowa, a - 1, f1, ' ');
710 fetch(ixold, a, b, f1, '-');
711 }
712 if (ch == 'a')
713 fetch(ixnew, lowc, c - 1, f2, ' ');
714 if (ch == 'c' || ch == 'a')
715 fetch(ixnew, c, d, f2, '+');
716 lowa = b + 1;
717 lowc = d + 1;
718 }
719 fetch(ixnew, d + 1, upd, f2, ' ');
720
721 context_vec_ptr = context_vec_start - 1;
722}
723
724
725static void print_header(const char *file1, const char *file2)
726{
727 if (label[0] != NULL)
728 printf("%s %s\n", "---", label[0]);
729 else
730 printf("%s %s\t%s", "---", file1, ctime(&stb1.st_mtime));
731 if (label[1] != NULL)
732 printf("%s %s\n", "+++", label[1]);
733 else
734 printf("%s %s\t%s", "+++", file2, ctime(&stb2.st_mtime));
735}
736
737
738
739/*
740 * Indicate that there is a difference between lines a and b of the from file
741 * to get to lines c to d of the to file. If a is greater then b then there
742 * are no lines in the from file involved and this means that there were
743 * lines appended (beginning at b). If c is greater than d then there are
744 * lines missing from the to file.
745 */
746static void change(char *file1, FILE * f1, char *file2, FILE * f2, int a,
747 int b, int c, int d)
748{
749 static size_t max_context = 64;
750
751 if (a > b && c > d)
752 return;
753 if (cmd_flags & FLAG_q)
754 return;
755
756 /*
757 * Allocate change records as needed.
758 */
759 if (context_vec_ptr == context_vec_end - 1) {
760 ptrdiff_t offset = context_vec_ptr - context_vec_start;
761
762 max_context <<= 1;
763 context_vec_start = xrealloc(context_vec_start,
764 max_context *
765 sizeof(struct context_vec));
766 context_vec_end = context_vec_start + max_context;
767 context_vec_ptr = context_vec_start + offset;
768 }
769 if (anychange == 0) {
770 /*
771 * Print the context/unidiff header first time through.
772 */
773 print_header(file1, file2);
774 anychange = 1;
775 } else if (a > context_vec_ptr->b + (2 * context) + 1 &&
776 c > context_vec_ptr->d + (2 * context) + 1) {
777 /*
778 * If this change is more than 'context' lines from the
779 * previous change, dump the record and reset it.
780 */
781 dump_unified_vec(f1, f2);
782 }
783 context_vec_ptr++;
784 context_vec_ptr->a = a;
785 context_vec_ptr->b = b;
786 context_vec_ptr->c = c;
787 context_vec_ptr->d = d;
788 return;
789
790}
791
792
793static void output(char *file1, FILE * f1, char *file2, FILE * f2)
794{
795
796 /* Note that j0 and j1 can't be used as they are defined in math.h.
797 * This also allows the rather amusing variable 'j00'... */
798 int m, i0, i1, j00, j01;
799
800 rewind(f1);
801 rewind(f2);
802 m = len[0];
803 J[0] = 0;
804 J[m + 1] = len[1] + 1;
805 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
806 while (i0 <= m && J[i0] == J[i0 - 1] + 1)
807 i0++;
808 j00 = J[i0 - 1] + 1;
809 i1 = i0 - 1;
810 while (i1 < m && J[i1 + 1] == 0)
811 i1++;
812 j01 = J[i1 + 1] - 1;
813 J[i1] = j01;
814 change(file1, f1, file2, f2, i0, i1, j00, j01);
815 }
816 if (m == 0) {
817 change(file1, f1, file2, f2, 1, 0, 1, len[1]);
818 }
819 if (anychange != 0) {
820 dump_unified_vec(f1, f2);
821 }
822}
823
824/*
825 * The following code uses an algorithm due to Harold Stone,
826 * which finds a pair of longest identical subsequences in
827 * the two files.
828 *
829 * The major goal is to generate the match vector J.
830 * J[i] is the index of the line in file1 corresponding
831 * to line i file0. J[i] = 0 if there is no
832 * such line in file1.
833 *
834 * Lines are hashed so as to work in core. All potential
835 * matches are located by sorting the lines of each file
836 * on the hash (called ``value''). In particular, this
837 * collects the equivalence classes in file1 together.
838 * Subroutine equiv replaces the value of each line in
839 * file0 by the index of the first element of its
840 * matching equivalence in (the reordered) file1.
841 * To save space equiv squeezes file1 into a single
842 * array member in which the equivalence classes
843 * are simply concatenated, except that their first
844 * members are flagged by changing sign.
845 *
846 * Next the indices that point into member are unsorted into
847 * array class according to the original order of file0.
848 *
849 * The cleverness lies in routine stone. This marches
850 * through the lines of file0, developing a vector klist
851 * of "k-candidates". At step i a k-candidate is a matched
852 * pair of lines x,y (x in file0 y in file1) such that
853 * there is a common subsequence of length k
854 * between the first i lines of file0 and the first y
855 * lines of file1, but there is no such subsequence for
856 * any smaller y. x is the earliest possible mate to y
857 * that occurs in such a subsequence.
858 *
859 * Whenever any of the members of the equivalence class of
860 * lines in file1 matable to a line in file0 has serial number
861 * less than the y of some k-candidate, that k-candidate
862 * with the smallest such y is replaced. The new
863 * k-candidate is chained (via pred) to the current
864 * k-1 candidate so that the actual subsequence can
865 * be recovered. When a member has serial number greater
866 * that the y of all k-candidates, the klist is extended.
867 * At the end, the longest subsequence is pulled out
868 * and placed in the array J by unravel
869 *
870 * With J in hand, the matches there recorded are
871 * checked against reality to assure that no spurious
872 * matches have crept in due to hashing. If they have,
873 * they are broken, and "jackpot" is recorded--a harmless
874 * matter except that a true match for a spuriously
875 * mated line may now be unnecessarily reported as a change.
876 *
877 * Much of the complexity of the program comes simply
878 * from trying to minimize core utilization and
879 * maximize the range of doable problems by dynamically
880 * allocating what is needed and reusing what is not.
881 * The core requirements for problems larger than somewhat
882 * are (in words) 2*length(file0) + length(file1) +
883 * 3*(number of k-candidates installed), typically about
884 * 6n words for files of length n.
885 */
886
887static int diffreg(char *ofile1, char *ofile2, int flags)
888{
889 char *file1 = ofile1;
890 char *file2 = ofile2;
891 FILE *f1 = NULL;
892 FILE *f2 = NULL;
893 int rval = D_SAME;
894 int i;
895
896 anychange = 0;
897 context_vec_ptr = context_vec_start - 1;
898
899 if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
900 return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
901 if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
902 goto closem;
903
904 if (flags & D_EMPTY1)
905 f1 = xfopen(bb_dev_null, "r");
906 else {
907 if (strcmp(file1, "-") == 0)
908 f1 = stdin;
909 else
910 f1 = xfopen(file1, "r");
911 }
912
913 if (flags & D_EMPTY2)
914 f2 = xfopen(bb_dev_null, "r");
915 else {
916 if (strcmp(file2, "-") == 0)
917 f2 = stdin;
918 else
919 f2 = xfopen(file2, "r");
920 }
921
922 if ((i = files_differ(f1, f2, flags)) == 0)
923 goto closem;
924 else if (i != 1) { /* 1 == ok */
925 /* error */
926 status |= 2;
927 goto closem;
928 }
929
930 if (!asciifile(f1) || !asciifile(f2)) {
931 rval = D_BINARY;
932 status |= 1;
933 goto closem;
934 }
935
936 prepare(0, f1, stb1.st_size);
937 prepare(1, f2, stb2.st_size);
938 prune();
939 sort(sfile[0], slen[0]);
940 sort(sfile[1], slen[1]);
941
942 member = (int *) file[1];
943 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
944 member = xrealloc(member, (slen[1] + 2) * sizeof(int));
945
946 class = (int *) file[0];
947 unsort(sfile[0], slen[0], class);
948 class = xrealloc(class, (slen[0] + 2) * sizeof(int));
949
950 klist = xmalloc((slen[0] + 2) * sizeof(int));
951 clen = 0;
952 clistlen = 100;
953 clist = xmalloc(clistlen * sizeof(struct cand));
954 i = stone(class, slen[0], member, klist);
955 free(member);
956 free(class);
957
958 J = xrealloc(J, (len[0] + 2) * sizeof(int));
959 unravel(klist[i]);
960 free(clist);
961 free(klist);
962
963 ixold = xrealloc(ixold, (len[0] + 2) * sizeof(long));
964 ixnew = xrealloc(ixnew, (len[1] + 2) * sizeof(long));
965 check(f1, f2);
966 output(file1, f1, file2, f2);
967
968 closem:
969 if (anychange) {
970 status |= 1;
971 if (rval == D_SAME)
972 rval = D_DIFFER;
973 }
974 if (f1 != NULL)
975 fclose(f1);
976 if (f2 != NULL)
977 fclose(f2);
978 if (file1 != ofile1)
979 free(file1);
980 if (file2 != ofile2)
981 free(file2);
982 return rval;
983}
984
985#if ENABLE_FEATURE_DIFF_DIR
986static void do_diff(char *dir1, char *path1, char *dir2, char *path2)
987{
988
989 int flags = D_HEADER;
990 int val;
991
992 char *fullpath1 = xasprintf("%s/%s", dir1, path1);
993 char *fullpath2 = xasprintf("%s/%s", dir2, path2);
994
995 if (stat(fullpath1, &stb1) != 0) {
996 flags |= D_EMPTY1;
997 memset(&stb1, 0, sizeof(stb1));
998 fullpath1 = xasprintf("%s/%s", dir1, path2);
999 }
1000 if (stat(fullpath2, &stb2) != 0) {
1001 flags |= D_EMPTY2;
1002 memset(&stb2, 0, sizeof(stb2));
1003 stb2.st_mode = stb1.st_mode;
1004 fullpath2 = xasprintf("%s/%s", dir2, path1);
1005 }
1006
1007 if (stb1.st_mode == 0)
1008 stb1.st_mode = stb2.st_mode;
1009
1010 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1011 printf("Common subdirectories: %s and %s\n", fullpath1, fullpath2);
1012 return;
1013 }
1014
1015 if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode))
1016 val = D_SKIPPED1;
1017 else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode))
1018 val = D_SKIPPED2;
1019 else
1020 val = diffreg(fullpath1, fullpath2, flags);
1021
1022 print_status(val, fullpath1, fullpath2, NULL);
1023}
1024#endif
1025
1026#if ENABLE_FEATURE_DIFF_DIR
1027static int dir_strcmp(const void *p1, const void *p2)
1028{
1029 return strcmp(*(char *const *) p1, *(char *const *) p2);
1030}
1031
1032/* This function adds a filename to dl, the directory listing. */
1033
1034static int add_to_dirlist(const char *filename,
1035 struct stat ATTRIBUTE_UNUSED * sb, void *userdata,
1036 int depth ATTRIBUTE_UNUSED)
1037{
1038 dl_count++;
1039 dl = xrealloc(dl, dl_count * sizeof(char *));
1040 dl[dl_count - 1] = xstrdup(filename);
1041 if (cmd_flags & FLAG_r) {
1042 int *pp = (int *) userdata;
1043 int path_len = *pp + 1;
1044
1045 dl[dl_count - 1] = &(dl[dl_count - 1])[path_len];
1046 }
1047 return TRUE;
1048}
1049
1050/* This returns a sorted directory listing. */
1051static char **get_dir(char *path)
1052{
1053
1054 int i;
1055 char **retval;
1056
1057 /* If -r has been set, then the recursive_action function will be
1058 * used. Unfortunately, this outputs the root directory along with
1059 * the recursed paths, so use void *userdata to specify the string
1060 * length of the root directory. It can then be removed in
1061 * add_to_dirlist. */
1062
1063 int path_len = strlen(path);
1064 void *userdata = &path_len;
1065
1066 /* Reset dl_count - there's no need to free dl as xrealloc does
1067 * the job nicely. */
1068 dl_count = 0;
1069
1070 /* Now fill dl with a listing. */
1071 if (cmd_flags & FLAG_r)
1072 recursive_action(path, TRUE, TRUE, FALSE, add_to_dirlist, NULL,
1073 userdata, 0);
1074 else {
1075 DIR *dp;
1076 struct dirent *ep;
1077
1078 dp = warn_opendir(path);
1079 while ((ep = readdir(dp))) {
1080 if ((!strcmp(ep->d_name, "..")) || (!strcmp(ep->d_name, ".")))
1081 continue;
1082 add_to_dirlist(ep->d_name, NULL, NULL, 0);
1083 }
1084 closedir(dp);
1085 }
1086
1087 /* Sort dl alphabetically. */
1088 qsort(dl, dl_count, sizeof(char *), dir_strcmp);
1089
1090 /* Copy dl so that we can return it. */
1091 retval = xmalloc(dl_count * sizeof(char *));
1092 for (i = 0; i < dl_count; i++)
1093 retval[i] = xstrdup(dl[i]);
1094
1095 return retval;
1096}
1097
1098static void diffdir(char *p1, char *p2)
1099{
1100
1101 char **dirlist1, **dirlist2;
1102 char *dp1, *dp2;
1103 int dirlist1_count, dirlist2_count;
1104 int pos;
1105
1106 /* Check for trailing slashes. */
1107
1108 dp1 = last_char_is(p1, '/');
1109 if (dp1 != NULL)
1110 *dp1 = '\0';
1111 dp2 = last_char_is(p2, '/');
1112 if (dp2 != NULL)
1113 *dp2 = '\0';
1114
1115 /* Get directory listings for p1 and p2. */
1116
1117 dirlist1 = get_dir(p1);
1118 dirlist1_count = dl_count;
1119 dirlist1[dirlist1_count] = NULL;
1120 dirlist2 = get_dir(p2);
1121 dirlist2_count = dl_count;
1122 dirlist2[dirlist2_count] = NULL;
1123
1124 /* If -S was set, find the starting point. */
1125 if (start) {
1126 while (*dirlist1 != NULL && strcmp(*dirlist1, start) < 0)
1127 dirlist1++;
1128 while (*dirlist2 != NULL && strcmp(*dirlist2, start) < 0)
1129 dirlist2++;
1130 if ((*dirlist1 == NULL) || (*dirlist2 == NULL))
1131 bb_error_msg(bb_msg_invalid_arg, "NULL", "-S");
1132 }
1133
1134 /* Now that both dirlist1 and dirlist2 contain sorted directory
1135 * listings, we can start to go through dirlist1. If both listings
1136 * contain the same file, then do a normal diff. Otherwise, behaviour
1137 * is determined by whether the -N flag is set. */
1138 while (*dirlist1 != NULL || *dirlist2 != NULL) {
1139 dp1 = *dirlist1;
1140 dp2 = *dirlist2;
1141 pos = dp1 == NULL ? 1 : dp2 == NULL ? -1 : strcmp(dp1, dp2);
1142 if (pos == 0) {
1143 do_diff(p1, dp1, p2, dp2);
1144 dirlist1++;
1145 dirlist2++;
1146 } else if (pos < 0) {
1147 if (cmd_flags & FLAG_N)
1148 do_diff(p1, dp1, p2, NULL);
1149 else
1150 print_only(p1, strlen(p1) + 1, dp1);
1151 dirlist1++;
1152 } else {
1153 if (cmd_flags & FLAG_N)
1154 do_diff(p1, NULL, p2, dp2);
1155 else
1156 print_only(p2, strlen(p2) + 1, dp2);
1157 dirlist2++;
1158 }
1159 }
1160}
1161#endif
1162
1163
1164
1165int diff_main(int argc, char **argv)
1166{
1167 int gotstdin = 0;
1168
1169 char *U_opt;
1170 llist_t *L_arg = NULL;
1171
1172 opt_complementary = "L::";
1173 cmd_flags = getopt32(argc, argv, "abdiL:NqrsS:tTU:wu",
1174 &L_arg, &start, &U_opt);
1175
1176 if (cmd_flags & FLAG_L) {
1177 while (L_arg) {
1178 if (label[0] == NULL)
1179 label[0] = L_arg->data;
1180 else if (label[1] == NULL)
1181 label[1] = L_arg->data;
1182 else
1183 bb_show_usage();
1184
1185 L_arg = L_arg->link;
1186 }
1187
1188 /* If both label[0] and label[1] were set, they need to be swapped. */
1189 if (label[0] && label[1]) {
1190 char *tmp;
1191
1192 tmp = label[1];
1193 label[1] = label[0];
1194 label[0] = tmp;
1195 }
1196 }
1197
1198 context = 3; /* This is the default number of lines of context. */
1199 if (cmd_flags & FLAG_U) {
1200 context = xatoul_range(U_opt, 1, INT_MAX);
1201 }
1202 argc -= optind;
1203 argv += optind;
1204
1205 /*
1206 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
1207 * driver routine. Both drivers use the contents of stb1 and stb2.
1208 */
1209 if (argc < 2) {
1210 bb_error_msg("missing filename");
1211 bb_show_usage();
1212 }
1213 if (strcmp(argv[0], "-") == 0) {
1214 fstat(STDIN_FILENO, &stb1);
1215 gotstdin = 1;
1216 } else
1217 xstat(argv[0], &stb1);
1218 if (strcmp(argv[1], "-") == 0) {
1219 fstat(STDIN_FILENO, &stb2);
1220 gotstdin = 1;
1221 } else
1222 xstat(argv[1], &stb2);
1223 if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
1224 bb_error_msg_and_die("can't compare - to a directory");
1225 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1226#if ENABLE_FEATURE_DIFF_DIR
1227 diffdir(argv[0], argv[1]);
1228#else
1229 bb_error_msg_and_die("directory comparison not supported");
1230#endif
1231 } else {
1232 if (S_ISDIR(stb1.st_mode)) {
1233 argv[0] = concat_path_file(argv[0], argv[1]);
1234 xstat(argv[0], &stb1);
1235 }
1236 if (S_ISDIR(stb2.st_mode)) {
1237 argv[1] = concat_path_file(argv[1], argv[0]);
1238 xstat(argv[1], &stb2);
1239 }
1240 print_status(diffreg(argv[0], argv[1], 0), argv[0], argv[1], NULL);
1241 }
1242 exit(status);
1243}