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