decompress_bunzip2.c 23 KB

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