1 /* vi: set sw=4 ts=4: */
3 * Mini diff implementation for busybox, adapted from OpenBSD diff.
5 * Copyright (C) 2006 by Robert Sullivan <cogito.ergo.cogito@hotmail.com>
6 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
8 * Sponsored in part by the Defense Advanced Research Projects
9 * Agency (DARPA) and Air Force Research Laboratory, Air Force
10 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
12 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
17 // #define FSIZE_MAX 32768
19 /* NOINLINEs added to prevent gcc from merging too much into diffreg()
20 * (it bites more than it can (efficiently) chew). */
25 #define D_HEADER 1 /* Print a header/footer between files */
26 #define D_EMPTY1 2 /* Treat first file as empty (/dev/null) */
27 #define D_EMPTY2 4 /* Treat second file as empty (/dev/null) */
30 * Status values for print_status() and diffreg() return values
32 * D_SAME - files are the same
33 * D_DIFFER - files differ
34 * D_BINARY - binary files differ
35 * D_COMMON - subdirectory common to both dirs
36 * D_ONLY - file only exists in one dir
37 * D_ISDIR1 - path1 a dir, path2 a file
38 * D_ISDIR2 - path1 a file, path2 a dir
39 * D_ERROR - error occurred
40 * D_SKIPPED1 - skipped path1 as it is a special file
41 * D_SKIPPED2 - skipped path2 as it is a special file
44 #define D_DIFFER (1 << 0)
45 #define D_BINARY (1 << 1)
46 #define D_COMMON (1 << 2)
47 /*#define D_ONLY (1 << 3) - unused */
48 #define D_ISDIR1 (1 << 4)
49 #define D_ISDIR2 (1 << 5)
50 #define D_ERROR (1 << 6)
51 #define D_SKIPPED1 (1 << 7)
52 #define D_SKIPPED2 (1 << 8)
54 /* Command line options */
55 #define FLAG_a (1 << 0)
56 #define FLAG_b (1 << 1)
57 #define FLAG_d (1 << 2)
58 #define FLAG_i (1 << 3)
59 #define FLAG_L (1 << 4)
60 #define FLAG_N (1 << 5)
61 #define FLAG_q (1 << 6)
62 #define FLAG_r (1 << 7)
63 #define FLAG_s (1 << 8)
64 #define FLAG_S (1 << 9)
65 #define FLAG_t (1 << 10)
66 #define FLAG_T (1 << 11)
67 #define FLAG_U (1 << 12)
68 #define FLAG_w (1 << 13)
83 * The following struct is used to record change information
84 * doing a "context" or "unified" diff. (see routine "change" to
85 * understand the highly mnemonic field names)
88 int a; /* start line in old file */
89 int b; /* end line in old file */
90 int c; /* start line in new file */
91 int d; /* end line in new file */
95 #define g_read_buf bb_common_bufsiz1
98 USE_FEATURE_DIFF_DIR(char **dl;)
99 USE_FEATURE_DIFF_DIR(int dl_count;)
101 /* This is the default number of lines of context. */
107 struct line *file[2];
108 int *J; /* will be overlaid on class */
111 int pref, suff; /* length of prefix and suffix */
114 long *ixnew; /* will be overlaid on file[1] */
115 long *ixold; /* will be overlaid on klist */
116 struct cand *clist; /* merely a free storage pot for candidates */
117 int clistlen; /* the length of clist */
118 struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
119 struct context_vec *context_vec_start;
120 struct context_vec *context_vec_end;
121 struct context_vec *context_vec_ptr;
122 struct stat stb1, stb2;
123 char *tempname1, *tempname2;
125 #define G (*ptr_to_globals)
127 #define dl_count (G.dl_count )
128 #define context (G.context )
129 #define max_context (G.max_context )
130 #define status (G.status )
131 #define start (G.start )
132 #define label1 (G.label1 )
133 #define label2 (G.label2 )
134 #define file (G.file )
136 #define clen (G.clen )
138 #define pref (G.pref )
139 #define suff (G.suff )
140 #define slen (G.slen )
141 #define anychange (G.anychange )
142 #define ixnew (G.ixnew )
143 #define ixold (G.ixold )
144 #define clist (G.clist )
145 #define clistlen (G.clistlen )
146 #define sfile (G.sfile )
147 #define context_vec_start (G.context_vec_start )
148 #define context_vec_end (G.context_vec_end )
149 #define context_vec_ptr (G.context_vec_ptr )
150 #define stb1 (G.stb1 )
151 #define stb2 (G.stb2 )
152 #define tempname1 (G.tempname1 )
153 #define tempname2 (G.tempname2 )
154 #define INIT_G() do { \
155 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
161 /*static void print_only(const char *path, size_t dirlen, const char *entry)*/
162 static void print_only(const char *path, const char *entry)
164 printf("Only in %s: %s\n", path, entry);
168 /*static void print_status(int val, char *path1, char *path2, char *entry)*/
169 static void print_status(int val, char *_path1, char *_path2)
171 /*const char *const _entry = entry ? entry : "";*/
172 /*char *const _path1 = entry ? concat_path_file(path1, _entry) : path1;*/
173 /*char *const _path2 = entry ? concat_path_file(path2, _entry) : path2;*/
177 print_only(path1, entry);
181 printf("Common subdirectories: %s and %s\n", _path1, _path2);
184 printf("Binary files %s and %s differ\n", _path1, _path2);
187 if (option_mask32 & FLAG_q)
188 printf("Files %s and %s differ\n", _path1, _path2);
191 if (option_mask32 & FLAG_s)
192 printf("Files %s and %s are identical\n", _path1, _path2);
195 printf("File %s is a %s while file %s is a %s\n",
196 _path1, "directory", _path2, "regular file");
199 printf("File %s is a %s while file %s is a %s\n",
200 _path1, "regular file", _path2, "directory");
203 printf("File %s is not a regular file or directory and was skipped\n",
207 printf("File %s is not a regular file or directory and was skipped\n",
220 /* Read line, return its nonzero hash. Return 0 if EOF.
222 * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
224 static ALWAYS_INLINE int fiddle_sum(int sum, int t)
226 return sum * 127 + t;
228 static int readhash(FILE *fp)
236 if (!(option_mask32 & (FLAG_b | FLAG_w))) {
237 while ((t = getc(fp)) != '\n') {
243 sum = fiddle_sum(sum, t);
248 switch (t = getc(fp)) {
257 if (space && !(option_mask32 & FLAG_w)) {
261 sum = fiddle_sum(sum, t);
275 * There is a remote possibility that we end up with a zero sum.
276 * Zero is used as an EOF marker, so return 1 instead.
278 return (sum == 0 ? 1 : sum);
282 static char *make_temp(FILE *f, struct stat *sb)
287 if (S_ISREG(sb->st_mode))
289 name = xstrdup("/tmp/difXXXXXX");
292 bb_perror_msg_and_die("mkstemp");
293 if (bb_copyfd_eof(fileno(f), fd) < 0) {
296 xfunc_die(); /* error message is printed by bb_copyfd_eof */
300 if (freopen(name, "r+", f) == NULL) {
301 bb_perror_msg("freopen");
309 * Check to see if the given files differ.
310 * Returns 0 if they are the same, 1 if different, and -1 on error.
312 static NOINLINE int files_differ(FILE *f1, FILE *f2, int flags)
316 tempname1 = make_temp(f1, &stb1);
317 tempname2 = make_temp(f2, &stb2);
318 if ((flags & (D_EMPTY1 | D_EMPTY2)) || stb1.st_size != stb2.st_size) {
322 i = fread(g_read_buf, 1, COMMON_BUFSIZE/2, f1);
323 j = fread(g_read_buf + COMMON_BUFSIZE/2, 1, COMMON_BUFSIZE/2, f2);
327 return (ferror(f1) || ferror(f2)) ? -1 : 0;
328 if (memcmp(g_read_buf,
329 g_read_buf + COMMON_BUFSIZE/2, i) != 0)
335 static void prepare(int i, FILE *fp /*, off_t filesize*/)
343 /*sz = (filesize <= FSIZE_MAX ? filesize : FSIZE_MAX) / 25;*/
347 p = xmalloc((sz + 3) * sizeof(p[0]));
349 while ((h = readhash(fp)) != 0) { /* while not EOF */
352 p = xrealloc(p, (sz + 3) * sizeof(p[0]));
361 static void prune(void)
365 for (pref = 0; pref < len[0] && pref < len[1] &&
366 file[0][pref + 1].value == file[1][pref + 1].value; pref++)
368 for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
369 file[0][len[0] - suff].value == file[1][len[1] - suff].value;
372 for (j = 0; j < 2; j++) {
373 sfile[j] = file[j] + pref;
374 slen[j] = len[j] - pref - suff;
375 for (i = 0; i <= slen[j]; i++)
376 sfile[j][i].serial = i;
381 static void equiv(struct line *a, int n, struct line *b, int m, int *c)
386 while (i <= n && j <= m) {
387 if (a[i].value < b[j].value)
389 else if (a[i].value == b[j].value)
400 while (b[j + 1].value == b[j].value) {
409 static int isqrt(int n)
421 } while ((x - y) > 1 || (x - y) < -1);
427 static int newcand(int x, int y, int pred)
431 if (clen == clistlen) {
432 clistlen = clistlen * 11 / 10;
433 clist = xrealloc(clist, clistlen * sizeof(struct cand));
443 static int search(int *c, int k, int y)
447 if (clist[c[k]].y < y) /* quick look for typical case */
467 static int stone(int *a, int n, int *b, int *c)
471 unsigned int numtries;
472 #if ENABLE_FEATURE_DIFF_MINIMAL
473 const unsigned int bound =
474 (option_mask32 & FLAG_d) ? UINT_MAX : MAX(256, isqrt(n));
476 const unsigned int bound = MAX(256, isqrt(n));
480 c[0] = newcand(0, 0, 0);
481 for (i = 1; i <= n; i++) {
490 if (y <= clist[oldc].y)
496 if (clist[c[l]].y <= y)
499 c[l] = newcand(i, y, oldc);
504 c[l] = newcand(i, y, oldc);
508 } while ((y = b[++j]) > 0 && numtries < bound);
514 static void unravel(int p)
519 for (i = 0; i <= len[0]; i++)
520 J[i] = i <= pref ? i : i > len[0] - suff ? i + len[1] - len[0] : 0;
521 for (q = clist + p; q->y != 0; q = clist + q->pred)
522 J[q->x + pref] = q->y + pref;
526 static void unsort(struct line *f, int l, int *b)
530 a = xmalloc((l + 1) * sizeof(int));
531 for (i = 1; i <= l; i++)
532 a[f[i].serial] = f[i].value;
533 for (i = 1; i <= l; i++)
539 static int skipline(FILE *f)
543 for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
550 * Check does double duty:
551 * 1. ferret out any fortuitous correspondences due
552 * to confounding by hashing (which result in "jackpot")
553 * 2. collect random access indexes to the two files
555 static NOINLINE void check(FILE *f1, FILE *f2)
557 int i, j, jackpot, c, d;
563 ixold[0] = ixnew[0] = 0;
566 for (i = 1; i <= len[0]; i++) {
568 ixold[i] = ctold += skipline(f1);
572 ixnew[j] = ctnew += skipline(f2);
575 if (option_mask32 & (FLAG_b | FLAG_w | FLAG_i)) {
580 * GNU diff ignores a missing newline
581 * in one file if bflag || wflag.
583 if ((option_mask32 & (FLAG_b | FLAG_w))
584 && ((c == EOF && d == '\n') || (c == '\n' && d == EOF))
590 if ((option_mask32 & FLAG_b) && isspace(c) && isspace(d)) {
596 } while (isspace(c));
602 } while (isspace(d));
603 } else if (option_mask32 & FLAG_w) {
604 while (isspace(c) && c != '\n') {
608 while (isspace(d) && d != '\n') {
616 if (c != '\n' && c != EOF)
617 ctold += skipline(f1);
618 if (d != '\n' && c != EOF)
619 ctnew += skipline(f2);
622 if (c == '\n' || c == EOF)
633 if (c != '\n' && c != EOF)
634 ctold += skipline(f1);
635 // BUG? Should be "if (d != '\n' && d != EOF)" ?
636 if (d != '\n' && c != EOF)
637 ctnew += skipline(f2);
640 if (c == '\n' || c == EOF)
648 for (; j <= len[1]; j++)
649 ixnew[j] = ctnew += skipline(f2);
653 /* shellsort CACM #201 */
654 static void sort(struct line *a, int n)
656 struct line *ai, *aim, w;
661 for (j = 1; j <= n; j *= 2)
663 for (m /= 2; m != 0; m /= 2) {
665 for (j = 1; j <= k; j++) {
666 for (ai = &a[j]; ai > a; ai -= m) {
669 break; /* wraparound */
670 if (aim->value > ai[0].value
671 || (aim->value == ai[0].value && aim->serial > ai[0].serial)
675 w.value = ai[0].value;
676 ai[0].value = aim->value;
677 aim->value = w.value;
678 w.serial = ai[0].serial;
679 ai[0].serial = aim->serial;
680 aim->serial = w.serial;
687 static void uni_range(int a, int b)
690 printf("%d,%d", a, b - a + 1);
698 static void fetch(long *f, int a, int b, FILE *lb, int ch)
700 int i, j, c, lastc, col, nc;
704 for (i = a; i <= b; i++) {
705 fseek(lb, f[i - 1], SEEK_SET);
706 nc = f[i] - f[i - 1];
709 if (option_mask32 & FLAG_T)
713 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
716 printf("\n\\ No newline at end of file\n");
719 if (c == '\t' && (option_mask32 & FLAG_t)) {
732 #if ENABLE_FEATURE_DIFF_BINARY
733 static int asciifile(FILE *f)
737 if (option_mask32 & FLAG_a)
740 cnt = fread(g_read_buf, 1, COMMON_BUFSIZE, f);
741 for (i = 0; i < cnt; i++) {
742 if (!isprint(g_read_buf[i])
743 && !isspace(g_read_buf[i])
751 #define asciifile(f) 1
755 /* dump accumulated "unified" diff changes */
756 static void dump_unified_vec(FILE *f1, FILE *f2)
758 struct context_vec *cvp = context_vec_start;
759 int lowa, upb, lowc, upd;
763 if (context_vec_start > context_vec_ptr)
767 lowa = MAX(1, cvp->a - context);
768 upb = MIN(len[0], context_vec_ptr->b + context);
769 lowc = MAX(1, cvp->c - context);
770 upd = MIN(len[1], context_vec_ptr->d + context);
773 uni_range(lowa, upb);
775 uni_range(lowc, upd);
779 * Output changes in "unified" diff format--the old and new lines
780 * are printed together.
782 for (; cvp <= context_vec_ptr; cvp++) {
789 * c: both new and old changes
790 * d: only changes in the old file
791 * a: only changes in the new file
793 if (a <= b && c <= d)
796 ch = (a <= b) ? 'd' : 'a';
801 fetch(ixold, lowa, a - 1, f1, ' ');
802 fetch(ixold, a, b, f1, '-');
803 fetch(ixnew, c, d, f2, '+');
806 fetch(ixold, lowa, a - 1, f1, ' ');
807 fetch(ixold, a, b, f1, '-');
810 fetch(ixnew, lowc, c - 1, f2, ' ');
811 fetch(ixnew, c, d, f2, '+');
815 if (ch == 'c' || ch == 'd') {
816 fetch(ixold, lowa, a - 1, f1, ' ');
817 fetch(ixold, a, b, f1, '-');
820 fetch(ixnew, lowc, c - 1, f2, ' ');
821 if (ch == 'c' || ch == 'a')
822 fetch(ixnew, c, d, f2, '+');
827 fetch(ixnew, d + 1, upd, f2, ' ');
829 context_vec_ptr = context_vec_start - 1;
833 static void print_header(const char *file1, const char *file2)
836 printf("--- %s\n", label1);
838 printf("--- %s\t%s", file1, ctime(&stb1.st_mtime));
840 printf("+++ %s\n", label2);
842 printf("+++ %s\t%s", file2, ctime(&stb2.st_mtime));
847 * Indicate that there is a difference between lines a and b of the from file
848 * to get to lines c to d of the to file. If a is greater than b then there
849 * are no lines in the from file involved and this means that there were
850 * lines appended (beginning at b). If c is greater than d then there are
851 * lines missing from the to file.
853 static void change(char *file1, FILE *f1, char *file2, FILE *f2,
854 int a, int b, int c, int d)
856 if ((a > b && c > d) || (option_mask32 & FLAG_q)) {
862 * Allocate change records as needed.
864 if (context_vec_ptr == context_vec_end - 1) {
865 ptrdiff_t offset = context_vec_ptr - context_vec_start;
868 context_vec_start = xrealloc(context_vec_start,
869 max_context * sizeof(struct context_vec));
870 context_vec_end = context_vec_start + max_context;
871 context_vec_ptr = context_vec_start + offset;
873 if (anychange == 0) {
875 * Print the context/unidiff header first time through.
877 print_header(file1, file2);
878 } else if (a > context_vec_ptr->b + (2 * context) + 1
879 && c > context_vec_ptr->d + (2 * context) + 1
882 * If this change is more than 'context' lines from the
883 * previous change, dump the record and reset it.
885 // dump_unified_vec() seeks!
886 dump_unified_vec(f1, f2);
889 context_vec_ptr->a = a;
890 context_vec_ptr->b = b;
891 context_vec_ptr->c = c;
892 context_vec_ptr->d = d;
897 static void output(char *file1, FILE *f1, char *file2, FILE *f2)
899 /* Note that j0 and j1 can't be used as they are defined in math.h.
900 * This also allows the rather amusing variable 'j00'... */
901 int m, i0, i1, j00, j01;
907 J[m + 1] = len[1] + 1;
908 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
909 while (i0 <= m && J[i0] == J[i0 - 1] + 1)
913 while (i1 < m && J[i1 + 1] == 0)
918 change(file1, f1, file2, f2, i0, i1, j00, j01);
922 change(file1, f1, file2, f2, 1, 0, 1, len[1]);
924 if (anychange != 0 && !(option_mask32 & FLAG_q)) {
925 // dump_unified_vec() seeks!
926 dump_unified_vec(f1, f2);
931 * The following code uses an algorithm due to Harold Stone,
932 * which finds a pair of longest identical subsequences in
935 * The major goal is to generate the match vector J.
936 * J[i] is the index of the line in file1 corresponding
937 * to line i in file0. J[i] = 0 if there is no
938 * such line in file1.
940 * Lines are hashed so as to work in core. All potential
941 * matches are located by sorting the lines of each file
942 * on the hash (called "value"). In particular, this
943 * collects the equivalence classes in file1 together.
944 * Subroutine equiv replaces the value of each line in
945 * file0 by the index of the first element of its
946 * matching equivalence in (the reordered) file1.
947 * To save space equiv squeezes file1 into a single
948 * array member in which the equivalence classes
949 * are simply concatenated, except that their first
950 * members are flagged by changing sign.
952 * Next the indices that point into member are unsorted into
953 * array class according to the original order of file0.
955 * The cleverness lies in routine stone. This marches
956 * through the lines of file0, developing a vector klist
957 * of "k-candidates". At step i a k-candidate is a matched
958 * pair of lines x,y (x in file0, y in file1) such that
959 * there is a common subsequence of length k
960 * between the first i lines of file0 and the first y
961 * lines of file1, but there is no such subsequence for
962 * any smaller y. x is the earliest possible mate to y
963 * that occurs in such a subsequence.
965 * Whenever any of the members of the equivalence class of
966 * lines in file1 matable to a line in file0 has serial number
967 * less than the y of some k-candidate, that k-candidate
968 * with the smallest such y is replaced. The new
969 * k-candidate is chained (via pred) to the current
970 * k-1 candidate so that the actual subsequence can
971 * be recovered. When a member has serial number greater
972 * that the y of all k-candidates, the klist is extended.
973 * At the end, the longest subsequence is pulled out
974 * and placed in the array J by unravel
976 * With J in hand, the matches there recorded are
977 * checked against reality to assure that no spurious
978 * matches have crept in due to hashing. If they have,
979 * they are broken, and "jackpot" is recorded--a harmless
980 * matter except that a true match for a spuriously
981 * mated line may now be unnecessarily reported as a change.
983 * Much of the complexity of the program comes simply
984 * from trying to minimize core utilization and
985 * maximize the range of doable problems by dynamically
986 * allocating what is needed and reusing what is not.
987 * The core requirements for problems larger than somewhat
988 * are (in words) 2*length(file0) + length(file1) +
989 * 3*(number of k-candidates installed), typically about
990 * 6n words for files of length n.
992 /* NB: files can be not REGular. The only sure thing that they
993 * are not both DIRectories. */
994 static unsigned diffreg(char *file1, char *file2, int flags)
996 int *member; /* will be overlaid on file[1] */
997 int *class; /* will be overlaid on file[0] */
998 int *klist; /* will be overlaid on file[0] after class */
1005 context_vec_ptr = context_vec_start - 1;
1007 /* Is any of them a directory? Then it's simple */
1008 if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
1009 return (S_ISDIR(stb1.st_mode) ? D_ISDIR1 : D_ISDIR2);
1011 /* None of them are directories */
1014 if (flags & D_EMPTY1)
1015 f1 = xfopen(bb_dev_null, "r");
1017 f1 = xfopen_stdin(file1);
1018 if (flags & D_EMPTY2)
1019 f2 = xfopen(bb_dev_null, "r");
1021 f2 = xfopen_stdin(file2);
1023 /* Quick check whether they are different */
1024 /* NB: copies non-REG files to tempfiles and fills tempname1/2 */
1025 i = files_differ(f1, f2, flags);
1026 if (i != 1) { /* not different? */
1027 if (i != 0) /* error? */
1032 if (!asciifile(f1) || !asciifile(f2)) {
1039 prepare(0, f1 /*, stb1.st_size*/);
1040 prepare(1, f2 /*, stb2.st_size*/);
1042 sort(sfile[0], slen[0]);
1043 sort(sfile[1], slen[1]);
1045 member = (int *) file[1];
1046 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
1047 member = xrealloc(member, (slen[1] + 2) * sizeof(int));
1049 class = (int *) file[0];
1050 unsort(sfile[0], slen[0], class);
1051 class = xrealloc(class, (slen[0] + 2) * sizeof(int));
1053 klist = xmalloc((slen[0] + 2) * sizeof(int));
1056 clist = xmalloc(clistlen * sizeof(struct cand));
1057 i = stone(class, slen[0], member, klist);
1061 J = xrealloc(J, (len[0] + 2) * sizeof(int));
1066 ixold = xrealloc(ixold, (len[0] + 2) * sizeof(long));
1067 ixnew = xrealloc(ixnew, (len[1] + 2) * sizeof(long));
1071 output(file1, f1, file2, f2);
1079 fclose_if_not_stdin(f1);
1080 fclose_if_not_stdin(f2);
1093 #if ENABLE_FEATURE_DIFF_DIR
1094 static void do_diff(char *dir1, char *path1, char *dir2, char *path2)
1096 int flags = D_HEADER;
1098 char *fullpath1 = NULL; /* if -N */
1099 char *fullpath2 = NULL;
1102 fullpath1 = concat_path_file(dir1, path1);
1104 fullpath2 = concat_path_file(dir2, path2);
1106 if (!fullpath1 || stat(fullpath1, &stb1) != 0) {
1108 memset(&stb1, 0, sizeof(stb1));
1111 fullpath1 = concat_path_file(dir1, path2);
1114 if (!fullpath2 || stat(fullpath2, &stb2) != 0) {
1116 memset(&stb2, 0, sizeof(stb2));
1117 stb2.st_mode = stb1.st_mode;
1120 fullpath2 = concat_path_file(dir2, path1);
1124 if (stb1.st_mode == 0)
1125 stb1.st_mode = stb2.st_mode;
1127 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1128 printf("Common subdirectories: %s and %s\n", fullpath1, fullpath2);
1132 if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode))
1134 else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode))
1137 /* Both files are either REGular or DIRectories */
1138 val = diffreg(fullpath1, fullpath2, flags);
1141 print_status(val, fullpath1, fullpath2 /*, NULL*/);
1149 #if ENABLE_FEATURE_DIFF_DIR
1150 /* This function adds a filename to dl, the directory listing. */
1151 static int add_to_dirlist(const char *filename,
1152 struct stat ATTRIBUTE_UNUSED *sb,
1154 int depth ATTRIBUTE_UNUSED)
1156 /* +2: with space for eventual trailing NULL */
1157 dl = xrealloc(dl, (dl_count+2) * sizeof(dl[0]));
1158 dl[dl_count] = xstrdup(filename + (int)(ptrdiff_t)userdata);
1164 /* This returns a sorted directory listing. */
1165 static char **get_recursive_dirlist(char *path)
1168 dl = xzalloc(sizeof(dl[0]));
1170 /* If -r has been set, then the recursive_action function will be
1171 * used. Unfortunately, this outputs the root directory along with
1172 * the recursed paths, so use void *userdata to specify the string
1173 * length of the root directory - '(void*)(strlen(path)+)'.
1174 * add_to_dirlist then removes root dir prefix. */
1175 if (option_mask32 & FLAG_r) {
1176 recursive_action(path, ACTION_RECURSE|ACTION_FOLLOWLINKS,
1177 add_to_dirlist, NULL,
1178 (void*)(strlen(path)+1), 0);
1183 dp = warn_opendir(path);
1184 while ((ep = readdir(dp))) {
1185 if (!strcmp(ep->d_name, "..") || LONE_CHAR(ep->d_name, '.'))
1187 add_to_dirlist(ep->d_name, NULL, (void*)(int)0, 0);
1192 /* Sort dl alphabetically. */
1193 qsort_string_vector(dl, dl_count);
1195 dl[dl_count] = NULL;
1200 static void diffdir(char *p1, char *p2)
1202 char **dirlist1, **dirlist2;
1206 /* Check for trailing slashes. */
1207 dp1 = last_char_is(p1, '/');
1210 dp2 = last_char_is(p2, '/');
1214 /* Get directory listings for p1 and p2. */
1215 dirlist1 = get_recursive_dirlist(p1);
1216 dirlist2 = get_recursive_dirlist(p2);
1218 /* If -S was set, find the starting point. */
1220 while (*dirlist1 != NULL && strcmp(*dirlist1, start) < 0)
1222 while (*dirlist2 != NULL && strcmp(*dirlist2, start) < 0)
1224 if ((*dirlist1 == NULL) || (*dirlist2 == NULL))
1225 bb_error_msg(bb_msg_invalid_arg, "NULL", "-S");
1228 /* Now that both dirlist1 and dirlist2 contain sorted directory
1229 * listings, we can start to go through dirlist1. If both listings
1230 * contain the same file, then do a normal diff. Otherwise, behaviour
1231 * is determined by whether the -N flag is set. */
1232 while (*dirlist1 != NULL || *dirlist2 != NULL) {
1235 pos = dp1 == NULL ? 1 : (dp2 == NULL ? -1 : strcmp(dp1, dp2));
1237 do_diff(p1, dp1, p2, dp2);
1240 } else if (pos < 0) {
1241 if (option_mask32 & FLAG_N)
1242 do_diff(p1, dp1, p2, NULL);
1244 print_only(p1, dp1);
1247 if (option_mask32 & FLAG_N)
1248 do_diff(p1, NULL, p2, dp2);
1250 print_only(p2, dp2);
1258 int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1259 int diff_main(int argc ATTRIBUTE_UNUSED, char **argv)
1263 llist_t *L_arg = NULL;
1267 /* exactly 2 params; collect multiple -L <label>; -U N */
1268 opt_complementary = "=2:L::U+";
1269 getopt32(argv, "abdiL:NqrsS:tTU:wu"
1270 "p" /* ignored (for compatibility) */,
1271 &L_arg, &start, &context);
1275 if (label1 && label2)
1278 label1 = L_arg->data;
1279 else { /* then label2 is NULL */
1281 label1 = L_arg->data;
1283 /* we leak L_arg here... */
1284 L_arg = L_arg->link;
1288 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
1289 * driver routine. Both drivers use the contents of stb1 and stb2.
1293 if (LONE_DASH(f1)) {
1294 fstat(STDIN_FILENO, &stb1);
1298 if (LONE_DASH(f2)) {
1299 fstat(STDIN_FILENO, &stb2);
1304 if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
1305 bb_error_msg_and_die("can't compare stdin to a directory");
1307 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1308 #if ENABLE_FEATURE_DIFF_DIR
1312 bb_error_msg_and_die("no support for directory comparison");
1316 if (S_ISDIR(stb1.st_mode)) { /* "diff dir file" */
1317 /* NB: "diff dir dir2/dir3/file" must become
1318 * "diff dir/file dir2/dir3/file" */
1319 char *slash = strrchr(f2, '/');
1320 f1 = concat_path_file(f1, slash ? slash+1 : f2);
1323 if (S_ISDIR(stb2.st_mode)) {
1324 char *slash = strrchr(f1, '/');
1325 f2 = concat_path_file(f2, slash ? slash+1 : f1);
1329 /* diffreg can get non-regular files here,
1330 * they are not both DIRestories */
1331 print_status((gotstdin > 1 ? D_SAME : diffreg(f1, f2, 0)),