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>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
11 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
14 * use, copy, modify, and distribute this software for any
15 * purpose with or without fee is hereby granted, provided that the above
16 * copyright notice and this permission notice appear in all copies.
18 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
19 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
21 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
22 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
23 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
24 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 * Sponsored in part by the Defense Advanced Research Projects
27 * Agency (DARPA) and Air Force Research Laboratory, Air Force
28 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
32 #include <sys/types.h>
33 #include <sys/param.h>
50 #define FSIZE_MAX 32768
55 #define D_HEADER 1 /* Print a header/footer between files */
56 #define D_EMPTY1 2 /* Treat first file as empty (/dev/null) */
57 #define D_EMPTY2 4 /* Treat second file as empty (/dev/null) */
60 * Status values for print_status() and diffreg() return values
62 * D_SAME - files are the same
63 * D_DIFFER - files differ
64 * D_BINARY - binary files differ
65 * D_COMMON - subdirectory common to both dirs
66 * D_ONLY - file only exists in one dir
67 * D_MISMATCH1 - path1 a dir, path2 a file
68 * D_MISMATCH2 - path1 a file, path2 a dir
69 * D_ERROR - error occurred
70 * D_SKIPPED1 - skipped path1 as it is a special file
71 * D_SKIPPED2 - skipped path2 as it is a special file
75 #define D_DIFFER (1<<0)
76 #define D_BINARY (1<<1)
77 #define D_COMMON (1<<2)
79 #define D_MISMATCH1 (1<<4)
80 #define D_MISMATCH2 (1<<5)
81 #define D_ERROR (1<<6)
82 #define D_SKIPPED1 (1<<7)
83 #define D_SKIPPED2 (1<<8)
85 /* Command line options */
86 static unsigned long cmd_flags;
97 #define FLAG_T (1<<10)
98 #define FLAG_U (1<<11)
99 #define FLAG_w (1<<12)
102 char *start, *label[2];
103 struct stat stb1, stb2;
119 * The following struct is used to record change information
120 * doing a "context" or "unified" diff. (see routine "change" to
121 * understand the highly mnemonic field names)
124 int a; /* start line in old file */
125 int b; /* end line in old file */
126 int c; /* start line in new file */
127 int d; /* end line in new file */
130 static int *J; /* will be overlaid on class */
131 static int *class; /* will be overlaid on file[0] */
132 static int *klist; /* will be overlaid on file[0] after class */
133 static int *member; /* will be overlaid on file[1] */
136 static int pref, suff; /* length of prefix and suffix */
138 static int anychange;
139 static long *ixnew; /* will be overlaid on file[1] */
140 static long *ixold; /* will be overlaid on klist */
141 static struct cand *clist; /* merely a free storage pot for candidates */
142 static int clistlen; /* the length of clist */
143 static struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
144 static struct context_vec *context_vec_start;
145 static struct context_vec *context_vec_end;
146 static struct context_vec *context_vec_ptr;
148 static void print_only(const char *path, size_t dirlen, const char *entry)
152 printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
155 static void print_status(int val, char *path1, char *path2, char *entry)
157 const char * const _entry = entry ? entry : "";
158 char *_path1 = entry ? concat_path_file(path1, _entry) : path1;
159 char *_path2 = entry ? concat_path_file(path2, _entry) : path2;
162 print_only(path1, strlen(path1), entry);
165 printf("Common subdirectories: %s and %s\n", _path1, _path2);
168 printf("Binary files %s and %s differ\n", _path1, _path2);
171 if (cmd_flags & FLAG_q)
172 printf("Files %s and %s differ\n", _path1, _path2);
175 if (cmd_flags & FLAG_s)
176 printf("Files %s and %s are identical\n", _path1, _path2);
179 printf("File %s is a directory while file %s is a regular file\n",
183 printf("File %s is a regular file while file %s is a directory\n",
187 printf("File %s is not a regular file or directory and was skipped\n",
191 printf("File %s is not a regular file or directory and was skipped\n",
202 * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
204 static int readhash(FILE *f)
211 if (!(cmd_flags & FLAG_b) && !(cmd_flags & FLAG_w)) {
213 for (i = 0; (t = getc(f)) != '\n'; i++) {
222 for (i = 0; (t = getc(f)) != '\n'; i++) {
232 switch (t = getc(f)) {
241 if (space && !(cmd_flags & FLAG_w)) {
259 * There is a remote possibility that we end up with a zero sum.
260 * Zero is used as an EOF marker, so return 1 instead.
262 return (sum == 0 ? 1 : sum);
268 * Check to see if the given files differ.
269 * Returns 0 if they are the same, 1 if different, and -1 on error.
271 static int files_differ(FILE *f1, FILE *f2, int flags)
273 char buf1[BUFSIZ], buf2[BUFSIZ];
276 if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
277 (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
280 i = fread(buf1, 1, sizeof(buf1), f1);
281 j = fread(buf2, 1, sizeof(buf2), f2);
284 if (i == 0 && j == 0) {
285 if (ferror(f1) || ferror(f2))
289 if (memcmp(buf1, buf2, i) != 0)
294 static void prepare(int i, FILE *fd, off_t filesize)
302 sz = (filesize <= FSIZE_MAX ? filesize : FSIZE_MAX) / 25;
306 p = xmalloc((sz + 3) * sizeof(struct line));
307 for (j = 0; (h = readhash(fd));) {
310 p = xrealloc(p, (sz + 3) * sizeof(struct line));
318 static void prune(void)
322 for (pref = 0; pref < len[0] && pref < len[1] &&
323 file[0][pref + 1].value == file[1][pref + 1].value;
326 for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
327 file[0][len[0] - suff].value == file[1][len[1] - suff].value;
330 for (j = 0; j < 2; j++) {
331 sfile[j] = file[j] + pref;
332 slen[j] = len[j] - pref - suff;
333 for (i = 0; i <= slen[j]; i++)
334 sfile[j][i].serial = i;
338 static void equiv(struct line *a, int n, struct line *b, int m, int *c)
343 while (i <= n && j <= m) {
344 if (a[i].value < b[j].value)
346 else if (a[i].value == b[j].value)
357 while (b[j + 1].value == b[j].value) {
365 static int isqrt(int n) {
367 if (n == 0) return(0);
374 } while ((x - y) > 1 || (x - y) < -1);
380 static int newcand(int x, int y, int pred)
384 if (clen == clistlen) {
385 clistlen = clistlen * 11 / 10;
386 clist = xrealloc(clist, clistlen * sizeof(struct cand));
396 static int search(int *c, int k, int y)
400 if (clist[c[k]].y < y) /* quick look for typical case */
420 static int stone(int *a, int n, int *b, int *c)
425 #ifdef CONFIG_FEATURE_DIFF_MINIMAL
426 const u_int bound = (cmd_flags & FLAG_d) ? UINT_MAX : MAX(256, isqrt(n));
428 const u_int bound = MAX(256, isqrt(n));
431 c[0] = newcand(0, 0, 0);
432 for (i = 1; i <= n; i++) {
441 if (y <= clist[oldc].y)
447 if (clist[c[l]].y <= y)
450 c[l] = newcand(i, y, oldc);
455 c[l] = newcand(i, y, oldc);
459 } while ((y = b[++j]) > 0 && numtries < bound);
464 static void unravel(int p)
469 for (i = 0; i <= len[0]; i++)
470 J[i] = i <= pref ? i :
471 i > len[0] - suff ? i + len[1] - len[0] : 0;
472 for (q = clist + p; q->y != 0; q = clist + q->pred)
473 J[q->x + pref] = q->y + pref;
477 static void unsort(struct line *f, int l, int *b)
481 a = xmalloc((l + 1) * sizeof(int));
482 for (i = 1; i <= l; i++)
483 a[f[i].serial] = f[i].value;
484 for (i = 1; i <= l; i++)
489 static int skipline(FILE *f)
493 for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
500 * Check does double duty:
501 * 1. ferret out any fortuitous correspondences due
502 * to confounding by hashing (which result in "jackpot")
503 * 2. collect random access indexes to the two files
505 static void check(FILE *f1, FILE *f2)
507 int i, j, jackpot, c, d;
513 ixold[0] = ixnew[0] = 0;
516 for (i = 1; i <= len[0]; i++) {
518 ixold[i] = ctold += skipline(f1);
522 ixnew[j] = ctnew += skipline(f2);
525 if ((cmd_flags & FLAG_b) || (cmd_flags & FLAG_w) || (cmd_flags & FLAG_i)) {
530 * GNU diff ignores a missing newline
531 * in one file if bflag || wflag.
533 if (((cmd_flags & FLAG_b) || (cmd_flags & FLAG_w)) &&
534 ((c == EOF && d == '\n') ||
535 (c == '\n' && d == EOF))) {
540 if ((cmd_flags & FLAG_b) && isspace(c) && isspace(d)) {
545 } while (isspace(c = getc(f1)));
550 } while (isspace(d = getc(f2)));
551 } else if (cmd_flags & FLAG_w) {
552 while (isspace(c) && c != '\n') {
556 while (isspace(d) && d != '\n') {
564 if (c != '\n' && c != EOF)
565 ctold += skipline(f1);
566 if (d != '\n' && c != EOF)
567 ctnew += skipline(f2);
570 if (c == '\n' || c == EOF)
577 if ((c = getc(f1)) != (d = getc(f2))) {
579 if (c != '\n' && c != EOF)
580 ctold += skipline(f1);
581 if (d != '\n' && c != EOF)
582 ctnew += skipline(f2);
585 if (c == '\n' || c == EOF)
593 for (; j <= len[1]; j++)
594 ixnew[j] = ctnew += skipline(f2);
597 /* shellsort CACM #201 */
598 static void sort(struct line *a, int n)
600 struct line *ai, *aim, w;
605 for (j = 1; j <= n; j *= 2)
607 for (m /= 2; m != 0; m /= 2) {
609 for (j = 1; j <= k; j++) {
610 for (ai = &a[j]; ai > a; ai -= m) {
613 break; /* wraparound */
614 if (aim->value > ai[0].value ||
615 (aim->value == ai[0].value &&
616 aim->serial > ai[0].serial))
618 w.value = ai[0].value;
619 ai[0].value = aim->value;
620 aim->value = w.value;
621 w.serial = ai[0].serial;
622 ai[0].serial = aim->serial;
623 aim->serial = w.serial;
630 static void uni_range(int a, int b)
633 printf("%d,%d", a, b - a + 1);
640 static int fetch(long *f, int a, int b, FILE *lb, int ch)
642 int i, j, c, lastc, col, nc;
646 for (i = a; i <= b; i++) {
647 fseek(lb, f[i - 1], SEEK_SET);
648 nc = f[i] - f[i - 1];
651 if (cmd_flags & FLAG_T)
655 for (j = 0, lastc = '\0'; j < nc; j++, lastc = c) {
656 if ((c = getc(lb)) == EOF) {
657 puts("\n\\ No newline at end of file");
660 if (c == '\t' && (cmd_flags & FLAG_t)) {
673 static int asciifile(FILE *f)
675 #ifdef CONFIG_FEATURE_DIFF_BINARY
676 unsigned char buf[BUFSIZ];
680 if ((cmd_flags & FLAG_a) || f == NULL)
683 #ifdef CONFIG_FEATURE_DIFF_BINARY
685 cnt = fread(buf, 1, sizeof(buf), f);
686 for (i = 0; i < cnt; i++)
687 if (!isprint(buf[i]) && !isspace(buf[i]))
693 /* dump accumulated "unified" diff changes */
694 static void dump_unified_vec(FILE *f1, FILE *f2)
696 struct context_vec *cvp = context_vec_start;
697 int lowa, upb, lowc, upd;
701 if (context_vec_start > context_vec_ptr)
705 lowa = MAX(1, cvp->a - context);
706 upb = MIN(len[0], context_vec_ptr->b + context);
707 lowc = MAX(1, cvp->c - context);
708 upd = MIN(len[1], context_vec_ptr->d + context);
710 fputs("@@ -", stdout);
711 uni_range(lowa, upb);
713 uni_range(lowc, upd);
714 fputs(" @@", stdout);
718 * Output changes in "unified" diff format--the old and new lines
719 * are printed together.
721 for (; cvp <= context_vec_ptr; cvp++) {
728 * c: both new and old changes
729 * d: only changes in the old file
730 * a: only changes in the new file
732 if (a <= b && c <= d)
735 ch = (a <= b) ? 'd' : 'a';
739 fetch(ixold, lowa, a - 1, f1, ' ');
740 fetch(ixold, a, b, f1, '-');
741 fetch(ixnew, c, d, f2, '+');
744 fetch(ixold, lowa, a - 1, f1, ' ');
745 fetch(ixold, a, b, f1, '-');
748 fetch(ixnew, lowc, c - 1, f2, ' ');
749 fetch(ixnew, c, d, f2, '+');
753 if (ch == 'c' || ch == 'd') {
754 fetch(ixold, lowa, a - 1, f1, ' ');
755 fetch(ixold, a, b, f1, '-');
758 fetch(ixnew, lowc, c - 1, f2, ' ');
759 if (ch == 'c' || ch == 'a')
760 fetch(ixnew, c, d, f2, '+');
765 fetch(ixnew, d + 1, upd, f2, ' ');
767 context_vec_ptr = context_vec_start - 1;
771 static void print_header(const char *file1, const char *file2)
773 if (label[0] != NULL)
774 printf("%s %s\n", "---",
777 printf("%s %s\t%s", "---",
778 file1, ctime(&stb1.st_mtime));
779 if (label[1] != NULL)
780 printf("%s %s\n", "+++",
783 printf("%s %s\t%s", "+++",
784 file2, ctime(&stb2.st_mtime));
790 * Indicate that there is a difference between lines a and b of the from file
791 * to get to lines c to d of the to file. If a is greater then b then there
792 * are no lines in the from file involved and this means that there were
793 * lines appended (beginning at b). If c is greater than d then there are
794 * lines missing from the to file.
796 static void change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d)
798 static size_t max_context = 64;
800 if (a > b && c > d) return;
801 if (cmd_flags & FLAG_q) return;
804 * Allocate change records as needed.
806 if (context_vec_ptr == context_vec_end - 1) {
807 ptrdiff_t offset = context_vec_ptr - context_vec_start;
809 context_vec_start = xrealloc(context_vec_start,
810 max_context * sizeof(struct context_vec));
811 context_vec_end = context_vec_start + max_context;
812 context_vec_ptr = context_vec_start + offset;
814 if (anychange == 0) {
816 * Print the context/unidiff header first time through.
818 print_header(file1, file2);
820 } else if (a > context_vec_ptr->b + (2 * context) + 1 &&
821 c > context_vec_ptr->d + (2 * context) + 1) {
823 * If this change is more than 'context' lines from the
824 * previous change, dump the record and reset it.
826 dump_unified_vec(f1, f2);
829 context_vec_ptr->a = a;
830 context_vec_ptr->b = b;
831 context_vec_ptr->c = c;
832 context_vec_ptr->d = d;
838 static void output(char *file1, FILE *f1, char *file2, FILE *f2)
840 int m, i0, i1, j0, j1;
846 J[m + 1] = len[1] + 1;
847 for (i0 = 1; i0 <= m; i0 = i1 + 1) {
848 while (i0 <= m && J[i0] == J[i0 - 1] + 1)
852 while (i1 < m && J[i1 + 1] == 0)
856 change(file1, f1, file2, f2, i0, i1, j0, j1);
859 change(file1, f1, file2, f2, 1, 0, 1, len[1]);
861 if (anychange != 0) {
862 dump_unified_vec(f1, f2);
867 * The following code uses an algorithm due to Harold Stone,
868 * which finds a pair of longest identical subsequences in
871 * The major goal is to generate the match vector J.
872 * J[i] is the index of the line in file1 corresponding
873 * to line i file0. J[i] = 0 if there is no
874 * such line in file1.
876 * Lines are hashed so as to work in core. All potential
877 * matches are located by sorting the lines of each file
878 * on the hash (called ``value''). In particular, this
879 * collects the equivalence classes in file1 together.
880 * Subroutine equiv replaces the value of each line in
881 * file0 by the index of the first element of its
882 * matching equivalence in (the reordered) file1.
883 * To save space equiv squeezes file1 into a single
884 * array member in which the equivalence classes
885 * are simply concatenated, except that their first
886 * members are flagged by changing sign.
888 * Next the indices that point into member are unsorted into
889 * array class according to the original order of file0.
891 * The cleverness lies in routine stone. This marches
892 * through the lines of file0, developing a vector klist
893 * of "k-candidates". At step i a k-candidate is a matched
894 * pair of lines x,y (x in file0 y in file1) such that
895 * there is a common subsequence of length k
896 * between the first i lines of file0 and the first y
897 * lines of file1, but there is no such subsequence for
898 * any smaller y. x is the earliest possible mate to y
899 * that occurs in such a subsequence.
901 * Whenever any of the members of the equivalence class of
902 * lines in file1 matable to a line in file0 has serial number
903 * less than the y of some k-candidate, that k-candidate
904 * with the smallest such y is replaced. The new
905 * k-candidate is chained (via pred) to the current
906 * k-1 candidate so that the actual subsequence can
907 * be recovered. When a member has serial number greater
908 * that the y of all k-candidates, the klist is extended.
909 * At the end, the longest subsequence is pulled out
910 * and placed in the array J by unravel
912 * With J in hand, the matches there recorded are
913 * checked against reality to assure that no spurious
914 * matches have crept in due to hashing. If they have,
915 * they are broken, and "jackpot" is recorded--a harmless
916 * matter except that a true match for a spuriously
917 * mated line may now be unnecessarily reported as a change.
919 * Much of the complexity of the program comes simply
920 * from trying to minimize core utilization and
921 * maximize the range of doable problems by dynamically
922 * allocating what is needed and reusing what is not.
923 * The core requirements for problems larger than somewhat
924 * are (in words) 2*length(file0) + length(file1) +
925 * 3*(number of k-candidates installed), typically about
926 * 6n words for files of length n.
929 static int diffreg(char *ofile1, char *ofile2, int flags)
931 char *file1 = ofile1;
932 char *file2 = ofile2;
939 context_vec_ptr = context_vec_start - 1;
941 if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
942 return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
943 if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
946 if (flags & D_EMPTY1)
947 f1 = bb_xfopen(_PATH_DEVNULL, "r");
949 if (strcmp(file1, "-") == 0)
952 f1 = bb_xfopen(file1, "r");
955 if (flags & D_EMPTY2)
956 f2 = bb_xfopen(_PATH_DEVNULL, "r");
958 if (strcmp(file2, "-") == 0)
961 f2 = bb_xfopen(file2, "r");
964 if ((i=files_differ(f1, f2, flags)) == 0)
966 else if (i != 1) {/* 1 == ok */
972 if (!asciifile(f1) || !asciifile(f2)) {
978 prepare(0, f1, stb1.st_size);
979 prepare(1, f2, stb2.st_size);
981 sort(sfile[0], slen[0]);
982 sort(sfile[1], slen[1]);
984 member = (int *)file[1];
985 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
986 member = xrealloc(member, (slen[1] + 2) * sizeof(int));
988 class = (int *)file[0];
989 unsort(sfile[0], slen[0], class);
990 class = xrealloc(class, (slen[0] + 2) * sizeof(int));
992 klist = xmalloc((slen[0] + 2) * sizeof(int));
995 clist = xmalloc(clistlen * sizeof(struct cand));
996 i = stone(class, slen[0], member, klist);
1000 J = xrealloc(J, (len[0] + 2) * sizeof(int));
1005 ixold = xrealloc(ixold, (len[0] + 2) * sizeof(long));
1006 ixnew = xrealloc(ixnew, (len[1] + 2) * sizeof(long));
1008 output(file1, f1, file2, f2);
1020 if (file1 != ofile1)
1022 if (file2 != ofile2)
1027 #if ENABLE_FEATURE_DIFF_DIR
1028 static void do_diff (char *dir1, char *path1, char *dir2, char *path2) {
1030 int flags = D_HEADER;
1033 char *fullpath1 = bb_xasprintf("%s/%s", dir1, path1);
1034 char *fullpath2 = bb_xasprintf("%s/%s", dir2, path2);
1036 if (stat(fullpath1, &stb1) != 0) {
1038 memset(&stb1, 0, sizeof(stb1));
1039 fullpath1 = bb_xasprintf("%s/%s", dir1, path2);
1041 if (stat(fullpath2, &stb2) != 0) {
1043 memset(&stb2, 0, sizeof(stb2));
1044 stb2.st_mode = stb1.st_mode;
1045 fullpath2 = bb_xasprintf("%s/%s", dir2, path1);
1048 if (stb1.st_mode == 0)
1049 stb1.st_mode = stb2.st_mode;
1051 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1052 printf("Common subdirectories: %s and %s\n", fullpath1, fullpath2);
1056 if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode))
1058 else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode))
1061 val = diffreg(fullpath1, fullpath2, flags);
1063 print_status(val, fullpath1, fullpath2, NULL);
1067 #ifdef CONFIG_FEATURE_DIFF_DIR
1068 static int dir_strcmp(const void *p1, const void *p2) {
1069 return strcmp(*(char * const *)p1, *(char * const *)p2);
1072 /* This function adds a filename to dl, the directory listing. */
1074 static int add_to_dirlist (const char *filename,
1075 struct stat ATTRIBUTE_UNUSED *sb, void *userdata) {
1077 dl = xrealloc(dl, dl_count * sizeof(char *));
1078 dl[dl_count - 1] = bb_xstrdup(filename);
1079 if (cmd_flags & FLAG_r) {
1080 int *pp = (int *) userdata;
1081 int path_len = *pp + 1;
1082 dl[dl_count - 1] = &(dl[dl_count - 1])[path_len];
1087 /* This returns a sorted directory listing. */
1088 static char **get_dir(char *path) {
1093 /* If -r has been set, then the recursive_action function will be
1094 * used. Unfortunately, this outputs the root directory along with
1095 * the recursed paths, so use void *userdata to specify the string
1096 * length of the root directory. It can then be removed in
1097 * add_to_dirlist. */
1099 int path_len = strlen(path);
1100 void *userdata = &path_len;
1102 /* Reset dl_count - there's no need to free dl as bb_xrealloc does
1103 * the job nicely. */
1106 /* Now fill dl with a listing. */
1107 if (cmd_flags & FLAG_r)
1108 recursive_action(path, TRUE, TRUE, FALSE, add_to_dirlist, NULL, userdata);
1112 if ((dp = opendir(path)) == NULL)
1113 bb_error_msg("Error reading directory");
1114 while ((ep = readdir(dp))) {
1115 if ((!strcmp(ep->d_name, "..")) || (!strcmp(ep->d_name, ".")))
1117 add_to_dirlist(ep->d_name, NULL, NULL);
1122 /* Sort dl alphabetically. */
1123 qsort(dl, dl_count, sizeof(char *), dir_strcmp);
1125 /* Copy dl so that we can return it. */
1126 retval = xmalloc(dl_count * sizeof(char *));
1127 for (i = 0; i < dl_count; i++)
1128 retval[i] = bb_xstrdup(dl[i]);
1133 static void diffdir (char *p1, char *p2) {
1135 char **dirlist1, **dirlist2;
1137 int dirlist1_count, dirlist2_count;
1140 /* Check for trailing slashes. */
1142 if (p1[strlen(p1) - 1] == '/')
1143 p1[strlen(p1) - 1] = '\0';
1144 if (p2[strlen(p2) - 1] == '/')
1145 p2[strlen(p2) - 1] = '\0';
1147 /* Get directory listings for p1 and p2. */
1149 dirlist1 = get_dir(p1);
1150 dirlist1_count = dl_count;
1151 dirlist1[dirlist1_count] = NULL;
1152 dirlist2 = get_dir(p2);
1153 dirlist2_count = dl_count;
1154 dirlist2[dirlist2_count] = NULL;
1156 /* If -S was set, find the starting point. */
1158 while (*dirlist1 != NULL && strcmp(*dirlist1, start) < 0)
1160 while (*dirlist2 != NULL && strcmp(*dirlist2, start) < 0)
1162 if ((*dirlist1 == NULL) || (*dirlist2 == NULL))
1163 bb_error_msg("Invalid argument to -S");
1166 /* Now that both dirlist1 and dirlist2 contain sorted directory
1167 * listings, we can start to go through dirlist1. If both listings
1168 * contain the same file, then do a normal diff. Otherwise, behaviour
1169 * is determined by whether the -N flag is set. */
1170 while (*dirlist1 != NULL || *dirlist2 != NULL) {
1173 pos = dp1 == NULL ? 1 : dp2 == NULL ? -1 : strcmp(dp1, dp2);
1175 do_diff(p1, dp1, p2, dp2);
1180 if (cmd_flags & FLAG_N)
1181 do_diff(p1, dp1, p2, NULL);
1183 print_only(p1, strlen(p1) + 1, dp1);
1187 if (cmd_flags & FLAG_N)
1188 do_diff(p1, NULL, p2, dp2);
1190 print_only(p2, strlen(p2) + 1, dp2);
1199 extern int diff_main(int argc, char **argv) {
1204 cmd_flags = bb_getopt_ulflags(argc, argv, "abdiNqrsS:tTU:wu", &start, &U_opt);
1206 context = 3; /* This is the default number of lines of context. */
1207 if (cmd_flags & FLAG_U) {
1208 context = strtol(U_opt, &ep, 10);
1210 bb_error_msg("Invalid context length");
1218 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
1219 * driver routine. Both drivers use the contents of stb1 and stb2.
1222 bb_error_msg("Missing filename");
1225 if (strcmp(argv[0], "-") == 0) {
1226 fstat(STDIN_FILENO, &stb1);
1228 } else if (stat(argv[0], &stb1) != 0)
1229 bb_perror_msg_and_die("Couldn't stat %s", argv[0]);
1230 if (strcmp(argv[1], "-") == 0) {
1231 fstat(STDIN_FILENO, &stb2);
1233 } else if (stat(argv[1], &stb2) != 0)
1234 bb_perror_msg_and_die("Couldn't stat %s", argv[1]);
1235 if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
1236 bb_error_msg_and_die("Can't compare - to a directory");
1237 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
1238 #ifdef CONFIG_FEATURE_DIFF_DIR
1239 diffdir(argv[0], argv[1]);
1241 bb_error_msg_and_die("Directory comparison not supported");
1245 if (S_ISDIR(stb1.st_mode)) {
1246 argv[0] = concat_path_file(argv[0], argv[1]);
1247 if (stat(argv[0], &stb1) < 0)
1248 bb_perror_msg_and_die("Couldn't stat %s", argv[0]);
1250 if (S_ISDIR(stb2.st_mode)) {
1251 argv[1] = concat_path_file(argv[1], argv[0]);
1252 if (stat(argv[1], &stb2) < 0)
1253 bb_perror_msg_and_die("Couldn't stat %s", argv[1]);
1255 print_status(diffreg(argv[0], argv[1], 0), argv[0], argv[1], NULL);