blob: 42e2b4f880bab16d175b2466b16d99bfc0442169 [file] [log] [blame]
Eric Andersen0d6d88a2003-10-18 01:58:35 +00001/* vi: set sw=4 ts=4: */
Denys Vlasenko2ab94032017-10-05 15:33:28 +02002/*
3 * Small bzip2 deflate implementation, by Rob Landley (rob@landley.net).
Denys Vlasenkoebe6d9d2017-10-05 14:40:24 +02004 *
5 * Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
6 * which also acknowledges contributions by Mike Burrows, David Wheeler,
7 * Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
8 * Robert Sedgewick, and Jon L. Bentley.
9 *
10 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 */
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 */
Glenn L McGrath1c834402003-10-28 23:32:12 +000041#include "libbb.h"
Denys Vlasenkod184a722011-09-22 12:45:14 +020042#include "bb_archive.h"
Bernhard Reutner-Fischercfb53df2006-04-02 21:50:01 +000043
Denys Vlasenko932e2332013-10-06 22:53:14 +020044#if 0
45# define dbg(...) bb_error_msg(__VA_ARGS__)
46#else
47# define dbg(...) ((void)0)
48#endif
49
Eric Andersenaff114c2004-04-14 17:51:38 +000050/* Constants for Huffman coding */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000051#define MAX_GROUPS 6
52#define GROUP_SIZE 50 /* 64 would have been more efficient */
53#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
54#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
55#define SYMBOL_RUNA 0
56#define SYMBOL_RUNB 1
Glenn L McGrath60bce492002-11-03 07:28:38 +000057
Eric Andersen0d6d88a2003-10-18 01:58:35 +000058/* Status return values */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000059#define RETVAL_OK 0
Denys Vlasenko932e2332013-10-06 22:53:14 +020060#define RETVAL_LAST_BLOCK (dbg("%d", __LINE__), -1)
61#define RETVAL_NOT_BZIP_DATA (dbg("%d", __LINE__), -2)
62#define RETVAL_UNEXPECTED_INPUT_EOF (dbg("%d", __LINE__), -3)
63#define RETVAL_SHORT_WRITE (dbg("%d", __LINE__), -4)
64#define RETVAL_DATA_ERROR (dbg("%d", __LINE__), -5)
65#define RETVAL_OUT_OF_MEMORY (dbg("%d", __LINE__), -6)
66#define RETVAL_OBSOLETE_INPUT (dbg("%d", __LINE__), -7)
Glenn L McGrath60bce492002-11-03 07:28:38 +000067
Eric Andersen0d6d88a2003-10-18 01:58:35 +000068/* Other housekeeping constants */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000069#define IOBUF_SIZE 4096
Glenn L McGrath60bce492002-11-03 07:28:38 +000070
Eric Andersenaff114c2004-04-14 17:51:38 +000071/* This is what we know about each Huffman coding group */
Eric Andersen0d6d88a2003-10-18 01:58:35 +000072struct group_data {
Denis Vlasenko52a43882007-10-10 20:53:41 +000073 /* We have an extra slot at the end of limit[] for a sentinel value. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +000074 int limit[MAX_HUFCODE_BITS+1], base[MAX_HUFCODE_BITS], permute[MAX_SYMBOLS];
Eric Andersen5fa4db22003-10-23 06:52:01 +000075 int minLen, maxLen;
Glenn L McGrath60bce492002-11-03 07:28:38 +000076};
77
Eric Andersen0d6d88a2003-10-18 01:58:35 +000078/* Structure holding all the housekeeping data, including IO buffers and
Denis Vlasenko52a43882007-10-10 20:53:41 +000079 * memory that persists between calls to bunzip
80 * Found the most used member:
81 * cat this_file.c | sed -e 's/"/ /g' -e "s/'/ /g" | xargs -n1 \
82 * | grep 'bd->' | sed 's/^.*bd->/bd->/' | sort | $PAGER
83 * and moved it (inbufBitCount) to offset 0.
84 */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000085struct bunzip_data {
Eric Andersen5fa4db22003-10-23 06:52:01 +000086 /* I/O tracking data (file handles, buffers, positions, etc.) */
Denis Vlasenko52a43882007-10-10 20:53:41 +000087 unsigned inbufBitCount, inbufBits;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +000088 int in_fd, out_fd, inbufCount, inbufPos /*, outbufPos*/;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020089 uint8_t *inbuf /*,*outbuf*/;
Denis Vlasenko52a43882007-10-10 20:53:41 +000090
91 /* State for interrupting output loop */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020092 int writeCopies, writePos, writeRunCountdown, writeCount;
93 int writeCurrent; /* actually a uint8_t */
Rob Landleyf856eab2006-02-17 03:43:49 +000094
Eric Andersen0d6d88a2003-10-18 01:58:35 +000095 /* The CRC values stored in the block header and calculated from the data */
Rob Landleyc57ec372006-04-10 17:07:15 +000096 uint32_t headerCRC, totalCRC, writeCRC;
Rob Landleyf856eab2006-02-17 03:43:49 +000097
Denis Vlasenkoc6758a02007-04-10 21:40:19 +000098 /* Intermediate buffer and its size (in bytes) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +020099 uint32_t *dbuf;
100 unsigned dbufSize;
Rob Landleyf856eab2006-02-17 03:43:49 +0000101
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000102 /* For I/O error handling */
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200103 jmp_buf *jmpbuf;
Rob Landleyf856eab2006-02-17 03:43:49 +0000104
Denis Vlasenko52a43882007-10-10 20:53:41 +0000105 /* Big things go last (register-relative addressing can be larger for big offsets) */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000106 uint32_t crc32Table[256];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200107 uint8_t selectors[32768]; /* nSelectors=15 bits */
Denys Vlasenkofb132e42010-10-29 11:46:52 +0200108 struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000109};
Ron Yorstonc339c7f2018-11-02 14:14:31 +0100110typedef struct bunzip_data bunzip_data;
Rob Landleyf856eab2006-02-17 03:43:49 +0000111
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000112
113/* Return the next nnn bits of input. All reads from the compressed input
114 are done through this function. All reads are big endian */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000115static unsigned get_bits(bunzip_data *bd, int bits_wanted)
Glenn L McGrath60bce492002-11-03 07:28:38 +0000116{
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000117 unsigned bits = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200118 /* Cache bd->inbufBitCount in a CPU register (hopefully): */
119 int bit_count = bd->inbufBitCount;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000120
121 /* If we need to get more data from the byte buffer, do so. (Loop getting
122 one byte at a time to enforce endianness and avoid unaligned access.) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200123 while (bit_count < bits_wanted) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000124
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000125 /* If we need to read more data from file into byte buffer, do so */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000126 if (bd->inbufPos == bd->inbufCount) {
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000127 /* if "no input fd" case: in_fd == -1, read fails, we jump */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000128 bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);
129 if (bd->inbufCount <= 0)
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200130 longjmp(*bd->jmpbuf, RETVAL_UNEXPECTED_INPUT_EOF);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000131 bd->inbufPos = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000132 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000133
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000134 /* Avoid 32-bit overflow (dump bit buffer to top of output) */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200135 if (bit_count >= 24) {
Rostislav Skudnov87625122017-02-01 18:35:13 +0000136 bits = bd->inbufBits & ((1U << bit_count) - 1);
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200137 bits_wanted -= bit_count;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000138 bits <<= bits_wanted;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200139 bit_count = 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000140 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000141
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000142 /* Grab next 8 bits of input from buffer. */
Denis Vlasenko52a43882007-10-10 20:53:41 +0000143 bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200144 bit_count += 8;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000145 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000146
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000147 /* Calculate result */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200148 bit_count -= bits_wanted;
149 bd->inbufBitCount = bit_count;
150 bits |= (bd->inbufBits >> bit_count) & ((1 << bits_wanted) - 1);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000151
152 return bits;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000153}
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200154//#define get_bits(bd, n) (dbg("%d:get_bits()", __LINE__), get_bits(bd, n))
Glenn L McGrath60bce492002-11-03 07:28:38 +0000155
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{
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200159 int groupCount, selector,
Denys Vlasenko0402cb32017-10-22 18:23:23 +0200160 i, j, symCount, symTotal, nSelectors, byteCount[256];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200161 uint8_t uc, symToByte[256], mtfSymbol[256], *selectors;
162 uint32_t *dbuf;
Rostislav Skudnov87625122017-02-01 18:35:13 +0000163 unsigned origPtr, t;
Denys Vlasenko0402cb32017-10-22 18:23:23 +0200164 unsigned dbufCount, runPos;
165 unsigned runCnt = runCnt; /* for compiler */
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000166
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000167 dbuf = bd->dbuf;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000168 selectors = bd->selectors;
Rob Landley2c98c402006-02-17 05:12:03 +0000169
Denys Vlasenko0c576972010-10-30 00:54:10 +0200170/* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */
171#if 0
Eric Andersen5fa4db22003-10-23 06:52:01 +0000172 /* Reset longjmp I/O error handling */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000173 i = setjmp(bd->jmpbuf);
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000174 if (i) return i;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200175#endif
Rob Landley2c98c402006-02-17 05:12:03 +0000176
Eric Andersen5fa4db22003-10-23 06:52:01 +0000177 /* Read in header signature and CRC, then validate signature.
178 (last block signature means CRC is for whole file, return now) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000179 i = get_bits(bd, 24);
180 j = get_bits(bd, 24);
181 bd->headerCRC = get_bits(bd, 32);
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200182 if ((i == 0x177245) && (j == 0x385090))
183 return RETVAL_LAST_BLOCK;
184 if ((i != 0x314159) || (j != 0x265359))
185 return RETVAL_NOT_BZIP_DATA;
Rob Landley2c98c402006-02-17 05:12:03 +0000186
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000187 /* We can add support for blockRandomised if anybody complains. There was
188 some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
189 it didn't actually work. */
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200190 if (get_bits(bd, 1))
191 return RETVAL_OBSOLETE_INPUT;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000192 origPtr = get_bits(bd, 24);
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200193 if (origPtr > bd->dbufSize)
194 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000195
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000196 /* mapping table: if some byte values are never used (encoding things
197 like ascii text), the compression code removes the gaps to have fewer
198 symbols to deal with, and writes a sparse bitfield indicating which
199 values were present. We make a translation table to convert the symbols
200 back to the corresponding bytes. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000201 symTotal = 0;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200202 i = 0;
203 t = get_bits(bd, 16);
204 do {
205 if (t & (1 << 15)) {
206 unsigned inner_map = get_bits(bd, 16);
207 do {
208 if (inner_map & (1 << 15))
209 symToByte[symTotal++] = i;
210 inner_map <<= 1;
211 i++;
212 } while (i & 15);
213 i -= 16;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000214 }
Denys Vlasenko0c576972010-10-30 00:54:10 +0200215 t <<= 1;
216 i += 16;
217 } while (i < 256);
Rob Landley2c98c402006-02-17 05:12:03 +0000218
Eric Andersenaff114c2004-04-14 17:51:38 +0000219 /* How many different Huffman coding groups does this block use? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000220 groupCount = get_bits(bd, 3);
221 if (groupCount < 2 || groupCount > MAX_GROUPS)
222 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000223
Eric Andersenaff114c2004-04-14 17:51:38 +0000224 /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000225 group. Read in the group selector list, which is stored as MTF encoded
Eric Andersen5fa4db22003-10-23 06:52:01 +0000226 bit runs. (MTF=Move To Front, as each value is used it's moved to the
227 start of the list.) */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200228 for (i = 0; i < groupCount; i++)
229 mtfSymbol[i] = i;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000230 nSelectors = get_bits(bd, 15);
Denys Vlasenko0c576972010-10-30 00:54:10 +0200231 if (!nSelectors)
232 return RETVAL_DATA_ERROR;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000233 for (i = 0; i < nSelectors; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200234 uint8_t tmp_byte;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000235 /* Get next value */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200236 int n = 0;
237 while (get_bits(bd, 1)) {
Denys Vlasenko58d998d2019-05-23 14:54:13 +0200238 n++;
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200239 if (n >= groupCount)
240 return RETVAL_DATA_ERROR;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200241 }
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000242 /* Decode MTF to get the next selector */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200243 tmp_byte = mtfSymbol[n];
244 while (--n >= 0)
245 mtfSymbol[n + 1] = mtfSymbol[n];
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200246//We catch it later, in the second loop where we use selectors[i].
247//Maybe this is a better place, though?
248// if (tmp_byte >= groupCount) {
249// dbg("%d: selectors[%d]:%d groupCount:%d",
250// __LINE__, i, tmp_byte, groupCount);
251// return RETVAL_DATA_ERROR;
252// }
Denys Vlasenko0c576972010-10-30 00:54:10 +0200253 mtfSymbol[0] = selectors[i] = tmp_byte;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000254 }
Rob Landley2c98c402006-02-17 05:12:03 +0000255
Eric Andersenaff114c2004-04-14 17:51:38 +0000256 /* Read the Huffman coding tables for each group, which code for symTotal
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000257 literal symbols, plus two run symbols (RUNA, RUNB) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000258 symCount = symTotal + 2;
259 for (j = 0; j < groupCount; j++) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200260 uint8_t length[MAX_SYMBOLS];
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000261 /* 8 bits is ALMOST enough for temp[], see below */
262 unsigned temp[MAX_HUFCODE_BITS+1];
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200263 struct group_data *hufGroup;
264 int *base, *limit;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200265 int minLen, maxLen, pp, len_m1;
Rob Landley2c98c402006-02-17 05:12:03 +0000266
Eric Andersenaff114c2004-04-14 17:51:38 +0000267 /* Read Huffman code lengths for each symbol. They're stored in
Eric Andersen5fa4db22003-10-23 06:52:01 +0000268 a way similar to mtf; record a starting value for the first symbol,
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200269 and an offset from the previous value for every symbol after that.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000270 (Subtracting 1 before the loop and then adding it back at the end is
271 an optimization that makes the test inside the loop simpler: symbol
272 length 0 becomes negative, so an unsigned inequality catches it.) */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200273 len_m1 = get_bits(bd, 5) - 1;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000274 for (i = 0; i < symCount; i++) {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000275 for (;;) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200276 int two_bits;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200277 if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1))
Eric Andersen5fa4db22003-10-23 06:52:01 +0000278 return RETVAL_DATA_ERROR;
Rob Landley2c98c402006-02-17 05:12:03 +0000279
Eric Andersen5fa4db22003-10-23 06:52:01 +0000280 /* If first bit is 0, stop. Else second bit indicates whether
281 to increment or decrement the value. Optimization: grab 2
282 bits and unget the second if the first was 0. */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200283 two_bits = get_bits(bd, 2);
284 if (two_bits < 2) {
Eric Andersen5fa4db22003-10-23 06:52:01 +0000285 bd->inbufBitCount++;
286 break;
287 }
Rob Landley2c98c402006-02-17 05:12:03 +0000288
Eric Andersen5fa4db22003-10-23 06:52:01 +0000289 /* Add one if second bit 1, else subtract 1. Avoids if/else */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200290 len_m1 += (((two_bits+1) & 2) - 1);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000291 }
Rob Landley2c98c402006-02-17 05:12:03 +0000292
Eric Andersen5fa4db22003-10-23 06:52:01 +0000293 /* Correct for the initial -1, to get the final symbol length */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200294 length[i] = len_m1 + 1;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000295 }
Rob Landley2c98c402006-02-17 05:12:03 +0000296
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000297 /* Find largest and smallest lengths in this group */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000298 minLen = maxLen = length[0];
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000299 for (i = 1; i < symCount; i++) {
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200300 if (length[i] > maxLen)
301 maxLen = length[i];
302 else if (length[i] < minLen)
303 minLen = length[i];
Glenn L McGrath60bce492002-11-03 07:28:38 +0000304 }
Rob Landley2c98c402006-02-17 05:12:03 +0000305
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000306 /* Calculate permute[], base[], and limit[] tables from length[].
307 *
Eric Andersenaff114c2004-04-14 17:51:38 +0000308 * permute[] is the lookup table for converting Huffman coded symbols
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000309 * into decoded symbols. base[] is the amount to subtract from the
Eric Andersenaff114c2004-04-14 17:51:38 +0000310 * value of a Huffman symbol of a given length when using permute[].
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000311 *
312 * limit[] indicates the largest numerical value a symbol with a given
Eric Andersenaff114c2004-04-14 17:51:38 +0000313 * number of bits can have. This is how the Huffman codes can vary in
Eric Andersen5fa4db22003-10-23 06:52:01 +0000314 * length: each code with a value>limit[length] needs another bit.
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000315 */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000316 hufGroup = bd->groups + j;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000317 hufGroup->minLen = minLen;
318 hufGroup->maxLen = maxLen;
Rob Landley2c98c402006-02-17 05:12:03 +0000319
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000320 /* Note that minLen can't be smaller than 1, so we adjust the base
321 and limit array pointers so we're not always wasting the first
Denys Vlasenko0c576972010-10-30 00:54:10 +0200322 entry. We do this again when using them (during symbol decoding). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000323 base = hufGroup->base - 1;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000324 limit = hufGroup->limit - 1;
Rob Landley2c98c402006-02-17 05:12:03 +0000325
Denys Vlasenko10ad6222017-04-17 16:13:32 +0200326 /* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000327 pp = 0;
328 for (i = minLen; i <= maxLen; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200329 int k;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000330 temp[i] = limit[i] = 0;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200331 for (k = 0; k < symCount; k++)
332 if (length[k] == i)
333 hufGroup->permute[pp++] = k;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000334 }
Rob Landley2c98c402006-02-17 05:12:03 +0000335
Eric Andersen5fa4db22003-10-23 06:52:01 +0000336 /* Count symbols coded for at each bit length */
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000337 /* NB: in pathological cases, temp[8] can end ip being 256.
338 * That's why uint8_t is too small for temp[]. */
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200339 for (i = 0; i < symCount; i++)
340 temp[length[i]]++;
Rob Landley2c98c402006-02-17 05:12:03 +0000341
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000342 /* Calculate limit[] (the largest symbol-coding value at each bit
343 * length, which is (previous limit<<1)+symbols at this level), and
344 * base[] (number of symbols to ignore at each bit length, which is
Eric Andersen5fa4db22003-10-23 06:52:01 +0000345 * limit minus the cumulative count of symbols coded for already). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000346 pp = t = 0;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200347 for (i = minLen; i < maxLen;) {
348 unsigned temp_i = temp[i];
349
350 pp += temp_i;
Rob Landley2c98c402006-02-17 05:12:03 +0000351
Eric Andersen5fa4db22003-10-23 06:52:01 +0000352 /* We read the largest possible symbol size and then unget bits
353 after determining how many we need, and those extra bits could
354 be set to anything. (They're noise from future symbols.) At
355 each level we're really only interested in the first few bits,
356 so here we set all the trailing to-be-ignored bits to 1 so they
357 don't affect the value>limit[length] comparison. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000358 limit[i] = (pp << (maxLen - i)) - 1;
359 pp <<= 1;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200360 t += temp_i;
361 base[++i] = pp - t;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000362 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000363 limit[maxLen] = pp + temp[maxLen] - 1;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200364 limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000365 base[minLen] = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000366 }
Rob Landley2c98c402006-02-17 05:12:03 +0000367
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000368 /* We've finished reading and digesting the block header. Now read this
Eric Andersenaff114c2004-04-14 17:51:38 +0000369 block's Huffman coded symbols from the file and undo the Huffman coding
Denis Vlasenko52a43882007-10-10 20:53:41 +0000370 and run length encoding, saving the result into dbuf[dbufCount++] = uc */
Glenn L McGrath60bce492002-11-03 07:28:38 +0000371
Eric Andersen5fa4db22003-10-23 06:52:01 +0000372 /* Initialize symbol occurrence counters and symbol Move To Front table */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200373 /*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000374 for (i = 0; i < 256; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200375 byteCount[i] = 0;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200376 mtfSymbol[i] = (uint8_t)i;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000377 }
Rob Landley2c98c402006-02-17 05:12:03 +0000378
Eric Andersen5fa4db22003-10-23 06:52:01 +0000379 /* Loop through compressed symbols. */
Rob Landley2c98c402006-02-17 05:12:03 +0000380
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000381 runPos = dbufCount = selector = 0;
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000382 for (;;) {
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200383 struct group_data *hufGroup;
384 int *base, *limit;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200385 int nextSym;
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200386 uint8_t ngrp;
Rob Landley2c98c402006-02-17 05:12:03 +0000387
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000388 /* Fetch next Huffman coding group from list. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000389 symCount = GROUP_SIZE - 1;
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200390 if (selector >= nSelectors)
391 return RETVAL_DATA_ERROR;
392 ngrp = selectors[selector++];
393 if (ngrp >= groupCount) {
394 dbg("%d selectors[%d]:%d groupCount:%d",
395 __LINE__, selector-1, ngrp, groupCount);
396 return RETVAL_DATA_ERROR;
397 }
398 hufGroup = bd->groups + ngrp;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000399 base = hufGroup->base - 1;
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000400 limit = hufGroup->limit - 1;
Rob Landley2c98c402006-02-17 05:12:03 +0000401
Denys Vlasenko0c576972010-10-30 00:54:10 +0200402 continue_this_group:
Eric Andersenaff114c2004-04-14 17:51:38 +0000403 /* Read next Huffman-coded symbol. */
Rob Landley2c98c402006-02-17 05:12:03 +0000404
Eric Andersen5fa4db22003-10-23 06:52:01 +0000405 /* Note: It is far cheaper to read maxLen bits and back up than it is
Denys Vlasenko0c576972010-10-30 00:54:10 +0200406 to read minLen bits and then add additional bit at a time, testing
Eric Andersen5fa4db22003-10-23 06:52:01 +0000407 as we go. Because there is a trailing last block (with file CRC),
408 there is no danger of the overread causing an unexpected EOF for a
Denys Vlasenko0c576972010-10-30 00:54:10 +0200409 valid compressed file.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000410 */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200411 if (1) {
412 /* As a further optimization, we do the read inline
413 (falling back to a call to get_bits if the buffer runs dry).
414 */
415 int new_cnt;
416 while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) {
417 /* bd->inbufBitCount < hufGroup->maxLen */
418 if (bd->inbufPos == bd->inbufCount) {
419 nextSym = get_bits(bd, hufGroup->maxLen);
420 goto got_huff_bits;
421 }
422 bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
423 bd->inbufBitCount += 8;
424 };
425 bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */
426 nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1);
427 got_huff_bits: ;
428 } else { /* unoptimized equivalent */
429 nextSym = get_bits(bd, hufGroup->maxLen);
430 }
431 /* Figure how many bits are in next symbol and unget extras */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000432 i = hufGroup->minLen;
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200433 while (nextSym > limit[i])
434 ++i;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200435 j = hufGroup->maxLen - i;
436 if (j < 0)
437 return RETVAL_DATA_ERROR;
438 bd->inbufBitCount += j;
Rob Landley2c98c402006-02-17 05:12:03 +0000439
Eric Andersen5fa4db22003-10-23 06:52:01 +0000440 /* Huffman decode value to get nextSym (with bounds checking) */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200441 nextSym = (nextSym >> j) - base[i];
442 if ((unsigned)nextSym >= MAX_SYMBOLS)
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000443 return RETVAL_DATA_ERROR;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200444 nextSym = hufGroup->permute[nextSym];
Rob Landley2c98c402006-02-17 05:12:03 +0000445
Eric Andersen5fa4db22003-10-23 06:52:01 +0000446 /* We have now decoded the symbol, which indicates either a new literal
447 byte, or a repeated run of the most recent literal byte. First,
448 check if nextSym indicates a repeated run, and if so loop collecting
449 how many times to repeat the last literal. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000450 if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
Rob Landley2c98c402006-02-17 05:12:03 +0000451
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000452 /* If this is the start of a new run, zero out counter */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200453 if (runPos == 0) {
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000454 runPos = 1;
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200455 runCnt = 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000456 }
Rob Landley2c98c402006-02-17 05:12:03 +0000457
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000458 /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
459 each bit position, add 1 or 2 instead. For example,
460 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
461 You can make any bit pattern that way using 1 less symbol than
462 the basic or 0/1 method (except all bits 0, which would use no
463 symbols, but a run of length 0 doesn't mean anything in this
464 context). Thus space is saved. */
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200465 runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
Denys Vlasenko0402cb32017-10-22 18:23:23 +0200466//The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
467//This would be the fix (catches too large count way before it can overflow):
468// if (runCnt > bd->dbufSize) {
469// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
470// runCnt, bd->dbufSize);
471// return RETVAL_DATA_ERROR;
472// }
473 if (runPos < bd->dbufSize) runPos <<= 1;
Rob Landleya8b98d62004-11-16 12:07:04 +0000474 goto end_of_huffman_loop;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000475 }
Rob Landley2c98c402006-02-17 05:12:03 +0000476
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000477 /* When we hit the first non-run symbol after a run, we now know
478 how many times to repeat the last literal, so append that many
479 copies to our buffer of decoded symbols (dbuf) now. (The last
480 literal used is the one at the head of the mtfSymbol array.) */
Denys Vlasenko0c576972010-10-30 00:54:10 +0200481 if (runPos != 0) {
482 uint8_t tmp_byte;
Denys Vlasenko0402cb32017-10-22 18:23:23 +0200483 if (dbufCount + runCnt > bd->dbufSize) {
484 dbg("dbufCount:%u+runCnt:%u %u > dbufSize:%u RETVAL_DATA_ERROR",
485 dbufCount, runCnt, dbufCount + runCnt, bd->dbufSize);
Denys Vlasenko932e2332013-10-06 22:53:14 +0200486 return RETVAL_DATA_ERROR;
487 }
Denys Vlasenko0c576972010-10-30 00:54:10 +0200488 tmp_byte = symToByte[mtfSymbol[0]];
Denys Vlasenkof16727e2010-10-30 00:55:02 +0200489 byteCount[tmp_byte] += runCnt;
Denys Vlasenko0402cb32017-10-22 18:23:23 +0200490 while ((int)--runCnt >= 0)
491 dbuf[dbufCount++] = (uint32_t)tmp_byte;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200492 runPos = 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000493 }
Rob Landley2c98c402006-02-17 05:12:03 +0000494
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000495 /* Is this the terminating symbol? */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000496 if (nextSym > symTotal) break;
Rob Landley2c98c402006-02-17 05:12:03 +0000497
Eric Andersen5fa4db22003-10-23 06:52:01 +0000498 /* At this point, nextSym indicates a new literal character. Subtract
499 one to get the position in the MTF array at which this literal is
500 currently to be found. (Note that the result can't be -1 or 0,
501 because 0 and 1 are RUNA and RUNB. But another instance of the
502 first symbol in the mtf array, position 0, would have been handled
503 as part of a run above. Therefore 1 unused mtf position minus
504 2 non-literal nextSym values equals -1.) */
Denys Vlasenko0402cb32017-10-22 18:23:23 +0200505 if (dbufCount >= bd->dbufSize) return RETVAL_DATA_ERROR;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000506 i = nextSym - 1;
507 uc = mtfSymbol[i];
Rob Landley2c98c402006-02-17 05:12:03 +0000508
Eric Andersen5fa4db22003-10-23 06:52:01 +0000509 /* Adjust the MTF array. Since we typically expect to move only a
510 * small number of symbols, and are bound by 256 in any case, using
511 * memmove here would typically be bigger and slower due to function
512 * call overhead and other assorted setup costs. */
Eric Andersen1acfb722003-10-18 01:59:46 +0000513 do {
514 mtfSymbol[i] = mtfSymbol[i-1];
515 } while (--i);
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000516 mtfSymbol[0] = uc;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000517 uc = symToByte[uc];
Rob Landley2c98c402006-02-17 05:12:03 +0000518
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000519 /* We have our literal byte. Save it into dbuf. */
520 byteCount[uc]++;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200521 dbuf[dbufCount++] = (uint32_t)uc;
Rob Landley2c98c402006-02-17 05:12:03 +0000522
Rob Landleyf856eab2006-02-17 03:43:49 +0000523 /* Skip group initialization if we're not done with this group. Done
524 * this way to avoid compiler warning. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000525 end_of_huffman_loop:
Denys Vlasenko0c576972010-10-30 00:54:10 +0200526 if (--symCount >= 0) goto continue_this_group;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000527 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000528
Eric Andersenaff114c2004-04-14 17:51:38 +0000529 /* At this point, we've read all the Huffman-coded symbols (and repeated
Denis Vlasenko246b5c32007-04-10 17:18:12 +0000530 runs) for this block from the input stream, and decoded them into the
Eric Andersen5fa4db22003-10-23 06:52:01 +0000531 intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
532 Now undo the Burrows-Wheeler transform on dbuf.
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000533 See http://dogma.net/markn/articles/bwt/bwt.htm
534 */
Rob Landley2c98c402006-02-17 05:12:03 +0000535
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000536 /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000537 j = 0;
538 for (i = 0; i < 256; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200539 int tmp_count = j + byteCount[i];
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000540 byteCount[i] = j;
Denys Vlasenko0c576972010-10-30 00:54:10 +0200541 j = tmp_count;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000542 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000543
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000544 /* Figure out what order dbuf would be in if we sorted it. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000545 for (i = 0; i < dbufCount; i++) {
Denys Vlasenko0c576972010-10-30 00:54:10 +0200546 uint8_t tmp_byte = (uint8_t)dbuf[i];
547 int tmp_count = byteCount[tmp_byte];
548 dbuf[tmp_count] |= (i << 8);
549 byteCount[tmp_byte] = tmp_count + 1;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000550 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000551
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000552 /* Decode first byte by hand to initialize "previous" byte. Note that it
553 doesn't get output, and if the first three characters are identical
Eric Andersen5fa4db22003-10-23 06:52:01 +0000554 it doesn't qualify as a run (hence writeRunCountdown=5). */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000555 if (dbufCount) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200556 uint32_t tmp;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +0000557 if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200558 tmp = dbuf[origPtr];
559 bd->writeCurrent = (uint8_t)tmp;
560 bd->writePos = (tmp >> 8);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000561 bd->writeRunCountdown = 5;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000562 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000563 bd->writeCount = dbufCount;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000564
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000565 return RETVAL_OK;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000566}
567
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200568/* Undo Burrows-Wheeler transform on intermediate buffer to produce output.
Eric Andersen5fa4db22003-10-23 06:52:01 +0000569 If start_bunzip was initialized with out_fd=-1, then up to len bytes of
570 data are written to outbuf. Return value is number of bytes written or
571 error (all errors are negative numbers). If out_fd!=-1, outbuf and len
572 are ignored, data is written to out_fd and return is RETVAL_OK or error.
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200573
574 NB: read_bunzip returns < 0 on error, or the number of *unfilled* bytes
575 in outbuf. IOW: on EOF returns len ("all bytes are not filled"), not 0.
576 (Why? This allows to get rid of one local variable)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000577*/
Denys Vlasenko97c2a6d2018-11-02 14:20:54 +0100578static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000579{
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200580 const uint32_t *dbuf;
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200581 int pos, current, previous;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200582 uint32_t CRC;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000583
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200584 /* If we already have error/end indicator, return it */
585 if (bd->writeCount < 0)
586 return bd->writeCount;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000587
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000588 dbuf = bd->dbuf;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200589
590 /* Register-cached state (hopefully): */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000591 pos = bd->writePos;
592 current = bd->writeCurrent;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200593 CRC = bd->writeCRC; /* small loss on x86-32 (not enough regs), win on x86-64 */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000594
595 /* We will always have pending decoded data to write into the output
596 buffer unless this is the very first call (in which case we haven't
Eric Andersenaff114c2004-04-14 17:51:38 +0000597 Huffman-decoded a block into the intermediate buffer yet). */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000598 if (bd->writeCopies) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000599
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200600 dec_writeCopies:
Eric Andersen5fa4db22003-10-23 06:52:01 +0000601 /* Inside the loop, writeCopies means extra copies (beyond 1) */
602 --bd->writeCopies;
Rob Landleyf856eab2006-02-17 03:43:49 +0000603
Eric Andersen5fa4db22003-10-23 06:52:01 +0000604 /* Loop outputting bytes */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +0000605 for (;;) {
Rob Landleyf856eab2006-02-17 03:43:49 +0000606
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200607 /* If the output buffer is full, save cached state and return */
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200608 if (--len < 0) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200609 /* Unlikely branch.
610 * Use of "goto" instead of keeping code here
611 * helps compiler to realize this. */
612 goto outbuf_full;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000613 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000614
Eric Andersen5fa4db22003-10-23 06:52:01 +0000615 /* Write next byte into output buffer, updating CRC */
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200616 *outbuf++ = current;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200617 CRC = (CRC << 8) ^ bd->crc32Table[(CRC >> 24) ^ current];
Rob Landleyf856eab2006-02-17 03:43:49 +0000618
Eric Andersen5fa4db22003-10-23 06:52:01 +0000619 /* Loop now if we're outputting multiple copies of this byte */
620 if (bd->writeCopies) {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200621 /* Unlikely branch */
622 /*--bd->writeCopies;*/
623 /*continue;*/
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200624 /* Same, but (ab)using other existing --writeCopies operation
625 * (and this if() compiles into just test+branch pair): */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200626 goto dec_writeCopies;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000627 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000628 decode_next_byte:
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200629 if (--bd->writeCount < 0)
630 break; /* input block is fully consumed, need next one */
631
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000632 /* Follow sequence vector to undo Burrows-Wheeler transform */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000633 previous = current;
634 pos = dbuf[pos];
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200635 current = (uint8_t)pos;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000636 pos >>= 8;
Rob Landleyf856eab2006-02-17 03:43:49 +0000637
Denis Vlasenko52a43882007-10-10 20:53:41 +0000638 /* After 3 consecutive copies of the same byte, the 4th
639 * is a repeat count. We count down from 4 instead
Eric Andersen5fa4db22003-10-23 06:52:01 +0000640 * of counting up because testing for non-zero is faster */
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200641 if (--bd->writeRunCountdown != 0) {
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000642 if (current != previous)
643 bd->writeRunCountdown = 4;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000644 } else {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200645 /* Unlikely branch */
Eric Andersen5fa4db22003-10-23 06:52:01 +0000646 /* We have a repeated run, this byte indicates the count */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000647 bd->writeCopies = current;
648 current = previous;
649 bd->writeRunCountdown = 5;
Rob Landleyf856eab2006-02-17 03:43:49 +0000650
Eric Andersen5fa4db22003-10-23 06:52:01 +0000651 /* Sometimes there are just 3 bytes (run length 0) */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000652 if (!bd->writeCopies) goto decode_next_byte;
Rob Landleyf856eab2006-02-17 03:43:49 +0000653
Eric Andersen5fa4db22003-10-23 06:52:01 +0000654 /* Subtract the 1 copy we'd output anyway to get extras */
655 --bd->writeCopies;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000656 }
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200657 } /* for(;;) */
Rob Landleyf856eab2006-02-17 03:43:49 +0000658
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200659 /* Decompression of this input block completed successfully */
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200660 bd->writeCRC = CRC = ~CRC;
661 bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ CRC;
Rob Landleyf856eab2006-02-17 03:43:49 +0000662
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200663 /* If this block had a CRC error, force file level CRC error */
664 if (CRC != bd->headerCRC) {
Denis Vlasenko52a43882007-10-10 20:53:41 +0000665 bd->totalCRC = bd->headerCRC + 1;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000666 return RETVAL_LAST_BLOCK;
667 }
Glenn L McGrath60bce492002-11-03 07:28:38 +0000668 }
Eric Andersen5fa4db22003-10-23 06:52:01 +0000669
Eric Andersenaff114c2004-04-14 17:51:38 +0000670 /* Refill the intermediate buffer by Huffman-decoding next block of input */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200671 {
672 int r = get_next_block(bd);
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200673 if (r) { /* error/end */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200674 bd->writeCount = r;
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200675 return (r != RETVAL_LAST_BLOCK) ? r : len;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200676 }
Eric Andersen5fa4db22003-10-23 06:52:01 +0000677 }
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200678
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200679 CRC = ~0;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000680 pos = bd->writePos;
681 current = bd->writeCurrent;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000682 goto decode_next_byte;
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200683
684 outbuf_full:
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200685 /* Output buffer is full, save cached state and return */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200686 bd->writePos = pos;
687 bd->writeCurrent = current;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200688 bd->writeCRC = CRC;
689
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200690 bd->writeCopies++;
Denys Vlasenkobf3bec52010-10-29 18:16:29 +0200691
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200692 return 0;
Glenn L McGrath60bce492002-11-03 07:28:38 +0000693}
694
Eric Andersen5fa4db22003-10-23 06:52:01 +0000695/* Allocate the structure, read file header. If in_fd==-1, inbuf must contain
696 a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are
697 ignored, and data is read from file handle into temporary buffer. */
Rob Landleyf856eab2006-02-17 03:43:49 +0000698
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000699/* Because bunzip2 is used for help text unpacking, and because bb_show_usage()
700 should work for NOFORK applets too, we must be extremely careful to not leak
701 any allocations! */
Ron Yorstonc339c7f2018-11-02 14:14:31 +0100702static int FAST_FUNC start_bunzip(
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200703 void *jmpbuf,
704 bunzip_data **bdp,
705 int in_fd,
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200706 const void *inbuf, int len)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000707{
708 bunzip_data *bd;
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000709 unsigned i;
710 enum {
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000711 BZh0 = ('B' << 24) + ('Z' << 16) + ('h' << 8) + '0',
712 h0 = ('h' << 8) + '0',
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000713 };
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000714
715 /* Figure out how much data to allocate */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000716 i = sizeof(bunzip_data);
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200717 if (in_fd != -1)
718 i += IOBUF_SIZE;
Rob Landleyf856eab2006-02-17 03:43:49 +0000719
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000720 /* Allocate bunzip_data. Most fields initialize to zero. */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000721 bd = *bdp = xzalloc(i);
Rob Landleyf856eab2006-02-17 03:43:49 +0000722
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200723 bd->jmpbuf = jmpbuf;
724
Eric Andersen5fa4db22003-10-23 06:52:01 +0000725 /* Setup input buffer */
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000726 bd->in_fd = in_fd;
727 if (-1 == in_fd) {
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000728 /* in this case, bd->inbuf is read-only */
729 bd->inbuf = (void*)inbuf; /* cast away const-ness */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200730 } else {
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200731 bd->inbuf = (uint8_t*)(bd + 1);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200732 memcpy(bd->inbuf, inbuf, len);
733 }
734 bd->inbufCount = len;
Rob Landleyf856eab2006-02-17 03:43:49 +0000735
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000736 /* Init the CRC32 table (big endian) */
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000737 crc32_filltable(bd->crc32Table, 1);
Rob Landleyf856eab2006-02-17 03:43:49 +0000738
Eric Andersen5fa4db22003-10-23 06:52:01 +0000739 /* Ensure that file starts with "BZh['1'-'9']." */
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000740 /* Update: now caller verifies 1st two bytes, makes .gz/.bz2
741 * integration easier */
742 /* was: */
743 /* i = get_bits(bd, 32); */
744 /* if ((unsigned)(i - BZh0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA; */
745 i = get_bits(bd, 16);
746 if ((unsigned)(i - h0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000747
Denis Vlasenko86d88c02008-06-28 18:10:09 +0000748 /* Fourth byte (ascii '1'-'9') indicates block size in units of 100k of
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000749 uncompressed data. Allocate intermediate buffer for block. */
Denis Vlasenkoe9ad84d2008-08-05 13:10:34 +0000750 /* bd->dbufSize = 100000 * (i - BZh0); */
751 bd->dbufSize = 100000 * (i - h0);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000752
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000753 /* Cannot use xmalloc - may leak bd in NOFORK case! */
Denys Vlasenko36ef0a62010-10-29 16:05:05 +0200754 bd->dbuf = malloc_or_warn(bd->dbufSize * sizeof(bd->dbuf[0]));
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000755 if (!bd->dbuf) {
756 free(bd);
757 xfunc_die();
758 }
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000759 return RETVAL_OK;
760}
761
Ron Yorstonc339c7f2018-11-02 14:14:31 +0100762static void FAST_FUNC dealloc_bunzip(bunzip_data *bd)
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000763{
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000764 free(bd->dbuf);
765 free(bd);
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000766}
767
768
769/* Decompress src_fd to dst_fd. Stops at end of bzip data, not end of file. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000770IF_DESKTOP(long long) int FAST_FUNC
Denys Vlasenkob4c11c12014-12-07 00:44:00 +0100771unpack_bz2_stream(transformer_state_t *xstate)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000772{
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000773 IF_DESKTOP(long long total_written = 0;)
Denys Vlasenko4d4d1a02010-11-01 02:19:47 +0100774 bunzip_data *bd;
Eric Andersen5fa4db22003-10-23 06:52:01 +0000775 char *outbuf;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000776 int i;
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200777 unsigned len;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000778
Denys Vlasenkob4c11c12014-12-07 00:44:00 +0100779 if (check_signature16(xstate, BZIP2_MAGIC))
Denys Vlasenko8a6a2f92012-03-06 16:27:48 +0100780 return -1;
781
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000782 outbuf = xmalloc(IOBUF_SIZE);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200783 len = 0;
784 while (1) { /* "Process one BZ... stream" loop */
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200785 jmp_buf jmpbuf;
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200786
Denys Vlasenko38ccd6a2018-04-08 20:02:01 +0200787 /* Setup for I/O error handling via longjmp */
788 i = setjmp(jmpbuf);
789 if (i == 0)
790 i = start_bunzip(&jmpbuf, &bd, xstate->src_fd, outbuf + 2, len);
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200791
792 if (i == 0) {
793 while (1) { /* "Produce some output bytes" loop */
794 i = read_bunzip(bd, outbuf, IOBUF_SIZE);
Denys Vlasenko1014a9a2010-10-29 19:01:58 +0200795 if (i < 0) /* error? */
796 break;
797 i = IOBUF_SIZE - i; /* number of bytes produced */
798 if (i == 0) /* EOF? */
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200799 break;
Denys Vlasenkob4c11c12014-12-07 00:44:00 +0100800 if (i != transformer_write(xstate, outbuf, i)) {
Denys Vlasenko8531c432010-11-01 01:38:54 +0100801 i = RETVAL_SHORT_WRITE;
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200802 goto release_mem;
803 }
804 IF_DESKTOP(total_written += i;)
Eric Andersen5fa4db22003-10-23 06:52:01 +0000805 }
806 }
Rob Landleyf856eab2006-02-17 03:43:49 +0000807
Denys Vlasenkoc531b9a2011-10-31 01:05:16 +0100808 if (i != RETVAL_LAST_BLOCK
809 /* Observed case when i == RETVAL_OK:
810 * "bzcat z.bz2", where "z.bz2" is a bzipped zero-length file
811 * (to be exact, z.bz2 is exactly these 14 bytes:
Denys Vlasenko97c2a6d2018-11-02 14:20:54 +0100812 * 42 5a 68 39 17 72 45 38 50 90 00 00 00 00).
Denys Vlasenkoc531b9a2011-10-31 01:05:16 +0100813 */
814 && i != RETVAL_OK
815 ) {
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200816 bb_error_msg("bunzip error %d", i);
817 break;
818 }
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000819 if (bd->headerCRC != bd->totalCRC) {
James Byrne69374872019-07-02 11:35:03 +0200820 bb_simple_error_msg("CRC error");
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200821 break;
Glenn L McGrath1c834402003-10-28 23:32:12 +0000822 }
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200823
824 /* Successfully unpacked one BZ stream */
825 i = RETVAL_OK;
826
827 /* Do we have "BZ..." after last processed byte?
828 * pbzip2 (parallelized bzip2) produces such files.
829 */
830 len = bd->inbufCount - bd->inbufPos;
831 memcpy(outbuf, &bd->inbuf[bd->inbufPos], len);
832 if (len < 2) {
Denys Vlasenkob4c11c12014-12-07 00:44:00 +0100833 if (safe_read(xstate->src_fd, outbuf + len, 2 - len) != 2 - len)
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200834 break;
835 len = 2;
836 }
837 if (*(uint16_t*)outbuf != BZIP2_MAGIC) /* "BZ"? */
838 break;
839 dealloc_bunzip(bd);
840 len -= 2;
Glenn L McGrath1c834402003-10-28 23:32:12 +0000841 }
Denys Vlasenkocaddfc82010-10-28 23:08:53 +0200842
843 release_mem:
Denis Vlasenkoc6758a02007-04-10 21:40:19 +0000844 dealloc_bunzip(bd);
Eric Andersen5fa4db22003-10-23 06:52:01 +0000845 free(outbuf);
Glenn L McGrath1c834402003-10-28 23:32:12 +0000846
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000847 return i ? i : IF_DESKTOP(total_written) + 0;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000848}
849
Ron Yorstonc339c7f2018-11-02 14:14:31 +0100850char* FAST_FUNC
851unpack_bz2_data(const char *packed, int packed_len, int unpacked_len)
852{
853 char *outbuf = NULL;
854 bunzip_data *bd;
855 int i;
856 jmp_buf jmpbuf;
857
858 /* Setup for I/O error handling via longjmp */
859 i = setjmp(jmpbuf);
860 if (i == 0) {
861 i = start_bunzip(&jmpbuf,
862 &bd,
863 /* src_fd: */ -1,
864 /* inbuf: */ packed,
865 /* len: */ packed_len
866 );
867 }
868 /* read_bunzip can longjmp and end up here with i != 0
869 * on read data errors! Not trivial */
870 if (i == 0) {
871 /* Cannot use xmalloc: will leak bd in NOFORK case! */
872 outbuf = malloc_or_warn(unpacked_len);
873 if (outbuf)
874 read_bunzip(bd, outbuf, unpacked_len);
875 }
876 dealloc_bunzip(bd);
877 return outbuf;
878}
879
Eric Andersen5fa4db22003-10-23 06:52:01 +0000880#ifdef TESTING
Glenn L McGrath60bce492002-11-03 07:28:38 +0000881
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000882static char *const bunzip_errors[] = {
883 NULL, "Bad file checksum", "Not bzip data",
884 "Unexpected input EOF", "Unexpected output EOF", "Data error",
885 "Out of memory", "Obsolete (pre 0.9.5) bzip format not supported"
886};
Glenn L McGrath237ae422002-11-03 14:05:15 +0000887
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000888/* Dumb little test thing, decompress stdin to stdout */
Bernhard Reutner-Fischerfebe3c42007-04-04 20:52:03 +0000889int main(int argc, char **argv)
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000890{
Eric Andersen5fa4db22003-10-23 06:52:01 +0000891 char c;
892
Denys Vlasenko8a6a2f92012-03-06 16:27:48 +0100893 int i = unpack_bz2_stream(0, 1);
Denis Vlasenkob38cf3f2007-04-10 17:16:33 +0000894 if (i < 0)
Denis Vlasenkof5d8c902008-06-26 14:32:57 +0000895 fprintf(stderr, "%s\n", bunzip_errors[-i]);
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +0000896 else if (read(STDIN_FILENO, &c, 1))
Denis Vlasenkof5d8c902008-06-26 14:32:57 +0000897 fprintf(stderr, "Trailing garbage ignored\n");
Eric Andersen5fa4db22003-10-23 06:52:01 +0000898 return -i;
Eric Andersen0d6d88a2003-10-18 01:58:35 +0000899}
900#endif