diff.c 27 KB

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