decompress_bunzip2.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).
  4. *
  5. * Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
  6. * which also acknowledges contributions by Mike Burrows, David Wheeler,
  7. * Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
  8. * Robert Sedgewick, and Jon L. Bentley.
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  11. */
  12. /*
  13. Size and speed optimizations by Manuel Novoa III (mjn3@codepoet.org).
  14. More efficient reading of Huffman codes, a streamlined read_bunzip()
  15. function, and various other tweaks. In (limited) tests, approximately
  16. 20% faster than bzcat on x86 and about 10% faster on arm.
  17. Note that about 2/3 of the time is spent in read_bunzip() reversing
  18. the Burrows-Wheeler transformation. Much of that time is delay
  19. resulting from cache misses.
  20. (2010 update by vda: profiled "bzcat <84mbyte.bz2 >/dev/null"
  21. on x86-64 CPU with L2 > 1M: get_next_block is hotter than read_bunzip:
  22. %time seconds calls function
  23. 71.01 12.69 444 get_next_block
  24. 28.65 5.12 93065 read_bunzip
  25. 00.22 0.04 7736490 get_bits
  26. 00.11 0.02 47 dealloc_bunzip
  27. 00.00 0.00 93018 full_write
  28. ...)
  29. I would ask that anyone benefiting from this work, especially those
  30. using it in commercial products, consider making a donation to my local
  31. non-profit hospice organization (www.hospiceacadiana.com) in the name of
  32. the woman I loved, Toni W. Hagan, who passed away Feb. 12, 2003.
  33. Manuel
  34. */
  35. #include "libbb.h"
  36. #include "bb_archive.h"
  37. #if 0
  38. # define dbg(...) bb_error_msg(__VA_ARGS__)
  39. #else
  40. # define dbg(...) ((void)0)
  41. #endif
  42. /* Constants for Huffman coding */
  43. #define MAX_GROUPS 6
  44. #define GROUP_SIZE 50 /* 64 would have been more efficient */
  45. #define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
  46. #define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
  47. #define SYMBOL_RUNA 0
  48. #define SYMBOL_RUNB 1
  49. /* Status return values */
  50. #define RETVAL_OK 0
  51. #define RETVAL_LAST_BLOCK (dbg("%d", __LINE__), -1)
  52. #define RETVAL_NOT_BZIP_DATA (dbg("%d", __LINE__), -2)
  53. #define RETVAL_UNEXPECTED_INPUT_EOF (dbg("%d", __LINE__), -3)
  54. #define RETVAL_SHORT_WRITE (dbg("%d", __LINE__), -4)
  55. #define RETVAL_DATA_ERROR (dbg("%d", __LINE__), -5)
  56. #define RETVAL_OUT_OF_MEMORY (dbg("%d", __LINE__), -6)
  57. #define RETVAL_OBSOLETE_INPUT (dbg("%d", __LINE__), -7)
  58. /* Other housekeeping constants */
  59. #define IOBUF_SIZE 4096
  60. /* This is what we know about each Huffman coding group */
  61. struct group_data {
  62. /* We have an extra slot at the end of limit[] for a sentinel value. */
  63. int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
  64. int minLen, maxLen;
  65. };
  66. /* Structure holding all the housekeeping data, including IO buffers and
  67. * memory that persists between calls to bunzip
  68. * Found the most used member:
  69. * cat this_file.c | sed -e 's/"/ /g' -e "s/'/ /g" | xargs -n1 \
  70. * | grep 'bd->' | sed 's/^.*bd->/bd->/' | sort | $PAGER
  71. * and moved it (inbufBitCount) to offset 0.
  72. */
  73. struct bunzip_data {
  74. /* I/O tracking data (file handles, buffers, positions, etc.) */
  75. unsigned inbufBitCount, inbufBits;
  76. int in_fd, out_fd, inbufCount, inbufPos /*, outbufPos*/;
  77. uint8_t *inbuf /*,*outbuf*/;
  78. /* State for interrupting output loop */
  79. int writeCopies, writePos, writeRunCountdown, writeCount;
  80. int writeCurrent; /* actually a uint8_t */
  81. /* The CRC values stored in the block header and calculated from the data */
  82. uint32_t headerCRC, totalCRC, writeCRC;
  83. /* Intermediate buffer and its size (in bytes) */
  84. uint32_t *dbuf;
  85. unsigned dbufSize;
  86. /* For I/O error handling */
  87. jmp_buf *jmpbuf;
  88. /* Big things go last (register-relative addressing can be larger for big offsets) */
  89. uint32_t crc32Table[256];
  90. uint8_t selectors[32768]; /* nSelectors=15 bits */
  91. struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */
  92. };
  93. typedef struct bunzip_data bunzip_data;
  94. /* Return the next nnn bits of input. All reads from the compressed input
  95. are done through this function. All reads are big endian */
  96. static unsigned get_bits(bunzip_data *bd, int bits_wanted)
  97. {
  98. unsigned bits = 0;
  99. /* Cache bd->inbufBitCount in a CPU register (hopefully): */
  100. int bit_count = bd->inbufBitCount;
  101. /* If we need to get more data from the byte buffer, do so. (Loop getting
  102. one byte at a time to enforce endianness and avoid unaligned access.) */
  103. while (bit_count < bits_wanted) {
  104. /* If we need to read more data from file into byte buffer, do so */
  105. if (bd->inbufPos == bd->inbufCount) {
  106. /* if "no input fd" case: in_fd == -1, read fails, we jump */
  107. bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);
  108. if (bd->inbufCount <= 0)
  109. longjmp(*bd->jmpbuf, RETVAL_UNEXPECTED_INPUT_EOF);
  110. bd->inbufPos = 0;
  111. }
  112. /* Avoid 32-bit overflow (dump bit buffer to top of output) */
  113. if (bit_count >= 24) {
  114. bits = bd->inbufBits & ((1U << bit_count) - 1);
  115. bits_wanted -= bit_count;
  116. bits <<= bits_wanted;
  117. bit_count = 0;
  118. }
  119. /* Grab next 8 bits of input from buffer. */
  120. bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
  121. bit_count += 8;
  122. }
  123. /* Calculate result */
  124. bit_count -= bits_wanted;
  125. bd->inbufBitCount = bit_count;
  126. bits |= (bd->inbufBits >> bit_count) & ((1 << bits_wanted) - 1);
  127. return bits;
  128. }
  129. //#define get_bits(bd, n) (dbg("%d:get_bits()", __LINE__), get_bits(bd, n))
  130. /* Unpacks the next block and sets up for the inverse Burrows-Wheeler step. */
  131. static int get_next_block(bunzip_data *bd)
  132. {
  133. int groupCount, selector,
  134. i, j, symCount, symTotal, nSelectors, byteCount[256];
  135. uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
  136. uint32_t *dbuf;
  137. unsigned origPtr, t;
  138. unsigned dbufCount, runPos;
  139. unsigned runCnt = runCnt; /* for compiler */
  140. dbuf = bd->dbuf;
  141. selectors = bd->selectors;
  142. /* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
  143. #if 0
  144. /* Reset longjmp I/O error handling */
  145. i = setjmp(bd->jmpbuf);
  146. if (i) return i;
  147. #endif
  148. /* Read in header signature and CRC, then validate signature.
  149. (last block signature means CRC is for whole file, return now) */
  150. i = get_bits(bd, 24);
  151. j = get_bits(bd, 24);
  152. bd->headerCRC = get_bits(bd, 32);
  153. if ((i == 0x177245) && (j == 0x385090))
  154. return RETVAL_LAST_BLOCK;
  155. if ((i != 0x314159) || (j != 0x265359))
  156. return RETVAL_NOT_BZIP_DATA;
  157. /* We can add support for blockRandomised if anybody complains. There was
  158. some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
  159. it didn't actually work. */
  160. if (get_bits(bd, 1))
  161. return RETVAL_OBSOLETE_INPUT;
  162. origPtr = get_bits(bd, 24);
  163. if (origPtr > bd->dbufSize)
  164. return RETVAL_DATA_ERROR;
  165. /* mapping table: if some byte values are never used (encoding things
  166. like ascii text), the compression code removes the gaps to have fewer
  167. symbols to deal with, and writes a sparse bitfield indicating which
  168. values were present. We make a translation table to convert the symbols
  169. back to the corresponding bytes. */
  170. symTotal = 0;
  171. i = 0;
  172. t = get_bits(bd, 16);
  173. do {
  174. if (t & (1 << 15)) {
  175. unsigned inner_map = get_bits(bd, 16);
  176. do {
  177. if (inner_map & (1 << 15))
  178. symToByte[symTotal++] = i;
  179. inner_map <<= 1;
  180. i++;
  181. } while (i & 15);
  182. i -= 16;
  183. }
  184. t <<= 1;
  185. i += 16;
  186. } while (i < 256);
  187. /* How many different Huffman coding groups does this block use? */
  188. groupCount = get_bits(bd, 3);
  189. if (groupCount < 2 || groupCount > MAX_GROUPS)
  190. return RETVAL_DATA_ERROR;
  191. /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
  192. group. Read in the group selector list, which is stored as MTF encoded
  193. bit runs. (MTF=Move To Front, as each value is used it's moved to the
  194. start of the list.) */
  195. for (i = 0; i < groupCount; i++)
  196. mtfSymbol[i] = i;
  197. nSelectors = get_bits(bd, 15);
  198. if (!nSelectors)
  199. return RETVAL_DATA_ERROR;
  200. for (i = 0; i < nSelectors; i++) {
  201. uint8_t tmp_byte;
  202. /* Get next value */
  203. int n = 0;
  204. while (get_bits(bd, 1)) {
  205. n++;
  206. if (n >= groupCount)
  207. return RETVAL_DATA_ERROR;
  208. }
  209. /* Decode MTF to get the next selector */
  210. tmp_byte = mtfSymbol[n];
  211. while (--n >= 0)
  212. mtfSymbol[n + 1] = mtfSymbol[n];
  213. //We catch it later, in the second loop where we use selectors[i].
  214. //Maybe this is a better place, though?
  215. // if (tmp_byte >= groupCount) {
  216. // dbg("%d: selectors[%d]:%d groupCount:%d",
  217. // __LINE__, i, tmp_byte, groupCount);
  218. // return RETVAL_DATA_ERROR;
  219. // }
  220. mtfSymbol[0] = selectors[i] = tmp_byte;
  221. }
  222. /* Read the Huffman coding tables for each group, which code for symTotal
  223. literal symbols, plus two run symbols (RUNA, RUNB) */
  224. symCount = symTotal + 2;
  225. for (j = 0; j < groupCount; j++) {
  226. uint8_t length[MAX_SYMBOLS];
  227. /* 8 bits is ALMOST enough for temp[], see below */
  228. unsigned temp[MAX_HUFCODE_BITS+1];
  229. struct group_data *hufGroup;
  230. int *base, *limit;
  231. int minLen, maxLen, pp, len_m1;
  232. /* Read Huffman code lengths for each symbol. They're stored in
  233. a way similar to mtf; record a starting value for the first symbol,
  234. and an offset from the previous value for every symbol after that.
  235. (Subtracting 1 before the loop and then adding it back at the end is
  236. an optimization that makes the test inside the loop simpler: symbol
  237. length 0 becomes negative, so an unsigned inequality catches it.) */
  238. len_m1 = get_bits(bd, 5) - 1;
  239. for (i = 0; i < symCount; i++) {
  240. for (;;) {
  241. int two_bits;
  242. if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
  243. return RETVAL_DATA_ERROR;
  244. /* If first bit is 0, stop. Else second bit indicates whether
  245. to increment or decrement the value. Optimization: grab 2
  246. bits and unget the second if the first was 0. */
  247. two_bits = get_bits(bd, 2);
  248. if (two_bits < 2) {
  249. bd->inbufBitCount++;
  250. break;
  251. }
  252. /* Add one if second bit 1, else subtract 1. Avoids if/else */
  253. len_m1 += (((two_bits+1) & 2) - 1);
  254. }
  255. /* Correct for the initial -1, to get the final symbol length */
  256. length[i] = len_m1 + 1;
  257. }
  258. /* Find largest and smallest lengths in this group */
  259. minLen = maxLen = length[0];
  260. for (i = 1; i < symCount; i++) {
  261. if (length[i] > maxLen)
  262. maxLen = length[i];
  263. else if (length[i] < minLen)
  264. minLen = length[i];
  265. }
  266. /* Calculate permute[], base[], and limit[] tables from length[].
  267. *
  268. * permute[] is the lookup table for converting Huffman coded symbols
  269. * into decoded symbols. base[] is the amount to subtract from the
  270. * value of a Huffman symbol of a given length when using permute[].
  271. *
  272. * limit[] indicates the largest numerical value a symbol with a given
  273. * number of bits can have. This is how the Huffman codes can vary in
  274. * length: each code with a value>limit[length] needs another bit.
  275. */
  276. hufGroup = bd->groups + j;
  277. hufGroup->minLen = minLen;
  278. hufGroup->maxLen = maxLen;
  279. /* Note that minLen can't be smaller than 1, so we adjust the base
  280. and limit array pointers so we're not always wasting the first
  281. entry. We do this again when using them (during symbol decoding). */
  282. base = hufGroup->base - 1;
  283. limit = hufGroup->limit - 1;
  284. /* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */
  285. pp = 0;
  286. for (i = minLen; i <= maxLen; i++) {
  287. int k;
  288. temp[i] = limit[i] = 0;
  289. for (k = 0; k < symCount; k++)
  290. if (length[k] == i)
  291. hufGroup->permute[pp++] = k;
  292. }
  293. /* Count symbols coded for at each bit length */
  294. /* NB: in pathological cases, temp[8] can end ip being 256.
  295. * That's why uint8_t is too small for temp[]. */
  296. for (i = 0; i < symCount; i++)
  297. temp[length[i]]++;
  298. /* Calculate limit[] (the largest symbol-coding value at each bit
  299. * length, which is (previous limit<<1)+symbols at this level), and
  300. * base[] (number of symbols to ignore at each bit length, which is
  301. * limit minus the cumulative count of symbols coded for already). */
  302. pp = t = 0;
  303. for (i = minLen; i < maxLen;) {
  304. unsigned temp_i = temp[i];
  305. pp += temp_i;
  306. /* We read the largest possible symbol size and then unget bits
  307. after determining how many we need, and those extra bits could
  308. be set to anything. (They're noise from future symbols.) At
  309. each level we're really only interested in the first few bits,
  310. so here we set all the trailing to-be-ignored bits to 1 so they
  311. don't affect the value>limit[length] comparison. */
  312. limit[i] = (pp << (maxLen - i)) - 1;
  313. pp <<= 1;
  314. t += temp_i;
  315. base[++i] = pp - t;
  316. }
  317. limit[maxLen] = pp + temp[maxLen] - 1;
  318. limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
  319. base[minLen] = 0;
  320. }
  321. /* We've finished reading and digesting the block header. Now read this
  322. block's Huffman coded symbols from the file and undo the Huffman coding
  323. and run length encoding, saving the result into dbuf[dbufCount++] = uc */
  324. /* Initialize symbol occurrence counters and symbol Move To Front table */
  325. /*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
  326. for (i = 0; i < 256; i++) {
  327. byteCount[i] = 0;
  328. mtfSymbol[i] = (uint8_t)i;
  329. }
  330. /* Loop through compressed symbols. */
  331. runPos = dbufCount = selector = 0;
  332. for (;;) {
  333. struct group_data *hufGroup;
  334. int *base, *limit;
  335. int nextSym;
  336. uint8_t ngrp;
  337. /* Fetch next Huffman coding group from list. */
  338. symCount = GROUP_SIZE - 1;
  339. if (selector >= nSelectors)
  340. return RETVAL_DATA_ERROR;
  341. ngrp = selectors[selector++];
  342. if (ngrp >= groupCount) {
  343. dbg("%d selectors[%d]:%d groupCount:%d",
  344. __LINE__, selector-1, ngrp, groupCount);
  345. return RETVAL_DATA_ERROR;
  346. }
  347. hufGroup = bd->groups + ngrp;
  348. base = hufGroup->base - 1;
  349. limit = hufGroup->limit - 1;
  350. continue_this_group:
  351. /* Read next Huffman-coded symbol. */
  352. /* Note: It is far cheaper to read maxLen bits and back up than it is
  353. to read minLen bits and then add additional bit at a time, testing
  354. as we go. Because there is a trailing last block (with file CRC),
  355. there is no danger of the overread causing an unexpected EOF for a
  356. valid compressed file.
  357. */
  358. if (1) {
  359. /* As a further optimization, we do the read inline
  360. (falling back to a call to get_bits if the buffer runs dry).
  361. */
  362. int new_cnt;
  363. while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
  364. /* bd->inbufBitCount < hufGroup->maxLen */
  365. if (bd->inbufPos == bd->inbufCount) {
  366. nextSym = get_bits(bd, hufGroup->maxLen);
  367. goto got_huff_bits;
  368. }
  369. bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
  370. bd->inbufBitCount += 8;
  371. };
  372. bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
  373. nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
  374. got_huff_bits: ;
  375. } else { /* unoptimized equivalent */
  376. nextSym = get_bits(bd, hufGroup->maxLen);
  377. }
  378. /* Figure how many bits are in next symbol and unget extras */
  379. i = hufGroup->minLen;
  380. while (nextSym > limit[i])
  381. ++i;
  382. j = hufGroup->maxLen - i;
  383. if (j < 0)
  384. return RETVAL_DATA_ERROR;
  385. bd->inbufBitCount += j;
  386. /* Huffman decode value to get nextSym (with bounds checking) */
  387. nextSym = (nextSym >> j) - base[i];
  388. if ((unsigned)nextSym >= MAX_SYMBOLS)
  389. return RETVAL_DATA_ERROR;
  390. nextSym = hufGroup->permute[nextSym];
  391. /* We have now decoded the symbol, which indicates either a new literal
  392. byte, or a repeated run of the most recent literal byte. First,
  393. check if nextSym indicates a repeated run, and if so loop collecting
  394. how many times to repeat the last literal. */
  395. if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
  396. /* If this is the start of a new run, zero out counter */
  397. if (runPos == 0) {
  398. runPos = 1;
  399. runCnt = 0;
  400. }
  401. /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
  402. each bit position, add 1 or 2 instead. For example,
  403. 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
  404. You can make any bit pattern that way using 1 less symbol than
  405. the basic or 0/1 method (except all bits 0, which would use no
  406. symbols, but a run of length 0 doesn't mean anything in this
  407. context). Thus space is saved. */
  408. runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
  409. //The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
  410. //This would be the fix (catches too large count way before it can overflow):
  411. // if (runCnt > bd->dbufSize) {
  412. // dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
  413. // runCnt, bd->dbufSize);
  414. // return RETVAL_DATA_ERROR;
  415. // }
  416. if (runPos < bd->dbufSize) runPos <<= 1;
  417. goto end_of_huffman_loop;
  418. }
  419. /* When we hit the first non-run symbol after a run, we now know
  420. how many times to repeat the last literal, so append that many
  421. copies to our buffer of decoded symbols (dbuf) now. (The last
  422. literal used is the one at the head of the mtfSymbol array.) */
  423. if (runPos != 0) {
  424. uint8_t tmp_byte;
  425. if (dbufCount + runCnt > bd->dbufSize) {
  426. dbg("dbufCount:%u+runCnt:%u %u > dbufSize:%u RETVAL_DATA_ERROR",
  427. dbufCount, runCnt, dbufCount + runCnt, bd->dbufSize);
  428. return RETVAL_DATA_ERROR;
  429. }
  430. tmp_byte = symToByte[mtfSymbol[0]];
  431. byteCount[tmp_byte] += runCnt;
  432. while ((int)--runCnt >= 0)
  433. dbuf[dbufCount++] = (uint32_t)tmp_byte;
  434. runPos = 0;
  435. }
  436. /* Is this the terminating symbol? */
  437. if (nextSym > symTotal) break;
  438. /* At this point, nextSym indicates a new literal character. Subtract
  439. one to get the position in the MTF array at which this literal is
  440. currently to be found. (Note that the result can't be -1 or 0,
  441. because 0 and 1 are RUNA and RUNB. But another instance of the
  442. first symbol in the mtf array, position 0, would have been handled
  443. as part of a run above. Therefore 1 unused mtf position minus
  444. 2 non-literal nextSym values equals -1.) */
  445. if (dbufCount >= bd->dbufSize) return RETVAL_DATA_ERROR;
  446. i = nextSym - 1;
  447. uc = mtfSymbol[i];
  448. /* Adjust the MTF array. Since we typically expect to move only a
  449. * small number of symbols, and are bound by 256 in any case, using
  450. * memmove here would typically be bigger and slower due to function
  451. * call overhead and other assorted setup costs. */
  452. do {
  453. mtfSymbol[i] = mtfSymbol[i-1];
  454. } while (--i);
  455. mtfSymbol[0] = uc;
  456. uc = symToByte[uc];
  457. /* We have our literal byte. Save it into dbuf. */
  458. byteCount[uc]++;
  459. dbuf[dbufCount++] = (uint32_t)uc;
  460. /* Skip group initialization if we're not done with this group. Done
  461. * this way to avoid compiler warning. */
  462. end_of_huffman_loop:
  463. if (--symCount >= 0) goto continue_this_group;
  464. }
  465. /* At this point, we've read all the Huffman-coded symbols (and repeated
  466. runs) for this block from the input stream, and decoded them into the
  467. intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
  468. Now undo the Burrows-Wheeler transform on dbuf.
  469. See http://dogma.net/markn/articles/bwt/bwt.htm
  470. */
  471. /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
  472. j = 0;
  473. for (i = 0; i < 256; i++) {
  474. int tmp_count = j + byteCount[i];
  475. byteCount[i] = j;
  476. j = tmp_count;
  477. }
  478. /* Figure out what order dbuf would be in if we sorted it. */
  479. for (i = 0; i < dbufCount; i++) {
  480. uint8_t tmp_byte = (uint8_t)dbuf[i];
  481. int tmp_count = byteCount[tmp_byte];
  482. dbuf[tmp_count] |= (i << 8);
  483. byteCount[tmp_byte] = tmp_count + 1;
  484. }
  485. /* Decode first byte by hand to initialize "previous" byte. Note that it
  486. doesn't get output, and if the first three characters are identical
  487. it doesn't qualify as a run (hence writeRunCountdown=5). */
  488. if (dbufCount) {
  489. uint32_t tmp;
  490. if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
  491. tmp = dbuf[origPtr];
  492. bd->writeCurrent = (uint8_t)tmp;
  493. bd->writePos = (tmp >> 8);
  494. bd->writeRunCountdown = 5;
  495. }
  496. bd->writeCount = dbufCount;
  497. return RETVAL_OK;
  498. }
  499. /* Undo Burrows-Wheeler transform on intermediate buffer to produce output.
  500. If start_bunzip was initialized with out_fd=-1, then up to len bytes of
  501. data are written to outbuf. Return value is number of bytes written or
  502. error (all errors are negative numbers). If out_fd!=-1, outbuf and len
  503. are ignored, data is written to out_fd and return is RETVAL_OK or error.
  504. NB: read_bunzip returns < 0 on error, or the number of *unfilled* bytes
  505. in outbuf. IOW: on EOF returns len ("all bytes are not filled"), not 0.
  506. (Why? This allows to get rid of one local variable)
  507. */
  508. static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
  509. {
  510. const uint32_t *dbuf;
  511. int pos, current, previous;
  512. uint32_t CRC;
  513. /* If we already have error/end indicator, return it */
  514. if (bd->writeCount < 0)
  515. return bd->writeCount;
  516. dbuf = bd->dbuf;
  517. /* Register-cached state (hopefully): */
  518. pos = bd->writePos;
  519. current = bd->writeCurrent;
  520. CRC = bd->writeCRC; /* small loss on x86-32 (not enough regs), win on x86-64 */
  521. /* We will always have pending decoded data to write into the output
  522. buffer unless this is the very first call (in which case we haven't
  523. Huffman-decoded a block into the intermediate buffer yet). */
  524. if (bd->writeCopies) {
  525. dec_writeCopies:
  526. /* Inside the loop, writeCopies means extra copies (beyond 1) */
  527. --bd->writeCopies;
  528. /* Loop outputting bytes */
  529. for (;;) {
  530. /* If the output buffer is full, save cached state and return */
  531. if (--len < 0) {
  532. /* Unlikely branch.
  533. * Use of "goto" instead of keeping code here
  534. * helps compiler to realize this. */
  535. goto outbuf_full;
  536. }
  537. /* Write next byte into output buffer, updating CRC */
  538. *outbuf++ = current;
  539. CRC = (CRC << 8) ^ bd->crc32Table[(CRC >> 24) ^ current];
  540. /* Loop now if we're outputting multiple copies of this byte */
  541. if (bd->writeCopies) {
  542. /* Unlikely branch */
  543. /*--bd->writeCopies;*/
  544. /*continue;*/
  545. /* Same, but (ab)using other existing --writeCopies operation
  546. * (and this if() compiles into just test+branch pair): */
  547. goto dec_writeCopies;
  548. }
  549. decode_next_byte:
  550. if (--bd->writeCount < 0)
  551. break; /* input block is fully consumed, need next one */
  552. /* Follow sequence vector to undo Burrows-Wheeler transform */
  553. previous = current;
  554. pos = dbuf[pos];
  555. current = (uint8_t)pos;
  556. pos >>= 8;
  557. /* After 3 consecutive copies of the same byte, the 4th
  558. * is a repeat count. We count down from 4 instead
  559. * of counting up because testing for non-zero is faster */
  560. if (--bd->writeRunCountdown != 0) {
  561. if (current != previous)
  562. bd->writeRunCountdown = 4;
  563. } else {
  564. /* Unlikely branch */
  565. /* We have a repeated run, this byte indicates the count */
  566. bd->writeCopies = current;
  567. current = previous;
  568. bd->writeRunCountdown = 5;
  569. /* Sometimes there are just 3 bytes (run length 0) */
  570. if (!bd->writeCopies) goto decode_next_byte;
  571. /* Subtract the 1 copy we'd output anyway to get extras */
  572. --bd->writeCopies;
  573. }
  574. } /* for(;;) */
  575. /* Decompression of this input block completed successfully */
  576. bd->writeCRC = CRC = ~CRC;
  577. bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ CRC;
  578. /* If this block had a CRC error, force file level CRC error */
  579. if (CRC != bd->headerCRC) {
  580. bd->totalCRC = bd->headerCRC + 1;
  581. return RETVAL_LAST_BLOCK;
  582. }
  583. }
  584. /* Refill the intermediate buffer by Huffman-decoding next block of input */
  585. {
  586. int r = get_next_block(bd);
  587. if (r) { /* error/end */
  588. bd->writeCount = r;
  589. return (r != RETVAL_LAST_BLOCK) ? r : len;
  590. }
  591. }
  592. CRC = ~0;
  593. pos = bd->writePos;
  594. current = bd->writeCurrent;
  595. goto decode_next_byte;
  596. outbuf_full:
  597. /* Output buffer is full, save cached state and return */
  598. bd->writePos = pos;
  599. bd->writeCurrent = current;
  600. bd->writeCRC = CRC;
  601. bd->writeCopies++;
  602. return 0;
  603. }
  604. /* Allocate the structure, read file header. If in_fd==-1, inbuf must contain
  605. a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are
  606. ignored, and data is read from file handle into temporary buffer. */
  607. /* Because bunzip2 is used for help text unpacking, and because bb_show_usage()
  608. should work for NOFORK applets too, we must be extremely careful to not leak
  609. any allocations! */
  610. static int FAST_FUNC start_bunzip(
  611. void *jmpbuf,
  612. bunzip_data **bdp,
  613. int in_fd,
  614. const void *inbuf, int len)
  615. {
  616. bunzip_data *bd;
  617. unsigned i;
  618. enum {
  619. BZh0 = ('B' << 24) + ('Z' << 16) + ('h' << 8) + '0',
  620. h0 = ('h' << 8) + '0',
  621. };
  622. /* Figure out how much data to allocate */
  623. i = sizeof(bunzip_data);
  624. if (in_fd != -1)
  625. i += IOBUF_SIZE;
  626. /* Allocate bunzip_data. Most fields initialize to zero. */
  627. bd = *bdp = xzalloc(i);
  628. bd->jmpbuf = jmpbuf;
  629. /* Setup input buffer */
  630. bd->in_fd = in_fd;
  631. if (-1 == in_fd) {
  632. /* in this case, bd->inbuf is read-only */
  633. bd->inbuf = (void*)inbuf; /* cast away const-ness */
  634. } else {
  635. bd->inbuf = (uint8_t*)(bd + 1);
  636. memcpy(bd->inbuf, inbuf, len);
  637. }
  638. bd->inbufCount = len;
  639. /* Init the CRC32 table (big endian) */
  640. crc32_filltable(bd->crc32Table, 1);
  641. /* Ensure that file starts with "BZh['1'-'9']." */
  642. /* Update: now caller verifies 1st two bytes, makes .gz/.bz2
  643. * integration easier */
  644. /* was: */
  645. /* i = get_bits(bd, 32); */
  646. /* if ((unsigned)(i - BZh0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA; */
  647. i = get_bits(bd, 16);
  648. if ((unsigned)(i - h0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA;
  649. /* Fourth byte (ascii '1'-'9') indicates block size in units of 100k of
  650. uncompressed data. Allocate intermediate buffer for block. */
  651. /* bd->dbufSize = 100000 * (i - BZh0); */
  652. bd->dbufSize = 100000 * (i - h0);
  653. /* Cannot use xmalloc - may leak bd in NOFORK case! */
  654. bd->dbuf = malloc_or_warn(bd->dbufSize * sizeof(bd->dbuf[0]));
  655. if (!bd->dbuf) {
  656. free(bd);
  657. xfunc_die();
  658. }
  659. return RETVAL_OK;
  660. }
  661. static void FAST_FUNC dealloc_bunzip(bunzip_data *bd)
  662. {
  663. free(bd->dbuf);
  664. free(bd);
  665. }
  666. /* Decompress src_fd to dst_fd. Stops at end of bzip data, not end of file. */
  667. IF_DESKTOP(long long) int FAST_FUNC
  668. unpack_bz2_stream(transformer_state_t *xstate)
  669. {
  670. IF_DESKTOP(long long total_written = 0;)
  671. bunzip_data *bd;
  672. char *outbuf;
  673. int i;
  674. unsigned len;
  675. if (check_signature16(xstate, BZIP2_MAGIC))
  676. return -1;
  677. outbuf = xmalloc(IOBUF_SIZE);
  678. len = 0;
  679. while (1) { /* "Process one BZ... stream" loop */
  680. jmp_buf jmpbuf;
  681. /* Setup for I/O error handling via longjmp */
  682. i = setjmp(jmpbuf);
  683. if (i == 0)
  684. i = start_bunzip(&jmpbuf, &bd, xstate->src_fd, outbuf + 2, len);
  685. if (i == 0) {
  686. while (1) { /* "Produce some output bytes" loop */
  687. i = read_bunzip(bd, outbuf, IOBUF_SIZE);
  688. if (i < 0) /* error? */
  689. break;
  690. i = IOBUF_SIZE - i; /* number of bytes produced */
  691. if (i == 0) /* EOF? */
  692. break;
  693. if (i != transformer_write(xstate, outbuf, i)) {
  694. i = RETVAL_SHORT_WRITE;
  695. goto release_mem;
  696. }
  697. IF_DESKTOP(total_written += i;)
  698. }
  699. }
  700. if (i != RETVAL_LAST_BLOCK
  701. /* Observed case when i == RETVAL_OK:
  702. * "bzcat z.bz2", where "z.bz2" is a bzipped zero-length file
  703. * (to be exact, z.bz2 is exactly these 14 bytes:
  704. * 42 5a 68 39 17 72 45 38 50 90 00 00 00 00).
  705. */
  706. && i != RETVAL_OK
  707. ) {
  708. bb_error_msg("bunzip error %d", i);
  709. break;
  710. }
  711. if (bd->headerCRC != bd->totalCRC) {
  712. bb_simple_error_msg("CRC error");
  713. break;
  714. }
  715. /* Successfully unpacked one BZ stream */
  716. i = RETVAL_OK;
  717. /* Do we have "BZ..." after last processed byte?
  718. * pbzip2 (parallelized bzip2) produces such files.
  719. */
  720. len = bd->inbufCount - bd->inbufPos;
  721. memcpy(outbuf, &bd->inbuf[bd->inbufPos], len);
  722. if (len < 2) {
  723. if (safe_read(xstate->src_fd, outbuf + len, 2 - len) != 2 - len)
  724. break;
  725. len = 2;
  726. }
  727. if (*(uint16_t*)outbuf != BZIP2_MAGIC) /* "BZ"? */
  728. break;
  729. dealloc_bunzip(bd);
  730. len -= 2;
  731. }
  732. release_mem:
  733. dealloc_bunzip(bd);
  734. free(outbuf);
  735. return i ? i : IF_DESKTOP(total_written) + 0;
  736. }
  737. char* FAST_FUNC
  738. unpack_bz2_data(const char *packed, int packed_len, int unpacked_len)
  739. {
  740. char *outbuf = NULL;
  741. bunzip_data *bd;
  742. int i;
  743. jmp_buf jmpbuf;
  744. /* Setup for I/O error handling via longjmp */
  745. i = setjmp(jmpbuf);
  746. if (i == 0) {
  747. i = start_bunzip(&jmpbuf,
  748. &bd,
  749. /* src_fd: */ -1,
  750. /* inbuf: */ packed,
  751. /* len: */ packed_len
  752. );
  753. }
  754. /* read_bunzip can longjmp and end up here with i != 0
  755. * on read data errors! Not trivial */
  756. if (i == 0) {
  757. /* Cannot use xmalloc: will leak bd in NOFORK case! */
  758. outbuf = malloc_or_warn(unpacked_len);
  759. if (outbuf)
  760. read_bunzip(bd, outbuf, unpacked_len);
  761. }
  762. dealloc_bunzip(bd);
  763. return outbuf;
  764. }
  765. #ifdef TESTING
  766. static char *const bunzip_errors[] = {
  767. NULL, "Bad file checksum", "Not bzip data",
  768. "Unexpected input EOF", "Unexpected output EOF", "Data error",
  769. "Out of memory", "Obsolete (pre 0.9.5) bzip format not supported"
  770. };
  771. /* Dumb little test thing, decompress stdin to stdout */
  772. int main(int argc, char **argv)
  773. {
  774. char c;
  775. int i = unpack_bz2_stream(0, 1);
  776. if (i < 0)
  777. fprintf(stderr, "%s\n", bunzip_errors[-i]);
  778. else if (read(STDIN_FILENO, &c, 1))
  779. fprintf(stderr, "Trailing garbage ignored\n");
  780. return -i;
  781. }
  782. #endif