blob: 3a33346402e67d89676820e2388dfd4473c6af35 [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"
Pere Orga6a3e01d2011-04-01 22:56:30 +020084//usage: "\n -a Treat all files as text"
85//usage: "\n -b Ignore changes in the amount of whitespace"
86//usage: "\n -B Ignore changes whose lines are all blank"
87//usage: "\n -d Try hard to find a smaller set of changes"
88//usage: "\n -i Ignore case differences"
89//usage: "\n -L Use LABEL instead of the filename in the unified header"
90//usage: "\n -N Treat absent files as empty"
91//usage: "\n -q Output only whether files differ"
92//usage: "\n -r Recurse"
93//usage: "\n -S Start with FILE when comparing directories"
94//usage: "\n -T Make tabs line up by prefixing a tab when necessary"
95//usage: "\n -s Report when two files are the same"
96//usage: "\n -t Expand tabs to spaces in output"
97//usage: "\n -U Output LINES lines of context"
98//usage: "\n -w Ignore all whitespace"
99
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100100#include "libbb.h"
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000101
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100102#if 0
Denys Vlasenkod616ab62011-05-22 03:46:33 +0200103# define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100104#else
Denys Vlasenkod616ab62011-05-22 03:46:33 +0200105# define dbg_error_msg(...) ((void)0)
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000106#endif
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000107
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200108enum { /* print_status() and diffreg() return values */
109 STATUS_SAME, /* files are the same */
110 STATUS_DIFFER, /* files differ */
111 STATUS_BINARY, /* binary files differ */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100112};
113
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200114enum { /* Commandline flags */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100115 FLAG_a,
116 FLAG_b,
117 FLAG_d,
Matheus Izvekovb7a04402010-01-18 14:25:46 -0200118 FLAG_i,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200119 FLAG_L, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100120 FLAG_N,
121 FLAG_q,
122 FLAG_r,
123 FLAG_s,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200124 FLAG_S, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100125 FLAG_t,
126 FLAG_T,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200127 FLAG_U, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100128 FLAG_w,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200129 FLAG_u, /* ignored, this is the default */
130 FLAG_p, /* not implemented */
131 FLAG_B,
132 FLAG_E, /* not implemented */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100133};
134#define FLAG(x) (1 << FLAG_##x)
135
136/* We cache file position to avoid excessive seeking */
137typedef struct FILE_and_pos_t {
138 FILE *ft_fp;
139 off_t ft_pos;
140} FILE_and_pos_t;
141
142struct globals {
143 smallint exit_status;
144 int opt_U_context;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200145 const char *other_dir;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100146 char *label[2];
147 struct stat stb[2];
148};
149#define G (*ptr_to_globals)
150#define exit_status (G.exit_status )
151#define opt_U_context (G.opt_U_context )
152#define label (G.label )
153#define stb (G.stb )
154#define INIT_G() do { \
155 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
156 opt_U_context = 3; \
157} while (0)
158
159typedef int token_t;
160
161enum {
162 /* Public */
163 TOK_EMPTY = 1 << 9, /* Line fully processed, you can proceed to the next */
164 TOK_EOF = 1 << 10, /* File ended */
165 /* Private (Only to be used by read_token() */
166 TOK_EOL = 1 << 11, /* we saw EOL (sticky) */
167 TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
168 SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
169 CHAR_MASK = 0x1ff, /* 8th bit is used to distinguish EOF from 0xff */
170};
171
172/* Restores full EOF from one 8th bit: */
173//#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
174/* We don't really need the above, we only need to have EOF != any_real_char: */
175#define TOK2CHAR(t) ((t) & CHAR_MASK)
176
177static void seek_ft(FILE_and_pos_t *ft, off_t pos)
178{
179 if (ft->ft_pos != pos) {
180 ft->ft_pos = pos;
181 fseeko(ft->ft_fp, pos, SEEK_SET);
182 }
183}
184
185/* Reads tokens from given fp, handling -b and -w flags
186 * The user must reset tok every line start
187 */
188static int read_token(FILE_and_pos_t *ft, token_t tok)
189{
190 tok |= TOK_EMPTY;
191 while (!(tok & TOK_EOL)) {
192 bool is_space;
193 int t;
194
195 t = fgetc(ft->ft_fp);
196 if (t != EOF)
197 ft->ft_pos++;
198 is_space = (t == EOF || isspace(t));
199
200 /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
201 tok |= (t & (TOK_EOF + TOK_EOL));
202 /* Only EOL? */
203 if (t == '\n')
204 tok |= TOK_EOL;
205
Matheus Izvekovb7a04402010-01-18 14:25:46 -0200206 if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
207 t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
208
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100209 if ((option_mask32 & FLAG(w)) && is_space)
210 continue;
211
212 /* Trim char value to low 9 bits */
213 t &= CHAR_MASK;
214
215 if (option_mask32 & FLAG(b)) {
216 /* Was prev char whitespace? */
217 if (tok & TOK_SPACE) { /* yes */
218 if (is_space) /* this one too, ignore it */
219 continue;
220 tok &= ~TOK_SPACE;
221 } else if (is_space) {
222 /* 1st whitespace char.
223 * Set TOK_SPACE and replace char by ' ' */
224 t = TOK_SPACE + ' ';
225 }
226 }
227 /* Clear EMPTY */
228 tok &= ~(TOK_EMPTY + CHAR_MASK);
229 /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
230 tok |= t;
231 break;
232 }
233#if 0
234 bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
235 , tok & TOK_EOF ? " EOF" : ""
236 , tok & TOK_EOL ? " EOL" : ""
237 , tok & TOK_EMPTY ? " EMPTY" : ""
238 , tok & TOK_SPACE ? " SPACE" : ""
239 );
240#endif
241 return tok;
242}
243
244struct cand {
245 int x;
246 int y;
247 int pred;
248};
249
250static int search(const int *c, int k, int y, const struct cand *list)
251{
Dan Fandrichf111b672010-02-04 00:10:30 +0100252 int i, j;
253
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200254 if (list[c[k]].y < y) /* quick look for typical case */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100255 return k + 1;
256
Dan Fandrichf111b672010-02-04 00:10:30 +0100257 for (i = 0, j = k + 1;;) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100258 const int l = (i + j) >> 1;
259 if (l > i) {
260 const int t = list[c[l]].y;
261 if (t > y)
262 j = l;
263 else if (t < y)
264 i = l;
265 else
266 return l;
267 } else
268 return l + 1;
269 }
270}
271
272static unsigned isqrt(unsigned n)
273{
274 unsigned x = 1;
275 while (1) {
276 const unsigned y = x;
277 x = ((n / x) + x) >> 1;
278 if (x <= (y + 1) && x >= (y - 1))
279 return x;
280 }
281}
282
283static void stone(const int *a, int n, const int *b, int *J, int pref)
284{
285 const unsigned isq = isqrt(n);
286 const unsigned bound =
287 (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
288 int clen = 1;
289 int clistlen = 100;
290 int k = 0;
291 struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100292 struct cand cand;
293 struct cand *q;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100294 int *klist = xzalloc((n + 2) * sizeof(klist[0]));
295 /*clist[0] = (struct cand){0}; - xzalloc did it */
296 /*klist[0] = 0; */
297
Dan Fandrichf111b672010-02-04 00:10:30 +0100298 for (cand.x = 1; cand.x <= n; cand.x++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100299 int j = a[cand.x], oldl = 0;
300 unsigned numtries = 0;
301 if (j == 0)
302 continue;
303 cand.y = -b[j];
304 cand.pred = klist[0];
305 do {
306 int l, tc;
307 if (cand.y <= clist[cand.pred].y)
308 continue;
309 l = search(klist, k, cand.y, clist);
310 if (l != oldl + 1)
311 cand.pred = klist[l - 1];
312 if (l <= k && clist[klist[l]].y <= cand.y)
313 continue;
314 if (clen == clistlen) {
315 clistlen = clistlen * 11 / 10;
316 clist = xrealloc(clist, clistlen * sizeof(clist[0]));
317 }
318 clist[clen] = cand;
319 tc = klist[l];
320 klist[l] = clen++;
321 if (l <= k) {
322 cand.pred = tc;
323 oldl = l;
324 numtries++;
325 } else {
326 k++;
327 break;
328 }
329 } while ((cand.y = b[++j]) > 0 && numtries < bound);
330 }
331 /* Unravel */
Dan Fandrichf111b672010-02-04 00:10:30 +0100332 for (q = clist + klist[k]; q->y; q = clist + q->pred)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100333 J[q->x + pref] = q->y + pref;
334 free(klist);
335 free(clist);
336}
337
338struct line {
339 /* 'serial' is not used in the begining, so we reuse it
340 * to store line offsets, thus reducing memory pressure
341 */
342 union {
343 unsigned serial;
344 off_t offset;
345 };
346 unsigned value;
347};
348
349static void equiv(struct line *a, int n, struct line *b, int m, int *c)
350{
351 int i = 1, j = 1;
352
353 while (i <= n && j <= m) {
354 if (a[i].value < b[j].value)
355 a[i++].value = 0;
356 else if (a[i].value == b[j].value)
357 a[i++].value = j;
358 else
359 j++;
360 }
361 while (i <= n)
362 a[i++].value = 0;
363 b[m + 1].value = 0;
364 j = 0;
365 while (++j <= m) {
366 c[j] = -b[j].serial;
367 while (b[j + 1].value == b[j].value) {
368 j++;
369 c[j] = b[j].serial;
370 }
371 }
372 c[j] = -1;
373}
374
375static void unsort(const struct line *f, int l, int *b)
376{
Dan Fandrichf111b672010-02-04 00:10:30 +0100377 int i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100378 int *a = xmalloc((l + 1) * sizeof(a[0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100379 for (i = 1; i <= l; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100380 a[f[i].serial] = f[i].value;
Dan Fandrichf111b672010-02-04 00:10:30 +0100381 for (i = 1; i <= l; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100382 b[i] = a[i];
383 free(a);
384}
385
386static int line_compar(const void *a, const void *b)
387{
388#define l0 ((const struct line*)a)
389#define l1 ((const struct line*)b)
390 int r = l0->value - l1->value;
391 if (r)
392 return r;
393 return l0->serial - l1->serial;
394#undef l0
395#undef l1
396}
397
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100398static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
399{
Dan Fandrichf111b672010-02-04 00:10:30 +0100400 int i, j, col;
401 for (i = a; i <= b; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100402 seek_ft(ft, ix[i - 1]);
403 putchar(ch);
404 if (option_mask32 & FLAG(T))
405 putchar('\t');
Dan Fandrichf111b672010-02-04 00:10:30 +0100406 for (j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100407 int c = fgetc(ft->ft_fp);
408 if (c == EOF) {
409 printf("\n\\ No newline at end of file\n");
410 return;
411 }
412 ft->ft_pos++;
413 if (c == '\t' && (option_mask32 & FLAG(t)))
414 do putchar(' '); while (++col & 7);
415 else {
416 putchar(c);
417 col++;
418 }
419 }
420 }
421}
422
423/* Creates the match vector J, where J[i] is the index
424 * of the line in the new file corresponding to the line i
425 * in the old file. Lines start at 1 instead of 0, that value
426 * being used instead to denote no corresponding line.
427 * This vector is dynamically allocated and must be freed by the caller.
428 *
429 * * fp is an input parameter, where fp[0] and fp[1] are the open
430 * old file and new file respectively.
431 * * nlen is an output variable, where nlen[0] and nlen[1]
432 * gets the number of lines in the old and new file respectively.
433 * * ix is an output variable, where ix[0] and ix[1] gets
434 * assigned dynamically allocated vectors of the offsets of the lines
435 * of the old and new file respectively. These must be freed by the caller.
436 */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100437static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100438{
439 int *J, slen[2], *class, *member;
440 struct line *nfile[2], *sfile[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100441 int pref = 0, suff = 0, i, j, delta;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100442
443 /* Lines of both files are hashed, and in the process
444 * their offsets are stored in the array ix[fileno]
445 * where fileno == 0 points to the old file, and
446 * fileno == 1 points to the new one.
447 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100448 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100449 unsigned hash;
450 token_t tok;
451 size_t sz = 100;
452 nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100453 /* ft gets here without the correct position, cant use seek_ft */
Dan Fandrichf111b672010-02-04 00:10:30 +0100454 ft[i].ft_pos = 0;
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100455 fseeko(ft[i].ft_fp, 0, SEEK_SET);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100456
457 nlen[i] = 0;
458 /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
459 nfile[i][0].offset = 0;
460 goto start; /* saves code */
461 while (1) {
462 tok = read_token(&ft[i], tok);
463 if (!(tok & TOK_EMPTY)) {
464 /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
Denys Vlasenko032bf652010-01-18 05:22:34 +0100465 /*hash = hash * 128 - hash + TOK2CHAR(tok);
466 * gcc insists on optimizing above to "hash * 127 + ...", thus... */
467 unsigned o = hash - TOK2CHAR(tok);
468 hash = hash * 128 - o; /* we want SPEED here */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100469 continue;
470 }
471 if (nlen[i]++ == sz) {
472 sz = sz * 3 / 2;
473 nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
474 }
475 /* line_compar needs hashes fit into positive int */
476 nfile[i][nlen[i]].value = hash & INT_MAX;
477 /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
478 nfile[i][nlen[i]].offset = ft[i].ft_pos;
479 if (tok & TOK_EOF) {
480 /* EOF counts as a token, so we have to adjust it here */
481 nfile[i][nlen[i]].offset++;
482 break;
483 }
484start:
485 hash = tok = 0;
486 }
487 /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
488 if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
489 nlen[i]--;
490 /* Now we copy the line offsets into ix */
491 ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100492 for (j = 0; j < nlen[i] + 1; j++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100493 ix[i][j] = nfile[i][j].offset;
494 }
495
Dan Fandrich1821d182010-02-04 04:04:56 +0100496 /* length of prefix and suffix is calculated */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100497 for (; pref < nlen[0] && pref < nlen[1] &&
498 nfile[0][pref + 1].value == nfile[1][pref + 1].value;
499 pref++);
500 for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
501 nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
502 suff++);
Denys Vlasenko25b47552010-08-30 01:19:47 +0200503 /* Arrays are pruned by the suffix and prefix length,
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100504 * the result being sorted and stored in sfile[fileno],
505 * and their sizes are stored in slen[fileno]
506 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100507 for (j = 0; j < 2; j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100508 sfile[j] = nfile[j] + pref;
509 slen[j] = nlen[j] - pref - suff;
Dan Fandrichf111b672010-02-04 00:10:30 +0100510 for (i = 0; i <= slen[j]; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100511 sfile[j][i].serial = i;
512 qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
513 }
514 /* nfile arrays are reused to reduce memory pressure
515 * The #if zeroed out section performs the same task as the
516 * one in the #else section.
517 * Peak memory usage is higher, but one array copy is avoided
518 * by not using unsort()
519 */
520#if 0
521 member = xmalloc((slen[1] + 2) * sizeof(member[0]));
522 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
523 free(nfile[1]);
524
525 class = xmalloc((slen[0] + 1) * sizeof(class[0]));
Dan Fandrich1821d182010-02-04 04:04:56 +0100526 for (i = 1; i <= slen[0]; i++) /* Unsorting */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100527 class[sfile[0][i].serial] = sfile[0][i].value;
528 free(nfile[0]);
529#else
530 member = (int *)nfile[1];
531 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
532 member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
533
534 class = (int *)nfile[0];
535 unsort(sfile[0], slen[0], (int *)nfile[0]);
536 class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
537#endif
538 J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
539 /* The elements of J which fall inside the prefix and suffix regions
540 * are marked as unchanged, while the ones which fall outside
541 * are initialized with 0 (no matches), so that function stone can
542 * then assign them their right values
543 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100544 for (i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100545 J[i] = i <= pref ? i :
546 i > (nlen[0] - suff) ? (i + delta) : 0;
547 /* Here the magic is performed */
548 stone(class, slen[0], member, J, pref);
549 J[nlen[0] + 1] = nlen[1] + 1;
550
551 free(class);
552 free(member);
553
554 /* Both files are rescanned, in an effort to find any lines
555 * which, due to limitations intrinsic to any hashing algorithm,
556 * are different but ended up confounded as the same
557 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100558 for (i = 1; i <= nlen[0]; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100559 if (!J[i])
560 continue;
561
562 seek_ft(&ft[0], ix[0][i - 1]);
563 seek_ft(&ft[1], ix[1][J[i] - 1]);
564
Dan Fandrichf111b672010-02-04 00:10:30 +0100565 for (j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100566 token_t tok0 = 0, tok1 = 0;
567 do {
568 tok0 = read_token(&ft[0], tok0);
569 tok1 = read_token(&ft[1], tok1);
570
571 if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100572 || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
573 ) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100574 J[i] = 0; /* Break the correspondence */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100575 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100576 } while (!(tok0 & tok1 & TOK_EMPTY));
577 }
578 }
579
580 return J;
581}
582
Matheus Izvekov404f1442010-01-18 22:21:40 -0200583static bool diff(FILE* fp[2], char *file[2])
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100584{
585 int nlen[2];
586 off_t *ix[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100587 FILE_and_pos_t ft[2];
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200588 typedef struct { int a, b; } vec_t[2];
589 vec_t *vec = NULL;
Dan Fandrich1821d182010-02-04 04:04:56 +0100590 int i = 1, j, k, idx = -1;
Dan Fandrichf111b672010-02-04 00:10:30 +0100591 bool anychange = false;
592 int *J;
593
594 ft[0].ft_fp = fp[0];
595 ft[1].ft_fp = fp[1];
596 /* note that ft[i].ft_pos is unintitalized, create_J()
597 * must not assume otherwise */
598 J = create_J(ft, nlen, ix);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100599
600 do {
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200601 bool nonempty = false;
602
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100603 while (1) {
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200604 vec_t v;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100605
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200606 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 +0100607 continue;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200608 v[1].a = J[v[0].a - 1] + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100609
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200610 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 +0100611 continue;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200612 v[1].b = J[v[0].b + 1] - 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100613 /*
614 * Indicate that there is a difference between lines a and b of the 'from' file
615 * to get to lines c to d of the 'to' file. If a is greater than b then there
616 * are no lines in the 'from' file involved and this means that there were
617 * lines appended (beginning at b). If c is greater than d then there are
618 * lines missing from the 'to' file.
619 */
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200620 if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100621 /*
622 * If this change is more than 'context' lines from the
623 * previous change, dump the record and reset it.
624 */
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200625 int ct = (2 * opt_U_context) + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100626 if (idx >= 0
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200627 && v[0].a > vec[idx][0].b + ct
628 && v[1].a > vec[idx][1].b + ct
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100629 ) {
630 break;
631 }
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200632
Dan Fandrich1821d182010-02-04 04:04:56 +0100633 for (j = 0; j < 2; j++)
634 for (k = v[j].a; k < v[j].b; k++)
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200635 nonempty |= (ix[j][k+1] - ix[j][k] != 1);
636
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100637 vec = xrealloc_vector(vec, 6, ++idx);
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200638 memcpy(vec[idx], v, sizeof(v));
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100639 }
640
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200641 i = v[0].b + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100642 if (i > nlen[0])
643 break;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200644 J[v[0].b] = v[1].b;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100645 }
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200646 if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
647 goto cont;
648 if (!(option_mask32 & FLAG(q))) {
Dan Fandrich1821d182010-02-04 04:04:56 +0100649 int lowa;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200650 vec_t span, *cvp = vec;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100651
652 if (!anychange) {
653 /* Print the context/unidiff header first time through */
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100654 printf("--- %s\n", label[0] ? label[0] : file[0]);
655 printf("+++ %s\n", label[1] ? label[1] : file[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100656 }
657
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200658 printf("@@");
Dan Fandrich1821d182010-02-04 04:04:56 +0100659 for (j = 0; j < 2; j++) {
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200660 int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
661 int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100662
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200663 printf(" %c%d", j ? '+' : '-', MIN(a, b));
664 if (a == b)
665 continue;
666 printf(",%d", (a < b) ? b - a + 1 : 0);
667 }
668 printf(" @@\n");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100669 /*
670 * Output changes in "unified" diff format--the old and new lines
671 * are printed together.
672 */
Dan Fandrich1821d182010-02-04 04:04:56 +0100673 for (lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100674 bool end = cvp > &vec[idx];
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200675 fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100676 if (end)
677 break;
Dan Fandrich1821d182010-02-04 04:04:56 +0100678 for (j = 0; j < 2; j++)
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200679 fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100680 }
681 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100682 anychange = true;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200683 cont:
684 idx = -1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100685 } while (i <= nlen[0]);
686
687 free(vec);
688 free(ix[0]);
689 free(ix[1]);
690 free(J);
691 return anychange;
692}
693
694static int diffreg(char *file[2])
695{
Denys Vlasenko14bd16a2011-07-08 08:49:40 +0200696 FILE *fp[2];
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100697 bool binary = false, differ = false;
Dan Fandrichf111b672010-02-04 00:10:30 +0100698 int status = STATUS_SAME, i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100699
Denys Vlasenko14bd16a2011-07-08 08:49:40 +0200700 fp[0] = stdin;
701 fp[1] = stdin;
Dan Fandrichf111b672010-02-04 00:10:30 +0100702 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100703 int fd = open_or_warn_stdin(file[i]);
704 if (fd == -1)
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200705 goto out;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100706 /* Our diff implementation is using seek.
707 * When we meet non-seekable file, we must make a temp copy.
708 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100709 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
710 char name[] = "/tmp/difXXXXXX";
Alexander Shishkin67227372010-10-22 13:27:16 +0200711 int fd_tmp = xmkstemp(name);
712
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100713 unlink(name);
Matheus Izvekov404f1442010-01-18 22:21:40 -0200714 if (bb_copyfd_eof(fd, fd_tmp) < 0)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100715 xfunc_die();
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100716 if (fd) /* Prevents closing of stdin */
717 close(fd);
718 fd = fd_tmp;
719 }
Matheus Izvekov404f1442010-01-18 22:21:40 -0200720 fp[i] = fdopen(fd, "r");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100721 }
722
723 while (1) {
724 const size_t sz = COMMON_BUFSIZE / 2;
725 char *const buf0 = bb_common_bufsiz1;
726 char *const buf1 = buf0 + sz;
Dan Fandrichf111b672010-02-04 00:10:30 +0100727 int j, k;
Matheus Izvekov404f1442010-01-18 22:21:40 -0200728 i = fread(buf0, 1, sz, fp[0]);
729 j = fread(buf1, 1, sz, fp[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100730 if (i != j) {
731 differ = true;
732 i = MIN(i, j);
733 }
734 if (i == 0)
735 break;
Dan Fandrichf111b672010-02-04 00:10:30 +0100736 for (k = 0; k < i; k++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100737 if (!buf0[k] || !buf1[k])
738 binary = true;
739 if (buf0[k] != buf1[k])
740 differ = true;
741 }
742 }
743 if (differ) {
744 if (binary && !(option_mask32 & FLAG(a)))
745 status = STATUS_BINARY;
Matheus Izvekov404f1442010-01-18 22:21:40 -0200746 else if (diff(fp, file))
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100747 status = STATUS_DIFFER;
748 }
749 if (status != STATUS_SAME)
750 exit_status |= 1;
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200751out:
Matheus Izvekov404f1442010-01-18 22:21:40 -0200752 fclose_if_not_stdin(fp[0]);
753 fclose_if_not_stdin(fp[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100754
755 return status;
756}
757
758static void print_status(int status, char *path[2])
759{
760 switch (status) {
761 case STATUS_BINARY:
762 case STATUS_DIFFER:
763 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
764 printf("Files %s and %s differ\n", path[0], path[1]);
765 break;
766 case STATUS_SAME:
767 if (option_mask32 & FLAG(s))
768 printf("Files %s and %s are identical\n", path[0], path[1]);
769 break;
770 }
771}
Denis Vlasenko6a1d6612006-12-16 22:18:44 +0000772
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +0000773#if ENABLE_FEATURE_DIFF_DIR
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100774struct dlist {
775 size_t len;
776 int s, e;
777 char **dl;
778};
779
Denis Vlasenko6a1d6612006-12-16 22:18:44 +0000780/* This function adds a filename to dl, the directory listing. */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000781static int FAST_FUNC add_to_dirlist(const char *filename,
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000782 struct stat *sb UNUSED_PARAM,
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100783 void *userdata, int depth UNUSED_PARAM)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000784{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100785 struct dlist *const l = userdata;
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200786 const char *file = filename + l->len;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200787 while (*file == '/')
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200788 file++;
Denys Vlasenko32a6bae2010-07-09 19:44:38 +0200789 l->dl = xrealloc_vector(l->dl, 6, l->e);
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200790 l->dl[l->e] = xstrdup(file);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100791 l->e++;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000792 return TRUE;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000793}
794
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100795/* If recursion is not set, this function adds the directory
796 * to the list and prevents recursive_action from recursing into it.
797 */
798static int FAST_FUNC skip_dir(const char *filename,
799 struct stat *sb, void *userdata,
800 int depth)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000801{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100802 if (!(option_mask32 & FLAG(r)) && depth) {
803 add_to_dirlist(filename, sb, userdata, depth);
804 return SKIP;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000805 }
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200806 if (!(option_mask32 & FLAG(N))) {
807 /* -r without -N: no need to recurse into dirs
808 * which do not exist on the "other side".
809 * Testcase: diff -r /tmp /
810 * (it would recurse deep into /proc without this code) */
811 struct dlist *const l = userdata;
812 filename += l->len;
813 if (filename[0]) {
814 struct stat osb;
815 char *othername = concat_path_file(G.other_dir, filename);
816 int r = stat(othername, &osb);
817 free(othername);
818 if (r != 0 || !S_ISDIR(osb.st_mode)) {
819 /* other dir doesn't have similarly named
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200820 * directory, don't recurse; return 1 upon
821 * exit, just like diffutils' diff */
822 exit_status |= 1;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200823 return SKIP;
824 }
825 }
826 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100827 return TRUE;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000828}
829
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100830static void diffdir(char *p[2], const char *s_start)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000831{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100832 struct dlist list[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100833 int i;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000834
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100835 memset(&list, 0, sizeof(list));
Dan Fandrichf111b672010-02-04 00:10:30 +0100836 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100837 /*list[i].s = list[i].e = 0; - memset did it */
838 /*list[i].dl = NULL; */
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000839
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200840 G.other_dir = p[1 - i];
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100841 /* We need to trim root directory prefix.
842 * Using list.len to specify its length,
843 * add_to_dirlist will remove it. */
844 list[i].len = strlen(p[i]);
845 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
846 add_to_dirlist, skip_dir, &list[i], 0);
847 /* Sort dl alphabetically.
848 * GNU diff does this ignoring any number of trailing dots.
849 * We don't, so for us dotted files almost always are
850 * first on the list.
851 */
852 qsort_string_vector(list[i].dl, list[i].e);
853 /* If -S was set, find the starting point. */
854 if (!s_start)
855 continue;
856 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
857 list[i].s++;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000858 }
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000859 /* Now that both dirlist1 and dirlist2 contain sorted directory
860 * listings, we can start to go through dirlist1. If both listings
861 * contain the same file, then do a normal diff. Otherwise, behaviour
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000862 * is determined by whether the -N flag is set. */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100863 while (1) {
864 char *dp[2];
865 int pos;
866 int k;
867
868 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
869 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
870 if (!dp[0] && !dp[1])
871 break;
872 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
873 k = pos > 0;
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200874 if (pos && !(option_mask32 & FLAG(N))) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100875 printf("Only in %s: %s\n", p[k], dp[k]);
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200876 exit_status |= 1;
877 } else {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100878 char *fullpath[2], *path[2]; /* if -N */
879
Dan Fandrichf111b672010-02-04 00:10:30 +0100880 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100881 if (pos == 0 || i == k) {
882 path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
883 stat(fullpath[i], &stb[i]);
884 } else {
885 fullpath[i] = concat_path_file(p[i], dp[1 - i]);
886 path[i] = (char *)bb_dev_null;
887 }
888 }
889 if (pos)
890 stat(fullpath[k], &stb[1 - k]);
891
892 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
893 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
894 else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
895 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
896 else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
897 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
898 else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
899 if (S_ISDIR(stb[0].st_mode))
900 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
901 else
902 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
903 } else
904 print_status(diffreg(path), fullpath);
905
906 free(fullpath[0]);
907 free(fullpath[1]);
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000908 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100909 free(dp[k]);
910 list[k].s++;
911 if (pos == 0) {
912 free(dp[1 - k]);
913 list[1 - k].s++;
914 }
915 }
916 if (ENABLE_FEATURE_CLEAN_UP) {
917 free(list[0].dl);
918 free(list[1].dl);
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000919 }
920}
921#endif
922
Matheus Izvekovb32aa0c2010-01-18 18:40:02 -0200923#if ENABLE_FEATURE_DIFF_LONG_OPTIONS
924static const char diff_longopts[] ALIGN1 =
925 "ignore-case\0" No_argument "i"
926 "ignore-tab-expansion\0" No_argument "E"
927 "ignore-space-change\0" No_argument "b"
928 "ignore-all-space\0" No_argument "w"
929 "ignore-blank-lines\0" No_argument "B"
930 "text\0" No_argument "a"
931 "unified\0" Required_argument "U"
932 "label\0" Required_argument "L"
933 "show-c-function\0" No_argument "p"
934 "brief\0" No_argument "q"
935 "expand-tabs\0" No_argument "t"
936 "initial-tab\0" No_argument "T"
937 "recursive\0" No_argument "r"
938 "new-file\0" No_argument "N"
939 "report-identical-files\0" No_argument "s"
940 "starting-file\0" Required_argument "S"
941 "minimal\0" No_argument "d"
942 ;
943#endif
944
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +0000945int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000946int diff_main(int argc UNUSED_PARAM, char **argv)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000947{
Dan Fandrichf111b672010-02-04 00:10:30 +0100948 int gotstdin = 0, i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100949 char *file[2], *s_start = NULL;
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +0000950 llist_t *L_arg = NULL;
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000951
Denis Vlasenkoef4bb262007-06-04 12:21:53 +0000952 INIT_G();
953
Denis Vlasenko1d426652008-03-17 09:09:09 +0000954 /* exactly 2 params; collect multiple -L <label>; -U N */
955 opt_complementary = "=2:L::U+";
Matheus Izvekovb32aa0c2010-01-18 18:40:02 -0200956#if ENABLE_FEATURE_DIFF_LONG_OPTIONS
957 applet_long_options = diff_longopts;
958#endif
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200959 getopt32(argv, "abdiL:NqrsS:tTU:wupBE",
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100960 &L_arg, &s_start, &opt_U_context);
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000961 argv += optind;
Matheus Izvekov4de4cb62010-01-18 20:40:23 -0200962 while (L_arg)
963 label[!!label[0]] = llist_pop(&L_arg);
Denys Vlasenko38d90722009-06-09 12:55:13 +0200964 xfunc_error_retval = 2;
Dan Fandrichf111b672010-02-04 00:10:30 +0100965 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100966 file[i] = argv[i];
967 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
968 if (LONE_DASH(file[i])) {
969 fstat(STDIN_FILENO, &stb[i]);
970 gotstdin++;
971 } else
972 xstat(file[i], &stb[i]);
973 }
Denys Vlasenko38d90722009-06-09 12:55:13 +0200974 xfunc_error_retval = 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100975 if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
Denis Vlasenko04211fd2008-03-24 14:44:59 +0000976 bb_error_msg_and_die("can't compare stdin to a directory");
977
Roman Borisov95f5c522011-03-27 23:24:09 +0200978 /* Compare metadata to check if the files are the same physical file.
979 *
980 * Comment from diffutils source says:
981 * POSIX says that two files are identical if st_ino and st_dev are
982 * the same, but many file systems incorrectly assign the same (device,
983 * inode) pair to two distinct files, including:
984 * GNU/Linux NFS servers that export all local file systems as a
985 * single NFS file system, if a local device number (st_dev) exceeds
986 * 255, or if a local inode number (st_ino) exceeds 16777215.
987 */
988 if (ENABLE_DESKTOP
989 && stb[0].st_ino == stb[1].st_ino
990 && stb[0].st_dev == stb[1].st_dev
991 && stb[0].st_size == stb[1].st_size
992 && stb[0].st_mtime == stb[1].st_mtime
993 && stb[0].st_ctime == stb[1].st_ctime
994 && stb[0].st_mode == stb[1].st_mode
995 && stb[0].st_nlink == stb[1].st_nlink
996 && stb[0].st_uid == stb[1].st_uid
997 && stb[0].st_gid == stb[1].st_gid
998 ) {
999 /* files are physically the same; no need to compare them */
1000 return STATUS_SAME;
1001 }
1002
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001003 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +00001004#if ENABLE_FEATURE_DIFF_DIR
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001005 diffdir(file, s_start);
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001006#else
Denis Vlasenko04211fd2008-03-24 14:44:59 +00001007 bb_error_msg_and_die("no support for directory comparison");
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001008#endif
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001009 } else {
1010 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
1011 bool dir = S_ISDIR(stb[1].st_mode);
1012 if (dirfile) {
1013 const char *slash = strrchr(file[!dir], '/');
1014 file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
1015 xstat(file[dir], &stb[dir]);
1016 }
1017 /* diffreg can get non-regular files here */
1018 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
1019
1020 if (dirfile)
1021 free(file[dir]);
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001022 }
Denis Vlasenko04211fd2008-03-24 14:44:59 +00001023
Denis Vlasenko7fe0eba2008-03-24 16:19:21 +00001024 return exit_status;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001025}