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