diff.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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 begining, 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. printf("\n\\ No newline at end of file\n");
  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+1] - ix[j][k] != 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. printf(" @@\n");
  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) /* Prevents closing of stdin */
  681. close(fd);
  682. fd = fd_tmp;
  683. }
  684. fp[i] = fdopen(fd, "r");
  685. }
  686. while (1) {
  687. const size_t sz = COMMON_BUFSIZE / 2;
  688. char *const buf0 = bb_common_bufsiz1;
  689. char *const buf1 = buf0 + sz;
  690. int j, k;
  691. i = fread(buf0, 1, sz, fp[0]);
  692. j = fread(buf1, 1, sz, fp[1]);
  693. if (i != j) {
  694. differ = true;
  695. i = MIN(i, j);
  696. }
  697. if (i == 0)
  698. break;
  699. for (k = 0; k < i; k++) {
  700. if (!buf0[k] || !buf1[k])
  701. binary = true;
  702. if (buf0[k] != buf1[k])
  703. differ = true;
  704. }
  705. }
  706. if (differ) {
  707. if (binary && !(option_mask32 & FLAG(a)))
  708. status = STATUS_BINARY;
  709. else if (diff(fp, file))
  710. status = STATUS_DIFFER;
  711. }
  712. if (status != STATUS_SAME)
  713. exit_status |= 1;
  714. out:
  715. fclose_if_not_stdin(fp[0]);
  716. fclose_if_not_stdin(fp[1]);
  717. return status;
  718. }
  719. static void print_status(int status, char *path[2])
  720. {
  721. switch (status) {
  722. case STATUS_BINARY:
  723. case STATUS_DIFFER:
  724. if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
  725. printf("Files %s and %s differ\n", path[0], path[1]);
  726. break;
  727. case STATUS_SAME:
  728. if (option_mask32 & FLAG(s))
  729. printf("Files %s and %s are identical\n", path[0], path[1]);
  730. break;
  731. }
  732. }
  733. #if ENABLE_FEATURE_DIFF_DIR
  734. struct dlist {
  735. size_t len;
  736. int s, e;
  737. char **dl;
  738. };
  739. /* This function adds a filename to dl, the directory listing. */
  740. static int FAST_FUNC add_to_dirlist(const char *filename,
  741. struct stat *sb UNUSED_PARAM,
  742. void *userdata, int depth UNUSED_PARAM)
  743. {
  744. struct dlist *const l = userdata;
  745. const char *file = filename + l->len;
  746. while (*file == '/')
  747. file++;
  748. l->dl = xrealloc_vector(l->dl, 6, l->e);
  749. l->dl[l->e] = xstrdup(file);
  750. l->e++;
  751. return TRUE;
  752. }
  753. /* If recursion is not set, this function adds the directory
  754. * to the list and prevents recursive_action from recursing into it.
  755. */
  756. static int FAST_FUNC skip_dir(const char *filename,
  757. struct stat *sb, void *userdata,
  758. int depth)
  759. {
  760. if (!(option_mask32 & FLAG(r)) && depth) {
  761. add_to_dirlist(filename, sb, userdata, depth);
  762. return SKIP;
  763. }
  764. if (!(option_mask32 & FLAG(N))) {
  765. /* -r without -N: no need to recurse into dirs
  766. * which do not exist on the "other side".
  767. * Testcase: diff -r /tmp /
  768. * (it would recurse deep into /proc without this code) */
  769. struct dlist *const l = userdata;
  770. filename += l->len;
  771. if (filename[0]) {
  772. struct stat osb;
  773. char *othername = concat_path_file(G.other_dir, filename);
  774. int r = stat(othername, &osb);
  775. free(othername);
  776. if (r != 0 || !S_ISDIR(osb.st_mode)) {
  777. /* other dir doesn't have similarly named
  778. * directory, don't recurse; return 1 upon
  779. * exit, just like diffutils' diff */
  780. exit_status |= 1;
  781. return SKIP;
  782. }
  783. }
  784. }
  785. return TRUE;
  786. }
  787. static void diffdir(char *p[2], const char *s_start)
  788. {
  789. struct dlist list[2];
  790. int i;
  791. memset(&list, 0, sizeof(list));
  792. for (i = 0; i < 2; i++) {
  793. /*list[i].s = list[i].e = 0; - memset did it */
  794. /*list[i].dl = NULL; */
  795. G.other_dir = p[1 - i];
  796. /* We need to trim root directory prefix.
  797. * Using list.len to specify its length,
  798. * add_to_dirlist will remove it. */
  799. list[i].len = strlen(p[i]);
  800. recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
  801. add_to_dirlist, skip_dir, &list[i], 0);
  802. /* Sort dl alphabetically.
  803. * GNU diff does this ignoring any number of trailing dots.
  804. * We don't, so for us dotted files almost always are
  805. * first on the list.
  806. */
  807. qsort_string_vector(list[i].dl, list[i].e);
  808. /* If -S was set, find the starting point. */
  809. if (!s_start)
  810. continue;
  811. while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
  812. list[i].s++;
  813. }
  814. /* Now that both dirlist1 and dirlist2 contain sorted directory
  815. * listings, we can start to go through dirlist1. If both listings
  816. * contain the same file, then do a normal diff. Otherwise, behaviour
  817. * is determined by whether the -N flag is set. */
  818. while (1) {
  819. char *dp[2];
  820. int pos;
  821. int k;
  822. dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
  823. dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
  824. if (!dp[0] && !dp[1])
  825. break;
  826. pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
  827. k = pos > 0;
  828. if (pos && !(option_mask32 & FLAG(N))) {
  829. printf("Only in %s: %s\n", p[k], dp[k]);
  830. exit_status |= 1;
  831. } else {
  832. char *fullpath[2], *path[2]; /* if -N */
  833. for (i = 0; i < 2; i++) {
  834. if (pos == 0 || i == k) {
  835. path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
  836. stat(fullpath[i], &stb[i]);
  837. } else {
  838. fullpath[i] = concat_path_file(p[i], dp[1 - i]);
  839. path[i] = (char *)bb_dev_null;
  840. }
  841. }
  842. if (pos)
  843. stat(fullpath[k], &stb[1 - k]);
  844. if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
  845. printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
  846. else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
  847. printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
  848. else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
  849. printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
  850. else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
  851. if (S_ISDIR(stb[0].st_mode))
  852. printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
  853. else
  854. printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
  855. } else
  856. print_status(diffreg(path), fullpath);
  857. free(fullpath[0]);
  858. free(fullpath[1]);
  859. }
  860. free(dp[k]);
  861. list[k].s++;
  862. if (pos == 0) {
  863. free(dp[1 - k]);
  864. list[1 - k].s++;
  865. }
  866. }
  867. if (ENABLE_FEATURE_CLEAN_UP) {
  868. free(list[0].dl);
  869. free(list[1].dl);
  870. }
  871. }
  872. #endif
  873. #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
  874. static const char diff_longopts[] ALIGN1 =
  875. "ignore-case\0" No_argument "i"
  876. "ignore-tab-expansion\0" No_argument "E"
  877. "ignore-space-change\0" No_argument "b"
  878. "ignore-all-space\0" No_argument "w"
  879. "ignore-blank-lines\0" No_argument "B"
  880. "text\0" No_argument "a"
  881. "unified\0" Required_argument "U"
  882. "label\0" Required_argument "L"
  883. "show-c-function\0" No_argument "p"
  884. "brief\0" No_argument "q"
  885. "expand-tabs\0" No_argument "t"
  886. "initial-tab\0" No_argument "T"
  887. "recursive\0" No_argument "r"
  888. "new-file\0" No_argument "N"
  889. "report-identical-files\0" No_argument "s"
  890. "starting-file\0" Required_argument "S"
  891. "minimal\0" No_argument "d"
  892. ;
  893. #endif
  894. int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  895. int diff_main(int argc UNUSED_PARAM, char **argv)
  896. {
  897. int gotstdin = 0, i;
  898. char *file[2], *s_start = NULL;
  899. llist_t *L_arg = NULL;
  900. INIT_G();
  901. /* exactly 2 params; collect multiple -L <label>; -U N */
  902. opt_complementary = "=2:L::U+";
  903. #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
  904. applet_long_options = diff_longopts;
  905. #endif
  906. getopt32(argv, "abdiL:NqrsS:tTU:wupBE",
  907. &L_arg, &s_start, &opt_U_context);
  908. argv += optind;
  909. while (L_arg)
  910. label[!!label[0]] = llist_pop(&L_arg);
  911. xfunc_error_retval = 2;
  912. for (i = 0; i < 2; i++) {
  913. file[i] = argv[i];
  914. /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
  915. if (LONE_DASH(file[i])) {
  916. fstat(STDIN_FILENO, &stb[i]);
  917. gotstdin++;
  918. } else
  919. xstat(file[i], &stb[i]);
  920. }
  921. xfunc_error_retval = 1;
  922. if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
  923. bb_error_msg_and_die("can't compare stdin to a directory");
  924. /* Compare metadata to check if the files are the same physical file.
  925. *
  926. * Comment from diffutils source says:
  927. * POSIX says that two files are identical if st_ino and st_dev are
  928. * the same, but many file systems incorrectly assign the same (device,
  929. * inode) pair to two distinct files, including:
  930. * GNU/Linux NFS servers that export all local file systems as a
  931. * single NFS file system, if a local device number (st_dev) exceeds
  932. * 255, or if a local inode number (st_ino) exceeds 16777215.
  933. */
  934. if (ENABLE_DESKTOP
  935. && stb[0].st_ino == stb[1].st_ino
  936. && stb[0].st_dev == stb[1].st_dev
  937. && stb[0].st_size == stb[1].st_size
  938. && stb[0].st_mtime == stb[1].st_mtime
  939. && stb[0].st_ctime == stb[1].st_ctime
  940. && stb[0].st_mode == stb[1].st_mode
  941. && stb[0].st_nlink == stb[1].st_nlink
  942. && stb[0].st_uid == stb[1].st_uid
  943. && stb[0].st_gid == stb[1].st_gid
  944. ) {
  945. /* files are physically the same; no need to compare them */
  946. return STATUS_SAME;
  947. }
  948. if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
  949. #if ENABLE_FEATURE_DIFF_DIR
  950. diffdir(file, s_start);
  951. #else
  952. bb_error_msg_and_die("no support for directory comparison");
  953. #endif
  954. } else {
  955. bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
  956. bool dir = S_ISDIR(stb[1].st_mode);
  957. if (dirfile) {
  958. const char *slash = strrchr(file[!dir], '/');
  959. file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
  960. xstat(file[dir], &stb[dir]);
  961. }
  962. /* diffreg can get non-regular files here */
  963. print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
  964. if (dirfile)
  965. free(file[dir]);
  966. }
  967. return exit_status;
  968. }