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 dbg_error_msg(...) ((void)0)
18 //#define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
20 // #define FSIZE_MAX 32768
22 /* NOINLINEs added to prevent gcc from merging too much into diffreg()
23 * (it bites more than it can (efficiently) chew). */
29 /* Print a header/footer between files */
30 /* D_HEADER = 1, - unused */
31 /* Treat file as empty (/dev/null) */
32 D_EMPTY1 = 2 * ENABLE_FEATURE_DIFF_DIR,
33 D_EMPTY2 = 4 * ENABLE_FEATURE_DIFF_DIR,
37 * Status values for print_status() and diffreg() return values
39 * D_SAME - files are the same
40 * D_DIFFER - files differ
41 * D_BINARY - binary files differ
42 * D_COMMON - subdirectory common to both dirs
43 * D_ONLY - file only exists in one dir
44 * D_ISDIR1 - path1 a dir, path2 a file
45 * D_ISDIR2 - path1 a file, path2 a dir
46 * D_ERROR - error occurred
47 * D_SKIPPED1 - skipped path1 as it is a special file
48 * D_SKIPPED2 - skipped path2 as it is a special file
51 #define D_DIFFER (1 << 0)
52 #define D_BINARY (1 << 1)
53 #define D_COMMON (1 << 2)
54 /*#define D_ONLY (1 << 3) - unused */
55 #define D_ISDIR1 (1 << 4)
56 #define D_ISDIR2 (1 << 5)
57 #define D_ERROR (1 << 6)
58 #define D_SKIPPED1 (1 << 7)
59 #define D_SKIPPED2 (1 << 8)
61 /* Command line options */
62 #define FLAG_a (1 << 0)
63 #define FLAG_b (1 << 1)
64 #define FLAG_d (1 << 2)
65 #define FLAG_i (1 << 3)
66 #define FLAG_L (1 << 4)
67 #define FLAG_N (1 << 5)
68 #define FLAG_q (1 << 6)
69 #define FLAG_r (1 << 7)
70 #define FLAG_s (1 << 8)
71 #define FLAG_S (1 << 9)
72 #define FLAG_t (1 << 10)
73 #define FLAG_T (1 << 11)
74 #define FLAG_U (1 << 12)
75 #define FLAG_w (1 << 13)
90 * The following struct is used to record change information
91 * doing a "context" or "unified" diff. (see routine "change" to
92 * understand the highly mnemonic field names)
95 int a; /* start line in old file */
96 int b; /* end line in old file */
97 int c; /* start line in new file */
98 int d; /* end line in new file */
102 #define g_read_buf bb_common_bufsiz1
106 smallint exit_status;
109 IF_FEATURE_DIFF_DIR(int dl_count;)
110 IF_FEATURE_DIFF_DIR(char **dl;)
114 int *J; /* will be overlaid on class */
116 int pref, suff; /* length of prefix and suffix */
119 int clistlen; /* the length of clist */
120 struct cand *clist; /* merely a free storage pot for candidates */
121 long *ixnew; /* will be overlaid on nfile[1] */
122 long *ixold; /* will be overlaid on klist */
123 struct line *nfile[2];
124 struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
125 struct context_vec *context_vector;
126 char *tempname1, *tempname2;
127 struct stat stb1, stb2;
129 #define G (*ptr_to_globals)
130 #define anychange (G.anychange )
131 #define exit_status (G.exit_status )
132 #define opt_U_context (G.opt_U_context )
133 #define context_idx (G.context_idx )
134 #define dl_count (G.dl_count )
136 #define opt_S_start (G.opt_S_start )
137 #define label1 (G.label1 )
138 #define label2 (G.label2 )
140 #define clen (G.clen )
141 #define pref (G.pref )
142 #define suff (G.suff )
143 #define nlen (G.nlen )
144 #define slen (G.slen )
145 #define clistlen (G.clistlen )
146 #define clist (G.clist )
147 #define ixnew (G.ixnew )
148 #define ixold (G.ixold )
149 #define nfile (G.nfile )
150 #define sfile (G.sfile )
151 #define context_vector (G.context_vector )
152 #define stb1 (G.stb1 )
153 #define stb2 (G.stb2 )
154 #define tempname1 (G.tempname1 )
155 #define tempname2 (G.tempname2 )
156 #define INIT_G() do { \
157 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
159 context_vector = xrealloc_vector(context_vector, 6, 0); \
163 #if ENABLE_FEATURE_DIFF_DIR
164 static void print_only(const char *path, const char *entry)
166 printf("Only in %s: %s\n", path, entry);
171 static void print_status(int val, char *_path1, char *_path2)
173 /*const char *const _entry = entry ? entry : "";*/
174 /*char *const _path1 = entry ? concat_path_file(path1, _entry) : path1;*/
175 /*char *const _path2 = entry ? concat_path_file(path2, _entry) : path2;*/
179 print_only(path1, entry);
183 printf("Common subdirectories: %s and %s\n", _path1, _path2);
186 printf("Binary files %s and %s differ\n", _path1, _path2);
189 if (option_mask32 & FLAG_q)
190 printf("Files %s and %s differ\n", _path1, _path2);
193 if (option_mask32 & FLAG_s)
194 printf("Files %s and %s are identical\n", _path1, _path2);
197 printf("File %s is a %s while file %s is a %s\n",
198 _path1, "directory", _path2, "regular file");
201 printf("File %s is a %s while file %s is a %s\n",
202 _path1, "regular file", _path2, "directory");
205 printf("File %s is not a regular file or directory and was skipped\n",
209 printf("File %s is not a regular file or directory and was skipped\n",
222 /* Read line, return its nonzero hash. Return 0 if EOF.
224 * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
226 static ALWAYS_INLINE int fiddle_sum(int sum, int t)
228 return sum * 127 + t;
230 static int readhash(FILE *fp)
237 if (!(option_mask32 & (FLAG_b | FLAG_w))) {
238 while ((t = getc(fp)) != '\n') {
244 sum = fiddle_sum(sum, t);
261 if (space && !(option_mask32 & FLAG_w)) {
265 sum = fiddle_sum(sum, t);
279 * There is a remote possibility that we end up with a zero sum.
280 * Zero is used as an EOF marker, so return 1 instead.
282 return (sum == 0 ? 1 : sum);
286 /* Our diff implementation is using seek.
287 * When we meet non-seekable file, we must make a temp copy.
289 static char *make_temp(FILE *f, struct stat *sb)
294 if (S_ISREG(sb->st_mode) || S_ISBLK(sb->st_mode))
296 name = xstrdup("/tmp/difXXXXXX");
299 bb_perror_msg_and_die("mkstemp");
300 if (bb_copyfd_eof(fileno(f), fd) < 0) {
303 xfunc_die(); /* error message is printed by bb_copyfd_eof */
307 if (freopen(name, "r+", f) == NULL) {
308 bb_perror_msg("freopen");
316 * Check to see if the given files differ.
317 * Returns 0 if they are the same, 1 if different, and -1 on error.
319 static NOINLINE int files_differ(FILE *f1, FILE *f2)
323 /* Prevent making copies for "/dev/null" (too common) */
324 /* Deal with input from pipes etc */
325 tempname1 = make_temp(f1, &stb1);
326 tempname2 = make_temp(f2, &stb2);
327 if (stb1.st_size != stb2.st_size) {
331 i = fread(g_read_buf, 1, COMMON_BUFSIZE/2, f1);
332 j = fread(g_read_buf + COMMON_BUFSIZE/2, 1, COMMON_BUFSIZE/2, f2);
336 return (ferror(f1) || ferror(f2)) ? -1 : 0;
337 if (memcmp(g_read_buf,
338 g_read_buf + COMMON_BUFSIZE/2, i) != 0)
344 static void prepare(int i, FILE *fp /*, off_t filesize*/)
352 /*sz = (filesize <= FSIZE_MAX ? filesize : FSIZE_MAX) / 25;*/
356 p = xmalloc((sz + 3) * sizeof(p[0]));
358 while ((h = readhash(fp)) != 0) { /* while not EOF */
361 p = xrealloc(p, (sz + 3) * sizeof(p[0]));
370 static void prune(void)
374 for (pref = 0; pref < nlen[0] && pref < nlen[1] &&
375 nfile[0][pref + 1].value == nfile[1][pref + 1].value; pref++)
377 for (suff = 0; suff < nlen[0] - pref && suff < nlen[1] - pref &&
378 nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
381 for (j = 0; j < 2; j++) {
382 sfile[j] = nfile[j] + pref;
383 slen[j] = nlen[j] - pref - suff;
384 for (i = 0; i <= slen[j]; i++)
385 sfile[j][i].serial = i;
390 static void equiv(struct line *a, int n, struct line *b, int m, int *c)
395 while (i <= n && j <= m) {
396 if (a[i].value < b[j].value)
398 else if (a[i].value == b[j].value)
409 while (b[j + 1].value == b[j].value) {
418 static int isqrt(int n)
430 } while ((x - y) > 1 || (x - y) < -1);
436 static int newcand(int x, int y, int pred)
440 if (clen == clistlen) {
441 clistlen = clistlen * 11 / 10;
442 clist = xrealloc(clist, clistlen * sizeof(struct cand));
452 static int search(int *c, int k, int y)
456 if (clist[c[k]].y < y) /* quick look for typical case */
476 static int stone(int *a, int n, int *b, int *c)
482 #if ENABLE_FEATURE_DIFF_MINIMAL
483 const unsigned bound =
484 (option_mask32 & FLAG_d) ? UINT_MAX : MAX(256, isq);
486 const unsigned bound = MAX(256, isq);
490 c[0] = newcand(0, 0, 0);
491 for (i = 1; i <= n; i++) {
500 if (y <= clist[oldc].y)
506 if (clist[c[l]].y <= y)
509 c[l] = newcand(i, y, oldc);
514 c[l] = newcand(i, y, oldc);
518 } while ((y = b[++j]) > 0 && numtries < bound);
524 static void unravel(int p)
529 for (i = 0; i <= nlen[0]; i++)
530 J[i] = i <= pref ? i : i > nlen[0] - suff ? i + nlen[1] - nlen[0] : 0;
531 for (q = clist + p; q->y != 0; q = clist + q->pred)
532 J[q->x + pref] = q->y + pref;
536 static void unsort(struct line *f, int l, int *b)
540 a = xmalloc((l + 1) * sizeof(int));
541 for (i = 1; i <= l; i++)
542 a[f[i].serial] = f[i].value;
543 for (i = 1; i <= l; i++)
549 static int skipline(FILE *f)
553 for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
560 * Check does double duty:
561 * 1. ferret out any fortuitous correspondences due
562 * to confounding by hashing (which result in "jackpot")
563 * 2. collect random access indexes to the two files
565 static NOINLINE void check(FILE *f1, FILE *f2)
567 int i, j, jackpot, c, d;
573 ixold[0] = ixnew[0] = 0;
576 for (i = 1; i <= nlen[0]; i++) {
578 ixold[i] = ctold += skipline(f1);
582 ixnew[j] = ctnew += skipline(f2);
585 if (option_mask32 & (FLAG_b | FLAG_w | FLAG_i)) {
590 * GNU diff ignores a missing newline
591 * in one file if bflag || wflag.
593 if ((option_mask32 & (FLAG_b | FLAG_w))
594 && ((c == EOF && d == '\n') || (c == '\n' && d == EOF))
600 if ((option_mask32 & FLAG_b) && isspace(c) && isspace(d)) {
606 } while (isspace(c));
612 } while (isspace(d));
613 } else if (option_mask32 & FLAG_w) {
614 while (isspace(c) && c != '\n') {
618 while (isspace(d) && d != '\n') {
626 if (c != '\n' && c != EOF)
627 ctold += skipline(f1);
628 if (d != '\n' && c != EOF)
629 ctnew += skipline(f2);
632 if (c == '\n' || c == EOF)
643 if (c != '\n' && c != EOF)
644 ctold += skipline(f1);
645 /* was buggy? "if (d != '\n' && c != EOF)" */
646 if (d != '\n' && d != EOF)
647 ctnew += skipline(f2);
650 if (c == '\n' || c == EOF)
658 for (; j <= nlen[1]; j++)
659 ixnew[j] = ctnew += skipline(f2);
663 /* shellsort CACM #201 */
664 static void sort(struct line *a, int n)
666 struct line *ai, *aim, w;
671 for (j = 1; j <= n; j *= 2)
673 for (m /= 2; m != 0; m /= 2) {
675 for (j = 1; j <= k; j++) {
676 for (ai = &a[j]; ai > a; ai -= m) {
679 break; /* wraparound */
680 if (aim->value > ai[0].value
681 || (aim->value == ai[0].value && aim->serial > ai[0].serial)
685 w.value = ai[0].value;
686 ai[0].value = aim->value;
687 aim->value = w.value;
688 w.serial = ai[0].serial;
689 ai[0].serial = aim->serial;
690 aim->serial = w.serial;
697 static void uni_range(int a, int b)
700 printf("%d,%d", a, b - a + 1);
708 static void fetch(long *f, int a, int b, FILE *lb, int ch)
710 int i, j, c, lastc, col, nc;
714 for (i = a; i <= b; i++) {
715 fseek(lb, f[i - 1], SEEK_SET);
716 nc = f[i] - f[i - 1];
719 if (option_mask32 & FLAG_T)
723 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
726 printf("\n\\ No newline at end of file\n");
729 if (c == '\t' && (option_mask32 & FLAG_t)) {
742 #if ENABLE_FEATURE_DIFF_BINARY
743 static int asciifile(FILE *f)
747 if (option_mask32 & FLAG_a)
750 cnt = fread(g_read_buf, 1, COMMON_BUFSIZE, f);
751 for (i = 0; i < cnt; i++) {
752 if (!isprint_asciionly(g_read_buf[i])
753 && !isspace(g_read_buf[i])
761 #define asciifile(f) 1
765 /* dump accumulated "unified" diff changes */
766 static void dump_unified_vec(FILE *f1, FILE *f2)
768 struct context_vec *cvp = context_vector;
769 int lowa, upb, lowc, upd;
776 dbg_error_msg("dumping %d context_vecs", context_idx+1);
779 lowa = MAX(1, cvp->a - opt_U_context);
780 upb = MIN(nlen[0], context_vector[context_idx].b + opt_U_context);
781 lowc = MAX(1, cvp->c - opt_U_context);
782 upd = MIN(nlen[1], context_vector[context_idx].d + opt_U_context);
785 uni_range(lowa, upb);
787 uni_range(lowc, upd);
791 * Output changes in "unified" diff format--the old and new lines
792 * are printed together.
794 for (; cvp <= &context_vector[context_idx]; cvp++) {
801 * c: both new and old changes
802 * d: only changes in the old file
803 * a: only changes in the new file
805 if (a <= b && c <= d)
808 ch = (a <= b) ? 'd' : 'a';
813 fetch(ixold, lowa, a - 1, f1, ' ');
814 fetch(ixold, a, b, f1, '-');
815 fetch(ixnew, c, d, f2, '+');
818 fetch(ixold, lowa, a - 1, f1, ' ');
819 fetch(ixold, a, b, f1, '-');
822 fetch(ixnew, lowc, c - 1, f2, ' ');
823 fetch(ixnew, c, d, f2, '+');
827 if (ch == 'c' || ch == 'd') {
828 fetch(ixold, lowa, a - 1, f1, ' ');
829 fetch(ixold, a, b, f1, '-');
832 fetch(ixnew, lowc, c - 1, f2, ' ');
833 if (ch == 'c' || ch == 'a')
834 fetch(ixnew, c, d, f2, '+');
839 fetch(ixnew, d + 1, upd, f2, ' ');
845 static void print_header(const char *file1, const char *file2)
848 printf("--- %s\n", label1);
850 printf("--- %s\t%s", file1, ctime(&stb1.st_mtime));
852 printf("+++ %s\n", label2);
854 printf("+++ %s\t%s", file2, ctime(&stb2.st_mtime));
859 * Indicate that there is a difference between lines a and b of the from file
860 * to get to lines c to d of the to file. If a is greater than b then there
861 * are no lines in the from file involved and this means that there were
862 * lines appended (beginning at b). If c is greater than d then there are
863 * lines missing from the to file.
865 static void change(const char *file1, FILE *f1, const char *file2, FILE *f2,
866 int a, int b, int c, int d)
868 if ((a > b && c > d) || (option_mask32 & FLAG_q)) {
869 //compat BUG: "diff -ub F1 F2" will output nothing, but will exit 1
870 //if F1 and F2 differ only in whitespace. "standard" diff exits 0.
871 //This is the place where this erroneous exitcode is set:
872 dbg_error_msg("%d: abcd:%d,%d,%d,%d, anychange=1", __LINE__, a,b,c,d);
877 if (anychange == 0) {
879 * Print the context/unidiff header first time through.
881 print_header(file1, file2);
882 } else if (a > context_vector[context_idx].b + (2 * opt_U_context) + 1
883 && c > context_vector[context_idx].d + (2 * opt_U_context) + 1
886 * If this change is more than 'context' lines from the
887 * previous change, dump the record and reset it.
889 // dump_unified_vec() seeks!
890 dump_unified_vec(f1, f2);
893 context_vector = xrealloc_vector(context_vector, 6, context_idx);
894 context_vector[context_idx].a = a;
895 context_vector[context_idx].b = b;
896 context_vector[context_idx].c = c;
897 context_vector[context_idx].d = d;
898 dbg_error_msg("new context_vec[%d]:%d,%d,%d,%d", context_idx, a,b,c,d);
903 static void output(const char *file1, FILE *f1, const char *file2, FILE *f2)
905 /* Note that j0 and j1 can't be used as they are defined in math.h.
906 * This also allows the rather amusing variable 'j00'... */
907 int m, i0, i1, j00, j01;
913 J[m + 1] = nlen[1] + 1;
914 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
915 while (i0 <= m && J[i0] == J[i0 - 1] + 1)
919 while (i1 < m && J[i1 + 1] == 0)
924 change(file1, f1, file2, f2, i0, i1, j00, j01);
928 change(file1, f1, file2, f2, 1, 0, 1, nlen[1]);
930 if (anychange != 0 && !(option_mask32 & FLAG_q)) {
931 // dump_unified_vec() seeks!
932 dump_unified_vec(f1, f2);
937 * The following code uses an algorithm due to Harold Stone,
938 * which finds a pair of longest identical subsequences in
941 * The major goal is to generate the match vector J.
942 * J[i] is the index of the line in file1 corresponding
943 * to line i in file0. J[i] = 0 if there is no
944 * such line in file1.
946 * Lines are hashed so as to work in core. All potential
947 * matches are located by sorting the lines of each file
948 * on the hash (called "value"). In particular, this
949 * collects the equivalence classes in file1 together.
950 * Subroutine equiv replaces the value of each line in
951 * file0 by the index of the first element of its
952 * matching equivalence in (the reordered) file1.
953 * To save space equiv squeezes file1 into a single
954 * array member in which the equivalence classes
955 * are simply concatenated, except that their first
956 * members are flagged by changing sign.
958 * Next the indices that point into member are unsorted into
959 * array class according to the original order of file0.
961 * The cleverness lies in routine stone. This marches
962 * through the lines of file0, developing a vector klist
963 * of "k-candidates". At step i a k-candidate is a matched
964 * pair of lines x,y (x in file0, y in file1) such that
965 * there is a common subsequence of length k
966 * between the first i lines of file0 and the first y
967 * lines of file1, but there is no such subsequence for
968 * any smaller y. x is the earliest possible mate to y
969 * that occurs in such a subsequence.
971 * Whenever any of the members of the equivalence class of
972 * lines in file1 matable to a line in file0 has serial number
973 * less than the y of some k-candidate, that k-candidate
974 * with the smallest such y is replaced. The new
975 * k-candidate is chained (via pred) to the current
976 * k-1 candidate so that the actual subsequence can
977 * be recovered. When a member has serial number greater
978 * that the y of all k-candidates, the klist is extended.
979 * At the end, the longest subsequence is pulled out
980 * and placed in the array J by unravel
982 * With J in hand, the matches there recorded are
983 * checked against reality to assure that no spurious
984 * matches have crept in due to hashing. If they have,
985 * they are broken, and "jackpot" is recorded--a harmless
986 * matter except that a true match for a spuriously
987 * mated line may now be unnecessarily reported as a change.
989 * Much of the complexity of the program comes simply
990 * from trying to minimize core utilization and
991 * maximize the range of doable problems by dynamically
992 * allocating what is needed and reusing what is not.
993 * The core requirements for problems larger than somewhat
994 * are (in words) 2*length(file0) + length(file1) +
995 * 3*(number of k-candidates installed), typically about
996 * 6n words for files of length n.
998 /* NB: files can be not REGular. The only sure thing that they
999 * are not both DIRectories. */
1000 static unsigned diffreg(const char *file1, const char *file2, int flags)
1002 int *member; /* will be overlaid on nfile[1] */
1003 int *class; /* will be overlaid on nfile[0] */
1004 int *klist; /* will be overlaid on nfile[0] after class */
1012 tempname1 = tempname2 = NULL;
1014 /* Is any of them a directory? Then it's simple */
1015 if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
1016 return (S_ISDIR(stb1.st_mode) ? D_ISDIR1 : D_ISDIR2);
1018 /* None of them are directories */
1021 if (flags & D_EMPTY1)
1022 /* can't be stdin, but xfopen_stdin() is smaller code */
1023 file1 = bb_dev_null;
1024 f1 = xfopen_stdin(file1);
1025 if (flags & D_EMPTY2)
1026 file2 = bb_dev_null;
1027 f2 = xfopen_stdin(file2);
1029 /* NB: if D_EMPTY1/2 is set, other file is always a regular file,
1030 * not pipe/fifo/chardev/etc - D_EMPTY is used by "diff -r" only,
1031 * and it never diffs non-ordinary files in subdirs. */
1032 if (!(flags & (D_EMPTY1 | D_EMPTY2))) {
1033 /* Quick check whether they are different */
1034 /* NB: copies non-REG files to tempfiles and fills tempname1/2 */
1035 i = files_differ(f1, f2);
1036 if (i != 1) { /* not different? */
1037 if (i != 0) /* error? */
1043 if (!asciifile(f1) || !asciifile(f2)) {
1050 prepare(0, f1 /*, stb1.st_size*/);
1051 prepare(1, f2 /*, stb2.st_size*/);
1053 sort(sfile[0], slen[0]);
1054 sort(sfile[1], slen[1]);
1056 member = (int *) nfile[1];
1057 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
1058 //TODO: xrealloc_vector?
1059 member = xrealloc(member, (slen[1] + 2) * sizeof(int));
1061 class = (int *) nfile[0];
1062 unsort(sfile[0], slen[0], class);
1063 class = xrealloc(class, (slen[0] + 2) * sizeof(int));
1065 klist = xmalloc((slen[0] + 2) * sizeof(int));
1068 clist = xmalloc(clistlen * sizeof(struct cand));
1069 i = stone(class, slen[0], member, klist);
1073 J = xrealloc(J, (nlen[0] + 2) * sizeof(int));
1078 ixold = xrealloc(ixold, (nlen[0] + 2) * sizeof(long));
1079 ixnew = xrealloc(ixnew, (nlen[1] + 2) * sizeof(long));
1083 output(file1, f1, file2, f2);
1088 dbg_error_msg("exit_status|=1 = %d", exit_status);
1092 fclose_if_not_stdin(f1);
1093 fclose_if_not_stdin(f2);
1106 #if ENABLE_FEATURE_DIFF_DIR
1107 static void do_diff(char *dir1, char *path1, char *dir2, char *path2)
1109 int flags = 0; /*D_HEADER;*/
1111 char *fullpath1 = NULL; /* if -N */
1112 char *fullpath2 = NULL;
1115 fullpath1 = concat_path_file(dir1, path1);
1117 fullpath2 = concat_path_file(dir2, path2);
1119 if (!fullpath1 || stat(fullpath1, &stb1) != 0) {
1121 memset(&stb1, 0, sizeof(stb1));
1124 fullpath1 = concat_path_file(dir1, path2);
1127 if (!fullpath2 || stat(fullpath2, &stb2) != 0) {
1129 memset(&stb2, 0, sizeof(stb2));
1130 stb2.st_mode = stb1.st_mode;
1133 fullpath2 = concat_path_file(dir2, path1);
1137 if (stb1.st_mode == 0)
1138 stb1.st_mode = stb2.st_mode;
1140 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1141 printf("Common subdirectories: %s and %s\n", fullpath1, fullpath2);
1145 if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode))
1147 else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode))
1150 /* Both files are either REGular or DIRectories */
1151 val = diffreg(fullpath1, fullpath2, flags);
1154 print_status(val, fullpath1, fullpath2 /*, NULL*/);
1162 #if ENABLE_FEATURE_DIFF_DIR
1163 /* This function adds a filename to dl, the directory listing. */
1164 static int FAST_FUNC add_to_dirlist(const char *filename,
1165 struct stat *sb UNUSED_PARAM,
1167 int depth UNUSED_PARAM)
1169 dl = xrealloc_vector(dl, 5, dl_count);
1170 dl[dl_count] = xstrdup(filename + (int)(ptrdiff_t)userdata);
1176 /* This returns a sorted directory listing. */
1177 static char **get_recursive_dirlist(char *path)
1180 dl = xzalloc(sizeof(dl[0]));
1182 /* We need to trim root directory prefix.
1183 * Using void *userdata to specify its length,
1184 * add_to_dirlist will remove it. */
1185 if (option_mask32 & FLAG_r) {
1186 recursive_action(path, ACTION_RECURSE|ACTION_FOLLOWLINKS,
1187 add_to_dirlist, /* file_action */
1188 NULL, /* dir_action */
1189 (void*)(ptrdiff_t)(strlen(path) + 1),
1195 dp = warn_opendir(path);
1196 while ((ep = readdir(dp))) {
1197 if (!strcmp(ep->d_name, "..") || LONE_CHAR(ep->d_name, '.'))
1199 add_to_dirlist(ep->d_name, NULL, (void*)(int)0, 0);
1204 /* Sort dl alphabetically. */
1205 qsort_string_vector(dl, dl_count);
1207 dl[dl_count] = NULL;
1212 static void diffdir(char *p1, char *p2)
1214 char **dirlist1, **dirlist2;
1218 /* Check for trailing slashes. */
1219 dp1 = last_char_is(p1, '/');
1222 dp2 = last_char_is(p2, '/');
1226 /* Get directory listings for p1 and p2. */
1227 dirlist1 = get_recursive_dirlist(p1);
1228 dirlist2 = get_recursive_dirlist(p2);
1230 /* If -S was set, find the starting point. */
1232 while (*dirlist1 != NULL && strcmp(*dirlist1, opt_S_start) < 0)
1234 while (*dirlist2 != NULL && strcmp(*dirlist2, opt_S_start) < 0)
1236 if ((*dirlist1 == NULL) || (*dirlist2 == NULL))
1237 bb_error_msg(bb_msg_invalid_arg, "NULL", "-S");
1240 /* Now that both dirlist1 and dirlist2 contain sorted directory
1241 * listings, we can start to go through dirlist1. If both listings
1242 * contain the same file, then do a normal diff. Otherwise, behaviour
1243 * is determined by whether the -N flag is set. */
1244 while (*dirlist1 != NULL || *dirlist2 != NULL) {
1247 pos = dp1 == NULL ? 1 : (dp2 == NULL ? -1 : strcmp(dp1, dp2));
1249 do_diff(p1, dp1, p2, dp2);
1252 } else if (pos < 0) {
1253 if (option_mask32 & FLAG_N)
1254 do_diff(p1, dp1, p2, NULL);
1256 print_only(p1, dp1);
1259 if (option_mask32 & FLAG_N)
1260 do_diff(p1, NULL, p2, dp2);
1262 print_only(p2, dp2);
1270 int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1271 int diff_main(int argc UNUSED_PARAM, char **argv)
1275 llist_t *L_arg = NULL;
1279 /* exactly 2 params; collect multiple -L <label>; -U N */
1280 opt_complementary = "=2:L::U+";
1281 getopt32(argv, "abdiL:NqrsS:tTU:wu"
1282 "p" /* ignored (for compatibility) */,
1283 &L_arg, &opt_S_start, &opt_U_context);
1287 if (label1 && label2)
1289 if (label1) /* then label2 is NULL */
1291 label1 = llist_pop(&L_arg);
1295 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
1296 * driver routine. Both drivers use the contents of stb1 and stb2.
1300 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
1301 xfunc_error_retval = 2;
1302 if (LONE_DASH(f1)) {
1303 fstat(STDIN_FILENO, &stb1);
1307 if (LONE_DASH(f2)) {
1308 fstat(STDIN_FILENO, &stb2);
1312 xfunc_error_retval = 1;
1314 if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
1315 bb_error_msg_and_die("can't compare stdin to a directory");
1317 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1318 #if ENABLE_FEATURE_DIFF_DIR
1322 bb_error_msg_and_die("no support for directory comparison");
1326 if (S_ISDIR(stb1.st_mode)) { /* "diff dir file" */
1327 /* NB: "diff dir dir2/dir3/file" must become
1328 * "diff dir/file dir2/dir3/file" */
1329 char *slash = strrchr(f2, '/');
1330 f1 = concat_path_file(f1, slash ? slash + 1 : f2);
1333 if (S_ISDIR(stb2.st_mode)) {
1334 char *slash = strrchr(f1, '/');
1335 f2 = concat_path_file(f2, slash ? slash + 1 : f1);
1339 /* diffreg can get non-regular files here,
1340 * they are not both DIRestories */
1341 print_status((gotstdin > 1 ? D_SAME : diffreg(f1, f2, 0)),