decompress_bunzip2.c 23 KB

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