decompress_bunzip2.c 23 KB

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