blob: daa58af9b18ba0fbce3e4a5acbe3c7e159c95023 [file] [log] [blame]
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Mini diff implementation for busybox, adapted from OpenBSD diff.
4 *
Matheus Izvekovd4a77282010-01-18 04:57:17 +01005 * Copyright (C) 2010 by Matheus Izvekov <mizvekov@gmail.com>
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00006 * Copyright (C) 2006 by Robert Sullivan <cogito.ergo.cogito@hotmail.com>
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00007 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
8 *
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00009 * 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.
Bernhard Reutner-Fischer14aa06f2006-05-19 13:02:27 +000012 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020013 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000014 */
15
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +000016/*
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000017 * The following code uses an algorithm due to Harold Stone,
18 * which finds a pair of longest identical subsequences in
19 * the two files.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000020 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000021 * The major goal is to generate the match vector J.
22 * J[i] is the index of the line in file1 corresponding
Denis Vlasenkodc1cbf82008-03-24 14:44:20 +000023 * to line i in file0. J[i] = 0 if there is no
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000024 * such line in file1.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000025 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000026 * Lines are hashed so as to work in core. All potential
27 * matches are located by sorting the lines of each file
Denis Vlasenkodc1cbf82008-03-24 14:44:20 +000028 * on the hash (called "value"). In particular, this
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000029 * 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.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000037 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000038 * Next the indices that point into member are unsorted into
39 * array class according to the original order of file0.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000040 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000041 * 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
Denis Vlasenkodc1cbf82008-03-24 14:44:20 +000044 * pair of lines x,y (x in file0, y in file1) such that
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000045 * 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.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000050 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000051 * 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
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000061 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000062 * 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.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000068 *
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000069 * 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) +
Denis Vlasenkodc1cbf82008-03-24 14:44:20 +000075 * 3*(number of k-candidates installed), typically about
Denis Vlasenko02f0c4c2007-03-09 10:08:53 +000076 * 6n words for files of length n.
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000077 */
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +000078
Pere Orga6a3e01d2011-04-01 22:56:30 +020079//usage:#define diff_trivial_usage
80//usage: "[-abBdiNqrTstw] [-L LABEL] [-S FILE] [-U LINES] FILE1 FILE2"
81//usage:#define diff_full_usage "\n\n"
82//usage: "Compare files line by line and output the differences between them.\n"
83//usage: "This implementation supports unified diffs only.\n"
84//usage: "\nOptions:"
85//usage: "\n -a Treat all files as text"
86//usage: "\n -b Ignore changes in the amount of whitespace"
87//usage: "\n -B Ignore changes whose lines are all blank"
88//usage: "\n -d Try hard to find a smaller set of changes"
89//usage: "\n -i Ignore case differences"
90//usage: "\n -L Use LABEL instead of the filename in the unified header"
91//usage: "\n -N Treat absent files as empty"
92//usage: "\n -q Output only whether files differ"
93//usage: "\n -r Recurse"
94//usage: "\n -S Start with FILE when comparing directories"
95//usage: "\n -T Make tabs line up by prefixing a tab when necessary"
96//usage: "\n -s Report when two files are the same"
97//usage: "\n -t Expand tabs to spaces in output"
98//usage: "\n -U Output LINES lines of context"
99//usage: "\n -w Ignore all whitespace"
100
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100101#include "libbb.h"
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000102
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100103#if 0
104//#define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
105#else
106#define dbg_error_msg(...) ((void)0)
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000107#endif
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000108
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200109enum { /* print_status() and diffreg() return values */
110 STATUS_SAME, /* files are the same */
111 STATUS_DIFFER, /* files differ */
112 STATUS_BINARY, /* binary files differ */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100113};
114
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200115enum { /* Commandline flags */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100116 FLAG_a,
117 FLAG_b,
118 FLAG_d,
Matheus Izvekovb7a04402010-01-18 14:25:46 -0200119 FLAG_i,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200120 FLAG_L, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100121 FLAG_N,
122 FLAG_q,
123 FLAG_r,
124 FLAG_s,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200125 FLAG_S, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100126 FLAG_t,
127 FLAG_T,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200128 FLAG_U, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100129 FLAG_w,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200130 FLAG_u, /* ignored, this is the default */
131 FLAG_p, /* not implemented */
132 FLAG_B,
133 FLAG_E, /* not implemented */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100134};
135#define FLAG(x) (1 << FLAG_##x)
136
137/* We cache file position to avoid excessive seeking */
138typedef struct FILE_and_pos_t {
139 FILE *ft_fp;
140 off_t ft_pos;
141} FILE_and_pos_t;
142
143struct globals {
144 smallint exit_status;
145 int opt_U_context;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200146 const char *other_dir;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100147 char *label[2];
148 struct stat stb[2];
149};
150#define G (*ptr_to_globals)
151#define exit_status (G.exit_status )
152#define opt_U_context (G.opt_U_context )
153#define label (G.label )
154#define stb (G.stb )
155#define INIT_G() do { \
156 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
157 opt_U_context = 3; \
158} while (0)
159
160typedef int token_t;
161
162enum {
163 /* Public */
164 TOK_EMPTY = 1 << 9, /* Line fully processed, you can proceed to the next */
165 TOK_EOF = 1 << 10, /* File ended */
166 /* Private (Only to be used by read_token() */
167 TOK_EOL = 1 << 11, /* we saw EOL (sticky) */
168 TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
169 SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
170 CHAR_MASK = 0x1ff, /* 8th bit is used to distinguish EOF from 0xff */
171};
172
173/* Restores full EOF from one 8th bit: */
174//#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
175/* We don't really need the above, we only need to have EOF != any_real_char: */
176#define TOK2CHAR(t) ((t) & CHAR_MASK)
177
178static void seek_ft(FILE_and_pos_t *ft, off_t pos)
179{
180 if (ft->ft_pos != pos) {
181 ft->ft_pos = pos;
182 fseeko(ft->ft_fp, pos, SEEK_SET);
183 }
184}
185
186/* Reads tokens from given fp, handling -b and -w flags
187 * The user must reset tok every line start
188 */
189static int read_token(FILE_and_pos_t *ft, token_t tok)
190{
191 tok |= TOK_EMPTY;
192 while (!(tok & TOK_EOL)) {
193 bool is_space;
194 int t;
195
196 t = fgetc(ft->ft_fp);
197 if (t != EOF)
198 ft->ft_pos++;
199 is_space = (t == EOF || isspace(t));
200
201 /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
202 tok |= (t & (TOK_EOF + TOK_EOL));
203 /* Only EOL? */
204 if (t == '\n')
205 tok |= TOK_EOL;
206
Matheus Izvekovb7a04402010-01-18 14:25:46 -0200207 if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
208 t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
209
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100210 if ((option_mask32 & FLAG(w)) && is_space)
211 continue;
212
213 /* Trim char value to low 9 bits */
214 t &= CHAR_MASK;
215
216 if (option_mask32 & FLAG(b)) {
217 /* Was prev char whitespace? */
218 if (tok & TOK_SPACE) { /* yes */
219 if (is_space) /* this one too, ignore it */
220 continue;
221 tok &= ~TOK_SPACE;
222 } else if (is_space) {
223 /* 1st whitespace char.
224 * Set TOK_SPACE and replace char by ' ' */
225 t = TOK_SPACE + ' ';
226 }
227 }
228 /* Clear EMPTY */
229 tok &= ~(TOK_EMPTY + CHAR_MASK);
230 /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
231 tok |= t;
232 break;
233 }
234#if 0
235 bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
236 , tok & TOK_EOF ? " EOF" : ""
237 , tok & TOK_EOL ? " EOL" : ""
238 , tok & TOK_EMPTY ? " EMPTY" : ""
239 , tok & TOK_SPACE ? " SPACE" : ""
240 );
241#endif
242 return tok;
243}
244
245struct cand {
246 int x;
247 int y;
248 int pred;
249};
250
251static int search(const int *c, int k, int y, const struct cand *list)
252{
Dan Fandrichf111b672010-02-04 00:10:30 +0100253 int i, j;
254
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200255 if (list[c[k]].y < y) /* quick look for typical case */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100256 return k + 1;
257
Dan Fandrichf111b672010-02-04 00:10:30 +0100258 for (i = 0, j = k + 1;;) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100259 const int l = (i + j) >> 1;
260 if (l > i) {
261 const int t = list[c[l]].y;
262 if (t > y)
263 j = l;
264 else if (t < y)
265 i = l;
266 else
267 return l;
268 } else
269 return l + 1;
270 }
271}
272
273static unsigned isqrt(unsigned n)
274{
275 unsigned x = 1;
276 while (1) {
277 const unsigned y = x;
278 x = ((n / x) + x) >> 1;
279 if (x <= (y + 1) && x >= (y - 1))
280 return x;
281 }
282}
283
284static void stone(const int *a, int n, const int *b, int *J, int pref)
285{
286 const unsigned isq = isqrt(n);
287 const unsigned bound =
288 (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
289 int clen = 1;
290 int clistlen = 100;
291 int k = 0;
292 struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100293 struct cand cand;
294 struct cand *q;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100295 int *klist = xzalloc((n + 2) * sizeof(klist[0]));
296 /*clist[0] = (struct cand){0}; - xzalloc did it */
297 /*klist[0] = 0; */
298
Dan Fandrichf111b672010-02-04 00:10:30 +0100299 for (cand.x = 1; cand.x <= n; cand.x++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100300 int j = a[cand.x], oldl = 0;
301 unsigned numtries = 0;
302 if (j == 0)
303 continue;
304 cand.y = -b[j];
305 cand.pred = klist[0];
306 do {
307 int l, tc;
308 if (cand.y <= clist[cand.pred].y)
309 continue;
310 l = search(klist, k, cand.y, clist);
311 if (l != oldl + 1)
312 cand.pred = klist[l - 1];
313 if (l <= k && clist[klist[l]].y <= cand.y)
314 continue;
315 if (clen == clistlen) {
316 clistlen = clistlen * 11 / 10;
317 clist = xrealloc(clist, clistlen * sizeof(clist[0]));
318 }
319 clist[clen] = cand;
320 tc = klist[l];
321 klist[l] = clen++;
322 if (l <= k) {
323 cand.pred = tc;
324 oldl = l;
325 numtries++;
326 } else {
327 k++;
328 break;
329 }
330 } while ((cand.y = b[++j]) > 0 && numtries < bound);
331 }
332 /* Unravel */
Dan Fandrichf111b672010-02-04 00:10:30 +0100333 for (q = clist + klist[k]; q->y; q = clist + q->pred)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100334 J[q->x + pref] = q->y + pref;
335 free(klist);
336 free(clist);
337}
338
339struct line {
340 /* 'serial' is not used in the begining, so we reuse it
341 * to store line offsets, thus reducing memory pressure
342 */
343 union {
344 unsigned serial;
345 off_t offset;
346 };
347 unsigned value;
348};
349
350static void equiv(struct line *a, int n, struct line *b, int m, int *c)
351{
352 int i = 1, j = 1;
353
354 while (i <= n && j <= m) {
355 if (a[i].value < b[j].value)
356 a[i++].value = 0;
357 else if (a[i].value == b[j].value)
358 a[i++].value = j;
359 else
360 j++;
361 }
362 while (i <= n)
363 a[i++].value = 0;
364 b[m + 1].value = 0;
365 j = 0;
366 while (++j <= m) {
367 c[j] = -b[j].serial;
368 while (b[j + 1].value == b[j].value) {
369 j++;
370 c[j] = b[j].serial;
371 }
372 }
373 c[j] = -1;
374}
375
376static void unsort(const struct line *f, int l, int *b)
377{
Dan Fandrichf111b672010-02-04 00:10:30 +0100378 int i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100379 int *a = xmalloc((l + 1) * sizeof(a[0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100380 for (i = 1; i <= l; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100381 a[f[i].serial] = f[i].value;
Dan Fandrichf111b672010-02-04 00:10:30 +0100382 for (i = 1; i <= l; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100383 b[i] = a[i];
384 free(a);
385}
386
387static int line_compar(const void *a, const void *b)
388{
389#define l0 ((const struct line*)a)
390#define l1 ((const struct line*)b)
391 int r = l0->value - l1->value;
392 if (r)
393 return r;
394 return l0->serial - l1->serial;
395#undef l0
396#undef l1
397}
398
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100399static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
400{
Dan Fandrichf111b672010-02-04 00:10:30 +0100401 int i, j, col;
402 for (i = a; i <= b; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100403 seek_ft(ft, ix[i - 1]);
404 putchar(ch);
405 if (option_mask32 & FLAG(T))
406 putchar('\t');
Dan Fandrichf111b672010-02-04 00:10:30 +0100407 for (j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100408 int c = fgetc(ft->ft_fp);
409 if (c == EOF) {
410 printf("\n\\ No newline at end of file\n");
411 return;
412 }
413 ft->ft_pos++;
414 if (c == '\t' && (option_mask32 & FLAG(t)))
415 do putchar(' '); while (++col & 7);
416 else {
417 putchar(c);
418 col++;
419 }
420 }
421 }
422}
423
424/* Creates the match vector J, where J[i] is the index
425 * of the line in the new file corresponding to the line i
426 * in the old file. Lines start at 1 instead of 0, that value
427 * being used instead to denote no corresponding line.
428 * This vector is dynamically allocated and must be freed by the caller.
429 *
430 * * fp is an input parameter, where fp[0] and fp[1] are the open
431 * old file and new file respectively.
432 * * nlen is an output variable, where nlen[0] and nlen[1]
433 * gets the number of lines in the old and new file respectively.
434 * * ix is an output variable, where ix[0] and ix[1] gets
435 * assigned dynamically allocated vectors of the offsets of the lines
436 * of the old and new file respectively. These must be freed by the caller.
437 */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100438static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100439{
440 int *J, slen[2], *class, *member;
441 struct line *nfile[2], *sfile[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100442 int pref = 0, suff = 0, i, j, delta;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100443
444 /* Lines of both files are hashed, and in the process
445 * their offsets are stored in the array ix[fileno]
446 * where fileno == 0 points to the old file, and
447 * fileno == 1 points to the new one.
448 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100449 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100450 unsigned hash;
451 token_t tok;
452 size_t sz = 100;
453 nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100454 /* ft gets here without the correct position, cant use seek_ft */
Dan Fandrichf111b672010-02-04 00:10:30 +0100455 ft[i].ft_pos = 0;
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100456 fseeko(ft[i].ft_fp, 0, SEEK_SET);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100457
458 nlen[i] = 0;
459 /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
460 nfile[i][0].offset = 0;
461 goto start; /* saves code */
462 while (1) {
463 tok = read_token(&ft[i], tok);
464 if (!(tok & TOK_EMPTY)) {
465 /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
Denys Vlasenko032bf652010-01-18 05:22:34 +0100466 /*hash = hash * 128 - hash + TOK2CHAR(tok);
467 * gcc insists on optimizing above to "hash * 127 + ...", thus... */
468 unsigned o = hash - TOK2CHAR(tok);
469 hash = hash * 128 - o; /* we want SPEED here */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100470 continue;
471 }
472 if (nlen[i]++ == sz) {
473 sz = sz * 3 / 2;
474 nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
475 }
476 /* line_compar needs hashes fit into positive int */
477 nfile[i][nlen[i]].value = hash & INT_MAX;
478 /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
479 nfile[i][nlen[i]].offset = ft[i].ft_pos;
480 if (tok & TOK_EOF) {
481 /* EOF counts as a token, so we have to adjust it here */
482 nfile[i][nlen[i]].offset++;
483 break;
484 }
485start:
486 hash = tok = 0;
487 }
488 /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
489 if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
490 nlen[i]--;
491 /* Now we copy the line offsets into ix */
492 ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100493 for (j = 0; j < nlen[i] + 1; j++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100494 ix[i][j] = nfile[i][j].offset;
495 }
496
Dan Fandrich1821d182010-02-04 04:04:56 +0100497 /* length of prefix and suffix is calculated */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100498 for (; pref < nlen[0] && pref < nlen[1] &&
499 nfile[0][pref + 1].value == nfile[1][pref + 1].value;
500 pref++);
501 for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
502 nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
503 suff++);
Denys Vlasenko25b47552010-08-30 01:19:47 +0200504 /* Arrays are pruned by the suffix and prefix length,
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100505 * the result being sorted and stored in sfile[fileno],
506 * and their sizes are stored in slen[fileno]
507 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100508 for (j = 0; j < 2; j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100509 sfile[j] = nfile[j] + pref;
510 slen[j] = nlen[j] - pref - suff;
Dan Fandrichf111b672010-02-04 00:10:30 +0100511 for (i = 0; i <= slen[j]; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100512 sfile[j][i].serial = i;
513 qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
514 }
515 /* nfile arrays are reused to reduce memory pressure
516 * The #if zeroed out section performs the same task as the
517 * one in the #else section.
518 * Peak memory usage is higher, but one array copy is avoided
519 * by not using unsort()
520 */
521#if 0
522 member = xmalloc((slen[1] + 2) * sizeof(member[0]));
523 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
524 free(nfile[1]);
525
526 class = xmalloc((slen[0] + 1) * sizeof(class[0]));
Dan Fandrich1821d182010-02-04 04:04:56 +0100527 for (i = 1; i <= slen[0]; i++) /* Unsorting */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100528 class[sfile[0][i].serial] = sfile[0][i].value;
529 free(nfile[0]);
530#else
531 member = (int *)nfile[1];
532 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
533 member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
534
535 class = (int *)nfile[0];
536 unsort(sfile[0], slen[0], (int *)nfile[0]);
537 class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
538#endif
539 J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
540 /* The elements of J which fall inside the prefix and suffix regions
541 * are marked as unchanged, while the ones which fall outside
542 * are initialized with 0 (no matches), so that function stone can
543 * then assign them their right values
544 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100545 for (i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100546 J[i] = i <= pref ? i :
547 i > (nlen[0] - suff) ? (i + delta) : 0;
548 /* Here the magic is performed */
549 stone(class, slen[0], member, J, pref);
550 J[nlen[0] + 1] = nlen[1] + 1;
551
552 free(class);
553 free(member);
554
555 /* Both files are rescanned, in an effort to find any lines
556 * which, due to limitations intrinsic to any hashing algorithm,
557 * are different but ended up confounded as the same
558 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100559 for (i = 1; i <= nlen[0]; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100560 if (!J[i])
561 continue;
562
563 seek_ft(&ft[0], ix[0][i - 1]);
564 seek_ft(&ft[1], ix[1][J[i] - 1]);
565
Dan Fandrichf111b672010-02-04 00:10:30 +0100566 for (j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100567 token_t tok0 = 0, tok1 = 0;
568 do {
569 tok0 = read_token(&ft[0], tok0);
570 tok1 = read_token(&ft[1], tok1);
571
572 if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100573 || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
574 ) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100575 J[i] = 0; /* Break the correspondence */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100576 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100577 } while (!(tok0 & tok1 & TOK_EMPTY));
578 }
579 }
580
581 return J;
582}
583
Matheus Izvekov404f1442010-01-18 22:21:40 -0200584static bool diff(FILE* fp[2], char *file[2])
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100585{
586 int nlen[2];
587 off_t *ix[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100588 FILE_and_pos_t ft[2];
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200589 typedef struct { int a, b; } vec_t[2];
590 vec_t *vec = NULL;
Dan Fandrich1821d182010-02-04 04:04:56 +0100591 int i = 1, j, k, idx = -1;
Dan Fandrichf111b672010-02-04 00:10:30 +0100592 bool anychange = false;
593 int *J;
594
595 ft[0].ft_fp = fp[0];
596 ft[1].ft_fp = fp[1];
597 /* note that ft[i].ft_pos is unintitalized, create_J()
598 * must not assume otherwise */
599 J = create_J(ft, nlen, ix);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100600
601 do {
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200602 bool nonempty = false;
603
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100604 while (1) {
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200605 vec_t v;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100606
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200607 for (v[0].a = i; v[0].a <= nlen[0] && J[v[0].a] == J[v[0].a - 1] + 1; v[0].a++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100608 continue;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200609 v[1].a = J[v[0].a - 1] + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100610
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200611 for (v[0].b = v[0].a - 1; v[0].b < nlen[0] && !J[v[0].b + 1]; v[0].b++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100612 continue;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200613 v[1].b = J[v[0].b + 1] - 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100614 /*
615 * Indicate that there is a difference between lines a and b of the 'from' file
616 * to get to lines c to d of the 'to' file. If a is greater than b then there
617 * are no lines in the 'from' file involved and this means that there were
618 * lines appended (beginning at b). If c is greater than d then there are
619 * lines missing from the 'to' file.
620 */
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200621 if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100622 /*
623 * If this change is more than 'context' lines from the
624 * previous change, dump the record and reset it.
625 */
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200626 int ct = (2 * opt_U_context) + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100627 if (idx >= 0
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200628 && v[0].a > vec[idx][0].b + ct
629 && v[1].a > vec[idx][1].b + ct
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100630 ) {
631 break;
632 }
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200633
Dan Fandrich1821d182010-02-04 04:04:56 +0100634 for (j = 0; j < 2; j++)
635 for (k = v[j].a; k < v[j].b; k++)
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200636 nonempty |= (ix[j][k+1] - ix[j][k] != 1);
637
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100638 vec = xrealloc_vector(vec, 6, ++idx);
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200639 memcpy(vec[idx], v, sizeof(v));
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100640 }
641
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200642 i = v[0].b + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100643 if (i > nlen[0])
644 break;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200645 J[v[0].b] = v[1].b;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100646 }
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200647 if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
648 goto cont;
649 if (!(option_mask32 & FLAG(q))) {
Dan Fandrich1821d182010-02-04 04:04:56 +0100650 int lowa;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200651 vec_t span, *cvp = vec;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100652
653 if (!anychange) {
654 /* Print the context/unidiff header first time through */
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100655 printf("--- %s\n", label[0] ? label[0] : file[0]);
656 printf("+++ %s\n", label[1] ? label[1] : file[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100657 }
658
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200659 printf("@@");
Dan Fandrich1821d182010-02-04 04:04:56 +0100660 for (j = 0; j < 2; j++) {
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200661 int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
662 int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100663
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200664 printf(" %c%d", j ? '+' : '-', MIN(a, b));
665 if (a == b)
666 continue;
667 printf(",%d", (a < b) ? b - a + 1 : 0);
668 }
669 printf(" @@\n");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100670 /*
671 * Output changes in "unified" diff format--the old and new lines
672 * are printed together.
673 */
Dan Fandrich1821d182010-02-04 04:04:56 +0100674 for (lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100675 bool end = cvp > &vec[idx];
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200676 fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100677 if (end)
678 break;
Dan Fandrich1821d182010-02-04 04:04:56 +0100679 for (j = 0; j < 2; j++)
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200680 fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100681 }
682 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100683 anychange = true;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200684 cont:
685 idx = -1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100686 } while (i <= nlen[0]);
687
688 free(vec);
689 free(ix[0]);
690 free(ix[1]);
691 free(J);
692 return anychange;
693}
694
695static int diffreg(char *file[2])
696{
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200697 FILE *fp[2] = { stdin, stdin };
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100698 bool binary = false, differ = false;
Dan Fandrichf111b672010-02-04 00:10:30 +0100699 int status = STATUS_SAME, i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100700
Dan Fandrichf111b672010-02-04 00:10:30 +0100701 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100702 int fd = open_or_warn_stdin(file[i]);
703 if (fd == -1)
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200704 goto out;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100705 /* Our diff implementation is using seek.
706 * When we meet non-seekable file, we must make a temp copy.
707 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100708 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
709 char name[] = "/tmp/difXXXXXX";
Alexander Shishkin67227372010-10-22 13:27:16 +0200710 int fd_tmp = xmkstemp(name);
711
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100712 unlink(name);
Matheus Izvekov404f1442010-01-18 22:21:40 -0200713 if (bb_copyfd_eof(fd, fd_tmp) < 0)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100714 xfunc_die();
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100715 if (fd) /* Prevents closing of stdin */
716 close(fd);
717 fd = fd_tmp;
718 }
Matheus Izvekov404f1442010-01-18 22:21:40 -0200719 fp[i] = fdopen(fd, "r");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100720 }
721
722 while (1) {
723 const size_t sz = COMMON_BUFSIZE / 2;
724 char *const buf0 = bb_common_bufsiz1;
725 char *const buf1 = buf0 + sz;
Dan Fandrichf111b672010-02-04 00:10:30 +0100726 int j, k;
Matheus Izvekov404f1442010-01-18 22:21:40 -0200727 i = fread(buf0, 1, sz, fp[0]);
728 j = fread(buf1, 1, sz, fp[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100729 if (i != j) {
730 differ = true;
731 i = MIN(i, j);
732 }
733 if (i == 0)
734 break;
Dan Fandrichf111b672010-02-04 00:10:30 +0100735 for (k = 0; k < i; k++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100736 if (!buf0[k] || !buf1[k])
737 binary = true;
738 if (buf0[k] != buf1[k])
739 differ = true;
740 }
741 }
742 if (differ) {
743 if (binary && !(option_mask32 & FLAG(a)))
744 status = STATUS_BINARY;
Matheus Izvekov404f1442010-01-18 22:21:40 -0200745 else if (diff(fp, file))
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100746 status = STATUS_DIFFER;
747 }
748 if (status != STATUS_SAME)
749 exit_status |= 1;
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200750out:
Matheus Izvekov404f1442010-01-18 22:21:40 -0200751 fclose_if_not_stdin(fp[0]);
752 fclose_if_not_stdin(fp[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100753
754 return status;
755}
756
757static void print_status(int status, char *path[2])
758{
759 switch (status) {
760 case STATUS_BINARY:
761 case STATUS_DIFFER:
762 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
763 printf("Files %s and %s differ\n", path[0], path[1]);
764 break;
765 case STATUS_SAME:
766 if (option_mask32 & FLAG(s))
767 printf("Files %s and %s are identical\n", path[0], path[1]);
768 break;
769 }
770}
Denis Vlasenko6a1d6612006-12-16 22:18:44 +0000771
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +0000772#if ENABLE_FEATURE_DIFF_DIR
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100773struct dlist {
774 size_t len;
775 int s, e;
776 char **dl;
777};
778
Denis Vlasenko6a1d6612006-12-16 22:18:44 +0000779/* This function adds a filename to dl, the directory listing. */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000780static int FAST_FUNC add_to_dirlist(const char *filename,
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000781 struct stat *sb UNUSED_PARAM,
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100782 void *userdata, int depth UNUSED_PARAM)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000783{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100784 struct dlist *const l = userdata;
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200785 const char *file = filename + l->len;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200786 while (*file == '/')
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200787 file++;
Denys Vlasenko32a6bae2010-07-09 19:44:38 +0200788 l->dl = xrealloc_vector(l->dl, 6, l->e);
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200789 l->dl[l->e] = xstrdup(file);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100790 l->e++;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000791 return TRUE;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000792}
793
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100794/* If recursion is not set, this function adds the directory
795 * to the list and prevents recursive_action from recursing into it.
796 */
797static int FAST_FUNC skip_dir(const char *filename,
798 struct stat *sb, void *userdata,
799 int depth)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000800{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100801 if (!(option_mask32 & FLAG(r)) && depth) {
802 add_to_dirlist(filename, sb, userdata, depth);
803 return SKIP;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000804 }
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200805 if (!(option_mask32 & FLAG(N))) {
806 /* -r without -N: no need to recurse into dirs
807 * which do not exist on the "other side".
808 * Testcase: diff -r /tmp /
809 * (it would recurse deep into /proc without this code) */
810 struct dlist *const l = userdata;
811 filename += l->len;
812 if (filename[0]) {
813 struct stat osb;
814 char *othername = concat_path_file(G.other_dir, filename);
815 int r = stat(othername, &osb);
816 free(othername);
817 if (r != 0 || !S_ISDIR(osb.st_mode)) {
818 /* other dir doesn't have similarly named
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200819 * directory, don't recurse; return 1 upon
820 * exit, just like diffutils' diff */
821 exit_status |= 1;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200822 return SKIP;
823 }
824 }
825 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100826 return TRUE;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000827}
828
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100829static void diffdir(char *p[2], const char *s_start)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000830{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100831 struct dlist list[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100832 int i;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000833
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100834 memset(&list, 0, sizeof(list));
Dan Fandrichf111b672010-02-04 00:10:30 +0100835 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100836 /*list[i].s = list[i].e = 0; - memset did it */
837 /*list[i].dl = NULL; */
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000838
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200839 G.other_dir = p[1 - i];
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100840 /* We need to trim root directory prefix.
841 * Using list.len to specify its length,
842 * add_to_dirlist will remove it. */
843 list[i].len = strlen(p[i]);
844 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
845 add_to_dirlist, skip_dir, &list[i], 0);
846 /* Sort dl alphabetically.
847 * GNU diff does this ignoring any number of trailing dots.
848 * We don't, so for us dotted files almost always are
849 * first on the list.
850 */
851 qsort_string_vector(list[i].dl, list[i].e);
852 /* If -S was set, find the starting point. */
853 if (!s_start)
854 continue;
855 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
856 list[i].s++;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000857 }
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000858 /* Now that both dirlist1 and dirlist2 contain sorted directory
859 * listings, we can start to go through dirlist1. If both listings
860 * contain the same file, then do a normal diff. Otherwise, behaviour
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000861 * is determined by whether the -N flag is set. */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100862 while (1) {
863 char *dp[2];
864 int pos;
865 int k;
866
867 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
868 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
869 if (!dp[0] && !dp[1])
870 break;
871 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
872 k = pos > 0;
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200873 if (pos && !(option_mask32 & FLAG(N))) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100874 printf("Only in %s: %s\n", p[k], dp[k]);
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200875 exit_status |= 1;
876 } else {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100877 char *fullpath[2], *path[2]; /* if -N */
878
Dan Fandrichf111b672010-02-04 00:10:30 +0100879 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100880 if (pos == 0 || i == k) {
881 path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
882 stat(fullpath[i], &stb[i]);
883 } else {
884 fullpath[i] = concat_path_file(p[i], dp[1 - i]);
885 path[i] = (char *)bb_dev_null;
886 }
887 }
888 if (pos)
889 stat(fullpath[k], &stb[1 - k]);
890
891 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
892 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
893 else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
894 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
895 else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
896 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
897 else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
898 if (S_ISDIR(stb[0].st_mode))
899 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
900 else
901 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
902 } else
903 print_status(diffreg(path), fullpath);
904
905 free(fullpath[0]);
906 free(fullpath[1]);
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000907 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100908 free(dp[k]);
909 list[k].s++;
910 if (pos == 0) {
911 free(dp[1 - k]);
912 list[1 - k].s++;
913 }
914 }
915 if (ENABLE_FEATURE_CLEAN_UP) {
916 free(list[0].dl);
917 free(list[1].dl);
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000918 }
919}
920#endif
921
Matheus Izvekovb32aa0c2010-01-18 18:40:02 -0200922#if ENABLE_FEATURE_DIFF_LONG_OPTIONS
923static const char diff_longopts[] ALIGN1 =
924 "ignore-case\0" No_argument "i"
925 "ignore-tab-expansion\0" No_argument "E"
926 "ignore-space-change\0" No_argument "b"
927 "ignore-all-space\0" No_argument "w"
928 "ignore-blank-lines\0" No_argument "B"
929 "text\0" No_argument "a"
930 "unified\0" Required_argument "U"
931 "label\0" Required_argument "L"
932 "show-c-function\0" No_argument "p"
933 "brief\0" No_argument "q"
934 "expand-tabs\0" No_argument "t"
935 "initial-tab\0" No_argument "T"
936 "recursive\0" No_argument "r"
937 "new-file\0" No_argument "N"
938 "report-identical-files\0" No_argument "s"
939 "starting-file\0" Required_argument "S"
940 "minimal\0" No_argument "d"
941 ;
942#endif
943
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +0000944int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000945int diff_main(int argc UNUSED_PARAM, char **argv)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000946{
Dan Fandrichf111b672010-02-04 00:10:30 +0100947 int gotstdin = 0, i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100948 char *file[2], *s_start = NULL;
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +0000949 llist_t *L_arg = NULL;
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000950
Denis Vlasenkoef4bb262007-06-04 12:21:53 +0000951 INIT_G();
952
Denis Vlasenko1d426652008-03-17 09:09:09 +0000953 /* exactly 2 params; collect multiple -L <label>; -U N */
954 opt_complementary = "=2:L::U+";
Matheus Izvekovb32aa0c2010-01-18 18:40:02 -0200955#if ENABLE_FEATURE_DIFF_LONG_OPTIONS
956 applet_long_options = diff_longopts;
957#endif
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200958 getopt32(argv, "abdiL:NqrsS:tTU:wupBE",
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100959 &L_arg, &s_start, &opt_U_context);
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000960 argv += optind;
Matheus Izvekov4de4cb62010-01-18 20:40:23 -0200961 while (L_arg)
962 label[!!label[0]] = llist_pop(&L_arg);
Denys Vlasenko38d90722009-06-09 12:55:13 +0200963 xfunc_error_retval = 2;
Dan Fandrichf111b672010-02-04 00:10:30 +0100964 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100965 file[i] = argv[i];
966 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
967 if (LONE_DASH(file[i])) {
968 fstat(STDIN_FILENO, &stb[i]);
969 gotstdin++;
970 } else
971 xstat(file[i], &stb[i]);
972 }
Denys Vlasenko38d90722009-06-09 12:55:13 +0200973 xfunc_error_retval = 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100974 if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
Denis Vlasenko04211fd2008-03-24 14:44:59 +0000975 bb_error_msg_and_die("can't compare stdin to a directory");
976
Roman Borisov95f5c522011-03-27 23:24:09 +0200977 /* Compare metadata to check if the files are the same physical file.
978 *
979 * Comment from diffutils source says:
980 * POSIX says that two files are identical if st_ino and st_dev are
981 * the same, but many file systems incorrectly assign the same (device,
982 * inode) pair to two distinct files, including:
983 * GNU/Linux NFS servers that export all local file systems as a
984 * single NFS file system, if a local device number (st_dev) exceeds
985 * 255, or if a local inode number (st_ino) exceeds 16777215.
986 */
987 if (ENABLE_DESKTOP
988 && stb[0].st_ino == stb[1].st_ino
989 && stb[0].st_dev == stb[1].st_dev
990 && stb[0].st_size == stb[1].st_size
991 && stb[0].st_mtime == stb[1].st_mtime
992 && stb[0].st_ctime == stb[1].st_ctime
993 && stb[0].st_mode == stb[1].st_mode
994 && stb[0].st_nlink == stb[1].st_nlink
995 && stb[0].st_uid == stb[1].st_uid
996 && stb[0].st_gid == stb[1].st_gid
997 ) {
998 /* files are physically the same; no need to compare them */
999 return STATUS_SAME;
1000 }
1001
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001002 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +00001003#if ENABLE_FEATURE_DIFF_DIR
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001004 diffdir(file, s_start);
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001005#else
Denis Vlasenko04211fd2008-03-24 14:44:59 +00001006 bb_error_msg_and_die("no support for directory comparison");
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001007#endif
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001008 } else {
1009 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
1010 bool dir = S_ISDIR(stb[1].st_mode);
1011 if (dirfile) {
1012 const char *slash = strrchr(file[!dir], '/');
1013 file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
1014 xstat(file[dir], &stb[dir]);
1015 }
1016 /* diffreg can get non-regular files here */
1017 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
1018
1019 if (dirfile)
1020 free(file[dir]);
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001021 }
Denis Vlasenko04211fd2008-03-24 14:44:59 +00001022
Denis Vlasenko7fe0eba2008-03-24 16:19:21 +00001023 return exit_status;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001024}