decompress_bunzip2.c 23 KB

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