blob: 3304edb26f9a4c7703ceb1e3a262526b5c685de9 [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
Denys Vlasenko73225b62013-11-13 12:45:33 +010079//config:config DIFF
80//config: bool "diff"
81//config: default y
82//config: help
83//config: diff compares two files or directories and outputs the
84//config: differences between them in a form that can be given to
85//config: the patch command.
86//config:
87//config:config FEATURE_DIFF_LONG_OPTIONS
88//config: bool "Enable long options"
89//config: default y
90//config: depends on DIFF && LONG_OPTS
Denys Vlasenko73225b62013-11-13 12:45:33 +010091//config:
92//config:config FEATURE_DIFF_DIR
93//config: bool "Enable directory support"
94//config: default y
95//config: depends on DIFF
96//config: help
97//config: This option enables support for directory and subdirectory
98//config: comparison.
99
100//kbuild:lib-$(CONFIG_DIFF) += diff.o
101
102//applet:IF_DIFF(APPLET(diff, BB_DIR_USR_BIN, BB_SUID_DROP))
103
Pere Orga6a3e01d2011-04-01 22:56:30 +0200104//usage:#define diff_trivial_usage
105//usage: "[-abBdiNqrTstw] [-L LABEL] [-S FILE] [-U LINES] FILE1 FILE2"
106//usage:#define diff_full_usage "\n\n"
107//usage: "Compare files line by line and output the differences between them.\n"
108//usage: "This implementation supports unified diffs only.\n"
Pere Orga6a3e01d2011-04-01 22:56:30 +0200109//usage: "\n -a Treat all files as text"
110//usage: "\n -b Ignore changes in the amount of whitespace"
111//usage: "\n -B Ignore changes whose lines are all blank"
112//usage: "\n -d Try hard to find a smaller set of changes"
113//usage: "\n -i Ignore case differences"
114//usage: "\n -L Use LABEL instead of the filename in the unified header"
115//usage: "\n -N Treat absent files as empty"
116//usage: "\n -q Output only whether files differ"
117//usage: "\n -r Recurse"
118//usage: "\n -S Start with FILE when comparing directories"
119//usage: "\n -T Make tabs line up by prefixing a tab when necessary"
120//usage: "\n -s Report when two files are the same"
121//usage: "\n -t Expand tabs to spaces in output"
122//usage: "\n -U Output LINES lines of context"
123//usage: "\n -w Ignore all whitespace"
124
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100125#include "libbb.h"
Denys Vlasenkoe6a2f4c2016-04-21 16:26:30 +0200126#include "common_bufsiz.h"
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000127
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100128#if 0
Denys Vlasenkod616ab62011-05-22 03:46:33 +0200129# define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100130#else
Denys Vlasenkod616ab62011-05-22 03:46:33 +0200131# define dbg_error_msg(...) ((void)0)
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000132#endif
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000133
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200134enum { /* print_status() and diffreg() return values */
135 STATUS_SAME, /* files are the same */
136 STATUS_DIFFER, /* files differ */
137 STATUS_BINARY, /* binary files differ */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100138};
139
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200140enum { /* Commandline flags */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100141 FLAG_a,
142 FLAG_b,
143 FLAG_d,
Matheus Izvekovb7a04402010-01-18 14:25:46 -0200144 FLAG_i,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200145 FLAG_L, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100146 FLAG_N,
147 FLAG_q,
148 FLAG_r,
149 FLAG_s,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200150 FLAG_S, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100151 FLAG_t,
152 FLAG_T,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200153 FLAG_U, /* never used, handled by getopt32 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100154 FLAG_w,
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200155 FLAG_u, /* ignored, this is the default */
156 FLAG_p, /* not implemented */
157 FLAG_B,
158 FLAG_E, /* not implemented */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100159};
160#define FLAG(x) (1 << FLAG_##x)
161
162/* We cache file position to avoid excessive seeking */
163typedef struct FILE_and_pos_t {
164 FILE *ft_fp;
165 off_t ft_pos;
166} FILE_and_pos_t;
167
168struct globals {
169 smallint exit_status;
170 int opt_U_context;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200171 const char *other_dir;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100172 char *label[2];
173 struct stat stb[2];
174};
175#define G (*ptr_to_globals)
176#define exit_status (G.exit_status )
177#define opt_U_context (G.opt_U_context )
178#define label (G.label )
179#define stb (G.stb )
180#define INIT_G() do { \
181 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
182 opt_U_context = 3; \
183} while (0)
184
185typedef int token_t;
186
187enum {
188 /* Public */
189 TOK_EMPTY = 1 << 9, /* Line fully processed, you can proceed to the next */
190 TOK_EOF = 1 << 10, /* File ended */
191 /* Private (Only to be used by read_token() */
192 TOK_EOL = 1 << 11, /* we saw EOL (sticky) */
193 TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
194 SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
195 CHAR_MASK = 0x1ff, /* 8th bit is used to distinguish EOF from 0xff */
196};
197
198/* Restores full EOF from one 8th bit: */
199//#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
200/* We don't really need the above, we only need to have EOF != any_real_char: */
201#define TOK2CHAR(t) ((t) & CHAR_MASK)
202
203static void seek_ft(FILE_and_pos_t *ft, off_t pos)
204{
205 if (ft->ft_pos != pos) {
206 ft->ft_pos = pos;
207 fseeko(ft->ft_fp, pos, SEEK_SET);
208 }
209}
210
211/* Reads tokens from given fp, handling -b and -w flags
212 * The user must reset tok every line start
213 */
214static int read_token(FILE_and_pos_t *ft, token_t tok)
215{
216 tok |= TOK_EMPTY;
217 while (!(tok & TOK_EOL)) {
218 bool is_space;
219 int t;
220
221 t = fgetc(ft->ft_fp);
222 if (t != EOF)
223 ft->ft_pos++;
224 is_space = (t == EOF || isspace(t));
225
226 /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
227 tok |= (t & (TOK_EOF + TOK_EOL));
228 /* Only EOL? */
229 if (t == '\n')
230 tok |= TOK_EOL;
231
Matheus Izvekovb7a04402010-01-18 14:25:46 -0200232 if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
233 t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
234
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100235 if ((option_mask32 & FLAG(w)) && is_space)
236 continue;
237
238 /* Trim char value to low 9 bits */
239 t &= CHAR_MASK;
240
241 if (option_mask32 & FLAG(b)) {
242 /* Was prev char whitespace? */
243 if (tok & TOK_SPACE) { /* yes */
244 if (is_space) /* this one too, ignore it */
245 continue;
246 tok &= ~TOK_SPACE;
247 } else if (is_space) {
248 /* 1st whitespace char.
249 * Set TOK_SPACE and replace char by ' ' */
250 t = TOK_SPACE + ' ';
251 }
252 }
253 /* Clear EMPTY */
254 tok &= ~(TOK_EMPTY + CHAR_MASK);
255 /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
256 tok |= t;
257 break;
258 }
259#if 0
260 bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
261 , tok & TOK_EOF ? " EOF" : ""
262 , tok & TOK_EOL ? " EOL" : ""
263 , tok & TOK_EMPTY ? " EMPTY" : ""
264 , tok & TOK_SPACE ? " SPACE" : ""
265 );
266#endif
267 return tok;
268}
269
270struct cand {
271 int x;
272 int y;
273 int pred;
274};
275
276static int search(const int *c, int k, int y, const struct cand *list)
277{
Dan Fandrichf111b672010-02-04 00:10:30 +0100278 int i, j;
279
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200280 if (list[c[k]].y < y) /* quick look for typical case */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100281 return k + 1;
282
Dan Fandrichf111b672010-02-04 00:10:30 +0100283 for (i = 0, j = k + 1;;) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100284 const int l = (i + j) >> 1;
285 if (l > i) {
286 const int t = list[c[l]].y;
287 if (t > y)
288 j = l;
289 else if (t < y)
290 i = l;
291 else
292 return l;
293 } else
294 return l + 1;
295 }
296}
297
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100298static void stone(const int *a, int n, const int *b, int *J, int pref)
299{
300 const unsigned isq = isqrt(n);
301 const unsigned bound =
302 (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
303 int clen = 1;
304 int clistlen = 100;
305 int k = 0;
306 struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100307 struct cand cand;
308 struct cand *q;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100309 int *klist = xzalloc((n + 2) * sizeof(klist[0]));
310 /*clist[0] = (struct cand){0}; - xzalloc did it */
311 /*klist[0] = 0; */
312
Dan Fandrichf111b672010-02-04 00:10:30 +0100313 for (cand.x = 1; cand.x <= n; cand.x++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100314 int j = a[cand.x], oldl = 0;
315 unsigned numtries = 0;
316 if (j == 0)
317 continue;
318 cand.y = -b[j];
319 cand.pred = klist[0];
320 do {
321 int l, tc;
322 if (cand.y <= clist[cand.pred].y)
323 continue;
324 l = search(klist, k, cand.y, clist);
325 if (l != oldl + 1)
326 cand.pred = klist[l - 1];
327 if (l <= k && clist[klist[l]].y <= cand.y)
328 continue;
329 if (clen == clistlen) {
330 clistlen = clistlen * 11 / 10;
331 clist = xrealloc(clist, clistlen * sizeof(clist[0]));
332 }
333 clist[clen] = cand;
334 tc = klist[l];
335 klist[l] = clen++;
336 if (l <= k) {
337 cand.pred = tc;
338 oldl = l;
339 numtries++;
340 } else {
341 k++;
342 break;
343 }
344 } while ((cand.y = b[++j]) > 0 && numtries < bound);
345 }
346 /* Unravel */
Dan Fandrichf111b672010-02-04 00:10:30 +0100347 for (q = clist + klist[k]; q->y; q = clist + q->pred)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100348 J[q->x + pref] = q->y + pref;
349 free(klist);
350 free(clist);
351}
352
353struct line {
Maninder Singh97c64912015-05-25 13:46:36 +0200354 /* 'serial' is not used in the beginning, so we reuse it
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100355 * to store line offsets, thus reducing memory pressure
356 */
357 union {
358 unsigned serial;
359 off_t offset;
360 };
361 unsigned value;
362};
363
364static void equiv(struct line *a, int n, struct line *b, int m, int *c)
365{
366 int i = 1, j = 1;
367
368 while (i <= n && j <= m) {
369 if (a[i].value < b[j].value)
370 a[i++].value = 0;
371 else if (a[i].value == b[j].value)
372 a[i++].value = j;
373 else
374 j++;
375 }
376 while (i <= n)
377 a[i++].value = 0;
378 b[m + 1].value = 0;
379 j = 0;
380 while (++j <= m) {
381 c[j] = -b[j].serial;
382 while (b[j + 1].value == b[j].value) {
383 j++;
384 c[j] = b[j].serial;
385 }
386 }
387 c[j] = -1;
388}
389
390static void unsort(const struct line *f, int l, int *b)
391{
Dan Fandrichf111b672010-02-04 00:10:30 +0100392 int i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100393 int *a = xmalloc((l + 1) * sizeof(a[0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100394 for (i = 1; i <= l; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100395 a[f[i].serial] = f[i].value;
Dan Fandrichf111b672010-02-04 00:10:30 +0100396 for (i = 1; i <= l; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100397 b[i] = a[i];
398 free(a);
399}
400
401static int line_compar(const void *a, const void *b)
402{
403#define l0 ((const struct line*)a)
404#define l1 ((const struct line*)b)
405 int r = l0->value - l1->value;
406 if (r)
407 return r;
408 return l0->serial - l1->serial;
409#undef l0
410#undef l1
411}
412
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100413static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
414{
Dan Fandrichf111b672010-02-04 00:10:30 +0100415 int i, j, col;
416 for (i = a; i <= b; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100417 seek_ft(ft, ix[i - 1]);
418 putchar(ch);
419 if (option_mask32 & FLAG(T))
420 putchar('\t');
Dan Fandrichf111b672010-02-04 00:10:30 +0100421 for (j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100422 int c = fgetc(ft->ft_fp);
423 if (c == EOF) {
Denys Vlasenkod60752f2015-10-07 22:42:45 +0200424 puts("\n\\ No newline at end of file");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100425 return;
426 }
427 ft->ft_pos++;
428 if (c == '\t' && (option_mask32 & FLAG(t)))
429 do putchar(' '); while (++col & 7);
430 else {
431 putchar(c);
432 col++;
433 }
434 }
435 }
436}
437
438/* Creates the match vector J, where J[i] is the index
439 * of the line in the new file corresponding to the line i
440 * in the old file. Lines start at 1 instead of 0, that value
441 * being used instead to denote no corresponding line.
442 * This vector is dynamically allocated and must be freed by the caller.
443 *
444 * * fp is an input parameter, where fp[0] and fp[1] are the open
445 * old file and new file respectively.
446 * * nlen is an output variable, where nlen[0] and nlen[1]
447 * gets the number of lines in the old and new file respectively.
448 * * ix is an output variable, where ix[0] and ix[1] gets
449 * assigned dynamically allocated vectors of the offsets of the lines
450 * of the old and new file respectively. These must be freed by the caller.
451 */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100452static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100453{
454 int *J, slen[2], *class, *member;
455 struct line *nfile[2], *sfile[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100456 int pref = 0, suff = 0, i, j, delta;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100457
458 /* Lines of both files are hashed, and in the process
459 * their offsets are stored in the array ix[fileno]
460 * where fileno == 0 points to the old file, and
461 * fileno == 1 points to the new one.
462 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100463 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100464 unsigned hash;
465 token_t tok;
466 size_t sz = 100;
467 nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100468 /* ft gets here without the correct position, cant use seek_ft */
Dan Fandrichf111b672010-02-04 00:10:30 +0100469 ft[i].ft_pos = 0;
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100470 fseeko(ft[i].ft_fp, 0, SEEK_SET);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100471
472 nlen[i] = 0;
473 /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
474 nfile[i][0].offset = 0;
475 goto start; /* saves code */
476 while (1) {
477 tok = read_token(&ft[i], tok);
478 if (!(tok & TOK_EMPTY)) {
479 /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
Denys Vlasenko032bf652010-01-18 05:22:34 +0100480 /*hash = hash * 128 - hash + TOK2CHAR(tok);
481 * gcc insists on optimizing above to "hash * 127 + ...", thus... */
482 unsigned o = hash - TOK2CHAR(tok);
483 hash = hash * 128 - o; /* we want SPEED here */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100484 continue;
485 }
486 if (nlen[i]++ == sz) {
487 sz = sz * 3 / 2;
488 nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
489 }
490 /* line_compar needs hashes fit into positive int */
491 nfile[i][nlen[i]].value = hash & INT_MAX;
492 /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
493 nfile[i][nlen[i]].offset = ft[i].ft_pos;
494 if (tok & TOK_EOF) {
495 /* EOF counts as a token, so we have to adjust it here */
496 nfile[i][nlen[i]].offset++;
497 break;
498 }
499start:
500 hash = tok = 0;
501 }
502 /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
503 if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
504 nlen[i]--;
505 /* Now we copy the line offsets into ix */
506 ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
Dan Fandrichf111b672010-02-04 00:10:30 +0100507 for (j = 0; j < nlen[i] + 1; j++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100508 ix[i][j] = nfile[i][j].offset;
509 }
510
Dan Fandrich1821d182010-02-04 04:04:56 +0100511 /* length of prefix and suffix is calculated */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100512 for (; pref < nlen[0] && pref < nlen[1] &&
513 nfile[0][pref + 1].value == nfile[1][pref + 1].value;
514 pref++);
515 for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
516 nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
517 suff++);
Denys Vlasenko25b47552010-08-30 01:19:47 +0200518 /* Arrays are pruned by the suffix and prefix length,
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100519 * the result being sorted and stored in sfile[fileno],
520 * and their sizes are stored in slen[fileno]
521 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100522 for (j = 0; j < 2; j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100523 sfile[j] = nfile[j] + pref;
524 slen[j] = nlen[j] - pref - suff;
Dan Fandrichf111b672010-02-04 00:10:30 +0100525 for (i = 0; i <= slen[j]; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100526 sfile[j][i].serial = i;
527 qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
528 }
529 /* nfile arrays are reused to reduce memory pressure
530 * The #if zeroed out section performs the same task as the
531 * one in the #else section.
532 * Peak memory usage is higher, but one array copy is avoided
533 * by not using unsort()
534 */
535#if 0
536 member = xmalloc((slen[1] + 2) * sizeof(member[0]));
537 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
538 free(nfile[1]);
539
540 class = xmalloc((slen[0] + 1) * sizeof(class[0]));
Dan Fandrich1821d182010-02-04 04:04:56 +0100541 for (i = 1; i <= slen[0]; i++) /* Unsorting */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100542 class[sfile[0][i].serial] = sfile[0][i].value;
543 free(nfile[0]);
544#else
545 member = (int *)nfile[1];
546 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
547 member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
548
549 class = (int *)nfile[0];
550 unsort(sfile[0], slen[0], (int *)nfile[0]);
551 class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
552#endif
553 J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
554 /* The elements of J which fall inside the prefix and suffix regions
555 * are marked as unchanged, while the ones which fall outside
556 * are initialized with 0 (no matches), so that function stone can
557 * then assign them their right values
558 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100559 for (i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100560 J[i] = i <= pref ? i :
561 i > (nlen[0] - suff) ? (i + delta) : 0;
562 /* Here the magic is performed */
563 stone(class, slen[0], member, J, pref);
564 J[nlen[0] + 1] = nlen[1] + 1;
565
566 free(class);
567 free(member);
568
569 /* Both files are rescanned, in an effort to find any lines
570 * which, due to limitations intrinsic to any hashing algorithm,
571 * are different but ended up confounded as the same
572 */
Dan Fandrichf111b672010-02-04 00:10:30 +0100573 for (i = 1; i <= nlen[0]; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100574 if (!J[i])
575 continue;
576
577 seek_ft(&ft[0], ix[0][i - 1]);
578 seek_ft(&ft[1], ix[1][J[i] - 1]);
579
Dan Fandrichf111b672010-02-04 00:10:30 +0100580 for (j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100581 token_t tok0 = 0, tok1 = 0;
582 do {
583 tok0 = read_token(&ft[0], tok0);
584 tok1 = read_token(&ft[1], tok1);
585
586 if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100587 || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
588 ) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100589 J[i] = 0; /* Break the correspondence */
Denys Vlasenko9e0879a2010-01-18 06:15:57 +0100590 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100591 } while (!(tok0 & tok1 & TOK_EMPTY));
592 }
593 }
594
595 return J;
596}
597
Matheus Izvekov404f1442010-01-18 22:21:40 -0200598static bool diff(FILE* fp[2], char *file[2])
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100599{
600 int nlen[2];
601 off_t *ix[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100602 FILE_and_pos_t ft[2];
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200603 typedef struct { int a, b; } vec_t[2];
604 vec_t *vec = NULL;
Dan Fandrich1821d182010-02-04 04:04:56 +0100605 int i = 1, j, k, idx = -1;
Dan Fandrichf111b672010-02-04 00:10:30 +0100606 bool anychange = false;
607 int *J;
608
609 ft[0].ft_fp = fp[0];
610 ft[1].ft_fp = fp[1];
611 /* note that ft[i].ft_pos is unintitalized, create_J()
612 * must not assume otherwise */
613 J = create_J(ft, nlen, ix);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100614
615 do {
Matheus Izvekovfe1ce2e2010-01-18 16:07:07 -0200616 bool nonempty = false;
617
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100618 while (1) {
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200619 vec_t v;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100620
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200621 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 +0100622 continue;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200623 v[1].a = J[v[0].a - 1] + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100624
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200625 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 +0100626 continue;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200627 v[1].b = J[v[0].b + 1] - 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100628 /*
629 * Indicate that there is a difference between lines a and b of the 'from' file
630 * to get to lines c to d of the 'to' file. If a is greater than b then there
631 * are no lines in the 'from' file involved and this means that there were
632 * lines appended (beginning at b). If c is greater than d then there are
633 * lines missing from the 'to' file.
634 */
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200635 if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100636 /*
637 * If this change is more than 'context' lines from the
638 * previous change, dump the record and reset it.
639 */
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200640 int ct = (2 * opt_U_context) + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100641 if (idx >= 0
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200642 && v[0].a > vec[idx][0].b + ct
643 && v[1].a > vec[idx][1].b + ct
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100644 ) {
645 break;
646 }
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200647
Dan Fandrich1821d182010-02-04 04:04:56 +0100648 for (j = 0; j < 2; j++)
Aaro Koskinena47fcca2015-07-30 23:13:25 +0300649 for (k = v[j].a; k <= v[j].b; k++)
650 nonempty |= (ix[j][k] - ix[j][k - 1] != 1);
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200651
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100652 vec = xrealloc_vector(vec, 6, ++idx);
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200653 memcpy(vec[idx], v, sizeof(v));
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100654 }
655
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200656 i = v[0].b + 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100657 if (i > nlen[0])
658 break;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200659 J[v[0].b] = v[1].b;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100660 }
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200661 if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
662 goto cont;
663 if (!(option_mask32 & FLAG(q))) {
Dan Fandrich1821d182010-02-04 04:04:56 +0100664 int lowa;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200665 vec_t span, *cvp = vec;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100666
667 if (!anychange) {
668 /* Print the context/unidiff header first time through */
Denys Vlasenko94ca6942010-01-20 02:51:09 +0100669 printf("--- %s\n", label[0] ? label[0] : file[0]);
670 printf("+++ %s\n", label[1] ? label[1] : file[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100671 }
672
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200673 printf("@@");
Dan Fandrich1821d182010-02-04 04:04:56 +0100674 for (j = 0; j < 2; j++) {
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200675 int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
676 int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100677
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200678 printf(" %c%d", j ? '+' : '-', MIN(a, b));
679 if (a == b)
680 continue;
681 printf(",%d", (a < b) ? b - a + 1 : 0);
682 }
Denys Vlasenkod60752f2015-10-07 22:42:45 +0200683 puts(" @@");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100684 /*
685 * Output changes in "unified" diff format--the old and new lines
686 * are printed together.
687 */
Dan Fandrich1821d182010-02-04 04:04:56 +0100688 for (lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100689 bool end = cvp > &vec[idx];
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200690 fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100691 if (end)
692 break;
Dan Fandrich1821d182010-02-04 04:04:56 +0100693 for (j = 0; j < 2; j++)
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200694 fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100695 }
696 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100697 anychange = true;
Matheus Izvekov6f99c912010-01-21 18:58:03 -0200698 cont:
699 idx = -1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100700 } while (i <= nlen[0]);
701
702 free(vec);
703 free(ix[0]);
704 free(ix[1]);
705 free(J);
706 return anychange;
707}
708
709static int diffreg(char *file[2])
710{
Denys Vlasenko14bd16a2011-07-08 08:49:40 +0200711 FILE *fp[2];
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100712 bool binary = false, differ = false;
Dan Fandrichf111b672010-02-04 00:10:30 +0100713 int status = STATUS_SAME, i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100714
Denys Vlasenko14bd16a2011-07-08 08:49:40 +0200715 fp[0] = stdin;
716 fp[1] = stdin;
Dan Fandrichf111b672010-02-04 00:10:30 +0100717 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100718 int fd = open_or_warn_stdin(file[i]);
719 if (fd == -1)
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200720 goto out;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100721 /* Our diff implementation is using seek.
722 * When we meet non-seekable file, we must make a temp copy.
723 */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100724 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
725 char name[] = "/tmp/difXXXXXX";
Alexander Shishkin67227372010-10-22 13:27:16 +0200726 int fd_tmp = xmkstemp(name);
727
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100728 unlink(name);
Matheus Izvekov404f1442010-01-18 22:21:40 -0200729 if (bb_copyfd_eof(fd, fd_tmp) < 0)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100730 xfunc_die();
Denys Vlasenko39f01722015-01-11 16:41:54 +0100731 if (fd != STDIN_FILENO)
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100732 close(fd);
733 fd = fd_tmp;
Denys Vlasenko39f01722015-01-11 16:41:54 +0100734 xlseek(fd, 0, SEEK_SET);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100735 }
Matheus Izvekov404f1442010-01-18 22:21:40 -0200736 fp[i] = fdopen(fd, "r");
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100737 }
738
Denys Vlasenko9de2e5a2016-04-21 18:38:51 +0200739 setup_common_bufsiz();
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100740 while (1) {
741 const size_t sz = COMMON_BUFSIZE / 2;
742 char *const buf0 = bb_common_bufsiz1;
743 char *const buf1 = buf0 + sz;
Dan Fandrichf111b672010-02-04 00:10:30 +0100744 int j, k;
Matheus Izvekov404f1442010-01-18 22:21:40 -0200745 i = fread(buf0, 1, sz, fp[0]);
746 j = fread(buf1, 1, sz, fp[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100747 if (i != j) {
748 differ = true;
749 i = MIN(i, j);
750 }
751 if (i == 0)
752 break;
Dan Fandrichf111b672010-02-04 00:10:30 +0100753 for (k = 0; k < i; k++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100754 if (!buf0[k] || !buf1[k])
755 binary = true;
756 if (buf0[k] != buf1[k])
757 differ = true;
758 }
759 }
760 if (differ) {
761 if (binary && !(option_mask32 & FLAG(a)))
762 status = STATUS_BINARY;
Matheus Izvekov404f1442010-01-18 22:21:40 -0200763 else if (diff(fp, file))
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100764 status = STATUS_DIFFER;
765 }
766 if (status != STATUS_SAME)
767 exit_status |= 1;
Matheus Izvekov94a6fd12010-01-18 23:34:29 -0200768out:
Matheus Izvekov404f1442010-01-18 22:21:40 -0200769 fclose_if_not_stdin(fp[0]);
770 fclose_if_not_stdin(fp[1]);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100771
772 return status;
773}
774
775static void print_status(int status, char *path[2])
776{
777 switch (status) {
778 case STATUS_BINARY:
779 case STATUS_DIFFER:
780 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
781 printf("Files %s and %s differ\n", path[0], path[1]);
782 break;
783 case STATUS_SAME:
784 if (option_mask32 & FLAG(s))
785 printf("Files %s and %s are identical\n", path[0], path[1]);
786 break;
787 }
788}
Denis Vlasenko6a1d6612006-12-16 22:18:44 +0000789
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +0000790#if ENABLE_FEATURE_DIFF_DIR
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100791struct dlist {
792 size_t len;
793 int s, e;
794 char **dl;
795};
796
Denis Vlasenko6a1d6612006-12-16 22:18:44 +0000797/* This function adds a filename to dl, the directory listing. */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000798static int FAST_FUNC add_to_dirlist(const char *filename,
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000799 struct stat *sb UNUSED_PARAM,
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100800 void *userdata, int depth UNUSED_PARAM)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000801{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100802 struct dlist *const l = userdata;
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200803 const char *file = filename + l->len;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200804 while (*file == '/')
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200805 file++;
Denys Vlasenko32a6bae2010-07-09 19:44:38 +0200806 l->dl = xrealloc_vector(l->dl, 6, l->e);
Matheus Izvekov61f5f782010-07-09 19:40:00 +0200807 l->dl[l->e] = xstrdup(file);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100808 l->e++;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000809 return TRUE;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000810}
811
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100812/* If recursion is not set, this function adds the directory
813 * to the list and prevents recursive_action from recursing into it.
814 */
815static int FAST_FUNC skip_dir(const char *filename,
816 struct stat *sb, void *userdata,
817 int depth)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000818{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100819 if (!(option_mask32 & FLAG(r)) && depth) {
820 add_to_dirlist(filename, sb, userdata, depth);
821 return SKIP;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000822 }
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200823 if (!(option_mask32 & FLAG(N))) {
824 /* -r without -N: no need to recurse into dirs
825 * which do not exist on the "other side".
826 * Testcase: diff -r /tmp /
827 * (it would recurse deep into /proc without this code) */
828 struct dlist *const l = userdata;
829 filename += l->len;
830 if (filename[0]) {
831 struct stat osb;
832 char *othername = concat_path_file(G.other_dir, filename);
833 int r = stat(othername, &osb);
834 free(othername);
835 if (r != 0 || !S_ISDIR(osb.st_mode)) {
836 /* other dir doesn't have similarly named
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200837 * directory, don't recurse; return 1 upon
838 * exit, just like diffutils' diff */
839 exit_status |= 1;
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200840 return SKIP;
841 }
842 }
843 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100844 return TRUE;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +0000845}
846
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100847static void diffdir(char *p[2], const char *s_start)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000848{
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100849 struct dlist list[2];
Dan Fandrichf111b672010-02-04 00:10:30 +0100850 int i;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000851
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100852 memset(&list, 0, sizeof(list));
Dan Fandrichf111b672010-02-04 00:10:30 +0100853 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100854 /*list[i].s = list[i].e = 0; - memset did it */
855 /*list[i].dl = NULL; */
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000856
Denys Vlasenko75703eb2010-07-10 16:25:47 +0200857 G.other_dir = p[1 - i];
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100858 /* We need to trim root directory prefix.
859 * Using list.len to specify its length,
860 * add_to_dirlist will remove it. */
861 list[i].len = strlen(p[i]);
862 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
Denys Vlasenko60cb48c2013-01-14 15:57:44 +0100863 add_to_dirlist, skip_dir, &list[i], 0);
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100864 /* Sort dl alphabetically.
865 * GNU diff does this ignoring any number of trailing dots.
866 * We don't, so for us dotted files almost always are
867 * first on the list.
868 */
869 qsort_string_vector(list[i].dl, list[i].e);
870 /* If -S was set, find the starting point. */
871 if (!s_start)
872 continue;
873 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
874 list[i].s++;
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000875 }
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000876 /* Now that both dirlist1 and dirlist2 contain sorted directory
877 * listings, we can start to go through dirlist1. If both listings
878 * contain the same file, then do a normal diff. Otherwise, behaviour
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000879 * is determined by whether the -N flag is set. */
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100880 while (1) {
881 char *dp[2];
882 int pos;
883 int k;
884
885 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
886 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
887 if (!dp[0] && !dp[1])
888 break;
889 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
890 k = pos > 0;
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200891 if (pos && !(option_mask32 & FLAG(N))) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100892 printf("Only in %s: %s\n", p[k], dp[k]);
Alexander Shishkinf18a82d2011-01-25 18:03:46 +0200893 exit_status |= 1;
894 } else {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100895 char *fullpath[2], *path[2]; /* if -N */
896
Dan Fandrichf111b672010-02-04 00:10:30 +0100897 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100898 if (pos == 0 || i == k) {
899 path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
900 stat(fullpath[i], &stb[i]);
901 } else {
902 fullpath[i] = concat_path_file(p[i], dp[1 - i]);
903 path[i] = (char *)bb_dev_null;
904 }
905 }
906 if (pos)
907 stat(fullpath[k], &stb[1 - k]);
908
909 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
910 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
911 else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
912 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
913 else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
914 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
915 else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
916 if (S_ISDIR(stb[0].st_mode))
917 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
918 else
919 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
920 } else
921 print_status(diffreg(path), fullpath);
922
923 free(fullpath[0]);
924 free(fullpath[1]);
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000925 }
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100926 free(dp[k]);
927 list[k].s++;
928 if (pos == 0) {
929 free(dp[1 - k]);
930 list[1 - k].s++;
931 }
932 }
933 if (ENABLE_FEATURE_CLEAN_UP) {
934 free(list[0].dl);
935 free(list[1].dl);
Bernhard Reutner-Fischer693a9362006-04-06 08:15:24 +0000936 }
937}
938#endif
939
Matheus Izvekovb32aa0c2010-01-18 18:40:02 -0200940#if ENABLE_FEATURE_DIFF_LONG_OPTIONS
941static const char diff_longopts[] ALIGN1 =
942 "ignore-case\0" No_argument "i"
943 "ignore-tab-expansion\0" No_argument "E"
944 "ignore-space-change\0" No_argument "b"
945 "ignore-all-space\0" No_argument "w"
946 "ignore-blank-lines\0" No_argument "B"
947 "text\0" No_argument "a"
948 "unified\0" Required_argument "U"
949 "label\0" Required_argument "L"
950 "show-c-function\0" No_argument "p"
951 "brief\0" No_argument "q"
952 "expand-tabs\0" No_argument "t"
953 "initial-tab\0" No_argument "T"
954 "recursive\0" No_argument "r"
955 "new-file\0" No_argument "N"
956 "report-identical-files\0" No_argument "s"
957 "starting-file\0" Required_argument "S"
958 "minimal\0" No_argument "d"
959 ;
960#endif
961
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +0000962int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000963int diff_main(int argc UNUSED_PARAM, char **argv)
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000964{
Dan Fandrichf111b672010-02-04 00:10:30 +0100965 int gotstdin = 0, i;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100966 char *file[2], *s_start = NULL;
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +0000967 llist_t *L_arg = NULL;
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000968
Denis Vlasenkoef4bb262007-06-04 12:21:53 +0000969 INIT_G();
970
Denis Vlasenko1d426652008-03-17 09:09:09 +0000971 /* exactly 2 params; collect multiple -L <label>; -U N */
Denys Vlasenko237bedd2016-07-06 21:58:02 +0200972 opt_complementary = "=2";
Matheus Izvekovb32aa0c2010-01-18 18:40:02 -0200973#if ENABLE_FEATURE_DIFF_LONG_OPTIONS
974 applet_long_options = diff_longopts;
975#endif
Denys Vlasenko237bedd2016-07-06 21:58:02 +0200976 getopt32(argv, "abdiL:*NqrsS:tTU:+wupBE",
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100977 &L_arg, &s_start, &opt_U_context);
Bernhard Reutner-Fischerbbc225e2006-05-29 12:12:45 +0000978 argv += optind;
Matheus Izvekov4de4cb62010-01-18 20:40:23 -0200979 while (L_arg)
980 label[!!label[0]] = llist_pop(&L_arg);
Denys Vlasenko38d90722009-06-09 12:55:13 +0200981 xfunc_error_retval = 2;
Dan Fandrichf111b672010-02-04 00:10:30 +0100982 for (i = 0; i < 2; i++) {
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100983 file[i] = argv[i];
984 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
985 if (LONE_DASH(file[i])) {
986 fstat(STDIN_FILENO, &stb[i]);
987 gotstdin++;
988 } else
989 xstat(file[i], &stb[i]);
990 }
Denys Vlasenko38d90722009-06-09 12:55:13 +0200991 xfunc_error_retval = 1;
Matheus Izvekovd4a77282010-01-18 04:57:17 +0100992 if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
Denis Vlasenko04211fd2008-03-24 14:44:59 +0000993 bb_error_msg_and_die("can't compare stdin to a directory");
994
Roman Borisov95f5c522011-03-27 23:24:09 +0200995 /* Compare metadata to check if the files are the same physical file.
996 *
997 * Comment from diffutils source says:
998 * POSIX says that two files are identical if st_ino and st_dev are
999 * the same, but many file systems incorrectly assign the same (device,
1000 * inode) pair to two distinct files, including:
1001 * GNU/Linux NFS servers that export all local file systems as a
1002 * single NFS file system, if a local device number (st_dev) exceeds
1003 * 255, or if a local inode number (st_ino) exceeds 16777215.
1004 */
1005 if (ENABLE_DESKTOP
1006 && stb[0].st_ino == stb[1].st_ino
1007 && stb[0].st_dev == stb[1].st_dev
1008 && stb[0].st_size == stb[1].st_size
1009 && stb[0].st_mtime == stb[1].st_mtime
1010 && stb[0].st_ctime == stb[1].st_ctime
1011 && stb[0].st_mode == stb[1].st_mode
1012 && stb[0].st_nlink == stb[1].st_nlink
1013 && stb[0].st_uid == stb[1].st_uid
1014 && stb[0].st_gid == stb[1].st_gid
1015 ) {
1016 /* files are physically the same; no need to compare them */
1017 return STATUS_SAME;
1018 }
1019
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001020 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
Bernhard Reutner-Fischerbc142142006-04-06 16:07:08 +00001021#if ENABLE_FEATURE_DIFF_DIR
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001022 diffdir(file, s_start);
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001023#else
Denis Vlasenko04211fd2008-03-24 14:44:59 +00001024 bb_error_msg_and_die("no support for directory comparison");
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001025#endif
Matheus Izvekovd4a77282010-01-18 04:57:17 +01001026 } else {
1027 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
1028 bool dir = S_ISDIR(stb[1].st_mode);
1029 if (dirfile) {
1030 const char *slash = strrchr(file[!dir], '/');
1031 file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
1032 xstat(file[dir], &stb[dir]);
1033 }
1034 /* diffreg can get non-regular files here */
1035 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
1036
1037 if (dirfile)
1038 free(file[dir]);
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001039 }
Denis Vlasenko04211fd2008-03-24 14:44:59 +00001040
Denis Vlasenko7fe0eba2008-03-24 16:19:21 +00001041 return exit_status;
Bernhard Reutner-Fischer8f7d3892006-04-06 08:11:08 +00001042}