diff: defeat gcc's optimization
[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, /* 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 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                                         J[i] = 0; /* Break the correspondence */
547                         } while (!(tok0 & tok1 & TOK_EMPTY));
548                 }
549         }
550
551         return J;
552 }
553
554 /*
555  * The following struct is used to record change information
556  * doing a "context" or "unified" diff.
557  */
558 struct context_vec {
559         int a;          /* start line in old file */
560         int b;          /* end line in old file */
561         int c;          /* start line in new file */
562         int d;          /* end line in new file */
563 };
564
565 static bool diff(FILE_and_pos_t ft[2], char *file[2])
566 {
567         int nlen[2];
568         off_t *ix[2];
569         int *J = create_J(ft, nlen, ix);
570
571         bool anychange = false;
572         struct context_vec *vec = NULL;
573         int idx = -1, i = 1;
574
575         do {
576                 while (1) {
577                         struct context_vec v;
578
579                         for (v.a = i; v.a <= nlen[0] && J[v.a] == J[v.a - 1] + 1; v.a++)
580                                 continue;
581                         v.c = J[v.a - 1] + 1;
582
583                         for (v.b = v.a - 1; v.b < nlen[0] && !J[v.b + 1]; v.b++)
584                                 continue;
585                         v.d = J[v.b + 1] - 1;
586                         /*
587                          * Indicate that there is a difference between lines a and b of the 'from' file
588                          * to get to lines c to d of the 'to' file. If a is greater than b then there
589                          * are no lines in the 'from' file involved and this means that there were
590                          * lines appended (beginning at b).  If c is greater than d then there are
591                          * lines missing from the 'to' file.
592                          */
593                         if (v.a <= v.b || v.c <= v.d) {
594                                 /*
595                                  * If this change is more than 'context' lines from the
596                                  * previous change, dump the record and reset it.
597                                  */
598                                 if (idx >= 0
599                                  && v.a > vec[idx].b + (2 * opt_U_context) + 1
600                                  && v.c > vec[idx].d + (2 * opt_U_context) + 1
601                                 ) {
602                                         break;
603                                 }
604                                 vec = xrealloc_vector(vec, 6, ++idx);
605                                 vec[idx] = v;
606                         }
607
608                         i = v.b + 1;
609                         if (i > nlen[0])
610                                 break;
611                         J[v.b] = v.d;
612                 }
613                 if (idx < 0)
614                         continue;
615                 if (!(option_mask32 & FLAG(q))) {
616                         struct context_vec *cvp = vec;
617                         int lowa = MAX(1, cvp->a - opt_U_context);
618                         int upb  = MIN(nlen[0], vec[idx].b + opt_U_context);
619                         int lowc = MAX(1, cvp->c - opt_U_context);
620                         int upd  = MIN(nlen[1], vec[idx].d + opt_U_context);
621
622                         if (!anychange) {
623                                 /* Print the context/unidiff header first time through */
624                                 printf("--- %s\n", label[0] ?: file[0]);
625                                 printf("+++ %s\n", label[1] ?: file[1]);
626                         }
627
628                         printf("@@ -");
629                         uni_range(lowa, upb);
630                         printf(" +");
631                         uni_range(lowc, upd);
632                         printf(" @@\n");
633
634                         /*
635                          * Output changes in "unified" diff format--the old and new lines
636                          * are printed together.
637                          */
638                         while (1) {
639                                 bool end = cvp > &vec[idx];
640                                 fetch(&ft[0], ix[0], lowa, end ? upb : cvp->a - 1, ' ');
641                                 if (end)
642                                         break;
643                                 fetch(&ft[0], ix[0], cvp->a, cvp->b, '-');
644                                 fetch(&ft[1], ix[1], cvp->c, cvp->d, '+');
645                                 lowa = cvp++->b + 1;
646                         }
647                 }
648                 idx = -1;
649                 anychange = true;
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_and_pos_t ft[2];
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                         xfunc_die();
669                 /* Our diff implementation is using seek.
670                  * When we meet non-seekable file, we must make a temp copy.
671                  */
672                 ft[i].ft_pos = 0;
673                 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
674                         char name[] = "/tmp/difXXXXXX";
675                         int fd_tmp = mkstemp(name);
676                         if (fd_tmp < 0)
677                                 bb_perror_msg_and_die("mkstemp");
678                         unlink(name);
679                         ft[i].ft_pos = bb_copyfd_eof(fd, fd_tmp);
680                         /* error message is printed by bb_copyfd_eof */
681                         if (ft[i].ft_pos < 0)
682                                 xfunc_die();
683                         fstat(fd, &stb[i]);
684                         if (fd) /* Prevents closing of stdin */
685                                 close(fd);
686                         fd = fd_tmp;
687                 }
688                 ft[i].ft_fp = fdopen(fd, "r");
689         }
690
691         while (1) {
692                 const size_t sz = COMMON_BUFSIZE / 2;
693                 char *const buf0 = bb_common_bufsiz1;
694                 char *const buf1 = buf0 + sz;
695                 int i, j;
696                 i = fread(buf0, 1, sz, ft[0].ft_fp);
697                 ft[0].ft_pos += i;
698                 j = fread(buf1, 1, sz, ft[1].ft_fp);
699                 ft[1].ft_pos += j;
700                 if (i != j) {
701                         differ = true;
702                         i = MIN(i, j);
703                 }
704                 if (i == 0)
705                         break;
706                 for (int k = 0; k < i; k++) {
707                         if (!buf0[k] || !buf1[k])
708                                 binary = true;
709                         if (buf0[k] != buf1[k])
710                                 differ = true;
711                 }
712         }
713         if (differ) {
714                 if (binary && !(option_mask32 & FLAG(a)))
715                         status = STATUS_BINARY;
716                 else if (diff(ft, file))
717                         status = STATUS_DIFFER;
718         }
719         if (status != STATUS_SAME)
720                 exit_status |= 1;
721
722         fclose_if_not_stdin(ft[0].ft_fp);
723         fclose_if_not_stdin(ft[1].ft_fp);
724
725         return status;
726 }
727
728 static void print_status(int status, char *path[2])
729 {
730         switch (status) {
731         case STATUS_BINARY:
732         case STATUS_DIFFER:
733                 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
734                         printf("Files %s and %s differ\n", path[0], path[1]);
735                 break;
736         case STATUS_SAME:
737                 if (option_mask32 & FLAG(s))
738                         printf("Files %s and %s are identical\n", path[0], path[1]);
739                 break;
740         }
741 }
742
743 #if ENABLE_FEATURE_DIFF_DIR
744 struct dlist {
745         size_t len;
746         int s, e;
747         char **dl;
748 };
749
750 /* This function adds a filename to dl, the directory listing. */
751 static int FAST_FUNC add_to_dirlist(const char *filename,
752                 struct stat *sb UNUSED_PARAM,
753                 void *userdata, int depth UNUSED_PARAM)
754 {
755         struct dlist *const l = userdata;
756         l->dl = xrealloc_vector(l->dl, 6, l->e);
757         /* + 1 skips "/" after dirname */
758         l->dl[l->e] = xstrdup(filename + l->len + 1);
759         l->e++;
760         return TRUE;
761 }
762
763 /* If recursion is not set, this function adds the directory
764  * to the list and prevents recursive_action from recursing into it.
765  */
766 static int FAST_FUNC skip_dir(const char *filename,
767                 struct stat *sb, void *userdata,
768                 int depth)
769 {
770         if (!(option_mask32 & FLAG(r)) && depth) {
771                 add_to_dirlist(filename, sb, userdata, depth);
772                 return SKIP;
773         }
774         return TRUE;
775 }
776
777 static void diffdir(char *p[2], const char *s_start)
778 {
779         struct dlist list[2];
780
781         memset(&list, 0, sizeof(list));
782         for (int i = 0; i < 2; i++) {
783                 /*list[i].s = list[i].e = 0; - memset did it */
784                 /*list[i].dl = NULL; */
785
786                 /* We need to trim root directory prefix.
787                  * Using list.len to specify its length,
788                  * add_to_dirlist will remove it. */
789                 list[i].len = strlen(p[i]);
790                 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
791                                  add_to_dirlist, skip_dir, &list[i], 0);
792                 /* Sort dl alphabetically.
793                  * GNU diff does this ignoring any number of trailing dots.
794                  * We don't, so for us dotted files almost always are
795                  * first on the list.
796                  */
797                 qsort_string_vector(list[i].dl, list[i].e);
798                 /* If -S was set, find the starting point. */
799                 if (!s_start)
800                         continue;
801                 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
802                         list[i].s++;
803         }
804         /* Now that both dirlist1 and dirlist2 contain sorted directory
805          * listings, we can start to go through dirlist1. If both listings
806          * contain the same file, then do a normal diff. Otherwise, behaviour
807          * is determined by whether the -N flag is set. */
808         while (1) {
809                 char *dp[2];
810                 int pos;
811                 int k;
812
813                 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
814                 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
815                 if (!dp[0] && !dp[1])
816                         break;
817                 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
818                 k = pos > 0;
819                 if (pos && !(option_mask32 & FLAG(N)))
820                         printf("Only in %s: %s\n", p[k], dp[k]);
821                 else {
822                         char *fullpath[2], *path[2]; /* if -N */
823
824                         for (int i = 0; i < 2; i++) {
825                                 if (pos == 0 || i == k) {
826                                         path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
827                                         stat(fullpath[i], &stb[i]);
828                                 } else {
829                                         fullpath[i] = concat_path_file(p[i], dp[1 - i]);
830                                         path[i] = (char *)bb_dev_null;
831                                 }
832                         }
833                         if (pos)
834                                 stat(fullpath[k], &stb[1 - k]);
835
836                         if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
837                                 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
838                         else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
839                                 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
840                         else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
841                                 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
842                         else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
843                                 if (S_ISDIR(stb[0].st_mode))
844                                         printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
845                                 else
846                                         printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
847                         } else
848                                 print_status(diffreg(path), fullpath);
849
850                         free(fullpath[0]);
851                         free(fullpath[1]);
852                 }
853                 free(dp[k]);
854                 list[k].s++;
855                 if (pos == 0) {
856                         free(dp[1 - k]);
857                         list[1 - k].s++;
858                 }
859         }
860         if (ENABLE_FEATURE_CLEAN_UP) {
861                 free(list[0].dl);
862                 free(list[1].dl);
863         }
864 }
865 #endif
866
867 int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
868 int diff_main(int argc UNUSED_PARAM, char **argv)
869 {
870         int gotstdin = 0;
871         char *file[2], *s_start = NULL;
872         llist_t *L_arg = NULL;
873
874         INIT_G();
875
876         /* exactly 2 params; collect multiple -L <label>; -U N */
877         opt_complementary = "=2:L::U+";
878         getopt32(argv, "abdiL:NqrsS:tTU:wu"
879                         "p" /* ignored (for compatibility) */,
880                         &L_arg, &s_start, &opt_U_context);
881         argv += optind;
882         while (L_arg) {
883                 if (label[0] && label[1])
884                         bb_show_usage();
885                 if (label[0]) /* then label[1] is NULL */
886                         label[1] = label[0];
887                 label[0] = llist_pop(&L_arg);
888         }
889         xfunc_error_retval = 2;
890         for (int i = 0; i < 2; i++) {
891                 file[i] = argv[i];
892                 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
893                 if (LONE_DASH(file[i])) {
894                         fstat(STDIN_FILENO, &stb[i]);
895                         gotstdin++;
896                 } else
897                         xstat(file[i], &stb[i]);
898         }
899         xfunc_error_retval = 1;
900         if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
901                 bb_error_msg_and_die("can't compare stdin to a directory");
902
903         if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
904 #if ENABLE_FEATURE_DIFF_DIR
905                 diffdir(file, s_start);
906 #else
907                 bb_error_msg_and_die("no support for directory comparison");
908 #endif
909         } else {
910                 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
911                 bool dir = S_ISDIR(stb[1].st_mode);
912                 if (dirfile) {
913                         const char *slash = strrchr(file[!dir], '/');
914                         file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
915                         xstat(file[dir], &stb[dir]);
916                 }
917                 /* diffreg can get non-regular files here */
918                 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
919
920                 if (dirfile)
921                         free(file[dir]);
922         }
923
924         return exit_status;
925 }