/* vi: set sw = 4 ts = 4: */1/* Small bzip2 deflate implementation, by Rob Landley ([email protected]).23Based on bzip2 decompression code by Julian R Seward ([email protected]),4which also acknowledges contributions by Mike Burrows, David Wheeler,5Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,6Robert Sedgewick, and Jon L. Bentley.78This code is licensed under the LGPLv2:9LGPL (http://www.gnu.org/copyleft/lgpl.html10*/1112/*13Size and speed optimizations by Manuel Novoa III ([email protected]).1415More efficient reading of Huffman codes, a streamlined read_bunzip()16function, and various other tweaks. In (limited) tests, approximately1720% faster than bzcat on x86 and about 10% faster on arm.1819Note that about 2/3 of the time is spent in read_unzip() reversing20the Burrows-Wheeler transformation. Much of that time is delay21resulting from cache misses.2223I would ask that anyone benefiting from this work, especially those24using it in commercial products, consider making a donation to my local25non-profit hospice organization in the name of the woman I loved, who26passed away Feb. 12, 2003.2728In memory of Toni W. Hagan2930Hospice of Acadiana, Inc.312600 Johnston St., Suite 20032Lafayette, LA 70503-32403334Phone (337) 232-1234 or 1-800-738-222635Fax (337) 232-12973637http://www.hospiceacadiana.com/3839Manuel40*/4142/*43Made it fit for running in Linux Kernel by Alain Knaff ([email protected])44*/454647#ifdef STATIC48#define PREBOOT49#else50#include <linux/decompress/bunzip2.h>51#endif /* STATIC */5253#include <linux/decompress/mm.h>5455#ifndef INT_MAX56#define INT_MAX 0x7fffffff57#endif5859/* Constants for Huffman coding */60#define MAX_GROUPS 661#define GROUP_SIZE 50 /* 64 would have been more efficient */62#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */63#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */64#define SYMBOL_RUNA 065#define SYMBOL_RUNB 16667/* Status return values */68#define RETVAL_OK 069#define RETVAL_LAST_BLOCK (-1)70#define RETVAL_NOT_BZIP_DATA (-2)71#define RETVAL_UNEXPECTED_INPUT_EOF (-3)72#define RETVAL_UNEXPECTED_OUTPUT_EOF (-4)73#define RETVAL_DATA_ERROR (-5)74#define RETVAL_OUT_OF_MEMORY (-6)75#define RETVAL_OBSOLETE_INPUT (-7)7677/* Other housekeeping constants */78#define BZIP2_IOBUF_SIZE 40967980/* This is what we know about each Huffman coding group */81struct group_data {82/* We have an extra slot at the end of limit[] for a sentinal value. */83int limit[MAX_HUFCODE_BITS+1];84int base[MAX_HUFCODE_BITS];85int permute[MAX_SYMBOLS];86int minLen, maxLen;87};8889/* Structure holding all the housekeeping data, including IO buffers and90memory that persists between calls to bunzip */91struct bunzip_data {92/* State for interrupting output loop */93int writeCopies, writePos, writeRunCountdown, writeCount, writeCurrent;94/* I/O tracking data (file handles, buffers, positions, etc.) */95int (*fill)(void*, unsigned int);96int inbufCount, inbufPos /*, outbufPos*/;97unsigned char *inbuf /*,*outbuf*/;98unsigned int inbufBitCount, inbufBits;99/* The CRC values stored in the block header and calculated from the100data */101unsigned int crc32Table[256], headerCRC, totalCRC, writeCRC;102/* Intermediate buffer and its size (in bytes) */103unsigned int *dbuf, dbufSize;104/* These things are a bit too big to go on the stack */105unsigned char selectors[32768]; /* nSelectors = 15 bits */106struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */107int io_error; /* non-zero if we have IO error */108int byteCount[256];109unsigned char symToByte[256], mtfSymbol[256];110};111112113/* Return the next nnn bits of input. All reads from the compressed input114are done through this function. All reads are big endian */115static unsigned int INIT get_bits(struct bunzip_data *bd, char bits_wanted)116{117unsigned int bits = 0;118119/* If we need to get more data from the byte buffer, do so.120(Loop getting one byte at a time to enforce endianness and avoid121unaligned access.) */122while (bd->inbufBitCount < bits_wanted) {123/* If we need to read more data from file into byte buffer, do124so */125if (bd->inbufPos == bd->inbufCount) {126if (bd->io_error)127return 0;128bd->inbufCount = bd->fill(bd->inbuf, BZIP2_IOBUF_SIZE);129if (bd->inbufCount <= 0) {130bd->io_error = RETVAL_UNEXPECTED_INPUT_EOF;131return 0;132}133bd->inbufPos = 0;134}135/* Avoid 32-bit overflow (dump bit buffer to top of output) */136if (bd->inbufBitCount >= 24) {137bits = bd->inbufBits&((1 << bd->inbufBitCount)-1);138bits_wanted -= bd->inbufBitCount;139bits <<= bits_wanted;140bd->inbufBitCount = 0;141}142/* Grab next 8 bits of input from buffer. */143bd->inbufBits = (bd->inbufBits << 8)|bd->inbuf[bd->inbufPos++];144bd->inbufBitCount += 8;145}146/* Calculate result */147bd->inbufBitCount -= bits_wanted;148bits |= (bd->inbufBits >> bd->inbufBitCount)&((1 << bits_wanted)-1);149150return bits;151}152153/* Unpacks the next block and sets up for the inverse burrows-wheeler step. */154155static int INIT get_next_block(struct bunzip_data *bd)156{157struct group_data *hufGroup = NULL;158int *base = NULL;159int *limit = NULL;160int dbufCount, nextSym, dbufSize, groupCount, selector,161i, j, k, t, runPos, symCount, symTotal, nSelectors, *byteCount;162unsigned char uc, *symToByte, *mtfSymbol, *selectors;163unsigned int *dbuf, origPtr;164165dbuf = bd->dbuf;166dbufSize = bd->dbufSize;167selectors = bd->selectors;168byteCount = bd->byteCount;169symToByte = bd->symToByte;170mtfSymbol = bd->mtfSymbol;171172/* Read in header signature and CRC, then validate signature.173(last block signature means CRC is for whole file, return now) */174i = get_bits(bd, 24);175j = get_bits(bd, 24);176bd->headerCRC = get_bits(bd, 32);177if ((i == 0x177245) && (j == 0x385090))178return RETVAL_LAST_BLOCK;179if ((i != 0x314159) || (j != 0x265359))180return RETVAL_NOT_BZIP_DATA;181/* We can add support for blockRandomised if anybody complains.182There was some code for this in busybox 1.0.0-pre3, but nobody ever183noticed that it didn't actually work. */184if (get_bits(bd, 1))185return RETVAL_OBSOLETE_INPUT;186origPtr = get_bits(bd, 24);187if (origPtr > dbufSize)188return RETVAL_DATA_ERROR;189/* mapping table: if some byte values are never used (encoding things190like ascii text), the compression code removes the gaps to have fewer191symbols to deal with, and writes a sparse bitfield indicating which192values were present. We make a translation table to convert the193symbols back to the corresponding bytes. */194t = get_bits(bd, 16);195symTotal = 0;196for (i = 0; i < 16; i++) {197if (t&(1 << (15-i))) {198k = get_bits(bd, 16);199for (j = 0; j < 16; j++)200if (k&(1 << (15-j)))201symToByte[symTotal++] = (16*i)+j;202}203}204/* How many different Huffman coding groups does this block use? */205groupCount = get_bits(bd, 3);206if (groupCount < 2 || groupCount > MAX_GROUPS)207return RETVAL_DATA_ERROR;208/* nSelectors: Every GROUP_SIZE many symbols we select a new209Huffman coding group. Read in the group selector list,210which is stored as MTF encoded bit runs. (MTF = Move To211Front, as each value is used it's moved to the start of the212list.) */213nSelectors = get_bits(bd, 15);214if (!nSelectors)215return RETVAL_DATA_ERROR;216for (i = 0; i < groupCount; i++)217mtfSymbol[i] = i;218for (i = 0; i < nSelectors; i++) {219/* Get next value */220for (j = 0; get_bits(bd, 1); j++)221if (j >= groupCount)222return RETVAL_DATA_ERROR;223/* Decode MTF to get the next selector */224uc = mtfSymbol[j];225for (; j; j--)226mtfSymbol[j] = mtfSymbol[j-1];227mtfSymbol[0] = selectors[i] = uc;228}229/* Read the Huffman coding tables for each group, which code230for symTotal literal symbols, plus two run symbols (RUNA,231RUNB) */232symCount = symTotal+2;233for (j = 0; j < groupCount; j++) {234unsigned char length[MAX_SYMBOLS], temp[MAX_HUFCODE_BITS+1];235int minLen, maxLen, pp;236/* Read Huffman code lengths for each symbol. They're237stored in a way similar to mtf; record a starting238value for the first symbol, and an offset from the239previous value for everys symbol after that.240(Subtracting 1 before the loop and then adding it241back at the end is an optimization that makes the242test inside the loop simpler: symbol length 0243becomes negative, so an unsigned inequality catches244it.) */245t = get_bits(bd, 5)-1;246for (i = 0; i < symCount; i++) {247for (;;) {248if (((unsigned)t) > (MAX_HUFCODE_BITS-1))249return RETVAL_DATA_ERROR;250251/* If first bit is 0, stop. Else252second bit indicates whether to253increment or decrement the value.254Optimization: grab 2 bits and unget255the second if the first was 0. */256257k = get_bits(bd, 2);258if (k < 2) {259bd->inbufBitCount++;260break;261}262/* Add one if second bit 1, else263* subtract 1. Avoids if/else */264t += (((k+1)&2)-1);265}266/* Correct for the initial -1, to get the267* final symbol length */268length[i] = t+1;269}270/* Find largest and smallest lengths in this group */271minLen = maxLen = length[0];272273for (i = 1; i < symCount; i++) {274if (length[i] > maxLen)275maxLen = length[i];276else if (length[i] < minLen)277minLen = length[i];278}279280/* Calculate permute[], base[], and limit[] tables from281* length[].282*283* permute[] is the lookup table for converting284* Huffman coded symbols into decoded symbols. base[]285* is the amount to subtract from the value of a286* Huffman symbol of a given length when using287* permute[].288*289* limit[] indicates the largest numerical value a290* symbol with a given number of bits can have. This291* is how the Huffman codes can vary in length: each292* code with a value > limit[length] needs another293* bit.294*/295hufGroup = bd->groups+j;296hufGroup->minLen = minLen;297hufGroup->maxLen = maxLen;298/* Note that minLen can't be smaller than 1, so we299adjust the base and limit array pointers so we're300not always wasting the first entry. We do this301again when using them (during symbol decoding).*/302base = hufGroup->base-1;303limit = hufGroup->limit-1;304/* Calculate permute[]. Concurrently, initialize305* temp[] and limit[]. */306pp = 0;307for (i = minLen; i <= maxLen; i++) {308temp[i] = limit[i] = 0;309for (t = 0; t < symCount; t++)310if (length[t] == i)311hufGroup->permute[pp++] = t;312}313/* Count symbols coded for at each bit length */314for (i = 0; i < symCount; i++)315temp[length[i]]++;316/* Calculate limit[] (the largest symbol-coding value317*at each bit length, which is (previous limit <<318*1)+symbols at this level), and base[] (number of319*symbols to ignore at each bit length, which is limit320*minus the cumulative count of symbols coded for321*already). */322pp = t = 0;323for (i = minLen; i < maxLen; i++) {324pp += temp[i];325/* We read the largest possible symbol size326and then unget bits after determining how327many we need, and those extra bits could be328set to anything. (They're noise from329future symbols.) At each level we're330really only interested in the first few331bits, so here we set all the trailing332to-be-ignored bits to 1 so they don't333affect the value > limit[length]334comparison. */335limit[i] = (pp << (maxLen - i)) - 1;336pp <<= 1;337base[i+1] = pp-(t += temp[i]);338}339limit[maxLen+1] = INT_MAX; /* Sentinal value for340* reading next sym. */341limit[maxLen] = pp+temp[maxLen]-1;342base[minLen] = 0;343}344/* We've finished reading and digesting the block header. Now345read this block's Huffman coded symbols from the file and346undo the Huffman coding and run length encoding, saving the347result into dbuf[dbufCount++] = uc */348349/* Initialize symbol occurrence counters and symbol Move To350* Front table */351for (i = 0; i < 256; i++) {352byteCount[i] = 0;353mtfSymbol[i] = (unsigned char)i;354}355/* Loop through compressed symbols. */356runPos = dbufCount = symCount = selector = 0;357for (;;) {358/* Determine which Huffman coding group to use. */359if (!(symCount--)) {360symCount = GROUP_SIZE-1;361if (selector >= nSelectors)362return RETVAL_DATA_ERROR;363hufGroup = bd->groups+selectors[selector++];364base = hufGroup->base-1;365limit = hufGroup->limit-1;366}367/* Read next Huffman-coded symbol. */368/* Note: It is far cheaper to read maxLen bits and369back up than it is to read minLen bits and then an370additional bit at a time, testing as we go.371Because there is a trailing last block (with file372CRC), there is no danger of the overread causing an373unexpected EOF for a valid compressed file. As a374further optimization, we do the read inline375(falling back to a call to get_bits if the buffer376runs dry). The following (up to got_huff_bits:) is377equivalent to j = get_bits(bd, hufGroup->maxLen);378*/379while (bd->inbufBitCount < hufGroup->maxLen) {380if (bd->inbufPos == bd->inbufCount) {381j = get_bits(bd, hufGroup->maxLen);382goto got_huff_bits;383}384bd->inbufBits =385(bd->inbufBits << 8)|bd->inbuf[bd->inbufPos++];386bd->inbufBitCount += 8;387};388bd->inbufBitCount -= hufGroup->maxLen;389j = (bd->inbufBits >> bd->inbufBitCount)&390((1 << hufGroup->maxLen)-1);391got_huff_bits:392/* Figure how how many bits are in next symbol and393* unget extras */394i = hufGroup->minLen;395while (j > limit[i])396++i;397bd->inbufBitCount += (hufGroup->maxLen - i);398/* Huffman decode value to get nextSym (with bounds checking) */399if ((i > hufGroup->maxLen)400|| (((unsigned)(j = (j>>(hufGroup->maxLen-i))-base[i]))401>= MAX_SYMBOLS))402return RETVAL_DATA_ERROR;403nextSym = hufGroup->permute[j];404/* We have now decoded the symbol, which indicates405either a new literal byte, or a repeated run of the406most recent literal byte. First, check if nextSym407indicates a repeated run, and if so loop collecting408how many times to repeat the last literal. */409if (((unsigned)nextSym) <= SYMBOL_RUNB) { /* RUNA or RUNB */410/* If this is the start of a new run, zero out411* counter */412if (!runPos) {413runPos = 1;414t = 0;415}416/* Neat trick that saves 1 symbol: instead of417or-ing 0 or 1 at each bit position, add 1418or 2 instead. For example, 1011 is 1 << 0419+ 1 << 1 + 2 << 2. 1010 is 2 << 0 + 2 << 1420+ 1 << 2. You can make any bit pattern421that way using 1 less symbol than the basic422or 0/1 method (except all bits 0, which423would use no symbols, but a run of length 0424doesn't mean anything in this context).425Thus space is saved. */426t += (runPos << nextSym);427/* +runPos if RUNA; +2*runPos if RUNB */428429runPos <<= 1;430continue;431}432/* When we hit the first non-run symbol after a run,433we now know how many times to repeat the last434literal, so append that many copies to our buffer435of decoded symbols (dbuf) now. (The last literal436used is the one at the head of the mtfSymbol437array.) */438if (runPos) {439runPos = 0;440if (dbufCount+t >= dbufSize)441return RETVAL_DATA_ERROR;442443uc = symToByte[mtfSymbol[0]];444byteCount[uc] += t;445while (t--)446dbuf[dbufCount++] = uc;447}448/* Is this the terminating symbol? */449if (nextSym > symTotal)450break;451/* At this point, nextSym indicates a new literal452character. Subtract one to get the position in the453MTF array at which this literal is currently to be454found. (Note that the result can't be -1 or 0,455because 0 and 1 are RUNA and RUNB. But another456instance of the first symbol in the mtf array,457position 0, would have been handled as part of a458run above. Therefore 1 unused mtf position minus 2459non-literal nextSym values equals -1.) */460if (dbufCount >= dbufSize)461return RETVAL_DATA_ERROR;462i = nextSym - 1;463uc = mtfSymbol[i];464/* Adjust the MTF array. Since we typically expect to465*move only a small number of symbols, and are bound466*by 256 in any case, using memmove here would467*typically be bigger and slower due to function call468*overhead and other assorted setup costs. */469do {470mtfSymbol[i] = mtfSymbol[i-1];471} while (--i);472mtfSymbol[0] = uc;473uc = symToByte[uc];474/* We have our literal byte. Save it into dbuf. */475byteCount[uc]++;476dbuf[dbufCount++] = (unsigned int)uc;477}478/* At this point, we've read all the Huffman-coded symbols479(and repeated runs) for this block from the input stream,480and decoded them into the intermediate buffer. There are481dbufCount many decoded bytes in dbuf[]. Now undo the482Burrows-Wheeler transform on dbuf. See483http://dogma.net/markn/articles/bwt/bwt.htm484*/485/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */486j = 0;487for (i = 0; i < 256; i++) {488k = j+byteCount[i];489byteCount[i] = j;490j = k;491}492/* Figure out what order dbuf would be in if we sorted it. */493for (i = 0; i < dbufCount; i++) {494uc = (unsigned char)(dbuf[i] & 0xff);495dbuf[byteCount[uc]] |= (i << 8);496byteCount[uc]++;497}498/* Decode first byte by hand to initialize "previous" byte.499Note that it doesn't get output, and if the first three500characters are identical it doesn't qualify as a run (hence501writeRunCountdown = 5). */502if (dbufCount) {503if (origPtr >= dbufCount)504return RETVAL_DATA_ERROR;505bd->writePos = dbuf[origPtr];506bd->writeCurrent = (unsigned char)(bd->writePos&0xff);507bd->writePos >>= 8;508bd->writeRunCountdown = 5;509}510bd->writeCount = dbufCount;511512return RETVAL_OK;513}514515/* Undo burrows-wheeler transform on intermediate buffer to produce output.516If start_bunzip was initialized with out_fd =-1, then up to len bytes of517data are written to outbuf. Return value is number of bytes written or518error (all errors are negative numbers). If out_fd!=-1, outbuf and len519are ignored, data is written to out_fd and return is RETVAL_OK or error.520*/521522static int INIT read_bunzip(struct bunzip_data *bd, char *outbuf, int len)523{524const unsigned int *dbuf;525int pos, xcurrent, previous, gotcount;526527/* If last read was short due to end of file, return last block now */528if (bd->writeCount < 0)529return bd->writeCount;530531gotcount = 0;532dbuf = bd->dbuf;533pos = bd->writePos;534xcurrent = bd->writeCurrent;535536/* We will always have pending decoded data to write into the output537buffer unless this is the very first call (in which case we haven't538Huffman-decoded a block into the intermediate buffer yet). */539540if (bd->writeCopies) {541/* Inside the loop, writeCopies means extra copies (beyond 1) */542--bd->writeCopies;543/* Loop outputting bytes */544for (;;) {545/* If the output buffer is full, snapshot546* state and return */547if (gotcount >= len) {548bd->writePos = pos;549bd->writeCurrent = xcurrent;550bd->writeCopies++;551return len;552}553/* Write next byte into output buffer, updating CRC */554outbuf[gotcount++] = xcurrent;555bd->writeCRC = (((bd->writeCRC) << 8)556^bd->crc32Table[((bd->writeCRC) >> 24)557^xcurrent]);558/* Loop now if we're outputting multiple559* copies of this byte */560if (bd->writeCopies) {561--bd->writeCopies;562continue;563}564decode_next_byte:565if (!bd->writeCount--)566break;567/* Follow sequence vector to undo568* Burrows-Wheeler transform */569previous = xcurrent;570pos = dbuf[pos];571xcurrent = pos&0xff;572pos >>= 8;573/* After 3 consecutive copies of the same574byte, the 4th is a repeat count. We count575down from 4 instead *of counting up because576testing for non-zero is faster */577if (--bd->writeRunCountdown) {578if (xcurrent != previous)579bd->writeRunCountdown = 4;580} else {581/* We have a repeated run, this byte582* indicates the count */583bd->writeCopies = xcurrent;584xcurrent = previous;585bd->writeRunCountdown = 5;586/* Sometimes there are just 3 bytes587* (run length 0) */588if (!bd->writeCopies)589goto decode_next_byte;590/* Subtract the 1 copy we'd output591* anyway to get extras */592--bd->writeCopies;593}594}595/* Decompression of this block completed successfully */596bd->writeCRC = ~bd->writeCRC;597bd->totalCRC = ((bd->totalCRC << 1) |598(bd->totalCRC >> 31)) ^ bd->writeCRC;599/* If this block had a CRC error, force file level CRC error. */600if (bd->writeCRC != bd->headerCRC) {601bd->totalCRC = bd->headerCRC+1;602return RETVAL_LAST_BLOCK;603}604}605606/* Refill the intermediate buffer by Huffman-decoding next607* block of input */608/* (previous is just a convenient unused temp variable here) */609previous = get_next_block(bd);610if (previous) {611bd->writeCount = previous;612return (previous != RETVAL_LAST_BLOCK) ? previous : gotcount;613}614bd->writeCRC = 0xffffffffUL;615pos = bd->writePos;616xcurrent = bd->writeCurrent;617goto decode_next_byte;618}619620static int INIT nofill(void *buf, unsigned int len)621{622return -1;623}624625/* Allocate the structure, read file header. If in_fd ==-1, inbuf must contain626a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are627ignored, and data is read from file handle into temporary buffer. */628static int INIT start_bunzip(struct bunzip_data **bdp, void *inbuf, int len,629int (*fill)(void*, unsigned int))630{631struct bunzip_data *bd;632unsigned int i, j, c;633const unsigned int BZh0 =634(((unsigned int)'B') << 24)+(((unsigned int)'Z') << 16)635+(((unsigned int)'h') << 8)+(unsigned int)'0';636637/* Figure out how much data to allocate */638i = sizeof(struct bunzip_data);639640/* Allocate bunzip_data. Most fields initialize to zero. */641bd = *bdp = malloc(i);642if (!bd)643return RETVAL_OUT_OF_MEMORY;644memset(bd, 0, sizeof(struct bunzip_data));645/* Setup input buffer */646bd->inbuf = inbuf;647bd->inbufCount = len;648if (fill != NULL)649bd->fill = fill;650else651bd->fill = nofill;652653/* Init the CRC32 table (big endian) */654for (i = 0; i < 256; i++) {655c = i << 24;656for (j = 8; j; j--)657c = c&0x80000000 ? (c << 1)^0x04c11db7 : (c << 1);658bd->crc32Table[i] = c;659}660661/* Ensure that file starts with "BZh['1'-'9']." */662i = get_bits(bd, 32);663if (((unsigned int)(i-BZh0-1)) >= 9)664return RETVAL_NOT_BZIP_DATA;665666/* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of667uncompressed data. Allocate intermediate buffer for block. */668bd->dbufSize = 100000*(i-BZh0);669670bd->dbuf = large_malloc(bd->dbufSize * sizeof(int));671if (!bd->dbuf)672return RETVAL_OUT_OF_MEMORY;673return RETVAL_OK;674}675676/* Example usage: decompress src_fd to dst_fd. (Stops at end of bzip2 data,677not end of file.) */678STATIC int INIT bunzip2(unsigned char *buf, int len,679int(*fill)(void*, unsigned int),680int(*flush)(void*, unsigned int),681unsigned char *outbuf,682int *pos,683void(*error)(char *x))684{685struct bunzip_data *bd;686int i = -1;687unsigned char *inbuf;688689if (flush)690outbuf = malloc(BZIP2_IOBUF_SIZE);691692if (!outbuf) {693error("Could not allocate output bufer");694return RETVAL_OUT_OF_MEMORY;695}696if (buf)697inbuf = buf;698else699inbuf = malloc(BZIP2_IOBUF_SIZE);700if (!inbuf) {701error("Could not allocate input bufer");702i = RETVAL_OUT_OF_MEMORY;703goto exit_0;704}705i = start_bunzip(&bd, inbuf, len, fill);706if (!i) {707for (;;) {708i = read_bunzip(bd, outbuf, BZIP2_IOBUF_SIZE);709if (i <= 0)710break;711if (!flush)712outbuf += i;713else714if (i != flush(outbuf, i)) {715i = RETVAL_UNEXPECTED_OUTPUT_EOF;716break;717}718}719}720/* Check CRC and release memory */721if (i == RETVAL_LAST_BLOCK) {722if (bd->headerCRC != bd->totalCRC)723error("Data integrity error when decompressing.");724else725i = RETVAL_OK;726} else if (i == RETVAL_UNEXPECTED_OUTPUT_EOF) {727error("Compressed file ends unexpectedly");728}729if (!bd)730goto exit_1;731if (bd->dbuf)732large_free(bd->dbuf);733if (pos)734*pos = bd->inbufPos;735free(bd);736exit_1:737if (!buf)738free(inbuf);739exit_0:740if (flush)741free(outbuf);742return i;743}744745#ifdef PREBOOT746STATIC int INIT decompress(unsigned char *buf, int len,747int(*fill)(void*, unsigned int),748int(*flush)(void*, unsigned int),749unsigned char *outbuf,750int *pos,751void(*error)(char *x))752{753return bunzip2(buf, len - 4, fill, flush, outbuf, pos, error);754}755#endif756757758