decompress_bunzip2.c 23 KB

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