blob: 0e3ab436440d89aa01239bde3701f641605812ff [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"
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020043#include "bb_archive.h"
Bernhard Reutner-Fischercfb53df2006-04-02 21:50:01 +000044
Denys Vlasenko641a8c72013-10-06 22:53:14 +020045#if 0
46# define dbg(...) bb_error_msg(__VA_ARGS__)
47#else
48# define dbg(...) ((void)0)
49#endif
50
Eric Andersenaff114c2004-04-14 17:51:38 +000051/* Constants for Huffman coding */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000052#define MAX_GROUPS 6
53#define GROUP_SIZE 50 /* 64 would have been more efficient */
54#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
55#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
56#define SYMBOL_RUNA 0
57#define SYMBOL_RUNB 1
Glenn L McGrath60bce492002-11-03 07:28:38 +000058
Eric Andersen0d6d88a2003-10-18 01:58:35 +000059/* Status return values */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000060#define RETVAL_OK 0
Denys Vlasenko641a8c72013-10-06 22:53:14 +020061#define RETVAL_LAST_BLOCK (dbg("%d", __LINE__), -1)
62#define RETVAL_NOT_BZIP_DATA (dbg("%d", __LINE__), -2)
63#define RETVAL_UNEXPECTED_INPUT_EOF (dbg("%d", __LINE__), -3)
64#define RETVAL_SHORT_WRITE (dbg("%d", __LINE__), -4)
65#define RETVAL_DATA_ERROR (dbg("%d", __LINE__), -5)
66#define RETVAL_OUT_OF_MEMORY (dbg("%d", __LINE__), -6)
67#define RETVAL_OBSOLETE_INPUT (dbg("%d", __LINE__), -7)
Glenn L McGrath60bce492002-11-03 07:28:38 +000068
Eric Andersen0d6d88a2003-10-18 01:58:35 +000069/* Other housekeeping constants */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000070#define IOBUF_SIZE 4096
Glenn L McGrath60bce492002-11-03 07:28:38 +000071
Eric Andersenaff114c2004-04-14 17:51:38 +000072/* This is what we know about each Huffman coding group */
Eric Andersen0d6d88a2003-10-18 01:58:35 +000073struct group_data {
Denis Vlasenko52a43882007-10-10 20:53:41 +000074 /* We have an extra slot at the end of limit[] for a sentinel value. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +000075 int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
Eric Andersen5fa4db22003-10-23 06:52:01 +000076 int minLen, maxLen;
Glenn L McGrath60bce492002-11-03 07:28:38 +000077};
78
Eric Andersen0d6d88a2003-10-18 01:58:35 +000079/* Structure holding all the housekeeping data, including IO buffers and
Denis Vlasenko52a43882007-10-10 20:53:41 +000080 * memory that persists between calls to bunzip
81 * Found the most used member:
82 * cat this_file.c | sed -e 's/"/ /g' -e "s/'/ /g" | xargs -n1 \
83 * | grep 'bd->' | sed 's/^.*bd->/bd->/' | sort | $PAGER
84 * and moved it (inbufBitCount) to offset 0.
85 */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000086struct bunzip_data {
Eric Andersen5fa4db22003-10-23 06:52:01 +000087 /* I/O tracking data (file handles, buffers, positions, etc.) */
Denis Vlasenko52a43882007-10-10 20:53:41 +000088 unsigned inbufBitCount, inbufBits;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +000089 int in_fd, out_fd, inbufCount, inbufPos /*, outbufPos*/;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020090 uint8_t *inbuf /*,*outbuf*/;
Denis Vlasenko52a43882007-10-10 20:53:41 +000091
92 /* State for interrupting output loop */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020093 int writeCopies, writePos, writeRunCountdown, writeCount;
94 int writeCurrent; /* actually a uint8_t */
Rob Landleyf856eab2006-02-17 03:43:49 +000095
Eric Andersen0d6d88a2003-10-18 01:58:35 +000096 /* The CRC values stored in the block header and calculated from the data */
Rob Landleyc57ec372006-04-10 17:07:15 +000097 uint32_t headerCRC, totalCRC, writeCRC;
Rob Landleyf856eab2006-02-17 03:43:49 +000098
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000099 /* Intermediate buffer and its size (in bytes) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200100 uint32_t *dbuf;
101 unsigned dbufSize;
Rob Landleyf856eab2006-02-17 03:43:49 +0000102
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000103 /* For I/O error handling */
104 jmp_buf jmpbuf;
Rob Landleyf856eab2006-02-17 03:43:49 +0000105
Denis Vlasenko52a43882007-10-10 20:53:41 +0000106 /* Big things go last (register-relative addressing can be larger for big offsets) */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000107 uint32_t crc32Table[256];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200108 uint8_t selectors[32768]; /* nSelectors=15 bits */
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200109 struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000110};
111/* typedef struct bunzip_data bunzip_data; -- done in .h file */
Rob Landleyf856eab2006-02-17 03:43:49 +0000112
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000113
114/* Return the next nnn bits of input. All reads from the compressed input
115 are done through this function. All reads are big endian */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000116static unsigned get_bits(bunzip_data *bd, int bits_wanted)
Glenn L McGrath60bce492002-11-03 07:28:38 +0000117{
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000118 unsigned bits = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200119 /* Cache bd->inbufBitCount in a CPU register (hopefully): */
120 int bit_count = bd->inbufBitCount;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000121
122 /* If we need to get more data from the byte buffer, do so. (Loop getting
123 one byte at a time to enforce endianness and avoid unaligned access.) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200124 while (bit_count < bits_wanted) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000125
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000126 /* If we need to read more data from file into byte buffer, do so */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000127 if (bd->inbufPos == bd->inbufCount) {
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000128 /* if "no input fd" case: in_fd == -1, read fails, we jump */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000129 bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);
130 if (bd->inbufCount <= 0)
131 longjmp(bd->jmpbuf, RETVAL_UNEXPECTED_INPUT_EOF);
132 bd->inbufPos = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000133 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000134
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000135 /* Avoid 32-bit overflow (dump bit buffer to top of output) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200136 if (bit_count >= 24) {
137 bits = bd->inbufBits & ((1 << bit_count) - 1);
138 bits_wanted -= bit_count;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000139 bits <<= bits_wanted;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200140 bit_count = 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000141 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000142
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000143 /* Grab next 8 bits of input from buffer. */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000144 bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200145 bit_count += 8;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000146 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000147
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000148 /* Calculate result */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200149 bit_count -= bits_wanted;
150 bd->inbufBitCount = bit_count;
151 bits |= (bd->inbufBits >> bit_count) & ((1 << bits_wanted) - 1);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000152
153 return bits;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000154}
155
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200156/* Unpacks the next block and sets up for the inverse Burrows-Wheeler step. */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000157static int get_next_block(bunzip_data *bd)
Glenn L McGrath60bce492002-11-03 07:28:38 +0000158{
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000159 struct group_data *hufGroup;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200160 int dbufCount, dbufSize, groupCount, *base, *limit, selector,
161 i, j, t, runPos, symCount, symTotal, nSelectors, byteCount[256];
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +0200162 int runCnt = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200163 uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
164 uint32_t *dbuf;
165 unsigned origPtr;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000166
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000167 dbuf = bd->dbuf;
168 dbufSize = bd->dbufSize;
169 selectors = bd->selectors;
Rob Landley2c98c402006-02-17 05:12:03 +0000170
Denys Vlasenko0c576972010-10-30 00:54:10 +0200171/* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
172#if 0
Eric Andersen5fa4db22003-10-23 06:52:01 +0000173 /* Reset longjmp I/O error handling */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000174 i = setjmp(bd->jmpbuf);
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000175 if (i) return i;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200176#endif
Rob Landley2c98c402006-02-17 05:12:03 +0000177
Eric Andersen5fa4db22003-10-23 06:52:01 +0000178 /* Read in header signature and CRC, then validate signature.
179 (last block signature means CRC is for whole file, return now) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000180 i = get_bits(bd, 24);
181 j = get_bits(bd, 24);
182 bd->headerCRC = get_bits(bd, 32);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000183 if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK;
184 if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA;
Rob Landley2c98c402006-02-17 05:12:03 +0000185
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000186 /* We can add support for blockRandomised if anybody complains. There was
187 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
188 it didn't actually work. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000189 if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
190 origPtr = get_bits(bd, 24);
Denis Vlasenko6b06cb82008-05-15 21:30:45 +0000191 if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000192
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000193 /* mapping table: if some byte values are never used (encoding things
194 like ascii text), the compression code removes the gaps to have fewer
195 symbols to deal with, and writes a sparse bitfield indicating which
196 values were present. We make a translation table to convert the symbols
197 back to the corresponding bytes. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000198 symTotal = 0;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200199 i = 0;
200 t = get_bits(bd, 16);
201 do {
202 if (t & (1 << 15)) {
203 unsigned inner_map = get_bits(bd, 16);
204 do {
205 if (inner_map & (1 << 15))
206 symToByte[symTotal++] = i;
207 inner_map <<= 1;
208 i++;
209 } while (i & 15);
210 i -= 16;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000211 }
Denys Vlasenko0c576972010-10-30 00:54:10 +0200212 t <<= 1;
213 i += 16;
214 } while (i < 256);
Rob Landley2c98c402006-02-17 05:12:03 +0000215
Eric Andersenaff114c2004-04-14 17:51:38 +0000216 /* How many different Huffman coding groups does this block use? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000217 groupCount = get_bits(bd, 3);
218 if (groupCount < 2 || groupCount > MAX_GROUPS)
219 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000220
Eric Andersenaff114c2004-04-14 17:51:38 +0000221 /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000222 group. Read in the group selector list, which is stored as MTF encoded
Eric Andersen5fa4db22003-10-23 06:52:01 +0000223 bit runs. (MTF=Move To Front, as each value is used it's moved to the
224 start of the list.) */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200225 for (i = 0; i < groupCount; i++)
226 mtfSymbol[i] = i;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000227 nSelectors = get_bits(bd, 15);
Denys Vlasenko0c576972010-10-30 00:54:10 +0200228 if (!nSelectors)
229 return RETVAL_DATA_ERROR;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000230 for (i = 0; i < nSelectors; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200231 uint8_t tmp_byte;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000232 /* Get next value */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200233 int n = 0;
234 while (get_bits(bd, 1)) {
235 if (n >= groupCount) return RETVAL_DATA_ERROR;
236 n++;
237 }
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000238 /* Decode MTF to get the next selector */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200239 tmp_byte = mtfSymbol[n];
240 while (--n >= 0)
241 mtfSymbol[n + 1] = mtfSymbol[n];
242 mtfSymbol[0] = selectors[i] = tmp_byte;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000243 }
Rob Landley2c98c402006-02-17 05:12:03 +0000244
Eric Andersenaff114c2004-04-14 17:51:38 +0000245 /* Read the Huffman coding tables for each group, which code for symTotal
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000246 literal symbols, plus two run symbols (RUNA, RUNB) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000247 symCount = symTotal + 2;
248 for (j = 0; j < groupCount; j++) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200249 uint8_t length[MAX_SYMBOLS];
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000250 /* 8 bits is ALMOST enough for temp[], see below */
251 unsigned temp[MAX_HUFCODE_BITS+1];
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200252 int minLen, maxLen, pp, len_m1;
Rob Landley2c98c402006-02-17 05:12:03 +0000253
Eric Andersenaff114c2004-04-14 17:51:38 +0000254 /* Read Huffman code lengths for each symbol. They're stored in
Eric Andersen5fa4db22003-10-23 06:52:01 +0000255 a way similar to mtf; record a starting value for the first symbol,
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200256 and an offset from the previous value for every symbol after that.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000257 (Subtracting 1 before the loop and then adding it back at the end is
258 an optimization that makes the test inside the loop simpler: symbol
259 length 0 becomes negative, so an unsigned inequality catches it.) */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200260 len_m1 = get_bits(bd, 5) - 1;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000261 for (i = 0; i < symCount; i++) {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000262 for (;;) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200263 int two_bits;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200264 if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
Eric Andersen5fa4db22003-10-23 06:52:01 +0000265 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000266
Eric Andersen5fa4db22003-10-23 06:52:01 +0000267 /* If first bit is 0, stop. Else second bit indicates whether
268 to increment or decrement the value. Optimization: grab 2
269 bits and unget the second if the first was 0. */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200270 two_bits = get_bits(bd, 2);
271 if (two_bits < 2) {
Eric Andersen5fa4db22003-10-23 06:52:01 +0000272 bd->inbufBitCount++;
273 break;
274 }
Rob Landley2c98c402006-02-17 05:12:03 +0000275
Eric Andersen5fa4db22003-10-23 06:52:01 +0000276 /* Add one if second bit 1, else subtract 1. Avoids if/else */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200277 len_m1 += (((two_bits+1) & 2) - 1);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000278 }
Rob Landley2c98c402006-02-17 05:12:03 +0000279
Eric Andersen5fa4db22003-10-23 06:52:01 +0000280 /* Correct for the initial -1, to get the final symbol length */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200281 length[i] = len_m1 + 1;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000282 }
Rob Landley2c98c402006-02-17 05:12:03 +0000283
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000284 /* Find largest and smallest lengths in this group */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000285 minLen = maxLen = length[0];
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000286 for (i = 1; i < symCount; i++) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000287 if (length[i] > maxLen) maxLen = length[i];
288 else if (length[i] < minLen) minLen = length[i];
Glenn L McGrath60bce492002-11-03 07:28:38 +0000289 }
Rob Landley2c98c402006-02-17 05:12:03 +0000290
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000291 /* Calculate permute[], base[], and limit[] tables from length[].
292 *
Eric Andersenaff114c2004-04-14 17:51:38 +0000293 * permute[] is the lookup table for converting Huffman coded symbols
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000294 * into decoded symbols. base[] is the amount to subtract from the
Eric Andersenaff114c2004-04-14 17:51:38 +0000295 * value of a Huffman symbol of a given length when using permute[].
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000296 *
297 * limit[] indicates the largest numerical value a symbol with a given
Eric Andersenaff114c2004-04-14 17:51:38 +0000298 * number of bits can have. This is how the Huffman codes can vary in
Eric Andersen5fa4db22003-10-23 06:52:01 +0000299 * length: each code with a value>limit[length] needs another bit.
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000300 */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000301 hufGroup = bd->groups + j;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000302 hufGroup->minLen = minLen;
303 hufGroup->maxLen = maxLen;
Rob Landley2c98c402006-02-17 05:12:03 +0000304
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000305 /* Note that minLen can't be smaller than 1, so we adjust the base
306 and limit array pointers so we're not always wasting the first
Denys Vlasenko0c576972010-10-30 00:54:10 +0200307 entry. We do this again when using them (during symbol decoding). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000308 base = hufGroup->base - 1;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000309 limit = hufGroup->limit - 1;
Rob Landley2c98c402006-02-17 05:12:03 +0000310
Eric Andersen5fa4db22003-10-23 06:52:01 +0000311 /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000312 pp = 0;
313 for (i = minLen; i <= maxLen; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200314 int k;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000315 temp[i] = limit[i] = 0;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200316 for (k = 0; k < symCount; k++)
317 if (length[k] == i)
318 hufGroup->permute[pp++] = k;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000319 }
Rob Landley2c98c402006-02-17 05:12:03 +0000320
Eric Andersen5fa4db22003-10-23 06:52:01 +0000321 /* Count symbols coded for at each bit length */
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000322 /* NB: in pathological cases, temp[8] can end ip being 256.
323 * That's why uint8_t is too small for temp[]. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000324 for (i = 0; i < symCount; i++) temp[length[i]]++;
Rob Landley2c98c402006-02-17 05:12:03 +0000325
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000326 /* Calculate limit[] (the largest symbol-coding value at each bit
327 * length, which is (previous limit<<1)+symbols at this level), and
328 * base[] (number of symbols to ignore at each bit length, which is
Eric Andersen5fa4db22003-10-23 06:52:01 +0000329 * limit minus the cumulative count of symbols coded for already). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000330 pp = t = 0;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200331 for (i = minLen; i < maxLen;) {
332 unsigned temp_i = temp[i];
333
334 pp += temp_i;
Rob Landley2c98c402006-02-17 05:12:03 +0000335
Eric Andersen5fa4db22003-10-23 06:52:01 +0000336 /* We read the largest possible symbol size and then unget bits
337 after determining how many we need, and those extra bits could
338 be set to anything. (They're noise from future symbols.) At
339 each level we're really only interested in the first few bits,
340 so here we set all the trailing to-be-ignored bits to 1 so they
341 don't affect the value>limit[length] comparison. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000342 limit[i] = (pp << (maxLen - i)) - 1;
343 pp <<= 1;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200344 t += temp_i;
345 base[++i] = pp - t;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000346 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000347 limit[maxLen] = pp + temp[maxLen] - 1;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200348 limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000349 base[minLen] = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000350 }
Rob Landley2c98c402006-02-17 05:12:03 +0000351
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000352 /* We've finished reading and digesting the block header. Now read this
Eric Andersenaff114c2004-04-14 17:51:38 +0000353 block's Huffman coded symbols from the file and undo the Huffman coding
Denis Vlasenko52a43882007-10-10 20:53:41 +0000354 and run length encoding, saving the result into dbuf[dbufCount++] = uc */
Glenn L McGrath60bce492002-11-03 07:28:38 +0000355
Eric Andersen5fa4db22003-10-23 06:52:01 +0000356 /* Initialize symbol occurrence counters and symbol Move To Front table */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200357 /*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000358 for (i = 0; i < 256; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200359 byteCount[i] = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200360 mtfSymbol[i] = (uint8_t)i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000361 }
Rob Landley2c98c402006-02-17 05:12:03 +0000362
Eric Andersen5fa4db22003-10-23 06:52:01 +0000363 /* Loop through compressed symbols. */
Rob Landley2c98c402006-02-17 05:12:03 +0000364
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000365 runPos = dbufCount = selector = 0;
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000366 for (;;) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200367 int nextSym;
Rob Landley2c98c402006-02-17 05:12:03 +0000368
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000369 /* Fetch next Huffman coding group from list. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000370 symCount = GROUP_SIZE - 1;
371 if (selector >= nSelectors) return RETVAL_DATA_ERROR;
372 hufGroup = bd->groups + selectors[selector++];
373 base = hufGroup->base - 1;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000374 limit = hufGroup->limit - 1;
Rob Landley2c98c402006-02-17 05:12:03 +0000375
Denys Vlasenko0c576972010-10-30 00:54:10 +0200376 continue_this_group:
Eric Andersenaff114c2004-04-14 17:51:38 +0000377 /* Read next Huffman-coded symbol. */
Rob Landley2c98c402006-02-17 05:12:03 +0000378
Eric Andersen5fa4db22003-10-23 06:52:01 +0000379 /* Note: It is far cheaper to read maxLen bits and back up than it is
Denys Vlasenko0c576972010-10-30 00:54:10 +0200380 to read minLen bits and then add additional bit at a time, testing
Eric Andersen5fa4db22003-10-23 06:52:01 +0000381 as we go. Because there is a trailing last block (with file CRC),
382 there is no danger of the overread causing an unexpected EOF for a
Denys Vlasenko0c576972010-10-30 00:54:10 +0200383 valid compressed file.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000384 */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200385 if (1) {
386 /* As a further optimization, we do the read inline
387 (falling back to a call to get_bits if the buffer runs dry).
388 */
389 int new_cnt;
390 while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
391 /* bd->inbufBitCount < hufGroup->maxLen */
392 if (bd->inbufPos == bd->inbufCount) {
393 nextSym = get_bits(bd, hufGroup->maxLen);
394 goto got_huff_bits;
395 }
396 bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
397 bd->inbufBitCount += 8;
398 };
399 bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
400 nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
401 got_huff_bits: ;
402 } else { /* unoptimized equivalent */
403 nextSym = get_bits(bd, hufGroup->maxLen);
404 }
405 /* Figure how many bits are in next symbol and unget extras */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000406 i = hufGroup->minLen;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200407 while (nextSym > limit[i]) ++i;
408 j = hufGroup->maxLen - i;
409 if (j < 0)
410 return RETVAL_DATA_ERROR;
411 bd->inbufBitCount += j;
Rob Landley2c98c402006-02-17 05:12:03 +0000412
Eric Andersen5fa4db22003-10-23 06:52:01 +0000413 /* Huffman decode value to get nextSym (with bounds checking) */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200414 nextSym = (nextSym >> j) - base[i];
415 if ((unsigned)nextSym >= MAX_SYMBOLS)
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000416 return RETVAL_DATA_ERROR;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200417 nextSym = hufGroup->permute[nextSym];
Rob Landley2c98c402006-02-17 05:12:03 +0000418
Eric Andersen5fa4db22003-10-23 06:52:01 +0000419 /* We have now decoded the symbol, which indicates either a new literal
420 byte, or a repeated run of the most recent literal byte. First,
421 check if nextSym indicates a repeated run, and if so loop collecting
422 how many times to repeat the last literal. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000423 if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
Rob Landley2c98c402006-02-17 05:12:03 +0000424
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000425 /* If this is the start of a new run, zero out counter */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200426 if (runPos == 0) {
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000427 runPos = 1;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200428 runCnt = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000429 }
Rob Landley2c98c402006-02-17 05:12:03 +0000430
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000431 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
432 each bit position, add 1 or 2 instead. For example,
433 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
434 You can make any bit pattern that way using 1 less symbol than
435 the basic or 0/1 method (except all bits 0, which would use no
436 symbols, but a run of length 0 doesn't mean anything in this
437 context). Thus space is saved. */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200438 runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000439 if (runPos < dbufSize) runPos <<= 1;
Rob Landleya8b98d62004-11-16 12:07:04 +0000440 goto end_of_huffman_loop;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000441 }
Rob Landley2c98c402006-02-17 05:12:03 +0000442
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000443 /* When we hit the first non-run symbol after a run, we now know
444 how many times to repeat the last literal, so append that many
445 copies to our buffer of decoded symbols (dbuf) now. (The last
446 literal used is the one at the head of the mtfSymbol array.) */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200447 if (runPos != 0) {
448 uint8_t tmp_byte;
Denys Vlasenko641a8c72013-10-06 22:53:14 +0200449 if (dbufCount + runCnt > dbufSize) {
450 dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR",
451 dbufCount, runCnt, dbufCount + runCnt, dbufSize);
452 return RETVAL_DATA_ERROR;
453 }
Denys Vlasenko0c576972010-10-30 00:54:10 +0200454 tmp_byte = symToByte[mtfSymbol[0]];
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200455 byteCount[tmp_byte] += runCnt;
456 while (--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200457 runPos = 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000458 }
Rob Landley2c98c402006-02-17 05:12:03 +0000459
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000460 /* Is this the terminating symbol? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000461 if (nextSym > symTotal) break;
Rob Landley2c98c402006-02-17 05:12:03 +0000462
Eric Andersen5fa4db22003-10-23 06:52:01 +0000463 /* At this point, nextSym indicates a new literal character. Subtract
464 one to get the position in the MTF array at which this literal is
465 currently to be found. (Note that the result can't be -1 or 0,
466 because 0 and 1 are RUNA and RUNB. But another instance of the
467 first symbol in the mtf array, position 0, would have been handled
468 as part of a run above. Therefore 1 unused mtf position minus
469 2 non-literal nextSym values equals -1.) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000470 if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000471 i = nextSym - 1;
472 uc = mtfSymbol[i];
Rob Landley2c98c402006-02-17 05:12:03 +0000473
Eric Andersen5fa4db22003-10-23 06:52:01 +0000474 /* Adjust the MTF array. Since we typically expect to move only a
475 * small number of symbols, and are bound by 256 in any case, using
476 * memmove here would typically be bigger and slower due to function
477 * call overhead and other assorted setup costs. */
Eric Andersen1acfb722003-10-18 01:59:46 +0000478 do {
479 mtfSymbol[i] = mtfSymbol[i-1];
480 } while (--i);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000481 mtfSymbol[0] = uc;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000482 uc = symToByte[uc];
Rob Landley2c98c402006-02-17 05:12:03 +0000483
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000484 /* We have our literal byte. Save it into dbuf. */
485 byteCount[uc]++;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200486 dbuf[dbufCount++] = (uint32_t)uc;
Rob Landley2c98c402006-02-17 05:12:03 +0000487
Rob Landleyf856eab2006-02-17 03:43:49 +0000488 /* Skip group initialization if we're not done with this group. Done
489 * this way to avoid compiler warning. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000490 end_of_huffman_loop:
Denys Vlasenko0c576972010-10-30 00:54:10 +0200491 if (--symCount >= 0) goto continue_this_group;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000492 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000493
Eric Andersenaff114c2004-04-14 17:51:38 +0000494 /* At this point, we've read all the Huffman-coded symbols (and repeated
Denis Vlasenko246b5c32007-04-10 17:18:12 +0000495 runs) for this block from the input stream, and decoded them into the
Eric Andersen5fa4db22003-10-23 06:52:01 +0000496 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
497 Now undo the Burrows-Wheeler transform on dbuf.
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000498 See http://dogma.net/markn/articles/bwt/bwt.htm
499 */
Rob Landley2c98c402006-02-17 05:12:03 +0000500
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000501 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000502 j = 0;
503 for (i = 0; i < 256; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200504 int tmp_count = j + byteCount[i];
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000505 byteCount[i] = j;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200506 j = tmp_count;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000507 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000508
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000509 /* Figure out what order dbuf would be in if we sorted it. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000510 for (i = 0; i < dbufCount; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200511 uint8_t tmp_byte = (uint8_t)dbuf[i];
512 int tmp_count = byteCount[tmp_byte];
513 dbuf[tmp_count] |= (i << 8);
514 byteCount[tmp_byte] = tmp_count + 1;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000515 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000516
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000517 /* Decode first byte by hand to initialize "previous" byte. Note that it
518 doesn't get output, and if the first three characters are identical
Eric Andersen5fa4db22003-10-23 06:52:01 +0000519 it doesn't qualify as a run (hence writeRunCountdown=5). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000520 if (dbufCount) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200521 uint32_t tmp;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +0000522 if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200523 tmp = dbuf[origPtr];
524 bd->writeCurrent = (uint8_t)tmp;
525 bd->writePos = (tmp >> 8);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000526 bd->writeRunCountdown = 5;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000527 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000528 bd->writeCount = dbufCount;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000529
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000530 return RETVAL_OK;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000531}
532
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200533/* Undo Burrows-Wheeler transform on intermediate buffer to produce output.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000534 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
535 data are written to outbuf. Return value is number of bytes written or
536 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
537 are ignored, data is written to out_fd and return is RETVAL_OK or error.
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200538
539 NB: read_bunzip returns < 0 on error, or the number of *unfilled* bytes
540 in outbuf. IOW: on EOF returns len ("all bytes are not filled"), not 0.
541 (Why? This allows to get rid of one local variable)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000542*/
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000543int FAST_FUNC read_bunzip(bunzip_data *bd, char *outbuf, int len)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000544{
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200545 const uint32_t *dbuf;
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200546 int pos, current, previous;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200547 uint32_t CRC;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000548
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200549 /* If we already have error/end indicator, return it */
550 if (bd->writeCount < 0)
551 return bd->writeCount;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000552
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000553 dbuf = bd->dbuf;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200554
555 /* Register-cached state (hopefully): */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000556 pos = bd->writePos;
557 current = bd->writeCurrent;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200558 CRC = bd->writeCRC; /* small loss on x86-32 (not enough regs), win on x86-64 */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000559
560 /* We will always have pending decoded data to write into the output
561 buffer unless this is the very first call (in which case we haven't
Eric Andersenaff114c2004-04-14 17:51:38 +0000562 Huffman-decoded a block into the intermediate buffer yet). */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000563 if (bd->writeCopies) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000564
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200565 dec_writeCopies:
Eric Andersen5fa4db22003-10-23 06:52:01 +0000566 /* Inside the loop, writeCopies means extra copies (beyond 1) */
567 --bd->writeCopies;
Rob Landleyf856eab2006-02-17 03:43:49 +0000568
Eric Andersen5fa4db22003-10-23 06:52:01 +0000569 /* Loop outputting bytes */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000570 for (;;) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000571
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200572 /* If the output buffer is full, save cached state and return */
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200573 if (--len < 0) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200574 /* Unlikely branch.
575 * Use of "goto" instead of keeping code here
576 * helps compiler to realize this. */
577 goto outbuf_full;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000578 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000579
Eric Andersen5fa4db22003-10-23 06:52:01 +0000580 /* Write next byte into output buffer, updating CRC */
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200581 *outbuf++ = current;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200582 CRC = (CRC << 8) ^ bd->crc32Table[(CRC >> 24) ^ current];
Rob Landleyf856eab2006-02-17 03:43:49 +0000583
Eric Andersen5fa4db22003-10-23 06:52:01 +0000584 /* Loop now if we're outputting multiple copies of this byte */
585 if (bd->writeCopies) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200586 /* Unlikely branch */
587 /*--bd->writeCopies;*/
588 /*continue;*/
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200589 /* Same, but (ab)using other existing --writeCopies operation
590 * (and this if() compiles into just test+branch pair): */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200591 goto dec_writeCopies;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000592 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000593 decode_next_byte:
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200594 if (--bd->writeCount < 0)
595 break; /* input block is fully consumed, need next one */
596
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000597 /* Follow sequence vector to undo Burrows-Wheeler transform */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000598 previous = current;
599 pos = dbuf[pos];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200600 current = (uint8_t)pos;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000601 pos >>= 8;
Rob Landleyf856eab2006-02-17 03:43:49 +0000602
Denis Vlasenko52a43882007-10-10 20:53:41 +0000603 /* After 3 consecutive copies of the same byte, the 4th
604 * is a repeat count. We count down from 4 instead
Eric Andersen5fa4db22003-10-23 06:52:01 +0000605 * of counting up because testing for non-zero is faster */
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200606 if (--bd->writeRunCountdown != 0) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000607 if (current != previous)
608 bd->writeRunCountdown = 4;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000609 } else {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200610 /* Unlikely branch */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000611 /* We have a repeated run, this byte indicates the count */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000612 bd->writeCopies = current;
613 current = previous;
614 bd->writeRunCountdown = 5;
Rob Landleyf856eab2006-02-17 03:43:49 +0000615
Eric Andersen5fa4db22003-10-23 06:52:01 +0000616 /* Sometimes there are just 3 bytes (run length 0) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000617 if (!bd->writeCopies) goto decode_next_byte;
Rob Landleyf856eab2006-02-17 03:43:49 +0000618
Eric Andersen5fa4db22003-10-23 06:52:01 +0000619 /* Subtract the 1 copy we'd output anyway to get extras */
620 --bd->writeCopies;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000621 }
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200622 } /* for(;;) */
Rob Landleyf856eab2006-02-17 03:43:49 +0000623
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200624 /* Decompression of this input block completed successfully */
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200625 bd->writeCRC = CRC = ~CRC;
626 bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ CRC;
Rob Landleyf856eab2006-02-17 03:43:49 +0000627
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200628 /* If this block had a CRC error, force file level CRC error */
629 if (CRC != bd->headerCRC) {
Denis Vlasenko52a43882007-10-10 20:53:41 +0000630 bd->totalCRC = bd->headerCRC + 1;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000631 return RETVAL_LAST_BLOCK;
632 }
Glenn L McGrath60bce492002-11-03 07:28:38 +0000633 }
Eric Andersen5fa4db22003-10-23 06:52:01 +0000634
Eric Andersenaff114c2004-04-14 17:51:38 +0000635 /* Refill the intermediate buffer by Huffman-decoding next block of input */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200636 {
637 int r = get_next_block(bd);
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200638 if (r) { /* error/end */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200639 bd->writeCount = r;
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200640 return (r != RETVAL_LAST_BLOCK) ? r : len;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200641 }
Eric Andersen5fa4db22003-10-23 06:52:01 +0000642 }
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200643
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200644 CRC = ~0;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000645 pos = bd->writePos;
646 current = bd->writeCurrent;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000647 goto decode_next_byte;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200648
649 outbuf_full:
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200650 /* Output buffer is full, save cached state and return */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200651 bd->writePos = pos;
652 bd->writeCurrent = current;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200653 bd->writeCRC = CRC;
654
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200655 bd->writeCopies++;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200656
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200657 return 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000658}
659
Eric Andersen5fa4db22003-10-23 06:52:01 +0000660/* Allocate the structure, read file header. If in_fd==-1, inbuf must contain
661 a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are
662 ignored, and data is read from file handle into temporary buffer. */
Rob Landleyf856eab2006-02-17 03:43:49 +0000663
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000664/* Because bunzip2 is used for help text unpacking, and because bb_show_usage()
665 should work for NOFORK applets too, we must be extremely careful to not leak
666 any allocations! */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200667int FAST_FUNC start_bunzip(bunzip_data **bdp, int in_fd,
668 const void *inbuf, int len)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000669{
670 bunzip_data *bd;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000671 unsigned i;
672 enum {
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000673 BZh0 = ('B' << 24) + ('Z' << 16) + ('h' << 8) + '0',
674 h0 = ('h' << 8) + '0',
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000675 };
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000676
677 /* Figure out how much data to allocate */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000678 i = sizeof(bunzip_data);
679 if (in_fd != -1) i += IOBUF_SIZE;
Rob Landleyf856eab2006-02-17 03:43:49 +0000680
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000681 /* Allocate bunzip_data. Most fields initialize to zero. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000682 bd = *bdp = xzalloc(i);
Rob Landleyf856eab2006-02-17 03:43:49 +0000683
Eric Andersen5fa4db22003-10-23 06:52:01 +0000684 /* Setup input buffer */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000685 bd->in_fd = in_fd;
686 if (-1 == in_fd) {
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000687 /* in this case, bd->inbuf is read-only */
688 bd->inbuf = (void*)inbuf; /* cast away const-ness */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200689 } else {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200690 bd->inbuf = (uint8_t*)(bd + 1);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200691 memcpy(bd->inbuf, inbuf, len);
692 }
693 bd->inbufCount = len;
Rob Landleyf856eab2006-02-17 03:43:49 +0000694
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000695 /* Init the CRC32 table (big endian) */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000696 crc32_filltable(bd->crc32Table, 1);
Rob Landleyf856eab2006-02-17 03:43:49 +0000697
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000698 /* Setup for I/O error handling via longjmp */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000699 i = setjmp(bd->jmpbuf);
700 if (i) return i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000701
702 /* Ensure that file starts with "BZh['1'-'9']." */
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000703 /* Update: now caller verifies 1st two bytes, makes .gz/.bz2
704 * integration easier */
705 /* was: */
706 /* i = get_bits(bd, 32); */
707 /* if ((unsigned)(i - BZh0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA; */
708 i = get_bits(bd, 16);
709 if ((unsigned)(i - h0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000710
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000711 /* Fourth byte (ascii '1'-'9') indicates block size in units of 100k of
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000712 uncompressed data. Allocate intermediate buffer for block. */
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000713 /* bd->dbufSize = 100000 * (i - BZh0); */
714 bd->dbufSize = 100000 * (i - h0);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000715
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000716 /* Cannot use xmalloc - may leak bd in NOFORK case! */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200717 bd->dbuf = malloc_or_warn(bd->dbufSize * sizeof(bd->dbuf[0]));
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000718 if (!bd->dbuf) {
719 free(bd);
720 xfunc_die();
721 }
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000722 return RETVAL_OK;
723}
724
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000725void FAST_FUNC dealloc_bunzip(bunzip_data *bd)
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000726{
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000727 free(bd->dbuf);
728 free(bd);
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000729}
730
731
732/* Decompress src_fd to dst_fd. Stops at end of bzip data, not end of file. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000733IF_DESKTOP(long long) int FAST_FUNC
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200734unpack_bz2_stream(transformer_aux_data_t *aux, int src_fd, int dst_fd)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000735{
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000736 IF_DESKTOP(long long total_written = 0;)
Denys Vlasenko4d4d1a02010-11-01 02:19:47 +0100737 bunzip_data *bd;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000738 char *outbuf;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000739 int i;
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200740 unsigned len;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000741
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200742 if (check_signature16(aux, src_fd, BZIP2_MAGIC))
743 return -1;
744
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000745 outbuf = xmalloc(IOBUF_SIZE);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200746 len = 0;
747 while (1) { /* "Process one BZ... stream" loop */
748
749 i = start_bunzip(&bd, src_fd, outbuf + 2, len);
750
751 if (i == 0) {
752 while (1) { /* "Produce some output bytes" loop */
753 i = read_bunzip(bd, outbuf, IOBUF_SIZE);
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200754 if (i < 0) /* error? */
755 break;
756 i = IOBUF_SIZE - i; /* number of bytes produced */
757 if (i == 0) /* EOF? */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200758 break;
759 if (i != full_write(dst_fd, outbuf, i)) {
760 bb_error_msg("short write");
Denys Vlasenko8531c432010-11-01 01:38:54 +0100761 i = RETVAL_SHORT_WRITE;
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200762 goto release_mem;
763 }
764 IF_DESKTOP(total_written += i;)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000765 }
766 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000767
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200768 if (i != RETVAL_LAST_BLOCK
769 /* Observed case when i == RETVAL_OK:
770 * "bzcat z.bz2", where "z.bz2" is a bzipped zero-length file
771 * (to be exact, z.bz2 is exactly these 14 bytes:
772 * 42 5a 68 39 17 72 45 38 50 90 00 00 00 00).
773 */
774 && i != RETVAL_OK
775 ) {
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200776 bb_error_msg("bunzip error %d", i);
777 break;
778 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000779 if (bd->headerCRC != bd->totalCRC) {
Denis Vlasenko66bbfbd2007-09-28 23:45:56 +0000780 bb_error_msg("CRC error");
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200781 break;
Glenn L McGrath1c834402003-10-28 23:32:12 +0000782 }
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200783
784 /* Successfully unpacked one BZ stream */
785 i = RETVAL_OK;
786
787 /* Do we have "BZ..." after last processed byte?
788 * pbzip2 (parallelized bzip2) produces such files.
789 */
790 len = bd->inbufCount - bd->inbufPos;
791 memcpy(outbuf, &bd->inbuf[bd->inbufPos], len);
792 if (len < 2) {
Tanguy Pruvot6fef6a32012-05-05 15:26:43 +0200793 if (safe_read(src_fd, outbuf + len, 2 - len) != (int)(2 - len))
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200794 break;
795 len = 2;
796 }
797 if (*(uint16_t*)outbuf != BZIP2_MAGIC) /* "BZ"? */
798 break;
799 dealloc_bunzip(bd);
800 len -= 2;
Glenn L McGrath1c834402003-10-28 23:32:12 +0000801 }
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200802
803 release_mem:
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000804 dealloc_bunzip(bd);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000805 free(outbuf);
Glenn L McGrath1c834402003-10-28 23:32:12 +0000806
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000807 return i ? i : IF_DESKTOP(total_written) + 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000808}
809
Eric Andersen5fa4db22003-10-23 06:52:01 +0000810#ifdef TESTING
Glenn L McGrath60bce492002-11-03 07:28:38 +0000811
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000812static char *const bunzip_errors[] = {
813 NULL, "Bad file checksum", "Not bzip data",
814 "Unexpected input EOF", "Unexpected output EOF", "Data error",
815 "Out of memory", "Obsolete (pre 0.9.5) bzip format not supported"
816};
Glenn L McGrath237ae422002-11-03 14:05:15 +0000817
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000818/* Dumb little test thing, decompress stdin to stdout */
Bernhard Reutner-Fischerfebe3c42007-04-04 20:52:03 +0000819int main(int argc, char **argv)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000820{
Eric Andersen5fa4db22003-10-23 06:52:01 +0000821 char c;
822
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200823 int i = unpack_bz2_stream(0, 1);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000824 if (i < 0)
Denis Vlasenkof5d8c902008-06-26 14:32:57 +0000825 fprintf(stderr, "%s\n", bunzip_errors[-i]);
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000826 else if (read(STDIN_FILENO, &c, 1))
Denis Vlasenkof5d8c902008-06-26 14:32:57 +0000827 fprintf(stderr, "Trailing garbage ignored\n");
Eric Andersen5fa4db22003-10-23 06:52:01 +0000828 return -i;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000829}
830#endif