rdate: make it do something remotely sane, facing 32-bit time overflow
[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) 2010 by Matheus Izvekov <mizvekov@gmail.com>
6  * Copyright (C) 2006 by Robert Sullivan <cogito.ergo.cogito@hotmail.com>
7  * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
8  *
9  * Sponsored in part by the Defense Advanced Research Projects
10  * Agency (DARPA) and Air Force Research Laboratory, Air Force
11  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
12  *
13  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14  */
15
16 /*
17  * The following code uses an algorithm due to Harold Stone,
18  * which finds a pair of longest identical subsequences in
19  * the two files.
20  *
21  * The major goal is to generate the match vector J.
22  * J[i] is the index of the line in file1 corresponding
23  * to line i in file0. J[i] = 0 if there is no
24  * such line in file1.
25  *
26  * Lines are hashed so as to work in core. All potential
27  * matches are located by sorting the lines of each file
28  * on the hash (called "value"). In particular, this
29  * collects the equivalence classes in file1 together.
30  * Subroutine equiv replaces the value of each line in
31  * file0 by the index of the first element of its
32  * matching equivalence in (the reordered) file1.
33  * To save space equiv squeezes file1 into a single
34  * array member in which the equivalence classes
35  * are simply concatenated, except that their first
36  * members are flagged by changing sign.
37  *
38  * Next the indices that point into member are unsorted into
39  * array class according to the original order of file0.
40  *
41  * The cleverness lies in routine stone. This marches
42  * through the lines of file0, developing a vector klist
43  * of "k-candidates". At step i a k-candidate is a matched
44  * pair of lines x,y (x in file0, y in file1) such that
45  * there is a common subsequence of length k
46  * between the first i lines of file0 and the first y
47  * lines of file1, but there is no such subsequence for
48  * any smaller y. x is the earliest possible mate to y
49  * that occurs in such a subsequence.
50  *
51  * Whenever any of the members of the equivalence class of
52  * lines in file1 matable to a line in file0 has serial number
53  * less than the y of some k-candidate, that k-candidate
54  * with the smallest such y is replaced. The new
55  * k-candidate is chained (via pred) to the current
56  * k-1 candidate so that the actual subsequence can
57  * be recovered. When a member has serial number greater
58  * that the y of all k-candidates, the klist is extended.
59  * At the end, the longest subsequence is pulled out
60  * and placed in the array J by unravel
61  *
62  * With J in hand, the matches there recorded are
63  * checked against reality to assure that no spurious
64  * matches have crept in due to hashing. If they have,
65  * they are broken, and "jackpot" is recorded--a harmless
66  * matter except that a true match for a spuriously
67  * mated line may now be unnecessarily reported as a change.
68  *
69  * Much of the complexity of the program comes simply
70  * from trying to minimize core utilization and
71  * maximize the range of doable problems by dynamically
72  * allocating what is needed and reusing what is not.
73  * The core requirements for problems larger than somewhat
74  * are (in words) 2*length(file0) + length(file1) +
75  * 3*(number of k-candidates installed), typically about
76  * 6n words for files of length n.
77  */
78
79 //config:config DIFF
80 //config:       bool "diff"
81 //config:       default y
82 //config:       help
83 //config:         diff compares two files or directories and outputs the
84 //config:         differences between them in a form that can be given to
85 //config:         the patch command.
86 //config:
87 //config:config FEATURE_DIFF_LONG_OPTIONS
88 //config:       bool "Enable long options"
89 //config:       default y
90 //config:       depends on DIFF && LONG_OPTS
91 //config:
92 //config:config FEATURE_DIFF_DIR
93 //config:       bool "Enable directory support"
94 //config:       default y
95 //config:       depends on DIFF
96 //config:       help
97 //config:         This option enables support for directory and subdirectory
98 //config:         comparison.
99
100 //kbuild:lib-$(CONFIG_DIFF) += diff.o
101
102 //applet:IF_DIFF(APPLET(diff, BB_DIR_USR_BIN, BB_SUID_DROP))
103
104 //usage:#define diff_trivial_usage
105 //usage:       "[-abBdiNqrTstw] [-L LABEL] [-S FILE] [-U LINES] FILE1 FILE2"
106 //usage:#define diff_full_usage "\n\n"
107 //usage:       "Compare files line by line and output the differences between them.\n"
108 //usage:       "This implementation supports unified diffs only.\n"
109 //usage:     "\n        -a      Treat all files as text"
110 //usage:     "\n        -b      Ignore changes in the amount of whitespace"
111 //usage:     "\n        -B      Ignore changes whose lines are all blank"
112 //usage:     "\n        -d      Try hard to find a smaller set of changes"
113 //usage:     "\n        -i      Ignore case differences"
114 //usage:     "\n        -L      Use LABEL instead of the filename in the unified header"
115 //usage:     "\n        -N      Treat absent files as empty"
116 //usage:     "\n        -q      Output only whether files differ"
117 //usage:     "\n        -r      Recurse"
118 //usage:     "\n        -S      Start with FILE when comparing directories"
119 //usage:     "\n        -T      Make tabs line up by prefixing a tab when necessary"
120 //usage:     "\n        -s      Report when two files are the same"
121 //usage:     "\n        -t      Expand tabs to spaces in output"
122 //usage:     "\n        -U      Output LINES lines of context"
123 //usage:     "\n        -w      Ignore all whitespace"
124
125 #include "libbb.h"
126 #include "common_bufsiz.h"
127
128 #if 0
129 # define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
130 #else
131 # define dbg_error_msg(...) ((void)0)
132 #endif
133
134 enum {                  /* print_status() and diffreg() return values */
135         STATUS_SAME,    /* files are the same */
136         STATUS_DIFFER,  /* files differ */
137         STATUS_BINARY,  /* binary files differ */
138 };
139
140 enum {                  /* Commandline flags */
141         FLAG_a,
142         FLAG_b,
143         FLAG_d,
144         FLAG_i,
145         FLAG_L,         /* never used, handled by getopt32 */
146         FLAG_N,
147         FLAG_q,
148         FLAG_r,
149         FLAG_s,
150         FLAG_S,         /* never used, handled by getopt32 */
151         FLAG_t,
152         FLAG_T,
153         FLAG_U,         /* never used, handled by getopt32 */
154         FLAG_w,
155         FLAG_u,         /* ignored, this is the default */
156         FLAG_p,         /* not implemented */
157         FLAG_B,
158         FLAG_E,         /* not implemented */
159 };
160 #define FLAG(x) (1 << FLAG_##x)
161
162 /* We cache file position to avoid excessive seeking */
163 typedef struct FILE_and_pos_t {
164         FILE *ft_fp;
165         off_t ft_pos;
166 } FILE_and_pos_t;
167
168 struct globals {
169         smallint exit_status;
170         int opt_U_context;
171         const char *other_dir;
172         char *label[2];
173         struct stat stb[2];
174 };
175 #define G (*ptr_to_globals)
176 #define exit_status        (G.exit_status       )
177 #define opt_U_context      (G.opt_U_context     )
178 #define label              (G.label             )
179 #define stb                (G.stb               )
180 #define INIT_G() do { \
181         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
182         opt_U_context = 3; \
183 } while (0)
184
185 typedef int token_t;
186
187 enum {
188         /* Public */
189         TOK_EMPTY = 1 << 9,  /* Line fully processed, you can proceed to the next */
190         TOK_EOF   = 1 << 10, /* File ended */
191         /* Private (Only to be used by read_token() */
192         TOK_EOL   = 1 << 11, /* we saw EOL (sticky) */
193         TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
194         SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
195         CHAR_MASK = 0x1ff,   /* 8th bit is used to distinguish EOF from 0xff */
196 };
197
198 /* Restores full EOF from one 8th bit: */
199 //#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
200 /* We don't really need the above, we only need to have EOF != any_real_char: */
201 #define TOK2CHAR(t) ((t) & CHAR_MASK)
202
203 static void seek_ft(FILE_and_pos_t *ft, off_t pos)
204 {
205         if (ft->ft_pos != pos) {
206                 ft->ft_pos = pos;
207                 fseeko(ft->ft_fp, pos, SEEK_SET);
208         }
209 }
210
211 /* Reads tokens from given fp, handling -b and -w flags
212  * The user must reset tok every line start
213  */
214 static int read_token(FILE_and_pos_t *ft, token_t tok)
215 {
216         tok |= TOK_EMPTY;
217         while (!(tok & TOK_EOL)) {
218                 bool is_space;
219                 int t;
220
221                 t = fgetc(ft->ft_fp);
222                 if (t != EOF)
223                         ft->ft_pos++;
224                 is_space = (t == EOF || isspace(t));
225
226                 /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
227                 tok |= (t & (TOK_EOF + TOK_EOL));
228                 /* Only EOL? */
229                 if (t == '\n')
230                         tok |= TOK_EOL;
231
232                 if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
233                         t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
234
235                 if ((option_mask32 & FLAG(w)) && is_space)
236                         continue;
237
238                 /* Trim char value to low 9 bits */
239                 t &= CHAR_MASK;
240
241                 if (option_mask32 & FLAG(b)) {
242                         /* Was prev char whitespace? */
243                         if (tok & TOK_SPACE) { /* yes */
244                                 if (is_space) /* this one too, ignore it */
245                                         continue;
246                                 tok &= ~TOK_SPACE;
247                         } else if (is_space) {
248                                 /* 1st whitespace char.
249                                  * Set TOK_SPACE and replace char by ' ' */
250                                 t = TOK_SPACE + ' ';
251                         }
252                 }
253                 /* Clear EMPTY */
254                 tok &= ~(TOK_EMPTY + CHAR_MASK);
255                 /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
256                 tok |= t;
257                 break;
258         }
259 #if 0
260         bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
261                 , tok & TOK_EOF ? " EOF" : ""
262                 , tok & TOK_EOL ? " EOL" : ""
263                 , tok & TOK_EMPTY ? " EMPTY" : ""
264                 , tok & TOK_SPACE ? " SPACE" : ""
265         );
266 #endif
267         return tok;
268 }
269
270 struct cand {
271         int x;
272         int y;
273         int pred;
274 };
275
276 static int search(const int *c, int k, int y, const struct cand *list)
277 {
278         int i, j;
279
280         if (list[c[k]].y < y)  /* quick look for typical case */
281                 return k + 1;
282
283         for (i = 0, j = k + 1;;) {
284                 const int l = (i + j) >> 1;
285                 if (l > i) {
286                         const int t = list[c[l]].y;
287                         if (t > y)
288                                 j = l;
289                         else if (t < y)
290                                 i = l;
291                         else
292                                 return l;
293                 } else
294                         return l + 1;
295         }
296 }
297
298 static unsigned isqrt(unsigned n)
299 {
300         unsigned x = 1;
301         while (1) {
302                 const unsigned y = x;
303                 x = ((n / x) + x) >> 1;
304                 if (x <= (y + 1) && x >= (y - 1))
305                         return x;
306         }
307 }
308
309 static void stone(const int *a, int n, const int *b, int *J, int pref)
310 {
311         const unsigned isq = isqrt(n);
312         const unsigned bound =
313                 (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
314         int clen = 1;
315         int clistlen = 100;
316         int k = 0;
317         struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
318         struct cand cand;
319         struct cand *q;
320         int *klist = xzalloc((n + 2) * sizeof(klist[0]));
321         /*clist[0] = (struct cand){0}; - xzalloc did it */
322         /*klist[0] = 0; */
323
324         for (cand.x = 1; cand.x <= n; cand.x++) {
325                 int j = a[cand.x], oldl = 0;
326                 unsigned numtries = 0;
327                 if (j == 0)
328                         continue;
329                 cand.y = -b[j];
330                 cand.pred = klist[0];
331                 do {
332                         int l, tc;
333                         if (cand.y <= clist[cand.pred].y)
334                                 continue;
335                         l = search(klist, k, cand.y, clist);
336                         if (l != oldl + 1)
337                                 cand.pred = klist[l - 1];
338                         if (l <= k && clist[klist[l]].y <= cand.y)
339                                 continue;
340                         if (clen == clistlen) {
341                                 clistlen = clistlen * 11 / 10;
342                                 clist = xrealloc(clist, clistlen * sizeof(clist[0]));
343                         }
344                         clist[clen] = cand;
345                         tc = klist[l];
346                         klist[l] = clen++;
347                         if (l <= k) {
348                                 cand.pred = tc;
349                                 oldl = l;
350                                 numtries++;
351                         } else {
352                                 k++;
353                                 break;
354                         }
355                 } while ((cand.y = b[++j]) > 0 && numtries < bound);
356         }
357         /* Unravel */
358         for (q = clist + klist[k]; q->y; q = clist + q->pred)
359                 J[q->x + pref] = q->y + pref;
360         free(klist);
361         free(clist);
362 }
363
364 struct line {
365         /* 'serial' is not used in the beginning, so we reuse it
366          * to store line offsets, thus reducing memory pressure
367          */
368         union {
369                 unsigned serial;
370                 off_t offset;
371         };
372         unsigned value;
373 };
374
375 static void equiv(struct line *a, int n, struct line *b, int m, int *c)
376 {
377         int i = 1, j = 1;
378
379         while (i <= n && j <= m) {
380                 if (a[i].value < b[j].value)
381                         a[i++].value = 0;
382                 else if (a[i].value == b[j].value)
383                         a[i++].value = j;
384                 else
385                         j++;
386         }
387         while (i <= n)
388                 a[i++].value = 0;
389         b[m + 1].value = 0;
390         j = 0;
391         while (++j <= m) {
392                 c[j] = -b[j].serial;
393                 while (b[j + 1].value == b[j].value) {
394                         j++;
395                         c[j] = b[j].serial;
396                 }
397         }
398         c[j] = -1;
399 }
400
401 static void unsort(const struct line *f, int l, int *b)
402 {
403         int i;
404         int *a = xmalloc((l + 1) * sizeof(a[0]));
405         for (i = 1; i <= l; i++)
406                 a[f[i].serial] = f[i].value;
407         for (i = 1; i <= l; i++)
408                 b[i] = a[i];
409         free(a);
410 }
411
412 static int line_compar(const void *a, const void *b)
413 {
414 #define l0 ((const struct line*)a)
415 #define l1 ((const struct line*)b)
416         int r = l0->value - l1->value;
417         if (r)
418                 return r;
419         return l0->serial - l1->serial;
420 #undef l0
421 #undef l1
422 }
423
424 static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
425 {
426         int i, j, col;
427         for (i = a; i <= b; i++) {
428                 seek_ft(ft, ix[i - 1]);
429                 putchar(ch);
430                 if (option_mask32 & FLAG(T))
431                         putchar('\t');
432                 for (j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
433                         int c = fgetc(ft->ft_fp);
434                         if (c == EOF) {
435                                 puts("\n\\ No newline at end of file");
436                                 return;
437                         }
438                         ft->ft_pos++;
439                         if (c == '\t' && (option_mask32 & FLAG(t)))
440                                 do putchar(' '); while (++col & 7);
441                         else {
442                                 putchar(c);
443                                 col++;
444                         }
445                 }
446         }
447 }
448
449 /* Creates the match vector J, where J[i] is the index
450  * of the line in the new file corresponding to the line i
451  * in the old file. Lines start at 1 instead of 0, that value
452  * being used instead to denote no corresponding line.
453  * This vector is dynamically allocated and must be freed by the caller.
454  *
455  * * fp is an input parameter, where fp[0] and fp[1] are the open
456  *   old file and new file respectively.
457  * * nlen is an output variable, where nlen[0] and nlen[1]
458  *   gets the number of lines in the old and new file respectively.
459  * * ix is an output variable, where ix[0] and ix[1] gets
460  *   assigned dynamically allocated vectors of the offsets of the lines
461  *   of the old and new file respectively. These must be freed by the caller.
462  */
463 static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
464 {
465         int *J, slen[2], *class, *member;
466         struct line *nfile[2], *sfile[2];
467         int pref = 0, suff = 0, i, j, delta;
468
469         /* Lines of both files are hashed, and in the process
470          * their offsets are stored in the array ix[fileno]
471          * where fileno == 0 points to the old file, and
472          * fileno == 1 points to the new one.
473          */
474         for (i = 0; i < 2; i++) {
475                 unsigned hash;
476                 token_t tok;
477                 size_t sz = 100;
478                 nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
479                 /* ft gets here without the correct position, cant use seek_ft */
480                 ft[i].ft_pos = 0;
481                 fseeko(ft[i].ft_fp, 0, SEEK_SET);
482
483                 nlen[i] = 0;
484                 /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
485                 nfile[i][0].offset = 0;
486                 goto start; /* saves code */
487                 while (1) {
488                         tok = read_token(&ft[i], tok);
489                         if (!(tok & TOK_EMPTY)) {
490                                 /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
491                                 /*hash = hash * 128 - hash + TOK2CHAR(tok);
492                                  * gcc insists on optimizing above to "hash * 127 + ...", thus... */
493                                 unsigned o = hash - TOK2CHAR(tok);
494                                 hash = hash * 128 - o; /* we want SPEED here */
495                                 continue;
496                         }
497                         if (nlen[i]++ == sz) {
498                                 sz = sz * 3 / 2;
499                                 nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
500                         }
501                         /* line_compar needs hashes fit into positive int */
502                         nfile[i][nlen[i]].value = hash & INT_MAX;
503                         /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
504                         nfile[i][nlen[i]].offset = ft[i].ft_pos;
505                         if (tok & TOK_EOF) {
506                                 /* EOF counts as a token, so we have to adjust it here */
507                                 nfile[i][nlen[i]].offset++;
508                                 break;
509                         }
510 start:
511                         hash = tok = 0;
512                 }
513                 /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
514                 if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
515                         nlen[i]--;
516                 /* Now we copy the line offsets into ix */
517                 ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
518                 for (j = 0; j < nlen[i] + 1; j++)
519                         ix[i][j] = nfile[i][j].offset;
520         }
521
522         /* length of prefix and suffix is calculated */
523         for (; pref < nlen[0] && pref < nlen[1] &&
524                nfile[0][pref + 1].value == nfile[1][pref + 1].value;
525                pref++);
526         for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
527                nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
528                suff++);
529         /* Arrays are pruned by the suffix and prefix length,
530          * the result being sorted and stored in sfile[fileno],
531          * and their sizes are stored in slen[fileno]
532          */
533         for (j = 0; j < 2; j++) {
534                 sfile[j] = nfile[j] + pref;
535                 slen[j] = nlen[j] - pref - suff;
536                 for (i = 0; i <= slen[j]; i++)
537                         sfile[j][i].serial = i;
538                 qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
539         }
540         /* nfile arrays are reused to reduce memory pressure
541          * The #if zeroed out section performs the same task as the
542          * one in the #else section.
543          * Peak memory usage is higher, but one array copy is avoided
544          * by not using unsort()
545          */
546 #if 0
547         member = xmalloc((slen[1] + 2) * sizeof(member[0]));
548         equiv(sfile[0], slen[0], sfile[1], slen[1], member);
549         free(nfile[1]);
550
551         class = xmalloc((slen[0] + 1) * sizeof(class[0]));
552         for (i = 1; i <= slen[0]; i++) /* Unsorting */
553                 class[sfile[0][i].serial] = sfile[0][i].value;
554         free(nfile[0]);
555 #else
556         member = (int *)nfile[1];
557         equiv(sfile[0], slen[0], sfile[1], slen[1], member);
558         member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
559
560         class = (int *)nfile[0];
561         unsort(sfile[0], slen[0], (int *)nfile[0]);
562         class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
563 #endif
564         J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
565         /* The elements of J which fall inside the prefix and suffix regions
566          * are marked as unchanged, while the ones which fall outside
567          * are initialized with 0 (no matches), so that function stone can
568          * then assign them their right values
569          */
570         for (i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
571                 J[i] = i <= pref            ?  i :
572                        i > (nlen[0] - suff) ? (i + delta) : 0;
573         /* Here the magic is performed */
574         stone(class, slen[0], member, J, pref);
575         J[nlen[0] + 1] = nlen[1] + 1;
576
577         free(class);
578         free(member);
579
580         /* Both files are rescanned, in an effort to find any lines
581          * which, due to limitations intrinsic to any hashing algorithm,
582          * are different but ended up confounded as the same
583          */
584         for (i = 1; i <= nlen[0]; i++) {
585                 if (!J[i])
586                         continue;
587
588                 seek_ft(&ft[0], ix[0][i - 1]);
589                 seek_ft(&ft[1], ix[1][J[i] - 1]);
590
591                 for (j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
592                         token_t tok0 = 0, tok1 = 0;
593                         do {
594                                 tok0 = read_token(&ft[0], tok0);
595                                 tok1 = read_token(&ft[1], tok1);
596
597                                 if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
598                                  || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
599                                 ) {
600                                         J[i] = 0; /* Break the correspondence */
601                                 }
602                         } while (!(tok0 & tok1 & TOK_EMPTY));
603                 }
604         }
605
606         return J;
607 }
608
609 static bool diff(FILE* fp[2], char *file[2])
610 {
611         int nlen[2];
612         off_t *ix[2];
613         FILE_and_pos_t ft[2];
614         typedef struct { int a, b; } vec_t[2];
615         vec_t *vec = NULL;
616         int i = 1, j, k, idx = -1;
617         bool anychange = false;
618         int *J;
619
620         ft[0].ft_fp = fp[0];
621         ft[1].ft_fp = fp[1];
622         /* note that ft[i].ft_pos is unintitalized, create_J()
623          * must not assume otherwise */
624         J = create_J(ft, nlen, ix);
625
626         do {
627                 bool nonempty = false;
628
629                 while (1) {
630                         vec_t v;
631
632                         for (v[0].a = i; v[0].a <= nlen[0] && J[v[0].a] == J[v[0].a - 1] + 1; v[0].a++)
633                                 continue;
634                         v[1].a = J[v[0].a - 1] + 1;
635
636                         for (v[0].b = v[0].a - 1; v[0].b < nlen[0] && !J[v[0].b + 1]; v[0].b++)
637                                 continue;
638                         v[1].b = J[v[0].b + 1] - 1;
639                         /*
640                          * Indicate that there is a difference between lines a and b of the 'from' file
641                          * to get to lines c to d of the 'to' file. If a is greater than b then there
642                          * are no lines in the 'from' file involved and this means that there were
643                          * lines appended (beginning at b).  If c is greater than d then there are
644                          * lines missing from the 'to' file.
645                          */
646                         if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
647                                 /*
648                                  * If this change is more than 'context' lines from the
649                                  * previous change, dump the record and reset it.
650                                  */
651                                 int ct = (2 * opt_U_context) + 1;
652                                 if (idx >= 0
653                                  && v[0].a > vec[idx][0].b + ct
654                                  && v[1].a > vec[idx][1].b + ct
655                                 ) {
656                                         break;
657                                 }
658
659                                 for (j = 0; j < 2; j++)
660                                         for (k = v[j].a; k <= v[j].b; k++)
661                                                 nonempty |= (ix[j][k] - ix[j][k - 1] != 1);
662
663                                 vec = xrealloc_vector(vec, 6, ++idx);
664                                 memcpy(vec[idx], v, sizeof(v));
665                         }
666
667                         i = v[0].b + 1;
668                         if (i > nlen[0])
669                                 break;
670                         J[v[0].b] = v[1].b;
671                 }
672                 if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
673                         goto cont;
674                 if (!(option_mask32 & FLAG(q))) {
675                         int lowa;
676                         vec_t span, *cvp = vec;
677
678                         if (!anychange) {
679                                 /* Print the context/unidiff header first time through */
680                                 printf("--- %s\n", label[0] ? label[0] : file[0]);
681                                 printf("+++ %s\n", label[1] ? label[1] : file[1]);
682                         }
683
684                         printf("@@");
685                         for (j = 0; j < 2; j++) {
686                                 int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
687                                 int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
688
689                                 printf(" %c%d", j ? '+' : '-', MIN(a, b));
690                                 if (a == b)
691                                         continue;
692                                 printf(",%d", (a < b) ? b - a + 1 : 0);
693                         }
694                         puts(" @@");
695                         /*
696                          * Output changes in "unified" diff format--the old and new lines
697                          * are printed together.
698                          */
699                         for (lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
700                                 bool end = cvp > &vec[idx];
701                                 fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
702                                 if (end)
703                                         break;
704                                 for (j = 0; j < 2; j++)
705                                         fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
706                         }
707                 }
708                 anychange = true;
709  cont:
710                 idx = -1;
711         } while (i <= nlen[0]);
712
713         free(vec);
714         free(ix[0]);
715         free(ix[1]);
716         free(J);
717         return anychange;
718 }
719
720 static int diffreg(char *file[2])
721 {
722         FILE *fp[2];
723         bool binary = false, differ = false;
724         int status = STATUS_SAME, i;
725
726         fp[0] = stdin;
727         fp[1] = stdin;
728         for (i = 0; i < 2; i++) {
729                 int fd = open_or_warn_stdin(file[i]);
730                 if (fd == -1)
731                         goto out;
732                 /* Our diff implementation is using seek.
733                  * When we meet non-seekable file, we must make a temp copy.
734                  */
735                 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
736                         char name[] = "/tmp/difXXXXXX";
737                         int fd_tmp = xmkstemp(name);
738
739                         unlink(name);
740                         if (bb_copyfd_eof(fd, fd_tmp) < 0)
741                                 xfunc_die();
742                         if (fd != STDIN_FILENO)
743                                 close(fd);
744                         fd = fd_tmp;
745                         xlseek(fd, 0, SEEK_SET);
746                 }
747                 fp[i] = fdopen(fd, "r");
748         }
749
750         setup_common_bufsiz();
751         while (1) {
752                 const size_t sz = COMMON_BUFSIZE / 2;
753                 char *const buf0 = bb_common_bufsiz1;
754                 char *const buf1 = buf0 + sz;
755                 int j, k;
756                 i = fread(buf0, 1, sz, fp[0]);
757                 j = fread(buf1, 1, sz, fp[1]);
758                 if (i != j) {
759                         differ = true;
760                         i = MIN(i, j);
761                 }
762                 if (i == 0)
763                         break;
764                 for (k = 0; k < i; k++) {
765                         if (!buf0[k] || !buf1[k])
766                                 binary = true;
767                         if (buf0[k] != buf1[k])
768                                 differ = true;
769                 }
770         }
771         if (differ) {
772                 if (binary && !(option_mask32 & FLAG(a)))
773                         status = STATUS_BINARY;
774                 else if (diff(fp, file))
775                         status = STATUS_DIFFER;
776         }
777         if (status != STATUS_SAME)
778                 exit_status |= 1;
779 out:
780         fclose_if_not_stdin(fp[0]);
781         fclose_if_not_stdin(fp[1]);
782
783         return status;
784 }
785
786 static void print_status(int status, char *path[2])
787 {
788         switch (status) {
789         case STATUS_BINARY:
790         case STATUS_DIFFER:
791                 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
792                         printf("Files %s and %s differ\n", path[0], path[1]);
793                 break;
794         case STATUS_SAME:
795                 if (option_mask32 & FLAG(s))
796                         printf("Files %s and %s are identical\n", path[0], path[1]);
797                 break;
798         }
799 }
800
801 #if ENABLE_FEATURE_DIFF_DIR
802 struct dlist {
803         size_t len;
804         int s, e;
805         char **dl;
806 };
807
808 /* This function adds a filename to dl, the directory listing. */
809 static int FAST_FUNC add_to_dirlist(const char *filename,
810                 struct stat *sb UNUSED_PARAM,
811                 void *userdata, int depth UNUSED_PARAM)
812 {
813         struct dlist *const l = userdata;
814         const char *file = filename + l->len;
815         while (*file == '/')
816                 file++;
817         l->dl = xrealloc_vector(l->dl, 6, l->e);
818         l->dl[l->e] = xstrdup(file);
819         l->e++;
820         return TRUE;
821 }
822
823 /* If recursion is not set, this function adds the directory
824  * to the list and prevents recursive_action from recursing into it.
825  */
826 static int FAST_FUNC skip_dir(const char *filename,
827                 struct stat *sb, void *userdata,
828                 int depth)
829 {
830         if (!(option_mask32 & FLAG(r)) && depth) {
831                 add_to_dirlist(filename, sb, userdata, depth);
832                 return SKIP;
833         }
834         if (!(option_mask32 & FLAG(N))) {
835                 /* -r without -N: no need to recurse into dirs
836                  * which do not exist on the "other side".
837                  * Testcase: diff -r /tmp /
838                  * (it would recurse deep into /proc without this code) */
839                 struct dlist *const l = userdata;
840                 filename += l->len;
841                 if (filename[0]) {
842                         struct stat osb;
843                         char *othername = concat_path_file(G.other_dir, filename);
844                         int r = stat(othername, &osb);
845                         free(othername);
846                         if (r != 0 || !S_ISDIR(osb.st_mode)) {
847                                 /* other dir doesn't have similarly named
848                                  * directory, don't recurse; return 1 upon
849                                  * exit, just like diffutils' diff */
850                                 exit_status |= 1;
851                                 return SKIP;
852                         }
853                 }
854         }
855         return TRUE;
856 }
857
858 static void diffdir(char *p[2], const char *s_start)
859 {
860         struct dlist list[2];
861         int i;
862
863         memset(&list, 0, sizeof(list));
864         for (i = 0; i < 2; i++) {
865                 /*list[i].s = list[i].e = 0; - memset did it */
866                 /*list[i].dl = NULL; */
867
868                 G.other_dir = p[1 - i];
869                 /* We need to trim root directory prefix.
870                  * Using list.len to specify its length,
871                  * add_to_dirlist will remove it. */
872                 list[i].len = strlen(p[i]);
873                 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
874                                 add_to_dirlist, skip_dir, &list[i], 0);
875                 /* Sort dl alphabetically.
876                  * GNU diff does this ignoring any number of trailing dots.
877                  * We don't, so for us dotted files almost always are
878                  * first on the list.
879                  */
880                 qsort_string_vector(list[i].dl, list[i].e);
881                 /* If -S was set, find the starting point. */
882                 if (!s_start)
883                         continue;
884                 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
885                         list[i].s++;
886         }
887         /* Now that both dirlist1 and dirlist2 contain sorted directory
888          * listings, we can start to go through dirlist1. If both listings
889          * contain the same file, then do a normal diff. Otherwise, behaviour
890          * is determined by whether the -N flag is set. */
891         while (1) {
892                 char *dp[2];
893                 int pos;
894                 int k;
895
896                 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
897                 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
898                 if (!dp[0] && !dp[1])
899                         break;
900                 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
901                 k = pos > 0;
902                 if (pos && !(option_mask32 & FLAG(N))) {
903                         printf("Only in %s: %s\n", p[k], dp[k]);
904                         exit_status |= 1;
905                 } else {
906                         char *fullpath[2], *path[2]; /* if -N */
907
908                         for (i = 0; i < 2; i++) {
909                                 if (pos == 0 || i == k) {
910                                         path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
911                                         stat(fullpath[i], &stb[i]);
912                                 } else {
913                                         fullpath[i] = concat_path_file(p[i], dp[1 - i]);
914                                         path[i] = (char *)bb_dev_null;
915                                 }
916                         }
917                         if (pos)
918                                 stat(fullpath[k], &stb[1 - k]);
919
920                         if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
921                                 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
922                         else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
923                                 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
924                         else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
925                                 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
926                         else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
927                                 if (S_ISDIR(stb[0].st_mode))
928                                         printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
929                                 else
930                                         printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
931                         } else
932                                 print_status(diffreg(path), fullpath);
933
934                         free(fullpath[0]);
935                         free(fullpath[1]);
936                 }
937                 free(dp[k]);
938                 list[k].s++;
939                 if (pos == 0) {
940                         free(dp[1 - k]);
941                         list[1 - k].s++;
942                 }
943         }
944         if (ENABLE_FEATURE_CLEAN_UP) {
945                 free(list[0].dl);
946                 free(list[1].dl);
947         }
948 }
949 #endif
950
951 #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
952 static const char diff_longopts[] ALIGN1 =
953         "ignore-case\0"              No_argument       "i"
954         "ignore-tab-expansion\0"     No_argument       "E"
955         "ignore-space-change\0"      No_argument       "b"
956         "ignore-all-space\0"         No_argument       "w"
957         "ignore-blank-lines\0"       No_argument       "B"
958         "text\0"                     No_argument       "a"
959         "unified\0"                  Required_argument "U"
960         "label\0"                    Required_argument "L"
961         "show-c-function\0"          No_argument       "p"
962         "brief\0"                    No_argument       "q"
963         "expand-tabs\0"              No_argument       "t"
964         "initial-tab\0"              No_argument       "T"
965         "recursive\0"                No_argument       "r"
966         "new-file\0"                 No_argument       "N"
967         "report-identical-files\0"   No_argument       "s"
968         "starting-file\0"            Required_argument "S"
969         "minimal\0"                  No_argument       "d"
970         ;
971 #endif
972
973 int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
974 int diff_main(int argc UNUSED_PARAM, char **argv)
975 {
976         int gotstdin = 0, i;
977         char *file[2], *s_start = NULL;
978         llist_t *L_arg = NULL;
979
980         INIT_G();
981
982         /* exactly 2 params; collect multiple -L <label>; -U N */
983         opt_complementary = "=2";
984 #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
985         applet_long_options = diff_longopts;
986 #endif
987         getopt32(argv, "abdiL:*NqrsS:tTU:+wupBE",
988                         &L_arg, &s_start, &opt_U_context);
989         argv += optind;
990         while (L_arg)
991                 label[!!label[0]] = llist_pop(&L_arg);
992         xfunc_error_retval = 2;
993         for (i = 0; i < 2; i++) {
994                 file[i] = argv[i];
995                 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
996                 if (LONE_DASH(file[i])) {
997                         fstat(STDIN_FILENO, &stb[i]);
998                         gotstdin++;
999                 } else
1000                         xstat(file[i], &stb[i]);
1001         }
1002         xfunc_error_retval = 1;
1003         if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
1004                 bb_error_msg_and_die("can't compare stdin to a directory");
1005
1006         /* Compare metadata to check if the files are the same physical file.
1007          *
1008          * Comment from diffutils source says:
1009          * POSIX says that two files are identical if st_ino and st_dev are
1010          * the same, but many file systems incorrectly assign the same (device,
1011          * inode) pair to two distinct files, including:
1012          * GNU/Linux NFS servers that export all local file systems as a
1013          * single NFS file system, if a local device number (st_dev) exceeds
1014          * 255, or if a local inode number (st_ino) exceeds 16777215.
1015          */
1016         if (ENABLE_DESKTOP
1017          && stb[0].st_ino == stb[1].st_ino
1018          && stb[0].st_dev == stb[1].st_dev
1019          && stb[0].st_size == stb[1].st_size
1020          && stb[0].st_mtime == stb[1].st_mtime
1021          && stb[0].st_ctime == stb[1].st_ctime
1022          && stb[0].st_mode == stb[1].st_mode
1023          && stb[0].st_nlink == stb[1].st_nlink
1024          && stb[0].st_uid == stb[1].st_uid
1025          && stb[0].st_gid == stb[1].st_gid
1026         ) {
1027                 /* files are physically the same; no need to compare them */
1028                 return STATUS_SAME;
1029         }
1030
1031         if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
1032 #if ENABLE_FEATURE_DIFF_DIR
1033                 diffdir(file, s_start);
1034 #else
1035                 bb_error_msg_and_die("no support for directory comparison");
1036 #endif
1037         } else {
1038                 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
1039                 bool dir = S_ISDIR(stb[1].st_mode);
1040                 if (dirfile) {
1041                         const char *slash = strrchr(file[!dir], '/');
1042                         file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
1043                         xstat(file[dir], &stb[dir]);
1044                 }
1045                 /* diffreg can get non-regular files here */
1046                 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
1047
1048                 if (dirfile)
1049                         free(file[dir]);
1050         }
1051
1052         return exit_status;
1053 }