1 /* bzcat.c - decompress stdin to stdout using bunzip2.
2  *
3  * Copyright 2003, 2007 Rob Landley <rob@landley.net>
4  *
5  * Based on a close reading (but not the actual code) of the original bzip2
6  * decompression code by Julian R Seward (jseward@acm.org), which also
7  * acknowledges contributions by Mike Burrows, David Wheeler, Peter Fenwick,
8  * Alistair Moffat, Radford Neal, Ian H. Witten, Robert Sedgewick, and
9  * Jon L. Bentley.
10  *
11  * No standard.
12 
13 
14 USE_BZCAT(NEWTOY(bzcat, NULL, TOYFLAG_USR|TOYFLAG_BIN))
15 
16 config BZCAT
17   bool "bzcat"
18   default y
19   help
20     usage: bzcat [filename...]
21 
22     Decompress listed files to stdout. Use stdin if no files listed.
23 */
24 
25 #include "toys.h"
26 
27 #define THREADS 1
28 
29 // Constants for huffman coding
30 #define MAX_GROUPS               6
31 #define GROUP_SIZE               50     /* 64 would have been more efficient */
32 #define MAX_HUFCODE_BITS         20     /* Longest huffman code allowed */
33 #define MAX_SYMBOLS              258    /* 256 literals + RUNA + RUNB */
34 #define SYMBOL_RUNA              0
35 #define SYMBOL_RUNB              1
36 
37 // Other housekeeping constants
38 #define IOBUF_SIZE               4096
39 
40 // Status return values
41 #define RETVAL_LAST_BLOCK        (-100)
42 #define RETVAL_NOT_BZIP_DATA     (-1)
43 #define RETVAL_DATA_ERROR        (-2)
44 #define RETVAL_OBSOLETE_INPUT    (-3)
45 
46 // This is what we know about each huffman coding group
47 struct group_data {
48   int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
49   char minLen, maxLen;
50 };
51 
52 // Data for burrows wheeler transform
53 
54 struct bwdata {
55   unsigned int origPtr;
56   int byteCount[256];
57   // State saved when interrupting output
58   int writePos, writeRun, writeCount, writeCurrent;
59   unsigned int dataCRC, headerCRC;
60   unsigned int *dbuf;
61 };
62 
63 // Structure holding all the housekeeping data, including IO buffers and
64 // memory that persists between calls to bunzip
65 struct bunzip_data {
66   // Input stream, input buffer, input bit buffer
67   int in_fd, inbufCount, inbufPos;
68   char *inbuf;
69   unsigned int inbufBitCount, inbufBits;
70 
71   // Output buffer
72   char outbuf[IOBUF_SIZE];
73   int outbufPos;
74 
75   unsigned int totalCRC;
76 
77   // First pass decompression data (Huffman and MTF decoding)
78   char selectors[32768];                  // nSelectors=15 bits
79   struct group_data groups[MAX_GROUPS];   // huffman coding tables
80   int symTotal, groupCount, nSelectors;
81   unsigned char symToByte[256], mtfSymbol[256];
82 
83   // The CRC values stored in the block header and calculated from the data
84   unsigned int crc32Table[256];
85 
86   // Second pass decompression data (burrows-wheeler transform)
87   unsigned int dbufSize;
88   struct bwdata bwdata[THREADS];
89 };
90 
91 // Return the next nnn bits of input.  All reads from the compressed input
92 // are done through this function.  All reads are big endian.
get_bits(struct bunzip_data * bd,char bits_wanted)93 static unsigned int get_bits(struct bunzip_data *bd, char bits_wanted)
94 {
95   unsigned int bits = 0;
96 
97   // If we need to get more data from the byte buffer, do so.  (Loop getting
98   // one byte at a time to enforce endianness and avoid unaligned access.)
99   while (bd->inbufBitCount < bits_wanted) {
100 
101     // If we need to read more data from file into byte buffer, do so
102     if (bd->inbufPos == bd->inbufCount) {
103       if (0 >= (bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE)))
104         error_exit("input EOF");
105       bd->inbufPos = 0;
106     }
107 
108     // Avoid 32-bit overflow (dump bit buffer to top of output)
109     if (bd->inbufBitCount>=24) {
110       bits = bd->inbufBits&((1<<bd->inbufBitCount)-1);
111       bits_wanted -= bd->inbufBitCount;
112       bits <<= bits_wanted;
113       bd->inbufBitCount = 0;
114     }
115 
116     // Grab next 8 bits of input from buffer.
117     bd->inbufBits = (bd->inbufBits<<8) | bd->inbuf[bd->inbufPos++];
118     bd->inbufBitCount += 8;
119   }
120 
121   // Calculate result
122   bd->inbufBitCount -= bits_wanted;
123   bits |= (bd->inbufBits>>bd->inbufBitCount) & ((1<<bits_wanted)-1);
124 
125   return bits;
126 }
127 
128 /* Read block header at start of a new compressed data block.  Consists of:
129  *
130  * 48 bits : Block signature, either pi (data block) or e (EOF block).
131  * 32 bits : bw->headerCRC
132  * 1  bit  : obsolete feature flag.
133  * 24 bits : origPtr (Burrows-wheeler unwind index, only 20 bits ever used)
134  * 16 bits : Mapping table index.
135  *[16 bits]: symToByte[symTotal] (Mapping table.  For each bit set in mapping
136  *           table index above, read another 16 bits of mapping table data.
137  *           If correspondig bit is unset, all bits in that mapping table
138  *           section are 0.)
139  *  3 bits : groupCount (how many huffman tables used to encode, anywhere
140  *           from 2 to MAX_GROUPS)
141  * variable: hufGroup[groupCount] (MTF encoded huffman table data.)
142  */
143 
read_block_header(struct bunzip_data * bd,struct bwdata * bw)144 static int read_block_header(struct bunzip_data *bd, struct bwdata *bw)
145 {
146   struct group_data *hufGroup;
147   int hh, ii, jj, kk, symCount, *base, *limit;
148   unsigned char uc;
149 
150   // Read in header signature and CRC (which is stored big endian)
151   ii = get_bits(bd, 24);
152   jj = get_bits(bd, 24);
153   bw->headerCRC = get_bits(bd,32);
154 
155   // Is this the EOF block with CRC for whole file?  (Constant is "e")
156   if (ii==0x177245 && jj==0x385090) return RETVAL_LAST_BLOCK;
157 
158   // Is this a valid data block?  (Constant is "pi".)
159   if (ii!=0x314159 || jj!=0x265359) return RETVAL_NOT_BZIP_DATA;
160 
161   // We can add support for blockRandomised if anybody complains.
162   if (get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
163   if ((bw->origPtr = get_bits(bd,24)) > bd->dbufSize) return RETVAL_DATA_ERROR;
164 
165   // mapping table: if some byte values are never used (encoding things
166   // like ascii text), the compression code removes the gaps to have fewer
167   // symbols to deal with, and writes a sparse bitfield indicating which
168   // values were present.  We make a translation table to convert the symbols
169   // back to the corresponding bytes.
170   hh = get_bits(bd, 16);
171   bd->symTotal = 0;
172   for (ii=0; ii<16; ii++) {
173     if (hh & (1 << (15 - ii))) {
174       kk = get_bits(bd, 16);
175       for (jj=0; jj<16; jj++)
176         if (kk & (1 << (15 - jj)))
177           bd->symToByte[bd->symTotal++] = (16 * ii) + jj;
178     }
179   }
180 
181   // How many different huffman coding groups does this block use?
182   bd->groupCount = get_bits(bd,3);
183   if (bd->groupCount<2 || bd->groupCount>MAX_GROUPS) return RETVAL_DATA_ERROR;
184 
185   // nSelectors: Every GROUP_SIZE many symbols we switch huffman coding
186   // tables.  Each group has a selector, which is an index into the huffman
187   // coding table arrays.
188   //
189   // Read in the group selector array, which is stored as MTF encoded
190   // bit runs.  (MTF = Move To Front.  Every time a symbol occurs it's moved
191   // to the front of the table, so it has a shorter encoding next time.)
192   if (!(bd->nSelectors = get_bits(bd, 15))) return RETVAL_DATA_ERROR;
193   for (ii=0; ii<bd->groupCount; ii++) bd->mtfSymbol[ii] = ii;
194   for (ii=0; ii<bd->nSelectors; ii++) {
195 
196     // Get next value
197     for(jj=0;get_bits(bd,1);jj++)
198       if (jj>=bd->groupCount) return RETVAL_DATA_ERROR;
199 
200     // Decode MTF to get the next selector, and move it to the front.
201     uc = bd->mtfSymbol[jj];
202     memmove(bd->mtfSymbol+1, bd->mtfSymbol, jj);
203     bd->mtfSymbol[0] = bd->selectors[ii] = uc;
204   }
205 
206   // Read the huffman coding tables for each group, which code for symTotal
207   // literal symbols, plus two run symbols (RUNA, RUNB)
208   symCount = bd->symTotal+2;
209   for (jj=0; jj<bd->groupCount; jj++) {
210     unsigned char length[MAX_SYMBOLS];
211     unsigned temp[MAX_HUFCODE_BITS+1];
212     int minLen, maxLen, pp;
213 
214     // Read lengths
215     hh = get_bits(bd, 5);
216     for (ii = 0; ii < symCount; ii++) {
217       for(;;) {
218         // !hh || hh > MAX_HUFCODE_BITS in one test.
219         if (MAX_HUFCODE_BITS-1 < (unsigned)hh-1) return RETVAL_DATA_ERROR;
220         // Grab 2 bits instead of 1 (slightly smaller/faster).  Stop if
221         // first bit is 0, otherwise second bit says whether to
222         // increment or decrement.
223         kk = get_bits(bd, 2);
224         if (kk & 2) hh += 1 - ((kk&1)<<1);
225         else {
226           bd->inbufBitCount++;
227           break;
228         }
229       }
230       length[ii] = hh;
231     }
232 
233     // Find largest and smallest lengths in this group
234     minLen = maxLen = length[0];
235     for (ii = 1; ii < symCount; ii++) {
236       if(length[ii] > maxLen) maxLen = length[ii];
237       else if(length[ii] < minLen) minLen = length[ii];
238     }
239 
240     /* Calculate permute[], base[], and limit[] tables from length[].
241      *
242      * permute[] is the lookup table for converting huffman coded symbols
243      * into decoded symbols.  It contains symbol values sorted by length.
244      *
245      * base[] is the amount to subtract from the value of a huffman symbol
246      * of a given length when using permute[].
247      *
248      * limit[] indicates the largest numerical value a symbol with a given
249      * number of bits can have.  It lets us know when to stop reading.
250      *
251      * To use these, keep reading bits until value <= limit[bitcount] or
252      * you've read over 20 bits (error).  Then the decoded symbol
253      * equals permute[hufcode_value - base[hufcode_bitcount]].
254      */
255     hufGroup = bd->groups+jj;
256     hufGroup->minLen = minLen;
257     hufGroup->maxLen = maxLen;
258 
259     // Note that minLen can't be smaller than 1, so we adjust the base
260     // and limit array pointers so we're not always wasting the first
261     // entry.  We do this again when using them (during symbol decoding).
262     base = hufGroup->base-1;
263     limit = hufGroup->limit-1;
264 
265     // zero temp[] and limit[], and calculate permute[]
266     pp = 0;
267     for (ii = minLen; ii <= maxLen; ii++) {
268       temp[ii] = limit[ii] = 0;
269       for (hh = 0; hh < symCount; hh++)
270         if (length[hh] == ii) hufGroup->permute[pp++] = hh;
271     }
272 
273     // Count symbols coded for at each bit length
274     for (ii = 0; ii < symCount; ii++) temp[length[ii]]++;
275 
276     /* Calculate limit[] (the largest symbol-coding value at each bit
277      * length, which is (previous limit<<1)+symbols at this level), and
278      * base[] (number of symbols to ignore at each bit length, which is
279      * limit minus the cumulative count of symbols coded for already). */
280     pp = hh = 0;
281     for (ii = minLen; ii < maxLen; ii++) {
282       pp += temp[ii];
283       limit[ii] = pp-1;
284       pp <<= 1;
285       base[ii+1] = pp-(hh+=temp[ii]);
286     }
287     limit[maxLen] = pp+temp[maxLen]-1;
288     limit[maxLen+1] = INT_MAX;
289     base[minLen] = 0;
290   }
291 
292   return 0;
293 }
294 
295 /* First pass, read block's symbols into dbuf[dbufCount].
296  *
297  * This undoes three types of compression: huffman coding, run length encoding,
298  * and move to front encoding.  We have to undo all those to know when we've
299  * read enough input.
300  */
301 
read_huffman_data(struct bunzip_data * bd,struct bwdata * bw)302 static int read_huffman_data(struct bunzip_data *bd, struct bwdata *bw)
303 {
304   struct group_data *hufGroup;
305   int hh, ii, jj, kk, runPos, dbufCount, symCount, selector, nextSym,
306     *byteCount, *base, *limit;
307   unsigned int *dbuf = bw->dbuf;
308   unsigned char uc;
309 
310   // We've finished reading and digesting the block header.  Now read this
311   // block's huffman coded symbols from the file and undo the huffman coding
312   // and run length encoding, saving the result into dbuf[dbufCount++] = uc
313 
314   // Initialize symbol occurrence counters and symbol mtf table
315   byteCount = bw->byteCount;
316   for(ii=0; ii<256; ii++) {
317     byteCount[ii] = 0;
318     bd->mtfSymbol[ii] = ii;
319   }
320 
321   // Loop through compressed symbols.  This is the first "tight inner loop"
322   // that needs to be micro-optimized for speed.  (This one fills out dbuf[]
323   // linearly, staying in cache more, so isn't as limited by DRAM access.)
324   runPos = dbufCount = symCount = selector = 0;
325   // Some unnecessary initializations to shut gcc up.
326   base = limit = 0;
327   hufGroup = 0;
328   hh = 0;
329 
330   for (;;) {
331     // Have we reached the end of this huffman group?
332     if (!(symCount--)) {
333       // Determine which huffman coding group to use.
334       symCount = GROUP_SIZE-1;
335       if (selector >= bd->nSelectors) return RETVAL_DATA_ERROR;
336       hufGroup = bd->groups + bd->selectors[selector++];
337       base = hufGroup->base-1;
338       limit = hufGroup->limit-1;
339     }
340 
341     // Read next huffman-coded symbol (into jj).
342     ii = hufGroup->minLen;
343     jj = get_bits(bd, ii);
344     while (jj > limit[ii]) {
345       // if (ii > hufGroup->maxLen) return RETVAL_DATA_ERROR;
346       ii++;
347 
348       // Unroll get_bits() to avoid a function call when the data's in
349       // the buffer already.
350       kk = bd->inbufBitCount
351         ? (bd->inbufBits >> --(bd->inbufBitCount)) & 1 : get_bits(bd, 1);
352       jj = (jj << 1) | kk;
353     }
354     // Huffman decode jj into nextSym (with bounds checking)
355     jj-=base[ii];
356 
357     if (ii > hufGroup->maxLen || (unsigned)jj >= MAX_SYMBOLS)
358       return RETVAL_DATA_ERROR;
359     nextSym = hufGroup->permute[jj];
360 
361     // If this is a repeated run, loop collecting data
362     if ((unsigned)nextSym <= SYMBOL_RUNB) {
363       // If this is the start of a new run, zero out counter
364       if(!runPos) {
365         runPos = 1;
366         hh = 0;
367       }
368 
369       /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
370          each bit position, add 1 or 2 instead. For example,
371          1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
372          You can make any bit pattern that way using 1 less symbol than
373          the basic or 0/1 method (except all bits 0, which would use no
374          symbols, but a run of length 0 doesn't mean anything in this
375          context). Thus space is saved. */
376       hh += (runPos << nextSym); // +runPos if RUNA; +2*runPos if RUNB
377       runPos <<= 1;
378       continue;
379     }
380 
381     /* When we hit the first non-run symbol after a run, we now know
382        how many times to repeat the last literal, so append that many
383        copies to our buffer of decoded symbols (dbuf) now. (The last
384        literal used is the one at the head of the mtfSymbol array.) */
385     if (runPos) {
386       runPos = 0;
387       if (dbufCount+hh > bd->dbufSize) return RETVAL_DATA_ERROR;
388 
389       uc = bd->symToByte[bd->mtfSymbol[0]];
390       byteCount[uc] += hh;
391       while (hh--) dbuf[dbufCount++] = uc;
392     }
393 
394     // Is this the terminating symbol?
395     if (nextSym>bd->symTotal) break;
396 
397     /* At this point, the symbol we just decoded indicates a new literal
398        character. Subtract one to get the position in the MTF array
399        at which this literal is currently to be found. (Note that the
400        result can't be -1 or 0, because 0 and 1 are RUNA and RUNB.
401        Another instance of the first symbol in the mtf array, position 0,
402        would have been handled as part of a run.) */
403     if (dbufCount>=bd->dbufSize) return RETVAL_DATA_ERROR;
404     ii = nextSym - 1;
405     uc = bd->mtfSymbol[ii];
406     // On my laptop, unrolling this memmove() into a loop shaves 3.5% off
407     // the total running time.
408     while(ii--) bd->mtfSymbol[ii+1] = bd->mtfSymbol[ii];
409     bd->mtfSymbol[0] = uc;
410     uc = bd->symToByte[uc];
411 
412     // We have our literal byte.  Save it into dbuf.
413     byteCount[uc]++;
414     dbuf[dbufCount++] = (unsigned int)uc;
415   }
416 
417   // Now we know what dbufCount is, do a better sanity check on origPtr.
418   if (bw->origPtr >= (bw->writeCount = dbufCount)) return RETVAL_DATA_ERROR;
419 
420   return 0;
421 }
422 
423 // Flush output buffer to disk
flush_bunzip_outbuf(struct bunzip_data * bd,int out_fd)424 void flush_bunzip_outbuf(struct bunzip_data *bd, int out_fd)
425 {
426   if (bd->outbufPos) {
427     if (write(out_fd, bd->outbuf, bd->outbufPos) != bd->outbufPos)
428       error_exit("output EOF");
429     bd->outbufPos = 0;
430   }
431 }
432 
burrows_wheeler_prep(struct bunzip_data * bd,struct bwdata * bw)433 void burrows_wheeler_prep(struct bunzip_data *bd, struct bwdata *bw)
434 {
435   int ii, jj;
436   unsigned int *dbuf = bw->dbuf;
437   int *byteCount = bw->byteCount;
438 
439   // Technically this part is preparation for the burrows-wheeler
440   // transform, but it's quick and convenient to do here.
441 
442   // Turn byteCount into cumulative occurrence counts of 0 to n-1.
443   jj = 0;
444   for (ii=0; ii<256; ii++) {
445     int kk = jj + byteCount[ii];
446     byteCount[ii] = jj;
447     jj = kk;
448   }
449 
450   // Use occurrence counts to quickly figure out what order dbuf would be in
451   // if we sorted it.
452   for (ii=0; ii < bw->writeCount; ii++) {
453     unsigned char uc = dbuf[ii];
454     dbuf[byteCount[uc]] |= (ii << 8);
455     byteCount[uc]++;
456   }
457 
458   // blockRandomised support would go here.
459 
460   // Using ii as position, jj as previous character, hh as current character,
461   // and uc as run count.
462   bw->dataCRC = 0xffffffffL;
463 
464   /* Decode first byte by hand to initialize "previous" byte. Note that it
465      doesn't get output, and if the first three characters are identical
466      it doesn't qualify as a run (hence uc=255, which will either wrap
467      to 1 or get reset). */
468   if (bw->writeCount) {
469     bw->writePos = dbuf[bw->origPtr];
470     bw->writeCurrent = (unsigned char)bw->writePos;
471     bw->writePos >>= 8;
472     bw->writeRun = -1;
473   }
474 }
475 
476 // Decompress a block of text to intermediate buffer
read_bunzip_data(struct bunzip_data * bd)477 int read_bunzip_data(struct bunzip_data *bd)
478 {
479   int rc = read_block_header(bd, bd->bwdata);
480   if (!rc) rc=read_huffman_data(bd, bd->bwdata);
481 
482   // First thing that can be done by a background thread.
483   burrows_wheeler_prep(bd, bd->bwdata);
484 
485   return rc;
486 }
487 
488 // Undo burrows-wheeler transform on intermediate buffer to produce output.
489 // If !len, write up to len bytes of data to buf.  Otherwise write to out_fd.
490 // Returns len ? bytes written : 0.  Notice all errors are negative #'s.
491 //
492 // Burrows-wheeler transform is described at:
493 // http://dogma.net/markn/articles/bwt/bwt.htm
494 // http://marknelson.us/1996/09/01/bwt/
495 
write_bunzip_data(struct bunzip_data * bd,struct bwdata * bw,int out_fd,char * outbuf,int len)496 int write_bunzip_data(struct bunzip_data *bd, struct bwdata *bw, int out_fd, char *outbuf, int len)
497 {
498   unsigned int *dbuf = bw->dbuf;
499   int count, pos, current, run, copies, outbyte, previous, gotcount = 0;
500 
501   for (;;) {
502     // If last read was short due to end of file, return last block now
503     if (bw->writeCount < 0) return bw->writeCount;
504 
505     // If we need to refill dbuf, do it.
506     if (!bw->writeCount) {
507       int i = read_bunzip_data(bd);
508       if (i) {
509         if (i == RETVAL_LAST_BLOCK) {
510           bw->writeCount = i;
511           return gotcount;
512         } else return i;
513       }
514     }
515 
516     // loop generating output
517     count = bw->writeCount;
518     pos = bw->writePos;
519     current = bw->writeCurrent;
520     run = bw->writeRun;
521     while (count) {
522 
523       // If somebody (like tar) wants a certain number of bytes of
524       // data from memory instead of written to a file, humor them.
525       if (len && bd->outbufPos >= len) goto dataus_interruptus;
526       count--;
527 
528       // Follow sequence vector to undo Burrows-Wheeler transform.
529       previous = current;
530       pos = dbuf[pos];
531       current = pos&0xff;
532       pos >>= 8;
533 
534       // Whenever we see 3 consecutive copies of the same byte,
535       // the 4th is a repeat count
536       if (run++ == 3) {
537         copies = current;
538         outbyte = previous;
539         current = -1;
540       } else {
541         copies = 1;
542         outbyte = current;
543       }
544 
545       // Output bytes to buffer, flushing to file if necessary
546       while (copies--) {
547         if (bd->outbufPos == IOBUF_SIZE) flush_bunzip_outbuf(bd, out_fd);
548         bd->outbuf[bd->outbufPos++] = outbyte;
549         bw->dataCRC = (bw->dataCRC << 8)
550                 ^ bd->crc32Table[(bw->dataCRC >> 24) ^ outbyte];
551       }
552       if (current != previous) run=0;
553     }
554 
555     // decompression of this block completed successfully
556     bw->dataCRC = ~(bw->dataCRC);
557     bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bw->dataCRC;
558 
559     // if this block had a crc error, force file level crc error.
560     if (bw->dataCRC != bw->headerCRC) {
561       bd->totalCRC = bw->headerCRC+1;
562 
563       return RETVAL_LAST_BLOCK;
564     }
565 dataus_interruptus:
566     bw->writeCount = count;
567     if (len) {
568       gotcount += bd->outbufPos;
569       memcpy(outbuf, bd->outbuf, len);
570 
571       // If we got enough data, checkpoint loop state and return
572       if ((len -= bd->outbufPos)<1) {
573         bd->outbufPos -= len;
574         if (bd->outbufPos) memmove(bd->outbuf, bd->outbuf+len, bd->outbufPos);
575         bw->writePos = pos;
576         bw->writeCurrent = current;
577         bw->writeRun = run;
578 
579         return gotcount;
580       }
581     }
582   }
583 }
584 
585 // Allocate the structure, read file header. If !len, src_fd contains
586 // filehandle to read from. Else inbuf contains data.
start_bunzip(struct bunzip_data ** bdp,int src_fd,char * inbuf,int len)587 int start_bunzip(struct bunzip_data **bdp, int src_fd, char *inbuf, int len)
588 {
589   struct bunzip_data *bd;
590   unsigned int i;
591 
592   // Figure out how much data to allocate.
593   i = sizeof(struct bunzip_data);
594   if (!len) i += IOBUF_SIZE;
595 
596   // Allocate bunzip_data. Most fields initialize to zero.
597   bd = *bdp = xzalloc(i);
598   if (len) {
599     bd->inbuf = inbuf;
600     bd->inbufCount = len;
601     bd->in_fd = -1;
602   } else {
603     bd->inbuf = (char *)(bd+1);
604     bd->in_fd = src_fd;
605   }
606 
607   crc_init(bd->crc32Table, 0);
608 
609   // Ensure that file starts with "BZh".
610   for (i=0;i<3;i++) if (get_bits(bd,8)!="BZh"[i]) return RETVAL_NOT_BZIP_DATA;
611 
612   // Next byte ascii '1'-'9', indicates block size in units of 100k of
613   // uncompressed data. Allocate intermediate buffer for block.
614   i = get_bits(bd, 8);
615   if (i<'1' || i>'9') return RETVAL_NOT_BZIP_DATA;
616   bd->dbufSize = 100000*(i-'0')*THREADS;
617   for (i=0; i<THREADS; i++)
618     bd->bwdata[i].dbuf = xmalloc(bd->dbufSize * sizeof(int));
619 
620   return 0;
621 }
622 
623 // Example usage: decompress src_fd to dst_fd. (Stops at end of bzip data,
624 // not end of file.)
bunzipStream(int src_fd,int dst_fd)625 void bunzipStream(int src_fd, int dst_fd)
626 {
627   struct bunzip_data *bd;
628   char *bunzip_errors[]={NULL, "not bzip", "bad data", "old format"};
629   int i, j;
630 
631   if (!(i = start_bunzip(&bd,src_fd, 0, 0))) {
632     i = write_bunzip_data(bd,bd->bwdata, dst_fd, 0, 0);
633     if (i==RETVAL_LAST_BLOCK && bd->bwdata[0].headerCRC==bd->totalCRC) i = 0;
634   }
635   flush_bunzip_outbuf(bd, dst_fd);
636 
637   for (j=0; j<THREADS; j++) free(bd->bwdata[j].dbuf);
638   free(bd);
639   if (i) error_exit(bunzip_errors[-i]);
640 }
641 
do_bzcat(int fd,char * name)642 static void do_bzcat(int fd, char *name)
643 {
644   bunzipStream(fd, 1);
645 }
646 
bzcat_main(void)647 void bzcat_main(void)
648 {
649   loopfiles(toys.optargs, do_bzcat);
650 }
651