Rob Landley's new micro-bunzip version 3. Rob writes:
[oweals/busybox.git] / archival / libunarchive / decompress_bunzip2.c
1 /* vi: set sw=4 ts=4: */
2 /*      Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).
3
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.
8
9         This code is licensed under the LGPLv2:
10                 LGPL (http://www.gnu.org/copyleft/lgpl.html
11 */
12
13 #include <setjmp.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18
19 /* Constants for huffman coding */
20 #define MAX_GROUPS                      6
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 */
24 #define SYMBOL_RUNA                     0
25 #define SYMBOL_RUNB                     1
26
27 /* Status return values */
28 #define RETVAL_OK                                               0
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)
36
37 /* Other housekeeping constants */
38 #define IOBUF_SIZE                      4096
39
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."};
43
44 /* This is what we know about each huffman coding group */
45 struct group_data {
46         int limit[MAX_HUFCODE_BITS],base[MAX_HUFCODE_BITS],permute[MAX_SYMBOLS];
47         char minLen, maxLen;
48 };
49
50 /* Structure holding all the housekeeping data, including IO buffers and
51    memory that persists between calls to bunzip */
52 typedef struct {
53         /* For I/O error handling */
54         jmp_buf jmpbuf;
55         /* Input stream, input buffer, input bit buffer */
56         int in_fd,inbufCount,inbufPos;
57         unsigned char *inbuf;
58         unsigned int inbufBitCount, inbufBits;
59         /* Output buffer */
60         char outbuf[IOBUF_SIZE];
61         int outbufPos;
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;
68
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 */
72 } bunzip_data;
73
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)
77 {
78         unsigned int bits=0;
79
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);
87                         bd->inbufPos=0;
88                 }
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;
93                         bits<<=bits_wanted;
94                         bd->inbufBitCount=0;
95                 }
96                 /* Grab next 8 bits of input from buffer. */
97                 bd->inbufBits=(bd->inbufBits<<8)|bd->inbuf[bd->inbufPos++];
98                 bd->inbufBitCount+=8;
99         }
100         /* Calculate result */
101         bd->inbufBitCount-=bits_wanted;
102         bits|=(bd->inbufBits>>bd->inbufBitCount)&((1<<bits_wanted)-1);
103
104         return bits;
105 }
106
107 /* Decompress a block of text to into intermediate buffer */
108
109 extern int read_bunzip_data(bunzip_data *bd)
110 {
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;
115         unsigned int *dbuf;
116
117         /* Read in header signature (borrowing mtfSymbol for temp space). */
118         for(i=0;i<6;i++) mtfSymbol[i]=get_bits(bd,8);
119         mtfSymbol[6]=0;
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;
128
129         dbuf=bd->dbuf;
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. */
142         t=get_bits(bd, 16);
143         memset(symToByte,0,256);
144         symTotal=0;
145         for (i=0;i<16;i++) {
146                 if(t&(1<<(15-i))) {
147                         k=get_bits(bd,16);
148                         for(j=0;j<16;j++)
149                                 if(k&(1<<(15-j))) symToByte[symTotal++]=(16*i)+j;
150                 }
151         }
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
157            bit runs. */
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++) {
161                 /* Get next value */
162                 for(j=0;get_bits(bd,1);j++) if (j>=groupCount) return RETVAL_DATA_ERROR;
163                 /* Decode MTF to get the next selector */
164                 uc = mtfSymbol[j];
165                 memmove(mtfSymbol+1,mtfSymbol,j);
166                 mtfSymbol[0]=selectors[i]=uc;
167         }
168         /* Read the huffman coding tables for each group, which code for symTotal
169            literal symbols, plus two run symbols (RUNA, RUNB) */
170         symCount=symTotal+2;
171         for (j=0; j<groupCount; j++) {
172                 unsigned char length[MAX_SYMBOLS],temp[MAX_HUFCODE_BITS+1];
173                 int     minLen, maxLen, pp;
174                 /* Read lengths */
175                 t=get_bits(bd, 5);
176                 for (i = 0; i < symCount; i++) {
177                         for(;;) {
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++;
181                                         else t--;
182                         }
183                         length[i] = t;
184                 }
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];
190                 }
191                 /* Calculate permute[], base[], and limit[] tables from length[].
192                  *
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[].
196                  *
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.
199                  *
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]].
203                  */
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[] */
213                 pp = 0;
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). */
224                 pp=t=0;
225                 for (i=minLen; i<maxLen; i++) {
226                         pp+=temp[i];
227                         limit[i]=pp-1;
228                         pp<<=1;
229                         base[i+1]=pp-(t+=temp[i]);
230                 }
231                 limit[maxLen]=pp+temp[maxLen]-1;
232                 base[minLen]=0;
233         }
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 */
237
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;
243         for(;;) {
244                 /* Determine which huffman coding group to use. */
245                 if(!(symCount--)) {
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;
251                 }
252                 /* Read next huffman-coded symbol */
253                 i = hufGroup->minLen;
254                 j=get_bits(bd, i);
255                 for(;;) {
256                         if (i > hufGroup->maxLen) return RETVAL_DATA_ERROR;
257                         if (j <= limit[i]) break;
258                         i++;
259
260                         j = (j << 1) | get_bits(bd,1);
261                 }
262                 /* Huffman decode nextSym (with bounds checking) */
263                 j-=base[i];
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 */
269                         if(!runPos) {
270                                 runPos = 1;
271                                 t = 0;
272                         }
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;
281                         else t += 2*runPos;
282                         runPos <<= 1;
283                         continue;
284                 }
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.) */
289                 if(runPos) {
290                         runPos=0;
291                         if(dbufCount+t>=dbufSize) return RETVAL_DATA_ERROR;
292
293                         uc = symToByte[mtfSymbol[0]];
294                         byteCount[uc] += t;
295                         while(t--) dbuf[dbufCount++]=uc;
296                 }
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;
306                 i = nextSym - 1;
307                 uc = mtfSymbol[i];
308                 memmove(mtfSymbol+1,mtfSymbol,i);
309                 mtfSymbol[0] = uc;
310                 uc=symToByte[uc];
311                 /* We have our literal byte.  Save it into dbuf. */
312                 byteCount[uc]++;
313                 dbuf[dbufCount++] = (unsigned int)uc;
314         }
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
319          */
320
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. */
324         j=0;
325         for(i=0;i<256;i++) {
326                 k=j+byteCount[i];
327                 byteCount[i] = j;
328                 j=k;
329         }
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);
334                 byteCount[uc]++;
335         }
336         /* blockRandomised support would go here. */
337
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). */
345         if(dbufCount) {
346                 bd->writePos=dbuf[origPtr];
347             bd->writeCurrent=(unsigned char)(bd->writePos&0xff);
348                 bd->writePos>>=8;
349                 bd->writeRun=-1;
350         }
351         bd->writeCount=dbufCount;
352
353         return RETVAL_OK;
354 }
355
356 /* Flush output buffer to disk */
357 extern void flush_bunzip_outbuf(bunzip_data *bd, int out_fd)
358 {
359         if(bd->outbufPos) {
360                 if(write(out_fd, bd->outbuf, bd->outbufPos) != bd->outbufPos)
361                         longjmp(bd->jmpbuf,RETVAL_UNEXPECTED_OUTPUT_EOF);
362                 bd->outbufPos=0;
363         }
364 }
365
366
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)
371 {
372         unsigned int *dbuf=bd->dbuf;
373         int count,pos,current, run,copies,outbyte,previous,gotcount=0;
374
375         for(;;) {
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);
381                         if(i) {
382                                 if(i==RETVAL_LAST_BLOCK) {
383                                         bd->writeCount=i;
384                                         return gotcount;
385                                 } else return i;
386                         }
387                 }
388                 /* Loop generating output */
389                 count=bd->writeCount;
390                 pos=bd->writePos;
391                 current=bd->writeCurrent;
392                 run=bd->writeRun;
393                 while(count) {
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;
397                         count--;
398                         /* Follow sequence vector to undo Burrows-Wheeler transform */
399                         previous=current;
400                         pos=dbuf[pos];
401                         current=pos&0xff;
402                         pos>>=8;
403                         /* Whenever we see 3 consecutive copies of the same byte,
404                            the 4th is a repeat count */
405                         if(run++==3) {
406                                 copies=current;
407                                 outbyte=previous;
408                                 current=-1;
409                         } else {
410                                 copies=1;
411                                 outbyte=current;
412                         }
413                         /* Output bytes to buffer, flushing to file if necessary */
414                         while(copies--) {
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];
419                         }
420                         if(current!=previous) run=0;
421                 }
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;
429                 }
430 dataus_interruptus:
431                 bd->writeCount=count;
432                 if(len) {
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) {
437                                 bd->outbufPos-=len;
438                                 if(bd->outbufPos)
439                                         memmove(bd->outbuf,bd->outbuf+len,bd->outbufPos);
440                                 bd->writePos=pos;
441                                 bd->writeCurrent=current;
442                                 bd->writeRun=run;
443                                 return gotcount;
444                         }
445                 }
446         }
447 }
448
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)
452 {
453         bunzip_data *bd;
454         unsigned int i,j,c;
455
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));
462         if(len) {
463                 bd->inbuf=inbuf;
464                 bd->inbufCount=len;
465                 bd->in_fd=-1;
466         } else {
467                 bd->inbuf=(char *)(bd+1);
468                 bd->in_fd=src_fd;
469         }
470         /* Init the CRC32 table (big endian) */
471         for(i=0;i<256;i++) {
472                 c=i<<24;
473                 for(j=8;j;j--)
474                         c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
475                 bd->crc32Table[i]=c;
476         }
477         /* Setup for I/O error handling via longjmp */
478         i=setjmp(bd->jmpbuf);
479         if(i) return i;
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. */
484         i=get_bits(bd,8);
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;
489         return RETVAL_OK;
490 }
491
492 extern char *uncompressStream(int src_fd, int dst_fd)
493 {
494         bunzip_data *bd;
495         int i;
496
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;
500         }
501         flush_bunzip_outbuf(bd,dst_fd);
502         if(bd->dbuf) free(bd->dbuf);
503         free(bd);
504         return bunzip_errors[-i];
505 }
506
507 /* This new version is not yet properly integrated with tar */
508 extern ssize_t read_bz2(int fd, void *buf, size_t count)
509 {
510 #warning FIXME
511         return(0);
512 }
513
514 extern void BZ2_bzReadOpen(int fd, void *unused, int nUnused)
515 {
516 #warning FIXME
517         return;
518 }
519 extern void BZ2_bzReadClose(void)
520 {
521 #warning FIXME
522 }
523
524 #if 0
525 /* Dumb little test thing, decompress stdin to stdout */
526 int main(int argc, char *argv[])
527 {
528         char *c=uncompressStream(0,1);
529         fprintf(stderr,"\n%s\n", c ? c : "Completed OK");
530 }
531 #endif