blob: 2fa0f898a3c2c57c7d1d791c6b0bc4811bcf552d [file] [log] [blame]
Eric Andersen0d6d88a2003-10-18 01:58:35 +00001/* vi: set sw=4 ts=4: */
Rob Landleye66c7ef2006-04-14 19:25:01 +00002/* Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).
Glenn L McGrath60bce492002-11-03 07:28:38 +00003
Rob Landleye66c7ef2006-04-14 19:25:01 +00004 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.
Glenn L McGrath60bce492002-11-03 07:28:38 +00008
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02009 Licensed under GPLv2 or later, see file LICENSE in this source tree.
Eric Andersen0d6d88a2003-10-18 01:58:35 +000010*/
Glenn L McGrath60bce492002-11-03 07:28:38 +000011
Eric Andersen5fa4db22003-10-23 06:52:01 +000012/*
13 Size and speed optimizations by Manuel Novoa III (mjn3@codepoet.org).
14
Eric Andersenaff114c2004-04-14 17:51:38 +000015 More efficient reading of Huffman codes, a streamlined read_bunzip()
Eric Andersen5fa4db22003-10-23 06:52:01 +000016 function, and various other tweaks. In (limited) tests, approximately
17 20% faster than bzcat on x86 and about 10% faster on arm.
18
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020019 Note that about 2/3 of the time is spent in read_bunzip() reversing
Eric Andersen5fa4db22003-10-23 06:52:01 +000020 the Burrows-Wheeler transformation. Much of that time is delay
21 resulting from cache misses.
22
Denys Vlasenko5d49b722010-10-29 19:26:38 +020023 (2010 update by vda: profiled "bzcat <84mbyte.bz2 >/dev/null"
24 on x86-64 CPU with L2 > 1M: get_next_block is hotter than read_bunzip:
25 %time seconds calls function
26 71.01 12.69 444 get_next_block
27 28.65 5.12 93065 read_bunzip
28 00.22 0.04 7736490 get_bits
29 00.11 0.02 47 dealloc_bunzip
30 00.00 0.00 93018 full_write
31 ...)
32
33
Eric Andersen5fa4db22003-10-23 06:52:01 +000034 I would ask that anyone benefiting from this work, especially those
35 using it in commercial products, consider making a donation to my local
Rob Landleyf856eab2006-02-17 03:43:49 +000036 non-profit hospice organization (www.hospiceacadiana.com) in the name of
Bernhard Reutner-Fischercfb53df2006-04-02 21:50:01 +000037 the woman I loved, Toni W. Hagan, who passed away Feb. 12, 2003.
Eric Andersen5fa4db22003-10-23 06:52:01 +000038
39 Manuel
40 */
41
Glenn L McGrath1c834402003-10-28 23:32:12 +000042#include "libbb.h"
Bernhard Reutner-Fischercfb53df2006-04-02 21:50:01 +000043#include "unarchive.h"
44
Eric Andersenaff114c2004-04-14 17:51:38 +000045/* Constants for Huffman coding */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000046#define MAX_GROUPS 6
47#define GROUP_SIZE 50 /* 64 would have been more efficient */
48#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
49#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
50#define SYMBOL_RUNA 0
51#define SYMBOL_RUNB 1
Glenn L McGrath60bce492002-11-03 07:28:38 +000052
Eric Andersen0d6d88a2003-10-18 01:58:35 +000053/* Status return values */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000054#define RETVAL_OK 0
55#define RETVAL_LAST_BLOCK (-1)
56#define RETVAL_NOT_BZIP_DATA (-2)
57#define RETVAL_UNEXPECTED_INPUT_EOF (-3)
Denys Vlasenkocaddfc82010-10-28 23:08:53 +020058//#define RETVAL_SHORT_WRITE (-4)
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000059#define RETVAL_DATA_ERROR (-5)
60#define RETVAL_OUT_OF_MEMORY (-6)
61#define RETVAL_OBSOLETE_INPUT (-7)
Glenn L McGrath60bce492002-11-03 07:28:38 +000062
Eric Andersen0d6d88a2003-10-18 01:58:35 +000063/* Other housekeeping constants */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000064#define IOBUF_SIZE 4096
Glenn L McGrath60bce492002-11-03 07:28:38 +000065
Eric Andersenaff114c2004-04-14 17:51:38 +000066/* This is what we know about each Huffman coding group */
Eric Andersen0d6d88a2003-10-18 01:58:35 +000067struct group_data {
Denis Vlasenko52a43882007-10-10 20:53:41 +000068 /* We have an extra slot at the end of limit[] for a sentinel value. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +000069 int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
Eric Andersen5fa4db22003-10-23 06:52:01 +000070 int minLen, maxLen;
Glenn L McGrath60bce492002-11-03 07:28:38 +000071};
72
Eric Andersen0d6d88a2003-10-18 01:58:35 +000073/* Structure holding all the housekeeping data, including IO buffers and
Denis Vlasenko52a43882007-10-10 20:53:41 +000074 * memory that persists between calls to bunzip
75 * Found the most used member:
76 * cat this_file.c | sed -e 's/"/ /g' -e "s/'/ /g" | xargs -n1 \
77 * | grep 'bd->' | sed 's/^.*bd->/bd->/' | sort | $PAGER
78 * and moved it (inbufBitCount) to offset 0.
79 */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000080struct bunzip_data {
Eric Andersen5fa4db22003-10-23 06:52:01 +000081 /* I/O tracking data (file handles, buffers, positions, etc.) */
Denis Vlasenko52a43882007-10-10 20:53:41 +000082 unsigned inbufBitCount, inbufBits;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +000083 int in_fd, out_fd, inbufCount, inbufPos /*, outbufPos*/;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020084 uint8_t *inbuf /*,*outbuf*/;
Denis Vlasenko52a43882007-10-10 20:53:41 +000085
86 /* State for interrupting output loop */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020087 int writeCopies, writePos, writeRunCountdown, writeCount;
88 int writeCurrent; /* actually a uint8_t */
Rob Landleyf856eab2006-02-17 03:43:49 +000089
Eric Andersen0d6d88a2003-10-18 01:58:35 +000090 /* The CRC values stored in the block header and calculated from the data */
Rob Landleyc57ec372006-04-10 17:07:15 +000091 uint32_t headerCRC, totalCRC, writeCRC;
Rob Landleyf856eab2006-02-17 03:43:49 +000092
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000093 /* Intermediate buffer and its size (in bytes) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020094 uint32_t *dbuf;
95 unsigned dbufSize;
Rob Landleyf856eab2006-02-17 03:43:49 +000096
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000097 /* For I/O error handling */
98 jmp_buf jmpbuf;
Rob Landleyf856eab2006-02-17 03:43:49 +000099
Denis Vlasenko52a43882007-10-10 20:53:41 +0000100 /* Big things go last (register-relative addressing can be larger for big offsets) */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000101 uint32_t crc32Table[256];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200102 uint8_t selectors[32768]; /* nSelectors=15 bits */
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200103 struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000104};
105/* typedef struct bunzip_data bunzip_data; -- done in .h file */
Rob Landleyf856eab2006-02-17 03:43:49 +0000106
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000107
108/* Return the next nnn bits of input. All reads from the compressed input
109 are done through this function. All reads are big endian */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000110static unsigned get_bits(bunzip_data *bd, int bits_wanted)
Glenn L McGrath60bce492002-11-03 07:28:38 +0000111{
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000112 unsigned bits = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200113 /* Cache bd->inbufBitCount in a CPU register (hopefully): */
114 int bit_count = bd->inbufBitCount;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000115
116 /* If we need to get more data from the byte buffer, do so. (Loop getting
117 one byte at a time to enforce endianness and avoid unaligned access.) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200118 while (bit_count < bits_wanted) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000119
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000120 /* If we need to read more data from file into byte buffer, do so */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000121 if (bd->inbufPos == bd->inbufCount) {
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000122 /* if "no input fd" case: in_fd == -1, read fails, we jump */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000123 bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);
124 if (bd->inbufCount <= 0)
125 longjmp(bd->jmpbuf, RETVAL_UNEXPECTED_INPUT_EOF);
126 bd->inbufPos = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000127 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000128
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000129 /* Avoid 32-bit overflow (dump bit buffer to top of output) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200130 if (bit_count >= 24) {
131 bits = bd->inbufBits & ((1 << bit_count) - 1);
132 bits_wanted -= bit_count;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000133 bits <<= bits_wanted;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200134 bit_count = 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000135 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000136
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000137 /* Grab next 8 bits of input from buffer. */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000138 bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200139 bit_count += 8;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000140 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000141
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000142 /* Calculate result */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200143 bit_count -= bits_wanted;
144 bd->inbufBitCount = bit_count;
145 bits |= (bd->inbufBits >> bit_count) & ((1 << bits_wanted) - 1);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000146
147 return bits;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000148}
149
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200150/* Unpacks the next block and sets up for the inverse Burrows-Wheeler step. */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000151static int get_next_block(bunzip_data *bd)
Glenn L McGrath60bce492002-11-03 07:28:38 +0000152{
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000153 struct group_data *hufGroup;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000154 int dbufCount, nextSym, dbufSize, groupCount, *base, *limit, selector,
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000155 i, j, k, t, runPos, symCount, symTotal, nSelectors, byteCount[256];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200156 uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
157 uint32_t *dbuf;
158 unsigned origPtr;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000159
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000160 dbuf = bd->dbuf;
161 dbufSize = bd->dbufSize;
162 selectors = bd->selectors;
Rob Landley2c98c402006-02-17 05:12:03 +0000163
Eric Andersen5fa4db22003-10-23 06:52:01 +0000164 /* Reset longjmp I/O error handling */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000165 i = setjmp(bd->jmpbuf);
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000166 if (i) return i;
Rob Landley2c98c402006-02-17 05:12:03 +0000167
Eric Andersen5fa4db22003-10-23 06:52:01 +0000168 /* Read in header signature and CRC, then validate signature.
169 (last block signature means CRC is for whole file, return now) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000170 i = get_bits(bd, 24);
171 j = get_bits(bd, 24);
172 bd->headerCRC = get_bits(bd, 32);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000173 if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
174 if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
Rob Landley2c98c402006-02-17 05:12:03 +0000175
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000176 /* We can add support for blockRandomised if anybody complains. There was
177 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
178 it didn't actually work. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000179 if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
180 origPtr = get_bits(bd, 24);
Denis Vlasenko6b06cb82008-05-15 21:30:45 +0000181 if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000182
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000183 /* mapping table: if some byte values are never used (encoding things
184 like ascii text), the compression code removes the gaps to have fewer
185 symbols to deal with, and writes a sparse bitfield indicating which
186 values were present. We make a translation table to convert the symbols
187 back to the corresponding bytes. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000188 t = get_bits(bd, 16);
189 symTotal = 0;
190 for (i = 0; i < 16; i++) {
191 if (t & (1 << (15-i))) {
192 k = get_bits(bd, 16);
193 for (j = 0; j < 16; j++)
194 if (k & (1 << (15-j)))
195 symToByte[symTotal++] = (16*i) + j;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000196 }
197 }
Rob Landley2c98c402006-02-17 05:12:03 +0000198
Eric Andersenaff114c2004-04-14 17:51:38 +0000199 /* How many different Huffman coding groups does this block use? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000200 groupCount = get_bits(bd, 3);
201 if (groupCount < 2 || groupCount > MAX_GROUPS)
202 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000203
Eric Andersenaff114c2004-04-14 17:51:38 +0000204 /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000205 group. Read in the group selector list, which is stored as MTF encoded
Eric Andersen5fa4db22003-10-23 06:52:01 +0000206 bit runs. (MTF=Move To Front, as each value is used it's moved to the
207 start of the list.) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000208 nSelectors = get_bits(bd, 15);
209 if (!nSelectors) return RETVAL_DATA_ERROR;
210 for (i = 0; i < groupCount; i++) mtfSymbol[i] = i;
211 for (i = 0; i < nSelectors; i++) {
Rob Landley2c98c402006-02-17 05:12:03 +0000212
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000213 /* Get next value */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000214 for (j = 0; get_bits(bd, 1); j++)
Denis Vlasenko52a43882007-10-10 20:53:41 +0000215 if (j >= groupCount) return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000216
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000217 /* Decode MTF to get the next selector */
218 uc = mtfSymbol[j];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200219 for (; j; j--)
220 mtfSymbol[j] = mtfSymbol[j-1];
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000221 mtfSymbol[0] = selectors[i] = uc;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000222 }
Rob Landley2c98c402006-02-17 05:12:03 +0000223
Eric Andersenaff114c2004-04-14 17:51:38 +0000224 /* Read the Huffman coding tables for each group, which code for symTotal
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000225 literal symbols, plus two run symbols (RUNA, RUNB) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000226 symCount = symTotal + 2;
227 for (j = 0; j < groupCount; j++) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200228 uint8_t length[MAX_SYMBOLS];
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000229 /* 8 bits is ALMOST enough for temp[], see below */
230 unsigned temp[MAX_HUFCODE_BITS+1];
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000231 int minLen, maxLen, pp;
Rob Landley2c98c402006-02-17 05:12:03 +0000232
Eric Andersenaff114c2004-04-14 17:51:38 +0000233 /* Read Huffman code lengths for each symbol. They're stored in
Eric Andersen5fa4db22003-10-23 06:52:01 +0000234 a way similar to mtf; record a starting value for the first symbol,
235 and an offset from the previous value for everys symbol after that.
236 (Subtracting 1 before the loop and then adding it back at the end is
237 an optimization that makes the test inside the loop simpler: symbol
238 length 0 becomes negative, so an unsigned inequality catches it.) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000239 t = get_bits(bd, 5) - 1;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000240 for (i = 0; i < symCount; i++) {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000241 for (;;) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000242 if ((unsigned)t > (MAX_HUFCODE_BITS-1))
Eric Andersen5fa4db22003-10-23 06:52:01 +0000243 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000244
Eric Andersen5fa4db22003-10-23 06:52:01 +0000245 /* If first bit is 0, stop. Else second bit indicates whether
246 to increment or decrement the value. Optimization: grab 2
247 bits and unget the second if the first was 0. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000248 k = get_bits(bd, 2);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000249 if (k < 2) {
250 bd->inbufBitCount++;
251 break;
252 }
Rob Landley2c98c402006-02-17 05:12:03 +0000253
Eric Andersen5fa4db22003-10-23 06:52:01 +0000254 /* Add one if second bit 1, else subtract 1. Avoids if/else */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000255 t += (((k+1) & 2) - 1);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000256 }
Rob Landley2c98c402006-02-17 05:12:03 +0000257
Eric Andersen5fa4db22003-10-23 06:52:01 +0000258 /* Correct for the initial -1, to get the final symbol length */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000259 length[i] = t + 1;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000260 }
Rob Landley2c98c402006-02-17 05:12:03 +0000261
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000262 /* Find largest and smallest lengths in this group */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000263 minLen = maxLen = length[0];
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000264 for (i = 1; i < symCount; i++) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000265 if (length[i] > maxLen) maxLen = length[i];
266 else if (length[i] < minLen) minLen = length[i];
Glenn L McGrath60bce492002-11-03 07:28:38 +0000267 }
Rob Landley2c98c402006-02-17 05:12:03 +0000268
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000269 /* Calculate permute[], base[], and limit[] tables from length[].
270 *
Eric Andersenaff114c2004-04-14 17:51:38 +0000271 * permute[] is the lookup table for converting Huffman coded symbols
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000272 * into decoded symbols. base[] is the amount to subtract from the
Eric Andersenaff114c2004-04-14 17:51:38 +0000273 * value of a Huffman symbol of a given length when using permute[].
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000274 *
275 * limit[] indicates the largest numerical value a symbol with a given
Eric Andersenaff114c2004-04-14 17:51:38 +0000276 * number of bits can have. This is how the Huffman codes can vary in
Eric Andersen5fa4db22003-10-23 06:52:01 +0000277 * length: each code with a value>limit[length] needs another bit.
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000278 */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000279 hufGroup = bd->groups + j;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000280 hufGroup->minLen = minLen;
281 hufGroup->maxLen = maxLen;
Rob Landley2c98c402006-02-17 05:12:03 +0000282
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000283 /* Note that minLen can't be smaller than 1, so we adjust the base
284 and limit array pointers so we're not always wasting the first
285 entry. We do this again when using them (during symbol decoding).*/
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000286 base = hufGroup->base - 1;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000287 limit = hufGroup->limit - 1;
Rob Landley2c98c402006-02-17 05:12:03 +0000288
Eric Andersen5fa4db22003-10-23 06:52:01 +0000289 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000290 pp = 0;
291 for (i = minLen; i <= maxLen; i++) {
292 temp[i] = limit[i] = 0;
293 for (t = 0; t < symCount; t++)
294 if (length[t] == i)
295 hufGroup->permute[pp++] = t;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000296 }
Rob Landley2c98c402006-02-17 05:12:03 +0000297
Eric Andersen5fa4db22003-10-23 06:52:01 +0000298 /* Count symbols coded for at each bit length */
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000299 /* NB: in pathological cases, temp[8] can end ip being 256.
300 * That's why uint8_t is too small for temp[]. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000301 for (i = 0; i < symCount; i++) temp[length[i]]++;
Rob Landley2c98c402006-02-17 05:12:03 +0000302
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000303 /* Calculate limit[] (the largest symbol-coding value at each bit
304 * length, which is (previous limit<<1)+symbols at this level), and
305 * base[] (number of symbols to ignore at each bit length, which is
Eric Andersen5fa4db22003-10-23 06:52:01 +0000306 * limit minus the cumulative count of symbols coded for already). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000307 pp = t = 0;
308 for (i = minLen; i < maxLen; i++) {
309 pp += temp[i];
Rob Landley2c98c402006-02-17 05:12:03 +0000310
Eric Andersen5fa4db22003-10-23 06:52:01 +0000311 /* We read the largest possible symbol size and then unget bits
312 after determining how many we need, and those extra bits could
313 be set to anything. (They're noise from future symbols.) At
314 each level we're really only interested in the first few bits,
315 so here we set all the trailing to-be-ignored bits to 1 so they
316 don't affect the value>limit[length] comparison. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000317 limit[i] = (pp << (maxLen - i)) - 1;
318 pp <<= 1;
319 t += temp[i];
320 base[i+1] = pp - t;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000321 }
Denis Vlasenko52a43882007-10-10 20:53:41 +0000322 limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000323 limit[maxLen] = pp + temp[maxLen] - 1;
324 base[minLen] = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000325 }
Rob Landley2c98c402006-02-17 05:12:03 +0000326
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000327 /* We've finished reading and digesting the block header. Now read this
Eric Andersenaff114c2004-04-14 17:51:38 +0000328 block's Huffman coded symbols from the file and undo the Huffman coding
Denis Vlasenko52a43882007-10-10 20:53:41 +0000329 and run length encoding, saving the result into dbuf[dbufCount++] = uc */
Glenn L McGrath60bce492002-11-03 07:28:38 +0000330
Eric Andersen5fa4db22003-10-23 06:52:01 +0000331 /* Initialize symbol occurrence counters and symbol Move To Front table */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000332 memset(byteCount, 0, sizeof(byteCount)); /* smaller, maybe slower? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000333 for (i = 0; i < 256; i++) {
Denis Vlasenko52a43882007-10-10 20:53:41 +0000334 //byteCount[i] = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200335 mtfSymbol[i] = (uint8_t)i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000336 }
Rob Landley2c98c402006-02-17 05:12:03 +0000337
Eric Andersen5fa4db22003-10-23 06:52:01 +0000338 /* Loop through compressed symbols. */
Rob Landley2c98c402006-02-17 05:12:03 +0000339
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000340 runPos = dbufCount = selector = 0;
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000341 for (;;) {
Rob Landley2c98c402006-02-17 05:12:03 +0000342
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000343 /* Fetch next Huffman coding group from list. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000344 symCount = GROUP_SIZE - 1;
345 if (selector >= nSelectors) return RETVAL_DATA_ERROR;
346 hufGroup = bd->groups + selectors[selector++];
347 base = hufGroup->base - 1;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000348 limit = hufGroup->limit - 1;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000349 continue_this_group:
Rob Landley2c98c402006-02-17 05:12:03 +0000350
Eric Andersenaff114c2004-04-14 17:51:38 +0000351 /* Read next Huffman-coded symbol. */
Rob Landley2c98c402006-02-17 05:12:03 +0000352
Eric Andersen5fa4db22003-10-23 06:52:01 +0000353 /* Note: It is far cheaper to read maxLen bits and back up than it is
354 to read minLen bits and then an additional bit at a time, testing
355 as we go. Because there is a trailing last block (with file CRC),
356 there is no danger of the overread causing an unexpected EOF for a
357 valid compressed file. As a further optimization, we do the read
358 inline (falling back to a call to get_bits if the buffer runs
359 dry). The following (up to got_huff_bits:) is equivalent to
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000360 j = get_bits(bd, hufGroup->maxLen);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000361 */
Denis Vlasenko6b06cb82008-05-15 21:30:45 +0000362 while ((int)(bd->inbufBitCount) < hufGroup->maxLen) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000363 if (bd->inbufPos == bd->inbufCount) {
364 j = get_bits(bd, hufGroup->maxLen);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000365 goto got_huff_bits;
366 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000367 bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
368 bd->inbufBitCount += 8;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000369 };
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000370 bd->inbufBitCount -= hufGroup->maxLen;
371 j = (bd->inbufBits >> bd->inbufBitCount) & ((1 << hufGroup->maxLen) - 1);
Rob Landley2c98c402006-02-17 05:12:03 +0000372
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000373 got_huff_bits:
Rob Landley2c98c402006-02-17 05:12:03 +0000374
Eric Andersen5fa4db22003-10-23 06:52:01 +0000375 /* Figure how how many bits are in next symbol and unget extras */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000376 i = hufGroup->minLen;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000377 while (j > limit[i]) ++i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000378 bd->inbufBitCount += (hufGroup->maxLen - i);
Rob Landley2c98c402006-02-17 05:12:03 +0000379
Eric Andersen5fa4db22003-10-23 06:52:01 +0000380 /* Huffman decode value to get nextSym (with bounds checking) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000381 if (i > hufGroup->maxLen)
382 return RETVAL_DATA_ERROR;
383 j = (j >> (hufGroup->maxLen - i)) - base[i];
384 if ((unsigned)j >= MAX_SYMBOLS)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000385 return RETVAL_DATA_ERROR;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000386 nextSym = hufGroup->permute[j];
Rob Landley2c98c402006-02-17 05:12:03 +0000387
Eric Andersen5fa4db22003-10-23 06:52:01 +0000388 /* We have now decoded the symbol, which indicates either a new literal
389 byte, or a repeated run of the most recent literal byte. First,
390 check if nextSym indicates a repeated run, and if so loop collecting
391 how many times to repeat the last literal. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000392 if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
Rob Landley2c98c402006-02-17 05:12:03 +0000393
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000394 /* If this is the start of a new run, zero out counter */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000395 if (!runPos) {
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000396 runPos = 1;
397 t = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000398 }
Rob Landley2c98c402006-02-17 05:12:03 +0000399
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000400 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
401 each bit position, add 1 or 2 instead. For example,
402 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
403 You can make any bit pattern that way using 1 less symbol than
404 the basic or 0/1 method (except all bits 0, which would use no
405 symbols, but a run of length 0 doesn't mean anything in this
406 context). Thus space is saved. */
Eric Andersen1acfb722003-10-18 01:59:46 +0000407 t += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000408 if (runPos < dbufSize) runPos <<= 1;
Rob Landleya8b98d62004-11-16 12:07:04 +0000409 goto end_of_huffman_loop;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000410 }
Rob Landley2c98c402006-02-17 05:12:03 +0000411
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000412 /* When we hit the first non-run symbol after a run, we now know
413 how many times to repeat the last literal, so append that many
414 copies to our buffer of decoded symbols (dbuf) now. (The last
415 literal used is the one at the head of the mtfSymbol array.) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000416 if (runPos) {
417 runPos = 0;
418 if (dbufCount + t >= dbufSize) return RETVAL_DATA_ERROR;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000419
420 uc = symToByte[mtfSymbol[0]];
421 byteCount[uc] += t;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000422 while (t--) dbuf[dbufCount++] = uc;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000423 }
Rob Landley2c98c402006-02-17 05:12:03 +0000424
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000425 /* Is this the terminating symbol? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000426 if (nextSym > symTotal) break;
Rob Landley2c98c402006-02-17 05:12:03 +0000427
Eric Andersen5fa4db22003-10-23 06:52:01 +0000428 /* At this point, nextSym indicates a new literal character. Subtract
429 one to get the position in the MTF array at which this literal is
430 currently to be found. (Note that the result can't be -1 or 0,
431 because 0 and 1 are RUNA and RUNB. But another instance of the
432 first symbol in the mtf array, position 0, would have been handled
433 as part of a run above. Therefore 1 unused mtf position minus
434 2 non-literal nextSym values equals -1.) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000435 if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000436 i = nextSym - 1;
437 uc = mtfSymbol[i];
Rob Landley2c98c402006-02-17 05:12:03 +0000438
Eric Andersen5fa4db22003-10-23 06:52:01 +0000439 /* Adjust the MTF array. Since we typically expect to move only a
440 * small number of symbols, and are bound by 256 in any case, using
441 * memmove here would typically be bigger and slower due to function
442 * call overhead and other assorted setup costs. */
Eric Andersen1acfb722003-10-18 01:59:46 +0000443 do {
444 mtfSymbol[i] = mtfSymbol[i-1];
445 } while (--i);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000446 mtfSymbol[0] = uc;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000447 uc = symToByte[uc];
Rob Landley2c98c402006-02-17 05:12:03 +0000448
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000449 /* We have our literal byte. Save it into dbuf. */
450 byteCount[uc]++;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000451 dbuf[dbufCount++] = (unsigned)uc;
Rob Landley2c98c402006-02-17 05:12:03 +0000452
Rob Landleyf856eab2006-02-17 03:43:49 +0000453 /* Skip group initialization if we're not done with this group. Done
454 * this way to avoid compiler warning. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000455 end_of_huffman_loop:
456 if (symCount--) goto continue_this_group;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000457 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000458
Eric Andersenaff114c2004-04-14 17:51:38 +0000459 /* At this point, we've read all the Huffman-coded symbols (and repeated
Denis Vlasenko246b5c32007-04-10 17:18:12 +0000460 runs) for this block from the input stream, and decoded them into the
Eric Andersen5fa4db22003-10-23 06:52:01 +0000461 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
462 Now undo the Burrows-Wheeler transform on dbuf.
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000463 See http://dogma.net/markn/articles/bwt/bwt.htm
464 */
Rob Landley2c98c402006-02-17 05:12:03 +0000465
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000466 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000467 j = 0;
468 for (i = 0; i < 256; i++) {
469 k = j + byteCount[i];
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000470 byteCount[i] = j;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000471 j = k;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000472 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000473
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000474 /* Figure out what order dbuf would be in if we sorted it. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000475 for (i = 0; i < dbufCount; i++) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200476 uc = (uint8_t)dbuf[i];
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000477 dbuf[byteCount[uc]] |= (i << 8);
478 byteCount[uc]++;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000479 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000480
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000481 /* Decode first byte by hand to initialize "previous" byte. Note that it
482 doesn't get output, and if the first three characters are identical
Eric Andersen5fa4db22003-10-23 06:52:01 +0000483 it doesn't qualify as a run (hence writeRunCountdown=5). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000484 if (dbufCount) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200485 uint32_t tmp;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +0000486 if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200487 tmp = dbuf[origPtr];
488 bd->writeCurrent = (uint8_t)tmp;
489 bd->writePos = (tmp >> 8);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000490 bd->writeRunCountdown = 5;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000491 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000492 bd->writeCount = dbufCount;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000493
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000494 return RETVAL_OK;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000495}
496
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200497/* Undo Burrows-Wheeler transform on intermediate buffer to produce output.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000498 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
499 data are written to outbuf. Return value is number of bytes written or
500 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
501 are ignored, data is written to out_fd and return is RETVAL_OK or error.
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200502
503 NB: read_bunzip returns < 0 on error, or the number of *unfilled* bytes
504 in outbuf. IOW: on EOF returns len ("all bytes are not filled"), not 0.
505 (Why? This allows to get rid of one local variable)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000506*/
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000507int FAST_FUNC read_bunzip(bunzip_data *bd, char *outbuf, int len)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000508{
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200509 const uint32_t *dbuf;
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200510 int pos, current, previous;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200511 uint32_t CRC;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000512
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200513 /* If we already have error/end indicator, return it */
514 if (bd->writeCount < 0)
515 return bd->writeCount;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000516
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000517 dbuf = bd->dbuf;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200518
519 /* Register-cached state (hopefully): */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000520 pos = bd->writePos;
521 current = bd->writeCurrent;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200522 CRC = bd->writeCRC; /* small loss on x86-32 (not enough regs), win on x86-64 */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000523
524 /* We will always have pending decoded data to write into the output
525 buffer unless this is the very first call (in which case we haven't
Eric Andersenaff114c2004-04-14 17:51:38 +0000526 Huffman-decoded a block into the intermediate buffer yet). */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000527 if (bd->writeCopies) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000528
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200529 dec_writeCopies:
Eric Andersen5fa4db22003-10-23 06:52:01 +0000530 /* Inside the loop, writeCopies means extra copies (beyond 1) */
531 --bd->writeCopies;
Rob Landleyf856eab2006-02-17 03:43:49 +0000532
Eric Andersen5fa4db22003-10-23 06:52:01 +0000533 /* Loop outputting bytes */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000534 for (;;) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000535
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200536 /* If the output buffer is full, save cached state and return */
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200537 if (--len < 0) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200538 /* Unlikely branch.
539 * Use of "goto" instead of keeping code here
540 * helps compiler to realize this. */
541 goto outbuf_full;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000542 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000543
Eric Andersen5fa4db22003-10-23 06:52:01 +0000544 /* Write next byte into output buffer, updating CRC */
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200545 *outbuf++ = current;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200546 CRC = (CRC << 8) ^ bd->crc32Table[(CRC >> 24) ^ current];
Rob Landleyf856eab2006-02-17 03:43:49 +0000547
Eric Andersen5fa4db22003-10-23 06:52:01 +0000548 /* Loop now if we're outputting multiple copies of this byte */
549 if (bd->writeCopies) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200550 /* Unlikely branch */
551 /*--bd->writeCopies;*/
552 /*continue;*/
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200553 /* Same, but (ab)using other existing --writeCopies operation
554 * (and this if() compiles into just test+branch pair): */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200555 goto dec_writeCopies;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000556 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000557 decode_next_byte:
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200558 if (--bd->writeCount < 0)
559 break; /* input block is fully consumed, need next one */
560
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000561 /* Follow sequence vector to undo Burrows-Wheeler transform */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000562 previous = current;
563 pos = dbuf[pos];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200564 current = (uint8_t)pos;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000565 pos >>= 8;
Rob Landleyf856eab2006-02-17 03:43:49 +0000566
Denis Vlasenko52a43882007-10-10 20:53:41 +0000567 /* After 3 consecutive copies of the same byte, the 4th
568 * is a repeat count. We count down from 4 instead
Eric Andersen5fa4db22003-10-23 06:52:01 +0000569 * of counting up because testing for non-zero is faster */
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200570 if (--bd->writeRunCountdown != 0) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000571 if (current != previous)
572 bd->writeRunCountdown = 4;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000573 } else {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200574 /* Unlikely branch */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000575 /* We have a repeated run, this byte indicates the count */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000576 bd->writeCopies = current;
577 current = previous;
578 bd->writeRunCountdown = 5;
Rob Landleyf856eab2006-02-17 03:43:49 +0000579
Eric Andersen5fa4db22003-10-23 06:52:01 +0000580 /* Sometimes there are just 3 bytes (run length 0) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000581 if (!bd->writeCopies) goto decode_next_byte;
Rob Landleyf856eab2006-02-17 03:43:49 +0000582
Eric Andersen5fa4db22003-10-23 06:52:01 +0000583 /* Subtract the 1 copy we'd output anyway to get extras */
584 --bd->writeCopies;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000585 }
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200586 } /* for(;;) */
Rob Landleyf856eab2006-02-17 03:43:49 +0000587
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200588 /* Decompression of this input block completed successfully */
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200589 bd->writeCRC = CRC = ~CRC;
590 bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ CRC;
Rob Landleyf856eab2006-02-17 03:43:49 +0000591
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200592 /* If this block had a CRC error, force file level CRC error */
593 if (CRC != bd->headerCRC) {
Denis Vlasenko52a43882007-10-10 20:53:41 +0000594 bd->totalCRC = bd->headerCRC + 1;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000595 return RETVAL_LAST_BLOCK;
596 }
Glenn L McGrath60bce492002-11-03 07:28:38 +0000597 }
Eric Andersen5fa4db22003-10-23 06:52:01 +0000598
Eric Andersenaff114c2004-04-14 17:51:38 +0000599 /* Refill the intermediate buffer by Huffman-decoding next block of input */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200600 {
601 int r = get_next_block(bd);
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200602 if (r) { /* error/end */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200603 bd->writeCount = r;
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200604 return (r != RETVAL_LAST_BLOCK) ? r : len;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200605 }
Eric Andersen5fa4db22003-10-23 06:52:01 +0000606 }
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200607
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200608 CRC = ~0;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000609 pos = bd->writePos;
610 current = bd->writeCurrent;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000611 goto decode_next_byte;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200612
613 outbuf_full:
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200614 /* Output buffer is full, save cached state and return */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200615 bd->writePos = pos;
616 bd->writeCurrent = current;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200617 bd->writeCRC = CRC;
618
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200619 bd->writeCopies++;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200620
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200621 return 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000622}
623
Eric Andersen5fa4db22003-10-23 06:52:01 +0000624/* Allocate the structure, read file header. If in_fd==-1, inbuf must contain
625 a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are
626 ignored, and data is read from file handle into temporary buffer. */
Rob Landleyf856eab2006-02-17 03:43:49 +0000627
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000628/* Because bunzip2 is used for help text unpacking, and because bb_show_usage()
629 should work for NOFORK applets too, we must be extremely careful to not leak
630 any allocations! */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200631int FAST_FUNC start_bunzip(bunzip_data **bdp, int in_fd,
632 const void *inbuf, int len)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000633{
634 bunzip_data *bd;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000635 unsigned i;
636 enum {
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000637 BZh0 = ('B' << 24) + ('Z' << 16) + ('h' << 8) + '0',
638 h0 = ('h' << 8) + '0',
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000639 };
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000640
641 /* Figure out how much data to allocate */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000642 i = sizeof(bunzip_data);
643 if (in_fd != -1) i += IOBUF_SIZE;
Rob Landleyf856eab2006-02-17 03:43:49 +0000644
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000645 /* Allocate bunzip_data. Most fields initialize to zero. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000646 bd = *bdp = xzalloc(i);
Rob Landleyf856eab2006-02-17 03:43:49 +0000647
Eric Andersen5fa4db22003-10-23 06:52:01 +0000648 /* Setup input buffer */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000649 bd->in_fd = in_fd;
650 if (-1 == in_fd) {
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000651 /* in this case, bd->inbuf is read-only */
652 bd->inbuf = (void*)inbuf; /* cast away const-ness */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200653 } else {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200654 bd->inbuf = (uint8_t*)(bd + 1);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200655 memcpy(bd->inbuf, inbuf, len);
656 }
657 bd->inbufCount = len;
Rob Landleyf856eab2006-02-17 03:43:49 +0000658
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000659 /* Init the CRC32 table (big endian) */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000660 crc32_filltable(bd->crc32Table, 1);
Rob Landleyf856eab2006-02-17 03:43:49 +0000661
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000662 /* Setup for I/O error handling via longjmp */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000663 i = setjmp(bd->jmpbuf);
664 if (i) return i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000665
666 /* Ensure that file starts with "BZh['1'-'9']." */
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000667 /* Update: now caller verifies 1st two bytes, makes .gz/.bz2
668 * integration easier */
669 /* was: */
670 /* i = get_bits(bd, 32); */
671 /* if ((unsigned)(i - BZh0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA; */
672 i = get_bits(bd, 16);
673 if ((unsigned)(i - h0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000674
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000675 /* Fourth byte (ascii '1'-'9') indicates block size in units of 100k of
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000676 uncompressed data. Allocate intermediate buffer for block. */
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000677 /* bd->dbufSize = 100000 * (i - BZh0); */
678 bd->dbufSize = 100000 * (i - h0);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000679
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000680 /* Cannot use xmalloc - may leak bd in NOFORK case! */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200681 bd->dbuf = malloc_or_warn(bd->dbufSize * sizeof(bd->dbuf[0]));
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000682 if (!bd->dbuf) {
683 free(bd);
684 xfunc_die();
685 }
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000686 return RETVAL_OK;
687}
688
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000689void FAST_FUNC dealloc_bunzip(bunzip_data *bd)
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000690{
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000691 free(bd->dbuf);
692 free(bd);
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000693}
694
695
696/* Decompress src_fd to dst_fd. Stops at end of bzip data, not end of file. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000697IF_DESKTOP(long long) int FAST_FUNC
Denis Vlasenkoc14d39e2007-06-08 13:05:39 +0000698unpack_bz2_stream(int src_fd, int dst_fd)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000699{
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000700 IF_DESKTOP(long long total_written = 0;)
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200701 bunzip_data *bd;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000702 char *outbuf;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000703 int i;
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200704 unsigned len;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000705
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000706 outbuf = xmalloc(IOBUF_SIZE);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200707 len = 0;
708 while (1) { /* "Process one BZ... stream" loop */
709
710 i = start_bunzip(&bd, src_fd, outbuf + 2, len);
711
712 if (i == 0) {
713 while (1) { /* "Produce some output bytes" loop */
714 i = read_bunzip(bd, outbuf, IOBUF_SIZE);
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200715 if (i < 0) /* error? */
716 break;
717 i = IOBUF_SIZE - i; /* number of bytes produced */
718 if (i == 0) /* EOF? */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200719 break;
720 if (i != full_write(dst_fd, outbuf, i)) {
721 bb_error_msg("short write");
722 goto release_mem;
723 }
724 IF_DESKTOP(total_written += i;)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000725 }
726 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000727
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200728 if (i != RETVAL_LAST_BLOCK) {
729 bb_error_msg("bunzip error %d", i);
730 break;
731 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000732 if (bd->headerCRC != bd->totalCRC) {
Denis Vlasenko66bbfbd2007-09-28 23:45:56 +0000733 bb_error_msg("CRC error");
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200734 break;
Glenn L McGrath1c834402003-10-28 23:32:12 +0000735 }
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200736
737 /* Successfully unpacked one BZ stream */
738 i = RETVAL_OK;
739
740 /* Do we have "BZ..." after last processed byte?
741 * pbzip2 (parallelized bzip2) produces such files.
742 */
743 len = bd->inbufCount - bd->inbufPos;
744 memcpy(outbuf, &bd->inbuf[bd->inbufPos], len);
745 if (len < 2) {
746 if (safe_read(src_fd, outbuf + len, 2 - len) != 2 - len)
747 break;
748 len = 2;
749 }
750 if (*(uint16_t*)outbuf != BZIP2_MAGIC) /* "BZ"? */
751 break;
752 dealloc_bunzip(bd);
753 len -= 2;
Glenn L McGrath1c834402003-10-28 23:32:12 +0000754 }
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200755
756 release_mem:
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000757 dealloc_bunzip(bd);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000758 free(outbuf);
Glenn L McGrath1c834402003-10-28 23:32:12 +0000759
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000760 return i ? i : IF_DESKTOP(total_written) + 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000761}
762
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000763IF_DESKTOP(long long) int FAST_FUNC
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000764unpack_bz2_stream_prime(int src_fd, int dst_fd)
765{
Denys Vlasenko620e8632010-06-30 19:43:44 +0200766 uint16_t magic2;
767 xread(src_fd, &magic2, 2);
768 if (magic2 != BZIP2_MAGIC) {
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000769 bb_error_msg_and_die("invalid magic");
770 }
771 return unpack_bz2_stream(src_fd, dst_fd);
772}
773
Eric Andersen5fa4db22003-10-23 06:52:01 +0000774#ifdef TESTING
Glenn L McGrath60bce492002-11-03 07:28:38 +0000775
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000776static char *const bunzip_errors[] = {
777 NULL, "Bad file checksum", "Not bzip data",
778 "Unexpected input EOF", "Unexpected output EOF", "Data error",
779 "Out of memory", "Obsolete (pre 0.9.5) bzip format not supported"
780};
Glenn L McGrath237ae422002-11-03 14:05:15 +0000781
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000782/* Dumb little test thing, decompress stdin to stdout */
Bernhard Reutner-Fischerfebe3c42007-04-04 20:52:03 +0000783int main(int argc, char **argv)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000784{
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000785 int i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000786 char c;
787
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000788 int i = unpack_bz2_stream_prime(0, 1);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000789 if (i < 0)
Denis Vlasenkof5d8c902008-06-26 14:32:57 +0000790 fprintf(stderr, "%s\n", bunzip_errors[-i]);
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000791 else if (read(STDIN_FILENO, &c, 1))
Denis Vlasenkof5d8c902008-06-26 14:32:57 +0000792 fprintf(stderr, "Trailing garbage ignored\n");
Eric Andersen5fa4db22003-10-23 06:52:01 +0000793 return -i;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000794}
795#endif