diff.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini diff implementation for busybox, adapted from OpenBSD diff.
  4. *
  5. * Copyright (C) 2010 by Matheus Izvekov <mizvekov@gmail.com>
  6. * Copyright (C) 2006 by Robert Sullivan <cogito.ergo.cogito@hotmail.com>
  7. * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
  8. *
  9. * 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.
  12. *
  13. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  14. */
  15. /*
  16. * The following code uses an algorithm due to Harold Stone,
  17. * which finds a pair of longest identical subsequences in
  18. * the two files.
  19. *
  20. * The major goal is to generate the match vector J.
  21. * J[i] is the index of the line in file1 corresponding
  22. * to line i in file0. J[i] = 0 if there is no
  23. * such line in file1.
  24. *
  25. * Lines are hashed so as to work in core. All potential
  26. * matches are located by sorting the lines of each file
  27. * on the hash (called "value"). In particular, this
  28. * collects the equivalence classes in file1 together.
  29. * Subroutine equiv replaces the value of each line in
  30. * file0 by the index of the first element of its
  31. * matching equivalence in (the reordered) file1.
  32. * To save space equiv squeezes file1 into a single
  33. * array member in which the equivalence classes
  34. * are simply concatenated, except that their first
  35. * members are flagged by changing sign.
  36. *
  37. * Next the indices that point into member are unsorted into
  38. * array class according to the original order of file0.
  39. *
  40. * The cleverness lies in routine stone. This marches
  41. * through the lines of file0, developing a vector klist
  42. * of "k-candidates". At step i a k-candidate is a matched
  43. * pair of lines x,y (x in file0, y in file1) such that
  44. * there is a common subsequence of length k
  45. * between the first i lines of file0 and the first y
  46. * lines of file1, but there is no such subsequence for
  47. * any smaller y. x is the earliest possible mate to y
  48. * that occurs in such a subsequence.
  49. *
  50. * Whenever any of the members of the equivalence class of
  51. * lines in file1 matable to a line in file0 has serial number
  52. * less than the y of some k-candidate, that k-candidate
  53. * with the smallest such y is replaced. The new
  54. * k-candidate is chained (via pred) to the current
  55. * k-1 candidate so that the actual subsequence can
  56. * be recovered. When a member has serial number greater
  57. * that the y of all k-candidates, the klist is extended.
  58. * At the end, the longest subsequence is pulled out
  59. * and placed in the array J by unravel
  60. *
  61. * With J in hand, the matches there recorded are
  62. * checked against reality to assure that no spurious
  63. * matches have crept in due to hashing. If they have,
  64. * they are broken, and "jackpot" is recorded--a harmless
  65. * matter except that a true match for a spuriously
  66. * mated line may now be unnecessarily reported as a change.
  67. *
  68. * Much of the complexity of the program comes simply
  69. * from trying to minimize core utilization and
  70. * maximize the range of doable problems by dynamically
  71. * allocating what is needed and reusing what is not.
  72. * The core requirements for problems larger than somewhat
  73. * are (in words) 2*length(file0) + length(file1) +
  74. * 3*(number of k-candidates installed), typically about
  75. * 6n words for files of length n.
  76. */
  77. //config:config DIFF
  78. //config: bool "diff"
  79. //config: default y
  80. //config: help
  81. //config: diff compares two files or directories and outputs the
  82. //config: differences between them in a form that can be given to
  83. //config: the patch command.
  84. //config:
  85. //config:config FEATURE_DIFF_LONG_OPTIONS
  86. //config: bool "Enable long options"
  87. //config: default y
  88. //config: depends on DIFF && LONG_OPTS
  89. //config: help
  90. //config: Enable use of long options.
  91. //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. //kbuild:lib-$(CONFIG_DIFF) += diff.o
  100. //applet:IF_DIFF(APPLET(diff, BB_DIR_USR_BIN, BB_SUID_DROP))
  101. //usage:#define diff_trivial_usage
  102. //usage: "[-abBdiNqrTstw] [-L LABEL] [-S FILE] [-U LINES] FILE1 FILE2"
  103. //usage:#define diff_full_usage "\n\n"
  104. //usage: "Compare files line by line and output the differences between them.\n"
  105. //usage: "This implementation supports unified diffs only.\n"
  106. //usage: "\n -a Treat all files as text"
  107. //usage: "\n -b Ignore changes in the amount of whitespace"
  108. //usage: "\n -B Ignore changes whose lines are all blank"
  109. //usage: "\n -d Try hard to find a smaller set of changes"
  110. //usage: "\n -i Ignore case differences"
  111. //usage: "\n -L Use LABEL instead of the filename in the unified header"
  112. //usage: "\n -N Treat absent files as empty"
  113. //usage: "\n -q Output only whether files differ"
  114. //usage: "\n -r Recurse"
  115. //usage: "\n -S Start with FILE when comparing directories"
  116. //usage: "\n -T Make tabs line up by prefixing a tab when necessary"
  117. //usage: "\n -s Report when two files are the same"
  118. //usage: "\n -t Expand tabs to spaces in output"
  119. //usage: "\n -U Output LINES lines of context"
  120. //usage: "\n -w Ignore all whitespace"
  121. #include "libbb.h"
  122. #if 0
  123. # define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
  124. #else
  125. # define dbg_error_msg(...) ((void)0)
  126. #endif
  127. enum { /* print_status() and diffreg() return values */
  128. STATUS_SAME, /* files are the same */
  129. STATUS_DIFFER, /* files differ */
  130. STATUS_BINARY, /* binary files differ */
  131. };
  132. enum { /* Commandline flags */
  133. FLAG_a,
  134. FLAG_b,
  135. FLAG_d,
  136. FLAG_i,
  137. FLAG_L, /* never used, handled by getopt32 */
  138. FLAG_N,
  139. FLAG_q,
  140. FLAG_r,
  141. FLAG_s,
  142. FLAG_S, /* never used, handled by getopt32 */
  143. FLAG_t,
  144. FLAG_T,
  145. FLAG_U, /* never used, handled by getopt32 */
  146. FLAG_w,
  147. FLAG_u, /* ignored, this is the default */
  148. FLAG_p, /* not implemented */
  149. FLAG_B,
  150. FLAG_E, /* not implemented */
  151. };
  152. #define FLAG(x) (1 << FLAG_##x)
  153. /* We cache file position to avoid excessive seeking */
  154. typedef struct FILE_and_pos_t {
  155. FILE *ft_fp;
  156. off_t ft_pos;
  157. } FILE_and_pos_t;
  158. struct globals {
  159. smallint exit_status;
  160. int opt_U_context;
  161. const char *other_dir;
  162. char *label[2];
  163. struct stat stb[2];
  164. };
  165. #define G (*ptr_to_globals)
  166. #define exit_status (G.exit_status )
  167. #define opt_U_context (G.opt_U_context )
  168. #define label (G.label )
  169. #define stb (G.stb )
  170. #define INIT_G() do { \
  171. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  172. opt_U_context = 3; \
  173. } while (0)
  174. typedef int token_t;
  175. enum {
  176. /* Public */
  177. TOK_EMPTY = 1 << 9, /* Line fully processed, you can proceed to the next */
  178. TOK_EOF = 1 << 10, /* File ended */
  179. /* Private (Only to be used by read_token() */
  180. TOK_EOL = 1 << 11, /* we saw EOL (sticky) */
  181. TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
  182. SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
  183. CHAR_MASK = 0x1ff, /* 8th bit is used to distinguish EOF from 0xff */
  184. };
  185. /* Restores full EOF from one 8th bit: */
  186. //#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
  187. /* We don't really need the above, we only need to have EOF != any_real_char: */
  188. #define TOK2CHAR(t) ((t) & CHAR_MASK)
  189. static void seek_ft(FILE_and_pos_t *ft, off_t pos)
  190. {
  191. if (ft->ft_pos != pos) {
  192. ft->ft_pos = pos;
  193. fseeko(ft->ft_fp, pos, SEEK_SET);
  194. }
  195. }
  196. /* Reads tokens from given fp, handling -b and -w flags
  197. * The user must reset tok every line start
  198. */
  199. static int read_token(FILE_and_pos_t *ft, token_t tok)
  200. {
  201. tok |= TOK_EMPTY;
  202. while (!(tok & TOK_EOL)) {
  203. bool is_space;
  204. int t;
  205. t = fgetc(ft->ft_fp);
  206. if (t != EOF)
  207. ft->ft_pos++;
  208. is_space = (t == EOF || isspace(t));
  209. /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
  210. tok |= (t & (TOK_EOF + TOK_EOL));
  211. /* Only EOL? */
  212. if (t == '\n')
  213. tok |= TOK_EOL;
  214. if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
  215. t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
  216. if ((option_mask32 & FLAG(w)) && is_space)
  217. continue;
  218. /* Trim char value to low 9 bits */
  219. t &= CHAR_MASK;
  220. if (option_mask32 & FLAG(b)) {
  221. /* Was prev char whitespace? */
  222. if (tok & TOK_SPACE) { /* yes */
  223. if (is_space) /* this one too, ignore it */
  224. continue;
  225. tok &= ~TOK_SPACE;
  226. } else if (is_space) {
  227. /* 1st whitespace char.
  228. * Set TOK_SPACE and replace char by ' ' */
  229. t = TOK_SPACE + ' ';
  230. }
  231. }
  232. /* Clear EMPTY */
  233. tok &= ~(TOK_EMPTY + CHAR_MASK);
  234. /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
  235. tok |= t;
  236. break;
  237. }
  238. #if 0
  239. bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
  240. , tok & TOK_EOF ? " EOF" : ""
  241. , tok & TOK_EOL ? " EOL" : ""
  242. , tok & TOK_EMPTY ? " EMPTY" : ""
  243. , tok & TOK_SPACE ? " SPACE" : ""
  244. );
  245. #endif
  246. return tok;
  247. }
  248. struct cand {
  249. int x;
  250. int y;
  251. int pred;
  252. };
  253. static int search(const int *c, int k, int y, const struct cand *list)
  254. {
  255. int i, j;
  256. if (list[c[k]].y < y) /* quick look for typical case */
  257. return k + 1;
  258. for (i = 0, j = k + 1;;) {
  259. 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. static 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. static void stone(const int *a, int n, const int *b, int *J, int pref)
  283. {
  284. const unsigned isq = isqrt(n);
  285. const unsigned bound =
  286. (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
  287. int clen = 1;
  288. int clistlen = 100;
  289. int k = 0;
  290. struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
  291. struct cand cand;
  292. struct cand *q;
  293. int *klist = xzalloc((n + 2) * sizeof(klist[0]));
  294. /*clist[0] = (struct cand){0}; - xzalloc did it */
  295. /*klist[0] = 0; */
  296. for (cand.x = 1; cand.x <= n; cand.x++) {
  297. int j = a[cand.x], oldl = 0;
  298. unsigned numtries = 0;
  299. if (j == 0)
  300. continue;
  301. cand.y = -b[j];
  302. cand.pred = klist[0];
  303. do {
  304. int l, tc;
  305. if (cand.y <= clist[cand.pred].y)
  306. continue;
  307. l = search(klist, k, cand.y, clist);
  308. if (l != oldl + 1)
  309. cand.pred = klist[l - 1];
  310. if (l <= k && clist[klist[l]].y <= cand.y)
  311. continue;
  312. if (clen == clistlen) {
  313. clistlen = clistlen * 11 / 10;
  314. clist = xrealloc(clist, clistlen * sizeof(clist[0]));
  315. }
  316. clist[clen] = cand;
  317. tc = klist[l];
  318. klist[l] = clen++;
  319. if (l <= k) {
  320. cand.pred = tc;
  321. oldl = l;
  322. numtries++;
  323. } else {
  324. k++;
  325. break;
  326. }
  327. } while ((cand.y = b[++j]) > 0 && numtries < bound);
  328. }
  329. /* Unravel */
  330. for (q = clist + klist[k]; q->y; q = clist + q->pred)
  331. J[q->x + pref] = q->y + pref;
  332. free(klist);
  333. free(clist);
  334. }
  335. struct line {
  336. /* 'serial' is not used in the beginning, so we reuse it
  337. * to store line offsets, thus reducing memory pressure
  338. */
  339. union {
  340. unsigned serial;
  341. off_t offset;
  342. };
  343. unsigned value;
  344. };
  345. static void equiv(struct line *a, int n, struct line *b, int m, int *c)
  346. {
  347. int i = 1, j = 1;
  348. while (i <= n && j <= m) {
  349. if (a[i].value < b[j].value)
  350. a[i++].value = 0;
  351. else if (a[i].value == b[j].value)
  352. a[i++].value = j;
  353. else
  354. j++;
  355. }
  356. while (i <= n)
  357. a[i++].value = 0;
  358. b[m + 1].value = 0;
  359. j = 0;
  360. while (++j <= m) {
  361. c[j] = -b[j].serial;
  362. while (b[j + 1].value == b[j].value) {
  363. j++;
  364. c[j] = b[j].serial;
  365. }
  366. }
  367. c[j] = -1;
  368. }
  369. static void unsort(const struct line *f, int l, int *b)
  370. {
  371. int i;
  372. int *a = xmalloc((l + 1) * sizeof(a[0]));
  373. for (i = 1; i <= l; i++)
  374. a[f[i].serial] = f[i].value;
  375. for (i = 1; i <= l; i++)
  376. b[i] = a[i];
  377. free(a);
  378. }
  379. static int line_compar(const void *a, const void *b)
  380. {
  381. #define l0 ((const struct line*)a)
  382. #define l1 ((const struct line*)b)
  383. int r = l0->value - l1->value;
  384. if (r)
  385. return r;
  386. return l0->serial - l1->serial;
  387. #undef l0
  388. #undef l1
  389. }
  390. static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
  391. {
  392. int i, j, col;
  393. for (i = a; i <= b; i++) {
  394. seek_ft(ft, ix[i - 1]);
  395. putchar(ch);
  396. if (option_mask32 & FLAG(T))
  397. putchar('\t');
  398. for (j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
  399. int c = fgetc(ft->ft_fp);
  400. if (c == EOF) {
  401. puts("\n\\ No newline at end of file");
  402. return;
  403. }
  404. ft->ft_pos++;
  405. if (c == '\t' && (option_mask32 & FLAG(t)))
  406. do putchar(' '); while (++col & 7);
  407. else {
  408. putchar(c);
  409. col++;
  410. }
  411. }
  412. }
  413. }
  414. /* Creates the match vector J, where J[i] is the index
  415. * of the line in the new file corresponding to the line i
  416. * in the old file. Lines start at 1 instead of 0, that value
  417. * being used instead to denote no corresponding line.
  418. * This vector is dynamically allocated and must be freed by the caller.
  419. *
  420. * * fp is an input parameter, where fp[0] and fp[1] are the open
  421. * old file and new file respectively.
  422. * * nlen is an output variable, where nlen[0] and nlen[1]
  423. * gets the number of lines in the old and new file respectively.
  424. * * ix is an output variable, where ix[0] and ix[1] gets
  425. * assigned dynamically allocated vectors of the offsets of the lines
  426. * of the old and new file respectively. These must be freed by the caller.
  427. */
  428. static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
  429. {
  430. int *J, slen[2], *class, *member;
  431. struct line *nfile[2], *sfile[2];
  432. int pref = 0, suff = 0, i, j, delta;
  433. /* Lines of both files are hashed, and in the process
  434. * their offsets are stored in the array ix[fileno]
  435. * where fileno == 0 points to the old file, and
  436. * fileno == 1 points to the new one.
  437. */
  438. for (i = 0; i < 2; i++) {
  439. unsigned hash;
  440. token_t tok;
  441. size_t sz = 100;
  442. nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
  443. /* ft gets here without the correct position, cant use seek_ft */
  444. ft[i].ft_pos = 0;
  445. fseeko(ft[i].ft_fp, 0, SEEK_SET);
  446. nlen[i] = 0;
  447. /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
  448. nfile[i][0].offset = 0;
  449. goto start; /* saves code */
  450. while (1) {
  451. tok = read_token(&ft[i], tok);
  452. if (!(tok & TOK_EMPTY)) {
  453. /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
  454. /*hash = hash * 128 - hash + TOK2CHAR(tok);
  455. * gcc insists on optimizing above to "hash * 127 + ...", thus... */
  456. unsigned o = hash - TOK2CHAR(tok);
  457. hash = hash * 128 - o; /* we want SPEED here */
  458. continue;
  459. }
  460. if (nlen[i]++ == sz) {
  461. sz = sz * 3 / 2;
  462. nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
  463. }
  464. /* line_compar needs hashes fit into positive int */
  465. nfile[i][nlen[i]].value = hash & INT_MAX;
  466. /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
  467. nfile[i][nlen[i]].offset = ft[i].ft_pos;
  468. if (tok & TOK_EOF) {
  469. /* EOF counts as a token, so we have to adjust it here */
  470. nfile[i][nlen[i]].offset++;
  471. break;
  472. }
  473. start:
  474. hash = tok = 0;
  475. }
  476. /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
  477. if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
  478. nlen[i]--;
  479. /* Now we copy the line offsets into ix */
  480. ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
  481. for (j = 0; j < nlen[i] + 1; j++)
  482. ix[i][j] = nfile[i][j].offset;
  483. }
  484. /* length of prefix and suffix is calculated */
  485. for (; pref < nlen[0] && pref < nlen[1] &&
  486. nfile[0][pref + 1].value == nfile[1][pref + 1].value;
  487. pref++);
  488. for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
  489. nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
  490. suff++);
  491. /* Arrays are pruned by the suffix and prefix length,
  492. * the result being sorted and stored in sfile[fileno],
  493. * and their sizes are stored in slen[fileno]
  494. */
  495. for (j = 0; j < 2; j++) {
  496. sfile[j] = nfile[j] + pref;
  497. slen[j] = nlen[j] - pref - suff;
  498. for (i = 0; i <= slen[j]; i++)
  499. sfile[j][i].serial = i;
  500. qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
  501. }
  502. /* nfile arrays are reused to reduce memory pressure
  503. * The #if zeroed out section performs the same task as the
  504. * one in the #else section.
  505. * Peak memory usage is higher, but one array copy is avoided
  506. * by not using unsort()
  507. */
  508. #if 0
  509. member = xmalloc((slen[1] + 2) * sizeof(member[0]));
  510. equiv(sfile[0], slen[0], sfile[1], slen[1], member);
  511. free(nfile[1]);
  512. class = xmalloc((slen[0] + 1) * sizeof(class[0]));
  513. for (i = 1; i <= slen[0]; i++) /* Unsorting */
  514. class[sfile[0][i].serial] = sfile[0][i].value;
  515. free(nfile[0]);
  516. #else
  517. member = (int *)nfile[1];
  518. equiv(sfile[0], slen[0], sfile[1], slen[1], member);
  519. member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
  520. class = (int *)nfile[0];
  521. unsort(sfile[0], slen[0], (int *)nfile[0]);
  522. class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
  523. #endif
  524. J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
  525. /* The elements of J which fall inside the prefix and suffix regions
  526. * are marked as unchanged, while the ones which fall outside
  527. * are initialized with 0 (no matches), so that function stone can
  528. * then assign them their right values
  529. */
  530. for (i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
  531. J[i] = i <= pref ? i :
  532. i > (nlen[0] - suff) ? (i + delta) : 0;
  533. /* Here the magic is performed */
  534. stone(class, slen[0], member, J, pref);
  535. J[nlen[0] + 1] = nlen[1] + 1;
  536. free(class);
  537. free(member);
  538. /* Both files are rescanned, in an effort to find any lines
  539. * which, due to limitations intrinsic to any hashing algorithm,
  540. * are different but ended up confounded as the same
  541. */
  542. for (i = 1; i <= nlen[0]; i++) {
  543. if (!J[i])
  544. continue;
  545. seek_ft(&ft[0], ix[0][i - 1]);
  546. seek_ft(&ft[1], ix[1][J[i] - 1]);
  547. for (j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
  548. token_t tok0 = 0, tok1 = 0;
  549. do {
  550. tok0 = read_token(&ft[0], tok0);
  551. tok1 = read_token(&ft[1], tok1);
  552. if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
  553. || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
  554. ) {
  555. J[i] = 0; /* Break the correspondence */
  556. }
  557. } while (!(tok0 & tok1 & TOK_EMPTY));
  558. }
  559. }
  560. return J;
  561. }
  562. static bool diff(FILE* fp[2], char *file[2])
  563. {
  564. int nlen[2];
  565. off_t *ix[2];
  566. FILE_and_pos_t ft[2];
  567. typedef struct { int a, b; } vec_t[2];
  568. vec_t *vec = NULL;
  569. int i = 1, j, k, idx = -1;
  570. bool anychange = false;
  571. int *J;
  572. ft[0].ft_fp = fp[0];
  573. ft[1].ft_fp = fp[1];
  574. /* note that ft[i].ft_pos is unintitalized, create_J()
  575. * must not assume otherwise */
  576. J = create_J(ft, nlen, ix);
  577. do {
  578. bool nonempty = false;
  579. while (1) {
  580. vec_t v;
  581. for (v[0].a = i; v[0].a <= nlen[0] && J[v[0].a] == J[v[0].a - 1] + 1; v[0].a++)
  582. continue;
  583. v[1].a = J[v[0].a - 1] + 1;
  584. for (v[0].b = v[0].a - 1; v[0].b < nlen[0] && !J[v[0].b + 1]; v[0].b++)
  585. continue;
  586. v[1].b = J[v[0].b + 1] - 1;
  587. /*
  588. * Indicate that there is a difference between lines a and b of the 'from' file
  589. * to get to lines c to d of the 'to' file. If a is greater than b then there
  590. * are no lines in the 'from' file involved and this means that there were
  591. * lines appended (beginning at b). If c is greater than d then there are
  592. * lines missing from the 'to' file.
  593. */
  594. if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
  595. /*
  596. * If this change is more than 'context' lines from the
  597. * previous change, dump the record and reset it.
  598. */
  599. int ct = (2 * opt_U_context) + 1;
  600. if (idx >= 0
  601. && v[0].a > vec[idx][0].b + ct
  602. && v[1].a > vec[idx][1].b + ct
  603. ) {
  604. break;
  605. }
  606. for (j = 0; j < 2; j++)
  607. for (k = v[j].a; k <= v[j].b; k++)
  608. nonempty |= (ix[j][k] - ix[j][k - 1] != 1);
  609. vec = xrealloc_vector(vec, 6, ++idx);
  610. memcpy(vec[idx], v, sizeof(v));
  611. }
  612. i = v[0].b + 1;
  613. if (i > nlen[0])
  614. break;
  615. J[v[0].b] = v[1].b;
  616. }
  617. if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
  618. goto cont;
  619. if (!(option_mask32 & FLAG(q))) {
  620. int lowa;
  621. vec_t span, *cvp = vec;
  622. if (!anychange) {
  623. /* Print the context/unidiff header first time through */
  624. printf("--- %s\n", label[0] ? label[0] : file[0]);
  625. printf("+++ %s\n", label[1] ? label[1] : file[1]);
  626. }
  627. printf("@@");
  628. for (j = 0; j < 2; j++) {
  629. int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
  630. int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
  631. printf(" %c%d", j ? '+' : '-', MIN(a, b));
  632. if (a == b)
  633. continue;
  634. printf(",%d", (a < b) ? b - a + 1 : 0);
  635. }
  636. puts(" @@");
  637. /*
  638. * Output changes in "unified" diff format--the old and new lines
  639. * are printed together.
  640. */
  641. for (lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
  642. bool end = cvp > &vec[idx];
  643. fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
  644. if (end)
  645. break;
  646. for (j = 0; j < 2; j++)
  647. fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
  648. }
  649. }
  650. anychange = true;
  651. cont:
  652. idx = -1;
  653. } while (i <= nlen[0]);
  654. free(vec);
  655. free(ix[0]);
  656. free(ix[1]);
  657. free(J);
  658. return anychange;
  659. }
  660. static int diffreg(char *file[2])
  661. {
  662. FILE *fp[2];
  663. bool binary = false, differ = false;
  664. int status = STATUS_SAME, i;
  665. fp[0] = stdin;
  666. fp[1] = stdin;
  667. for (i = 0; i < 2; i++) {
  668. int fd = open_or_warn_stdin(file[i]);
  669. if (fd == -1)
  670. goto out;
  671. /* Our diff implementation is using seek.
  672. * When we meet non-seekable file, we must make a temp copy.
  673. */
  674. if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
  675. char name[] = "/tmp/difXXXXXX";
  676. int fd_tmp = xmkstemp(name);
  677. unlink(name);
  678. if (bb_copyfd_eof(fd, fd_tmp) < 0)
  679. xfunc_die();
  680. if (fd != STDIN_FILENO)
  681. close(fd);
  682. fd = fd_tmp;
  683. xlseek(fd, 0, SEEK_SET);
  684. }
  685. fp[i] = fdopen(fd, "r");
  686. }
  687. while (1) {
  688. const size_t sz = COMMON_BUFSIZE / 2;
  689. char *const buf0 = bb_common_bufsiz1;
  690. char *const buf1 = buf0 + sz;
  691. int j, k;
  692. i = fread(buf0, 1, sz, fp[0]);
  693. j = fread(buf1, 1, sz, fp[1]);
  694. if (i != j) {
  695. differ = true;
  696. i = MIN(i, j);
  697. }
  698. if (i == 0)
  699. break;
  700. for (k = 0; k < i; k++) {
  701. if (!buf0[k] || !buf1[k])
  702. binary = true;
  703. if (buf0[k] != buf1[k])
  704. differ = true;
  705. }
  706. }
  707. if (differ) {
  708. if (binary && !(option_mask32 & FLAG(a)))
  709. status = STATUS_BINARY;
  710. else if (diff(fp, file))
  711. status = STATUS_DIFFER;
  712. }
  713. if (status != STATUS_SAME)
  714. exit_status |= 1;
  715. out:
  716. fclose_if_not_stdin(fp[0]);
  717. fclose_if_not_stdin(fp[1]);
  718. return status;
  719. }
  720. static void print_status(int status, char *path[2])
  721. {
  722. switch (status) {
  723. case STATUS_BINARY:
  724. case STATUS_DIFFER:
  725. if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
  726. printf("Files %s and %s differ\n", path[0], path[1]);
  727. break;
  728. case STATUS_SAME:
  729. if (option_mask32 & FLAG(s))
  730. printf("Files %s and %s are identical\n", path[0], path[1]);
  731. break;
  732. }
  733. }
  734. #if ENABLE_FEATURE_DIFF_DIR
  735. struct dlist {
  736. size_t len;
  737. int s, e;
  738. char **dl;
  739. };
  740. /* This function adds a filename to dl, the directory listing. */
  741. static int FAST_FUNC add_to_dirlist(const char *filename,
  742. struct stat *sb UNUSED_PARAM,
  743. void *userdata, int depth UNUSED_PARAM)
  744. {
  745. struct dlist *const l = userdata;
  746. const char *file = filename + l->len;
  747. while (*file == '/')
  748. file++;
  749. l->dl = xrealloc_vector(l->dl, 6, l->e);
  750. l->dl[l->e] = xstrdup(file);
  751. l->e++;
  752. return TRUE;
  753. }
  754. /* If recursion is not set, this function adds the directory
  755. * to the list and prevents recursive_action from recursing into it.
  756. */
  757. static int FAST_FUNC skip_dir(const char *filename,
  758. struct stat *sb, void *userdata,
  759. int depth)
  760. {
  761. if (!(option_mask32 & FLAG(r)) && depth) {
  762. add_to_dirlist(filename, sb, userdata, depth);
  763. return SKIP;
  764. }
  765. if (!(option_mask32 & FLAG(N))) {
  766. /* -r without -N: no need to recurse into dirs
  767. * which do not exist on the "other side".
  768. * Testcase: diff -r /tmp /
  769. * (it would recurse deep into /proc without this code) */
  770. struct dlist *const l = userdata;
  771. filename += l->len;
  772. if (filename[0]) {
  773. struct stat osb;
  774. char *othername = concat_path_file(G.other_dir, filename);
  775. int r = stat(othername, &osb);
  776. free(othername);
  777. if (r != 0 || !S_ISDIR(osb.st_mode)) {
  778. /* other dir doesn't have similarly named
  779. * directory, don't recurse; return 1 upon
  780. * exit, just like diffutils' diff */
  781. exit_status |= 1;
  782. return SKIP;
  783. }
  784. }
  785. }
  786. return TRUE;
  787. }
  788. static void diffdir(char *p[2], const char *s_start)
  789. {
  790. struct dlist list[2];
  791. int i;
  792. memset(&list, 0, sizeof(list));
  793. for (i = 0; i < 2; i++) {
  794. /*list[i].s = list[i].e = 0; - memset did it */
  795. /*list[i].dl = NULL; */
  796. G.other_dir = p[1 - i];
  797. /* We need to trim root directory prefix.
  798. * Using list.len to specify its length,
  799. * add_to_dirlist will remove it. */
  800. list[i].len = strlen(p[i]);
  801. recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
  802. add_to_dirlist, skip_dir, &list[i], 0);
  803. /* Sort dl alphabetically.
  804. * GNU diff does this ignoring any number of trailing dots.
  805. * We don't, so for us dotted files almost always are
  806. * first on the list.
  807. */
  808. qsort_string_vector(list[i].dl, list[i].e);
  809. /* If -S was set, find the starting point. */
  810. if (!s_start)
  811. continue;
  812. while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
  813. list[i].s++;
  814. }
  815. /* Now that both dirlist1 and dirlist2 contain sorted directory
  816. * listings, we can start to go through dirlist1. If both listings
  817. * contain the same file, then do a normal diff. Otherwise, behaviour
  818. * is determined by whether the -N flag is set. */
  819. while (1) {
  820. char *dp[2];
  821. int pos;
  822. int k;
  823. dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
  824. dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
  825. if (!dp[0] && !dp[1])
  826. break;
  827. pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
  828. k = pos > 0;
  829. if (pos && !(option_mask32 & FLAG(N))) {
  830. printf("Only in %s: %s\n", p[k], dp[k]);
  831. exit_status |= 1;
  832. } else {
  833. char *fullpath[2], *path[2]; /* if -N */
  834. for (i = 0; i < 2; i++) {
  835. if (pos == 0 || i == k) {
  836. path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
  837. stat(fullpath[i], &stb[i]);
  838. } else {
  839. fullpath[i] = concat_path_file(p[i], dp[1 - i]);
  840. path[i] = (char *)bb_dev_null;
  841. }
  842. }
  843. if (pos)
  844. stat(fullpath[k], &stb[1 - k]);
  845. if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
  846. printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
  847. else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
  848. printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
  849. else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
  850. printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
  851. else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
  852. if (S_ISDIR(stb[0].st_mode))
  853. printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
  854. else
  855. printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
  856. } else
  857. print_status(diffreg(path), fullpath);
  858. free(fullpath[0]);
  859. free(fullpath[1]);
  860. }
  861. free(dp[k]);
  862. list[k].s++;
  863. if (pos == 0) {
  864. free(dp[1 - k]);
  865. list[1 - k].s++;
  866. }
  867. }
  868. if (ENABLE_FEATURE_CLEAN_UP) {
  869. free(list[0].dl);
  870. free(list[1].dl);
  871. }
  872. }
  873. #endif
  874. #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
  875. static const char diff_longopts[] ALIGN1 =
  876. "ignore-case\0" No_argument "i"
  877. "ignore-tab-expansion\0" No_argument "E"
  878. "ignore-space-change\0" No_argument "b"
  879. "ignore-all-space\0" No_argument "w"
  880. "ignore-blank-lines\0" No_argument "B"
  881. "text\0" No_argument "a"
  882. "unified\0" Required_argument "U"
  883. "label\0" Required_argument "L"
  884. "show-c-function\0" No_argument "p"
  885. "brief\0" No_argument "q"
  886. "expand-tabs\0" No_argument "t"
  887. "initial-tab\0" No_argument "T"
  888. "recursive\0" No_argument "r"
  889. "new-file\0" No_argument "N"
  890. "report-identical-files\0" No_argument "s"
  891. "starting-file\0" Required_argument "S"
  892. "minimal\0" No_argument "d"
  893. ;
  894. #endif
  895. int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  896. int diff_main(int argc UNUSED_PARAM, char **argv)
  897. {
  898. int gotstdin = 0, i;
  899. char *file[2], *s_start = NULL;
  900. llist_t *L_arg = NULL;
  901. INIT_G();
  902. /* exactly 2 params; collect multiple -L <label>; -U N */
  903. opt_complementary = "=2:L::U+";
  904. #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
  905. applet_long_options = diff_longopts;
  906. #endif
  907. getopt32(argv, "abdiL:NqrsS:tTU:wupBE",
  908. &L_arg, &s_start, &opt_U_context);
  909. argv += optind;
  910. while (L_arg)
  911. label[!!label[0]] = llist_pop(&L_arg);
  912. xfunc_error_retval = 2;
  913. for (i = 0; i < 2; i++) {
  914. file[i] = argv[i];
  915. /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
  916. if (LONE_DASH(file[i])) {
  917. fstat(STDIN_FILENO, &stb[i]);
  918. gotstdin++;
  919. } else
  920. xstat(file[i], &stb[i]);
  921. }
  922. xfunc_error_retval = 1;
  923. if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
  924. bb_error_msg_and_die("can't compare stdin to a directory");
  925. /* Compare metadata to check if the files are the same physical file.
  926. *
  927. * Comment from diffutils source says:
  928. * POSIX says that two files are identical if st_ino and st_dev are
  929. * the same, but many file systems incorrectly assign the same (device,
  930. * inode) pair to two distinct files, including:
  931. * GNU/Linux NFS servers that export all local file systems as a
  932. * single NFS file system, if a local device number (st_dev) exceeds
  933. * 255, or if a local inode number (st_ino) exceeds 16777215.
  934. */
  935. if (ENABLE_DESKTOP
  936. && stb[0].st_ino == stb[1].st_ino
  937. && stb[0].st_dev == stb[1].st_dev
  938. && stb[0].st_size == stb[1].st_size
  939. && stb[0].st_mtime == stb[1].st_mtime
  940. && stb[0].st_ctime == stb[1].st_ctime
  941. && stb[0].st_mode == stb[1].st_mode
  942. && stb[0].st_nlink == stb[1].st_nlink
  943. && stb[0].st_uid == stb[1].st_uid
  944. && stb[0].st_gid == stb[1].st_gid
  945. ) {
  946. /* files are physically the same; no need to compare them */
  947. return STATUS_SAME;
  948. }
  949. if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
  950. #if ENABLE_FEATURE_DIFF_DIR
  951. diffdir(file, s_start);
  952. #else
  953. bb_error_msg_and_die("no support for directory comparison");
  954. #endif
  955. } else {
  956. bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
  957. bool dir = S_ISDIR(stb[1].st_mode);
  958. if (dirfile) {
  959. const char *slash = strrchr(file[!dir], '/');
  960. file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
  961. xstat(file[dir], &stb[dir]);
  962. }
  963. /* diffreg can get non-regular files here */
  964. print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
  965. if (dirfile)
  966. free(file[dir]);
  967. }
  968. return exit_status;
  969. }