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
19 /* Constants for huffman coding */
21 #define GROUP_SIZE 50 /* 64 would have been more efficient */
22 #define MAX_HUFCODE_BITS 20 /* Longest huffman code allowed */
23 #define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
27 /* Status return values */
29 #define RETVAL_LAST_BLOCK (-1)
30 #define RETVAL_NOT_BZIP_DATA (-2)
31 #define RETVAL_UNEXPECTED_INPUT_EOF (-3)
32 #define RETVAL_UNEXPECTED_OUTPUT_EOF (-4)
33 #define RETVAL_DATA_ERROR (-5)
34 #define RETVAL_OUT_OF_MEMORY (-6)
35 #define RETVAL_OBSOLETE_INPUT (-7)
37 /* Other housekeeping constants */
38 #define IOBUF_SIZE 4096
40 char *bunzip_errors[]={NULL,"Bad file checksum","Not bzip data",
41 "Unexpected input EOF","Unexpected output EOF","Data error",
42 "Out of memory","Obsolete (pre 0.9.5) bzip format not supported."};
44 /* This is what we know about each huffman coding group */
46 int limit[MAX_HUFCODE_BITS],base[MAX_HUFCODE_BITS],permute[MAX_SYMBOLS];
50 /* Structure holding all the housekeeping data, including IO buffers and
51 memory that persists between calls to bunzip */
53 /* For I/O error handling */
55 /* Input stream, input buffer, input bit buffer */
56 int in_fd,inbufCount,inbufPos;
58 unsigned int inbufBitCount, inbufBits;
60 char outbuf[IOBUF_SIZE];
62 /* The CRC values stored in the block header and calculated from the data */
63 unsigned int crc32Table[256],headerCRC, dataCRC, totalCRC;
64 /* Intermediate buffer and its size (in bytes) */
65 unsigned int *dbuf, dbufSize;
66 /* State for interrupting output loop */
67 int writePos,writeRun,writeCount,writeCurrent;
69 /* These things are a bit too big to go on the stack */
70 unsigned char selectors[32768]; /* nSelectors=15 bits */
71 struct group_data groups[MAX_GROUPS]; /* huffman coding tables */
74 /* Return the next nnn bits of input. All reads from the compressed input
75 are done through this function. All reads are big endian */
76 static unsigned int get_bits(bunzip_data *bd, char bits_wanted)
80 /* If we need to get more data from the byte buffer, do so. (Loop getting
81 one byte at a time to enforce endianness and avoid unaligned access.) */
82 while (bd->inbufBitCount<bits_wanted) {
83 /* If we need to read more data from file into byte buffer, do so */
84 if(bd->inbufPos==bd->inbufCount) {
85 if(!(bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE)))
86 longjmp(bd->jmpbuf,RETVAL_UNEXPECTED_INPUT_EOF);
89 /* Avoid 32-bit overflow (dump bit buffer to top of output) */
90 if(bd->inbufBitCount>=24) {
91 bits=bd->inbufBits&((1<<bd->inbufBitCount)-1);
92 bits_wanted-=bd->inbufBitCount;
96 /* Grab next 8 bits of input from buffer. */
97 bd->inbufBits=(bd->inbufBits<<8)|bd->inbuf[bd->inbufPos++];
100 /* Calculate result */
101 bd->inbufBitCount-=bits_wanted;
102 bits|=(bd->inbufBits>>bd->inbufBitCount)&((1<<bits_wanted)-1);
107 /* Decompress a block of text to into intermediate buffer */
109 extern int read_bunzip_data(bunzip_data *bd)
111 struct group_data *hufGroup;
112 int dbufCount,nextSym,dbufSize,origPtr,groupCount,*base,*limit,selector,
113 i,j,k,t,runPos,symCount,symTotal,nSelectors,byteCount[256];
114 unsigned char uc, symToByte[256], mtfSymbol[256], *selectors;
117 /* Read in header signature (borrowing mtfSymbol for temp space). */
118 for(i=0;i<6;i++) mtfSymbol[i]=get_bits(bd,8);
120 /* Read CRC (which is stored big endian). */
121 bd->headerCRC=get_bits(bd,32);
122 /* Is this the last block (with CRC for file)? */
123 if(!strcmp(mtfSymbol,"\x17\x72\x45\x38\x50\x90"))
124 return RETVAL_LAST_BLOCK;
125 /* If it's not a valid data block, barf. */
126 if(strcmp(mtfSymbol,"\x31\x41\x59\x26\x53\x59"))
127 return RETVAL_NOT_BZIP_DATA;
130 dbufSize=bd->dbufSize;
131 selectors=bd->selectors;
132 /* We can add support for blockRandomised if anybody complains. There was
133 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
134 it didn't actually work. */
135 if(get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
136 if((origPtr=get_bits(bd,24)) > dbufSize) return RETVAL_DATA_ERROR;
137 /* mapping table: if some byte values are never used (encoding things
138 like ascii text), the compression code removes the gaps to have fewer
139 symbols to deal with, and writes a sparse bitfield indicating which
140 values were present. We make a translation table to convert the symbols
141 back to the corresponding bytes. */
143 memset(symToByte,0,256);
149 if(k&(1<<(15-j))) symToByte[symTotal++]=(16*i)+j;
152 /* How many different huffman coding groups does this block use? */
153 groupCount=get_bits(bd,3);
154 if (groupCount<2 || groupCount>MAX_GROUPS) return RETVAL_DATA_ERROR;
155 /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
156 group. Read in the group selector list, which is stored as MTF encoded
158 if(!(nSelectors=get_bits(bd, 15))) return RETVAL_DATA_ERROR;
159 for(i=0; i<groupCount; i++) mtfSymbol[i] = i;
160 for(i=0; i<nSelectors; i++) {
162 for(j=0;get_bits(bd,1);j++) if (j>=groupCount) return RETVAL_DATA_ERROR;
163 /* Decode MTF to get the next selector */
165 memmove(mtfSymbol+1,mtfSymbol,j);
166 mtfSymbol[0]=selectors[i]=uc;
168 /* Read the huffman coding tables for each group, which code for symTotal
169 literal symbols, plus two run symbols (RUNA, RUNB) */
171 for (j=0; j<groupCount; j++) {
172 unsigned char length[MAX_SYMBOLS],temp[MAX_HUFCODE_BITS+1];
173 int minLen, maxLen, pp;
176 for (i = 0; i < symCount; i++) {
178 if (t < 1 || t > MAX_HUFCODE_BITS) return RETVAL_DATA_ERROR;
179 if(!get_bits(bd, 1)) break;
180 if(!get_bits(bd, 1)) t++;
185 /* Find largest and smallest lengths in this group */
186 minLen=maxLen=length[0];
187 for(i = 1; i < symCount; i++) {
188 if(length[i] > maxLen) maxLen = length[i];
189 else if(length[i] < minLen) minLen = length[i];
191 /* Calculate permute[], base[], and limit[] tables from length[].
193 * permute[] is the lookup table for converting huffman coded symbols
194 * into decoded symbols. base[] is the amount to subtract from the
195 * value of a huffman symbol of a given length when using permute[].
197 * limit[] indicates the largest numerical value a symbol with a given
198 * number of bits can have. It lets us know when to stop reading.
200 * To use these, keep reading bits until value<=limit[bitcount] or
201 * you've read over 20 bits (error). Then the decoded symbol
202 * equals permute[hufcode_value-base[hufcode_bitcount]].
204 hufGroup=bd->groups+j;
205 hufGroup->minLen = minLen;
206 hufGroup->maxLen = maxLen;
207 /* Note that minLen can't be smaller than 1, so we adjust the base
208 and limit array pointers so we're not always wasting the first
209 entry. We do this again when using them (during symbol decoding).*/
210 base=hufGroup->base-1;
211 limit=hufGroup->limit-1;
212 /* Calculate permute[] */
214 for(i=minLen;i<=maxLen;i++)
215 for(t=0;t<symCount;t++)
216 if(length[t]==i) hufGroup->permute[pp++] = t;
217 /* Count cumulative symbols coded for at each bit length */
218 for (i=minLen;i<=maxLen;i++) temp[i]=limit[i]=0;
219 for (i=0;i<symCount;i++) temp[length[i]]++;
220 /* Calculate limit[] (the largest symbol-coding value at each bit
221 * length, which is (previous limit<<1)+symbols at this level), and
222 * base[] (number of symbols to ignore at each bit length, which is
223 * limit-cumulative count of symbols coded for already). */
225 for (i=minLen; i<maxLen; i++) {
229 base[i+1]=pp-(t+=temp[i]);
231 limit[maxLen]=pp+temp[maxLen]-1;
234 /* We've finished reading and digesting the block header. Now read this
235 block's huffman coded symbols from the file and undo the huffman coding
236 and run length encoding, saving the result into dbuf[dbufCount++]=uc */
238 /* Initialize symbol occurrence counters and symbol mtf table */
239 memset(byteCount,0,256*sizeof(int));
240 for(i=0;i<256;i++) mtfSymbol[i]=(unsigned char)i;
241 /* Loop through compressed symbols */
242 runPos=dbufCount=symCount=selector=0;
244 /* Determine which huffman coding group to use. */
246 symCount=GROUP_SIZE-1;
247 if(selector>=nSelectors) return RETVAL_DATA_ERROR;
248 hufGroup=bd->groups+selectors[selector++];
249 base=hufGroup->base-1;
250 limit=hufGroup->limit-1;
252 /* Read next huffman-coded symbol */
253 i = hufGroup->minLen;
256 if (i > hufGroup->maxLen) return RETVAL_DATA_ERROR;
257 if (j <= limit[i]) break;
260 j = (j << 1) | get_bits(bd,1);
262 /* Huffman decode nextSym (with bounds checking) */
264 if (j < 0 || j >= MAX_SYMBOLS) return RETVAL_DATA_ERROR;
265 nextSym = hufGroup->permute[j];
266 /* If this is a repeated run, loop collecting data */
267 if (nextSym == SYMBOL_RUNA || nextSym == SYMBOL_RUNB) {
268 /* If this is the start of a new run, zero out counter */
273 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
274 each bit position, add 1 or 2 instead. For example,
275 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
276 You can make any bit pattern that way using 1 less symbol than
277 the basic or 0/1 method (except all bits 0, which would use no
278 symbols, but a run of length 0 doesn't mean anything in this
279 context). Thus space is saved. */
280 if (nextSym == SYMBOL_RUNA) t += runPos;
285 /* When we hit the first non-run symbol after a run, we now know
286 how many times to repeat the last literal, so append that many
287 copies to our buffer of decoded symbols (dbuf) now. (The last
288 literal used is the one at the head of the mtfSymbol array.) */
291 if(dbufCount+t>=dbufSize) return RETVAL_DATA_ERROR;
293 uc = symToByte[mtfSymbol[0]];
295 while(t--) dbuf[dbufCount++]=uc;
297 /* Is this the terminating symbol? */
298 if(nextSym>symTotal) break;
299 /* At this point, the symbol we just decoded indicates a new literal
300 character. Subtract one to get the position in the MTF array
301 at which this literal is currently to be found. (Note that the
302 result can't be -1 or 0, because 0 and 1 are RUNA and RUNB.
303 Another instance of the first symbol in the mtf array, position 0,
304 would have been handled as part of a run.) */
305 if(dbufCount>=dbufSize) return RETVAL_DATA_ERROR;
308 memmove(mtfSymbol+1,mtfSymbol,i);
311 /* We have our literal byte. Save it into dbuf. */
313 dbuf[dbufCount++] = (unsigned int)uc;
315 /* At this point, we've finished reading huffman-coded symbols and
316 compressed runs from the input stream. There are dbufCount many of
317 them in dbuf[]. Now undo the Burrows-Wheeler transform on dbuf.
318 See http://dogma.net/markn/articles/bwt/bwt.htm
321 /* Now we know what dbufCount is, do a better sanity check on origPtr. */
322 if (origPtr<0 || origPtr>=dbufCount) return RETVAL_DATA_ERROR;
323 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
330 /* Figure out what order dbuf would be in if we sorted it. */
331 for (i=0;i<dbufCount;i++) {
332 uc = (unsigned char)(dbuf[i] & 0xff);
333 dbuf[byteCount[uc]] |= (i << 8);
336 /* blockRandomised support would go here. */
338 /* Using i as position, j as previous character, t as current character,
339 and uc as run count */
340 bd->dataCRC = 0xffffffffL;
341 /* Decode first byte by hand to initialize "previous" byte. Note that it
342 doesn't get output, and if the first three characters are identical
343 it doesn't qualify as a run (hence uc=255, which will either wrap
344 to 1 or get reset). */
346 bd->writePos=dbuf[origPtr];
347 bd->writeCurrent=(unsigned char)(bd->writePos&0xff);
351 bd->writeCount=dbufCount;
356 /* Flush output buffer to disk */
357 extern void flush_bunzip_outbuf(bunzip_data *bd, int out_fd)
360 if(write(out_fd, bd->outbuf, bd->outbufPos) != bd->outbufPos)
361 longjmp(bd->jmpbuf,RETVAL_UNEXPECTED_OUTPUT_EOF);
367 /* Undo burrows-wheeler transform on intermediate buffer to produce output.
368 If !len, write up to len bytes of data to buf. Otherwise write to out_fd.
369 Returns len ? bytes written : RETVAL_OK. Notice all errors negative #'s. */
370 extern int write_bunzip_data(bunzip_data *bd, int out_fd, char *outbuf, int len)
372 unsigned int *dbuf=bd->dbuf;
373 int count,pos,current, run,copies,outbyte,previous,gotcount=0;
376 /* If last read was short due to end of file, return last block now */
377 if(bd->writeCount<0) return bd->writeCount;
378 /* If we need to refill dbuf, do it. */
379 if(!bd->writeCount) {
380 int i=read_bunzip_data(bd);
382 if(i==RETVAL_LAST_BLOCK) {
388 /* Loop generating output */
389 count=bd->writeCount;
391 current=bd->writeCurrent;
394 /* If somebody (like busybox tar) wants a certain number of bytes of
395 data from memory instead of written to a file, humor them */
396 if(len && bd->outbufPos>=len) goto dataus_interruptus;
398 /* Follow sequence vector to undo Burrows-Wheeler transform */
403 /* Whenever we see 3 consecutive copies of the same byte,
404 the 4th is a repeat count */
413 /* Output bytes to buffer, flushing to file if necessary */
415 if(bd->outbufPos == IOBUF_SIZE) flush_bunzip_outbuf(bd,out_fd);
416 bd->outbuf[bd->outbufPos++] = outbyte;
417 bd->dataCRC = (bd->dataCRC << 8)
418 ^ bd->crc32Table[(bd->dataCRC >> 24) ^ outbyte];
420 if(current!=previous) run=0;
422 /* Decompression of this block completed successfully */
423 bd->dataCRC=~(bd->dataCRC);
424 bd->totalCRC=((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bd->dataCRC;
425 /* If this block had a CRC error, force file level CRC error. */
426 if(bd->dataCRC!=bd->headerCRC) {
427 bd->totalCRC=bd->headerCRC+1;
428 return RETVAL_LAST_BLOCK;
431 bd->writeCount=count;
433 gotcount+=bd->outbufPos;
434 memcpy(outbuf,bd->outbuf,len);
435 /* If we got enough data, checkpoint loop state and return */
436 if((len-=bd->outbufPos)<1) {
439 memmove(bd->outbuf,bd->outbuf+len,bd->outbufPos);
441 bd->writeCurrent=current;
449 /* Allocate the structure, read file header. If !len, src_fd contains
450 filehandle to read from. Else inbuf contains data. */
451 extern int start_bunzip(bunzip_data **bdp, int src_fd, char *inbuf, int len)
456 /* Figure out how much data to allocate */
457 i=sizeof(bunzip_data);
458 if(!len) i+=IOBUF_SIZE;
459 /* Allocate bunzip_data. Most fields initialize to zero. */
460 if(!(bd=*bdp=malloc(i))) return RETVAL_OUT_OF_MEMORY;
461 memset(bd,0,sizeof(bunzip_data));
467 bd->inbuf=(char *)(bd+1);
470 /* Init the CRC32 table (big endian) */
474 c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
477 /* Setup for I/O error handling via longjmp */
478 i=setjmp(bd->jmpbuf);
480 /* Ensure that file starts with "BZh" */
481 for(i=0;i<3;i++) if(get_bits(bd,8)!="BZh"[i]) return RETVAL_NOT_BZIP_DATA;
482 /* Next byte ascii '1'-'9', indicates block size in units of 100k of
483 uncompressed data. Allocate intermediate buffer for block. */
485 if (i<'1' || i>'9') return RETVAL_NOT_BZIP_DATA;
486 bd->dbufSize=100000*(i-'0');
487 if(!(bd->dbuf=malloc(bd->dbufSize * sizeof(int))))
488 return RETVAL_OUT_OF_MEMORY;
492 extern char *uncompressStream(int src_fd, int dst_fd)
497 if(!(i=start_bunzip(&bd,src_fd,0,0))) {
498 i=write_bunzip_data(bd,dst_fd,0,0);
499 if(i==RETVAL_LAST_BLOCK && bd->headerCRC==bd->totalCRC) i=RETVAL_OK;
501 flush_bunzip_outbuf(bd,dst_fd);
502 if(bd->dbuf) free(bd->dbuf);
504 return bunzip_errors[-i];
507 /* This new version is not yet properly integrated with tar */
508 extern ssize_t read_bz2(int fd, void *buf, size_t count)
514 extern void BZ2_bzReadOpen(int fd, void *unused, int nUnused)
519 extern void BZ2_bzReadClose(void)
525 /* Dumb little test thing, decompress stdin to stdout */
526 int main(int argc, char *argv[])
528 char *c=uncompressStream(0,1);
529 fprintf(stderr,"\n%s\n", c ? c : "Completed OK");