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