mkfs_ext2: fix bad comment. no code changes
[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 tarball for details.
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 #include "libbb.h"
80
81 #if 0
82 //#define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
83 #else
84 #define dbg_error_msg(...) ((void)0)
85 #endif
86
87 enum {                  /* print_status() and diffreg() return values */
88         STATUS_SAME,    /* files are the same */
89         STATUS_DIFFER,  /* files differ */
90         STATUS_BINARY,  /* binary files differ */
91 };
92
93 enum {                  /* Commandline flags */
94         FLAG_a,
95         FLAG_b,
96         FLAG_d,
97         FLAG_i,
98         FLAG_L,         /* never used, handled by getopt32 */
99         FLAG_N,
100         FLAG_q,
101         FLAG_r,
102         FLAG_s,
103         FLAG_S,         /* never used, handled by getopt32 */
104         FLAG_t,
105         FLAG_T,
106         FLAG_U,         /* never used, handled by getopt32 */
107         FLAG_w,
108         FLAG_u,         /* ignored, this is the default */
109         FLAG_p,         /* not implemented */
110         FLAG_B,
111         FLAG_E,         /* not implemented */
112 };
113 #define FLAG(x) (1 << FLAG_##x)
114
115 /* We cache file position to avoid excessive seeking */
116 typedef struct FILE_and_pos_t {
117         FILE *ft_fp;
118         off_t ft_pos;
119 } FILE_and_pos_t;
120
121 struct globals {
122         smallint exit_status;
123         int opt_U_context;
124         char *label[2];
125         struct stat stb[2];
126 };
127 #define G (*ptr_to_globals)
128 #define exit_status        (G.exit_status       )
129 #define opt_U_context      (G.opt_U_context     )
130 #define label              (G.label             )
131 #define stb                (G.stb               )
132 #define INIT_G() do { \
133         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
134         opt_U_context = 3; \
135 } while (0)
136
137 typedef int token_t;
138
139 enum {
140         /* Public */
141         TOK_EMPTY = 1 << 9,  /* Line fully processed, you can proceed to the next */
142         TOK_EOF   = 1 << 10, /* File ended */
143         /* Private (Only to be used by read_token() */
144         TOK_EOL   = 1 << 11, /* we saw EOL (sticky) */
145         TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
146         SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
147         CHAR_MASK = 0x1ff,   /* 8th bit is used to distinguish EOF from 0xff */
148 };
149
150 /* Restores full EOF from one 8th bit: */
151 //#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
152 /* We don't really need the above, we only need to have EOF != any_real_char: */
153 #define TOK2CHAR(t) ((t) & CHAR_MASK)
154
155 static void seek_ft(FILE_and_pos_t *ft, off_t pos)
156 {
157         if (ft->ft_pos != pos) {
158                 ft->ft_pos = pos;
159                 fseeko(ft->ft_fp, pos, SEEK_SET);
160         }
161 }
162
163 /* Reads tokens from given fp, handling -b and -w flags
164  * The user must reset tok every line start
165  */
166 static int read_token(FILE_and_pos_t *ft, token_t tok)
167 {
168         tok |= TOK_EMPTY;
169         while (!(tok & TOK_EOL)) {
170                 bool is_space;
171                 int t;
172
173                 t = fgetc(ft->ft_fp);
174                 if (t != EOF)
175                         ft->ft_pos++;
176                 is_space = (t == EOF || isspace(t));
177
178                 /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
179                 tok |= (t & (TOK_EOF + TOK_EOL));
180                 /* Only EOL? */
181                 if (t == '\n')
182                         tok |= TOK_EOL;
183
184                 if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
185                         t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
186
187                 if ((option_mask32 & FLAG(w)) && is_space)
188                         continue;
189
190                 /* Trim char value to low 9 bits */
191                 t &= CHAR_MASK;
192
193                 if (option_mask32 & FLAG(b)) {
194                         /* Was prev char whitespace? */
195                         if (tok & TOK_SPACE) { /* yes */
196                                 if (is_space) /* this one too, ignore it */
197                                         continue;
198                                 tok &= ~TOK_SPACE;
199                         } else if (is_space) {
200                                 /* 1st whitespace char.
201                                  * Set TOK_SPACE and replace char by ' ' */
202                                 t = TOK_SPACE + ' ';
203                         }
204                 }
205                 /* Clear EMPTY */
206                 tok &= ~(TOK_EMPTY + CHAR_MASK);
207                 /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
208                 tok |= t;
209                 break;
210         }
211 #if 0
212         bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
213                 , tok & TOK_EOF ? " EOF" : ""
214                 , tok & TOK_EOL ? " EOL" : ""
215                 , tok & TOK_EMPTY ? " EMPTY" : ""
216                 , tok & TOK_SPACE ? " SPACE" : ""
217         );
218 #endif
219         return tok;
220 }
221
222 struct cand {
223         int x;
224         int y;
225         int pred;
226 };
227
228 static int search(const int *c, int k, int y, const struct cand *list)
229 {
230         if (list[c[k]].y < y)   /* quick look for typical case */
231                 return k + 1;
232
233         for (int i = 0, j = k + 1;;) {
234                 const int l = (i + j) >> 1;
235                 if (l > i) {
236                         const int t = list[c[l]].y;
237                         if (t > y)
238                                 j = l;
239                         else if (t < y)
240                                 i = l;
241                         else
242                                 return l;
243                 } else
244                         return l + 1;
245         }
246 }
247
248 static unsigned isqrt(unsigned n)
249 {
250         unsigned x = 1;
251         while (1) {
252                 const unsigned y = x;
253                 x = ((n / x) + x) >> 1;
254                 if (x <= (y + 1) && x >= (y - 1))
255                         return x;
256         }
257 }
258
259 static void stone(const int *a, int n, const int *b, int *J, int pref)
260 {
261         const unsigned isq = isqrt(n);
262         const unsigned bound =
263                 (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
264         int clen = 1;
265         int clistlen = 100;
266         int k = 0;
267         struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
268         int *klist = xzalloc((n + 2) * sizeof(klist[0]));
269         /*clist[0] = (struct cand){0}; - xzalloc did it */
270         /*klist[0] = 0; */
271
272         for (struct cand cand = {1}; cand.x <= n; cand.x++) {
273                 int j = a[cand.x], oldl = 0;
274                 unsigned numtries = 0;
275                 if (j == 0)
276                         continue;
277                 cand.y = -b[j];
278                 cand.pred = klist[0];
279                 do {
280                         int l, tc;
281                         if (cand.y <= clist[cand.pred].y)
282                                 continue;
283                         l = search(klist, k, cand.y, clist);
284                         if (l != oldl + 1)
285                                 cand.pred = klist[l - 1];
286                         if (l <= k && clist[klist[l]].y <= cand.y)
287                                 continue;
288                         if (clen == clistlen) {
289                                 clistlen = clistlen * 11 / 10;
290                                 clist = xrealloc(clist, clistlen * sizeof(clist[0]));
291                         }
292                         clist[clen] = cand;
293                         tc = klist[l];
294                         klist[l] = clen++;
295                         if (l <= k) {
296                                 cand.pred = tc;
297                                 oldl = l;
298                                 numtries++;
299                         } else {
300                                 k++;
301                                 break;
302                         }
303                 } while ((cand.y = b[++j]) > 0 && numtries < bound);
304         }
305         /* Unravel */
306         for (struct cand *q = clist + klist[k]; q->y; q = clist + q->pred)
307                 J[q->x + pref] = q->y + pref;
308         free(klist);
309         free(clist);
310 }
311
312 struct line {
313         /* 'serial' is not used in the begining, so we reuse it
314          * to store line offsets, thus reducing memory pressure
315          */
316         union {
317                 unsigned serial;
318                 off_t offset;
319         };
320         unsigned value;
321 };
322
323 static void equiv(struct line *a, int n, struct line *b, int m, int *c)
324 {
325         int i = 1, j = 1;
326
327         while (i <= n && j <= m) {
328                 if (a[i].value < b[j].value)
329                         a[i++].value = 0;
330                 else if (a[i].value == b[j].value)
331                         a[i++].value = j;
332                 else
333                         j++;
334         }
335         while (i <= n)
336                 a[i++].value = 0;
337         b[m + 1].value = 0;
338         j = 0;
339         while (++j <= m) {
340                 c[j] = -b[j].serial;
341                 while (b[j + 1].value == b[j].value) {
342                         j++;
343                         c[j] = b[j].serial;
344                 }
345         }
346         c[j] = -1;
347 }
348
349 static void unsort(const struct line *f, int l, int *b)
350 {
351         int *a = xmalloc((l + 1) * sizeof(a[0]));
352         for (int i = 1; i <= l; i++)
353                 a[f[i].serial] = f[i].value;
354         for (int i = 1; i <= l; i++)
355                 b[i] = a[i];
356         free(a);
357 }
358
359 static int line_compar(const void *a, const void *b)
360 {
361 #define l0 ((const struct line*)a)
362 #define l1 ((const struct line*)b)
363         int r = l0->value - l1->value;
364         if (r)
365                 return r;
366         return l0->serial - l1->serial;
367 #undef l0
368 #undef l1
369 }
370
371 static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
372 {
373         for (int i = a; i <= b; i++) {
374                 seek_ft(ft, ix[i - 1]);
375                 putchar(ch);
376                 if (option_mask32 & FLAG(T))
377                         putchar('\t');
378                 for (int j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
379                         int c = fgetc(ft->ft_fp);
380                         if (c == EOF) {
381                                 printf("\n\\ No newline at end of file\n");
382                                 return;
383                         }
384                         ft->ft_pos++;
385                         if (c == '\t' && (option_mask32 & FLAG(t)))
386                                 do putchar(' '); while (++col & 7);
387                         else {
388                                 putchar(c);
389                                 col++;
390                         }
391                 }
392         }
393 }
394
395 /* Creates the match vector J, where J[i] is the index
396  * of the line in the new file corresponding to the line i
397  * in the old file. Lines start at 1 instead of 0, that value
398  * being used instead to denote no corresponding line.
399  * This vector is dynamically allocated and must be freed by the caller.
400  *
401  * * fp is an input parameter, where fp[0] and fp[1] are the open
402  *   old file and new file respectively.
403  * * nlen is an output variable, where nlen[0] and nlen[1]
404  *   gets the number of lines in the old and new file respectively.
405  * * ix is an output variable, where ix[0] and ix[1] gets
406  *   assigned dynamically allocated vectors of the offsets of the lines
407  *   of the old and new file respectively. These must be freed by the caller.
408  */
409 static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
410 {
411         int *J, slen[2], *class, *member;
412         struct line *nfile[2], *sfile[2];
413         int pref = 0, suff = 0;
414
415         /* Lines of both files are hashed, and in the process
416          * their offsets are stored in the array ix[fileno]
417          * where fileno == 0 points to the old file, and
418          * fileno == 1 points to the new one.
419          */
420         for (int i = 0; i < 2; i++) {
421                 unsigned hash;
422                 token_t tok;
423                 size_t sz = 100;
424                 nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
425                 /* ft gets here without the correct position, cant use seek_ft */
426                 fseeko(ft[i].ft_fp, 0, SEEK_SET);
427
428                 nlen[i] = 0;
429                 /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
430                 nfile[i][0].offset = 0;
431                 goto start; /* saves code */
432                 while (1) {
433                         tok = read_token(&ft[i], tok);
434                         if (!(tok & TOK_EMPTY)) {
435                                 /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
436                                 /*hash = hash * 128 - hash + TOK2CHAR(tok);
437                                  * gcc insists on optimizing above to "hash * 127 + ...", thus... */
438                                 unsigned o = hash - TOK2CHAR(tok);
439                                 hash = hash * 128 - o; /* we want SPEED here */
440                                 continue;
441                         }
442                         if (nlen[i]++ == sz) {
443                                 sz = sz * 3 / 2;
444                                 nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
445                         }
446                         /* line_compar needs hashes fit into positive int */
447                         nfile[i][nlen[i]].value = hash & INT_MAX;
448                         /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
449                         nfile[i][nlen[i]].offset = ft[i].ft_pos;
450                         if (tok & TOK_EOF) {
451                                 /* EOF counts as a token, so we have to adjust it here */
452                                 nfile[i][nlen[i]].offset++;
453                                 break;
454                         }
455 start:
456                         hash = tok = 0;
457                 }
458                 /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
459                 if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
460                         nlen[i]--;
461                 /* Now we copy the line offsets into ix */
462                 ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
463                 for (int j = 0; j < nlen[i] + 1; j++)
464                         ix[i][j] = nfile[i][j].offset;
465         }
466
467         /* lenght of prefix and suffix is calculated */
468         for (; pref < nlen[0] && pref < nlen[1] &&
469                nfile[0][pref + 1].value == nfile[1][pref + 1].value;
470                pref++);
471         for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
472                nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
473                suff++);
474         /* Arrays are pruned by the suffix and prefix lenght,
475          * the result being sorted and stored in sfile[fileno],
476          * and their sizes are stored in slen[fileno]
477          */
478         for (int j = 0; j < 2; j++) {
479                 sfile[j] = nfile[j] + pref;
480                 slen[j] = nlen[j] - pref - suff;
481                 for (int i = 0; i <= slen[j]; i++)
482                         sfile[j][i].serial = i;
483                 qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
484         }
485         /* nfile arrays are reused to reduce memory pressure
486          * The #if zeroed out section performs the same task as the
487          * one in the #else section.
488          * Peak memory usage is higher, but one array copy is avoided
489          * by not using unsort()
490          */
491 #if 0
492         member = xmalloc((slen[1] + 2) * sizeof(member[0]));
493         equiv(sfile[0], slen[0], sfile[1], slen[1], member);
494         free(nfile[1]);
495
496         class = xmalloc((slen[0] + 1) * sizeof(class[0]));
497         for (int i = 1; i <= slen[0]; i++) /* Unsorting */
498                 class[sfile[0][i].serial] = sfile[0][i].value;
499         free(nfile[0]);
500 #else
501         member = (int *)nfile[1];
502         equiv(sfile[0], slen[0], sfile[1], slen[1], member);
503         member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
504
505         class = (int *)nfile[0];
506         unsort(sfile[0], slen[0], (int *)nfile[0]);
507         class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
508 #endif
509         J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
510         /* The elements of J which fall inside the prefix and suffix regions
511          * are marked as unchanged, while the ones which fall outside
512          * are initialized with 0 (no matches), so that function stone can
513          * then assign them their right values
514          */
515         for (int i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
516                 J[i] = i <= pref            ?  i :
517                        i > (nlen[0] - suff) ? (i + delta) : 0;
518         /* Here the magic is performed */
519         stone(class, slen[0], member, J, pref);
520         J[nlen[0] + 1] = nlen[1] + 1;
521
522         free(class);
523         free(member);
524
525         /* Both files are rescanned, in an effort to find any lines
526          * which, due to limitations intrinsic to any hashing algorithm,
527          * are different but ended up confounded as the same
528          */
529         for (int i = 1; i <= nlen[0]; i++) {
530                 if (!J[i])
531                         continue;
532
533                 seek_ft(&ft[0], ix[0][i - 1]);
534                 seek_ft(&ft[1], ix[1][J[i] - 1]);
535
536                 for (int j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
537                         token_t tok0 = 0, tok1 = 0;
538                         do {
539                                 tok0 = read_token(&ft[0], tok0);
540                                 tok1 = read_token(&ft[1], tok1);
541
542                                 if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
543                                  || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
544                                 ) {
545                                         J[i] = 0; /* Break the correspondence */
546                                 }
547                         } while (!(tok0 & tok1 & TOK_EMPTY));
548                 }
549         }
550
551         return J;
552 }
553
554 static bool diff(FILE* fp[2], char *file[2])
555 {
556         int nlen[2];
557         off_t *ix[2];
558         FILE_and_pos_t ft[2] = { { fp[0] }, { fp[1] } };
559         int *J = create_J(ft, nlen, ix);
560
561         bool anychange = false;
562         typedef struct { int a, b; } vec_t[2];
563         vec_t *vec = NULL;
564         int i = 1, idx = -1;
565
566         do {
567                 bool nonempty = false;
568
569                 while (1) {
570                         vec_t v;
571
572                         for (v[0].a = i; v[0].a <= nlen[0] && J[v[0].a] == J[v[0].a - 1] + 1; v[0].a++)
573                                 continue;
574                         v[1].a = J[v[0].a - 1] + 1;
575
576                         for (v[0].b = v[0].a - 1; v[0].b < nlen[0] && !J[v[0].b + 1]; v[0].b++)
577                                 continue;
578                         v[1].b = J[v[0].b + 1] - 1;
579                         /*
580                          * Indicate that there is a difference between lines a and b of the 'from' file
581                          * to get to lines c to d of the 'to' file. If a is greater than b then there
582                          * are no lines in the 'from' file involved and this means that there were
583                          * lines appended (beginning at b).  If c is greater than d then there are
584                          * lines missing from the 'to' file.
585                          */
586                         if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
587                                 /*
588                                  * If this change is more than 'context' lines from the
589                                  * previous change, dump the record and reset it.
590                                  */
591                                 int ct = (2 * opt_U_context) + 1;
592                                 if (idx >= 0
593                                  && v[0].a > vec[idx][0].b + ct
594                                  && v[1].a > vec[idx][1].b + ct
595                                 ) {
596                                         break;
597                                 }
598
599                                 for (int j = 0; j < 2; j++)
600                                         for (int k = v[j].a; k < v[j].b; k++)
601                                                 nonempty |= (ix[j][k+1] - ix[j][k] != 1);
602
603                                 vec = xrealloc_vector(vec, 6, ++idx);
604                                 memcpy(vec[idx], v, sizeof(v));
605                         }
606
607                         i = v[0].b + 1;
608                         if (i > nlen[0])
609                                 break;
610                         J[v[0].b] = v[1].b;
611                 }
612                 if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
613                         goto cont;
614                 if (!(option_mask32 & FLAG(q))) {
615                         vec_t span, *cvp = vec;
616
617                         if (!anychange) {
618                                 /* Print the context/unidiff header first time through */
619                                 printf("--- %s\n", label[0] ? label[0] : file[0]);
620                                 printf("+++ %s\n", label[1] ? label[1] : file[1]);
621                         }
622
623                         printf("@@");
624                         for (int j = 0; j < 2; j++) {
625                                 int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
626                                 int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
627
628                                 printf(" %c%d", j ? '+' : '-', MIN(a, b));
629                                 if (a == b)
630                                         continue;
631                                 printf(",%d", (a < b) ? b - a + 1 : 0);
632                         }
633                         printf(" @@\n");
634                         /*
635                          * Output changes in "unified" diff format--the old and new lines
636                          * are printed together.
637                          */
638                         for (int lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
639                                 bool end = cvp > &vec[idx];
640                                 fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
641                                 if (end)
642                                         break;
643                                 for (int j = 0; j < 2; j++)
644                                         fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
645                         }
646                 }
647                 anychange = true;
648  cont:
649                 idx = -1;
650         } while (i <= nlen[0]);
651
652         free(vec);
653         free(ix[0]);
654         free(ix[1]);
655         free(J);
656         return anychange;
657 }
658
659 static int diffreg(char *file[2])
660 {
661         FILE *fp[2] = { stdin, stdin };
662         bool binary = false, differ = false;
663         int status = STATUS_SAME;
664
665         for (int i = 0; i < 2; i++) {
666                 int fd = open_or_warn_stdin(file[i]);
667                 if (fd == -1)
668                         goto out;
669                 /* Our diff implementation is using seek.
670                  * When we meet non-seekable file, we must make a temp copy.
671                  */
672                 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
673                         char name[] = "/tmp/difXXXXXX";
674                         int fd_tmp = mkstemp(name);
675                         if (fd_tmp < 0)
676                                 bb_perror_msg_and_die("mkstemp");
677                         unlink(name);
678                         if (bb_copyfd_eof(fd, fd_tmp) < 0)
679                                 xfunc_die();
680                         if (fd) /* Prevents closing of stdin */
681                                 close(fd);
682                         fd = fd_tmp;
683                 }
684                 fp[i] = fdopen(fd, "r");
685         }
686
687         while (1) {
688                 const size_t sz = COMMON_BUFSIZE / 2;
689                 char *const buf0 = bb_common_bufsiz1;
690                 char *const buf1 = buf0 + sz;
691                 int i, j;
692                 i = fread(buf0, 1, sz, fp[0]);
693                 j = fread(buf1, 1, sz, fp[1]);
694                 if (i != j) {
695                         differ = true;
696                         i = MIN(i, j);
697                 }
698                 if (i == 0)
699                         break;
700                 for (int k = 0; k < i; k++) {
701                         if (!buf0[k] || !buf1[k])
702                                 binary = true;
703                         if (buf0[k] != buf1[k])
704                                 differ = true;
705                 }
706         }
707         if (differ) {
708                 if (binary && !(option_mask32 & FLAG(a)))
709                         status = STATUS_BINARY;
710                 else if (diff(fp, file))
711                         status = STATUS_DIFFER;
712         }
713         if (status != STATUS_SAME)
714                 exit_status |= 1;
715 out:
716         fclose_if_not_stdin(fp[0]);
717         fclose_if_not_stdin(fp[1]);
718
719         return status;
720 }
721
722 static void print_status(int status, char *path[2])
723 {
724         switch (status) {
725         case STATUS_BINARY:
726         case STATUS_DIFFER:
727                 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
728                         printf("Files %s and %s differ\n", path[0], path[1]);
729                 break;
730         case STATUS_SAME:
731                 if (option_mask32 & FLAG(s))
732                         printf("Files %s and %s are identical\n", path[0], path[1]);
733                 break;
734         }
735 }
736
737 #if ENABLE_FEATURE_DIFF_DIR
738 struct dlist {
739         size_t len;
740         int s, e;
741         char **dl;
742 };
743
744 /* This function adds a filename to dl, the directory listing. */
745 static int FAST_FUNC add_to_dirlist(const char *filename,
746                 struct stat *sb UNUSED_PARAM,
747                 void *userdata, int depth UNUSED_PARAM)
748 {
749         struct dlist *const l = userdata;
750         l->dl = xrealloc_vector(l->dl, 6, l->e);
751         /* + 1 skips "/" after dirname */
752         l->dl[l->e] = xstrdup(filename + l->len + 1);
753         l->e++;
754         return TRUE;
755 }
756
757 /* If recursion is not set, this function adds the directory
758  * to the list and prevents recursive_action from recursing into it.
759  */
760 static int FAST_FUNC skip_dir(const char *filename,
761                 struct stat *sb, void *userdata,
762                 int depth)
763 {
764         if (!(option_mask32 & FLAG(r)) && depth) {
765                 add_to_dirlist(filename, sb, userdata, depth);
766                 return SKIP;
767         }
768         return TRUE;
769 }
770
771 static void diffdir(char *p[2], const char *s_start)
772 {
773         struct dlist list[2];
774
775         memset(&list, 0, sizeof(list));
776         for (int i = 0; i < 2; i++) {
777                 /*list[i].s = list[i].e = 0; - memset did it */
778                 /*list[i].dl = NULL; */
779
780                 /* We need to trim root directory prefix.
781                  * Using list.len to specify its length,
782                  * add_to_dirlist will remove it. */
783                 list[i].len = strlen(p[i]);
784                 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
785                                  add_to_dirlist, skip_dir, &list[i], 0);
786                 /* Sort dl alphabetically.
787                  * GNU diff does this ignoring any number of trailing dots.
788                  * We don't, so for us dotted files almost always are
789                  * first on the list.
790                  */
791                 qsort_string_vector(list[i].dl, list[i].e);
792                 /* If -S was set, find the starting point. */
793                 if (!s_start)
794                         continue;
795                 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
796                         list[i].s++;
797         }
798         /* Now that both dirlist1 and dirlist2 contain sorted directory
799          * listings, we can start to go through dirlist1. If both listings
800          * contain the same file, then do a normal diff. Otherwise, behaviour
801          * is determined by whether the -N flag is set. */
802         while (1) {
803                 char *dp[2];
804                 int pos;
805                 int k;
806
807                 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
808                 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
809                 if (!dp[0] && !dp[1])
810                         break;
811                 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
812                 k = pos > 0;
813                 if (pos && !(option_mask32 & FLAG(N)))
814                         printf("Only in %s: %s\n", p[k], dp[k]);
815                 else {
816                         char *fullpath[2], *path[2]; /* if -N */
817
818                         for (int i = 0; i < 2; i++) {
819                                 if (pos == 0 || i == k) {
820                                         path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
821                                         stat(fullpath[i], &stb[i]);
822                                 } else {
823                                         fullpath[i] = concat_path_file(p[i], dp[1 - i]);
824                                         path[i] = (char *)bb_dev_null;
825                                 }
826                         }
827                         if (pos)
828                                 stat(fullpath[k], &stb[1 - k]);
829
830                         if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
831                                 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
832                         else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
833                                 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
834                         else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
835                                 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
836                         else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
837                                 if (S_ISDIR(stb[0].st_mode))
838                                         printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
839                                 else
840                                         printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
841                         } else
842                                 print_status(diffreg(path), fullpath);
843
844                         free(fullpath[0]);
845                         free(fullpath[1]);
846                 }
847                 free(dp[k]);
848                 list[k].s++;
849                 if (pos == 0) {
850                         free(dp[1 - k]);
851                         list[1 - k].s++;
852                 }
853         }
854         if (ENABLE_FEATURE_CLEAN_UP) {
855                 free(list[0].dl);
856                 free(list[1].dl);
857         }
858 }
859 #endif
860
861 #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
862 static const char diff_longopts[] ALIGN1 =
863         "ignore-case\0"              No_argument       "i"
864         "ignore-tab-expansion\0"     No_argument       "E"
865         "ignore-space-change\0"      No_argument       "b"
866         "ignore-all-space\0"         No_argument       "w"
867         "ignore-blank-lines\0"       No_argument       "B"
868         "text\0"                     No_argument       "a"
869         "unified\0"                  Required_argument "U"
870         "label\0"                    Required_argument "L"
871         "show-c-function\0"          No_argument       "p"
872         "brief\0"                    No_argument       "q"
873         "expand-tabs\0"              No_argument       "t"
874         "initial-tab\0"              No_argument       "T"
875         "recursive\0"                No_argument       "r"
876         "new-file\0"                 No_argument       "N"
877         "report-identical-files\0"   No_argument       "s"
878         "starting-file\0"            Required_argument "S"
879         "minimal\0"                  No_argument       "d"
880         ;
881 #endif
882
883 int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
884 int diff_main(int argc UNUSED_PARAM, char **argv)
885 {
886         int gotstdin = 0;
887         char *file[2], *s_start = NULL;
888         llist_t *L_arg = NULL;
889
890         INIT_G();
891
892         /* exactly 2 params; collect multiple -L <label>; -U N */
893         opt_complementary = "=2:L::U+";
894 #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
895         applet_long_options = diff_longopts;
896 #endif
897         getopt32(argv, "abdiL:NqrsS:tTU:wupBE",
898                         &L_arg, &s_start, &opt_U_context);
899         argv += optind;
900         while (L_arg)
901                 label[!!label[0]] = llist_pop(&L_arg);
902         xfunc_error_retval = 2;
903         for (int i = 0; i < 2; i++) {
904                 file[i] = argv[i];
905                 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
906                 if (LONE_DASH(file[i])) {
907                         fstat(STDIN_FILENO, &stb[i]);
908                         gotstdin++;
909                 } else
910                         xstat(file[i], &stb[i]);
911         }
912         xfunc_error_retval = 1;
913         if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
914                 bb_error_msg_and_die("can't compare stdin to a directory");
915
916         if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
917 #if ENABLE_FEATURE_DIFF_DIR
918                 diffdir(file, s_start);
919 #else
920                 bb_error_msg_and_die("no support for directory comparison");
921 #endif
922         } else {
923                 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
924                 bool dir = S_ISDIR(stb[1].st_mode);
925                 if (dirfile) {
926                         const char *slash = strrchr(file[!dir], '/');
927                         file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
928                         xstat(file[dir], &stb[dir]);
929                 }
930                 /* diffreg can get non-regular files here */
931                 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
932
933                 if (dirfile)
934                         free(file[dir]);
935         }
936
937         return exit_status;
938 }