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