1 /* bzcat.c - decompress stdin to stdout using bunzip2.
3 * Copyright 2003, 2007 Rob Landley <rob@landley.net>
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
14 USE_BZCAT(NEWTOY(bzcat, NULL, TOYFLAG_USR|TOYFLAG_BIN))
20 usage: bzcat [filename...]
22 Decompress listed files to stdout. Use stdin if no files listed.
29 // Constants for huffman coding
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 */
37 // Other housekeeping constants
38 #define IOBUF_SIZE 4096
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)
46 // This is what we know about each huffman coding group
48 int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
52 // Data for burrows wheeler transform
57 // State saved when interrupting output
58 int writePos, writeRun, writeCount, writeCurrent;
59 unsigned int dataCRC, headerCRC;
63 // Structure holding all the housekeeping data, including IO buffers and
64 // memory that persists between calls to bunzip
66 // Input stream, input buffer, input bit buffer
67 int in_fd, inbufCount, inbufPos;
69 unsigned int inbufBitCount, inbufBits;
72 char outbuf[IOBUF_SIZE];
75 unsigned int totalCRC;
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];
83 // The CRC values stored in the block header and calculated from the data
84 unsigned int crc32Table[256];
86 // Second pass decompression data (burrows-wheeler transform)
87 unsigned int dbufSize;
88 struct bwdata bwdata[THREADS];
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.
93 static unsigned int get_bits(struct bunzip_data *bd, char bits_wanted)
95 unsigned int bits = 0;
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) {
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");
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;
116 // Grab next 8 bits of input from buffer.
117 bd->inbufBits = (bd->inbufBits<<8) | bd->inbuf[bd->inbufPos++];
118 bd->inbufBitCount += 8;
122 bd->inbufBitCount -= bits_wanted;
123 bits |= (bd->inbufBits>>bd->inbufBitCount) & ((1<<bits_wanted)-1);
128 /* Read block header at start of a new compressed data block. Consists of:
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
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.)
144 static int read_block_header(struct bunzip_data *bd, struct bwdata *bw)
146 struct group_data *hufGroup;
147 int hh, ii, jj, kk, symCount, *base, *limit;
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);
155 // Is this the EOF block with CRC for whole file? (Constant is "e")
156 if (ii==0x177245 && jj==0x385090) return RETVAL_LAST_BLOCK;
158 // Is this a valid data block? (Constant is "pi".)
159 if (ii!=0x314159 || jj!=0x265359) return RETVAL_NOT_BZIP_DATA;
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;
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);
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;
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;
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.
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++) {
197 for(jj=0;get_bits(bd,1);jj++)
198 if (jj>=bd->groupCount) return RETVAL_DATA_ERROR;
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;
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;
215 hh = get_bits(bd, 5);
216 for (ii = 0; ii < symCount; ii++) {
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);
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];
240 /* Calculate permute[], base[], and limit[] tables from length[].
242 * permute[] is the lookup table for converting huffman coded symbols
243 * into decoded symbols. It contains symbol values sorted by length.
245 * base[] is the amount to subtract from the value of a huffman symbol
246 * of a given length when using permute[].
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.
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]].
255 hufGroup = bd->groups+jj;
256 hufGroup->minLen = minLen;
257 hufGroup->maxLen = maxLen;
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;
265 // zero temp[] and limit[], and calculate permute[]
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;
273 // Count symbols coded for at each bit length
274 for (ii = 0; ii < symCount; ii++) temp[length[ii]]++;
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). */
281 for (ii = minLen; ii < maxLen; ii++) {
285 base[ii+1] = pp-(hh+=temp[ii]);
287 limit[maxLen] = pp+temp[maxLen]-1;
288 limit[maxLen+1] = INT_MAX;
295 /* First pass, read block's symbols into dbuf[dbufCount].
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
302 static int read_huffman_data(struct bunzip_data *bd, struct bwdata *bw)
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;
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
314 // Initialize symbol occurrence counters and symbol mtf table
315 byteCount = bw->byteCount;
316 for(ii=0; ii<256; ii++) {
318 bd->mtfSymbol[ii] = ii;
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.
331 // Have we reached the end of this huffman group?
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;
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;
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);
354 // Huffman decode jj into nextSym (with bounds checking)
357 if (ii > hufGroup->maxLen || (unsigned)jj >= MAX_SYMBOLS)
358 return RETVAL_DATA_ERROR;
359 nextSym = hufGroup->permute[jj];
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
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
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.) */
387 if (dbufCount+hh > bd->dbufSize) return RETVAL_DATA_ERROR;
389 uc = bd->symToByte[bd->mtfSymbol[0]];
391 while (hh--) dbuf[dbufCount++] = uc;
394 // Is this the terminating symbol?
395 if (nextSym>bd->symTotal) break;
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;
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];
412 // We have our literal byte. Save it into dbuf.
414 dbuf[dbufCount++] = (unsigned int)uc;
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;
423 // Flush output buffer to disk
424 void flush_bunzip_outbuf(struct bunzip_data *bd, int out_fd)
427 if (write(out_fd, bd->outbuf, bd->outbufPos) != bd->outbufPos)
428 error_exit("output EOF");
433 void burrows_wheeler_prep(struct bunzip_data *bd, struct bwdata *bw)
436 unsigned int *dbuf = bw->dbuf;
437 int *byteCount = bw->byteCount;
439 // Technically this part is preparation for the burrows-wheeler
440 // transform, but it's quick and convenient to do here.
442 // Turn byteCount into cumulative occurrence counts of 0 to n-1.
444 for (ii=0; ii<256; ii++) {
445 int kk = jj + byteCount[ii];
450 // Use occurrence counts to quickly figure out what order dbuf would be in
452 for (ii=0; ii < bw->writeCount; ii++) {
453 unsigned char uc = dbuf[ii];
454 dbuf[byteCount[uc]] |= (ii << 8);
458 // blockRandomised support would go here.
460 // Using ii as position, jj as previous character, hh as current character,
461 // and uc as run count.
462 bw->dataCRC = 0xffffffffL;
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;
476 // Decompress a block of text to intermediate buffer
477 int read_bunzip_data(struct bunzip_data *bd)
479 int rc = read_block_header(bd, bd->bwdata);
480 if (!rc) rc=read_huffman_data(bd, bd->bwdata);
482 // First thing that can be done by a background thread.
483 burrows_wheeler_prep(bd, bd->bwdata);
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.
492 // Burrows-wheeler transform is described at:
493 // http://dogma.net/markn/articles/bwt/bwt.htm
494 // http://marknelson.us/1996/09/01/bwt/
496 int write_bunzip_data(struct bunzip_data *bd, struct bwdata *bw, int out_fd, char *outbuf, int len)
498 unsigned int *dbuf = bw->dbuf;
499 int count, pos, current, run, copies, outbyte, previous, gotcount = 0;
502 // If last read was short due to end of file, return last block now
503 if (bw->writeCount < 0) return bw->writeCount;
505 // If we need to refill dbuf, do it.
506 if (!bw->writeCount) {
507 int i = read_bunzip_data(bd);
509 if (i == RETVAL_LAST_BLOCK) {
516 // loop generating output
517 count = bw->writeCount;
519 current = bw->writeCurrent;
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;
528 // Follow sequence vector to undo Burrows-Wheeler transform.
534 // Whenever we see 3 consecutive copies of the same byte,
535 // the 4th is a repeat count
545 // Output bytes to buffer, flushing to file if necessary
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];
552 if (current != previous) run=0;
555 // decompression of this block completed successfully
556 bw->dataCRC = ~(bw->dataCRC);
557 bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bw->dataCRC;
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;
563 return RETVAL_LAST_BLOCK;
566 bw->writeCount = count;
568 gotcount += bd->outbufPos;
569 memcpy(outbuf, bd->outbuf, len);
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);
576 bw->writeCurrent = current;
585 // Allocate the structure, read file header. If !len, src_fd contains
586 // filehandle to read from. Else inbuf contains data.
587 int start_bunzip(struct bunzip_data **bdp, int src_fd, char *inbuf, int len)
589 struct bunzip_data *bd;
592 // Figure out how much data to allocate.
593 i = sizeof(struct bunzip_data);
594 if (!len) i += IOBUF_SIZE;
596 // Allocate bunzip_data. Most fields initialize to zero.
597 bd = *bdp = xzalloc(i);
600 bd->inbufCount = len;
603 bd->inbuf = (char *)(bd+1);
607 crc_init(bd->crc32Table, 0);
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;
612 // Next byte ascii '1'-'9', indicates block size in units of 100k of
613 // uncompressed data. Allocate intermediate buffer for block.
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));
623 // Example usage: decompress src_fd to dst_fd. (Stops at end of bzip data,
625 void bunzipStream(int src_fd, int dst_fd)
627 struct bunzip_data *bd;
628 char *bunzip_errors[]={NULL, "not bzip", "bad data", "old format"};
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;
635 flush_bunzip_outbuf(bd, dst_fd);
637 for (j=0; j<THREADS; j++) free(bd->bwdata[j].dbuf);
639 if (i) error_exit(bunzip_errors[-i]);
642 static void do_bzcat(int fd, char *name)
647 void bzcat_main(void)
649 loopfiles(toys.optargs, do_bzcat);