decompress_bunzip2.c 23 KB

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