1 /**************************************************************************
2  *
3  * Copyright 2013-2014 RAD Game Tools and Valve Software
4  * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26 
27 #include "miniz.h"
28 
29 #ifdef __cplusplus
30 extern "C" {
31 #endif
32 
33 /* ------------------- Low-level Decompression (completely independent from all compression API's) */
34 
35 #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
36 #define TINFL_MEMSET(p, c, l) memset(p, c, l)
37 
38 #define TINFL_CR_BEGIN  \
39     switch (r->m_state) \
40     {                   \
41         case 0:
42 #define TINFL_CR_RETURN(state_index, result) \
43     do                                       \
44     {                                        \
45         status = result;                     \
46         r->m_state = state_index;            \
47         goto common_exit;                    \
48         case state_index:;                   \
49     }                                        \
50     MZ_MACRO_END
51 #define TINFL_CR_RETURN_FOREVER(state_index, result) \
52     do                                               \
53     {                                                \
54         for (;;)                                     \
55         {                                            \
56             TINFL_CR_RETURN(state_index, result);    \
57         }                                            \
58     }                                                \
59     MZ_MACRO_END
60 #define TINFL_CR_FINISH }
61 
62 #define TINFL_GET_BYTE(state_index, c)                                                                                                                           \
63     do                                                                                                                                                           \
64     {                                                                                                                                                            \
65         while (pIn_buf_cur >= pIn_buf_end)                                                                                                                       \
66         {                                                                                                                                                        \
67             TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \
68         }                                                                                                                                                        \
69         c = *pIn_buf_cur++;                                                                                                                                      \
70     }                                                                                                                                                            \
71     MZ_MACRO_END
72 
73 #define TINFL_NEED_BITS(state_index, n)                \
74     do                                                 \
75     {                                                  \
76         mz_uint c;                                     \
77         TINFL_GET_BYTE(state_index, c);                \
78         bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
79         num_bits += 8;                                 \
80     } while (num_bits < (mz_uint)(n))
81 #define TINFL_SKIP_BITS(state_index, n)      \
82     do                                       \
83     {                                        \
84         if (num_bits < (mz_uint)(n))         \
85         {                                    \
86             TINFL_NEED_BITS(state_index, n); \
87         }                                    \
88         bit_buf >>= (n);                     \
89         num_bits -= (n);                     \
90     }                                        \
91     MZ_MACRO_END
92 #define TINFL_GET_BITS(state_index, b, n)    \
93     do                                       \
94     {                                        \
95         if (num_bits < (mz_uint)(n))         \
96         {                                    \
97             TINFL_NEED_BITS(state_index, n); \
98         }                                    \
99         b = bit_buf & ((1 << (n)) - 1);      \
100         bit_buf >>= (n);                     \
101         num_bits -= (n);                     \
102     }                                        \
103     MZ_MACRO_END
104 
105 /* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */
106 /* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */
107 /* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */
108 /* bit buffer contains >=15 bits (deflate's max. Huffman code size). */
109 #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff)                             \
110     do                                                                         \
111     {                                                                          \
112         temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)];     \
113         if (temp >= 0)                                                         \
114         {                                                                      \
115             code_len = temp >> 9;                                              \
116             if ((code_len) && (num_bits >= code_len))                          \
117                 break;                                                         \
118         }                                                                      \
119         else if (num_bits > TINFL_FAST_LOOKUP_BITS)                            \
120         {                                                                      \
121             code_len = TINFL_FAST_LOOKUP_BITS;                                 \
122             do                                                                 \
123             {                                                                  \
124                 temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
125             } while ((temp < 0) && (num_bits >= (code_len + 1)));              \
126             if (temp >= 0)                                                     \
127                 break;                                                         \
128         }                                                                      \
129         TINFL_GET_BYTE(state_index, c);                                        \
130         bit_buf |= (((tinfl_bit_buf_t)c) << num_bits);                         \
131         num_bits += 8;                                                         \
132     } while (num_bits < 15);
133 
134 /* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */
135 /* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */
136 /* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */
137 /* The slow path is only executed at the very end of the input buffer. */
138 /* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */
139 /* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */
140 #define TINFL_HUFF_DECODE(state_index, sym, pHuff)                                                                                  \
141     do                                                                                                                              \
142     {                                                                                                                               \
143         int temp;                                                                                                                   \
144         mz_uint code_len, c;                                                                                                        \
145         if (num_bits < 15)                                                                                                          \
146         {                                                                                                                           \
147             if ((pIn_buf_end - pIn_buf_cur) < 2)                                                                                    \
148             {                                                                                                                       \
149                 TINFL_HUFF_BITBUF_FILL(state_index, pHuff);                                                                         \
150             }                                                                                                                       \
151             else                                                                                                                    \
152             {                                                                                                                       \
153                 bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
154                 pIn_buf_cur += 2;                                                                                                   \
155                 num_bits += 16;                                                                                                     \
156             }                                                                                                                       \
157         }                                                                                                                           \
158         if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)                                               \
159             code_len = temp >> 9, temp &= 511;                                                                                      \
160         else                                                                                                                        \
161         {                                                                                                                           \
162             code_len = TINFL_FAST_LOOKUP_BITS;                                                                                      \
163             do                                                                                                                      \
164             {                                                                                                                       \
165                 temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)];                                                      \
166             } while (temp < 0);                                                                                                     \
167         }                                                                                                                           \
168         sym = temp;                                                                                                                 \
169         bit_buf >>= code_len;                                                                                                       \
170         num_bits -= code_len;                                                                                                       \
171     }                                                                                                                               \
172     MZ_MACRO_END
173 
tinfl_decompress(tinfl_decompressor * r,const mz_uint8 * pIn_buf_next,size_t * pIn_buf_size,mz_uint8 * pOut_buf_start,mz_uint8 * pOut_buf_next,size_t * pOut_buf_size,const mz_uint32 decomp_flags)174 tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
175 {
176     static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 };
177     static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 };
178     static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 };
179     static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
180     static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
181     static const int s_min_table_sizes[3] = { 257, 1, 4 };
182 
183     tinfl_status status = TINFL_STATUS_FAILED;
184     mz_uint32 num_bits, dist, counter, num_extra;
185     tinfl_bit_buf_t bit_buf;
186     const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
187     mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
188     size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
189 
190     /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */
191     if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start))
192     {
193         *pIn_buf_size = *pOut_buf_size = 0;
194         return TINFL_STATUS_BAD_PARAM;
195     }
196 
197     num_bits = r->m_num_bits;
198     bit_buf = r->m_bit_buf;
199     dist = r->m_dist;
200     counter = r->m_counter;
201     num_extra = r->m_num_extra;
202     dist_from_out_buf_start = r->m_dist_from_out_buf_start;
203     TINFL_CR_BEGIN
204 
205     bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
206     r->m_z_adler32 = r->m_check_adler32 = 1;
207     if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
208     {
209         TINFL_GET_BYTE(1, r->m_zhdr0);
210         TINFL_GET_BYTE(2, r->m_zhdr1);
211         counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
212 //        if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
213 //            counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
214         /* rewritten to avoid compilation warning */
215         if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
216             mz_uint32 t = (1U << (8U + (r->m_zhdr0 >> 4)));
217             counter |= ((t > 32768U) || ((out_buf_size_mask + 1) < (size_t)(t)));
218         }
219 
220         if (counter)
221         {
222             TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
223         }
224     }
225 
226     do
227     {
228         TINFL_GET_BITS(3, r->m_final, 3);
229         r->m_type = r->m_final >> 1;
230         if (r->m_type == 0)
231         {
232             TINFL_SKIP_BITS(5, num_bits & 7);
233             for (counter = 0; counter < 4; ++counter)
234             {
235                 if (num_bits)
236                     TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
237                 else
238                     TINFL_GET_BYTE(7, r->m_raw_header[counter]);
239             }
240             if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8))))
241             {
242                 TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
243             }
244             while ((counter) && (num_bits))
245             {
246                 TINFL_GET_BITS(51, dist, 8);
247                 while (pOut_buf_cur >= pOut_buf_end)
248                 {
249                     TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
250                 }
251                 *pOut_buf_cur++ = (mz_uint8)dist;
252                 counter--;
253             }
254             while (counter)
255             {
256                 size_t n;
257                 while (pOut_buf_cur >= pOut_buf_end)
258                 {
259                     TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
260                 }
261                 while (pIn_buf_cur >= pIn_buf_end)
262                 {
263                     TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS);
264                 }
265                 n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
266                 TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
267                 pIn_buf_cur += n;
268                 pOut_buf_cur += n;
269                 counter -= (mz_uint)n;
270             }
271         }
272         else if (r->m_type == 3)
273         {
274             TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
275         }
276         else
277         {
278             if (r->m_type == 1)
279             {
280                 mz_uint8 *p = r->m_tables[0].m_code_size;
281                 mz_uint i;
282                 r->m_table_sizes[0] = 288;
283                 r->m_table_sizes[1] = 32;
284                 TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
285                 for (i = 0; i <= 143; ++i)
286                     *p++ = 8;
287                 for (; i <= 255; ++i)
288                     *p++ = 9;
289                 for (; i <= 279; ++i)
290                     *p++ = 7;
291                 for (; i <= 287; ++i)
292                     *p++ = 8;
293             }
294             else
295             {
296                 for (counter = 0; counter < 3; counter++)
297                 {
298                     TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
299                     r->m_table_sizes[counter] += s_min_table_sizes[counter];
300                 }
301                 MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
302                 for (counter = 0; counter < r->m_table_sizes[2]; counter++)
303                 {
304                     mz_uint s;
305                     TINFL_GET_BITS(14, s, 3);
306                     r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
307                 }
308                 r->m_table_sizes[2] = 19;
309             }
310             for (; (int)r->m_type >= 0; r->m_type--)
311             {
312                 int tree_next, tree_cur;
313                 tinfl_huff_table *pTable;
314                 mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16];
315                 pTable = &r->m_tables[r->m_type];
316                 MZ_CLEAR_OBJ(total_syms);
317                 MZ_CLEAR_OBJ(pTable->m_look_up);
318                 MZ_CLEAR_OBJ(pTable->m_tree);
319                 for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
320                     total_syms[pTable->m_code_size[i]]++;
321                 used_syms = 0, total = 0;
322                 next_code[0] = next_code[1] = 0;
323                 for (i = 1; i <= 15; ++i)
324                 {
325                     used_syms += total_syms[i];
326                     next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
327                 }
328                 if ((65536 != total) && (used_syms > 1))
329                 {
330                     TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
331                 }
332                 for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
333                 {
334                     mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index];
335                     if (!code_size)
336                         continue;
337                     cur_code = next_code[code_size]++;
338                     for (l = code_size; l > 0; l--, cur_code >>= 1)
339                         rev_code = (rev_code << 1) | (cur_code & 1);
340                     if (code_size <= TINFL_FAST_LOOKUP_BITS)
341                     {
342                         mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
343                         while (rev_code < TINFL_FAST_LOOKUP_SIZE)
344                         {
345                             pTable->m_look_up[rev_code] = k;
346                             rev_code += (1 << code_size);
347                         }
348                         continue;
349                     }
350                     if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)]))
351                     {
352                         pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next;
353                         tree_cur = tree_next;
354                         tree_next -= 2;
355                     }
356                     rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
357                     for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
358                     {
359                         tree_cur -= ((rev_code >>= 1) & 1);
360                         if (!pTable->m_tree[-tree_cur - 1])
361                         {
362                             pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
363                             tree_cur = tree_next;
364                             tree_next -= 2;
365                         }
366                         else
367                             tree_cur = pTable->m_tree[-tree_cur - 1];
368                     }
369                     tree_cur -= ((rev_code >>= 1) & 1);
370                     pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
371                 }
372                 if (r->m_type == 2)
373                 {
374                     for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);)
375                     {
376                         mz_uint s;
377                         TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
378                         if (dist < 16)
379                         {
380                             r->m_len_codes[counter++] = (mz_uint8)dist;
381                             continue;
382                         }
383                         if ((dist == 16) && (!counter))
384                         {
385                             TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
386                         }
387                         num_extra = "\02\03\07"[dist - 16];
388                         TINFL_GET_BITS(18, s, num_extra);
389                         s += "\03\03\013"[dist - 16];
390                         TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
391                         counter += s;
392                     }
393                     if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
394                     {
395                         TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
396                     }
397                     TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]);
398                     TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
399                 }
400             }
401             for (;;)
402             {
403                 mz_uint8 *pSrc;
404                 for (;;)
405                 {
406                     if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
407                     {
408                         TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
409                         if (counter >= 256)
410                             break;
411                         while (pOut_buf_cur >= pOut_buf_end)
412                         {
413                             TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
414                         }
415                         *pOut_buf_cur++ = (mz_uint8)counter;
416                     }
417                     else
418                     {
419                         int sym2;
420                         mz_uint code_len;
421 #if TINFL_USE_64BIT_BITBUF
422                         if (num_bits < 30)
423                         {
424                             bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
425                             pIn_buf_cur += 4;
426                             num_bits += 32;
427                         }
428 #else
429                         if (num_bits < 15)
430                         {
431                             bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
432                             pIn_buf_cur += 2;
433                             num_bits += 16;
434                         }
435 #endif
436                         if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
437                             code_len = sym2 >> 9;
438                         else
439                         {
440                             code_len = TINFL_FAST_LOOKUP_BITS;
441                             do
442                             {
443                                 sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
444                             } while (sym2 < 0);
445                         }
446                         counter = sym2;
447                         bit_buf >>= code_len;
448                         num_bits -= code_len;
449                         if (counter & 256)
450                             break;
451 
452 #if !TINFL_USE_64BIT_BITBUF
453                         if (num_bits < 15)
454                         {
455                             bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
456                             pIn_buf_cur += 2;
457                             num_bits += 16;
458                         }
459 #endif
460                         if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
461                             code_len = sym2 >> 9;
462                         else
463                         {
464                             code_len = TINFL_FAST_LOOKUP_BITS;
465                             do
466                             {
467                                 sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
468                             } while (sym2 < 0);
469                         }
470                         bit_buf >>= code_len;
471                         num_bits -= code_len;
472 
473                         pOut_buf_cur[0] = (mz_uint8)counter;
474                         if (sym2 & 256)
475                         {
476                             pOut_buf_cur++;
477                             counter = sym2;
478                             break;
479                         }
480                         pOut_buf_cur[1] = (mz_uint8)sym2;
481                         pOut_buf_cur += 2;
482                     }
483                 }
484                 if ((counter &= 511) == 256)
485                     break;
486 
487                 num_extra = s_length_extra[counter - 257];
488                 counter = s_length_base[counter - 257];
489                 if (num_extra)
490                 {
491                     mz_uint extra_bits;
492                     TINFL_GET_BITS(25, extra_bits, num_extra);
493                     counter += extra_bits;
494                 }
495 
496                 TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
497                 num_extra = s_dist_extra[dist];
498                 dist = s_dist_base[dist];
499                 if (num_extra)
500                 {
501                     mz_uint extra_bits;
502                     TINFL_GET_BITS(27, extra_bits, num_extra);
503                     dist += extra_bits;
504                 }
505 
506                 dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
507                 if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
508                 {
509                     TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
510                 }
511 
512                 pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
513 
514                 if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
515                 {
516                     while (counter--)
517                     {
518                         while (pOut_buf_cur >= pOut_buf_end)
519                         {
520                             TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
521                         }
522                         *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
523                     }
524                     continue;
525                 }
526 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
527                 else if ((counter >= 9) && (counter <= dist))
528                 {
529                     const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
530                     do
531                     {
532 #ifdef MINIZ_UNALIGNED_USE_MEMCPY
533 						memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2);
534 #else
535                         ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
536                         ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
537 #endif
538                         pOut_buf_cur += 8;
539                     } while ((pSrc += 8) < pSrc_end);
540                     if ((counter &= 7) < 3)
541                     {
542                         if (counter)
543                         {
544                             pOut_buf_cur[0] = pSrc[0];
545                             if (counter > 1)
546                                 pOut_buf_cur[1] = pSrc[1];
547                             pOut_buf_cur += counter;
548                         }
549                         continue;
550                     }
551                 }
552 #endif
553                 while(counter>2)
554                 {
555                     pOut_buf_cur[0] = pSrc[0];
556                     pOut_buf_cur[1] = pSrc[1];
557                     pOut_buf_cur[2] = pSrc[2];
558                     pOut_buf_cur += 3;
559                     pSrc += 3;
560 					counter -= 3;
561                 }
562                 if (counter > 0)
563                 {
564                     pOut_buf_cur[0] = pSrc[0];
565                     if (counter > 1)
566                         pOut_buf_cur[1] = pSrc[1];
567                     pOut_buf_cur += counter;
568                 }
569             }
570         }
571     } while (!(r->m_final & 1));
572 
573     /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */
574     /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */
575     TINFL_SKIP_BITS(32, num_bits & 7);
576     while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8))
577     {
578         --pIn_buf_cur;
579         num_bits -= 8;
580     }
581     bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);
582     MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */
583 
584     if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
585     {
586         for (counter = 0; counter < 4; ++counter)
587         {
588             mz_uint s;
589             if (num_bits)
590                 TINFL_GET_BITS(41, s, 8);
591             else
592                 TINFL_GET_BYTE(42, s);
593             r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
594         }
595     }
596     TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
597 
598     TINFL_CR_FINISH
599 
600 common_exit:
601     /* As long as we aren't telling the caller that we NEED more input to make forward progress: */
602     /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */
603     /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */
604     if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS))
605     {
606         while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8))
607         {
608             --pIn_buf_cur;
609             num_bits -= 8;
610         }
611     }
612     r->m_num_bits = num_bits;
613     r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);
614     r->m_dist = dist;
615     r->m_counter = counter;
616     r->m_num_extra = num_extra;
617     r->m_dist_from_out_buf_start = dist_from_out_buf_start;
618     *pIn_buf_size = pIn_buf_cur - pIn_buf_next;
619     *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
620     if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
621     {
622         const mz_uint8 *ptr = pOut_buf_next;
623         size_t buf_len = *pOut_buf_size;
624         mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16;
625         size_t block_len = buf_len % 5552;
626         while (buf_len)
627         {
628             for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
629             {
630                 s1 += ptr[0], s2 += s1;
631                 s1 += ptr[1], s2 += s1;
632                 s1 += ptr[2], s2 += s1;
633                 s1 += ptr[3], s2 += s1;
634                 s1 += ptr[4], s2 += s1;
635                 s1 += ptr[5], s2 += s1;
636                 s1 += ptr[6], s2 += s1;
637                 s1 += ptr[7], s2 += s1;
638             }
639             for (; i < block_len; ++i)
640                 s1 += *ptr++, s2 += s1;
641             s1 %= 65521U, s2 %= 65521U;
642             buf_len -= block_len;
643             block_len = 5552;
644         }
645         r->m_check_adler32 = (s2 << 16) + s1;
646         if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32))
647             status = TINFL_STATUS_ADLER32_MISMATCH;
648     }
649     return status;
650 }
651 
652 /* Higher level helper functions. */
tinfl_decompress_mem_to_heap(const void * pSrc_buf,size_t src_buf_len,size_t * pOut_len,int flags)653 void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
654 {
655     tinfl_decompressor decomp;
656     void *pBuf = NULL, *pNew_buf;
657     size_t src_buf_ofs = 0, out_buf_capacity = 0;
658     *pOut_len = 0;
659     tinfl_init(&decomp);
660     for (;;)
661     {
662         size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
663         tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size,
664                                                (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
665         if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
666         {
667             MZ_FREE(pBuf);
668             *pOut_len = 0;
669             return NULL;
670         }
671         src_buf_ofs += src_buf_size;
672         *pOut_len += dst_buf_size;
673         if (status == TINFL_STATUS_DONE)
674             break;
675         new_out_buf_capacity = out_buf_capacity * 2;
676         if (new_out_buf_capacity < 128)
677             new_out_buf_capacity = 128;
678         pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
679         if (!pNew_buf)
680         {
681             MZ_FREE(pBuf);
682             *pOut_len = 0;
683             return NULL;
684         }
685         pBuf = pNew_buf;
686         out_buf_capacity = new_out_buf_capacity;
687     }
688     return pBuf;
689 }
690 
tinfl_decompress_mem_to_mem(void * pOut_buf,size_t out_buf_len,const void * pSrc_buf,size_t src_buf_len,int flags)691 size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
692 {
693     tinfl_decompressor decomp;
694     tinfl_status status;
695     tinfl_init(&decomp);
696     status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
697     return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
698 }
699 
tinfl_decompress_mem_to_callback(const void * pIn_buf,size_t * pIn_buf_size,tinfl_put_buf_func_ptr pPut_buf_func,void * pPut_buf_user,int flags)700 int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
701 {
702     int result = 0;
703     tinfl_decompressor decomp;
704     mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
705     size_t in_buf_ofs = 0, dict_ofs = 0;
706     if (!pDict)
707         return TINFL_STATUS_FAILED;
708     tinfl_init(&decomp);
709     for (;;)
710     {
711         size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
712         tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
713                                                (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
714         in_buf_ofs += in_buf_size;
715         if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
716             break;
717         if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
718         {
719             result = (status == TINFL_STATUS_DONE);
720             break;
721         }
722         dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
723     }
724     MZ_FREE(pDict);
725     *pIn_buf_size = in_buf_ofs;
726     return result;
727 }
728 
729 #ifndef MINIZ_NO_MALLOC
tinfl_decompressor_alloc()730 tinfl_decompressor *tinfl_decompressor_alloc()
731 {
732     tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor));
733     if (pDecomp)
734         tinfl_init(pDecomp);
735     return pDecomp;
736 }
737 
tinfl_decompressor_free(tinfl_decompressor * pDecomp)738 void tinfl_decompressor_free(tinfl_decompressor *pDecomp)
739 {
740     MZ_FREE(pDecomp);
741 }
742 #endif
743 
744 #ifdef __cplusplus
745 }
746 #endif
747