1 /* vi: set sw=4 ts=4: */
2 /* Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).
4 Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
5 which also acknowledges contributions by Mike Burrows, David Wheeler,
6 Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
7 Robert Sedgewick, and Jon L. Bentley.
9 This code is licensed under the LGPLv2:
10 LGPL (http://www.gnu.org/copyleft/lgpl.html
20 /* Constants for huffman coding */
22 #define GROUP_SIZE 50 /* 64 would have been more efficient */
23 #define MAX_HUFCODE_BITS 20 /* Longest huffman code allowed */
24 #define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
28 /* Status return values */
30 #define RETVAL_LAST_BLOCK (-1)
31 #define RETVAL_NOT_BZIP_DATA (-2)
32 #define RETVAL_UNEXPECTED_INPUT_EOF (-3)
33 #define RETVAL_UNEXPECTED_OUTPUT_EOF (-4)
34 #define RETVAL_DATA_ERROR (-5)
35 #define RETVAL_OUT_OF_MEMORY (-6)
36 #define RETVAL_OBSOLETE_INPUT (-7)
38 /* Other housekeeping constants */
39 #define IOBUF_SIZE 4096
41 static char * const bunzip_errors[]={NULL,"Bad file checksum","Not bzip data",
42 "Unexpected input EOF","Unexpected output EOF","Data error",
43 "Out of memory","Obsolete (pre 0.9.5) bzip format not supported."};
45 /* This is what we know about each huffman coding group */
47 /* We have an extra slot at the end of limit[] for a sentinal value. */
48 int limit[MAX_HUFCODE_BITS+1],base[MAX_HUFCODE_BITS],permute[MAX_SYMBOLS];
52 /* Structure holding all the housekeeping data, including IO buffers and
53 memory that persists between calls to bunzip */
55 /* For I/O error handling */
57 /* Input stream, input buffer, input bit buffer */
58 int in_fd,inbufCount,inbufPos;
60 unsigned int inbufBitCount, inbufBits;
62 char outbuf[IOBUF_SIZE];
64 /* The CRC values stored in the block header and calculated from the data */
65 unsigned int crc32Table[256],headerCRC, dataCRC, totalCRC;
66 /* Intermediate buffer and its size (in bytes) */
67 unsigned int *dbuf, dbufSize;
68 /* State for interrupting output loop */
69 int writePos,writeRun,writeCount,writeCurrent;
71 /* These things are a bit too big to go on the stack */
72 unsigned char selectors[32768]; /* nSelectors=15 bits */
73 struct group_data groups[MAX_GROUPS]; /* huffman coding tables */
76 /* Return the next nnn bits of input. All reads from the compressed input
77 are done through this function. All reads are big endian */
78 static unsigned int get_bits(bunzip_data *bd, char bits_wanted)
82 /* If we need to get more data from the byte buffer, do so. (Loop getting
83 one byte at a time to enforce endianness and avoid unaligned access.) */
84 while (bd->inbufBitCount<bits_wanted) {
85 /* If we need to read more data from file into byte buffer, do so */
86 if(bd->inbufPos==bd->inbufCount) {
87 if((bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE)) <= 0)
88 longjmp(bd->jmpbuf,RETVAL_UNEXPECTED_INPUT_EOF);
91 /* Avoid 32-bit overflow (dump bit buffer to top of output) */
92 if(bd->inbufBitCount>=24) {
93 bits=bd->inbufBits&((1<<bd->inbufBitCount)-1);
94 bits_wanted-=bd->inbufBitCount;
98 /* Grab next 8 bits of input from buffer. */
99 bd->inbufBits=(bd->inbufBits<<8)|bd->inbuf[bd->inbufPos++];
100 bd->inbufBitCount+=8;
102 /* Calculate result */
103 bd->inbufBitCount-=bits_wanted;
104 bits|=(bd->inbufBits>>bd->inbufBitCount)&((1<<bits_wanted)-1);
109 /* At certain times, it pays to have an optimized inline version of
110 * get_bits() which gets a single bit. */
111 #define GET_A_BIT(bd) \
112 ((bd->inbufBitCount > 0) \
113 ? ((unsigned int)(((bd)->inbufBits >> --(bd)->inbufBitCount) & 1)) \
117 /* Decompress a block of text to into intermediate buffer */
119 extern int read_bunzip_data(bunzip_data *bd)
121 struct group_data *hufGroup;
122 int dbufCount,nextSym,dbufSize,origPtr,groupCount,*base,*limit,selector,
123 i,j,k,t,runPos,symCount,symTotal,nSelectors,byteCount[256];
124 unsigned char uc, symToByte[256], mtfSymbol[256], *selectors;
127 /* Read in header signature (borrowing mtfSymbol for temp space). */
128 for(i=0;i<6;i++) mtfSymbol[i]=get_bits(bd,8);
130 /* Read CRC (which is stored big endian). */
131 bd->headerCRC=get_bits(bd,32);
132 /* Is this the last block (with CRC for file)? */
133 if(!strcmp(mtfSymbol,"\x17\x72\x45\x38\x50\x90"))
134 return RETVAL_LAST_BLOCK;
135 /* If it's not a valid data block, barf. */
136 if(strcmp(mtfSymbol,"\x31\x41\x59\x26\x53\x59"))
137 return RETVAL_NOT_BZIP_DATA;
140 dbufSize=bd->dbufSize;
141 selectors=bd->selectors;
142 /* We can add support for blockRandomised if anybody complains. There was
143 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
144 it didn't actually work. */
145 if(get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
146 if((origPtr=get_bits(bd,24)) > dbufSize) return RETVAL_DATA_ERROR;
147 /* mapping table: if some byte values are never used (encoding things
148 like ascii text), the compression code removes the gaps to have fewer
149 symbols to deal with, and writes a sparse bitfield indicating which
150 values were present. We make a translation table to convert the symbols
151 back to the corresponding bytes. */
154 /* I don't believe this is necessary. Rob? */
155 memset(symToByte,0,256);
162 if(k&(1<<(15-j))) symToByte[symTotal++]=(16*i)+j;
165 /* How many different huffman coding groups does this block use? */
166 groupCount=get_bits(bd,3);
167 if (groupCount<2 || groupCount>MAX_GROUPS) return RETVAL_DATA_ERROR;
168 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
169 group. Read in the group selector list, which is stored as MTF encoded
171 if(!(nSelectors=get_bits(bd, 15))) return RETVAL_DATA_ERROR;
172 for(i=0; i<groupCount; i++) mtfSymbol[i] = i;
173 for(i=0; i<nSelectors; i++) {
175 for(j=0;get_bits(bd,1);j++) if (j>=groupCount) return RETVAL_DATA_ERROR;
176 /* Decode MTF to get the next selector */
178 /* A very small amount of data to move, so memmove is overkill
179 * and bigger at least in my tests. */
182 mtfSymbol[k] = mtfSymbol[k-1];
185 mtfSymbol[0]=selectors[i]=uc;
187 /* Read the huffman coding tables for each group, which code for symTotal
188 literal symbols, plus two run symbols (RUNA, RUNB) */
190 for (j=0; j<groupCount; j++) {
191 unsigned char length[MAX_SYMBOLS],temp[MAX_HUFCODE_BITS+1];
192 int minLen, maxLen, pp;
194 t=get_bits(bd, 5) - 1; /* This lets us avoid a test in the loop. */
195 for (i = 0; i < symCount; i++) {
197 if (((unsigned)t) > (MAX_HUFCODE_BITS-1)) return RETVAL_DATA_ERROR;
198 if(!get_bits(bd, 1)) break;
199 /* We can avoid an if/else with a little arithmetic. */
200 t += (1 - 2*get_bits(bd, 1)); /* 0 -> t++ ; 1 -> t-- */
202 length[i] = t + 1; /* Correct for the initial -1 adjustment. */
204 /* Find largest and smallest lengths in this group */
205 minLen=maxLen=length[0];
206 for(i = 1; i < symCount; i++) {
207 if(length[i] > maxLen) maxLen = length[i];
208 else if(length[i] < minLen) minLen = length[i];
210 /* Calculate permute[], base[], and limit[] tables from length[].
212 * permute[] is the lookup table for converting huffman coded symbols
213 * into decoded symbols. base[] is the amount to subtract from the
214 * value of a huffman symbol of a given length when using permute[].
216 * limit[] indicates the largest numerical value a symbol with a given
217 * number of bits can have. It lets us know when to stop reading.
219 * To use these, keep reading bits until value<=limit[bitcount] or
220 * you've read over 20 bits (error). Then the decoded symbol
221 * equals permute[hufcode_value-base[hufcode_bitcount]].
223 hufGroup=bd->groups+j;
224 hufGroup->minLen = minLen;
225 hufGroup->maxLen = maxLen;
226 /* Note that minLen can't be smaller than 1, so we adjust the base
227 and limit array pointers so we're not always wasting the first
228 entry. We do this again when using them (during symbol decoding).*/
229 base=hufGroup->base-1;
230 limit=hufGroup->limit-1;
231 /* Calculate permute[] */
233 for(i=minLen;i<=maxLen;i++)
234 for(t=0;t<symCount;t++)
235 if(length[t]==i) hufGroup->permute[pp++] = t;
236 /* Count cumulative symbols coded for at each bit length */
237 for (i=minLen;i<=maxLen;i++) temp[i]=limit[i]=0;
238 for (i=0;i<symCount;i++) temp[length[i]]++;
239 /* Calculate limit[] (the largest symbol-coding value at each bit
240 * length, which is (previous limit<<1)+symbols at this level), and
241 * base[] (number of symbols to ignore at each bit length, which is
242 * limit-cumulative count of symbols coded for already). */
244 for (i=minLen; i<maxLen; i++) {
248 base[i+1]=pp-(t+=temp[i]);
250 limit[maxLen+1] = INT_MAX; /* Sentinal value for reading next sym. */
251 limit[maxLen]=pp+temp[maxLen]-1;
254 /* We've finished reading and digesting the block header. Now read this
255 block's huffman coded symbols from the file and undo the huffman coding
256 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
258 /* Initialize symbol occurrence counters and symbol mtf table */
259 memset(byteCount,0,256*sizeof(int));
260 for(i=0;i<256;i++) mtfSymbol[i]=(unsigned char)i;
261 /* Loop through compressed symbols */
262 runPos=dbufCount=symCount=selector=0;
264 /* Determine which huffman coding group to use. */
266 symCount=GROUP_SIZE-1;
267 if(selector>=nSelectors) return RETVAL_DATA_ERROR;
268 hufGroup=bd->groups+selectors[selector++];
269 base=hufGroup->base-1;
270 limit=hufGroup->limit-1;
272 /* Read next huffman-coded symbol */
273 i = hufGroup->minLen;
275 while (j > limit[i]) { /* The sentinal allows us to avoid testing i. */
276 j = (j << 1) | GET_A_BIT(bd);
279 /* Huffman decode nextSym (with bounds checking) */
280 if ((i > hufGroup->maxLen) || (((unsigned)(j-=base[i])) >= MAX_SYMBOLS)) return RETVAL_DATA_ERROR;
281 nextSym = hufGroup->permute[j];
282 /* If this is a repeated run, loop collecting data */
283 if (((unsigned)nextSym) <= SYMBOL_RUNB) { /* RUNA or RUNB */
284 /* If this is the start of a new run, zero out counter */
289 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
290 each bit position, add 1 or 2 instead. For example,
291 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
292 You can make any bit pattern that way using 1 less symbol than
293 the basic or 0/1 method (except all bits 0, which would use no
294 symbols, but a run of length 0 doesn't mean anything in this
295 context). Thus space is saved. */
296 t += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
300 /* When we hit the first non-run symbol after a run, we now know
301 how many times to repeat the last literal, so append that many
302 copies to our buffer of decoded symbols (dbuf) now. (The last
303 literal used is the one at the head of the mtfSymbol array.) */
306 if(dbufCount+t>=dbufSize) return RETVAL_DATA_ERROR;
308 uc = symToByte[mtfSymbol[0]];
310 while(t--) dbuf[dbufCount++]=uc;
312 /* Is this the terminating symbol? */
313 if(nextSym>symTotal) break;
314 /* At this point, the symbol we just decoded indicates a new literal
315 character. Subtract one to get the position in the MTF array
316 at which this literal is currently to be found. (Note that the
317 result can't be -1 or 0, because 0 and 1 are RUNA and RUNB.
318 Another instance of the first symbol in the mtf array, position 0,
319 would have been handled as part of a run.) */
320 if(dbufCount>=dbufSize) return RETVAL_DATA_ERROR;
323 /* Since we typically expect to move only a small number of symbols,
324 * and are bound by 256 in any case, using memmove here would
325 * typically be slower due to function call overhead and other
326 * assorted setup costs. */
328 mtfSymbol[i] = mtfSymbol[i-1];
332 /* We have our literal byte. Save it into dbuf. */
334 dbuf[dbufCount++] = (unsigned int)uc;
336 /* At this point, we've finished reading huffman-coded symbols and
337 compressed runs from the input stream. There are dbufCount many of
338 them in dbuf[]. Now undo the Burrows-Wheeler transform on dbuf.
339 See http://dogma.net/markn/articles/bwt/bwt.htm
342 /* Now we know what dbufCount is, do a better sanity check on origPtr. */
343 if (((unsigned)origPtr)>=dbufCount) return RETVAL_DATA_ERROR;
344 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
351 /* Figure out what order dbuf would be in if we sorted it. */
352 for (i=0;i<dbufCount;i++) {
353 uc = (unsigned char)(dbuf[i] & 0xff);
354 dbuf[byteCount[uc]] |= (i << 8);
357 /* blockRandomised support would go here. */
359 /* Using i as position, j as previous character, t as current character,
360 and uc as run count */
361 bd->dataCRC = 0xffffffffL;
362 /* Decode first byte by hand to initialize "previous" byte. Note that it
363 doesn't get output, and if the first three characters are identical
364 it doesn't qualify as a run (hence uc=255, which will either wrap
365 to 1 or get reset). */
367 bd->writePos=dbuf[origPtr];
368 bd->writeCurrent=(unsigned char)(bd->writePos&0xff);
372 bd->writeCount=dbufCount;
377 /* Flush output buffer to disk */
378 extern void flush_bunzip_outbuf(bunzip_data *bd, int out_fd)
381 if(write(out_fd, bd->outbuf, bd->outbufPos) != bd->outbufPos)
382 longjmp(bd->jmpbuf,RETVAL_UNEXPECTED_OUTPUT_EOF);
388 /* Undo burrows-wheeler transform on intermediate buffer to produce output.
389 If !len, write up to len bytes of data to buf. Otherwise write to out_fd.
390 Returns len ? bytes written : RETVAL_OK. Notice all errors negative #'s. */
391 extern int write_bunzip_data(bunzip_data *bd, int out_fd, char *outbuf, int len)
393 unsigned int *dbuf=bd->dbuf;
394 int count,pos,current, run,copies,outbyte,previous,gotcount=0;
397 /* If last read was short due to end of file, return last block now */
398 if(bd->writeCount<0) return bd->writeCount;
399 /* If we need to refill dbuf, do it. */
400 if(!bd->writeCount) {
401 int i=read_bunzip_data(bd);
403 if(i==RETVAL_LAST_BLOCK) {
409 /* Loop generating output */
410 count=bd->writeCount;
412 current=bd->writeCurrent;
415 /* If somebody (like busybox tar) wants a certain number of bytes of
416 data from memory instead of written to a file, humor them */
417 if(len && bd->outbufPos>=len) goto dataus_interruptus;
419 /* Follow sequence vector to undo Burrows-Wheeler transform */
424 /* Whenever we see 3 consecutive copies of the same byte,
425 the 4th is a repeat count */
434 /* Output bytes to buffer, flushing to file if necessary */
436 if(bd->outbufPos == IOBUF_SIZE) flush_bunzip_outbuf(bd,out_fd);
437 bd->outbuf[bd->outbufPos++] = outbyte;
438 bd->dataCRC = (bd->dataCRC << 8)
439 ^ bd->crc32Table[(bd->dataCRC >> 24) ^ outbyte];
441 if(current!=previous) run=0;
443 /* Decompression of this block completed successfully */
444 bd->dataCRC=~(bd->dataCRC);
445 bd->totalCRC=((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bd->dataCRC;
446 /* If this block had a CRC error, force file level CRC error. */
447 if(bd->dataCRC!=bd->headerCRC) {
448 bd->totalCRC=bd->headerCRC+1;
449 return RETVAL_LAST_BLOCK;
452 bd->writeCount=count;
454 gotcount+=bd->outbufPos;
455 memcpy(outbuf,bd->outbuf,len);
456 /* If we got enough data, checkpoint loop state and return */
457 if((len-=bd->outbufPos)<1) {
460 memmove(bd->outbuf,bd->outbuf+len,bd->outbufPos);
462 bd->writeCurrent=current;
470 /* Allocate the structure, read file header. If !len, src_fd contains
471 filehandle to read from. Else inbuf contains data. */
472 extern int start_bunzip(bunzip_data **bdp, int src_fd, char *inbuf, int len)
477 /* Figure out how much data to allocate */
478 i=sizeof(bunzip_data);
479 if(!len) i+=IOBUF_SIZE;
480 /* Allocate bunzip_data. Most fields initialize to zero. */
481 if(!(bd=*bdp=malloc(i))) return RETVAL_OUT_OF_MEMORY;
482 memset(bd,0,sizeof(bunzip_data));
488 bd->inbuf=(char *)(bd+1);
491 /* Init the CRC32 table (big endian) */
495 c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
498 /* Setup for I/O error handling via longjmp */
499 i=setjmp(bd->jmpbuf);
501 /* Ensure that file starts with "BZh" */
502 for(i=0;i<3;i++) if(get_bits(bd,8)!="BZh"[i]) return RETVAL_NOT_BZIP_DATA;
503 /* Next byte ascii '1'-'9', indicates block size in units of 100k of
504 uncompressed data. Allocate intermediate buffer for block. */
506 if (i<'1' || i>'9') return RETVAL_NOT_BZIP_DATA;
507 bd->dbufSize=100000*(i-'0');
508 if(!(bd->dbuf=malloc(bd->dbufSize * sizeof(int))))
509 return RETVAL_OUT_OF_MEMORY;
513 extern char *uncompressStream(int src_fd, int dst_fd)
518 if(!(i=start_bunzip(&bd,src_fd,0,0))) {
519 i=write_bunzip_data(bd,dst_fd,0,0);
520 if(i==RETVAL_LAST_BLOCK && bd->headerCRC==bd->totalCRC) i=RETVAL_OK;
522 flush_bunzip_outbuf(bd,dst_fd);
523 if(bd->dbuf) free(bd->dbuf);
525 return bunzip_errors[-i];
528 /* This new version is not yet properly integrated with tar */
529 extern ssize_t read_bz2(int fd, void *buf, size_t count)
535 extern void BZ2_bzReadOpen(int fd, void *unused, int nUnused)
540 extern void BZ2_bzReadClose(void)
546 /* Dumb little test thing, decompress stdin to stdout */
547 int main(int argc, char *argv[])
549 char *c=uncompressStream(0,1);
550 fprintf(stderr,"\n%s\n", c ? c : "Completed OK");