decompress_bunzip2.c 23 KB

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