diff.c 30 KB

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