decompress_bunzip2.c 26 KB

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