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