decompress_bunzip2.c 22 KB

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