decompress_bunzip2.c 24 KB

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