decompress_bunzip2.c 22 KB

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