Path: blob/a-new-beginning/SharedDependencies/Sources/miniz/miniz.c
2 views
#include "miniz.h"1/**************************************************************************2*3* Copyright 2013-2014 RAD Game Tools and Valve Software4* Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC5* All Rights Reserved.6*7* Permission is hereby granted, free of charge, to any person obtaining a copy8* of this software and associated documentation files (the "Software"), to deal9* in the Software without restriction, including without limitation the rights10* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell11* copies of the Software, and to permit persons to whom the Software is12* furnished to do so, subject to the following conditions:13*14* The above copyright notice and this permission notice shall be included in15* all copies or substantial portions of the Software.16*17* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,19* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE20* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER21* 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 IN23* THE SOFTWARE.24*25**************************************************************************/26272829typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];30typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];31typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];3233#ifdef __cplusplus34extern "C" {35#endif3637/* ------------------- zlib-style API's */3839mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)40{41mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);42size_t block_len = buf_len % 5552;43if (!ptr)44return MZ_ADLER32_INIT;45while (buf_len)46{47for (i = 0; i + 7 < block_len; i += 8, ptr += 8)48{49s1 += ptr[0], s2 += s1;50s1 += ptr[1], s2 += s1;51s1 += ptr[2], s2 += s1;52s1 += ptr[3], s2 += s1;53s1 += ptr[4], s2 += s1;54s1 += ptr[5], s2 += s1;55s1 += ptr[6], s2 += s1;56s1 += ptr[7], s2 += s1;57}58for (; i < block_len; ++i)59s1 += *ptr++, s2 += s1;60s1 %= 65521U, s2 %= 65521U;61buf_len -= block_len;62block_len = 5552;63}64return (s2 << 16) + s1;65}6667/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */68#if 069mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)70{71static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,720xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };73mz_uint32 crcu32 = (mz_uint32)crc;74if (!ptr)75return MZ_CRC32_INIT;76crcu32 = ~crcu32;77while (buf_len--)78{79mz_uint8 b = *ptr++;80crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];81crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];82}83return ~crcu32;84}85#elif defined(USE_EXTERNAL_MZCRC)86/* If USE_EXTERNAL_CRC is defined, an external module will export the87* mz_crc32() symbol for us to use, e.g. an SSE-accelerated version.88* Depending on the impl, it may be necessary to ~ the input/output crc values.89*/90mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len);91#else92/* Faster, but larger CPU cache footprint.93*/94mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)95{96static const mz_uint32 s_crc_table[256] =97{980x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535,990x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,1000xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D,1010x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,1020x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,1030xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,1040xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC,1050x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,1060x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB,1070xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,1080x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB,1090x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,1100x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA,1110xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE,1120xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,1130x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,1140x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409,1150xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,1160xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739,1170x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,1180xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268,1190x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0,1200x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8,1210xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,1220xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,1230x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703,1240x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7,1250xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,1260x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE,1270x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,1280x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6,1290xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,1300xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D,1310x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5,1320x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,1330xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,1340xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D135};136137mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF;138const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr;139140while (buf_len >= 4)141{142crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF];143crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF];144crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF];145crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF];146pByte_buf += 4;147buf_len -= 4;148}149150while (buf_len)151{152crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF];153++pByte_buf;154--buf_len;155}156157return ~crc32;158}159#endif160161void mz_free(void *p)162{163MZ_FREE(p);164}165166MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size)167{168(void)opaque, (void)items, (void)size;169return MZ_MALLOC(items * size);170}171MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address)172{173(void)opaque, (void)address;174MZ_FREE(address);175}176MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size)177{178(void)opaque, (void)address, (void)items, (void)size;179return MZ_REALLOC(address, items * size);180}181182const char *mz_version(void)183{184return MZ_VERSION;185}186187#ifndef MINIZ_NO_ZLIB_APIS188189int mz_deflateInit(mz_streamp pStream, int level)190{191return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);192}193194int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)195{196tdefl_compressor *pComp;197mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);198199if (!pStream)200return MZ_STREAM_ERROR;201if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)))202return MZ_PARAM_ERROR;203204pStream->data_type = 0;205pStream->adler = MZ_ADLER32_INIT;206pStream->msg = NULL;207pStream->reserved = 0;208pStream->total_in = 0;209pStream->total_out = 0;210if (!pStream->zalloc)211pStream->zalloc = miniz_def_alloc_func;212if (!pStream->zfree)213pStream->zfree = miniz_def_free_func;214215pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));216if (!pComp)217return MZ_MEM_ERROR;218219pStream->state = (struct mz_internal_state *)pComp;220221if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)222{223mz_deflateEnd(pStream);224return MZ_PARAM_ERROR;225}226227return MZ_OK;228}229230int mz_deflateReset(mz_streamp pStream)231{232if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree))233return MZ_STREAM_ERROR;234pStream->total_in = pStream->total_out = 0;235tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags);236return MZ_OK;237}238239int mz_deflate(mz_streamp pStream, int flush)240{241size_t in_bytes, out_bytes;242mz_ulong orig_total_in, orig_total_out;243int mz_status = MZ_OK;244245if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out))246return MZ_STREAM_ERROR;247if (!pStream->avail_out)248return MZ_BUF_ERROR;249250if (flush == MZ_PARTIAL_FLUSH)251flush = MZ_SYNC_FLUSH;252253if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)254return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;255256orig_total_in = pStream->total_in;257orig_total_out = pStream->total_out;258for (;;)259{260tdefl_status defl_status;261in_bytes = pStream->avail_in;262out_bytes = pStream->avail_out;263264defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);265pStream->next_in += (mz_uint)in_bytes;266pStream->avail_in -= (mz_uint)in_bytes;267pStream->total_in += (mz_uint)in_bytes;268pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);269270pStream->next_out += (mz_uint)out_bytes;271pStream->avail_out -= (mz_uint)out_bytes;272pStream->total_out += (mz_uint)out_bytes;273274if (defl_status < 0)275{276mz_status = MZ_STREAM_ERROR;277break;278}279else if (defl_status == TDEFL_STATUS_DONE)280{281mz_status = MZ_STREAM_END;282break;283}284else if (!pStream->avail_out)285break;286else if ((!pStream->avail_in) && (flush != MZ_FINISH))287{288if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))289break;290return MZ_BUF_ERROR; /* Can't make forward progress without some input.291*/292}293}294return mz_status;295}296297int mz_deflateEnd(mz_streamp pStream)298{299if (!pStream)300return MZ_STREAM_ERROR;301if (pStream->state)302{303pStream->zfree(pStream->opaque, pStream->state);304pStream->state = NULL;305}306return MZ_OK;307}308309mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)310{311(void)pStream;312/* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */313return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);314}315316int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)317{318int status;319mz_stream stream;320memset(&stream, 0, sizeof(stream));321322/* In case mz_ulong is 64-bits (argh I hate longs). */323if ((source_len | *pDest_len) > 0xFFFFFFFFU)324return MZ_PARAM_ERROR;325326stream.next_in = pSource;327stream.avail_in = (mz_uint32)source_len;328stream.next_out = pDest;329stream.avail_out = (mz_uint32)*pDest_len;330331status = mz_deflateInit(&stream, level);332if (status != MZ_OK)333return status;334335status = mz_deflate(&stream, MZ_FINISH);336if (status != MZ_STREAM_END)337{338mz_deflateEnd(&stream);339return (status == MZ_OK) ? MZ_BUF_ERROR : status;340}341342*pDest_len = stream.total_out;343return mz_deflateEnd(&stream);344}345346int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)347{348return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);349}350351mz_ulong mz_compressBound(mz_ulong source_len)352{353return mz_deflateBound(NULL, source_len);354}355356typedef struct357{358tinfl_decompressor m_decomp;359mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;360int m_window_bits;361mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];362tinfl_status m_last_status;363} inflate_state;364365int mz_inflateInit2(mz_streamp pStream, int window_bits)366{367inflate_state *pDecomp;368if (!pStream)369return MZ_STREAM_ERROR;370if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))371return MZ_PARAM_ERROR;372373pStream->data_type = 0;374pStream->adler = 0;375pStream->msg = NULL;376pStream->total_in = 0;377pStream->total_out = 0;378pStream->reserved = 0;379if (!pStream->zalloc)380pStream->zalloc = miniz_def_alloc_func;381if (!pStream->zfree)382pStream->zfree = miniz_def_free_func;383384pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));385if (!pDecomp)386return MZ_MEM_ERROR;387388pStream->state = (struct mz_internal_state *)pDecomp;389390tinfl_init(&pDecomp->m_decomp);391pDecomp->m_dict_ofs = 0;392pDecomp->m_dict_avail = 0;393pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;394pDecomp->m_first_call = 1;395pDecomp->m_has_flushed = 0;396pDecomp->m_window_bits = window_bits;397398return MZ_OK;399}400401int mz_inflateInit(mz_streamp pStream)402{403return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);404}405406int mz_inflateReset(mz_streamp pStream)407{408inflate_state *pDecomp;409if (!pStream)410return MZ_STREAM_ERROR;411412pStream->data_type = 0;413pStream->adler = 0;414pStream->msg = NULL;415pStream->total_in = 0;416pStream->total_out = 0;417pStream->reserved = 0;418419pDecomp = (inflate_state *)pStream->state;420421tinfl_init(&pDecomp->m_decomp);422pDecomp->m_dict_ofs = 0;423pDecomp->m_dict_avail = 0;424pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;425pDecomp->m_first_call = 1;426pDecomp->m_has_flushed = 0;427/* pDecomp->m_window_bits = window_bits */;428429return MZ_OK;430}431432int mz_inflate(mz_streamp pStream, int flush)433{434inflate_state *pState;435mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;436size_t in_bytes, out_bytes, orig_avail_in;437tinfl_status status;438439if ((!pStream) || (!pStream->state))440return MZ_STREAM_ERROR;441if (flush == MZ_PARTIAL_FLUSH)442flush = MZ_SYNC_FLUSH;443if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))444return MZ_STREAM_ERROR;445446pState = (inflate_state *)pStream->state;447if (pState->m_window_bits > 0)448decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;449orig_avail_in = pStream->avail_in;450451first_call = pState->m_first_call;452pState->m_first_call = 0;453if (pState->m_last_status < 0)454return MZ_DATA_ERROR;455456if (pState->m_has_flushed && (flush != MZ_FINISH))457return MZ_STREAM_ERROR;458pState->m_has_flushed |= (flush == MZ_FINISH);459460if ((flush == MZ_FINISH) && (first_call))461{462/* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */463decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;464in_bytes = pStream->avail_in;465out_bytes = pStream->avail_out;466status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);467pState->m_last_status = status;468pStream->next_in += (mz_uint)in_bytes;469pStream->avail_in -= (mz_uint)in_bytes;470pStream->total_in += (mz_uint)in_bytes;471pStream->adler = tinfl_get_adler32(&pState->m_decomp);472pStream->next_out += (mz_uint)out_bytes;473pStream->avail_out -= (mz_uint)out_bytes;474pStream->total_out += (mz_uint)out_bytes;475476if (status < 0)477return MZ_DATA_ERROR;478else if (status != TINFL_STATUS_DONE)479{480pState->m_last_status = TINFL_STATUS_FAILED;481return MZ_BUF_ERROR;482}483return MZ_STREAM_END;484}485/* flush != MZ_FINISH then we must assume there's more input. */486if (flush != MZ_FINISH)487decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;488489if (pState->m_dict_avail)490{491n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);492memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);493pStream->next_out += n;494pStream->avail_out -= n;495pStream->total_out += n;496pState->m_dict_avail -= n;497pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);498return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;499}500501for (;;)502{503in_bytes = pStream->avail_in;504out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;505506status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);507pState->m_last_status = status;508509pStream->next_in += (mz_uint)in_bytes;510pStream->avail_in -= (mz_uint)in_bytes;511pStream->total_in += (mz_uint)in_bytes;512pStream->adler = tinfl_get_adler32(&pState->m_decomp);513514pState->m_dict_avail = (mz_uint)out_bytes;515516n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);517memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);518pStream->next_out += n;519pStream->avail_out -= n;520pStream->total_out += n;521pState->m_dict_avail -= n;522pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);523524if (status < 0)525return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */526else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))527return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */528else if (flush == MZ_FINISH)529{530/* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */531if (status == TINFL_STATUS_DONE)532return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;533/* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */534else if (!pStream->avail_out)535return MZ_BUF_ERROR;536}537else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))538break;539}540541return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;542}543544int mz_inflateEnd(mz_streamp pStream)545{546if (!pStream)547return MZ_STREAM_ERROR;548if (pStream->state)549{550pStream->zfree(pStream->opaque, pStream->state);551pStream->state = NULL;552}553return MZ_OK;554}555556int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)557{558mz_stream stream;559int status;560memset(&stream, 0, sizeof(stream));561562/* In case mz_ulong is 64-bits (argh I hate longs). */563if ((source_len | *pDest_len) > 0xFFFFFFFFU)564return MZ_PARAM_ERROR;565566stream.next_in = pSource;567stream.avail_in = (mz_uint32)source_len;568stream.next_out = pDest;569stream.avail_out = (mz_uint32)*pDest_len;570571status = mz_inflateInit(&stream);572if (status != MZ_OK)573return status;574575status = mz_inflate(&stream, MZ_FINISH);576if (status != MZ_STREAM_END)577{578mz_inflateEnd(&stream);579return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;580}581*pDest_len = stream.total_out;582583return mz_inflateEnd(&stream);584}585586const char *mz_error(int err)587{588static struct589{590int m_err;591const char *m_pDesc;592} s_error_descs[] =593{594{ MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" }595};596mz_uint i;597for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)598if (s_error_descs[i].m_err == err)599return s_error_descs[i].m_pDesc;600return NULL;601}602603#endif /*MINIZ_NO_ZLIB_APIS */604605#ifdef __cplusplus606}607#endif608609/*610This is free and unencumbered software released into the public domain.611612Anyone is free to copy, modify, publish, use, compile, sell, or613distribute this software, either in source code form or as a compiled614binary, for any purpose, commercial or non-commercial, and by any615means.616617In jurisdictions that recognize copyright laws, the author or authors618of this software dedicate any and all copyright interest in the619software to the public domain. We make this dedication for the benefit620of the public at large and to the detriment of our heirs and621successors. We intend this dedication to be an overt act of622relinquishment in perpetuity of all present and future rights to this623software under copyright law.624625THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,626EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF627MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.628IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR629OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,630ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR631OTHER DEALINGS IN THE SOFTWARE.632633For more information, please refer to <http://unlicense.org/>634*/635/**************************************************************************636*637* Copyright 2013-2014 RAD Game Tools and Valve Software638* Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC639* All Rights Reserved.640*641* Permission is hereby granted, free of charge, to any person obtaining a copy642* of this software and associated documentation files (the "Software"), to deal643* in the Software without restriction, including without limitation the rights644* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell645* copies of the Software, and to permit persons to whom the Software is646* furnished to do so, subject to the following conditions:647*648* The above copyright notice and this permission notice shall be included in649* all copies or substantial portions of the Software.650*651* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR652* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,653* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE654* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER655* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,656* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN657* THE SOFTWARE.658*659**************************************************************************/660661662663#ifdef __cplusplus664extern "C" {665#endif666667/* ------------------- Low-level Compression (independent from all decompression API's) */668669/* Purposely making these tables static for faster init and thread safety. */670static const mz_uint16 s_tdefl_len_sym[256] =671{672257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272,673273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276,674277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,675279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,676281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,677282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,678283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,679284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285680};681682static const mz_uint8 s_tdefl_len_extra[256] =683{6840, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,6854, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,6865, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,6875, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0688};689690static const mz_uint8 s_tdefl_small_dist_sym[512] =691{6920, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11,69311, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13,69413, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,69514, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,69614, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,69715, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,69816, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,69916, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,70016, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,70117, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,70217, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,70317, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17704};705706static const mz_uint8 s_tdefl_small_dist_extra[512] =707{7080, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,7095, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,7106, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,7116, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,7127, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,7137, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,7147, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,7157, 7, 7, 7, 7, 7, 7, 7716};717718static const mz_uint8 s_tdefl_large_dist_sym[128] =719{7200, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,72126, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,72228, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29723};724725static const mz_uint8 s_tdefl_large_dist_extra[128] =726{7270, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,72812, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,72913, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13730};731732/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */733typedef struct734{735mz_uint16 m_key, m_sym_index;736} tdefl_sym_freq;737static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1)738{739mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];740tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;741MZ_CLEAR_OBJ(hist);742for (i = 0; i < num_syms; i++)743{744mz_uint freq = pSyms0[i].m_key;745hist[freq & 0xFF]++;746hist[256 + ((freq >> 8) & 0xFF)]++;747}748while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))749total_passes--;750for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)751{752const mz_uint32 *pHist = &hist[pass << 8];753mz_uint offsets[256], cur_ofs = 0;754for (i = 0; i < 256; i++)755{756offsets[i] = cur_ofs;757cur_ofs += pHist[i];758}759for (i = 0; i < num_syms; i++)760pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];761{762tdefl_sym_freq *t = pCur_syms;763pCur_syms = pNew_syms;764pNew_syms = t;765}766}767return pCur_syms;768}769770/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, [email protected], Jyrki Katajainen, [email protected], November 1996. */771static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)772{773int root, leaf, next, avbl, used, dpth;774if (n == 0)775return;776else if (n == 1)777{778A[0].m_key = 1;779return;780}781A[0].m_key += A[1].m_key;782root = 0;783leaf = 2;784for (next = 1; next < n - 1; next++)785{786if (leaf >= n || A[root].m_key < A[leaf].m_key)787{788A[next].m_key = A[root].m_key;789A[root++].m_key = (mz_uint16)next;790}791else792A[next].m_key = A[leaf++].m_key;793if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key))794{795A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);796A[root++].m_key = (mz_uint16)next;797}798else799A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);800}801A[n - 2].m_key = 0;802for (next = n - 3; next >= 0; next--)803A[next].m_key = A[A[next].m_key].m_key + 1;804avbl = 1;805used = dpth = 0;806root = n - 2;807next = n - 1;808while (avbl > 0)809{810while (root >= 0 && (int)A[root].m_key == dpth)811{812used++;813root--;814}815while (avbl > used)816{817A[next--].m_key = (mz_uint16)(dpth);818avbl--;819}820avbl = 2 * used;821dpth++;822used = 0;823}824}825826/* Limits canonical Huffman code table's max code size. */827enum828{829TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32830};831static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)832{833int i;834mz_uint32 total = 0;835if (code_list_len <= 1)836return;837for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)838pNum_codes[max_code_size] += pNum_codes[i];839for (i = max_code_size; i > 0; i--)840total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));841while (total != (1UL << max_code_size))842{843pNum_codes[max_code_size]--;844for (i = max_code_size - 1; i > 0; i--)845if (pNum_codes[i])846{847pNum_codes[i]--;848pNum_codes[i + 1] += 2;849break;850}851total--;852}853}854855static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)856{857int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];858mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];859MZ_CLEAR_OBJ(num_codes);860if (static_table)861{862for (i = 0; i < table_len; i++)863num_codes[d->m_huff_code_sizes[table_num][i]]++;864}865else866{867tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;868int num_used_syms = 0;869const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];870for (i = 0; i < table_len; i++)871if (pSym_count[i])872{873syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];874syms0[num_used_syms++].m_sym_index = (mz_uint16)i;875}876877pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);878tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);879880for (i = 0; i < num_used_syms; i++)881num_codes[pSyms[i].m_key]++;882883tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);884885MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);886MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);887for (i = 1, j = num_used_syms; i <= code_size_limit; i++)888for (l = num_codes[i]; l > 0; l--)889d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);890}891892next_code[1] = 0;893for (j = 0, i = 2; i <= code_size_limit; i++)894next_code[i] = j = ((j + num_codes[i - 1]) << 1);895896for (i = 0; i < table_len; i++)897{898mz_uint rev_code = 0, code, code_size;899if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0)900continue;901code = next_code[code_size]++;902for (l = code_size; l > 0; l--, code >>= 1)903rev_code = (rev_code << 1) | (code & 1);904d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;905}906}907908#define TDEFL_PUT_BITS(b, l) \909do \910{ \911mz_uint bits = b; \912mz_uint len = l; \913MZ_ASSERT(bits <= ((1U << len) - 1U)); \914d->m_bit_buffer |= (bits << d->m_bits_in); \915d->m_bits_in += len; \916while (d->m_bits_in >= 8) \917{ \918if (d->m_pOutput_buf < d->m_pOutput_buf_end) \919*d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \920d->m_bit_buffer >>= 8; \921d->m_bits_in -= 8; \922} \923} \924MZ_MACRO_END925926#define TDEFL_RLE_PREV_CODE_SIZE() \927{ \928if (rle_repeat_count) \929{ \930if (rle_repeat_count < 3) \931{ \932d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \933while (rle_repeat_count--) \934packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \935} \936else \937{ \938d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \939packed_code_sizes[num_packed_code_sizes++] = 16; \940packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \941} \942rle_repeat_count = 0; \943} \944}945946#define TDEFL_RLE_ZERO_CODE_SIZE() \947{ \948if (rle_z_count) \949{ \950if (rle_z_count < 3) \951{ \952d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \953while (rle_z_count--) \954packed_code_sizes[num_packed_code_sizes++] = 0; \955} \956else if (rle_z_count <= 10) \957{ \958d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \959packed_code_sizes[num_packed_code_sizes++] = 17; \960packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \961} \962else \963{ \964d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \965packed_code_sizes[num_packed_code_sizes++] = 18; \966packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \967} \968rle_z_count = 0; \969} \970}971972static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };973974static void tdefl_start_dynamic_block(tdefl_compressor *d)975{976int num_lit_codes, num_dist_codes, num_bit_lengths;977mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;978mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;979980d->m_huff_count[0][256] = 1;981982tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);983tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);984985for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)986if (d->m_huff_code_sizes[0][num_lit_codes - 1])987break;988for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)989if (d->m_huff_code_sizes[1][num_dist_codes - 1])990break;991992memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);993memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);994total_code_sizes_to_pack = num_lit_codes + num_dist_codes;995num_packed_code_sizes = 0;996rle_z_count = 0;997rle_repeat_count = 0;998999memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);1000for (i = 0; i < total_code_sizes_to_pack; i++)1001{1002mz_uint8 code_size = code_sizes_to_pack[i];1003if (!code_size)1004{1005TDEFL_RLE_PREV_CODE_SIZE();1006if (++rle_z_count == 138)1007{1008TDEFL_RLE_ZERO_CODE_SIZE();1009}1010}1011else1012{1013TDEFL_RLE_ZERO_CODE_SIZE();1014if (code_size != prev_code_size)1015{1016TDEFL_RLE_PREV_CODE_SIZE();1017d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1);1018packed_code_sizes[num_packed_code_sizes++] = code_size;1019}1020else if (++rle_repeat_count == 6)1021{1022TDEFL_RLE_PREV_CODE_SIZE();1023}1024}1025prev_code_size = code_size;1026}1027if (rle_repeat_count)1028{1029TDEFL_RLE_PREV_CODE_SIZE();1030}1031else1032{1033TDEFL_RLE_ZERO_CODE_SIZE();1034}10351036tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);10371038TDEFL_PUT_BITS(2, 2);10391040TDEFL_PUT_BITS(num_lit_codes - 257, 5);1041TDEFL_PUT_BITS(num_dist_codes - 1, 5);10421043for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)1044if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])1045break;1046num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));1047TDEFL_PUT_BITS(num_bit_lengths - 4, 4);1048for (i = 0; (int)i < num_bit_lengths; i++)1049TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);10501051for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;)1052{1053mz_uint code = packed_code_sizes[packed_code_sizes_index++];1054MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);1055TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);1056if (code >= 16)1057TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);1058}1059}10601061static void tdefl_start_static_block(tdefl_compressor *d)1062{1063mz_uint i;1064mz_uint8 *p = &d->m_huff_code_sizes[0][0];10651066for (i = 0; i <= 143; ++i)1067*p++ = 8;1068for (; i <= 255; ++i)1069*p++ = 9;1070for (; i <= 279; ++i)1071*p++ = 7;1072for (; i <= 287; ++i)1073*p++ = 8;10741075memset(d->m_huff_code_sizes[1], 5, 32);10761077tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);1078tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);10791080TDEFL_PUT_BITS(1, 2);1081}10821083static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };10841085#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS1086static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)1087{1088mz_uint flags;1089mz_uint8 *pLZ_codes;1090mz_uint8 *pOutput_buf = d->m_pOutput_buf;1091mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;1092mz_uint64 bit_buffer = d->m_bit_buffer;1093mz_uint bits_in = d->m_bits_in;10941095#define TDEFL_PUT_BITS_FAST(b, l) \1096{ \1097bit_buffer |= (((mz_uint64)(b)) << bits_in); \1098bits_in += (l); \1099}11001101flags = 1;1102for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1)1103{1104if (flags == 1)1105flags = *pLZ_codes++ | 0x100;11061107if (flags & 1)1108{1109mz_uint s0, s1, n0, n1, sym, num_extra_bits;1110mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1);1111pLZ_codes += 3;11121113MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);1114TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);1115TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);11161117/* This sequence coaxes MSVC into using cmov's vs. jmp's. */1118s0 = s_tdefl_small_dist_sym[match_dist & 511];1119n0 = s_tdefl_small_dist_extra[match_dist & 511];1120s1 = s_tdefl_large_dist_sym[match_dist >> 8];1121n1 = s_tdefl_large_dist_extra[match_dist >> 8];1122sym = (match_dist < 512) ? s0 : s1;1123num_extra_bits = (match_dist < 512) ? n0 : n1;11241125MZ_ASSERT(d->m_huff_code_sizes[1][sym]);1126TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);1127TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);1128}1129else1130{1131mz_uint lit = *pLZ_codes++;1132MZ_ASSERT(d->m_huff_code_sizes[0][lit]);1133TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);11341135if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))1136{1137flags >>= 1;1138lit = *pLZ_codes++;1139MZ_ASSERT(d->m_huff_code_sizes[0][lit]);1140TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);11411142if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))1143{1144flags >>= 1;1145lit = *pLZ_codes++;1146MZ_ASSERT(d->m_huff_code_sizes[0][lit]);1147TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);1148}1149}1150}11511152if (pOutput_buf >= d->m_pOutput_buf_end)1153return MZ_FALSE;11541155*(mz_uint64 *)pOutput_buf = bit_buffer;1156pOutput_buf += (bits_in >> 3);1157bit_buffer >>= (bits_in & ~7);1158bits_in &= 7;1159}11601161#undef TDEFL_PUT_BITS_FAST11621163d->m_pOutput_buf = pOutput_buf;1164d->m_bits_in = 0;1165d->m_bit_buffer = 0;11661167while (bits_in)1168{1169mz_uint32 n = MZ_MIN(bits_in, 16);1170TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);1171bit_buffer >>= n;1172bits_in -= n;1173}11741175TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);11761177return (d->m_pOutput_buf < d->m_pOutput_buf_end);1178}1179#else1180static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)1181{1182mz_uint flags;1183mz_uint8 *pLZ_codes;11841185flags = 1;1186for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)1187{1188if (flags == 1)1189flags = *pLZ_codes++ | 0x100;1190if (flags & 1)1191{1192mz_uint sym, num_extra_bits;1193mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));1194pLZ_codes += 3;11951196MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);1197TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);1198TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);11991200if (match_dist < 512)1201{1202sym = s_tdefl_small_dist_sym[match_dist];1203num_extra_bits = s_tdefl_small_dist_extra[match_dist];1204}1205else1206{1207sym = s_tdefl_large_dist_sym[match_dist >> 8];1208num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];1209}1210MZ_ASSERT(d->m_huff_code_sizes[1][sym]);1211TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);1212TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);1213}1214else1215{1216mz_uint lit = *pLZ_codes++;1217MZ_ASSERT(d->m_huff_code_sizes[0][lit]);1218TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);1219}1220}12211222TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);12231224return (d->m_pOutput_buf < d->m_pOutput_buf_end);1225}1226#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */12271228static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)1229{1230if (static_block)1231tdefl_start_static_block(d);1232else1233tdefl_start_dynamic_block(d);1234return tdefl_compress_lz_codes(d);1235}12361237static int tdefl_flush_block(tdefl_compressor *d, int flush)1238{1239mz_uint saved_bit_buf, saved_bits_in;1240mz_uint8 *pSaved_output_buf;1241mz_bool comp_block_succeeded = MZ_FALSE;1242int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;1243mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;12441245d->m_pOutput_buf = pOutput_buf_start;1246d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;12471248MZ_ASSERT(!d->m_output_flush_remaining);1249d->m_output_flush_ofs = 0;1250d->m_output_flush_remaining = 0;12511252*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);1253d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);12541255if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))1256{1257TDEFL_PUT_BITS(0x78, 8);1258TDEFL_PUT_BITS(0x01, 8);1259}12601261TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);12621263pSaved_output_buf = d->m_pOutput_buf;1264saved_bit_buf = d->m_bit_buffer;1265saved_bits_in = d->m_bits_in;12661267if (!use_raw_block)1268comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));12691270/* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */1271if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&1272((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size))1273{1274mz_uint i;1275d->m_pOutput_buf = pSaved_output_buf;1276d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;1277TDEFL_PUT_BITS(0, 2);1278if (d->m_bits_in)1279{1280TDEFL_PUT_BITS(0, 8 - d->m_bits_in);1281}1282for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)1283{1284TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);1285}1286for (i = 0; i < d->m_total_lz_bytes; ++i)1287{1288TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);1289}1290}1291/* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */1292else if (!comp_block_succeeded)1293{1294d->m_pOutput_buf = pSaved_output_buf;1295d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;1296tdefl_compress_block(d, MZ_TRUE);1297}12981299if (flush)1300{1301if (flush == TDEFL_FINISH)1302{1303if (d->m_bits_in)1304{1305TDEFL_PUT_BITS(0, 8 - d->m_bits_in);1306}1307if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER)1308{1309mz_uint i, a = d->m_adler32;1310for (i = 0; i < 4; i++)1311{1312TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);1313a <<= 8;1314}1315}1316}1317else1318{1319mz_uint i, z = 0;1320TDEFL_PUT_BITS(0, 3);1321if (d->m_bits_in)1322{1323TDEFL_PUT_BITS(0, 8 - d->m_bits_in);1324}1325for (i = 2; i; --i, z ^= 0xFFFF)1326{1327TDEFL_PUT_BITS(z & 0xFFFF, 16);1328}1329}1330}13311332MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);13331334memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);1335memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);13361337d->m_pLZ_code_buf = d->m_lz_code_buf + 1;1338d->m_pLZ_flags = d->m_lz_code_buf;1339d->m_num_flags_left = 8;1340d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;1341d->m_total_lz_bytes = 0;1342d->m_block_index++;13431344if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)1345{1346if (d->m_pPut_buf_func)1347{1348*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;1349if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))1350return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);1351}1352else if (pOutput_buf_start == d->m_output_buf)1353{1354int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));1355memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);1356d->m_out_buf_ofs += bytes_to_copy;1357if ((n -= bytes_to_copy) != 0)1358{1359d->m_output_flush_ofs = bytes_to_copy;1360d->m_output_flush_remaining = n;1361}1362}1363else1364{1365d->m_out_buf_ofs += n;1366}1367}13681369return d->m_output_flush_remaining;1370}13711372#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES1373#ifdef MINIZ_UNALIGNED_USE_MEMCPY1374static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p)1375{1376mz_uint16 ret;1377memcpy(&ret, p, sizeof(mz_uint16));1378return ret;1379}1380static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p)1381{1382mz_uint16 ret;1383memcpy(&ret, p, sizeof(mz_uint16));1384return ret;1385}1386#else1387#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)1388#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p)1389#endif1390static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)1391{1392mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;1393mz_uint num_probes_left = d->m_max_probes[match_len >= 32];1394const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;1395mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s);1396MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);1397if (max_match_len <= match_len)1398return;1399for (;;)1400{1401for (;;)1402{1403if (--num_probes_left == 0)1404return;1405#define TDEFL_PROBE \1406next_probe_pos = d->m_next[probe_pos]; \1407if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \1408return; \1409probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \1410if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \1411break;1412TDEFL_PROBE;1413TDEFL_PROBE;1414TDEFL_PROBE;1415}1416if (!dist)1417break;1418q = (const mz_uint16 *)(d->m_dict + probe_pos);1419if (TDEFL_READ_UNALIGNED_WORD2(q) != s01)1420continue;1421p = s;1422probe_len = 32;1423do1424{1425} while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) &&1426(TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0));1427if (!probe_len)1428{1429*pMatch_dist = dist;1430*pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN);1431break;1432}1433else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len)1434{1435*pMatch_dist = dist;1436if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len)1437break;1438c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);1439}1440}1441}1442#else1443static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)1444{1445mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;1446mz_uint num_probes_left = d->m_max_probes[match_len >= 32];1447const mz_uint8 *s = d->m_dict + pos, *p, *q;1448mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];1449MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);1450if (max_match_len <= match_len)1451return;1452for (;;)1453{1454for (;;)1455{1456if (--num_probes_left == 0)1457return;1458#define TDEFL_PROBE \1459next_probe_pos = d->m_next[probe_pos]; \1460if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \1461return; \1462probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \1463if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \1464break;1465TDEFL_PROBE;1466TDEFL_PROBE;1467TDEFL_PROBE;1468}1469if (!dist)1470break;1471p = s;1472q = d->m_dict + probe_pos;1473for (probe_len = 0; probe_len < max_match_len; probe_len++)1474if (*p++ != *q++)1475break;1476if (probe_len > match_len)1477{1478*pMatch_dist = dist;1479if ((*pMatch_len = match_len = probe_len) == max_match_len)1480return;1481c0 = d->m_dict[pos + match_len];1482c1 = d->m_dict[pos + match_len - 1];1483}1484}1485}1486#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */14871488#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN1489#ifdef MINIZ_UNALIGNED_USE_MEMCPY1490static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8* p)1491{1492mz_uint32 ret;1493memcpy(&ret, p, sizeof(mz_uint32));1494return ret;1495}1496#else1497#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p)1498#endif1499static mz_bool tdefl_compress_fast(tdefl_compressor *d)1500{1501/* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */1502mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;1503mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;1504mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;15051506while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size)))1507{1508const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;1509mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;1510mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);1511d->m_src_buf_left -= num_bytes_to_process;1512lookahead_size += num_bytes_to_process;15131514while (num_bytes_to_process)1515{1516mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);1517memcpy(d->m_dict + dst_pos, d->m_pSrc, n);1518if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))1519memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));1520d->m_pSrc += n;1521dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;1522num_bytes_to_process -= n;1523}15241525dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);1526if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))1527break;15281529while (lookahead_size >= 4)1530{1531mz_uint cur_match_dist, cur_match_len = 1;1532mz_uint8 *pCur_dict = d->m_dict + cur_pos;1533mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF;1534mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK;1535mz_uint probe_pos = d->m_hash[hash];1536d->m_hash[hash] = (mz_uint16)lookahead_pos;15371538if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((TDEFL_READ_UNALIGNED_WORD32(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram))1539{1540const mz_uint16 *p = (const mz_uint16 *)pCur_dict;1541const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);1542mz_uint32 probe_len = 32;1543do1544{1545} while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) &&1546(TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0));1547cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);1548if (!probe_len)1549cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;15501551if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)))1552{1553cur_match_len = 1;1554*pLZ_code_buf++ = (mz_uint8)first_trigram;1555*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);1556d->m_huff_count[0][(mz_uint8)first_trigram]++;1557}1558else1559{1560mz_uint32 s0, s1;1561cur_match_len = MZ_MIN(cur_match_len, lookahead_size);15621563MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE));15641565cur_match_dist--;15661567pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);1568#ifdef MINIZ_UNALIGNED_USE_MEMCPY1569memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist));1570#else1571*(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;1572#endif1573pLZ_code_buf += 3;1574*pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);15751576s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];1577s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];1578d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;15791580d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;1581}1582}1583else1584{1585*pLZ_code_buf++ = (mz_uint8)first_trigram;1586*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);1587d->m_huff_count[0][(mz_uint8)first_trigram]++;1588}15891590if (--num_flags_left == 0)1591{1592num_flags_left = 8;1593pLZ_flags = pLZ_code_buf++;1594}15951596total_lz_bytes += cur_match_len;1597lookahead_pos += cur_match_len;1598dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE);1599cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;1600MZ_ASSERT(lookahead_size >= cur_match_len);1601lookahead_size -= cur_match_len;16021603if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])1604{1605int n;1606d->m_lookahead_pos = lookahead_pos;1607d->m_lookahead_size = lookahead_size;1608d->m_dict_size = dict_size;1609d->m_total_lz_bytes = total_lz_bytes;1610d->m_pLZ_code_buf = pLZ_code_buf;1611d->m_pLZ_flags = pLZ_flags;1612d->m_num_flags_left = num_flags_left;1613if ((n = tdefl_flush_block(d, 0)) != 0)1614return (n < 0) ? MZ_FALSE : MZ_TRUE;1615total_lz_bytes = d->m_total_lz_bytes;1616pLZ_code_buf = d->m_pLZ_code_buf;1617pLZ_flags = d->m_pLZ_flags;1618num_flags_left = d->m_num_flags_left;1619}1620}16211622while (lookahead_size)1623{1624mz_uint8 lit = d->m_dict[cur_pos];16251626total_lz_bytes++;1627*pLZ_code_buf++ = lit;1628*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);1629if (--num_flags_left == 0)1630{1631num_flags_left = 8;1632pLZ_flags = pLZ_code_buf++;1633}16341635d->m_huff_count[0][lit]++;16361637lookahead_pos++;1638dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE);1639cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;1640lookahead_size--;16411642if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])1643{1644int n;1645d->m_lookahead_pos = lookahead_pos;1646d->m_lookahead_size = lookahead_size;1647d->m_dict_size = dict_size;1648d->m_total_lz_bytes = total_lz_bytes;1649d->m_pLZ_code_buf = pLZ_code_buf;1650d->m_pLZ_flags = pLZ_flags;1651d->m_num_flags_left = num_flags_left;1652if ((n = tdefl_flush_block(d, 0)) != 0)1653return (n < 0) ? MZ_FALSE : MZ_TRUE;1654total_lz_bytes = d->m_total_lz_bytes;1655pLZ_code_buf = d->m_pLZ_code_buf;1656pLZ_flags = d->m_pLZ_flags;1657num_flags_left = d->m_num_flags_left;1658}1659}1660}16611662d->m_lookahead_pos = lookahead_pos;1663d->m_lookahead_size = lookahead_size;1664d->m_dict_size = dict_size;1665d->m_total_lz_bytes = total_lz_bytes;1666d->m_pLZ_code_buf = pLZ_code_buf;1667d->m_pLZ_flags = pLZ_flags;1668d->m_num_flags_left = num_flags_left;1669return MZ_TRUE;1670}1671#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */16721673static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)1674{1675d->m_total_lz_bytes++;1676*d->m_pLZ_code_buf++ = lit;1677*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);1678if (--d->m_num_flags_left == 0)1679{1680d->m_num_flags_left = 8;1681d->m_pLZ_flags = d->m_pLZ_code_buf++;1682}1683d->m_huff_count[0][lit]++;1684}16851686static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)1687{1688mz_uint32 s0, s1;16891690MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));16911692d->m_total_lz_bytes += match_len;16931694d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);16951696match_dist -= 1;1697d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);1698d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);1699d->m_pLZ_code_buf += 3;17001701*d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);1702if (--d->m_num_flags_left == 0)1703{1704d->m_num_flags_left = 8;1705d->m_pLZ_flags = d->m_pLZ_code_buf++;1706}17071708s0 = s_tdefl_small_dist_sym[match_dist & 511];1709s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];1710d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;17111712if (match_len >= TDEFL_MIN_MATCH_LEN)1713d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;1714}17151716static mz_bool tdefl_compress_normal(tdefl_compressor *d)1717{1718const mz_uint8 *pSrc = d->m_pSrc;1719size_t src_buf_left = d->m_src_buf_left;1720tdefl_flush flush = d->m_flush;17211722while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))1723{1724mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;1725/* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */1726if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))1727{1728mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;1729mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];1730mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);1731const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;1732src_buf_left -= num_bytes_to_process;1733d->m_lookahead_size += num_bytes_to_process;1734while (pSrc != pSrc_end)1735{1736mz_uint8 c = *pSrc++;1737d->m_dict[dst_pos] = c;1738if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))1739d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;1740hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);1741d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];1742d->m_hash[hash] = (mz_uint16)(ins_pos);1743dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;1744ins_pos++;1745}1746}1747else1748{1749while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))1750{1751mz_uint8 c = *pSrc++;1752mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;1753src_buf_left--;1754d->m_dict[dst_pos] = c;1755if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))1756d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;1757if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)1758{1759mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;1760mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);1761d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];1762d->m_hash[hash] = (mz_uint16)(ins_pos);1763}1764}1765}1766d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);1767if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))1768break;17691770/* Simple lazy/greedy parsing state machine. */1771len_to_move = 1;1772cur_match_dist = 0;1773cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);1774cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;1775if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))1776{1777if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))1778{1779mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];1780cur_match_len = 0;1781while (cur_match_len < d->m_lookahead_size)1782{1783if (d->m_dict[cur_pos + cur_match_len] != c)1784break;1785cur_match_len++;1786}1787if (cur_match_len < TDEFL_MIN_MATCH_LEN)1788cur_match_len = 0;1789else1790cur_match_dist = 1;1791}1792}1793else1794{1795tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);1796}1797if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))1798{1799cur_match_dist = cur_match_len = 0;1800}1801if (d->m_saved_match_len)1802{1803if (cur_match_len > d->m_saved_match_len)1804{1805tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);1806if (cur_match_len >= 128)1807{1808tdefl_record_match(d, cur_match_len, cur_match_dist);1809d->m_saved_match_len = 0;1810len_to_move = cur_match_len;1811}1812else1813{1814d->m_saved_lit = d->m_dict[cur_pos];1815d->m_saved_match_dist = cur_match_dist;1816d->m_saved_match_len = cur_match_len;1817}1818}1819else1820{1821tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);1822len_to_move = d->m_saved_match_len - 1;1823d->m_saved_match_len = 0;1824}1825}1826else if (!cur_match_dist)1827tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);1828else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))1829{1830tdefl_record_match(d, cur_match_len, cur_match_dist);1831len_to_move = cur_match_len;1832}1833else1834{1835d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];1836d->m_saved_match_dist = cur_match_dist;1837d->m_saved_match_len = cur_match_len;1838}1839/* Move the lookahead forward by len_to_move bytes. */1840d->m_lookahead_pos += len_to_move;1841MZ_ASSERT(d->m_lookahead_size >= len_to_move);1842d->m_lookahead_size -= len_to_move;1843d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);1844/* Check if it's time to flush the current LZ codes to the internal output buffer. */1845if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||1846((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))))1847{1848int n;1849d->m_pSrc = pSrc;1850d->m_src_buf_left = src_buf_left;1851if ((n = tdefl_flush_block(d, 0)) != 0)1852return (n < 0) ? MZ_FALSE : MZ_TRUE;1853}1854}18551856d->m_pSrc = pSrc;1857d->m_src_buf_left = src_buf_left;1858return MZ_TRUE;1859}18601861static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)1862{1863if (d->m_pIn_buf_size)1864{1865*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;1866}18671868if (d->m_pOut_buf_size)1869{1870size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);1871memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);1872d->m_output_flush_ofs += (mz_uint)n;1873d->m_output_flush_remaining -= (mz_uint)n;1874d->m_out_buf_ofs += n;18751876*d->m_pOut_buf_size = d->m_out_buf_ofs;1877}18781879return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;1880}18811882tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)1883{1884if (!d)1885{1886if (pIn_buf_size)1887*pIn_buf_size = 0;1888if (pOut_buf_size)1889*pOut_buf_size = 0;1890return TDEFL_STATUS_BAD_PARAM;1891}18921893d->m_pIn_buf = pIn_buf;1894d->m_pIn_buf_size = pIn_buf_size;1895d->m_pOut_buf = pOut_buf;1896d->m_pOut_buf_size = pOut_buf_size;1897d->m_pSrc = (const mz_uint8 *)(pIn_buf);1898d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;1899d->m_out_buf_ofs = 0;1900d->m_flush = flush;19011902if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||1903(d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf))1904{1905if (pIn_buf_size)1906*pIn_buf_size = 0;1907if (pOut_buf_size)1908*pOut_buf_size = 0;1909return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);1910}1911d->m_wants_to_finish |= (flush == TDEFL_FINISH);19121913if ((d->m_output_flush_remaining) || (d->m_finished))1914return (d->m_prev_return_status = tdefl_flush_output_buffer(d));19151916#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN1917if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&1918((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&1919((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0))1920{1921if (!tdefl_compress_fast(d))1922return d->m_prev_return_status;1923}1924else1925#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */1926{1927if (!tdefl_compress_normal(d))1928return d->m_prev_return_status;1929}19301931if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))1932d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);19331934if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))1935{1936if (tdefl_flush_block(d, flush) < 0)1937return d->m_prev_return_status;1938d->m_finished = (flush == TDEFL_FINISH);1939if (flush == TDEFL_FULL_FLUSH)1940{1941MZ_CLEAR_OBJ(d->m_hash);1942MZ_CLEAR_OBJ(d->m_next);1943d->m_dict_size = 0;1944}1945}19461947return (d->m_prev_return_status = tdefl_flush_output_buffer(d));1948}19491950tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)1951{1952MZ_ASSERT(d->m_pPut_buf_func);1953return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);1954}19551956tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)1957{1958d->m_pPut_buf_func = pPut_buf_func;1959d->m_pPut_buf_user = pPut_buf_user;1960d->m_flags = (mz_uint)(flags);1961d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;1962d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;1963d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;1964if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))1965MZ_CLEAR_OBJ(d->m_hash);1966d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;1967d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;1968d->m_pLZ_code_buf = d->m_lz_code_buf + 1;1969d->m_pLZ_flags = d->m_lz_code_buf;1970d->m_num_flags_left = 8;1971d->m_pOutput_buf = d->m_output_buf;1972d->m_pOutput_buf_end = d->m_output_buf;1973d->m_prev_return_status = TDEFL_STATUS_OKAY;1974d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;1975d->m_adler32 = 1;1976d->m_pIn_buf = NULL;1977d->m_pOut_buf = NULL;1978d->m_pIn_buf_size = NULL;1979d->m_pOut_buf_size = NULL;1980d->m_flush = TDEFL_NO_FLUSH;1981d->m_pSrc = NULL;1982d->m_src_buf_left = 0;1983d->m_out_buf_ofs = 0;1984if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))1985MZ_CLEAR_OBJ(d->m_dict);1986memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);1987memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);1988return TDEFL_STATUS_OKAY;1989}19901991tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)1992{1993return d->m_prev_return_status;1994}19951996mz_uint32 tdefl_get_adler32(tdefl_compressor *d)1997{1998return d->m_adler32;1999}20002001mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)2002{2003tdefl_compressor *pComp;2004mz_bool succeeded;2005if (((buf_len) && (!pBuf)) || (!pPut_buf_func))2006return MZ_FALSE;2007pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));2008if (!pComp)2009return MZ_FALSE;2010succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);2011succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);2012MZ_FREE(pComp);2013return succeeded;2014}20152016typedef struct2017{2018size_t m_size, m_capacity;2019mz_uint8 *m_pBuf;2020mz_bool m_expandable;2021} tdefl_output_buffer;20222023static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)2024{2025tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;2026size_t new_size = p->m_size + len;2027if (new_size > p->m_capacity)2028{2029size_t new_capacity = p->m_capacity;2030mz_uint8 *pNew_buf;2031if (!p->m_expandable)2032return MZ_FALSE;2033do2034{2035new_capacity = MZ_MAX(128U, new_capacity << 1U);2036} while (new_size > new_capacity);2037pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);2038if (!pNew_buf)2039return MZ_FALSE;2040p->m_pBuf = pNew_buf;2041p->m_capacity = new_capacity;2042}2043memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);2044p->m_size = new_size;2045return MZ_TRUE;2046}20472048void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)2049{2050tdefl_output_buffer out_buf;2051MZ_CLEAR_OBJ(out_buf);2052if (!pOut_len)2053return MZ_FALSE;2054else2055*pOut_len = 0;2056out_buf.m_expandable = MZ_TRUE;2057if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))2058return NULL;2059*pOut_len = out_buf.m_size;2060return out_buf.m_pBuf;2061}20622063size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)2064{2065tdefl_output_buffer out_buf;2066MZ_CLEAR_OBJ(out_buf);2067if (!pOut_buf)2068return 0;2069out_buf.m_pBuf = (mz_uint8 *)pOut_buf;2070out_buf.m_capacity = out_buf_len;2071if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))2072return 0;2073return out_buf.m_size;2074}20752076static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };20772078/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */2079mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)2080{2081mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);2082if (window_bits > 0)2083comp_flags |= TDEFL_WRITE_ZLIB_HEADER;20842085if (!level)2086comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;2087else if (strategy == MZ_FILTERED)2088comp_flags |= TDEFL_FILTER_MATCHES;2089else if (strategy == MZ_HUFFMAN_ONLY)2090comp_flags &= ~TDEFL_MAX_PROBES_MASK;2091else if (strategy == MZ_FIXED)2092comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;2093else if (strategy == MZ_RLE)2094comp_flags |= TDEFL_RLE_MATCHES;20952096return comp_flags;2097}20982099#ifdef _MSC_VER2100#pragma warning(push)2101#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */2102#endif21032104/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at2105http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.2106This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */2107void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip)2108{2109/* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */2110static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };2111tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));2112tdefl_output_buffer out_buf;2113int i, bpl = w * num_chans, y, z;2114mz_uint32 c;2115*pLen_out = 0;2116if (!pComp)2117return NULL;2118MZ_CLEAR_OBJ(out_buf);2119out_buf.m_expandable = MZ_TRUE;2120out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);2121if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity)))2122{2123MZ_FREE(pComp);2124return NULL;2125}2126/* write dummy header */2127for (z = 41; z; --z)2128tdefl_output_buffer_putter(&z, 1, &out_buf);2129/* compress image data */2130tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);2131for (y = 0; y < h; ++y)2132{2133tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);2134tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH);2135}2136if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE)2137{2138MZ_FREE(pComp);2139MZ_FREE(out_buf.m_pBuf);2140return NULL;2141}2142/* write real header */2143*pLen_out = out_buf.m_size - 41;2144{2145static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 };2146mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d,21470x0a, 0x1a, 0x0a, 0x00, 0x00,21480x00, 0x0d, 0x49, 0x48, 0x44,21490x52, 0x00, 0x00, 0x00, 0x00,21500x00, 0x00, 0x00, 0x00, 0x08,21510x00, 0x00, 0x00, 0x00, 0x00,21520x00, 0x00, 0x00, 0x00, 0x00,21530x00, 0x00, 0x49, 0x44, 0x41,21540x54 };2155pnghdr[18] = (mz_uint8)(w >> 8);2156pnghdr[19] = (mz_uint8)w;2157pnghdr[22] = (mz_uint8)(h >> 8);2158pnghdr[23] = (mz_uint8)h;2159pnghdr[25] = chans[num_chans];2160pnghdr[33] = (mz_uint8)(*pLen_out >> 24);2161pnghdr[34] = (mz_uint8)(*pLen_out >> 16);2162pnghdr[35] = (mz_uint8)(*pLen_out >> 8);2163pnghdr[36] = (mz_uint8)*pLen_out;2164c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);2165for (i = 0; i < 4; ++i, c <<= 8)2166((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);2167memcpy(out_buf.m_pBuf, pnghdr, 41);2168}2169/* write footer (IDAT CRC-32, followed by IEND chunk) */2170if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf))2171{2172*pLen_out = 0;2173MZ_FREE(pComp);2174MZ_FREE(out_buf.m_pBuf);2175return NULL;2176}2177c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4);2178for (i = 0; i < 4; ++i, c <<= 8)2179(out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);2180/* compute final size of file, grab compressed data buffer and return */2181*pLen_out += 57;2182MZ_FREE(pComp);2183return out_buf.m_pBuf;2184}2185void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out)2186{2187/* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */2188return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE);2189}21902191#ifndef MINIZ_NO_MALLOC2192/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */2193/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */2194/* structure size and allocation mechanism. */2195tdefl_compressor *tdefl_compressor_alloc()2196{2197return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));2198}21992200void tdefl_compressor_free(tdefl_compressor *pComp)2201{2202MZ_FREE(pComp);2203}2204#endif22052206#ifdef _MSC_VER2207#pragma warning(pop)2208#endif22092210#ifdef __cplusplus2211}2212#endif2213/**************************************************************************2214*2215* Copyright 2013-2014 RAD Game Tools and Valve Software2216* Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC2217* All Rights Reserved.2218*2219* Permission is hereby granted, free of charge, to any person obtaining a copy2220* of this software and associated documentation files (the "Software"), to deal2221* in the Software without restriction, including without limitation the rights2222* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell2223* copies of the Software, and to permit persons to whom the Software is2224* furnished to do so, subject to the following conditions:2225*2226* The above copyright notice and this permission notice shall be included in2227* all copies or substantial portions of the Software.2228*2229* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR2230* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,2231* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE2232* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER2233* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,2234* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN2235* THE SOFTWARE.2236*2237**************************************************************************/2238223922402241#ifdef __cplusplus2242extern "C" {2243#endif22442245/* ------------------- Low-level Decompression (completely independent from all compression API's) */22462247#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)2248#define TINFL_MEMSET(p, c, l) memset(p, c, l)22492250#define TINFL_CR_BEGIN \2251switch (r->m_state) \2252{ \2253case 0:2254#define TINFL_CR_RETURN(state_index, result) \2255do \2256{ \2257status = result; \2258r->m_state = state_index; \2259goto common_exit; \2260case state_index:; \2261} \2262MZ_MACRO_END2263#define TINFL_CR_RETURN_FOREVER(state_index, result) \2264do \2265{ \2266for (;;) \2267{ \2268TINFL_CR_RETURN(state_index, result); \2269} \2270} \2271MZ_MACRO_END2272#define TINFL_CR_FINISH }22732274#define TINFL_GET_BYTE(state_index, c) \2275do \2276{ \2277while (pIn_buf_cur >= pIn_buf_end) \2278{ \2279TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \2280} \2281c = *pIn_buf_cur++; \2282} \2283MZ_MACRO_END22842285#define TINFL_NEED_BITS(state_index, n) \2286do \2287{ \2288mz_uint c; \2289TINFL_GET_BYTE(state_index, c); \2290bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \2291num_bits += 8; \2292} while (num_bits < (mz_uint)(n))2293#define TINFL_SKIP_BITS(state_index, n) \2294do \2295{ \2296if (num_bits < (mz_uint)(n)) \2297{ \2298TINFL_NEED_BITS(state_index, n); \2299} \2300bit_buf >>= (n); \2301num_bits -= (n); \2302} \2303MZ_MACRO_END2304#define TINFL_GET_BITS(state_index, b, n) \2305do \2306{ \2307if (num_bits < (mz_uint)(n)) \2308{ \2309TINFL_NEED_BITS(state_index, n); \2310} \2311b = bit_buf & ((1 << (n)) - 1); \2312bit_buf >>= (n); \2313num_bits -= (n); \2314} \2315MZ_MACRO_END23162317/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */2318/* 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 */2319/* 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 */2320/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */2321#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \2322do \2323{ \2324temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \2325if (temp >= 0) \2326{ \2327code_len = temp >> 9; \2328if ((code_len) && (num_bits >= code_len)) \2329break; \2330} \2331else if (num_bits > TINFL_FAST_LOOKUP_BITS) \2332{ \2333code_len = TINFL_FAST_LOOKUP_BITS; \2334do \2335{ \2336temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \2337} while ((temp < 0) && (num_bits >= (code_len + 1))); \2338if (temp >= 0) \2339break; \2340} \2341TINFL_GET_BYTE(state_index, c); \2342bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \2343num_bits += 8; \2344} while (num_bits < 15);23452346/* 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 */2347/* 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 */2348/* 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. */2349/* The slow path is only executed at the very end of the input buffer. */2350/* 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 */2351/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */2352#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \2353do \2354{ \2355int temp; \2356mz_uint code_len, c; \2357if (num_bits < 15) \2358{ \2359if ((pIn_buf_end - pIn_buf_cur) < 2) \2360{ \2361TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \2362} \2363else \2364{ \2365bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \2366pIn_buf_cur += 2; \2367num_bits += 16; \2368} \2369} \2370if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \2371code_len = temp >> 9, temp &= 511; \2372else \2373{ \2374code_len = TINFL_FAST_LOOKUP_BITS; \2375do \2376{ \2377temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \2378} while (temp < 0); \2379} \2380sym = temp; \2381bit_buf >>= code_len; \2382num_bits -= code_len; \2383} \2384MZ_MACRO_END23852386tinfl_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)2387{2388static 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 };2389static 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 };2390static 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 };2391static 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 };2392static 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 };2393static const int s_min_table_sizes[3] = { 257, 1, 4 };23942395tinfl_status status = TINFL_STATUS_FAILED;2396mz_uint32 num_bits, dist, counter, num_extra;2397tinfl_bit_buf_t bit_buf;2398const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;2399mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;2400size_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;24012402/* 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). */2403if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start))2404{2405*pIn_buf_size = *pOut_buf_size = 0;2406return TINFL_STATUS_BAD_PARAM;2407}24082409num_bits = r->m_num_bits;2410bit_buf = r->m_bit_buf;2411dist = r->m_dist;2412counter = r->m_counter;2413num_extra = r->m_num_extra;2414dist_from_out_buf_start = r->m_dist_from_out_buf_start;2415TINFL_CR_BEGIN24162417bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;2418r->m_z_adler32 = r->m_check_adler32 = 1;2419if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)2420{2421TINFL_GET_BYTE(1, r->m_zhdr0);2422TINFL_GET_BYTE(2, r->m_zhdr1);2423counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));2424if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))2425counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));2426if (counter)2427{2428TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);2429}2430}24312432do2433{2434TINFL_GET_BITS(3, r->m_final, 3);2435r->m_type = r->m_final >> 1;2436if (r->m_type == 0)2437{2438TINFL_SKIP_BITS(5, num_bits & 7);2439for (counter = 0; counter < 4; ++counter)2440{2441if (num_bits)2442TINFL_GET_BITS(6, r->m_raw_header[counter], 8);2443else2444TINFL_GET_BYTE(7, r->m_raw_header[counter]);2445}2446if ((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))))2447{2448TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);2449}2450while ((counter) && (num_bits))2451{2452TINFL_GET_BITS(51, dist, 8);2453while (pOut_buf_cur >= pOut_buf_end)2454{2455TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);2456}2457*pOut_buf_cur++ = (mz_uint8)dist;2458counter--;2459}2460while (counter)2461{2462size_t n;2463while (pOut_buf_cur >= pOut_buf_end)2464{2465TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);2466}2467while (pIn_buf_cur >= pIn_buf_end)2468{2469TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS);2470}2471n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);2472TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);2473pIn_buf_cur += n;2474pOut_buf_cur += n;2475counter -= (mz_uint)n;2476}2477}2478else if (r->m_type == 3)2479{2480TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);2481}2482else2483{2484if (r->m_type == 1)2485{2486mz_uint8 *p = r->m_tables[0].m_code_size;2487mz_uint i;2488r->m_table_sizes[0] = 288;2489r->m_table_sizes[1] = 32;2490TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);2491for (i = 0; i <= 143; ++i)2492*p++ = 8;2493for (; i <= 255; ++i)2494*p++ = 9;2495for (; i <= 279; ++i)2496*p++ = 7;2497for (; i <= 287; ++i)2498*p++ = 8;2499}2500else2501{2502for (counter = 0; counter < 3; counter++)2503{2504TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);2505r->m_table_sizes[counter] += s_min_table_sizes[counter];2506}2507MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);2508for (counter = 0; counter < r->m_table_sizes[2]; counter++)2509{2510mz_uint s;2511TINFL_GET_BITS(14, s, 3);2512r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;2513}2514r->m_table_sizes[2] = 19;2515}2516for (; (int)r->m_type >= 0; r->m_type--)2517{2518int tree_next, tree_cur;2519tinfl_huff_table *pTable;2520mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16];2521pTable = &r->m_tables[r->m_type];2522MZ_CLEAR_OBJ(total_syms);2523MZ_CLEAR_OBJ(pTable->m_look_up);2524MZ_CLEAR_OBJ(pTable->m_tree);2525for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)2526total_syms[pTable->m_code_size[i]]++;2527used_syms = 0, total = 0;2528next_code[0] = next_code[1] = 0;2529for (i = 1; i <= 15; ++i)2530{2531used_syms += total_syms[i];2532next_code[i + 1] = (total = ((total + total_syms[i]) << 1));2533}2534if ((65536 != total) && (used_syms > 1))2535{2536TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);2537}2538for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)2539{2540mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index];2541if (!code_size)2542continue;2543cur_code = next_code[code_size]++;2544for (l = code_size; l > 0; l--, cur_code >>= 1)2545rev_code = (rev_code << 1) | (cur_code & 1);2546if (code_size <= TINFL_FAST_LOOKUP_BITS)2547{2548mz_int16 k = (mz_int16)((code_size << 9) | sym_index);2549while (rev_code < TINFL_FAST_LOOKUP_SIZE)2550{2551pTable->m_look_up[rev_code] = k;2552rev_code += (1 << code_size);2553}2554continue;2555}2556if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)]))2557{2558pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next;2559tree_cur = tree_next;2560tree_next -= 2;2561}2562rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);2563for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)2564{2565tree_cur -= ((rev_code >>= 1) & 1);2566if (!pTable->m_tree[-tree_cur - 1])2567{2568pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;2569tree_cur = tree_next;2570tree_next -= 2;2571}2572else2573tree_cur = pTable->m_tree[-tree_cur - 1];2574}2575tree_cur -= ((rev_code >>= 1) & 1);2576pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;2577}2578if (r->m_type == 2)2579{2580for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);)2581{2582mz_uint s;2583TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);2584if (dist < 16)2585{2586r->m_len_codes[counter++] = (mz_uint8)dist;2587continue;2588}2589if ((dist == 16) && (!counter))2590{2591TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);2592}2593num_extra = "\02\03\07"[dist - 16];2594TINFL_GET_BITS(18, s, num_extra);2595s += "\03\03\013"[dist - 16];2596TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);2597counter += s;2598}2599if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)2600{2601TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);2602}2603TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]);2604TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);2605}2606}2607for (;;)2608{2609mz_uint8 *pSrc;2610for (;;)2611{2612if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))2613{2614TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);2615if (counter >= 256)2616break;2617while (pOut_buf_cur >= pOut_buf_end)2618{2619TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);2620}2621*pOut_buf_cur++ = (mz_uint8)counter;2622}2623else2624{2625int sym2;2626mz_uint code_len;2627#if TINFL_USE_64BIT_BITBUF2628if (num_bits < 30)2629{2630bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);2631pIn_buf_cur += 4;2632num_bits += 32;2633}2634#else2635if (num_bits < 15)2636{2637bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);2638pIn_buf_cur += 2;2639num_bits += 16;2640}2641#endif2642if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)2643code_len = sym2 >> 9;2644else2645{2646code_len = TINFL_FAST_LOOKUP_BITS;2647do2648{2649sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];2650} while (sym2 < 0);2651}2652counter = sym2;2653bit_buf >>= code_len;2654num_bits -= code_len;2655if (counter & 256)2656break;26572658#if !TINFL_USE_64BIT_BITBUF2659if (num_bits < 15)2660{2661bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);2662pIn_buf_cur += 2;2663num_bits += 16;2664}2665#endif2666if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)2667code_len = sym2 >> 9;2668else2669{2670code_len = TINFL_FAST_LOOKUP_BITS;2671do2672{2673sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];2674} while (sym2 < 0);2675}2676bit_buf >>= code_len;2677num_bits -= code_len;26782679pOut_buf_cur[0] = (mz_uint8)counter;2680if (sym2 & 256)2681{2682pOut_buf_cur++;2683counter = sym2;2684break;2685}2686pOut_buf_cur[1] = (mz_uint8)sym2;2687pOut_buf_cur += 2;2688}2689}2690if ((counter &= 511) == 256)2691break;26922693num_extra = s_length_extra[counter - 257];2694counter = s_length_base[counter - 257];2695if (num_extra)2696{2697mz_uint extra_bits;2698TINFL_GET_BITS(25, extra_bits, num_extra);2699counter += extra_bits;2700}27012702TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);2703num_extra = s_dist_extra[dist];2704dist = s_dist_base[dist];2705if (num_extra)2706{2707mz_uint extra_bits;2708TINFL_GET_BITS(27, extra_bits, num_extra);2709dist += extra_bits;2710}27112712dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;2713if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))2714{2715TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);2716}27172718pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);27192720if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)2721{2722while (counter--)2723{2724while (pOut_buf_cur >= pOut_buf_end)2725{2726TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);2727}2728*pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];2729}2730continue;2731}2732#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES2733else if ((counter >= 9) && (counter <= dist))2734{2735const mz_uint8 *pSrc_end = pSrc + (counter & ~7);2736do2737{2738#ifdef MINIZ_UNALIGNED_USE_MEMCPY2739memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2);2740#else2741((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];2742((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];2743#endif2744pOut_buf_cur += 8;2745} while ((pSrc += 8) < pSrc_end);2746if ((counter &= 7) < 3)2747{2748if (counter)2749{2750pOut_buf_cur[0] = pSrc[0];2751if (counter > 1)2752pOut_buf_cur[1] = pSrc[1];2753pOut_buf_cur += counter;2754}2755continue;2756}2757}2758#endif2759while(counter>2)2760{2761pOut_buf_cur[0] = pSrc[0];2762pOut_buf_cur[1] = pSrc[1];2763pOut_buf_cur[2] = pSrc[2];2764pOut_buf_cur += 3;2765pSrc += 3;2766counter -= 3;2767}2768if (counter > 0)2769{2770pOut_buf_cur[0] = pSrc[0];2771if (counter > 1)2772pOut_buf_cur[1] = pSrc[1];2773pOut_buf_cur += counter;2774}2775}2776}2777} while (!(r->m_final & 1));27782779/* 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. */2780/* 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. */2781TINFL_SKIP_BITS(32, num_bits & 7);2782while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8))2783{2784--pIn_buf_cur;2785num_bits -= 8;2786}2787bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);2788MZ_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). */27892790if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)2791{2792for (counter = 0; counter < 4; ++counter)2793{2794mz_uint s;2795if (num_bits)2796TINFL_GET_BITS(41, s, 8);2797else2798TINFL_GET_BYTE(42, s);2799r->m_z_adler32 = (r->m_z_adler32 << 8) | s;2800}2801}2802TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);28032804TINFL_CR_FINISH28052806common_exit:2807/* As long as we aren't telling the caller that we NEED more input to make forward progress: */2808/* 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. */2809/* 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. */2810if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS))2811{2812while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8))2813{2814--pIn_buf_cur;2815num_bits -= 8;2816}2817}2818r->m_num_bits = num_bits;2819r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);2820r->m_dist = dist;2821r->m_counter = counter;2822r->m_num_extra = num_extra;2823r->m_dist_from_out_buf_start = dist_from_out_buf_start;2824*pIn_buf_size = pIn_buf_cur - pIn_buf_next;2825*pOut_buf_size = pOut_buf_cur - pOut_buf_next;2826if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))2827{2828const mz_uint8 *ptr = pOut_buf_next;2829size_t buf_len = *pOut_buf_size;2830mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16;2831size_t block_len = buf_len % 5552;2832while (buf_len)2833{2834for (i = 0; i + 7 < block_len; i += 8, ptr += 8)2835{2836s1 += ptr[0], s2 += s1;2837s1 += ptr[1], s2 += s1;2838s1 += ptr[2], s2 += s1;2839s1 += ptr[3], s2 += s1;2840s1 += ptr[4], s2 += s1;2841s1 += ptr[5], s2 += s1;2842s1 += ptr[6], s2 += s1;2843s1 += ptr[7], s2 += s1;2844}2845for (; i < block_len; ++i)2846s1 += *ptr++, s2 += s1;2847s1 %= 65521U, s2 %= 65521U;2848buf_len -= block_len;2849block_len = 5552;2850}2851r->m_check_adler32 = (s2 << 16) + s1;2852if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32))2853status = TINFL_STATUS_ADLER32_MISMATCH;2854}2855return status;2856}28572858/* Higher level helper functions. */2859void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)2860{2861tinfl_decompressor decomp;2862void *pBuf = NULL, *pNew_buf;2863size_t src_buf_ofs = 0, out_buf_capacity = 0;2864*pOut_len = 0;2865tinfl_init(&decomp);2866for (;;)2867{2868size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;2869tinfl_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,2870(flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);2871if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))2872{2873MZ_FREE(pBuf);2874*pOut_len = 0;2875return NULL;2876}2877src_buf_ofs += src_buf_size;2878*pOut_len += dst_buf_size;2879if (status == TINFL_STATUS_DONE)2880break;2881new_out_buf_capacity = out_buf_capacity * 2;2882if (new_out_buf_capacity < 128)2883new_out_buf_capacity = 128;2884pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);2885if (!pNew_buf)2886{2887MZ_FREE(pBuf);2888*pOut_len = 0;2889return NULL;2890}2891pBuf = pNew_buf;2892out_buf_capacity = new_out_buf_capacity;2893}2894return pBuf;2895}28962897size_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)2898{2899tinfl_decompressor decomp;2900tinfl_status status;2901tinfl_init(&decomp);2902status = 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);2903return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;2904}29052906int 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)2907{2908int result = 0;2909tinfl_decompressor decomp;2910mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);2911size_t in_buf_ofs = 0, dict_ofs = 0;2912if (!pDict)2913return TINFL_STATUS_FAILED;2914tinfl_init(&decomp);2915for (;;)2916{2917size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;2918tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,2919(flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));2920in_buf_ofs += in_buf_size;2921if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))2922break;2923if (status != TINFL_STATUS_HAS_MORE_OUTPUT)2924{2925result = (status == TINFL_STATUS_DONE);2926break;2927}2928dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);2929}2930MZ_FREE(pDict);2931*pIn_buf_size = in_buf_ofs;2932return result;2933}29342935#ifndef MINIZ_NO_MALLOC2936tinfl_decompressor *tinfl_decompressor_alloc()2937{2938tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor));2939if (pDecomp)2940tinfl_init(pDecomp);2941return pDecomp;2942}29432944void tinfl_decompressor_free(tinfl_decompressor *pDecomp)2945{2946MZ_FREE(pDecomp);2947}2948#endif29492950#ifdef __cplusplus2951}2952#endif2953/**************************************************************************2954*2955* Copyright 2013-2014 RAD Game Tools and Valve Software2956* Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC2957* Copyright 2016 Martin Raiber2958* All Rights Reserved.2959*2960* Permission is hereby granted, free of charge, to any person obtaining a copy2961* of this software and associated documentation files (the "Software"), to deal2962* in the Software without restriction, including without limitation the rights2963* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell2964* copies of the Software, and to permit persons to whom the Software is2965* furnished to do so, subject to the following conditions:2966*2967* The above copyright notice and this permission notice shall be included in2968* all copies or substantial portions of the Software.2969*2970* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR2971* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,2972* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE2973* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER2974* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,2975* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN2976* THE SOFTWARE.2977*2978**************************************************************************/297929802981#ifndef MINIZ_NO_ARCHIVE_APIS29822983#ifdef __cplusplus2984extern "C" {2985#endif29862987/* ------------------- .ZIP archive reading */29882989#ifdef MINIZ_NO_STDIO2990#define MZ_FILE void *2991#else2992#include <sys/stat.h>29932994#if defined(_MSC_VER) || defined(__MINGW64__)2995static FILE *mz_fopen(const char *pFilename, const char *pMode)2996{2997FILE *pFile = NULL;2998fopen_s(&pFile, pFilename, pMode);2999return pFile;3000}3001static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream)3002{3003FILE *pFile = NULL;3004if (freopen_s(&pFile, pPath, pMode, pStream))3005return NULL;3006return pFile;3007}3008#ifndef MINIZ_NO_TIME3009#include <sys/utime.h>3010#endif3011#define MZ_FOPEN mz_fopen3012#define MZ_FCLOSE fclose3013#define MZ_FREAD fread3014#define MZ_FWRITE fwrite3015#define MZ_FTELL64 _ftelli643016#define MZ_FSEEK64 _fseeki643017#define MZ_FILE_STAT_STRUCT _stat643018#define MZ_FILE_STAT _stat643019#define MZ_FFLUSH fflush3020#define MZ_FREOPEN mz_freopen3021#define MZ_DELETE_FILE remove3022#elif defined(__MINGW32__)3023#ifndef MINIZ_NO_TIME3024#include <sys/utime.h>3025#endif3026#define MZ_FOPEN(f, m) fopen(f, m)3027#define MZ_FCLOSE fclose3028#define MZ_FREAD fread3029#define MZ_FWRITE fwrite3030#define MZ_FTELL64 ftello643031#define MZ_FSEEK64 fseeko643032#define MZ_FILE_STAT_STRUCT _stat3033#define MZ_FILE_STAT _stat3034#define MZ_FFLUSH fflush3035#define MZ_FREOPEN(f, m, s) freopen(f, m, s)3036#define MZ_DELETE_FILE remove3037#elif defined(__TINYC__)3038#ifndef MINIZ_NO_TIME3039#include <sys/utime.h>3040#endif3041#define MZ_FOPEN(f, m) fopen(f, m)3042#define MZ_FCLOSE fclose3043#define MZ_FREAD fread3044#define MZ_FWRITE fwrite3045#define MZ_FTELL64 ftell3046#define MZ_FSEEK64 fseek3047#define MZ_FILE_STAT_STRUCT stat3048#define MZ_FILE_STAT stat3049#define MZ_FFLUSH fflush3050#define MZ_FREOPEN(f, m, s) freopen(f, m, s)3051#define MZ_DELETE_FILE remove3052#elif defined(__USE_LARGEFILE64) // gcc, clang3053#ifndef MINIZ_NO_TIME3054#include <utime.h>3055#endif3056#define MZ_FOPEN(f, m) fopen64(f, m)3057#define MZ_FCLOSE fclose3058#define MZ_FREAD fread3059#define MZ_FWRITE fwrite3060#define MZ_FTELL64 ftello643061#define MZ_FSEEK64 fseeko643062#define MZ_FILE_STAT_STRUCT stat643063#define MZ_FILE_STAT stat643064#define MZ_FFLUSH fflush3065#define MZ_FREOPEN(p, m, s) freopen64(p, m, s)3066#define MZ_DELETE_FILE remove3067#elif defined(__APPLE__)3068#ifndef MINIZ_NO_TIME3069#include <utime.h>3070#endif3071#define MZ_FOPEN(f, m) fopen(f, m)3072#define MZ_FCLOSE fclose3073#define MZ_FREAD fread3074#define MZ_FWRITE fwrite3075#define MZ_FTELL64 ftello3076#define MZ_FSEEK64 fseeko3077#define MZ_FILE_STAT_STRUCT stat3078#define MZ_FILE_STAT stat3079#define MZ_FFLUSH fflush3080#define MZ_FREOPEN(p, m, s) freopen(p, m, s)3081#define MZ_DELETE_FILE remove30823083#else3084#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.")3085#ifndef MINIZ_NO_TIME3086#include <utime.h>3087#endif3088#define MZ_FOPEN(f, m) fopen(f, m)3089#define MZ_FCLOSE fclose3090#define MZ_FREAD fread3091#define MZ_FWRITE fwrite3092#ifdef __STRICT_ANSI__3093#define MZ_FTELL64 ftell3094#define MZ_FSEEK64 fseek3095#else3096#define MZ_FTELL64 ftello3097#define MZ_FSEEK64 fseeko3098#endif3099#define MZ_FILE_STAT_STRUCT stat3100#define MZ_FILE_STAT stat3101#define MZ_FFLUSH fflush3102#define MZ_FREOPEN(f, m, s) freopen(f, m, s)3103#define MZ_DELETE_FILE remove3104#endif /* #ifdef _MSC_VER */3105#endif /* #ifdef MINIZ_NO_STDIO */31063107#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))31083109/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */3110enum3111{3112/* ZIP archive identifiers and record sizes */3113MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,3114MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,3115MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,3116MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,3117MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,3118MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,31193120/* ZIP64 archive identifier and record sizes */3121MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50,3122MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50,3123MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56,3124MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20,3125MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001,3126MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50,3127MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24,3128MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16,31293130/* Central directory header record offsets */3131MZ_ZIP_CDH_SIG_OFS = 0,3132MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,3133MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,3134MZ_ZIP_CDH_BIT_FLAG_OFS = 8,3135MZ_ZIP_CDH_METHOD_OFS = 10,3136MZ_ZIP_CDH_FILE_TIME_OFS = 12,3137MZ_ZIP_CDH_FILE_DATE_OFS = 14,3138MZ_ZIP_CDH_CRC32_OFS = 16,3139MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,3140MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,3141MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,3142MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,3143MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,3144MZ_ZIP_CDH_DISK_START_OFS = 34,3145MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,3146MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,3147MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,31483149/* Local directory header offsets */3150MZ_ZIP_LDH_SIG_OFS = 0,3151MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,3152MZ_ZIP_LDH_BIT_FLAG_OFS = 6,3153MZ_ZIP_LDH_METHOD_OFS = 8,3154MZ_ZIP_LDH_FILE_TIME_OFS = 10,3155MZ_ZIP_LDH_FILE_DATE_OFS = 12,3156MZ_ZIP_LDH_CRC32_OFS = 14,3157MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,3158MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,3159MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,3160MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,3161MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3,31623163/* End of central directory offsets */3164MZ_ZIP_ECDH_SIG_OFS = 0,3165MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,3166MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,3167MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,3168MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,3169MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,3170MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,3171MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,31723173/* ZIP64 End of central directory locator offsets */3174MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */3175MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */3176MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */3177MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */31783179/* ZIP64 End of central directory header offsets */3180MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */3181MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */3182MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */3183MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */3184MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */3185MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */3186MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */3187MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */3188MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */3189MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */3190MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0,3191MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10,3192MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1,3193MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32,3194MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64,3195MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192,3196MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 113197};31983199typedef struct3200{3201void *m_p;3202size_t m_size, m_capacity;3203mz_uint m_element_size;3204} mz_zip_array;32053206struct mz_zip_internal_state_tag3207{3208mz_zip_array m_central_dir;3209mz_zip_array m_central_dir_offsets;3210mz_zip_array m_sorted_central_dir_offsets;32113212/* The flags passed in when the archive is initially opened. */3213uint32_t m_init_flags;32143215/* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */3216mz_bool m_zip64;32173218/* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */3219mz_bool m_zip64_has_extended_info_fields;32203221/* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */3222MZ_FILE *m_pFile;3223mz_uint64 m_file_archive_start_ofs;32243225void *m_pMem;3226size_t m_mem_size;3227size_t m_mem_capacity;3228};32293230#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size32313232#if defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG)3233static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index)3234{3235MZ_ASSERT(index < pArray->m_size);3236return index;3237}3238#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)]3239#else3240#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index]3241#endif32423243static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size)3244{3245memset(pArray, 0, sizeof(mz_zip_array));3246pArray->m_element_size = element_size;3247}32483249static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray)3250{3251pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);3252memset(pArray, 0, sizeof(mz_zip_array));3253}32543255static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing)3256{3257void *pNew_p;3258size_t new_capacity = min_new_capacity;3259MZ_ASSERT(pArray->m_element_size);3260if (pArray->m_capacity >= min_new_capacity)3261return MZ_TRUE;3262if (growing)3263{3264new_capacity = MZ_MAX(1, pArray->m_capacity);3265while (new_capacity < min_new_capacity)3266new_capacity *= 2;3267}3268if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity)))3269return MZ_FALSE;3270pArray->m_p = pNew_p;3271pArray->m_capacity = new_capacity;3272return MZ_TRUE;3273}32743275static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing)3276{3277if (new_capacity > pArray->m_capacity)3278{3279if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))3280return MZ_FALSE;3281}3282return MZ_TRUE;3283}32843285static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing)3286{3287if (new_size > pArray->m_capacity)3288{3289if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))3290return MZ_FALSE;3291}3292pArray->m_size = new_size;3293return MZ_TRUE;3294}32953296static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n)3297{3298return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);3299}33003301static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n)3302{3303size_t orig_size = pArray->m_size;3304if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))3305return MZ_FALSE;3306if (n > 0)3307memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size);3308return MZ_TRUE;3309}33103311#ifndef MINIZ_NO_TIME3312static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date)3313{3314struct tm tm;3315memset(&tm, 0, sizeof(tm));3316tm.tm_isdst = -1;3317tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;3318tm.tm_mon = ((dos_date >> 5) & 15) - 1;3319tm.tm_mday = dos_date & 31;3320tm.tm_hour = (dos_time >> 11) & 31;3321tm.tm_min = (dos_time >> 5) & 63;3322tm.tm_sec = (dos_time << 1) & 62;3323return mktime(&tm);3324}33253326#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS3327static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)3328{3329#ifdef _MSC_VER3330struct tm tm_struct;3331struct tm *tm = &tm_struct;3332errno_t err = localtime_s(tm, &time);3333if (err)3334{3335*pDOS_date = 0;3336*pDOS_time = 0;3337return;3338}3339#else3340struct tm *tm = localtime(&time);3341#endif /* #ifdef _MSC_VER */33423343*pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1));3344*pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday);3345}3346#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */33473348#ifndef MINIZ_NO_STDIO3349#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS3350static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime)3351{3352struct MZ_FILE_STAT_STRUCT file_stat;33533354/* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */3355if (MZ_FILE_STAT(pFilename, &file_stat) != 0)3356return MZ_FALSE;33573358*pTime = file_stat.st_mtime;33593360return MZ_TRUE;3361}3362#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/33633364static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time)3365{3366struct utimbuf t;33673368memset(&t, 0, sizeof(t));3369t.actime = access_time;3370t.modtime = modified_time;33713372return !utime(pFilename, &t);3373}3374#endif /* #ifndef MINIZ_NO_STDIO */3375#endif /* #ifndef MINIZ_NO_TIME */33763377static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num)3378{3379if (pZip)3380pZip->m_last_error = err_num;3381return MZ_FALSE;3382}33833384static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags)3385{3386(void)flags;3387if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))3388return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);33893390if (!pZip->m_pAlloc)3391pZip->m_pAlloc = miniz_def_alloc_func;3392if (!pZip->m_pFree)3393pZip->m_pFree = miniz_def_free_func;3394if (!pZip->m_pRealloc)3395pZip->m_pRealloc = miniz_def_realloc_func;33963397pZip->m_archive_size = 0;3398pZip->m_central_directory_file_ofs = 0;3399pZip->m_total_files = 0;3400pZip->m_last_error = MZ_ZIP_NO_ERROR;34013402if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))3403return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);34043405memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));3406MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));3407MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));3408MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));3409pZip->m_pState->m_init_flags = flags;3410pZip->m_pState->m_zip64 = MZ_FALSE;3411pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE;34123413pZip->m_zip_mode = MZ_ZIP_MODE_READING;34143415return MZ_TRUE;3416}34173418static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index)3419{3420const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;3421const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));3422mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);3423mz_uint8 l = 0, r = 0;3424pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;3425pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;3426pE = pL + MZ_MIN(l_len, r_len);3427while (pL < pE)3428{3429if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))3430break;3431pL++;3432pR++;3433}3434return (pL == pE) ? (l_len < r_len) : (l < r);3435}34363437#define MZ_SWAP_UINT32(a, b) \3438do \3439{ \3440mz_uint32 t = a; \3441a = b; \3442b = t; \3443} \3444MZ_MACRO_END34453446/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */3447static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip)3448{3449mz_zip_internal_state *pState = pZip->m_pState;3450const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;3451const mz_zip_array *pCentral_dir = &pState->m_central_dir;3452mz_uint32 *pIndices;3453mz_uint32 start, end;3454const mz_uint32 size = pZip->m_total_files;34553456if (size <= 1U)3457return;34583459pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);34603461start = (size - 2U) >> 1U;3462for (;;)3463{3464mz_uint64 child, root = start;3465for (;;)3466{3467if ((child = (root << 1U) + 1U) >= size)3468break;3469child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])));3470if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))3471break;3472MZ_SWAP_UINT32(pIndices[root], pIndices[child]);3473root = child;3474}3475if (!start)3476break;3477start--;3478}34793480end = size - 1;3481while (end > 0)3482{3483mz_uint64 child, root = 0;3484MZ_SWAP_UINT32(pIndices[end], pIndices[0]);3485for (;;)3486{3487if ((child = (root << 1U) + 1U) >= end)3488break;3489child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]));3490if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))3491break;3492MZ_SWAP_UINT32(pIndices[root], pIndices[child]);3493root = child;3494}3495end--;3496}3497}34983499static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs)3500{3501mz_int64 cur_file_ofs;3502mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];3503mz_uint8 *pBuf = (mz_uint8 *)buf_u32;35043505/* Basic sanity checks - reject files which are too small */3506if (pZip->m_archive_size < record_size)3507return MZ_FALSE;35083509/* Find the record by scanning the file from the end towards the beginning. */3510cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);3511for (;;)3512{3513int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);35143515if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)3516return MZ_FALSE;35173518for (i = n - 4; i >= 0; --i)3519{3520mz_uint s = MZ_READ_LE32(pBuf + i);3521if (s == record_sig)3522{3523if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size)3524break;3525}3526}35273528if (i >= 0)3529{3530cur_file_ofs += i;3531break;3532}35333534/* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */3535if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size)))3536return MZ_FALSE;35373538cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);3539}35403541*pOfs = cur_file_ofs;3542return MZ_TRUE;3543}35443545static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags)3546{3547mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0;3548mz_uint64 cdir_ofs = 0;3549mz_int64 cur_file_ofs = 0;3550const mz_uint8 *p;35513552mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];3553mz_uint8 *pBuf = (mz_uint8 *)buf_u32;3554mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);3555mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];3556mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32;35573558mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];3559mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32;35603561mz_uint64 zip64_end_of_central_dir_ofs = 0;35623563/* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */3564if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)3565return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);35663567if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs))3568return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR);35693570/* Read and verify the end of central directory record. */3571if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)3572return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);35733574if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)3575return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);35763577if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE))3578{3579if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE)3580{3581if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG)3582{3583zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS);3584if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE))3585return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);35863587if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)3588{3589if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG)3590{3591pZip->m_pState->m_zip64 = MZ_TRUE;3592}3593}3594}3595}3596}35973598pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS);3599cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS);3600num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);3601cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);3602cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS);3603cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);36043605if (pZip->m_pState->m_zip64)3606{3607mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS);3608mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS);3609mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS);3610mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS);3611mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS);36123613if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12))3614return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);36153616if (zip64_total_num_of_disks != 1U)3617return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);36183619/* Check for miniz's practical limits */3620if (zip64_cdir_total_entries > MZ_UINT32_MAX)3621return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);36223623pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries;36243625if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX)3626return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);36273628cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk;36293630/* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */3631if (zip64_size_of_central_directory > MZ_UINT32_MAX)3632return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);36333634cdir_size = (mz_uint32)zip64_size_of_central_directory;36353636num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS);36373638cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS);36393640cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS);3641}36423643if (pZip->m_total_files != cdir_entries_on_this_disk)3644return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);36453646if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1)))3647return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);36483649if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)3650return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);36513652if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)3653return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);36543655pZip->m_central_directory_file_ofs = cdir_ofs;36563657if (pZip->m_total_files)3658{3659mz_uint i, n;3660/* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */3661if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) ||3662(!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)))3663return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);36643665if (sort_central_dir)3666{3667if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))3668return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);3669}36703671if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size)3672return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);36733674/* Now create an index into the central directory file records, do some basic sanity checking on each record */3675p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;3676for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i)3677{3678mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size;3679mz_uint64 comp_size, decomp_size, local_header_ofs;36803681if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))3682return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);36833684MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);36853686if (sort_central_dir)3687MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i;36883689comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);3690decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);3691local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);3692filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);3693ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS);36943695if ((!pZip->m_pState->m_zip64_has_extended_info_fields) &&3696(ext_data_size) &&3697(MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX))3698{3699/* Attempt to find zip64 extended information field in the entry's extra data */3700mz_uint32 extra_size_remaining = ext_data_size;37013702if (extra_size_remaining)3703{3704const mz_uint8 *pExtra_data;3705void* buf = NULL;37063707if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n)3708{3709buf = MZ_MALLOC(ext_data_size);3710if(buf==NULL)3711return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);37123713if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size)3714{3715MZ_FREE(buf);3716return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);3717}37183719pExtra_data = (mz_uint8*)buf;3720}3721else3722{3723pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size;3724}37253726do3727{3728mz_uint32 field_id;3729mz_uint32 field_data_size;37303731if (extra_size_remaining < (sizeof(mz_uint16) * 2))3732{3733MZ_FREE(buf);3734return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);3735}37363737field_id = MZ_READ_LE16(pExtra_data);3738field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));37393740if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining)3741{3742MZ_FREE(buf);3743return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);3744}37453746if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID)3747{3748/* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */3749pZip->m_pState->m_zip64 = MZ_TRUE;3750pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE;3751break;3752}37533754pExtra_data += sizeof(mz_uint16) * 2 + field_data_size;3755extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size;3756} while (extra_size_remaining);37573758MZ_FREE(buf);3759}3760}37613762/* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */3763if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX))3764{3765if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size))3766return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);3767}37683769disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);3770if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1)))3771return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);37723773if (comp_size != MZ_UINT32_MAX)3774{3775if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)3776return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);3777}37783779bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);3780if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED)3781return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);37823783if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n)3784return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);37853786n -= total_header_size;3787p += total_header_size;3788}3789}37903791if (sort_central_dir)3792mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);37933794return MZ_TRUE;3795}37963797void mz_zip_zero_struct(mz_zip_archive *pZip)3798{3799if (pZip)3800MZ_CLEAR_OBJ(*pZip);3801}38023803static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error)3804{3805mz_bool status = MZ_TRUE;38063807if (!pZip)3808return MZ_FALSE;38093810if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))3811{3812if (set_last_error)3813pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER;38143815return MZ_FALSE;3816}38173818if (pZip->m_pState)3819{3820mz_zip_internal_state *pState = pZip->m_pState;3821pZip->m_pState = NULL;38223823mz_zip_array_clear(pZip, &pState->m_central_dir);3824mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);3825mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);38263827#ifndef MINIZ_NO_STDIO3828if (pState->m_pFile)3829{3830if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE)3831{3832if (MZ_FCLOSE(pState->m_pFile) == EOF)3833{3834if (set_last_error)3835pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED;3836status = MZ_FALSE;3837}3838}3839pState->m_pFile = NULL;3840}3841#endif /* #ifndef MINIZ_NO_STDIO */38423843pZip->m_pFree(pZip->m_pAlloc_opaque, pState);3844}3845pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;38463847return status;3848}38493850mz_bool mz_zip_reader_end(mz_zip_archive *pZip)3851{3852return mz_zip_reader_end_internal(pZip, MZ_TRUE);3853}3854mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags)3855{3856if ((!pZip) || (!pZip->m_pRead))3857return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);38583859if (!mz_zip_reader_init_internal(pZip, flags))3860return MZ_FALSE;38613862pZip->m_zip_type = MZ_ZIP_TYPE_USER;3863pZip->m_archive_size = size;38643865if (!mz_zip_reader_read_central_dir(pZip, flags))3866{3867mz_zip_reader_end_internal(pZip, MZ_FALSE);3868return MZ_FALSE;3869}38703871return MZ_TRUE;3872}38733874static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)3875{3876mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;3877size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);3878memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);3879return s;3880}38813882mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags)3883{3884if (!pMem)3885return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);38863887if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)3888return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);38893890if (!mz_zip_reader_init_internal(pZip, flags))3891return MZ_FALSE;38923893pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY;3894pZip->m_archive_size = size;3895pZip->m_pRead = mz_zip_mem_read_func;3896pZip->m_pIO_opaque = pZip;3897pZip->m_pNeeds_keepalive = NULL;38983899#ifdef __cplusplus3900pZip->m_pState->m_pMem = const_cast<void *>(pMem);3901#else3902pZip->m_pState->m_pMem = (void *)pMem;3903#endif39043905pZip->m_pState->m_mem_size = size;39063907if (!mz_zip_reader_read_central_dir(pZip, flags))3908{3909mz_zip_reader_end_internal(pZip, MZ_FALSE);3910return MZ_FALSE;3911}39123913return MZ_TRUE;3914}39153916#ifndef MINIZ_NO_STDIO3917static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)3918{3919mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;3920mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);39213922file_ofs += pZip->m_pState->m_file_archive_start_ofs;39233924if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))3925return 0;39263927return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);3928}39293930mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags)3931{3932return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0);3933}39343935mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size)3936{3937mz_uint64 file_size;3938MZ_FILE *pFile;39393940if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))3941return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);39423943pFile = MZ_FOPEN(pFilename, "rb");3944if (!pFile)3945return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);39463947file_size = archive_size;3948if (!file_size)3949{3950if (MZ_FSEEK64(pFile, 0, SEEK_END))3951{3952MZ_FCLOSE(pFile);3953return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);3954}39553956file_size = MZ_FTELL64(pFile);3957}39583959/* TODO: Better sanity check archive_size and the # of actual remaining bytes */39603961if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)3962{3963MZ_FCLOSE(pFile);3964return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);3965}39663967if (!mz_zip_reader_init_internal(pZip, flags))3968{3969MZ_FCLOSE(pFile);3970return MZ_FALSE;3971}39723973pZip->m_zip_type = MZ_ZIP_TYPE_FILE;3974pZip->m_pRead = mz_zip_file_read_func;3975pZip->m_pIO_opaque = pZip;3976pZip->m_pState->m_pFile = pFile;3977pZip->m_archive_size = file_size;3978pZip->m_pState->m_file_archive_start_ofs = file_start_ofs;39793980if (!mz_zip_reader_read_central_dir(pZip, flags))3981{3982mz_zip_reader_end_internal(pZip, MZ_FALSE);3983return MZ_FALSE;3984}39853986return MZ_TRUE;3987}39883989mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags)3990{3991mz_uint64 cur_file_ofs;39923993if ((!pZip) || (!pFile))3994return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);39953996cur_file_ofs = MZ_FTELL64(pFile);39973998if (!archive_size)3999{4000if (MZ_FSEEK64(pFile, 0, SEEK_END))4001return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);40024003archive_size = MZ_FTELL64(pFile) - cur_file_ofs;40044005if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)4006return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);4007}40084009if (!mz_zip_reader_init_internal(pZip, flags))4010return MZ_FALSE;40114012pZip->m_zip_type = MZ_ZIP_TYPE_CFILE;4013pZip->m_pRead = mz_zip_file_read_func;40144015pZip->m_pIO_opaque = pZip;4016pZip->m_pState->m_pFile = pFile;4017pZip->m_archive_size = archive_size;4018pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs;40194020if (!mz_zip_reader_read_central_dir(pZip, flags))4021{4022mz_zip_reader_end_internal(pZip, MZ_FALSE);4023return MZ_FALSE;4024}40254026return MZ_TRUE;4027}40284029#endif /* #ifndef MINIZ_NO_STDIO */40304031static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index)4032{4033if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files))4034return NULL;4035return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));4036}40374038mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index)4039{4040mz_uint m_bit_flag;4041const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);4042if (!p)4043{4044mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);4045return MZ_FALSE;4046}40474048m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);4049return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0;4050}40514052mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index)4053{4054mz_uint bit_flag;4055mz_uint method;40564057const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);4058if (!p)4059{4060mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);4061return MZ_FALSE;4062}40634064method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);4065bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);40664067if ((method != 0) && (method != MZ_DEFLATED))4068{4069mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);4070return MZ_FALSE;4071}40724073if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION))4074{4075mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);4076return MZ_FALSE;4077}40784079if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)4080{4081mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);4082return MZ_FALSE;4083}40844085return MZ_TRUE;4086}40874088mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index)4089{4090mz_uint filename_len, attribute_mapping_id, external_attr;4091const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);4092if (!p)4093{4094mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);4095return MZ_FALSE;4096}40974098filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);4099if (filename_len)4100{4101if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')4102return MZ_TRUE;4103}41044105/* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */4106/* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */4107/* FIXME: Remove this check? Is it necessary - we already check the filename. */4108attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8;4109(void)attribute_mapping_id;41104111external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);4112if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0)4113{4114return MZ_TRUE;4115}41164117return MZ_FALSE;4118}41194120static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data)4121{4122mz_uint n;4123const mz_uint8 *p = pCentral_dir_header;41244125if (pFound_zip64_extra_data)4126*pFound_zip64_extra_data = MZ_FALSE;41274128if ((!p) || (!pStat))4129return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);41304131/* Extract fields from the central directory record. */4132pStat->m_file_index = file_index;4133pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);4134pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);4135pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);4136pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);4137pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);4138#ifndef MINIZ_NO_TIME4139pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));4140#endif4141pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);4142pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);4143pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);4144pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);4145pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);4146pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);41474148/* Copy as much of the filename and comment as possible. */4149n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);4150n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);4151memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);4152pStat->m_filename[n] = '\0';41534154n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);4155n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);4156pStat->m_comment_size = n;4157memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n);4158pStat->m_comment[n] = '\0';41594160/* Set some flags for convienance */4161pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index);4162pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index);4163pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index);41644165/* See if we need to read any zip64 extended information fields. */4166/* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */4167if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX)4168{4169/* Attempt to find zip64 extended information field in the entry's extra data */4170mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS);41714172if (extra_size_remaining)4173{4174const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);41754176do4177{4178mz_uint32 field_id;4179mz_uint32 field_data_size;41804181if (extra_size_remaining < (sizeof(mz_uint16) * 2))4182return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);41834184field_id = MZ_READ_LE16(pExtra_data);4185field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));41864187if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining)4188return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);41894190if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID)4191{4192const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2;4193mz_uint32 field_data_remaining = field_data_size;41944195if (pFound_zip64_extra_data)4196*pFound_zip64_extra_data = MZ_TRUE;41974198if (pStat->m_uncomp_size == MZ_UINT32_MAX)4199{4200if (field_data_remaining < sizeof(mz_uint64))4201return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);42024203pStat->m_uncomp_size = MZ_READ_LE64(pField_data);4204pField_data += sizeof(mz_uint64);4205field_data_remaining -= sizeof(mz_uint64);4206}42074208if (pStat->m_comp_size == MZ_UINT32_MAX)4209{4210if (field_data_remaining < sizeof(mz_uint64))4211return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);42124213pStat->m_comp_size = MZ_READ_LE64(pField_data);4214pField_data += sizeof(mz_uint64);4215field_data_remaining -= sizeof(mz_uint64);4216}42174218if (pStat->m_local_header_ofs == MZ_UINT32_MAX)4219{4220if (field_data_remaining < sizeof(mz_uint64))4221return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);42224223pStat->m_local_header_ofs = MZ_READ_LE64(pField_data);4224pField_data += sizeof(mz_uint64);4225field_data_remaining -= sizeof(mz_uint64);4226}42274228break;4229}42304231pExtra_data += sizeof(mz_uint16) * 2 + field_data_size;4232extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size;4233} while (extra_size_remaining);4234}4235}42364237return MZ_TRUE;4238}42394240static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags)4241{4242mz_uint i;4243if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)4244return 0 == memcmp(pA, pB, len);4245for (i = 0; i < len; ++i)4246if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))4247return MZ_FALSE;4248return MZ_TRUE;4249}42504251static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len)4252{4253const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;4254mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);4255mz_uint8 l = 0, r = 0;4256pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;4257pE = pL + MZ_MIN(l_len, r_len);4258while (pL < pE)4259{4260if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))4261break;4262pL++;4263pR++;4264}4265return (pL == pE) ? (int)(l_len - r_len) : (l - r);4266}42674268static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex)4269{4270mz_zip_internal_state *pState = pZip->m_pState;4271const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;4272const mz_zip_array *pCentral_dir = &pState->m_central_dir;4273mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);4274const uint32_t size = pZip->m_total_files;4275const mz_uint filename_len = (mz_uint)strlen(pFilename);42764277if (pIndex)4278*pIndex = 0;42794280if (size)4281{4282/* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */4283/* honestly the major expense here on 32-bit CPU's will still be the filename compare */4284mz_int64 l = 0, h = (mz_int64)size - 1;42854286while (l <= h)4287{4288mz_int64 m = l + ((h - l) >> 1);4289uint32_t file_index = pIndices[(uint32_t)m];42904291int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len);4292if (!comp)4293{4294if (pIndex)4295*pIndex = file_index;4296return MZ_TRUE;4297}4298else if (comp < 0)4299l = m + 1;4300else4301h = m - 1;4302}4303}43044305return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND);4306}43074308int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags)4309{4310mz_uint32 index;4311if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index))4312return -1;4313else4314return (int)index;4315}43164317mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex)4318{4319mz_uint file_index;4320size_t name_len, comment_len;43214322if (pIndex)4323*pIndex = 0;43244325if ((!pZip) || (!pZip->m_pState) || (!pName))4326return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);43274328/* See if we can use a binary search */4329if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) &&4330(pZip->m_zip_mode == MZ_ZIP_MODE_READING) &&4331((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))4332{4333return mz_zip_locate_file_binary_search(pZip, pName, pIndex);4334}43354336/* Locate the entry by scanning the entire central directory */4337name_len = strlen(pName);4338if (name_len > MZ_UINT16_MAX)4339return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);43404341comment_len = pComment ? strlen(pComment) : 0;4342if (comment_len > MZ_UINT16_MAX)4343return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);43444345for (file_index = 0; file_index < pZip->m_total_files; file_index++)4346{4347const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));4348mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);4349const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;4350if (filename_len < name_len)4351continue;4352if (comment_len)4353{4354mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);4355const char *pFile_comment = pFilename + filename_len + file_extra_len;4356if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags)))4357continue;4358}4359if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len))4360{4361int ofs = filename_len - 1;4362do4363{4364if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':'))4365break;4366} while (--ofs >= 0);4367ofs++;4368pFilename += ofs;4369filename_len -= ofs;4370}4371if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags)))4372{4373if (pIndex)4374*pIndex = file_index;4375return MZ_TRUE;4376}4377}43784379return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND);4380}43814382mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)4383{4384int status = TINFL_STATUS_DONE;4385mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;4386mz_zip_archive_file_stat file_stat;4387void *pRead_buf;4388mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];4389mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;4390tinfl_decompressor inflator;43914392if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead))4393return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);43944395if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))4396return MZ_FALSE;43974398/* A directory or zero length file */4399if ((file_stat.m_is_directory) || (!file_stat.m_comp_size))4400return MZ_TRUE;44014402/* Encryption and patch files are not supported. */4403if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG))4404return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);44054406/* This function only supports decompressing stored and deflate. */4407if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))4408return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);44094410/* Ensure supplied output buffer is large enough. */4411needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size;4412if (buf_size < needed_size)4413return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL);44144415/* Read and parse the local directory entry. */4416cur_file_ofs = file_stat.m_local_header_ofs;4417if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)4418return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);44194420if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)4421return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);44224423cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);4424if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)4425return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);44264427if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))4428{4429/* The file is stored or the caller has requested the compressed data. */4430if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size)4431return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);44324433#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4434if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0)4435{4436if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)4437return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED);4438}4439#endif44404441return MZ_TRUE;4442}44434444/* Decompress the file either directly from memory or from a file input buffer. */4445tinfl_init(&inflator);44464447if (pZip->m_pState->m_pMem)4448{4449/* Read directly from the archive in memory. */4450pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;4451read_buf_size = read_buf_avail = file_stat.m_comp_size;4452comp_remaining = 0;4453}4454else if (pUser_read_buf)4455{4456/* Use a user provided read buffer. */4457if (!user_read_buf_size)4458return MZ_FALSE;4459pRead_buf = (mz_uint8 *)pUser_read_buf;4460read_buf_size = user_read_buf_size;4461read_buf_avail = 0;4462comp_remaining = file_stat.m_comp_size;4463}4464else4465{4466/* Temporarily allocate a read buffer. */4467read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);4468if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))4469return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);44704471if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))4472return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);44734474read_buf_avail = 0;4475comp_remaining = file_stat.m_comp_size;4476}44774478do4479{4480/* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */4481size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);4482if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))4483{4484read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);4485if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)4486{4487status = TINFL_STATUS_FAILED;4488mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED);4489break;4490}4491cur_file_ofs += read_buf_avail;4492comp_remaining -= read_buf_avail;4493read_buf_ofs = 0;4494}4495in_buf_size = (size_t)read_buf_avail;4496status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));4497read_buf_avail -= in_buf_size;4498read_buf_ofs += in_buf_size;4499out_buf_ofs += out_buf_size;4500} while (status == TINFL_STATUS_NEEDS_MORE_INPUT);45014502if (status == TINFL_STATUS_DONE)4503{4504/* Make sure the entire file was decompressed, and check its CRC. */4505if (out_buf_ofs != file_stat.m_uncomp_size)4506{4507mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE);4508status = TINFL_STATUS_FAILED;4509}4510#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4511else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)4512{4513mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED);4514status = TINFL_STATUS_FAILED;4515}4516#endif4517}45184519if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))4520pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);45214522return status == TINFL_STATUS_DONE;4523}45244525mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)4526{4527mz_uint32 file_index;4528if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))4529return MZ_FALSE;4530return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size);4531}45324533mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags)4534{4535return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0);4536}45374538mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags)4539{4540return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0);4541}45424543void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags)4544{4545mz_uint64 comp_size, uncomp_size, alloc_size;4546const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);4547void *pBuf;45484549if (pSize)4550*pSize = 0;45514552if (!p)4553{4554mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);4555return NULL;4556}45574558comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);4559uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);45604561alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;4562if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))4563{4564mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);4565return NULL;4566}45674568if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))4569{4570mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);4571return NULL;4572}45734574if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags))4575{4576pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);4577return NULL;4578}45794580if (pSize)4581*pSize = (size_t)alloc_size;4582return pBuf;4583}45844585void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags)4586{4587mz_uint32 file_index;4588if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))4589{4590if (pSize)4591*pSize = 0;4592return MZ_FALSE;4593}4594return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);4595}45964597mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)4598{4599int status = TINFL_STATUS_DONE;4600mz_uint file_crc32 = MZ_CRC32_INIT;4601mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs;4602mz_zip_archive_file_stat file_stat;4603void *pRead_buf = NULL;4604void *pWrite_buf = NULL;4605mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];4606mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;46074608if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead))4609return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);46104611if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))4612return MZ_FALSE;46134614/* A directory or zero length file */4615if ((file_stat.m_is_directory) || (!file_stat.m_comp_size))4616return MZ_TRUE;46174618/* Encryption and patch files are not supported. */4619if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG))4620return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);46214622/* This function only supports decompressing stored and deflate. */4623if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))4624return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);46254626/* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */4627cur_file_ofs = file_stat.m_local_header_ofs;4628if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)4629return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);46304631if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)4632return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);46334634cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);4635if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)4636return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);46374638/* Decompress the file either directly from memory or from a file input buffer. */4639if (pZip->m_pState->m_pMem)4640{4641pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;4642read_buf_size = read_buf_avail = file_stat.m_comp_size;4643comp_remaining = 0;4644}4645else4646{4647read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);4648if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))4649return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);46504651read_buf_avail = 0;4652comp_remaining = file_stat.m_comp_size;4653}46544655if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))4656{4657/* The file is stored or the caller has requested the compressed data. */4658if (pZip->m_pState->m_pMem)4659{4660if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX))4661return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);46624663if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)4664{4665mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED);4666status = TINFL_STATUS_FAILED;4667}4668else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))4669{4670#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4671file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size);4672#endif4673}46744675cur_file_ofs += file_stat.m_comp_size;4676out_buf_ofs += file_stat.m_comp_size;4677comp_remaining = 0;4678}4679else4680{4681while (comp_remaining)4682{4683read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);4684if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)4685{4686mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);4687status = TINFL_STATUS_FAILED;4688break;4689}46904691#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4692if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))4693{4694file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);4695}4696#endif46974698if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)4699{4700mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED);4701status = TINFL_STATUS_FAILED;4702break;4703}47044705cur_file_ofs += read_buf_avail;4706out_buf_ofs += read_buf_avail;4707comp_remaining -= read_buf_avail;4708}4709}4710}4711else4712{4713tinfl_decompressor inflator;4714tinfl_init(&inflator);47154716if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE)))4717{4718mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);4719status = TINFL_STATUS_FAILED;4720}4721else4722{4723do4724{4725mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));4726size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));4727if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))4728{4729read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);4730if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)4731{4732mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);4733status = TINFL_STATUS_FAILED;4734break;4735}4736cur_file_ofs += read_buf_avail;4737comp_remaining -= read_buf_avail;4738read_buf_ofs = 0;4739}47404741in_buf_size = (size_t)read_buf_avail;4742status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);4743read_buf_avail -= in_buf_size;4744read_buf_ofs += in_buf_size;47454746if (out_buf_size)4747{4748if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size)4749{4750mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED);4751status = TINFL_STATUS_FAILED;4752break;4753}47544755#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4756file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);4757#endif4758if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size)4759{4760mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED);4761status = TINFL_STATUS_FAILED;4762break;4763}4764}4765} while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT));4766}4767}47684769if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))4770{4771/* Make sure the entire file was decompressed, and check its CRC. */4772if (out_buf_ofs != file_stat.m_uncomp_size)4773{4774mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE);4775status = TINFL_STATUS_FAILED;4776}4777#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4778else if (file_crc32 != file_stat.m_crc32)4779{4780mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED);4781status = TINFL_STATUS_FAILED;4782}4783#endif4784}47854786if (!pZip->m_pState->m_pMem)4787pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);47884789if (pWrite_buf)4790pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);47914792return status == TINFL_STATUS_DONE;4793}47944795mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)4796{4797mz_uint32 file_index;4798if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))4799return MZ_FALSE;48004801return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags);4802}48034804mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags)4805{4806mz_zip_reader_extract_iter_state *pState;4807mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];4808mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;48094810/* Argument sanity check */4811if ((!pZip) || (!pZip->m_pState))4812return NULL;48134814/* Allocate an iterator status structure */4815pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state));4816if (!pState)4817{4818mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);4819return NULL;4820}48214822/* Fetch file details */4823if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat))4824{4825pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4826return NULL;4827}48284829/* Encryption and patch files are not supported. */4830if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG))4831{4832mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);4833pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4834return NULL;4835}48364837/* This function only supports decompressing stored and deflate. */4838if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED))4839{4840mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);4841pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4842return NULL;4843}48444845/* Init state - save args */4846pState->pZip = pZip;4847pState->flags = flags;48484849/* Init state - reset variables to defaults */4850pState->status = TINFL_STATUS_DONE;4851#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4852pState->file_crc32 = MZ_CRC32_INIT;4853#endif4854pState->read_buf_ofs = 0;4855pState->out_buf_ofs = 0;4856pState->pRead_buf = NULL;4857pState->pWrite_buf = NULL;4858pState->out_blk_remain = 0;48594860/* Read and parse the local directory entry. */4861pState->cur_file_ofs = pState->file_stat.m_local_header_ofs;4862if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)4863{4864mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);4865pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4866return NULL;4867}48684869if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)4870{4871mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);4872pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4873return NULL;4874}48754876pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);4877if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size)4878{4879mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);4880pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4881return NULL;4882}48834884/* Decompress the file either directly from memory or from a file input buffer. */4885if (pZip->m_pState->m_pMem)4886{4887pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs;4888pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size;4889pState->comp_remaining = pState->file_stat.m_comp_size;4890}4891else4892{4893if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)))4894{4895/* Decompression required, therefore intermediate read buffer required */4896pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);4897if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size)))4898{4899mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);4900pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4901return NULL;4902}4903}4904else4905{4906/* Decompression not required - we will be reading directly into user buffer, no temp buf required */4907pState->read_buf_size = 0;4908}4909pState->read_buf_avail = 0;4910pState->comp_remaining = pState->file_stat.m_comp_size;4911}49124913if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)))4914{4915/* Decompression required, init decompressor */4916tinfl_init( &pState->inflator );49174918/* Allocate write buffer */4919if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE)))4920{4921mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);4922if (pState->pRead_buf)4923pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf);4924pZip->m_pFree(pZip->m_pAlloc_opaque, pState);4925return NULL;4926}4927}49284929return pState;4930}49314932mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags)4933{4934mz_uint32 file_index;49354936/* Locate file index by name */4937if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))4938return NULL;49394940/* Construct iterator */4941return mz_zip_reader_extract_iter_new(pZip, file_index, flags);4942}49434944size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size)4945{4946size_t copied_to_caller = 0;49474948/* Argument sanity check */4949if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf))4950return 0;49514952if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))4953{4954/* The file is stored or the caller has requested the compressed data, calc amount to return. */4955copied_to_caller = (size_t)MZ_MIN( buf_size, pState->comp_remaining );49564957/* Zip is in memory....or requires reading from a file? */4958if (pState->pZip->m_pState->m_pMem)4959{4960/* Copy data to caller's buffer */4961memcpy( pvBuf, pState->pRead_buf, copied_to_caller );4962pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller;4963}4964else4965{4966/* Read directly into caller's buffer */4967if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller)4968{4969/* Failed to read all that was asked for, flag failure and alert user */4970mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED);4971pState->status = TINFL_STATUS_FAILED;4972copied_to_caller = 0;4973}4974}49754976#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS4977/* Compute CRC if not returning compressed data only */4978if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))4979pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller);4980#endif49814982/* Advance offsets, dec counters */4983pState->cur_file_ofs += copied_to_caller;4984pState->out_buf_ofs += copied_to_caller;4985pState->comp_remaining -= copied_to_caller;4986}4987else4988{4989do4990{4991/* Calc ptr to write buffer - given current output pos and block size */4992mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));49934994/* Calc max output size - given current output pos and block size */4995size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));49964997if (!pState->out_blk_remain)4998{4999/* Read more data from file if none available (and reading from file) */5000if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem))5001{5002/* Calc read size */5003pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining);5004if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail)5005{5006mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED);5007pState->status = TINFL_STATUS_FAILED;5008break;5009}50105011/* Advance offsets, dec counters */5012pState->cur_file_ofs += pState->read_buf_avail;5013pState->comp_remaining -= pState->read_buf_avail;5014pState->read_buf_ofs = 0;5015}50165017/* Perform decompression */5018in_buf_size = (size_t)pState->read_buf_avail;5019pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);5020pState->read_buf_avail -= in_buf_size;5021pState->read_buf_ofs += in_buf_size;50225023/* Update current output block size remaining */5024pState->out_blk_remain = out_buf_size;5025}50265027if (pState->out_blk_remain)5028{5029/* Calc amount to return. */5030size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain );50315032/* Copy data to caller's buffer */5033memcpy( (uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy );50345035#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS5036/* Perform CRC */5037pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy);5038#endif50395040/* Decrement data consumed from block */5041pState->out_blk_remain -= to_copy;50425043/* Inc output offset, while performing sanity check */5044if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size)5045{5046mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED);5047pState->status = TINFL_STATUS_FAILED;5048break;5049}50505051/* Increment counter of data copied to caller */5052copied_to_caller += to_copy;5053}5054} while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) );5055}50565057/* Return how many bytes were copied into user buffer */5058return copied_to_caller;5059}50605061mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState)5062{5063int status;50645065/* Argument sanity check */5066if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState))5067return MZ_FALSE;50685069/* Was decompression completed and requested? */5070if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))5071{5072/* Make sure the entire file was decompressed, and check its CRC. */5073if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size)5074{5075mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE);5076pState->status = TINFL_STATUS_FAILED;5077}5078#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS5079else if (pState->file_crc32 != pState->file_stat.m_crc32)5080{5081mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED);5082pState->status = TINFL_STATUS_FAILED;5083}5084#endif5085}50865087/* Free buffers */5088if (!pState->pZip->m_pState->m_pMem)5089pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf);5090if (pState->pWrite_buf)5091pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf);50925093/* Save status */5094status = pState->status;50955096/* Free context */5097pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState);50985099return status == TINFL_STATUS_DONE;5100}51015102#ifndef MINIZ_NO_STDIO5103static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n)5104{5105(void)ofs;51065107return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);5108}51095110mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags)5111{5112mz_bool status;5113mz_zip_archive_file_stat file_stat;5114MZ_FILE *pFile;51155116if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))5117return MZ_FALSE;51185119if ((file_stat.m_is_directory) || (!file_stat.m_is_supported))5120return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);51215122pFile = MZ_FOPEN(pDst_filename, "wb");5123if (!pFile)5124return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);51255126status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags);51275128if (MZ_FCLOSE(pFile) == EOF)5129{5130if (status)5131mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED);51325133status = MZ_FALSE;5134}51355136#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO)5137if (status)5138mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);5139#endif51405141return status;5142}51435144mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags)5145{5146mz_uint32 file_index;5147if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index))5148return MZ_FALSE;51495150return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);5151}51525153mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags)5154{5155mz_zip_archive_file_stat file_stat;51565157if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))5158return MZ_FALSE;51595160if ((file_stat.m_is_directory) || (!file_stat.m_is_supported))5161return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);51625163return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags);5164}51655166mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags)5167{5168mz_uint32 file_index;5169if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index))5170return MZ_FALSE;51715172return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags);5173}5174#endif /* #ifndef MINIZ_NO_STDIO */51755176static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)5177{5178mz_uint32 *p = (mz_uint32 *)pOpaque;5179(void)file_ofs;5180*p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n);5181return n;5182}51835184mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags)5185{5186mz_zip_archive_file_stat file_stat;5187mz_zip_internal_state *pState;5188const mz_uint8 *pCentral_dir_header;5189mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE;5190mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE;5191mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];5192mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;5193mz_uint64 local_header_ofs = 0;5194mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32;5195mz_uint64 local_header_comp_size, local_header_uncomp_size;5196mz_uint32 uncomp_crc32 = MZ_CRC32_INIT;5197mz_bool has_data_descriptor;5198mz_uint32 local_header_bit_flags;51995200mz_zip_array file_data_array;5201mz_zip_array_init(&file_data_array, 1);52025203if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead))5204return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);52055206if (file_index > pZip->m_total_files)5207return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);52085209pState = pZip->m_pState;52105211pCentral_dir_header = mz_zip_get_cdh(pZip, file_index);52125213if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir))5214return MZ_FALSE;52155216/* A directory or zero length file */5217if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size))5218return MZ_TRUE;52195220/* Encryption and patch files are not supported. */5221if (file_stat.m_is_encrypted)5222return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);52235224/* This function only supports stored and deflate. */5225if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))5226return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);52275228if (!file_stat.m_is_supported)5229return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);52305231/* Read and parse the local directory entry. */5232local_header_ofs = file_stat.m_local_header_ofs;5233if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)5234return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);52355236if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)5237return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);52385239local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS);5240local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);5241local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS);5242local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS);5243local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS);5244local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);5245has_data_descriptor = (local_header_bit_flags & 8) != 0;52465247if (local_header_filename_len != strlen(file_stat.m_filename))5248return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);52495250if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size)5251return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);52525253if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE))5254return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);52555256if (local_header_filename_len)5257{5258if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len)5259{5260mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);5261goto handle_failure;5262}52635264/* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */5265if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0)5266{5267mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);5268goto handle_failure;5269}5270}52715272if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX)))5273{5274mz_uint32 extra_size_remaining = local_header_extra_len;5275const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p;52765277if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len)5278{5279mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);5280goto handle_failure;5281}52825283do5284{5285mz_uint32 field_id, field_data_size, field_total_size;52865287if (extra_size_remaining < (sizeof(mz_uint16) * 2))5288return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);52895290field_id = MZ_READ_LE16(pExtra_data);5291field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));5292field_total_size = field_data_size + sizeof(mz_uint16) * 2;52935294if (field_total_size > extra_size_remaining)5295return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);52965297if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID)5298{5299const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32);53005301if (field_data_size < sizeof(mz_uint64) * 2)5302{5303mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);5304goto handle_failure;5305}53065307local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data);5308local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64));53095310found_zip64_ext_data_in_ldir = MZ_TRUE;5311break;5312}53135314pExtra_data += field_total_size;5315extra_size_remaining -= field_total_size;5316} while (extra_size_remaining);5317}53185319/* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */5320/* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */5321if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32))5322{5323mz_uint8 descriptor_buf[32];5324mz_bool has_id;5325const mz_uint8 *pSrc;5326mz_uint32 file_crc32;5327mz_uint64 comp_size = 0, uncomp_size = 0;53285329mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4;53305331if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s))5332{5333mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);5334goto handle_failure;5335}53365337has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID);5338pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf;53395340file_crc32 = MZ_READ_LE32(pSrc);53415342if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir))5343{5344comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32));5345uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64));5346}5347else5348{5349comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32));5350uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32));5351}53525353if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size))5354{5355mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);5356goto handle_failure;5357}5358}5359else5360{5361if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size))5362{5363mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);5364goto handle_failure;5365}5366}53675368mz_zip_array_clear(pZip, &file_data_array);53695370if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0)5371{5372if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0))5373return MZ_FALSE;53745375/* 1 more check to be sure, although the extract checks too. */5376if (uncomp_crc32 != file_stat.m_crc32)5377{5378mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);5379return MZ_FALSE;5380}5381}53825383return MZ_TRUE;53845385handle_failure:5386mz_zip_array_clear(pZip, &file_data_array);5387return MZ_FALSE;5388}53895390mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags)5391{5392mz_zip_internal_state *pState;5393uint32_t i;53945395if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead))5396return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);53975398pState = pZip->m_pState;53995400/* Basic sanity checks */5401if (!pState->m_zip64)5402{5403if (pZip->m_total_files > MZ_UINT16_MAX)5404return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);54055406if (pZip->m_archive_size > MZ_UINT32_MAX)5407return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);5408}5409else5410{5411if (pZip->m_total_files >= MZ_UINT32_MAX)5412return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);54135414if (pState->m_central_dir.m_size >= MZ_UINT32_MAX)5415return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);5416}54175418for (i = 0; i < pZip->m_total_files; i++)5419{5420if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags)5421{5422mz_uint32 found_index;5423mz_zip_archive_file_stat stat;54245425if (!mz_zip_reader_file_stat(pZip, i, &stat))5426return MZ_FALSE;54275428if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index))5429return MZ_FALSE;54305431/* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */5432if (found_index != i)5433return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);5434}54355436if (!mz_zip_validate_file(pZip, i, flags))5437return MZ_FALSE;5438}54395440return MZ_TRUE;5441}54425443mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr)5444{5445mz_bool success = MZ_TRUE;5446mz_zip_archive zip;5447mz_zip_error actual_err = MZ_ZIP_NO_ERROR;54485449if ((!pMem) || (!size))5450{5451if (pErr)5452*pErr = MZ_ZIP_INVALID_PARAMETER;5453return MZ_FALSE;5454}54555456mz_zip_zero_struct(&zip);54575458if (!mz_zip_reader_init_mem(&zip, pMem, size, flags))5459{5460if (pErr)5461*pErr = zip.m_last_error;5462return MZ_FALSE;5463}54645465if (!mz_zip_validate_archive(&zip, flags))5466{5467actual_err = zip.m_last_error;5468success = MZ_FALSE;5469}54705471if (!mz_zip_reader_end_internal(&zip, success))5472{5473if (!actual_err)5474actual_err = zip.m_last_error;5475success = MZ_FALSE;5476}54775478if (pErr)5479*pErr = actual_err;54805481return success;5482}54835484#ifndef MINIZ_NO_STDIO5485mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr)5486{5487mz_bool success = MZ_TRUE;5488mz_zip_archive zip;5489mz_zip_error actual_err = MZ_ZIP_NO_ERROR;54905491if (!pFilename)5492{5493if (pErr)5494*pErr = MZ_ZIP_INVALID_PARAMETER;5495return MZ_FALSE;5496}54975498mz_zip_zero_struct(&zip);54995500if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0))5501{5502if (pErr)5503*pErr = zip.m_last_error;5504return MZ_FALSE;5505}55065507if (!mz_zip_validate_archive(&zip, flags))5508{5509actual_err = zip.m_last_error;5510success = MZ_FALSE;5511}55125513if (!mz_zip_reader_end_internal(&zip, success))5514{5515if (!actual_err)5516actual_err = zip.m_last_error;5517success = MZ_FALSE;5518}55195520if (pErr)5521*pErr = actual_err;55225523return success;5524}5525#endif /* #ifndef MINIZ_NO_STDIO */55265527/* ------------------- .ZIP archive writing */55285529#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS55305531static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v)5532{5533p[0] = (mz_uint8)v;5534p[1] = (mz_uint8)(v >> 8);5535}5536static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v)5537{5538p[0] = (mz_uint8)v;5539p[1] = (mz_uint8)(v >> 8);5540p[2] = (mz_uint8)(v >> 16);5541p[3] = (mz_uint8)(v >> 24);5542}5543static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v)5544{5545mz_write_le32(p, (mz_uint32)v);5546mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32));5547}55485549#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))5550#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))5551#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v))55525553static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)5554{5555mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;5556mz_zip_internal_state *pState = pZip->m_pState;5557mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);55585559if (!n)5560return 0;55615562/* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */5563if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))5564{5565mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);5566return 0;5567}55685569if (new_size > pState->m_mem_capacity)5570{5571void *pNew_block;5572size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);55735574while (new_capacity < new_size)5575new_capacity *= 2;55765577if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))5578{5579mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);5580return 0;5581}55825583pState->m_pMem = pNew_block;5584pState->m_mem_capacity = new_capacity;5585}5586memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);5587pState->m_mem_size = (size_t)new_size;5588return n;5589}55905591static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error)5592{5593mz_zip_internal_state *pState;5594mz_bool status = MZ_TRUE;55955596if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))5597{5598if (set_last_error)5599mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);5600return MZ_FALSE;5601}56025603pState = pZip->m_pState;5604pZip->m_pState = NULL;5605mz_zip_array_clear(pZip, &pState->m_central_dir);5606mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);5607mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);56085609#ifndef MINIZ_NO_STDIO5610if (pState->m_pFile)5611{5612if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE)5613{5614if (MZ_FCLOSE(pState->m_pFile) == EOF)5615{5616if (set_last_error)5617mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED);5618status = MZ_FALSE;5619}5620}56215622pState->m_pFile = NULL;5623}5624#endif /* #ifndef MINIZ_NO_STDIO */56255626if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem))5627{5628pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);5629pState->m_pMem = NULL;5630}56315632pZip->m_pFree(pZip->m_pAlloc_opaque, pState);5633pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;5634return status;5635}56365637mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags)5638{5639mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0;56405641if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))5642return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);56435644if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)5645{5646if (!pZip->m_pRead)5647return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);5648}56495650if (pZip->m_file_offset_alignment)5651{5652/* Ensure user specified file offset alignment is a power of 2. */5653if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))5654return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);5655}56565657if (!pZip->m_pAlloc)5658pZip->m_pAlloc = miniz_def_alloc_func;5659if (!pZip->m_pFree)5660pZip->m_pFree = miniz_def_free_func;5661if (!pZip->m_pRealloc)5662pZip->m_pRealloc = miniz_def_realloc_func;56635664pZip->m_archive_size = existing_size;5665pZip->m_central_directory_file_ofs = 0;5666pZip->m_total_files = 0;56675668if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))5669return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);56705671memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));56725673MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));5674MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));5675MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));56765677pZip->m_pState->m_zip64 = zip64;5678pZip->m_pState->m_zip64_has_extended_info_fields = zip64;56795680pZip->m_zip_type = MZ_ZIP_TYPE_USER;5681pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;56825683return MZ_TRUE;5684}56855686mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size)5687{5688return mz_zip_writer_init_v2(pZip, existing_size, 0);5689}56905691mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags)5692{5693pZip->m_pWrite = mz_zip_heap_write_func;5694pZip->m_pNeeds_keepalive = NULL;56955696if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)5697pZip->m_pRead = mz_zip_mem_read_func;56985699pZip->m_pIO_opaque = pZip;57005701if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags))5702return MZ_FALSE;57035704pZip->m_zip_type = MZ_ZIP_TYPE_HEAP;57055706if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning)))5707{5708if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size)))5709{5710mz_zip_writer_end_internal(pZip, MZ_FALSE);5711return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);5712}5713pZip->m_pState->m_mem_capacity = initial_allocation_size;5714}57155716return MZ_TRUE;5717}57185719mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size)5720{5721return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0);5722}57235724#ifndef MINIZ_NO_STDIO5725static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)5726{5727mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;5728mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);57295730file_ofs += pZip->m_pState->m_file_archive_start_ofs;57315732if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))5733{5734mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);5735return 0;5736}57375738return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);5739}57405741mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning)5742{5743return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0);5744}57455746mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags)5747{5748MZ_FILE *pFile;57495750pZip->m_pWrite = mz_zip_file_write_func;5751pZip->m_pNeeds_keepalive = NULL;57525753if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)5754pZip->m_pRead = mz_zip_file_read_func;57555756pZip->m_pIO_opaque = pZip;57575758if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags))5759return MZ_FALSE;57605761if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb")))5762{5763mz_zip_writer_end(pZip);5764return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);5765}57665767pZip->m_pState->m_pFile = pFile;5768pZip->m_zip_type = MZ_ZIP_TYPE_FILE;57695770if (size_to_reserve_at_beginning)5771{5772mz_uint64 cur_ofs = 0;5773char buf[4096];57745775MZ_CLEAR_OBJ(buf);57765777do5778{5779size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);5780if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n)5781{5782mz_zip_writer_end(pZip);5783return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);5784}5785cur_ofs += n;5786size_to_reserve_at_beginning -= n;5787} while (size_to_reserve_at_beginning);5788}57895790return MZ_TRUE;5791}57925793mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags)5794{5795pZip->m_pWrite = mz_zip_file_write_func;5796pZip->m_pNeeds_keepalive = NULL;57975798if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)5799pZip->m_pRead = mz_zip_file_read_func;58005801pZip->m_pIO_opaque = pZip;58025803if (!mz_zip_writer_init_v2(pZip, 0, flags))5804return MZ_FALSE;58055806pZip->m_pState->m_pFile = pFile;5807pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);5808pZip->m_zip_type = MZ_ZIP_TYPE_CFILE;58095810return MZ_TRUE;5811}5812#endif /* #ifndef MINIZ_NO_STDIO */58135814mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags)5815{5816mz_zip_internal_state *pState;58175818if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))5819return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);58205821if (flags & MZ_ZIP_FLAG_WRITE_ZIP64)5822{5823/* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */5824if (!pZip->m_pState->m_zip64)5825return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);5826}58275828/* No sense in trying to write to an archive that's already at the support max size */5829if (pZip->m_pState->m_zip64)5830{5831if (pZip->m_total_files == MZ_UINT32_MAX)5832return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);5833}5834else5835{5836if (pZip->m_total_files == MZ_UINT16_MAX)5837return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);58385839if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)5840return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);5841}58425843pState = pZip->m_pState;58445845if (pState->m_pFile)5846{5847#ifdef MINIZ_NO_STDIO5848(void)pFilename;5849return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);5850#else5851if (pZip->m_pIO_opaque != pZip)5852return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);58535854if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE)5855{5856if (!pFilename)5857return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);58585859/* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */5860if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile)))5861{5862/* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */5863mz_zip_reader_end_internal(pZip, MZ_FALSE);5864return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);5865}5866}58675868pZip->m_pWrite = mz_zip_file_write_func;5869pZip->m_pNeeds_keepalive = NULL;5870#endif /* #ifdef MINIZ_NO_STDIO */5871}5872else if (pState->m_pMem)5873{5874/* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */5875if (pZip->m_pIO_opaque != pZip)5876return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);58775878pState->m_mem_capacity = pState->m_mem_size;5879pZip->m_pWrite = mz_zip_heap_write_func;5880pZip->m_pNeeds_keepalive = NULL;5881}5882/* Archive is being read via a user provided read function - make sure the user has specified a write function too. */5883else if (!pZip->m_pWrite)5884return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);58855886/* Start writing new files at the archive's current central directory location. */5887/* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */5888pZip->m_archive_size = pZip->m_central_directory_file_ofs;5889pZip->m_central_directory_file_ofs = 0;58905891/* Clear the sorted central dir offsets, they aren't useful or maintained now. */5892/* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */5893/* TODO: We could easily maintain the sorted central directory offsets. */5894mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets);58955896pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;58975898return MZ_TRUE;5899}59005901mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename)5902{5903return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0);5904}59055906/* TODO: pArchive_name is a terrible name here! */5907mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags)5908{5909return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0);5910}59115912typedef struct5913{5914mz_zip_archive *m_pZip;5915mz_uint64 m_cur_archive_file_ofs;5916mz_uint64 m_comp_size;5917} mz_zip_writer_add_state;59185919static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser)5920{5921mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;5922if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len)5923return MZ_FALSE;59245925pState->m_cur_archive_file_ofs += len;5926pState->m_comp_size += len;5927return MZ_TRUE;5928}59295930#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2)5931#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3)5932static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs)5933{5934mz_uint8 *pDst = pBuf;5935mz_uint32 field_size = 0;59365937MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID);5938MZ_WRITE_LE16(pDst + 2, 0);5939pDst += sizeof(mz_uint16) * 2;59405941if (pUncomp_size)5942{5943MZ_WRITE_LE64(pDst, *pUncomp_size);5944pDst += sizeof(mz_uint64);5945field_size += sizeof(mz_uint64);5946}59475948if (pComp_size)5949{5950MZ_WRITE_LE64(pDst, *pComp_size);5951pDst += sizeof(mz_uint64);5952field_size += sizeof(mz_uint64);5953}59545955if (pLocal_header_ofs)5956{5957MZ_WRITE_LE64(pDst, *pLocal_header_ofs);5958pDst += sizeof(mz_uint64);5959field_size += sizeof(mz_uint64);5960}59615962MZ_WRITE_LE16(pBuf + 2, field_size);59635964return (mz_uint32)(pDst - pBuf);5965}59665967static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date)5968{5969(void)pZip;5970memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);5971MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);5972MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);5973MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);5974MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);5975MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);5976MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);5977MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);5978MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX));5979MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX));5980MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);5981MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);5982return MZ_TRUE;5983}59845985static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst,5986mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size,5987mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32,5988mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,5989mz_uint64 local_header_ofs, mz_uint32 ext_attributes)5990{5991(void)pZip;5992memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);5993MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);5994MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);5995MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);5996MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);5997MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);5998MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);5999MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);6000MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX));6001MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX));6002MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);6003MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);6004MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);6005MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);6006MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX));6007return MZ_TRUE;6008}60096010static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,6011const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size,6012mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32,6013mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,6014mz_uint64 local_header_ofs, mz_uint32 ext_attributes,6015const char *user_extra_data, mz_uint user_extra_data_len)6016{6017mz_zip_internal_state *pState = pZip->m_pState;6018mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;6019size_t orig_central_dir_size = pState->m_central_dir.m_size;6020mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];60216022if (!pZip->m_pState->m_zip64)6023{6024if (local_header_ofs > 0xFFFFFFFF)6025return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);6026}60276028/* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */6029if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX)6030return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);60316032if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, (mz_uint16)(extra_size + user_extra_data_len), comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes))6033return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);60346035if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||6036(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) ||6037(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) ||6038(!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) ||6039(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) ||6040(!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1)))6041{6042/* Try to resize the central directory array back into its original state. */6043mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);6044return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6045}60466047return MZ_TRUE;6048}60496050static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name)6051{6052/* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */6053if (*pArchive_name == '/')6054return MZ_FALSE;60556056/* Making sure the name does not contain drive letters or DOS style backward slashes is the responsibility of the program using miniz*/60576058return MZ_TRUE;6059}60606061static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip)6062{6063mz_uint32 n;6064if (!pZip->m_file_offset_alignment)6065return 0;6066n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));6067return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1));6068}60696070static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n)6071{6072char buf[4096];6073memset(buf, 0, MZ_MIN(sizeof(buf), n));6074while (n)6075{6076mz_uint32 s = MZ_MIN(sizeof(buf), n);6077if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)6078return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);60796080cur_file_ofs += s;6081n -= s;6082}6083return MZ_TRUE;6084}60856086mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags,6087mz_uint64 uncomp_size, mz_uint32 uncomp_crc32)6088{6089return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0);6090}60916092mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size,6093mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified,6094const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len)6095{6096mz_uint16 method = 0, dos_time = 0, dos_date = 0;6097mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;6098mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;6099size_t archive_name_size;6100mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];6101tdefl_compressor *pComp = NULL;6102mz_bool store_data_uncompressed;6103mz_zip_internal_state *pState;6104mz_uint8 *pExtra_data = NULL;6105mz_uint32 extra_size = 0;6106mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE];6107mz_uint16 bit_flags = 0;61086109if ((int)level_and_flags < 0)6110level_and_flags = MZ_DEFAULT_LEVEL;61116112if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))6113bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR;61146115if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME))6116bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8;61176118level = level_and_flags & 0xF;6119store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));61206121if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))6122return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);61236124pState = pZip->m_pState;61256126if (pState->m_zip64)6127{6128if (pZip->m_total_files == MZ_UINT32_MAX)6129return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);6130}6131else6132{6133if (pZip->m_total_files == MZ_UINT16_MAX)6134{6135pState->m_zip64 = MZ_TRUE;6136/*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */6137}6138if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))6139{6140pState->m_zip64 = MZ_TRUE;6141/*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */6142}6143}61446145if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))6146return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);61476148if (!mz_zip_writer_validate_archive_name(pArchive_name))6149return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);61506151#ifndef MINIZ_NO_TIME6152if (last_modified != NULL)6153{6154mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date);6155}6156else6157{6158MZ_TIME_T cur_time;6159time(&cur_time);6160mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date);6161}6162#endif /* #ifndef MINIZ_NO_TIME */61636164if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))6165{6166uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);6167uncomp_size = buf_size;6168if (uncomp_size <= 3)6169{6170level = 0;6171store_data_uncompressed = MZ_TRUE;6172}6173}61746175archive_name_size = strlen(pArchive_name);6176if (archive_name_size > MZ_UINT16_MAX)6177return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);61786179num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);61806181/* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */6182if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX)6183return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);61846185if (!pState->m_zip64)6186{6187/* Bail early if the archive would obviously become too large */6188if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size6189+ MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len +6190pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len6191+ MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF)6192{6193pState->m_zip64 = MZ_TRUE;6194/*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */6195}6196}61976198if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/'))6199{6200/* Set DOS Subdirectory attribute bit. */6201ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG;62026203/* Subdirectories cannot contain data. */6204if ((buf_size) || (uncomp_size))6205return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);6206}62076208/* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */6209if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))6210return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);62116212if ((!store_data_uncompressed) && (buf_size))6213{6214if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))6215return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6216}62176218if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes))6219{6220pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6221return MZ_FALSE;6222}62236224local_dir_header_ofs += num_alignment_padding_bytes;6225if (pZip->m_file_offset_alignment)6226{6227MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0);6228}6229cur_archive_file_ofs += num_alignment_padding_bytes;62306231MZ_CLEAR_OBJ(local_dir_header);62326233if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))6234{6235method = MZ_DEFLATED;6236}62376238if (pState->m_zip64)6239{6240if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX)6241{6242pExtra_data = extra_data;6243extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,6244(uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL);6245}62466247if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, bit_flags, dos_time, dos_date))6248return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);62496250if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))6251return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);62526253cur_archive_file_ofs += sizeof(local_dir_header);62546255if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)6256{6257pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6258return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);6259}6260cur_archive_file_ofs += archive_name_size;62616262if (pExtra_data != NULL)6263{6264if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size)6265return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);62666267cur_archive_file_ofs += extra_size;6268}6269}6270else6271{6272if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX))6273return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);6274if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date))6275return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);62766277if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))6278return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);62796280cur_archive_file_ofs += sizeof(local_dir_header);62816282if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)6283{6284pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6285return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);6286}6287cur_archive_file_ofs += archive_name_size;6288}62896290if (user_extra_data_len > 0)6291{6292if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len)6293return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);62946295cur_archive_file_ofs += user_extra_data_len;6296}62976298if (store_data_uncompressed)6299{6300if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size)6301{6302pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6303return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);6304}63056306cur_archive_file_ofs += buf_size;6307comp_size = buf_size;6308}6309else if (buf_size)6310{6311mz_zip_writer_add_state state;63126313state.m_pZip = pZip;6314state.m_cur_archive_file_ofs = cur_archive_file_ofs;6315state.m_comp_size = 0;63166317if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) ||6318(tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE))6319{6320pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6321return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED);6322}63236324comp_size = state.m_comp_size;6325cur_archive_file_ofs = state.m_cur_archive_file_ofs;6326}63276328pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6329pComp = NULL;63306331if (uncomp_size)6332{6333mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64];6334mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32;63356336MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR);63376338MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID);6339MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32);6340if (pExtra_data == NULL)6341{6342if (comp_size > MZ_UINT32_MAX)6343return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);63446345MZ_WRITE_LE32(local_dir_footer + 8, comp_size);6346MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size);6347}6348else6349{6350MZ_WRITE_LE64(local_dir_footer + 8, comp_size);6351MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size);6352local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64;6353}63546355if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size)6356return MZ_FALSE;63576358cur_archive_file_ofs += local_dir_footer_size;6359}63606361if (pExtra_data != NULL)6362{6363extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,6364(uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL);6365}63666367if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment,6368comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes,6369user_extra_data_central, user_extra_data_central_len))6370return MZ_FALSE;63716372pZip->m_total_files++;6373pZip->m_archive_size = cur_archive_file_ofs;63746375return MZ_TRUE;6376}63776378mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags,6379const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len)6380{6381mz_uint16 gen_flags = MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR;6382mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;6383mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;6384mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = size_to_add, comp_size = 0;6385size_t archive_name_size;6386mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];6387mz_uint8 *pExtra_data = NULL;6388mz_uint32 extra_size = 0;6389mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE];6390mz_zip_internal_state *pState;6391mz_uint64 file_ofs = 0;63926393if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME))6394gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8;63956396if ((int)level_and_flags < 0)6397level_and_flags = MZ_DEFAULT_LEVEL;6398level = level_and_flags & 0xF;63996400/* Sanity checks */6401if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))6402return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);64036404pState = pZip->m_pState;64056406if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX))6407{6408/* Source file is too large for non-zip64 */6409/*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */6410pState->m_zip64 = MZ_TRUE;6411}64126413/* We could support this, but why? */6414if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)6415return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);64166417if (!mz_zip_writer_validate_archive_name(pArchive_name))6418return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);64196420if (pState->m_zip64)6421{6422if (pZip->m_total_files == MZ_UINT32_MAX)6423return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);6424}6425else6426{6427if (pZip->m_total_files == MZ_UINT16_MAX)6428{6429pState->m_zip64 = MZ_TRUE;6430/*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */6431}6432}64336434archive_name_size = strlen(pArchive_name);6435if (archive_name_size > MZ_UINT16_MAX)6436return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);64376438num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);64396440/* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */6441if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX)6442return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);64436444if (!pState->m_zip64)6445{6446/* Bail early if the archive would obviously become too large */6447if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE6448+ archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 10246449+ MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF)6450{6451pState->m_zip64 = MZ_TRUE;6452/*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */6453}6454}64556456#ifndef MINIZ_NO_TIME6457if (pFile_time)6458{6459mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date);6460}6461#endif64626463if (uncomp_size <= 3)6464level = 0;64656466if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes))6467{6468return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);6469}64706471cur_archive_file_ofs += num_alignment_padding_bytes;6472local_dir_header_ofs = cur_archive_file_ofs;64736474if (pZip->m_file_offset_alignment)6475{6476MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0);6477}64786479if (uncomp_size && level)6480{6481method = MZ_DEFLATED;6482}64836484MZ_CLEAR_OBJ(local_dir_header);6485if (pState->m_zip64)6486{6487if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX)6488{6489pExtra_data = extra_data;6490extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,6491(uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL);6492}64936494if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, gen_flags, dos_time, dos_date))6495return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);64966497if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))6498return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);64996500cur_archive_file_ofs += sizeof(local_dir_header);65016502if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)6503{6504return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);6505}65066507cur_archive_file_ofs += archive_name_size;65086509if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size)6510return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);65116512cur_archive_file_ofs += extra_size;6513}6514else6515{6516if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX))6517return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);6518if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date))6519return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);65206521if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))6522return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);65236524cur_archive_file_ofs += sizeof(local_dir_header);65256526if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)6527{6528return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);6529}65306531cur_archive_file_ofs += archive_name_size;6532}65336534if (user_extra_data_len > 0)6535{6536if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len)6537return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);65386539cur_archive_file_ofs += user_extra_data_len;6540}65416542if (uncomp_size)6543{6544mz_uint64 uncomp_remaining = uncomp_size;6545void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);6546if (!pRead_buf)6547{6548return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6549}65506551if (!level)6552{6553while (uncomp_remaining)6554{6555mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);6556if ((read_callback(callback_opaque, file_ofs, pRead_buf, n) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n))6557{6558pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);6559return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);6560}6561file_ofs += n;6562uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);6563uncomp_remaining -= n;6564cur_archive_file_ofs += n;6565}6566comp_size = uncomp_size;6567}6568else6569{6570mz_bool result = MZ_FALSE;6571mz_zip_writer_add_state state;6572tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));6573if (!pComp)6574{6575pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);6576return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6577}65786579state.m_pZip = pZip;6580state.m_cur_archive_file_ofs = cur_archive_file_ofs;6581state.m_comp_size = 0;65826583if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY)6584{6585pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);6586pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);6587return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);6588}65896590for (;;)6591{6592size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);6593tdefl_status status;6594tdefl_flush flush = TDEFL_NO_FLUSH;65956596if (read_callback(callback_opaque, file_ofs, pRead_buf, in_buf_size)!= in_buf_size)6597{6598mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);6599break;6600}66016602file_ofs += in_buf_size;6603uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);6604uncomp_remaining -= in_buf_size;66056606if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque))6607flush = TDEFL_FULL_FLUSH;66086609status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? flush : TDEFL_FINISH);6610if (status == TDEFL_STATUS_DONE)6611{6612result = MZ_TRUE;6613break;6614}6615else if (status != TDEFL_STATUS_OKAY)6616{6617mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED);6618break;6619}6620}66216622pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);66236624if (!result)6625{6626pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);6627return MZ_FALSE;6628}66296630comp_size = state.m_comp_size;6631cur_archive_file_ofs = state.m_cur_archive_file_ofs;6632}66336634pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);6635}66366637{6638mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64];6639mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32;66406641MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID);6642MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32);6643if (pExtra_data == NULL)6644{6645if (comp_size > MZ_UINT32_MAX)6646return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);66476648MZ_WRITE_LE32(local_dir_footer + 8, comp_size);6649MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size);6650}6651else6652{6653MZ_WRITE_LE64(local_dir_footer + 8, comp_size);6654MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size);6655local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64;6656}66576658if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size)6659return MZ_FALSE;66606661cur_archive_file_ofs += local_dir_footer_size;6662}66636664if (pExtra_data != NULL)6665{6666extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,6667(uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL);6668}66696670if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size,6671uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes,6672user_extra_data_central, user_extra_data_central_len))6673return MZ_FALSE;66746675pZip->m_total_files++;6676pZip->m_archive_size = cur_archive_file_ofs;66776678return MZ_TRUE;6679}66806681#ifndef MINIZ_NO_STDIO66826683static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)6684{6685MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque;6686mz_int64 cur_ofs = MZ_FTELL64(pSrc_file);66876688if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET))))6689return 0;66906691return MZ_FREAD(pBuf, 1, n, pSrc_file);6692}66936694mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags,6695const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len)6696{6697return mz_zip_writer_add_read_buf_callback(pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, size_to_add, pFile_time, pComment, comment_size, level_and_flags,6698user_extra_data, user_extra_data_len, user_extra_data_central, user_extra_data_central_len);6699}67006701mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)6702{6703MZ_FILE *pSrc_file = NULL;6704mz_uint64 uncomp_size = 0;6705MZ_TIME_T file_modified_time;6706MZ_TIME_T *pFile_time = NULL;6707mz_bool status;67086709memset(&file_modified_time, 0, sizeof(file_modified_time));67106711#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO)6712pFile_time = &file_modified_time;6713if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time))6714return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED);6715#endif67166717pSrc_file = MZ_FOPEN(pSrc_filename, "rb");6718if (!pSrc_file)6719return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);67206721MZ_FSEEK64(pSrc_file, 0, SEEK_END);6722uncomp_size = MZ_FTELL64(pSrc_file);6723MZ_FSEEK64(pSrc_file, 0, SEEK_SET);67246725status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0);67266727MZ_FCLOSE(pSrc_file);67286729return status;6730}6731#endif /* #ifndef MINIZ_NO_STDIO */67326733static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start)6734{6735/* + 64 should be enough for any new zip64 data */6736if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE))6737return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);67386739mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE);67406741if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start))6742{6743mz_uint8 new_ext_block[64];6744mz_uint8 *pDst = new_ext_block;6745mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID);6746mz_write_le16(pDst + sizeof(mz_uint16), 0);6747pDst += sizeof(mz_uint16) * 2;67486749if (pUncomp_size)6750{6751mz_write_le64(pDst, *pUncomp_size);6752pDst += sizeof(mz_uint64);6753}67546755if (pComp_size)6756{6757mz_write_le64(pDst, *pComp_size);6758pDst += sizeof(mz_uint64);6759}67606761if (pLocal_header_ofs)6762{6763mz_write_le64(pDst, *pLocal_header_ofs);6764pDst += sizeof(mz_uint64);6765}67666767if (pDisk_start)6768{6769mz_write_le32(pDst, *pDisk_start);6770pDst += sizeof(mz_uint32);6771}67726773mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2));67746775if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block))6776return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6777}67786779if ((pExt) && (ext_len))6780{6781mz_uint32 extra_size_remaining = ext_len;6782const mz_uint8 *pExtra_data = pExt;67836784do6785{6786mz_uint32 field_id, field_data_size, field_total_size;67876788if (extra_size_remaining < (sizeof(mz_uint16) * 2))6789return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);67906791field_id = MZ_READ_LE16(pExtra_data);6792field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));6793field_total_size = field_data_size + sizeof(mz_uint16) * 2;67946795if (field_total_size > extra_size_remaining)6796return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);67976798if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID)6799{6800if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size))6801return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6802}68036804pExtra_data += field_total_size;6805extra_size_remaining -= field_total_size;6806} while (extra_size_remaining);6807}68086809return MZ_TRUE;6810}68116812/* TODO: This func is now pretty freakin complex due to zip64, split it up? */6813mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index)6814{6815mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size;6816mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs;6817mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;6818mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)];6819mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;6820mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];6821size_t orig_central_dir_size;6822mz_zip_internal_state *pState;6823void *pBuf;6824const mz_uint8 *pSrc_central_header;6825mz_zip_archive_file_stat src_file_stat;6826mz_uint32 src_filename_len, src_comment_len, src_ext_len;6827mz_uint32 local_header_filename_size, local_header_extra_len;6828mz_uint64 local_header_comp_size, local_header_uncomp_size;6829mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE;68306831/* Sanity checks */6832if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead))6833return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);68346835pState = pZip->m_pState;68366837/* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */6838if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64))6839return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);68406841/* Get pointer to the source central dir header and crack it */6842if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index)))6843return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);68446845if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)6846return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);68476848src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS);6849src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);6850src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS);6851src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len;68526853/* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */6854if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX)6855return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);68566857num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);68586859if (!pState->m_zip64)6860{6861if (pZip->m_total_files == MZ_UINT16_MAX)6862return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);6863}6864else6865{6866/* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */6867if (pZip->m_total_files == MZ_UINT32_MAX)6868return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);6869}68706871if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL))6872return MZ_FALSE;68736874cur_src_file_ofs = src_file_stat.m_local_header_ofs;6875cur_dst_file_ofs = pZip->m_archive_size;68766877/* Read the source archive's local dir header */6878if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)6879return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);68806881if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)6882return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);68836884cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;68856886/* Compute the total size we need to copy (filename+extra data+compressed data) */6887local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS);6888local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);6889local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS);6890local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS);6891src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size;68926893/* Try to find a zip64 extended information field */6894if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX)))6895{6896mz_zip_array file_data_array;6897const mz_uint8 *pExtra_data;6898mz_uint32 extra_size_remaining = local_header_extra_len;68996900mz_zip_array_init(&file_data_array, 1);6901if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE))6902{6903return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);6904}69056906if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len)6907{6908mz_zip_array_clear(pZip, &file_data_array);6909return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);6910}69116912pExtra_data = (const mz_uint8 *)file_data_array.m_p;69136914do6915{6916mz_uint32 field_id, field_data_size, field_total_size;69176918if (extra_size_remaining < (sizeof(mz_uint16) * 2))6919{6920mz_zip_array_clear(pZip, &file_data_array);6921return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);6922}69236924field_id = MZ_READ_LE16(pExtra_data);6925field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));6926field_total_size = field_data_size + sizeof(mz_uint16) * 2;69276928if (field_total_size > extra_size_remaining)6929{6930mz_zip_array_clear(pZip, &file_data_array);6931return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);6932}69336934if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID)6935{6936const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32);69376938if (field_data_size < sizeof(mz_uint64) * 2)6939{6940mz_zip_array_clear(pZip, &file_data_array);6941return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);6942}69436944local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data);6945local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */69466947found_zip64_ext_data_in_ldir = MZ_TRUE;6948break;6949}69506951pExtra_data += field_total_size;6952extra_size_remaining -= field_total_size;6953} while (extra_size_remaining);69546955mz_zip_array_clear(pZip, &file_data_array);6956}69576958if (!pState->m_zip64)6959{6960/* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */6961/* We also check when the archive is finalized so this doesn't need to be perfect. */6962mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) +6963pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64;69646965if (approx_new_archive_size >= MZ_UINT32_MAX)6966return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);6967}69686969/* Write dest archive padding */6970if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes))6971return MZ_FALSE;69726973cur_dst_file_ofs += num_alignment_padding_bytes;69746975local_dir_header_ofs = cur_dst_file_ofs;6976if (pZip->m_file_offset_alignment)6977{6978MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0);6979}69806981/* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */6982if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)6983return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);69846985cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;69866987/* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */6988if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining)))))6989return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);69906991while (src_archive_bytes_remaining)6992{6993n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining);6994if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n)6995{6996pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);6997return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);6998}6999cur_src_file_ofs += n;70007001if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)7002{7003pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);7004return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);7005}7006cur_dst_file_ofs += n;70077008src_archive_bytes_remaining -= n;7009}70107011/* Now deal with the optional data descriptor */7012bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);7013if (bit_flags & 8)7014{7015/* Copy data descriptor */7016if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir))7017{7018/* src is zip64, dest must be zip64 */70197020/* name uint32_t's */7021/* id 1 (optional in zip64?) */7022/* crc 1 */7023/* comp_size 2 */7024/* uncomp_size 2 */7025if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6))7026{7027pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);7028return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);7029}70307031n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5);7032}7033else7034{7035/* src is NOT zip64 */7036mz_bool has_id;70377038if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4)7039{7040pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);7041return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);7042}70437044has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID);70457046if (pZip->m_pState->m_zip64)7047{7048/* dest is zip64, so upgrade the data descriptor */7049const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0));7050const mz_uint32 src_crc32 = pSrc_descriptor[0];7051const mz_uint64 src_comp_size = pSrc_descriptor[1];7052const mz_uint64 src_uncomp_size = pSrc_descriptor[2];70537054mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID);7055mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32);7056mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size);7057mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size);70587059n = sizeof(mz_uint32) * 6;7060}7061else7062{7063/* dest is NOT zip64, just copy it as-is */7064n = sizeof(mz_uint32) * (has_id ? 4 : 3);7065}7066}70677068if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)7069{7070pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);7071return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);7072}70737074cur_src_file_ofs += n;7075cur_dst_file_ofs += n;7076}7077pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);70787079/* Finally, add the new central dir header */7080orig_central_dir_size = pState->m_central_dir.m_size;70817082memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);70837084if (pState->m_zip64)7085{7086/* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */7087const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len;7088mz_zip_array new_ext_block;70897090mz_zip_array_init(&new_ext_block, sizeof(mz_uint8));70917092MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX);7093MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX);7094MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX);70957096if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL))7097{7098mz_zip_array_clear(pZip, &new_ext_block);7099return MZ_FALSE;7100}71017102MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size);71037104if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))7105{7106mz_zip_array_clear(pZip, &new_ext_block);7107return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);7108}71097110if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len))7111{7112mz_zip_array_clear(pZip, &new_ext_block);7113mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);7114return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);7115}71167117if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size))7118{7119mz_zip_array_clear(pZip, &new_ext_block);7120mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);7121return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);7122}71237124if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len))7125{7126mz_zip_array_clear(pZip, &new_ext_block);7127mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);7128return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);7129}71307131mz_zip_array_clear(pZip, &new_ext_block);7132}7133else7134{7135/* sanity checks */7136if (cur_dst_file_ofs > MZ_UINT32_MAX)7137return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);71387139if (local_dir_header_ofs >= MZ_UINT32_MAX)7140return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);71417142MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs);71437144if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))7145return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);71467147if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size))7148{7149mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);7150return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);7151}7152}71537154/* This shouldn't trigger unless we screwed up during the initial sanity checks */7155if (pState->m_central_dir.m_size >= MZ_UINT32_MAX)7156{7157/* TODO: Support central dirs >= 32-bits in size */7158mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);7159return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);7160}71617162n = (mz_uint32)orig_central_dir_size;7163if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1))7164{7165mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);7166return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);7167}71687169pZip->m_total_files++;7170pZip->m_archive_size = cur_dst_file_ofs;71717172return MZ_TRUE;7173}71747175mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip)7176{7177mz_zip_internal_state *pState;7178mz_uint64 central_dir_ofs, central_dir_size;7179mz_uint8 hdr[256];71807181if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))7182return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);71837184pState = pZip->m_pState;71857186if (pState->m_zip64)7187{7188if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX))7189return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);7190}7191else7192{7193if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX))7194return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);7195}71967197central_dir_ofs = 0;7198central_dir_size = 0;7199if (pZip->m_total_files)7200{7201/* Write central directory */7202central_dir_ofs = pZip->m_archive_size;7203central_dir_size = pState->m_central_dir.m_size;7204pZip->m_central_directory_file_ofs = central_dir_ofs;7205if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size)7206return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);72077208pZip->m_archive_size += central_dir_size;7209}72107211if (pState->m_zip64)7212{7213/* Write zip64 end of central directory header */7214mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size;72157216MZ_CLEAR_OBJ(hdr);7217MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG);7218MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64));7219MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */7220MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D);7221MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files);7222MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);7223MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size);7224MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs);7225if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)7226return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);72277228pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE;72297230/* Write zip64 end of central directory locator */7231MZ_CLEAR_OBJ(hdr);7232MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG);7233MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr);7234MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1);7235if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE)7236return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);72377238pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE;7239}72407241/* Write end of central directory record */7242MZ_CLEAR_OBJ(hdr);7243MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);7244MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files));7245MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files));7246MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size));7247MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs));72487249if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)7250return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);72517252#ifndef MINIZ_NO_STDIO7253if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))7254return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED);7255#endif /* #ifndef MINIZ_NO_STDIO */72567257pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE;72587259pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;7260return MZ_TRUE;7261}72627263mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize)7264{7265if ((!ppBuf) || (!pSize))7266return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);72677268*ppBuf = NULL;7269*pSize = 0;72707271if ((!pZip) || (!pZip->m_pState))7272return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);72737274if (pZip->m_pWrite != mz_zip_heap_write_func)7275return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);72767277if (!mz_zip_writer_finalize_archive(pZip))7278return MZ_FALSE;72797280*ppBuf = pZip->m_pState->m_pMem;7281*pSize = pZip->m_pState->m_mem_size;7282pZip->m_pState->m_pMem = NULL;7283pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;72847285return MZ_TRUE;7286}72877288mz_bool mz_zip_writer_end(mz_zip_archive *pZip)7289{7290return mz_zip_writer_end_internal(pZip, MZ_TRUE);7291}72927293#ifndef MINIZ_NO_STDIO7294mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)7295{7296return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL);7297}72987299mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr)7300{7301mz_bool status, created_new_archive = MZ_FALSE;7302mz_zip_archive zip_archive;7303struct MZ_FILE_STAT_STRUCT file_stat;7304mz_zip_error actual_err = MZ_ZIP_NO_ERROR;73057306mz_zip_zero_struct(&zip_archive);7307if ((int)level_and_flags < 0)7308level_and_flags = MZ_DEFAULT_LEVEL;73097310if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))7311{7312if (pErr)7313*pErr = MZ_ZIP_INVALID_PARAMETER;7314return MZ_FALSE;7315}73167317if (!mz_zip_writer_validate_archive_name(pArchive_name))7318{7319if (pErr)7320*pErr = MZ_ZIP_INVALID_FILENAME;7321return MZ_FALSE;7322}73237324/* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */7325/* So be sure to compile with _LARGEFILE64_SOURCE 1 */7326if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0)7327{7328/* Create a new archive. */7329if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags))7330{7331if (pErr)7332*pErr = zip_archive.m_last_error;7333return MZ_FALSE;7334}73357336created_new_archive = MZ_TRUE;7337}7338else7339{7340/* Append to an existing archive. */7341if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0))7342{7343if (pErr)7344*pErr = zip_archive.m_last_error;7345return MZ_FALSE;7346}73477348if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags))7349{7350if (pErr)7351*pErr = zip_archive.m_last_error;73527353mz_zip_reader_end_internal(&zip_archive, MZ_FALSE);73547355return MZ_FALSE;7356}7357}73587359status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0);7360actual_err = zip_archive.m_last_error;73617362/* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */7363if (!mz_zip_writer_finalize_archive(&zip_archive))7364{7365if (!actual_err)7366actual_err = zip_archive.m_last_error;73677368status = MZ_FALSE;7369}73707371if (!mz_zip_writer_end_internal(&zip_archive, status))7372{7373if (!actual_err)7374actual_err = zip_archive.m_last_error;73757376status = MZ_FALSE;7377}73787379if ((!status) && (created_new_archive))7380{7381/* It's a new archive and something went wrong, so just delete it. */7382int ignoredStatus = MZ_DELETE_FILE(pZip_filename);7383(void)ignoredStatus;7384}73857386if (pErr)7387*pErr = actual_err;73887389return status;7390}73917392void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr)7393{7394mz_uint32 file_index;7395mz_zip_archive zip_archive;7396void *p = NULL;73977398if (pSize)7399*pSize = 0;74007401if ((!pZip_filename) || (!pArchive_name))7402{7403if (pErr)7404*pErr = MZ_ZIP_INVALID_PARAMETER;74057406return NULL;7407}74087409mz_zip_zero_struct(&zip_archive);7410if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0))7411{7412if (pErr)7413*pErr = zip_archive.m_last_error;74147415return NULL;7416}74177418if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index))7419{7420p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);7421}74227423mz_zip_reader_end_internal(&zip_archive, p != NULL);74247425if (pErr)7426*pErr = zip_archive.m_last_error;74277428return p;7429}74307431void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags)7432{7433return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL);7434}74357436#endif /* #ifndef MINIZ_NO_STDIO */74377438#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */74397440/* ------------------- Misc utils */74417442mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip)7443{7444return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID;7445}74467447mz_zip_type mz_zip_get_type(mz_zip_archive *pZip)7448{7449return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID;7450}74517452mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num)7453{7454mz_zip_error prev_err;74557456if (!pZip)7457return MZ_ZIP_INVALID_PARAMETER;74587459prev_err = pZip->m_last_error;74607461pZip->m_last_error = err_num;7462return prev_err;7463}74647465mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip)7466{7467if (!pZip)7468return MZ_ZIP_INVALID_PARAMETER;74697470return pZip->m_last_error;7471}74727473mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip)7474{7475return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR);7476}74777478mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip)7479{7480mz_zip_error prev_err;74817482if (!pZip)7483return MZ_ZIP_INVALID_PARAMETER;74847485prev_err = pZip->m_last_error;74867487pZip->m_last_error = MZ_ZIP_NO_ERROR;7488return prev_err;7489}74907491const char *mz_zip_get_error_string(mz_zip_error mz_err)7492{7493switch (mz_err)7494{7495case MZ_ZIP_NO_ERROR:7496return "no error";7497case MZ_ZIP_UNDEFINED_ERROR:7498return "undefined error";7499case MZ_ZIP_TOO_MANY_FILES:7500return "too many files";7501case MZ_ZIP_FILE_TOO_LARGE:7502return "file too large";7503case MZ_ZIP_UNSUPPORTED_METHOD:7504return "unsupported method";7505case MZ_ZIP_UNSUPPORTED_ENCRYPTION:7506return "unsupported encryption";7507case MZ_ZIP_UNSUPPORTED_FEATURE:7508return "unsupported feature";7509case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR:7510return "failed finding central directory";7511case MZ_ZIP_NOT_AN_ARCHIVE:7512return "not a ZIP archive";7513case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED:7514return "invalid header or archive is corrupted";7515case MZ_ZIP_UNSUPPORTED_MULTIDISK:7516return "unsupported multidisk archive";7517case MZ_ZIP_DECOMPRESSION_FAILED:7518return "decompression failed or archive is corrupted";7519case MZ_ZIP_COMPRESSION_FAILED:7520return "compression failed";7521case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE:7522return "unexpected decompressed size";7523case MZ_ZIP_CRC_CHECK_FAILED:7524return "CRC-32 check failed";7525case MZ_ZIP_UNSUPPORTED_CDIR_SIZE:7526return "unsupported central directory size";7527case MZ_ZIP_ALLOC_FAILED:7528return "allocation failed";7529case MZ_ZIP_FILE_OPEN_FAILED:7530return "file open failed";7531case MZ_ZIP_FILE_CREATE_FAILED:7532return "file create failed";7533case MZ_ZIP_FILE_WRITE_FAILED:7534return "file write failed";7535case MZ_ZIP_FILE_READ_FAILED:7536return "file read failed";7537case MZ_ZIP_FILE_CLOSE_FAILED:7538return "file close failed";7539case MZ_ZIP_FILE_SEEK_FAILED:7540return "file seek failed";7541case MZ_ZIP_FILE_STAT_FAILED:7542return "file stat failed";7543case MZ_ZIP_INVALID_PARAMETER:7544return "invalid parameter";7545case MZ_ZIP_INVALID_FILENAME:7546return "invalid filename";7547case MZ_ZIP_BUF_TOO_SMALL:7548return "buffer too small";7549case MZ_ZIP_INTERNAL_ERROR:7550return "internal error";7551case MZ_ZIP_FILE_NOT_FOUND:7552return "file not found";7553case MZ_ZIP_ARCHIVE_TOO_LARGE:7554return "archive is too large";7555case MZ_ZIP_VALIDATION_FAILED:7556return "validation failed";7557case MZ_ZIP_WRITE_CALLBACK_FAILED:7558return "write calledback failed";7559default:7560break;7561}75627563return "unknown error";7564}75657566/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */7567mz_bool mz_zip_is_zip64(mz_zip_archive *pZip)7568{7569if ((!pZip) || (!pZip->m_pState))7570return MZ_FALSE;75717572return pZip->m_pState->m_zip64;7573}75747575size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip)7576{7577if ((!pZip) || (!pZip->m_pState))7578return 0;75797580return pZip->m_pState->m_central_dir.m_size;7581}75827583mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip)7584{7585return pZip ? pZip->m_total_files : 0;7586}75877588mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip)7589{7590if (!pZip)7591return 0;7592return pZip->m_archive_size;7593}75947595mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip)7596{7597if ((!pZip) || (!pZip->m_pState))7598return 0;7599return pZip->m_pState->m_file_archive_start_ofs;7600}76017602MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip)7603{7604if ((!pZip) || (!pZip->m_pState))7605return 0;7606return pZip->m_pState->m_pFile;7607}76087609size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n)7610{7611if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead))7612return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);76137614return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n);7615}76167617mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size)7618{7619mz_uint n;7620const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);7621if (!p)7622{7623if (filename_buf_size)7624pFilename[0] = '\0';7625mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);7626return 0;7627}7628n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);7629if (filename_buf_size)7630{7631n = MZ_MIN(n, filename_buf_size - 1);7632memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);7633pFilename[n] = '\0';7634}7635return n + 1;7636}76377638mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat)7639{7640return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL);7641}76427643mz_bool mz_zip_end(mz_zip_archive *pZip)7644{7645if (!pZip)7646return MZ_FALSE;76477648if (pZip->m_zip_mode == MZ_ZIP_MODE_READING)7649return mz_zip_reader_end(pZip);7650#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS7651else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))7652return mz_zip_writer_end(pZip);7653#endif76547655return MZ_FALSE;7656}76577658#ifdef __cplusplus7659}7660#endif76617662#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/766376647665