Debian Codegraph @

src/cdogs/cwolfmap/zip/miniz.h

raw symbols SCIP
1 #define MINIZ_EXPORT
2 /* miniz.c 2.2.0 - public domain deflate/inflate, zlib-subset, ZIP
3 reading/writing/appending, PNG writing See "unlicense" statement at the end
4 of this file. Rich Geldreich <[email protected]>, last updated Oct. 13,
5 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
6 http://www.ietf.org/rfc/rfc1951.txt
7
8 Most API's defined in miniz.c are optional. For example, to disable the
9 archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of
10 all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
11
12 * Low-level Deflate/Inflate implementation notes:
13
14 Compression: Use the "tdefl" API's. The compressor supports raw, static,
15 and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only,
16 and Huffman-only streams. It performs and compresses approximately as well as
17 zlib.
18
19 Decompression: Use the "tinfl" API's. The entire decompressor is
20 implemented as a single function coroutine: see tinfl_decompress(). It
21 supports decompression into a 32KB (or larger power of 2) wrapping buffer, or
22 into a memory block large enough to hold the entire file.
23
24 The low-level tdefl/tinfl API's do not make any use of dynamic memory
25 allocation.
26
27 * zlib-style API notes:
28
29 miniz.c implements a fairly large subset of zlib. There's enough
30 functionality present for it to be a drop-in zlib replacement in many apps:
31 The z_stream struct, optional memory allocation callbacks
32 deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
33 inflateInit/inflateInit2/inflate/inflateReset/inflateEnd
34 compress, compress2, compressBound, uncompress
35 CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
36 routines. Supports raw deflate streams or standard zlib streams with adler-32
37 checking.
38
39 Limitations:
40 The callback API's are not implemented yet. No support for gzip headers or
41 zlib static dictionaries. I've tried to closely emulate zlib's various
42 flavors of stream flushing and return status codes, but there are no
43 guarantees that miniz.c pulls this off perfectly.
44
45 * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
46 originally written by Alex Evans. Supports 1-4 bytes/pixel images.
47
48 * ZIP archive API notes:
49
50 The ZIP archive API's where designed with simplicity and efficiency in
51 mind, with just enough abstraction to get the job done with minimal fuss.
52 There are simple API's to retrieve file information, read files from existing
53 archives, create new archives, append new files to existing archives, or
54 clone archive data from one archive to another. It supports archives located
55 in memory or the heap, on disk (using stdio.h), or you can specify custom
56 file read/write callbacks.
57
58 - Archive reading: Just call this function to read a single file from a
59 disk archive:
60
61 void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
62 char *pArchive_name, size_t *pSize, mz_uint zip_flags);
63
64 For more complex cases, use the "mz_zip_reader" functions. Upon opening an
65 archive, the entire central directory is located and read as-is into memory,
66 and subsequent file access only occurs when reading individual files.
67
68 - Archives file scanning: The simple way is to use this function to scan a
69 loaded archive for a specific file:
70
71 int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
72 const char *pComment, mz_uint flags);
73
74 The locate operation can optionally check file comments too, which (as one
75 example) can be used to identify multiple versions of the same file in an
76 archive. This function uses a simple linear search through the central
77 directory, so it's not very fast.
78
79 Alternately, you can iterate through all the files in an archive (using
80 mz_zip_reader_get_num_files()) and retrieve detailed info on each file by
81 calling mz_zip_reader_file_stat().
82
83 - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
84 immediately writes compressed file data to disk and builds an exact image of
85 the central directory in memory. The central directory image is written all
86 at once at the end of the archive file when the archive is finalized.
87
88 The archive writer can optionally align each file's local header and file
89 data to any power of 2 alignment, which can be useful when the archive will
90 be read from optical media. Also, the writer supports placing arbitrary data
91 blobs at the very beginning of ZIP archives. Archives written using either
92 feature are still readable by any ZIP tool.
93
94 - Archive appending: The simple way to add a single file to an archive is
95 to call this function:
96
97 mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
98 const char *pArchive_name, const void *pBuf, size_t buf_size, const void
99 *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
100
101 The archive will be created if it doesn't already exist, otherwise it'll be
102 appended to. Note the appending is done in-place and is not an atomic
103 operation, so if something goes wrong during the operation it's possible the
104 archive could be left without a central directory (although the local file
105 headers and file data will be fine, so the archive will be recoverable).
106
107 For more complex archive modification scenarios:
108 1. The safest way is to use a mz_zip_reader to read the existing archive,
109 cloning only those bits you want to preserve into a new archive using using
110 the mz_zip_writer_add_from_zip_reader() function (which compiles the
111 compressed file data as-is). When you're done, delete the old archive and
112 rename the newly written archive, and you're done. This is safe but requires
113 a bunch of temporary disk space or heap memory.
114
115 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
116 mz_zip_writer_init_from_reader(), append new files as needed, then finalize
117 the archive which will write an updated central directory to the original
118 archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place()
119 does.) There's a possibility that the archive's central directory could be
120 lost with this method if anything goes wrong, though.
121
122 - ZIP archive support limitations:
123 No spanning support. Extraction functions can only handle unencrypted,
124 stored or deflated files. Requires streams capable of seeking.
125
126 * This is a header file library, like stb_image.c. To get only a header file,
127 either cut and paste the below header, or create miniz.h, #define
128 MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
129
130 * Important: For best perf. be sure to customize the below macros for your
131 target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define
132 MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1
133
134 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
135 including miniz.c to ensure miniz uses the 64-bit variants: fopen64(),
136 stat64(), etc. Otherwise you won't be able to process large files (i.e.
137 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
138 */
139 #pragma once
140
141 /* Defines to completely disable specific portions of miniz.c:
142 If all macros here are defined the only functionality remaining will be
143 CRC-32, adler-32, tinfl, and tdefl. */
144
145 /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
146 * stdio for file I/O. */
147 /*#define MINIZ_NO_STDIO */
148
149 /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
150 * to get the current time, or */
151 /* get/set file times, and the C run-time funcs that get/set times won't be
152 * called. */
153 /* The current downside is the times written to your archives will be from 1979.
154 */
155 /*#define MINIZ_NO_TIME */
156
157 /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */
158 /*#define MINIZ_NO_ARCHIVE_APIS */
159
160 /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP
161 * archive API's. */
162 /*#define MINIZ_NO_ARCHIVE_WRITING_APIS */
163
164 /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
165 * API's. */
166 /*#define MINIZ_NO_ZLIB_APIS */
167
168 /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
169 * conflicts against stock zlib. */
170 /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
171
172 /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
173 Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
174 user alloc/free/realloc callbacks to the zlib and archive API's, and a few
175 stand-alone helper API's which don't provide custom user functions (such as
176 tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
177 */
178 /*#define MINIZ_NO_MALLOC */
179
180 #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
181 /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
182 * on Linux */
183 #define MINIZ_NO_TIME
184 #endif
185
186 #include <stddef.h>
187
188 #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
189 #include <time.h>
190 #endif
191
192 #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
193 defined(__i386) || defined(__i486__) || defined(__i486) || \
194 defined(i386) || defined(__ia64__) || defined(__x86_64__)
195 /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */
196 #define MINIZ_X86_OR_X64_CPU 1
197 #else
198 #define MINIZ_X86_OR_X64_CPU 0
199 #endif
200
201 #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
202 /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */
203 #define MINIZ_LITTLE_ENDIAN 1
204 #else
205 #define MINIZ_LITTLE_ENDIAN 0
206 #endif
207
208 /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */
209 #if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES)
210 #if MINIZ_X86_OR_X64_CPU
211 /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
212 * integer loads and stores from unaligned addresses. */
213 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
214 #define MINIZ_UNALIGNED_USE_MEMCPY
215 #else
216 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
217 #endif
218 #endif
219
220 #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
221 defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
222 defined(__x86_64__)
223 /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
224 * reasonably fast (and don't involve compiler generated calls to helper
225 * functions). */
226 #define MINIZ_HAS_64BIT_REGISTERS 1
227 #else
228 #define MINIZ_HAS_64BIT_REGISTERS 0
229 #endif
230
231 #ifdef __cplusplus
232 extern "C" {
233 #endif
234
235 /* ------------------- zlib-style API Definitions. */
236
237 /* For more compatibility with zlib, miniz.c uses unsigned long for some
238 * parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */
239 typedef unsigned long mz_ulong;
240
241 /* mz_free() internally uses the MZ_FREE() macro (which by default calls free()
242 * unless you've modified the MZ_MALLOC macro) to release a block allocated from
243 * the heap. */
244 MINIZ_EXPORT void mz_free(void *p);
245
246 #define MZ_ADLER32_INIT (1)
247 /* mz_adler32() returns the initial adler-32 value to use when called with
248 * ptr==NULL. */
249 MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr,
250 size_t buf_len);
251
252 #define MZ_CRC32_INIT (0)
253 /* mz_crc32() returns the initial CRC-32 value to use when called with
254 * ptr==NULL. */
255 MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr,
256 size_t buf_len);
257
258 /* Compression strategies. */
259 enum {
260 MZ_DEFAULT_STRATEGY = 0,
261 MZ_FILTERED = 1,
262 MZ_HUFFMAN_ONLY = 2,
263 MZ_RLE = 3,
264 MZ_FIXED = 4
265 };
266
267 /* Method */
268 #define MZ_DEFLATED 8
269
270 /* Heap allocation callbacks.
271 Note that mz_alloc_func parameter types purposely differ from zlib's: items/size
272 is size_t, not unsigned long. */
273 typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
274 typedef void (*mz_free_func)(void *opaque, void *address);
275 typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
276 size_t size);
277
278 /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best
279 * possible compression (not zlib compatible, and may be very slow),
280 * MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */
281 enum {
282 MZ_NO_COMPRESSION = 0,
283 MZ_BEST_SPEED = 1,
284 MZ_BEST_COMPRESSION = 9,
285 MZ_UBER_COMPRESSION = 10,
286 MZ_DEFAULT_LEVEL = 6,
287 MZ_DEFAULT_COMPRESSION = -1
288 };
289
290 #define MZ_VERSION "10.2.0"
291 #define MZ_VERNUM 0xA100
292 #define MZ_VER_MAJOR 10
293 #define MZ_VER_MINOR 2
294 #define MZ_VER_REVISION 0
295 #define MZ_VER_SUBREVISION 0
296
297 #ifndef MINIZ_NO_ZLIB_APIS
298
299 /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
300 * other values are for advanced use (refer to the zlib docs). */
301 enum {
302 MZ_NO_FLUSH = 0,
303 MZ_PARTIAL_FLUSH = 1,
304 MZ_SYNC_FLUSH = 2,
305 MZ_FULL_FLUSH = 3,
306 MZ_FINISH = 4,
307 MZ_BLOCK = 5
308 };
309
310 /* Return status codes. MZ_PARAM_ERROR is non-standard. */
311 enum {
312 MZ_OK = 0,
313 MZ_STREAM_END = 1,
314 MZ_NEED_DICT = 2,
315 MZ_ERRNO = -1,
316 MZ_STREAM_ERROR = -2,
317 MZ_DATA_ERROR = -3,
318 MZ_MEM_ERROR = -4,
319 MZ_BUF_ERROR = -5,
320 MZ_VERSION_ERROR = -6,
321 MZ_PARAM_ERROR = -10000
322 };
323
324 /* Window bits */
325 #define MZ_DEFAULT_WINDOW_BITS 15
326
327 struct mz_internal_state;
328
329 /* Compression/decompression stream struct. */
330 typedef struct mz_stream_s {
331 const unsigned char *next_in; /* pointer to next byte to read */
332 unsigned int avail_in; /* number of bytes available at next_in */
333 mz_ulong total_in; /* total number of bytes consumed so far */
334
335 unsigned char *next_out; /* pointer to next byte to write */
336 unsigned int avail_out; /* number of bytes that can be written to next_out */
337 mz_ulong total_out; /* total number of bytes produced so far */
338
339 char *msg; /* error msg (unused) */
340 struct mz_internal_state
341 *state; /* internal state, allocated by zalloc/zfree */
342
343 mz_alloc_func
344 zalloc; /* optional heap allocation function (defaults to malloc) */
345 mz_free_func zfree; /* optional heap free function (defaults to free) */
346 void *opaque; /* heap alloc function user pointer */
347
348 int data_type; /* data_type (unused) */
349 mz_ulong adler; /* adler32 of the source or uncompressed data */
350 mz_ulong reserved; /* not used */
351 } mz_stream;
352
353 typedef mz_stream *mz_streamp;
354
355 /* Returns the version string of miniz.c. */
356 MINIZ_EXPORT const char *mz_version(void);
357
358 /* mz_deflateInit() initializes a compressor with default options: */
359 /* Parameters: */
360 /* pStream must point to an initialized mz_stream struct. */
361 /* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */
362 /* level 1 enables a specially optimized compression function that's been
363 * optimized purely for performance, not ratio. */
364 /* (This special func. is currently only enabled when
365 * MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */
366 /* Return values: */
367 /* MZ_OK on success. */
368 /* MZ_STREAM_ERROR if the stream is bogus. */
369 /* MZ_PARAM_ERROR if the input parameters are bogus. */
370 /* MZ_MEM_ERROR on out of memory. */
371 MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level);
372
373 /* mz_deflateInit2() is like mz_deflate(), except with more control: */
374 /* Additional parameters: */
375 /* method must be MZ_DEFLATED */
376 /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
377 * zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
378 * header or footer) */
379 /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */
380 MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method,
381 int window_bits, int mem_level, int strategy);
382
383 /* Quickly resets a compressor without having to reallocate anything. Same as
384 * calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */
385 MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream);
386
387 /* mz_deflate() compresses the input to output, consuming as much of the input
388 * and producing as much output as possible. */
389 /* Parameters: */
390 /* pStream is the stream to read from and write to. You must initialize/update
391 * the next_in, avail_in, next_out, and avail_out members. */
392 /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
393 * MZ_FINISH. */
394 /* Return values: */
395 /* MZ_OK on success (when flushing, or if more input is needed but not
396 * available, and/or there's more output to be written but the output buffer is
397 * full). */
398 /* MZ_STREAM_END if all input has been consumed and all output bytes have been
399 * written. Don't call mz_deflate() on the stream anymore. */
400 /* MZ_STREAM_ERROR if the stream is bogus. */
401 /* MZ_PARAM_ERROR if one of the parameters is invalid. */
402 /* MZ_BUF_ERROR if no forward progress is possible because the input and/or
403 * output buffers are empty. (Fill up the input buffer or free up some output
404 * space and try again.) */
405 MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush);
406
407 /* mz_deflateEnd() deinitializes a compressor: */
408 /* Return values: */
409 /* MZ_OK on success. */
410 /* MZ_STREAM_ERROR if the stream is bogus. */
411 MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream);
412
413 /* mz_deflateBound() returns a (very) conservative upper bound on the amount of
414 * data that could be generated by deflate(), assuming flush is set to only
415 * MZ_NO_FLUSH or MZ_FINISH. */
416 MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
417
418 /* Single-call compression functions mz_compress() and mz_compress2(): */
419 /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on
420 * failure. */
421 MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
422 const unsigned char *pSource, mz_ulong source_len);
423 MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
424 const unsigned char *pSource, mz_ulong source_len,
425 int level);
426
427 /* mz_compressBound() returns a (very) conservative upper bound on the amount of
428 * data that could be generated by calling mz_compress(). */
429 MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len);
430
431 /* Initializes a decompressor. */
432 MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream);
433
434 /* mz_inflateInit2() is like mz_inflateInit() with an additional option that
435 * controls the window size and whether or not the stream has been wrapped with
436 * a zlib header/footer: */
437 /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
438 * -MZ_DEFAULT_WINDOW_BITS (raw deflate). */
439 MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits);
440
441 /* Quickly resets a compressor without having to reallocate anything. Same as
442 * calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */
443 MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream);
444
445 /* Decompresses the input stream to the output, consuming only as much of the
446 * input as needed, and writing as much to the output as possible. */
447 /* Parameters: */
448 /* pStream is the stream to read from and write to. You must initialize/update
449 * the next_in, avail_in, next_out, and avail_out members. */
450 /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */
451 /* On the first call, if flush is MZ_FINISH it's assumed the input and output
452 * buffers are both sized large enough to decompress the entire stream in a
453 * single call (this is slightly faster). */
454 /* MZ_FINISH implies that there are no more source bytes available beside
455 * what's already in the input buffer, and that the output buffer is large
456 * enough to hold the rest of the decompressed data. */
457 /* Return values: */
458 /* MZ_OK on success. Either more input is needed but not available, and/or
459 * there's more output to be written but the output buffer is full. */
460 /* MZ_STREAM_END if all needed input has been consumed and all output bytes
461 * have been written. For zlib streams, the adler-32 of the decompressed data
462 * has also been verified. */
463 /* MZ_STREAM_ERROR if the stream is bogus. */
464 /* MZ_DATA_ERROR if the deflate stream is invalid. */
465 /* MZ_PARAM_ERROR if one of the parameters is invalid. */
466 /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is
467 * empty but the inflater needs more input to continue, or if the output buffer
468 * is not large enough. Call mz_inflate() again */
469 /* with more input data, or with more room in the output buffer (except when
470 * using single call decompression, described above). */
471 MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush);
472
473 /* Deinitializes a decompressor. */
474 MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream);
475
476 /* Single-call decompression. */
477 /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on
478 * failure. */
479 MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
480 const unsigned char *pSource,
481 mz_ulong source_len);
482 MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len,
483 const unsigned char *pSource,
484 mz_ulong *pSource_len);
485
486 /* Returns a string description of the specified error code, or NULL if the
487 * error code is invalid. */
488 MINIZ_EXPORT const char *mz_error(int err);
489
490 /* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
491 * as a drop-in replacement for the subset of zlib that miniz.c supports. */
492 /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
493 * use zlib in the same project. */
494 #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
495 typedef unsigned char Byte;
496 typedef unsigned int uInt;
497 typedef mz_ulong uLong;
498 typedef Byte Bytef;
499 typedef uInt uIntf;
500 typedef char charf;
501 typedef int intf;
502 typedef void *voidpf;
503 typedef uLong uLongf;
504 typedef void *voidp;
505 typedef void *const voidpc;
506 #define Z_NULL 0
507 #define Z_NO_FLUSH MZ_NO_FLUSH
508 #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
509 #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
510 #define Z_FULL_FLUSH MZ_FULL_FLUSH
511 #define Z_FINISH MZ_FINISH
512 #define Z_BLOCK MZ_BLOCK
513 #define Z_OK MZ_OK
514 #define Z_STREAM_END MZ_STREAM_END
515 #define Z_NEED_DICT MZ_NEED_DICT
516 #define Z_ERRNO MZ_ERRNO
517 #define Z_STREAM_ERROR MZ_STREAM_ERROR
518 #define Z_DATA_ERROR MZ_DATA_ERROR
519 #define Z_MEM_ERROR MZ_MEM_ERROR
520 #define Z_BUF_ERROR MZ_BUF_ERROR
521 #define Z_VERSION_ERROR MZ_VERSION_ERROR
522 #define Z_PARAM_ERROR MZ_PARAM_ERROR
523 #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
524 #define Z_BEST_SPEED MZ_BEST_SPEED
525 #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
526 #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
527 #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
528 #define Z_FILTERED MZ_FILTERED
529 #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
530 #define Z_RLE MZ_RLE
531 #define Z_FIXED MZ_FIXED
532 #define Z_DEFLATED MZ_DEFLATED
533 #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
534 #define alloc_func mz_alloc_func
535 #define free_func mz_free_func
536 #define internal_state mz_internal_state
537 #define z_stream mz_stream
538 #define deflateInit mz_deflateInit
539 #define deflateInit2 mz_deflateInit2
540 #define deflateReset mz_deflateReset
541 #define deflate mz_deflate
542 #define deflateEnd mz_deflateEnd
543 #define deflateBound mz_deflateBound
544 #define compress mz_compress
545 #define compress2 mz_compress2
546 #define compressBound mz_compressBound
547 #define inflateInit mz_inflateInit
548 #define inflateInit2 mz_inflateInit2
549 #define inflateReset mz_inflateReset
550 #define inflate mz_inflate
551 #define inflateEnd mz_inflateEnd
552 #define uncompress mz_uncompress
553 #define uncompress2 mz_uncompress2
554 #define crc32 mz_crc32
555 #define adler32 mz_adler32
556 #define MAX_WBITS 15
557 #define MAX_MEM_LEVEL 9
558 #define zError mz_error
559 #define ZLIB_VERSION MZ_VERSION
560 #define ZLIB_VERNUM MZ_VERNUM
561 #define ZLIB_VER_MAJOR MZ_VER_MAJOR
562 #define ZLIB_VER_MINOR MZ_VER_MINOR
563 #define ZLIB_VER_REVISION MZ_VER_REVISION
564 #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
565 #define zlibVersion mz_version
566 #define zlib_version mz_version()
567 #endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
568
569 #endif /* MINIZ_NO_ZLIB_APIS */
570
571 #ifdef __cplusplus
572 }
573 #endif
574
575 #pragma once
576 #include <assert.h>
577 #include <stdint.h>
578 #include <stdlib.h>
579 #include <string.h>
580
581 /* ------------------- Types and macros */
582 typedef unsigned char mz_uint8;
583 typedef signed short mz_int16;
584 typedef unsigned short mz_uint16;
585 typedef unsigned int mz_uint32;
586 typedef unsigned int mz_uint;
587 typedef int64_t mz_int64;
588 typedef uint64_t mz_uint64;
589 typedef int mz_bool;
590
591 #define MZ_FALSE (0)
592 #define MZ_TRUE (1)
593
594 /* Works around MSVC's spammy "warning C4127: conditional expression is
595 * constant" message. */
596 #ifdef _MSC_VER
597 #define MZ_MACRO_END while (0, 0)
598 #else
599 #define MZ_MACRO_END while (0)
600 #endif
601
602 #ifdef MINIZ_NO_STDIO
603 #define MZ_FILE void *
604 #else
605 #include <stdio.h>
606 #define MZ_FILE FILE
607 #endif /* #ifdef MINIZ_NO_STDIO */
608
609 #ifdef MINIZ_NO_TIME
610 typedef struct mz_dummy_time_t_tag {
611 int m_dummy;
612 } mz_dummy_time_t;
613 #define MZ_TIME_T mz_dummy_time_t
614 #else
615 #define MZ_TIME_T time_t
616 #endif
617
618 #define MZ_ASSERT(x) assert(x)
619
620 #ifdef MINIZ_NO_MALLOC
621 #define MZ_MALLOC(x) NULL
622 #define MZ_FREE(x) (void)x, ((void)0)
623 #define MZ_REALLOC(p, x) NULL
624 #else
625 #define MZ_MALLOC(x) malloc(x)
626 #define MZ_FREE(x) free(x)
627 #define MZ_REALLOC(p, x) realloc(p, x)
628 #endif
629
630 #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
631 #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
632 #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
633
634 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
635 #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
636 #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
637 #else
638 #define MZ_READ_LE16(p) \
639 ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
640 ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
641 #define MZ_READ_LE32(p) \
642 ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
643 ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
644 ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
645 ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
646 #endif
647
648 #define MZ_READ_LE64(p) \
649 (((mz_uint64)MZ_READ_LE32(p)) | \
650 (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) \
651 << 32U))
652
653 #ifdef _MSC_VER
654 #define MZ_FORCEINLINE __forceinline
655 #elif defined(__GNUC__)
656 #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__))
657 #else
658 #define MZ_FORCEINLINE inline
659 #endif
660
661 #ifdef __cplusplus
662 extern "C" {
663 #endif
664
665 extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items,
666 size_t size);
667 extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address);
668 extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address,
669 size_t items, size_t size);
670
671 #define MZ_UINT16_MAX (0xFFFFU)
672 #define MZ_UINT32_MAX (0xFFFFFFFFU)
673
674 #ifdef __cplusplus
675 }
676 #endif
677 #pragma once
678
679 #ifdef __cplusplus
680 extern "C" {
681 #endif
682 /* ------------------- Low-level Compression API Definitions */
683
684 /* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
685 * slower, and raw/dynamic blocks will be output more frequently). */
686 #define TDEFL_LESS_MEMORY 0
687
688 /* tdefl_init() compression flags logically OR'd together (low 12 bits contain
689 * the max. number of probes per dictionary search): */
690 /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
691 * per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
692 * compression), 4095=Huffman+LZ (slowest/best compression). */
693 enum {
694 TDEFL_HUFFMAN_ONLY = 0,
695 TDEFL_DEFAULT_MAX_PROBES = 128,
696 TDEFL_MAX_PROBES_MASK = 0xFFF
697 };
698
699 /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
700 * the deflate data, and the Adler-32 of the source data at the end. Otherwise,
701 * you'll get raw deflate data. */
702 /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
703 * when not writing zlib headers). */
704 /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
705 * efficient lazy parsing. */
706 /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
707 * initialization time to the minimum, but the output may vary from run to run
708 * given the same input (depending on the contents of memory). */
709 /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
710 */
711 /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */
712 /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */
713 /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */
714 /* The low 12 bits are reserved to control the max # of hash probes per
715 * dictionary lookup (see TDEFL_MAX_PROBES_MASK). */
716 enum {
717 TDEFL_WRITE_ZLIB_HEADER = 0x01000,
718 TDEFL_COMPUTE_ADLER32 = 0x02000,
719 TDEFL_GREEDY_PARSING_FLAG = 0x04000,
720 TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
721 TDEFL_RLE_MATCHES = 0x10000,
722 TDEFL_FILTER_MATCHES = 0x20000,
723 TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
724 TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
725 };
726
727 /* High level compression functions: */
728 /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
729 * allocated via malloc(). */
730 /* On entry: */
731 /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */
732 /* flags: The max match finder probes (default is 128) logically OR'd against
733 * the above flags. Higher probes are slower but improve compression. */
734 /* On return: */
735 /* Function returns a pointer to the compressed data, or NULL on failure. */
736 /* *pOut_len will be set to the compressed data's size, which could be larger
737 * than src_buf_len on uncompressible data. */
738 /* The caller must free() the returned block when it's no longer needed. */
739 MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf,
740 size_t src_buf_len,
741 size_t *pOut_len, int flags);
742
743 /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in
744 * memory. */
745 /* Returns 0 on failure. */
746 MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf,
747 size_t out_buf_len,
748 const void *pSrc_buf,
749 size_t src_buf_len, int flags);
750
751 /* Compresses an image to a compressed PNG file in memory. */
752 /* On entry: */
753 /* pImage, w, h, and num_chans describe the image to compress. num_chans may be
754 * 1, 2, 3, or 4. */
755 /* The image pitch in bytes per scanline will be w*num_chans. The leftmost
756 * pixel on the top scanline is stored first in memory. */
757 /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
758 * MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */
759 /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL
760 * apps). */
761 /* On return: */
762 /* Function returns a pointer to the compressed data, or NULL on failure. */
763 /* *pLen_out will be set to the size of the PNG image file. */
764 /* The caller must mz_free() the returned heap block (which will typically be
765 * larger than *pLen_out) when it's no longer needed. */
766 MINIZ_EXPORT void *
767 tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h,
768 int num_chans, size_t *pLen_out,
769 mz_uint level, mz_bool flip);
770 MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage,
771 int w, int h,
772 int num_chans,
773 size_t *pLen_out);
774
775 /* Output stream interface. The compressor uses this interface to write
776 * compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */
777 typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
778 void *pUser);
779
780 /* tdefl_compress_mem_to_output() compresses a block to an output stream. The
781 * above helpers use this function internally. */
782 MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(
783 const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func,
784 void *pPut_buf_user, int flags);
785
786 enum {
787 TDEFL_MAX_HUFF_TABLES = 3,
788 TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
789 TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
790 TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
791 TDEFL_LZ_DICT_SIZE = 32768,
792 TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
793 TDEFL_MIN_MATCH_LEN = 3,
794 TDEFL_MAX_MATCH_LEN = 258
795 };
796
797 /* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
798 * output block (using static/fixed Huffman codes). */
799 #if TDEFL_LESS_MEMORY
800 enum {
801 TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
802 TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
803 TDEFL_MAX_HUFF_SYMBOLS = 288,
804 TDEFL_LZ_HASH_BITS = 12,
805 TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
806 TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
807 TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
808 };
809 #else
810 enum {
811 TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
812 TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
813 TDEFL_MAX_HUFF_SYMBOLS = 288,
814 TDEFL_LZ_HASH_BITS = 15,
815 TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
816 TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
817 TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
818 };
819 #endif
820
821 /* The low-level tdefl functions below may be used directly if the above helper
822 * functions aren't flexible enough. The low-level functions don't make any heap
823 * allocations, unlike the above helper functions. */
824 typedef enum {
825 TDEFL_STATUS_BAD_PARAM = -2,
826 TDEFL_STATUS_PUT_BUF_FAILED = -1,
827 TDEFL_STATUS_OKAY = 0,
828 TDEFL_STATUS_DONE = 1
829 } tdefl_status;
830
831 /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */
832 typedef enum {
833 TDEFL_NO_FLUSH = 0,
834 TDEFL_SYNC_FLUSH = 2,
835 TDEFL_FULL_FLUSH = 3,
836 TDEFL_FINISH = 4
837 } tdefl_flush;
838
839 /* tdefl's compression state structure. */
840 typedef struct {
841 tdefl_put_buf_func_ptr m_pPut_buf_func;
842 void *m_pPut_buf_user;
843 mz_uint m_flags, m_max_probes[2];
844 int m_greedy_parsing;
845 mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
846 mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
847 mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
848 m_bit_buffer;
849 mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
850 m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
851 m_wants_to_finish;
852 tdefl_status m_prev_return_status;
853 const void *m_pIn_buf;
854 void *m_pOut_buf;
855 size_t *m_pIn_buf_size, *m_pOut_buf_size;
856 tdefl_flush m_flush;
857 const mz_uint8 *m_pSrc;
858 size_t m_src_buf_left, m_out_buf_ofs;
859 mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
860 mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
861 mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
862 mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
863 mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
864 mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
865 mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
866 mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
867 } tdefl_compressor;
868
869 /* Initializes the compressor. */
870 /* There is no corresponding deinit() function because the tdefl API's do not
871 * dynamically allocate memory. */
872 /* pBut_buf_func: If NULL, output data will be supplied to the specified
873 * callback. In this case, the user should call the tdefl_compress_buffer() API
874 * for compression. */
875 /* If pBut_buf_func is NULL the user should always call the tdefl_compress()
876 * API. */
877 /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
878 * etc.) */
879 MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d,
880 tdefl_put_buf_func_ptr pPut_buf_func,
881 void *pPut_buf_user, int flags);
882
883 /* Compresses a block of data, consuming as much of the specified input buffer
884 * as possible, and writing as much compressed data to the specified output
885 * buffer as possible. */
886 MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d,
887 const void *pIn_buf,
888 size_t *pIn_buf_size, void *pOut_buf,
889 size_t *pOut_buf_size,
890 tdefl_flush flush);
891
892 /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
893 * non-NULL tdefl_put_buf_func_ptr. */
894 /* tdefl_compress_buffer() always consumes the entire input buffer. */
895 MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d,
896 const void *pIn_buf,
897 size_t in_buf_size,
898 tdefl_flush flush);
899
900 MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
901 MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
902
903 /* Create tdefl_compress() flags given zlib-style compression parameters. */
904 /* level may range from [0,10] (where 10 is absolute max compression, but may be
905 * much slower on some files) */
906 /* window_bits may be -15 (raw deflate) or 15 (zlib) */
907 /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
908 * MZ_RLE, or MZ_FIXED */
909 MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level,
910 int window_bits,
911 int strategy);
912
913 #ifndef MINIZ_NO_MALLOC
914 /* Allocate the tdefl_compressor structure in C so that */
915 /* non-C language bindings to tdefl_ API don't need to worry about */
916 /* structure size and allocation mechanism. */
917 MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void);
918 MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp);
919 #endif
920
921 #ifdef __cplusplus
922 }
923 #endif
924 #pragma once
925
926 /* ------------------- Low-level Decompression API Definitions */
927
928 #ifdef __cplusplus
929 extern "C" {
930 #endif
931 /* Decompression flags used by tinfl_decompress(). */
932 /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
933 * ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
934 * input is a raw deflate stream. */
935 /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
936 * beyond the end of the supplied input buffer. If clear, the input buffer
937 * contains all remaining input. */
938 /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
939 * enough to hold the entire decompressed stream. If clear, the output buffer is
940 * at least the size of the dictionary (typically 32KB). */
941 /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
942 * decompressed bytes. */
943 enum {
944 TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
945 TINFL_FLAG_HAS_MORE_INPUT = 2,
946 TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
947 TINFL_FLAG_COMPUTE_ADLER32 = 8
948 };
949
950 /* High level decompression functions: */
951 /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
952 * allocated via malloc(). */
953 /* On entry: */
954 /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
955 * to decompress. */
956 /* On return: */
957 /* Function returns a pointer to the decompressed data, or NULL on failure. */
958 /* *pOut_len will be set to the decompressed data's size, which could be larger
959 * than src_buf_len on uncompressible data. */
960 /* The caller must call mz_free() on the returned block when it's no longer
961 * needed. */
962 MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf,
963 size_t src_buf_len,
964 size_t *pOut_len, int flags);
965
966 /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
967 * in memory. */
968 /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
969 * written on success. */
970 #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
971 MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf,
972 size_t out_buf_len,
973 const void *pSrc_buf,
974 size_t src_buf_len, int flags);
975
976 /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an
977 * internal 32KB buffer, and a user provided callback function will be called to
978 * flush the buffer. */
979 /* Returns 1 on success or 0 on failure. */
980 typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
981 MINIZ_EXPORT int
982 tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
983 tinfl_put_buf_func_ptr pPut_buf_func,
984 void *pPut_buf_user, int flags);
985
986 struct tinfl_decompressor_tag;
987 typedef struct tinfl_decompressor_tag tinfl_decompressor;
988
989 #ifndef MINIZ_NO_MALLOC
990 /* Allocate the tinfl_decompressor structure in C so that */
991 /* non-C language bindings to tinfl_ API don't need to worry about */
992 /* structure size and allocation mechanism. */
993 MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void);
994 MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp);
995 #endif
996
997 /* Max size of LZ dictionary. */
998 #define TINFL_LZ_DICT_SIZE 32768
999
1000 /* Return status. */
1001 typedef enum {
1002 /* This flags indicates the inflator needs 1 or more input bytes to make
1003 forward progress, but the caller is indicating that no more are available.
1004 The compressed data */
1005 /* is probably corrupted. If you call the inflator again with more bytes it'll
1006 try to continue processing the input but this is a BAD sign (either the
1007 data is corrupted or you called it incorrectly). */
1008 /* If you call it again with no input you'll just get
1009 TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */
1010 TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
1011
1012 /* This flag indicates that one or more of the input parameters was obviously
1013 bogus. (You can try calling it again, but if you get this error the calling
1014 code is wrong.) */
1015 TINFL_STATUS_BAD_PARAM = -3,
1016
1017 /* This flags indicate the inflator is finished but the adler32 check of the
1018 uncompressed data didn't match. If you call it again it'll return
1019 TINFL_STATUS_DONE. */
1020 TINFL_STATUS_ADLER32_MISMATCH = -2,
1021
1022 /* This flags indicate the inflator has somehow failed (bad code, corrupted
1023 input, etc.). If you call it again without resetting via tinfl_init() it
1024 it'll just keep on returning the same status failure code. */
1025 TINFL_STATUS_FAILED = -1,
1026
1027 /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */
1028
1029 /* This flag indicates the inflator has returned every byte of uncompressed
1030 data that it can, has consumed every byte that it needed, has successfully
1031 reached the end of the deflate stream, and */
1032 /* if zlib headers and adler32 checking enabled that it has successfully
1033 checked the uncompressed data's adler32. If you call it again you'll just
1034 get TINFL_STATUS_DONE over and over again. */
1035 TINFL_STATUS_DONE = 0,
1036
1037 /* This flag indicates the inflator MUST have more input data (even 1 byte)
1038 before it can make any more forward progress, or you need to clear the
1039 TINFL_FLAG_HAS_MORE_INPUT */
1040 /* flag on the next call if you don't have any more source data. If the source
1041 data was somehow corrupted it's also possible (but unlikely) for the
1042 inflator to keep on demanding input to */
1043 /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */
1044 TINFL_STATUS_NEEDS_MORE_INPUT = 1,
1045
1046 /* This flag indicates the inflator definitely has 1 or more bytes of
1047 uncompressed data available, but it cannot write this data into the output
1048 buffer. */
1049 /* Note if the source compressed data was corrupted it's possible for the
1050 inflator to return a lot of uncompressed data to the caller. I've been
1051 assuming you know how much uncompressed data to expect */
1052 /* (either exact or worst case) and will stop calling the inflator and fail
1053 after receiving too much. In pure streaming scenarios where you have no
1054 idea how many bytes to expect this may not be possible */
1055 /* so I may need to add some code to address this. */
1056 TINFL_STATUS_HAS_MORE_OUTPUT = 2
1057 } tinfl_status;
1058
1059 /* Initializes the decompressor to its initial state. */
1060 #define tinfl_init(r) \
1061 do { \
1062 (r)->m_state = 0; \
1063 } \
1064 MZ_MACRO_END
1065 #define tinfl_get_adler32(r) (r)->m_check_adler32
1066
1067 /* Main low-level decompressor coroutine function. This is the only function
1068 * actually needed for decompression. All the other functions are just
1069 * high-level helpers for improved usability. */
1070 /* This is a universal API, i.e. it can be used as a building block to build any
1071 * desired higher level decompression API. In the limit case, it can be called
1072 * once per every byte input or output. */
1073 MINIZ_EXPORT tinfl_status tinfl_decompress(
1074 tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size,
1075 mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
1076 const mz_uint32 decomp_flags);
1077
1078 /* Internal/private bits follow. */
1079 enum {
1080 TINFL_MAX_HUFF_TABLES = 3,
1081 TINFL_MAX_HUFF_SYMBOLS_0 = 288,
1082 TINFL_MAX_HUFF_SYMBOLS_1 = 32,
1083 TINFL_MAX_HUFF_SYMBOLS_2 = 19,
1084 TINFL_FAST_LOOKUP_BITS = 10,
1085 TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
1086 };
1087
1088 typedef struct {
1089 mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
1090 mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
1091 m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
1092 } tinfl_huff_table;
1093
1094 #if MINIZ_HAS_64BIT_REGISTERS
1095 #define TINFL_USE_64BIT_BITBUF 1
1096 #else
1097 #define TINFL_USE_64BIT_BITBUF 0
1098 #endif
1099
1100 #if TINFL_USE_64BIT_BITBUF
1101 typedef mz_uint64 tinfl_bit_buf_t;
1102 #define TINFL_BITBUF_SIZE (64)
1103 #else
1104 typedef mz_uint32 tinfl_bit_buf_t;
1105 #define TINFL_BITBUF_SIZE (32)
1106 #endif
1107
1108 struct tinfl_decompressor_tag {
1109 mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
1110 m_check_adler32, m_dist, m_counter, m_num_extra,
1111 m_table_sizes[TINFL_MAX_HUFF_TABLES];
1112 tinfl_bit_buf_t m_bit_buf;
1113 size_t m_dist_from_out_buf_start;
1114 tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
1115 mz_uint8 m_raw_header[4],
1116 m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
1117 };
1118
1119 #ifdef __cplusplus
1120 }
1121 #endif
1122
1123 #pragma once
1124
1125 /* ------------------- ZIP archive reading/writing */
1126
1127 #ifndef MINIZ_NO_ARCHIVE_APIS
1128
1129 #ifdef __cplusplus
1130 extern "C" {
1131 #endif
1132
1133 enum {
1134 /* Note: These enums can be reduced as needed to save memory or stack space -
1135 they are pretty conservative. */
1136 MZ_ZIP_MAX_IO_BUF_SIZE = 8 * 1024,
1137 MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512,
1138 MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512
1139 };
1140
1141 typedef struct {
1142 /* Central directory file index. */
1143 mz_uint32 m_file_index;
1144
1145 /* Byte offset of this entry in the archive's central directory. Note we
1146 * currently only support up to UINT_MAX or less bytes in the central dir. */
1147 mz_uint64 m_central_dir_ofs;
1148
1149 /* These fields are copied directly from the zip's central dir. */
1150 mz_uint16 m_version_made_by;
1151 mz_uint16 m_version_needed;
1152 mz_uint16 m_bit_flag;
1153 mz_uint16 m_method;
1154
1155 #ifndef MINIZ_NO_TIME
1156 MZ_TIME_T m_time;
1157 #endif
1158
1159 /* CRC-32 of uncompressed data. */
1160 mz_uint32 m_crc32;
1161
1162 /* File's compressed size. */
1163 mz_uint64 m_comp_size;
1164
1165 /* File's uncompressed size. Note, I've seen some old archives where directory
1166 * entries had 512 bytes for their uncompressed sizes, but when you try to
1167 * unpack them you actually get 0 bytes. */
1168 mz_uint64 m_uncomp_size;
1169
1170 /* Zip internal and external file attributes. */
1171 mz_uint16 m_internal_attr;
1172 mz_uint32 m_external_attr;
1173
1174 /* Entry's local header file offset in bytes. */
1175 mz_uint64 m_local_header_ofs;
1176
1177 /* Size of comment in bytes. */
1178 mz_uint32 m_comment_size;
1179
1180 /* MZ_TRUE if the entry appears to be a directory. */
1181 mz_bool m_is_directory;
1182
1183 /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip
1184 * doesn't support) */
1185 mz_bool m_is_encrypted;
1186
1187 /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a
1188 * compression method we support. */
1189 mz_bool m_is_supported;
1190
1191 /* Filename. If string ends in '/' it's a subdirectory entry. */
1192 /* Guaranteed to be zero terminated, may be truncated to fit. */
1193 char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
1194
1195 /* Comment field. */
1196 /* Guaranteed to be zero terminated, may be truncated to fit. */
1197 char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
1198
1199 } mz_zip_archive_file_stat;
1200
1201 typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
1202 void *pBuf, size_t n);
1203 typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
1204 const void *pBuf, size_t n);
1205 typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque);
1206
1207 struct mz_zip_internal_state_tag;
1208 typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
1209
1210 typedef enum {
1211 MZ_ZIP_MODE_INVALID = 0,
1212 MZ_ZIP_MODE_READING = 1,
1213 MZ_ZIP_MODE_WRITING = 2,
1214 MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
1215 } mz_zip_mode;
1216
1217 typedef enum {
1218 MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
1219 MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
1220 MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
1221 MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800,
1222 MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG =
1223 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each
1224 file as its validated to ensure the func finds the file in the
1225 central dir (intended for testing) */
1226 MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY =
1227 0x2000, /* validate the local headers, but don't decompress the entire
1228 file and check the crc32 */
1229 MZ_ZIP_FLAG_WRITE_ZIP64 =
1230 0x4000, /* always use the zip64 file format, instead of the original zip
1231 file format with automatic switch to zip64. Use as flags
1232 parameter with mz_zip_writer_init*_v2 */
1233 MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000,
1234 MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000,
1235 /*After adding a compressed file, seek back
1236 to local file header and set the correct sizes*/
1237 MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000
1238 } mz_zip_flags;
1239
1240 typedef enum {
1241 MZ_ZIP_TYPE_INVALID = 0,
1242 MZ_ZIP_TYPE_USER,
1243 MZ_ZIP_TYPE_MEMORY,
1244 MZ_ZIP_TYPE_HEAP,
1245 MZ_ZIP_TYPE_FILE,
1246 MZ_ZIP_TYPE_CFILE,
1247 MZ_ZIP_TOTAL_TYPES
1248 } mz_zip_type;
1249
1250 /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or
1251 * modify this enum. */
1252 typedef enum {
1253 MZ_ZIP_NO_ERROR = 0,
1254 MZ_ZIP_UNDEFINED_ERROR,
1255 MZ_ZIP_TOO_MANY_FILES,
1256 MZ_ZIP_FILE_TOO_LARGE,
1257 MZ_ZIP_UNSUPPORTED_METHOD,
1258 MZ_ZIP_UNSUPPORTED_ENCRYPTION,
1259 MZ_ZIP_UNSUPPORTED_FEATURE,
1260 MZ_ZIP_FAILED_FINDING_CENTRAL_DIR,
1261 MZ_ZIP_NOT_AN_ARCHIVE,
1262 MZ_ZIP_INVALID_HEADER_OR_CORRUPTED,
1263 MZ_ZIP_UNSUPPORTED_MULTIDISK,
1264 MZ_ZIP_DECOMPRESSION_FAILED,
1265 MZ_ZIP_COMPRESSION_FAILED,
1266 MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE,
1267 MZ_ZIP_CRC_CHECK_FAILED,
1268 MZ_ZIP_UNSUPPORTED_CDIR_SIZE,
1269 MZ_ZIP_ALLOC_FAILED,
1270 MZ_ZIP_FILE_OPEN_FAILED,
1271 MZ_ZIP_FILE_CREATE_FAILED,
1272 MZ_ZIP_FILE_WRITE_FAILED,
1273 MZ_ZIP_FILE_READ_FAILED,
1274 MZ_ZIP_FILE_CLOSE_FAILED,
1275 MZ_ZIP_FILE_SEEK_FAILED,
1276 MZ_ZIP_FILE_STAT_FAILED,
1277 MZ_ZIP_INVALID_PARAMETER,
1278 MZ_ZIP_INVALID_FILENAME,
1279 MZ_ZIP_BUF_TOO_SMALL,
1280 MZ_ZIP_INTERNAL_ERROR,
1281 MZ_ZIP_FILE_NOT_FOUND,
1282 MZ_ZIP_ARCHIVE_TOO_LARGE,
1283 MZ_ZIP_VALIDATION_FAILED,
1284 MZ_ZIP_WRITE_CALLBACK_FAILED,
1285 MZ_ZIP_TOTAL_ERRORS
1286 } mz_zip_error;
1287
1288 typedef struct {
1289 mz_uint64 m_archive_size;
1290 mz_uint64 m_central_directory_file_ofs;
1291
1292 /* We only support up to UINT32_MAX files in zip64 mode. */
1293 mz_uint32 m_total_files;
1294 mz_zip_mode m_zip_mode;
1295 mz_zip_type m_zip_type;
1296 mz_zip_error m_last_error;
1297
1298 mz_uint64 m_file_offset_alignment;
1299
1300 mz_alloc_func m_pAlloc;
1301 mz_free_func m_pFree;
1302 mz_realloc_func m_pRealloc;
1303 void *m_pAlloc_opaque;
1304
1305 mz_file_read_func m_pRead;
1306 mz_file_write_func m_pWrite;
1307 mz_file_needs_keepalive m_pNeeds_keepalive;
1308 void *m_pIO_opaque;
1309
1310 mz_zip_internal_state *m_pState;
1311
1312 } mz_zip_archive;
1313
1314 typedef struct {
1315 mz_zip_archive *pZip;
1316 mz_uint flags;
1317
1318 int status;
1319 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
1320 mz_uint file_crc32;
1321 #endif
1322 mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining,
1323 out_buf_ofs, cur_file_ofs;
1324 mz_zip_archive_file_stat file_stat;
1325 void *pRead_buf;
1326 void *pWrite_buf;
1327
1328 size_t out_blk_remain;
1329
1330 tinfl_decompressor inflator;
1331
1332 } mz_zip_reader_extract_iter_state;
1333
1334 /* -------- ZIP reading */
1335
1336 /* Inits a ZIP archive reader. */
1337 /* These functions read and validate the archive's central directory. */
1338 MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
1339 mz_uint flags);
1340
1341 MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip,
1342 const void *pMem, size_t size,
1343 mz_uint flags);
1344
1345 #ifndef MINIZ_NO_STDIO
1346 /* Read a archive from a disk file. */
1347 /* file_start_ofs is the file offset where the archive actually begins, or 0. */
1348 /* actual_archive_size is the true total size of the archive, which may be
1349 * smaller than the file's actual size on disk. If zero the entire file is
1350 * treated as the archive. */
1351 MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip,
1352 const char *pFilename,
1353 mz_uint32 flags);
1354 MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip,
1355 const char *pFilename,
1356 mz_uint flags,
1357 mz_uint64 file_start_ofs,
1358 mz_uint64 archive_size);
1359 MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2_rpb(mz_zip_archive *pZip,
1360 const char *pFilename,
1361 mz_uint flags,
1362 mz_uint64 file_start_ofs,
1363 mz_uint64 archive_size);
1364
1365 /* Read an archive from an already opened FILE, beginning at the current file
1366 * position. */
1367 /* The archive is assumed to be archive_size bytes long. If archive_size is 0,
1368 * then the entire rest of the file is assumed to contain the archive. */
1369 /* The FILE will NOT be closed when mz_zip_reader_end() is called. */
1370 MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip,
1371 MZ_FILE *pFile,
1372 mz_uint64 archive_size,
1373 mz_uint flags);
1374 #endif
1375
1376 /* Ends archive reading, freeing all allocations, and closing the input archive
1377 * file if mz_zip_reader_init_file() was used. */
1378 MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
1379
1380 /* -------- ZIP reading or writing */
1381
1382 /* Clears a mz_zip_archive struct to all zeros. */
1383 /* Important: This must be done before passing the struct to any mz_zip
1384 * functions. */
1385 MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip);
1386
1387 MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip);
1388 MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip);
1389
1390 /* Returns the total number of files in the archive. */
1391 MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
1392
1393 MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip);
1394 MINIZ_EXPORT mz_uint64
1395 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip);
1396 MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip);
1397
1398 /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf.
1399 */
1400 MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip,
1401 mz_uint64 file_ofs, void *pBuf,
1402 size_t n);
1403
1404 /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct.
1405 * These functions retrieve/manipulate this field. */
1406 /* Note that the m_last_error functionality is not thread safe. */
1407 MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip,
1408 mz_zip_error err_num);
1409 MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip);
1410 MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip);
1411 MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip);
1412 MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err);
1413
1414 /* MZ_TRUE if the archive file entry is a directory entry. */
1415 MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
1416 mz_uint file_index);
1417
1418 /* MZ_TRUE if the file is encrypted/strong encrypted. */
1419 MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
1420 mz_uint file_index);
1421
1422 /* MZ_TRUE if the compression method is supported, and the file is not
1423 * encrypted, and the file is not a compressed patch file. */
1424 MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip,
1425 mz_uint file_index);
1426
1427 /* Retrieves the filename of an archive file entry. */
1428 /* Returns the number of bytes written to pFilename, or if filename_buf_size is
1429 * 0 this function returns the number of bytes needed to fully store the
1430 * filename. */
1431 MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip,
1432 mz_uint file_index,
1433 char *pFilename,
1434 mz_uint filename_buf_size);
1435
1436 /* Attempts to locates a file in the archive's central directory. */
1437 /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */
1438 /* Returns -1 if the file cannot be found. */
1439 MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip,
1440 const char *pName,
1441 const char *pComment, mz_uint flags);
1442 MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip,
1443 const char *pName,
1444 const char *pComment,
1445 mz_uint flags,
1446 mz_uint32 *file_index);
1447
1448 /* Returns detailed information about an archive file entry. */
1449 MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip,
1450 mz_uint file_index,
1451 mz_zip_archive_file_stat *pStat);
1452
1453 /* MZ_TRUE if the file is in zip64 format. */
1454 /* A file is considered zip64 if it contained a zip64 end of central directory
1455 * marker, or if it contained any zip64 extended file information fields in the
1456 * central directory. */
1457 MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip);
1458
1459 /* Returns the total central directory size in bytes. */
1460 /* The current max supported size is <= MZ_UINT32_MAX. */
1461 MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip);
1462
1463 /* Extracts a archive file to a memory buffer using no memory allocation. */
1464 /* There must be at least enough room on the stack to store the inflator's state
1465 * (~34KB or so). */
1466 MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(
1467 mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size,
1468 mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
1469 MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
1470 mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
1471 mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
1472
1473 /* Extracts a archive file to a memory buffer. */
1474 MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip,
1475 mz_uint file_index,
1476 void *pBuf, size_t buf_size,
1477 mz_uint flags);
1478 MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
1479 const char *pFilename,
1480 void *pBuf,
1481 size_t buf_size,
1482 mz_uint flags);
1483
1484 /* Extracts a archive file to a dynamically allocated heap buffer. */
1485 /* The memory will be allocated via the mz_zip_archive's alloc/realloc
1486 * functions. */
1487 /* Returns NULL and sets the last error on failure. */
1488 MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip,
1489 mz_uint file_index,
1490 size_t *pSize, mz_uint flags);
1491 MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
1492 const char *pFilename,
1493 size_t *pSize,
1494 mz_uint flags);
1495
1496 /* Extracts a archive file using a callback function to output the file's data.
1497 */
1498 MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(
1499 mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback,
1500 void *pOpaque, mz_uint flags);
1501 MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(
1502 mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback,
1503 void *pOpaque, mz_uint flags);
1504
1505 /* Extract a file iteratively */
1506 MINIZ_EXPORT mz_zip_reader_extract_iter_state *
1507 mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index,
1508 mz_uint flags);
1509 MINIZ_EXPORT mz_zip_reader_extract_iter_state *
1510 mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename,
1511 mz_uint flags);
1512 MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(
1513 mz_zip_reader_extract_iter_state *pState, void *pvBuf, size_t buf_size);
1514 MINIZ_EXPORT mz_bool
1515 mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState);
1516
1517 #ifndef MINIZ_NO_STDIO
1518 /* Extracts a archive file to a disk file and sets its last accessed and
1519 * modified times. */
1520 /* This function only extracts files, not archive directory records. */
1521 MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip,
1522 mz_uint file_index,
1523 const char *pDst_filename,
1524 mz_uint flags);
1525 MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(
1526 mz_zip_archive *pZip, const char *pArchive_filename,
1527 const char *pDst_filename, mz_uint flags);
1528
1529 /* Extracts a archive file starting at the current position in the destination
1530 * FILE stream. */
1531 MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip,
1532 mz_uint file_index,
1533 MZ_FILE *File,
1534 mz_uint flags);
1535 MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(
1536 mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile,
1537 mz_uint flags);
1538 #endif
1539
1540 #if 0
1541 /* TODO */
1542 typedef void *mz_zip_streaming_extract_state_ptr;
1543 mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
1544 uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
1545 uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
1546 mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs);
1547 size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size);
1548 mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
1549 #endif
1550
1551 /* This function compares the archive's local headers, the optional local zip64
1552 * extended information block, and the optional descriptor following the
1553 * compressed data vs. the data in the central directory. */
1554 /* It also validates that each file can be successfully uncompressed unless the
1555 * MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */
1556 MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip,
1557 mz_uint file_index, mz_uint flags);
1558
1559 /* Validates an entire archive by calling mz_zip_validate_file() on each file.
1560 */
1561 MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip,
1562 mz_uint flags);
1563
1564 /* Misc utils/helpers, valid for ZIP reading or writing */
1565 MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size,
1566 mz_uint flags,
1567 mz_zip_error *pErr);
1568 MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename,
1569 mz_uint flags,
1570 mz_zip_error *pErr);
1571
1572 /* Universal end function - calls either mz_zip_reader_end() or
1573 * mz_zip_writer_end(). */
1574 MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip);
1575
1576 /* -------- ZIP writing */
1577
1578 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
1579
1580 /* Inits a ZIP archive writer. */
1581 /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init
1582 * or mz_zip_writer_init_v2*/
1583 /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases
1584 * only by n*/
1585 MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip,
1586 mz_uint64 existing_size);
1587 MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip,
1588 mz_uint64 existing_size,
1589 mz_uint flags);
1590
1591 MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(
1592 mz_zip_archive *pZip, size_t size_to_reserve_at_beginning,
1593 size_t initial_allocation_size);
1594 MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(
1595 mz_zip_archive *pZip, size_t size_to_reserve_at_beginning,
1596 size_t initial_allocation_size, mz_uint flags);
1597
1598 #ifndef MINIZ_NO_STDIO
1599 MINIZ_EXPORT mz_bool
1600 mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
1601 mz_uint64 size_to_reserve_at_beginning);
1602 MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(
1603 mz_zip_archive *pZip, const char *pFilename,
1604 mz_uint64 size_to_reserve_at_beginning, mz_uint flags);
1605 MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip,
1606 MZ_FILE *pFile, mz_uint flags);
1607 #endif
1608
1609 /* Converts a ZIP archive reader object into a writer object, to allow efficient
1610 * in-place file appends to occur on an existing archive. */
1611 /* For archives opened using mz_zip_reader_init_file, pFilename must be the
1612 * archive's filename so it can be reopened for writing. If the file can't be
1613 * reopened, mz_zip_reader_end() will be called. */
1614 /* For archives opened using mz_zip_reader_init_mem, the memory block must be
1615 * growable using the realloc callback (which defaults to realloc unless you've
1616 * overridden it). */
1617 /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
1618 * user provided m_pWrite function cannot be NULL. */
1619 /* Note: In-place archive modification is not recommended unless you know what
1620 * you're doing, because if execution stops or something goes wrong before */
1621 /* the archive is finalized the file's central directory will be hosed. */
1622 MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
1623 const char *pFilename);
1624 MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip,
1625 const char *pFilename,
1626 mz_uint flags);
1627 MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2_noreopen(
1628 mz_zip_archive *pZip, const char *pFilename, mz_uint flags);
1629
1630 /* Adds the contents of a memory buffer to an archive. These functions record
1631 * the current local time into the archive. */
1632 /* To add a directory entry, call this method with an archive name ending in a
1633 * forwardslash with an empty buffer. */
1634 /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
1635 * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
1636 * just set to MZ_DEFAULT_COMPRESSION. */
1637 MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip,
1638 const char *pArchive_name,
1639 const void *pBuf, size_t buf_size,
1640 mz_uint level_and_flags);
1641
1642 /* Like mz_zip_writer_add_mem(), except you can specify a file comment field,
1643 * and optionally supply the function with already compressed data. */
1644 /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA
1645 * flag is specified. */
1646 MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(
1647 mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf,
1648 size_t buf_size, const void *pComment, mz_uint16 comment_size,
1649 mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
1650
1651 MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(
1652 mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf,
1653 size_t buf_size, const void *pComment, mz_uint16 comment_size,
1654 mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32,
1655 MZ_TIME_T *last_modified, const char *user_extra_data_local,
1656 mz_uint user_extra_data_local_len, const char *user_extra_data_central,
1657 mz_uint user_extra_data_central_len);
1658
1659 /* Adds the contents of a file to an archive. This function also records the
1660 * disk file's modified time into the archive. */
1661 /* File data is supplied via a read callback function. User
1662 * mz_zip_writer_add_(c)file to add a file directly.*/
1663 MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(
1664 mz_zip_archive *pZip, const char *pArchive_name,
1665 mz_file_read_func read_callback, void *callback_opaque, mz_uint64 max_size,
1666 const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size,
1667 mz_uint level_and_flags, mz_uint32 ext_attributes,
1668 const char *user_extra_data_local, mz_uint user_extra_data_local_len,
1669 const char *user_extra_data_central, mz_uint user_extra_data_central_len);
1670
1671 #ifndef MINIZ_NO_STDIO
1672 /* Adds the contents of a disk file to an archive. This function also records
1673 * the disk file's modified time into the archive. */
1674 /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
1675 * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
1676 * just set to MZ_DEFAULT_COMPRESSION. */
1677 MINIZ_EXPORT mz_bool mz_zip_writer_add_file(
1678 mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename,
1679 const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags,
1680 mz_uint32 ext_attributes);
1681
1682 /* Like mz_zip_writer_add_file(), except the file data is read from the
1683 * specified FILE stream. */
1684 MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(
1685 mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file,
1686 mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment,
1687 mz_uint16 comment_size, mz_uint level_and_flags, mz_uint32 ext_attributes,
1688 const char *user_extra_data_local, mz_uint user_extra_data_local_len,
1689 const char *user_extra_data_central, mz_uint user_extra_data_central_len);
1690 #endif
1691
1692 /* Adds a file to an archive by fully cloning the data from another archive. */
1693 /* This function fully clones the source file's compressed data (no
1694 * recompression), along with its full filename, extra data (it may add or
1695 * modify the zip64 local header extra data field), and the optional descriptor
1696 * following the compressed data. */
1697 MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(
1698 mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index);
1699
1700 /* Finalizes the archive by writing the central directory records followed by
1701 * the end of central directory record. */
1702 /* After an archive is finalized, the only valid call on the mz_zip_archive
1703 * struct is mz_zip_writer_end(). */
1704 /* An archive must be manually finalized by calling this function for it to be
1705 * valid. */
1706 MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
1707
1708 /* Finalizes a heap archive, returning a poiner to the heap block and its size.
1709 */
1710 /* The heap block will be allocated using the mz_zip_archive's alloc/realloc
1711 * callbacks. */
1712 MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip,
1713 void **ppBuf,
1714 size_t *pSize);
1715
1716 /* Ends archive writing, freeing all allocations, and closing the output file if
1717 * mz_zip_writer_init_file() was used. */
1718 /* Note for the archive to be valid, it *must* have been finalized before ending
1719 * (this function will not do it for you). */
1720 MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
1721
1722 /* -------- Misc. high-level helper functions: */
1723
1724 /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
1725 * appends a memory blob to a ZIP archive. */
1726 /* Note this is NOT a fully safe operation. If it crashes or dies in some way
1727 * your archive can be left in a screwed up state (without a central directory).
1728 */
1729 /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
1730 * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
1731 * just set to MZ_DEFAULT_COMPRESSION. */
1732 /* TODO: Perhaps add an option to leave the existing central dir in place in
1733 * case the add dies? We could then truncate the file (so the old central dir
1734 * would be at the end) if something goes wrong. */
1735 MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(
1736 const char *pZip_filename, const char *pArchive_name, const void *pBuf,
1737 size_t buf_size, const void *pComment, mz_uint16 comment_size,
1738 mz_uint level_and_flags);
1739 MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(
1740 const char *pZip_filename, const char *pArchive_name, const void *pBuf,
1741 size_t buf_size, const void *pComment, mz_uint16 comment_size,
1742 mz_uint level_and_flags, mz_zip_error *pErr);
1743
1744 /* Reads a single file from an archive into a heap block. */
1745 /* If pComment is not NULL, only the file with the specified comment will be
1746 * extracted. */
1747 /* Returns NULL on failure. */
1748 MINIZ_EXPORT void *
1749 mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
1750 const char *pArchive_name, size_t *pSize,
1751 mz_uint flags);
1752 MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(
1753 const char *pZip_filename, const char *pArchive_name, const char *pComment,
1754 size_t *pSize, mz_uint flags, mz_zip_error *pErr);
1755
1756 #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */
1757
1758 #ifdef __cplusplus
1759 }
1760 #endif
1761
1762 #endif /* MINIZ_NO_ARCHIVE_APIS */
1763 /**************************************************************************
1764 *
1765 * Copyright 2013-2014 RAD Game Tools and Valve Software
1766 * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
1767 * All Rights Reserved.
1768 *
1769 * Permission is hereby granted, free of charge, to any person obtaining a copy
1770 * of this software and associated documentation files (the "Software"), to deal
1771 * in the Software without restriction, including without limitation the rights
1772 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1773 * copies of the Software, and to permit persons to whom the Software is
1774 * furnished to do so, subject to the following conditions:
1775 *
1776 * The above copyright notice and this permission notice shall be included in
1777 * all copies or substantial portions of the Software.
1778 *
1779 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1780 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1781 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1782 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1783 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1784 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1785 * THE SOFTWARE.
1786 *
1787 **************************************************************************/
1788
1789 typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
1790 typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
1791 typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
1792
1793 #ifdef __cplusplus
1794 extern "C" {
1795 #endif
1796
1797 /* ------------------- zlib-style API's */
1798
1799 mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
1800 mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
1801 size_t block_len = buf_len % 5552;
1802 if (!ptr)
1803 return MZ_ADLER32_INIT;
1804 while (buf_len) {
1805 for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
1806 s1 += ptr[0], s2 += s1;
1807 s1 += ptr[1], s2 += s1;
1808 s1 += ptr[2], s2 += s1;
1809 s1 += ptr[3], s2 += s1;
1810 s1 += ptr[4], s2 += s1;
1811 s1 += ptr[5], s2 += s1;
1812 s1 += ptr[6], s2 += s1;
1813 s1 += ptr[7], s2 += s1;
1814 }
1815 for (; i < block_len; ++i)
1816 s1 += *ptr++, s2 += s1;
1817 s1 %= 65521U, s2 %= 65521U;
1818 buf_len -= block_len;
1819 block_len = 5552;
1820 }
1821 return (s2 << 16) + s1;
1822 }
1823
1824 /* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
1825 * implementation that balances processor cache usage against speed":
1826 * http://www.geocities.com/malbrain/ */
1827 #if 0
1828 mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
1829 {
1830 static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
1831 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
1832 mz_uint32 crcu32 = (mz_uint32)crc;
1833 if (!ptr)
1834 return MZ_CRC32_INIT;
1835 crcu32 = ~crcu32;
1836 while (buf_len--)
1837 {
1838 mz_uint8 b = *ptr++;
1839 crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
1840 crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
1841 }
1842 return ~crcu32;
1843 }
1844 #elif defined(USE_EXTERNAL_MZCRC)
1845 /* If USE_EXTERNAL_CRC is defined, an external module will export the
1846 * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version.
1847 * Depending on the impl, it may be necessary to ~ the input/output crc values.
1848 */
1849 mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len);
1850 #else
1851 /* Faster, but larger CPU cache footprint.
1852 */
1853 mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
1854 static const mz_uint32 s_crc_table[256] = {
1855 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
1856 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
1857 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
1858 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
1859 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
1860 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
1861 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
1862 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
1863 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
1864 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
1865 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
1866 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
1867 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
1868 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
1869 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
1870 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
1871 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
1872 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
1873 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
1874 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
1875 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
1876 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
1877 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
1878 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
1879 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
1880 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
1881 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
1882 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
1883 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
1884 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
1885 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
1886 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
1887 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
1888 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
1889 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
1890 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
1891 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
1892 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
1893 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
1894 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
1895 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
1896 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
1897 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D};
1898
1899 mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF;
1900 const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr;
1901
1902 while (buf_len >= 4) {
1903 crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF];
1904 crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF];
1905 crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF];
1906 crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF];
1907 pByte_buf += 4;
1908 buf_len -= 4;
1909 }
1910
1911 while (buf_len) {
1912 crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF];
1913 ++pByte_buf;
1914 --buf_len;
1915 }
1916
1917 return ~crc32;
1918 }
1919 #endif
1920
1921 void mz_free(void *p) { MZ_FREE(p); }
1922
1923 MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items,
1924 size_t size) {
1925 (void)opaque, (void)items, (void)size;
1926 return MZ_MALLOC(items * size);
1927 }
1928 MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) {
1929 (void)opaque, (void)address;
1930 MZ_FREE(address);
1931 }
1932 MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address,
1933 size_t items, size_t size) {
1934 (void)opaque, (void)address, (void)items, (void)size;
1935 return MZ_REALLOC(address, items * size);
1936 }
1937
1938 const char *mz_version(void) { return MZ_VERSION; }
1939
1940 #ifndef MINIZ_NO_ZLIB_APIS
1941
1942 int mz_deflateInit(mz_streamp pStream, int level) {
1943 return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
1944 MZ_DEFAULT_STRATEGY);
1945 }
1946
1947 int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
1948 int mem_level, int strategy) {
1949 tdefl_compressor *pComp;
1950 mz_uint comp_flags =
1951 TDEFL_COMPUTE_ADLER32 |
1952 tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
1953
1954 if (!pStream)
1955 return MZ_STREAM_ERROR;
1956 if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
1957 ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
1958 (-window_bits != MZ_DEFAULT_WINDOW_BITS)))
1959 return MZ_PARAM_ERROR;
1960
1961 pStream->data_type = 0;
1962 pStream->adler = MZ_ADLER32_INIT;
1963 pStream->msg = NULL;
1964 pStream->reserved = 0;
1965 pStream->total_in = 0;
1966 pStream->total_out = 0;
1967 if (!pStream->zalloc)
1968 pStream->zalloc = miniz_def_alloc_func;
1969 if (!pStream->zfree)
1970 pStream->zfree = miniz_def_free_func;
1971
1972 pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
1973 sizeof(tdefl_compressor));
1974 if (!pComp)
1975 return MZ_MEM_ERROR;
1976
1977 pStream->state = (struct mz_internal_state *)pComp;
1978
1979 if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
1980 mz_deflateEnd(pStream);
1981 return MZ_PARAM_ERROR;
1982 }
1983
1984 return MZ_OK;
1985 }
1986
1987 int mz_deflateReset(mz_streamp pStream) {
1988 if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
1989 (!pStream->zfree))
1990 return MZ_STREAM_ERROR;
1991 pStream->total_in = pStream->total_out = 0;
1992 tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
1993 ((tdefl_compressor *)pStream->state)->m_flags);
1994 return MZ_OK;
1995 }
1996
1997 int mz_deflate(mz_streamp pStream, int flush) {
1998 size_t in_bytes, out_bytes;
1999 mz_ulong orig_total_in, orig_total_out;
2000 int mz_status = MZ_OK;
2001
2002 if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
2003 (!pStream->next_out))
2004 return MZ_STREAM_ERROR;
2005 if (!pStream->avail_out)
2006 return MZ_BUF_ERROR;
2007
2008 if (flush == MZ_PARTIAL_FLUSH)
2009 flush = MZ_SYNC_FLUSH;
2010
2011 if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
2012 TDEFL_STATUS_DONE)
2013 return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
2014
2015 orig_total_in = pStream->total_in;
2016 orig_total_out = pStream->total_out;
2017 for (;;) {
2018 tdefl_status defl_status;
2019 in_bytes = pStream->avail_in;
2020 out_bytes = pStream->avail_out;
2021
2022 defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
2023 pStream->next_in, &in_bytes, pStream->next_out,
2024 &out_bytes, (tdefl_flush)flush);
2025 pStream->next_in += (mz_uint)in_bytes;
2026 pStream->avail_in -= (mz_uint)in_bytes;
2027 pStream->total_in += (mz_uint)in_bytes;
2028 pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
2029
2030 pStream->next_out += (mz_uint)out_bytes;
2031 pStream->avail_out -= (mz_uint)out_bytes;
2032 pStream->total_out += (mz_uint)out_bytes;
2033
2034 if (defl_status < 0) {
2035 mz_status = MZ_STREAM_ERROR;
2036 break;
2037 } else if (defl_status == TDEFL_STATUS_DONE) {
2038 mz_status = MZ_STREAM_END;
2039 break;
2040 } else if (!pStream->avail_out)
2041 break;
2042 else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
2043 if ((flush) || (pStream->total_in != orig_total_in) ||
2044 (pStream->total_out != orig_total_out))
2045 break;
2046 return MZ_BUF_ERROR; /* Can't make forward progress without some input.
2047 */
2048 }
2049 }
2050 return mz_status;
2051 }
2052
2053 int mz_deflateEnd(mz_streamp pStream) {
2054 if (!pStream)
2055 return MZ_STREAM_ERROR;
2056 if (pStream->state) {
2057 pStream->zfree(pStream->opaque, pStream->state);
2058 pStream->state = NULL;
2059 }
2060 return MZ_OK;
2061 }
2062
2063 mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
2064 (void)pStream;
2065 /* This is really over conservative. (And lame, but it's actually pretty
2066 * tricky to compute a true upper bound given the way tdefl's blocking works.)
2067 */
2068 return MZ_MAX(128 + (source_len * 110) / 100,
2069 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
2070 }
2071
2072 int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
2073 const unsigned char *pSource, mz_ulong source_len, int level) {
2074 int status;
2075 mz_stream stream;
2076 memset(&stream, 0, sizeof(stream));
2077
2078 /* In case mz_ulong is 64-bits (argh I hate longs). */
2079 if ((source_len | *pDest_len) > 0xFFFFFFFFU)
2080 return MZ_PARAM_ERROR;
2081
2082 stream.next_in = pSource;
2083 stream.avail_in = (mz_uint32)source_len;
2084 stream.next_out = pDest;
2085 stream.avail_out = (mz_uint32)*pDest_len;
2086
2087 status = mz_deflateInit(&stream, level);
2088 if (status != MZ_OK)
2089 return status;
2090
2091 status = mz_deflate(&stream, MZ_FINISH);
2092 if (status != MZ_STREAM_END) {
2093 mz_deflateEnd(&stream);
2094 return (status == MZ_OK) ? MZ_BUF_ERROR : status;
2095 }
2096
2097 *pDest_len = stream.total_out;
2098 return mz_deflateEnd(&stream);
2099 }
2100
2101 int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
2102 const unsigned char *pSource, mz_ulong source_len) {
2103 return mz_compress2(pDest, pDest_len, pSource, source_len,
2104 MZ_DEFAULT_COMPRESSION);
2105 }
2106
2107 mz_ulong mz_compressBound(mz_ulong source_len) {
2108 return mz_deflateBound(NULL, source_len);
2109 }
2110
2111 typedef struct {
2112 tinfl_decompressor m_decomp;
2113 mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
2114 int m_window_bits;
2115 mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
2116 tinfl_status m_last_status;
2117 } inflate_state;
2118
2119 int mz_inflateInit2(mz_streamp pStream, int window_bits) {
2120 inflate_state *pDecomp;
2121 if (!pStream)
2122 return MZ_STREAM_ERROR;
2123 if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
2124 (-window_bits != MZ_DEFAULT_WINDOW_BITS))
2125 return MZ_PARAM_ERROR;
2126
2127 pStream->data_type = 0;
2128 pStream->adler = 0;
2129 pStream->msg = NULL;
2130 pStream->total_in = 0;
2131 pStream->total_out = 0;
2132 pStream->reserved = 0;
2133 if (!pStream->zalloc)
2134 pStream->zalloc = miniz_def_alloc_func;
2135 if (!pStream->zfree)
2136 pStream->zfree = miniz_def_free_func;
2137
2138 pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
2139 sizeof(inflate_state));
2140 if (!pDecomp)
2141 return MZ_MEM_ERROR;
2142
2143 pStream->state = (struct mz_internal_state *)pDecomp;
2144
2145 tinfl_init(&pDecomp->m_decomp);
2146 pDecomp->m_dict_ofs = 0;
2147 pDecomp->m_dict_avail = 0;
2148 pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
2149 pDecomp->m_first_call = 1;
2150 pDecomp->m_has_flushed = 0;
2151 pDecomp->m_window_bits = window_bits;
2152
2153 return MZ_OK;
2154 }
2155
2156 int mz_inflateInit(mz_streamp pStream) {
2157 return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
2158 }
2159
2160 int mz_inflateReset(mz_streamp pStream) {
2161 inflate_state *pDecomp;
2162 if (!pStream)
2163 return MZ_STREAM_ERROR;
2164
2165 pStream->data_type = 0;
2166 pStream->adler = 0;
2167 pStream->msg = NULL;
2168 pStream->total_in = 0;
2169 pStream->total_out = 0;
2170 pStream->reserved = 0;
2171
2172 pDecomp = (inflate_state *)pStream->state;
2173
2174 tinfl_init(&pDecomp->m_decomp);
2175 pDecomp->m_dict_ofs = 0;
2176 pDecomp->m_dict_avail = 0;
2177 pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
2178 pDecomp->m_first_call = 1;
2179 pDecomp->m_has_flushed = 0;
2180 /* pDecomp->m_window_bits = window_bits */;
2181
2182 return MZ_OK;
2183 }
2184
2185 int mz_inflate(mz_streamp pStream, int flush) {
2186 inflate_state *pState;
2187 mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
2188 size_t in_bytes, out_bytes, orig_avail_in;
2189 tinfl_status status;
2190
2191 if ((!pStream) || (!pStream->state))
2192 return MZ_STREAM_ERROR;
2193 if (flush == MZ_PARTIAL_FLUSH)
2194 flush = MZ_SYNC_FLUSH;
2195 if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
2196 return MZ_STREAM_ERROR;
2197
2198 pState = (inflate_state *)pStream->state;
2199 if (pState->m_window_bits > 0)
2200 decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
2201 orig_avail_in = pStream->avail_in;
2202
2203 first_call = pState->m_first_call;
2204 pState->m_first_call = 0;
2205 if (pState->m_last_status < 0)
2206 return MZ_DATA_ERROR;
2207
2208 if (pState->m_has_flushed && (flush != MZ_FINISH))
2209 return MZ_STREAM_ERROR;
2210 pState->m_has_flushed |= (flush == MZ_FINISH);
2211
2212 if ((flush == MZ_FINISH) && (first_call)) {
2213 /* MZ_FINISH on the first call implies that the input and output buffers are
2214 * large enough to hold the entire compressed/decompressed file. */
2215 decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
2216 in_bytes = pStream->avail_in;
2217 out_bytes = pStream->avail_out;
2218 status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
2219 pStream->next_out, pStream->next_out, &out_bytes,
2220 decomp_flags);
2221 pState->m_last_status = status;
2222 pStream->next_in += (mz_uint)in_bytes;
2223 pStream->avail_in -= (mz_uint)in_bytes;
2224 pStream->total_in += (mz_uint)in_bytes;
2225 pStream->adler = tinfl_get_adler32(&pState->m_decomp);
2226 pStream->next_out += (mz_uint)out_bytes;
2227 pStream->avail_out -= (mz_uint)out_bytes;
2228 pStream->total_out += (mz_uint)out_bytes;
2229
2230 if (status < 0)
2231 return MZ_DATA_ERROR;
2232 else if (status != TINFL_STATUS_DONE) {
2233 pState->m_last_status = TINFL_STATUS_FAILED;
2234 return MZ_BUF_ERROR;
2235 }
2236 return MZ_STREAM_END;
2237 }
2238 /* flush != MZ_FINISH then we must assume there's more input. */
2239 if (flush != MZ_FINISH)
2240 decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
2241
2242 if (pState->m_dict_avail) {
2243 n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
2244 memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
2245 pStream->next_out += n;
2246 pStream->avail_out -= n;
2247 pStream->total_out += n;
2248 pState->m_dict_avail -= n;
2249 pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
2250 return ((pState->m_last_status == TINFL_STATUS_DONE) &&
2251 (!pState->m_dict_avail))
2252 ? MZ_STREAM_END
2253 : MZ_OK;
2254 }
2255
2256 for (;;) {
2257 in_bytes = pStream->avail_in;
2258 out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
2259
2260 status = tinfl_decompress(
2261 &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
2262 pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
2263 pState->m_last_status = status;
2264
2265 pStream->next_in += (mz_uint)in_bytes;
2266 pStream->avail_in -= (mz_uint)in_bytes;
2267 pStream->total_in += (mz_uint)in_bytes;
2268 pStream->adler = tinfl_get_adler32(&pState->m_decomp);
2269
2270 pState->m_dict_avail = (mz_uint)out_bytes;
2271
2272 n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
2273 memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
2274 pStream->next_out += n;
2275 pStream->avail_out -= n;
2276 pStream->total_out += n;
2277 pState->m_dict_avail -= n;
2278 pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
2279
2280 if (status < 0)
2281 return MZ_DATA_ERROR; /* Stream is corrupted (there could be some
2282 uncompressed data left in the output dictionary -
2283 oh well). */
2284 else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
2285 return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress
2286 without supplying more input or by setting flush
2287 to MZ_FINISH. */
2288 else if (flush == MZ_FINISH) {
2289 /* The output buffer MUST be large to hold the remaining uncompressed data
2290 * when flush==MZ_FINISH. */
2291 if (status == TINFL_STATUS_DONE)
2292 return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
2293 /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
2294 * at least 1 more byte on the way. If there's no more room left in the
2295 * output buffer then something is wrong. */
2296 else if (!pStream->avail_out)
2297 return MZ_BUF_ERROR;
2298 } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
2299 (!pStream->avail_out) || (pState->m_dict_avail))
2300 break;
2301 }
2302
2303 return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
2304 ? MZ_STREAM_END
2305 : MZ_OK;
2306 }
2307
2308 int mz_inflateEnd(mz_streamp pStream) {
2309 if (!pStream)
2310 return MZ_STREAM_ERROR;
2311 if (pStream->state) {
2312 pStream->zfree(pStream->opaque, pStream->state);
2313 pStream->state = NULL;
2314 }
2315 return MZ_OK;
2316 }
2317 int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len,
2318 const unsigned char *pSource, mz_ulong *pSource_len) {
2319 mz_stream stream;
2320 int status;
2321 memset(&stream, 0, sizeof(stream));
2322
2323 /* In case mz_ulong is 64-bits (argh I hate longs). */
2324 if ((*pSource_len | *pDest_len) > 0xFFFFFFFFU)
2325 return MZ_PARAM_ERROR;
2326
2327 stream.next_in = pSource;
2328 stream.avail_in = (mz_uint32)*pSource_len;
2329 stream.next_out = pDest;
2330 stream.avail_out = (mz_uint32)*pDest_len;
2331
2332 status = mz_inflateInit(&stream);
2333 if (status != MZ_OK)
2334 return status;
2335
2336 status = mz_inflate(&stream, MZ_FINISH);
2337 *pSource_len = *pSource_len - stream.avail_in;
2338 if (status != MZ_STREAM_END) {
2339 mz_inflateEnd(&stream);
2340 return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
2341 : status;
2342 }
2343 *pDest_len = stream.total_out;
2344
2345 return mz_inflateEnd(&stream);
2346 }
2347
2348 int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
2349 const unsigned char *pSource, mz_ulong source_len) {
2350 return mz_uncompress2(pDest, pDest_len, pSource, &source_len);
2351 }
2352
2353 const char *mz_error(int err) {
2354 static struct {
2355 int m_err;
2356 const char *m_pDesc;
2357 } s_error_descs[] = {{MZ_OK, ""},
2358 {MZ_STREAM_END, "stream end"},
2359 {MZ_NEED_DICT, "need dictionary"},
2360 {MZ_ERRNO, "file error"},
2361 {MZ_STREAM_ERROR, "stream error"},
2362 {MZ_DATA_ERROR, "data error"},
2363 {MZ_MEM_ERROR, "out of memory"},
2364 {MZ_BUF_ERROR, "buf error"},
2365 {MZ_VERSION_ERROR, "version error"},
2366 {MZ_PARAM_ERROR, "parameter error"}};
2367 mz_uint i;
2368 for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
2369 if (s_error_descs[i].m_err == err)
2370 return s_error_descs[i].m_pDesc;
2371 return NULL;
2372 }
2373
2374 #endif /*MINIZ_NO_ZLIB_APIS */
2375
2376 #ifdef __cplusplus
2377 }
2378 #endif
2379
2380 /*
2381 This is free and unencumbered software released into the public domain.
2382
2383 Anyone is free to copy, modify, publish, use, compile, sell, or
2384 distribute this software, either in source code form or as a compiled
2385 binary, for any purpose, commercial or non-commercial, and by any
2386 means.
2387
2388 In jurisdictions that recognize copyright laws, the author or authors
2389 of this software dedicate any and all copyright interest in the
2390 software to the public domain. We make this dedication for the benefit
2391 of the public at large and to the detriment of our heirs and
2392 successors. We intend this dedication to be an overt act of
2393 relinquishment in perpetuity of all present and future rights to this
2394 software under copyright law.
2395
2396 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2397 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2398 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
2399 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
2400 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
2401 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2402 OTHER DEALINGS IN THE SOFTWARE.
2403
2404 For more information, please refer to <http://unlicense.org/>
2405 */
2406 /**************************************************************************
2407 *
2408 * Copyright 2013-2014 RAD Game Tools and Valve Software
2409 * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
2410 * All Rights Reserved.
2411 *
2412 * Permission is hereby granted, free of charge, to any person obtaining a copy
2413 * of this software and associated documentation files (the "Software"), to deal
2414 * in the Software without restriction, including without limitation the rights
2415 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2416 * copies of the Software, and to permit persons to whom the Software is
2417 * furnished to do so, subject to the following conditions:
2418 *
2419 * The above copyright notice and this permission notice shall be included in
2420 * all copies or substantial portions of the Software.
2421 *
2422 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2423 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2424 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2425 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2426 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2427 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2428 * THE SOFTWARE.
2429 *
2430 **************************************************************************/
2431
2432 #ifdef __cplusplus
2433 extern "C" {
2434 #endif
2435
2436 /* ------------------- Low-level Compression (independent from all decompression
2437 * API's) */
2438
2439 /* Purposely making these tables static for faster init and thread safety. */
2440 static const mz_uint16 s_tdefl_len_sym[256] = {
2441 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
2442 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
2443 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
2444 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
2445 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
2446 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
2447 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
2448 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
2449 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
2450 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
2451 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
2452 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
2453 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
2454 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
2455 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
2456 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
2457 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
2458 285};
2459
2460 static const mz_uint8 s_tdefl_len_extra[256] = {
2461 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2462 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2463 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
2464 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
2465 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
2466 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2467 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2468 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2469 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2470 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2471 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
2472
2473 static const mz_uint8 s_tdefl_small_dist_sym[512] = {
2474 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
2475 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
2476 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
2477 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
2478 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
2479 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
2480 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
2481 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
2482 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
2483 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
2484 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
2485 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
2486 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
2487 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2488 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2489 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2490 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2491 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2492 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2493 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2494 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
2495 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
2496 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
2497 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
2498 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
2499 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
2500 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
2501
2502 static const mz_uint8 s_tdefl_small_dist_extra[512] = {
2503 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2504 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,
2505 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
2506 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,
2507 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,
2508 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
2509 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,
2510 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,
2511 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,
2512 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,
2513 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,
2514 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,
2515 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,
2516 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,
2517 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,
2518 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,
2519 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,
2520 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,
2521 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,
2522 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,
2523 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
2524
2525 static const mz_uint8 s_tdefl_large_dist_sym[128] = {
2526 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
2527 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
2528 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
2529 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
2530 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
2531 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
2532 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
2533
2534 static const mz_uint8 s_tdefl_large_dist_extra[128] = {
2535 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
2536 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
2537 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
2538 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
2539 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
2540 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
2541 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
2542
2543 /* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
2544 * values. */
2545 typedef struct {
2546 mz_uint16 m_key, m_sym_index;
2547 } tdefl_sym_freq;
2548 static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
2549 tdefl_sym_freq *pSyms0,
2550 tdefl_sym_freq *pSyms1) {
2551 mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
2552 tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
2553 MZ_CLEAR_OBJ(hist);
2554 for (i = 0; i < num_syms; i++) {
2555 mz_uint freq = pSyms0[i].m_key;
2556 hist[freq & 0xFF]++;
2557 hist[256 + ((freq >> 8) & 0xFF)]++;
2558 }
2559 while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
2560 total_passes--;
2561 for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
2562 const mz_uint32 *pHist = &hist[pass << 8];
2563 mz_uint offsets[256], cur_ofs = 0;
2564 for (i = 0; i < 256; i++) {
2565 offsets[i] = cur_ofs;
2566 cur_ofs += pHist[i];
2567 }
2568 for (i = 0; i < num_syms; i++)
2569 pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
2570 pCur_syms[i];
2571 {
2572 tdefl_sym_freq *t = pCur_syms;
2573 pCur_syms = pNew_syms;
2574 pNew_syms = t;
2575 }
2576 }
2577 return pCur_syms;
2578 }
2579
2580 /* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
2581 * [email protected], Jyrki Katajainen, [email protected], November 1996. */
2582 static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
2583 int root, leaf, next, avbl, used, dpth;
2584 if (n == 0)
2585 return;
2586 else if (n == 1) {
2587 A[0].m_key = 1;
2588 return;
2589 }
2590 A[0].m_key += A[1].m_key;
2591 root = 0;
2592 leaf = 2;
2593 for (next = 1; next < n - 1; next++) {
2594 if (leaf >= n || A[root].m_key < A[leaf].m_key) {
2595 A[next].m_key = A[root].m_key;
2596 A[root++].m_key = (mz_uint16)next;
2597 } else
2598 A[next].m_key = A[leaf++].m_key;
2599 if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
2600 A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
2601 A[root++].m_key = (mz_uint16)next;
2602 } else
2603 A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
2604 }
2605 A[n - 2].m_key = 0;
2606 for (next = n - 3; next >= 0; next--)
2607 A[next].m_key = A[A[next].m_key].m_key + 1;
2608 avbl = 1;
2609 used = dpth = 0;
2610 root = n - 2;
2611 next = n - 1;
2612 while (avbl > 0) {
2613 while (root >= 0 && (int)A[root].m_key == dpth) {
2614 used++;
2615 root--;
2616 }
2617 while (avbl > used) {
2618 A[next--].m_key = (mz_uint16)(dpth);
2619 avbl--;
2620 }
2621 avbl = 2 * used;
2622 dpth++;
2623 used = 0;
2624 }
2625 }
2626
2627 /* Limits canonical Huffman code table's max code size. */
2628 enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
2629 static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
2630 int code_list_len,
2631 int max_code_size) {
2632 int i;
2633 mz_uint32 total = 0;
2634 if (code_list_len <= 1)
2635 return;
2636 for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
2637 pNum_codes[max_code_size] += pNum_codes[i];
2638 for (i = max_code_size; i > 0; i--)
2639 total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
2640 while (total != (1UL << max_code_size)) {
2641 pNum_codes[max_code_size]--;
2642 for (i = max_code_size - 1; i > 0; i--)
2643 if (pNum_codes[i]) {
2644 pNum_codes[i]--;
2645 pNum_codes[i + 1] += 2;
2646 break;
2647 }
2648 total--;
2649 }
2650 }
2651
2652 static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
2653 int table_len, int code_size_limit,
2654 int static_table) {
2655 int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
2656 mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
2657 MZ_CLEAR_OBJ(num_codes);
2658 if (static_table) {
2659 for (i = 0; i < table_len; i++)
2660 num_codes[d->m_huff_code_sizes[table_num][i]]++;
2661 } else {
2662 tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
2663 *pSyms;
2664 int num_used_syms = 0;
2665 const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
2666 for (i = 0; i < table_len; i++)
2667 if (pSym_count[i]) {
2668 syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
2669 syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
2670 }
2671
2672 pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
2673 tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
2674
2675 for (i = 0; i < num_used_syms; i++)
2676 num_codes[pSyms[i].m_key]++;
2677
2678 tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
2679 code_size_limit);
2680
2681 MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
2682 MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
2683 for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
2684 for (l = num_codes[i]; l > 0; l--)
2685 d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
2686 }
2687
2688 next_code[1] = 0;
2689 for (j = 0, i = 2; i <= code_size_limit; i++)
2690 next_code[i] = j = ((j + num_codes[i - 1]) << 1);
2691
2692 for (i = 0; i < table_len; i++) {
2693 mz_uint rev_code = 0, code, code_size;
2694 if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0)
2695 continue;
2696 code = next_code[code_size]++;
2697 for (l = code_size; l > 0; l--, code >>= 1)
2698 rev_code = (rev_code << 1) | (code & 1);
2699 d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
2700 }
2701 }
2702
2703 #define TDEFL_PUT_BITS(b, l) \
2704 do { \
2705 mz_uint bits = b; \
2706 mz_uint len = l; \
2707 MZ_ASSERT(bits <= ((1U << len) - 1U)); \
2708 d->m_bit_buffer |= (bits << d->m_bits_in); \
2709 d->m_bits_in += len; \
2710 while (d->m_bits_in >= 8) { \
2711 if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
2712 *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
2713 d->m_bit_buffer >>= 8; \
2714 d->m_bits_in -= 8; \
2715 } \
2716 } \
2717 MZ_MACRO_END
2718
2719 #define TDEFL_RLE_PREV_CODE_SIZE() \
2720 { \
2721 if (rle_repeat_count) { \
2722 if (rle_repeat_count < 3) { \
2723 d->m_huff_count[2][prev_code_size] = \
2724 (mz_uint16)(d->m_huff_count[2][prev_code_size] + \
2725 rle_repeat_count); \
2726 while (rle_repeat_count--) \
2727 packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
2728 } else { \
2729 d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
2730 packed_code_sizes[num_packed_code_sizes++] = 16; \
2731 packed_code_sizes[num_packed_code_sizes++] = \
2732 (mz_uint8)(rle_repeat_count - 3); \
2733 } \
2734 rle_repeat_count = 0; \
2735 } \
2736 }
2737
2738 #define TDEFL_RLE_ZERO_CODE_SIZE() \
2739 { \
2740 if (rle_z_count) { \
2741 if (rle_z_count < 3) { \
2742 d->m_huff_count[2][0] = \
2743 (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
2744 while (rle_z_count--) \
2745 packed_code_sizes[num_packed_code_sizes++] = 0; \
2746 } else if (rle_z_count <= 10) { \
2747 d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
2748 packed_code_sizes[num_packed_code_sizes++] = 17; \
2749 packed_code_sizes[num_packed_code_sizes++] = \
2750 (mz_uint8)(rle_z_count - 3); \
2751 } else { \
2752 d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
2753 packed_code_sizes[num_packed_code_sizes++] = 18; \
2754 packed_code_sizes[num_packed_code_sizes++] = \
2755 (mz_uint8)(rle_z_count - 11); \
2756 } \
2757 rle_z_count = 0; \
2758 } \
2759 }
2760
2761 static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
2762 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
2763
2764 static void tdefl_start_dynamic_block(tdefl_compressor *d) {
2765 int num_lit_codes, num_dist_codes, num_bit_lengths;
2766 mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
2767 rle_repeat_count, packed_code_sizes_index;
2768 mz_uint8
2769 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
2770 packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
2771 prev_code_size = 0xFF;
2772
2773 d->m_huff_count[0][256] = 1;
2774
2775 tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
2776 tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
2777
2778 for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
2779 if (d->m_huff_code_sizes[0][num_lit_codes - 1])
2780 break;
2781 for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
2782 if (d->m_huff_code_sizes[1][num_dist_codes - 1])
2783 break;
2784
2785 memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
2786 memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
2787 num_dist_codes);
2788 total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
2789 num_packed_code_sizes = 0;
2790 rle_z_count = 0;
2791 rle_repeat_count = 0;
2792
2793 memset(&d->m_huff_count[2][0], 0,
2794 sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
2795 for (i = 0; i < total_code_sizes_to_pack; i++) {
2796 mz_uint8 code_size = code_sizes_to_pack[i];
2797 if (!code_size) {
2798 TDEFL_RLE_PREV_CODE_SIZE();
2799 if (++rle_z_count == 138) {
2800 TDEFL_RLE_ZERO_CODE_SIZE();
2801 }
2802 } else {
2803 TDEFL_RLE_ZERO_CODE_SIZE();
2804 if (code_size != prev_code_size) {
2805 TDEFL_RLE_PREV_CODE_SIZE();
2806 d->m_huff_count[2][code_size] =
2807 (mz_uint16)(d->m_huff_count[2][code_size] + 1);
2808 packed_code_sizes[num_packed_code_sizes++] = code_size;
2809 } else if (++rle_repeat_count == 6) {
2810 TDEFL_RLE_PREV_CODE_SIZE();
2811 }
2812 }
2813 prev_code_size = code_size;
2814 }
2815 if (rle_repeat_count) {
2816 TDEFL_RLE_PREV_CODE_SIZE();
2817 } else {
2818 TDEFL_RLE_ZERO_CODE_SIZE();
2819 }
2820
2821 tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
2822
2823 TDEFL_PUT_BITS(2, 2);
2824
2825 TDEFL_PUT_BITS(num_lit_codes - 257, 5);
2826 TDEFL_PUT_BITS(num_dist_codes - 1, 5);
2827
2828 for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
2829 if (d->m_huff_code_sizes
2830 [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
2831 break;
2832 num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
2833 TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
2834 for (i = 0; (int)i < num_bit_lengths; i++)
2835 TDEFL_PUT_BITS(
2836 d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
2837
2838 for (packed_code_sizes_index = 0;
2839 packed_code_sizes_index < num_packed_code_sizes;) {
2840 mz_uint code = packed_code_sizes[packed_code_sizes_index++];
2841 MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
2842 TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
2843 if (code >= 16)
2844 TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
2845 "\02\03\07"[code - 16]);
2846 }
2847 }
2848
2849 static void tdefl_start_static_block(tdefl_compressor *d) {
2850 mz_uint i;
2851 mz_uint8 *p = &d->m_huff_code_sizes[0][0];
2852
2853 for (i = 0; i <= 143; ++i)
2854 *p++ = 8;
2855 for (; i <= 255; ++i)
2856 *p++ = 9;
2857 for (; i <= 279; ++i)
2858 *p++ = 7;
2859 for (; i <= 287; ++i)
2860 *p++ = 8;
2861
2862 memset(d->m_huff_code_sizes[1], 5, 32);
2863
2864 tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
2865 tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
2866
2867 TDEFL_PUT_BITS(1, 2);
2868 }
2869
2870 static const mz_uint mz_bitmasks[17] = {
2871 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
2872 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
2873
2874 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
2875 MINIZ_HAS_64BIT_REGISTERS
2876 static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
2877 mz_uint flags;
2878 mz_uint8 *pLZ_codes;
2879 mz_uint8 *pOutput_buf = d->m_pOutput_buf;
2880 mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
2881 mz_uint64 bit_buffer = d->m_bit_buffer;
2882 mz_uint bits_in = d->m_bits_in;
2883
2884 #define TDEFL_PUT_BITS_FAST(b, l) \
2885 { \
2886 bit_buffer |= (((mz_uint64)(b)) << bits_in); \
2887 bits_in += (l); \
2888 }
2889
2890 flags = 1;
2891 for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
2892 flags >>= 1) {
2893 if (flags == 1)
2894 flags = *pLZ_codes++ | 0x100;
2895
2896 if (flags & 1) {
2897 mz_uint s0, s1, n0, n1, sym, num_extra_bits;
2898 mz_uint match_len = pLZ_codes[0],
2899 match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
2900 pLZ_codes += 3;
2901
2902 MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
2903 TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
2904 d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
2905 TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
2906 s_tdefl_len_extra[match_len]);
2907
2908 /* This sequence coaxes MSVC into using cmov's vs. jmp's. */
2909 s0 = s_tdefl_small_dist_sym[match_dist & 511];
2910 n0 = s_tdefl_small_dist_extra[match_dist & 511];
2911 s1 = s_tdefl_large_dist_sym[match_dist >> 8];
2912 n1 = s_tdefl_large_dist_extra[match_dist >> 8];
2913 sym = (match_dist < 512) ? s0 : s1;
2914 num_extra_bits = (match_dist < 512) ? n0 : n1;
2915
2916 MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
2917 TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
2918 d->m_huff_code_sizes[1][sym]);
2919 TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
2920 num_extra_bits);
2921 } else {
2922 mz_uint lit = *pLZ_codes++;
2923 MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
2924 TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
2925 d->m_huff_code_sizes[0][lit]);
2926
2927 if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
2928 flags >>= 1;
2929 lit = *pLZ_codes++;
2930 MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
2931 TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
2932 d->m_huff_code_sizes[0][lit]);
2933
2934 if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
2935 flags >>= 1;
2936 lit = *pLZ_codes++;
2937 MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
2938 TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
2939 d->m_huff_code_sizes[0][lit]);
2940 }
2941 }
2942 }
2943
2944 if (pOutput_buf >= d->m_pOutput_buf_end)
2945 return MZ_FALSE;
2946
2947 *(mz_uint64 *)pOutput_buf = bit_buffer;
2948 pOutput_buf += (bits_in >> 3);
2949 bit_buffer >>= (bits_in & ~7);
2950 bits_in &= 7;
2951 }
2952
2953 #undef TDEFL_PUT_BITS_FAST
2954
2955 d->m_pOutput_buf = pOutput_buf;
2956 d->m_bits_in = 0;
2957 d->m_bit_buffer = 0;
2958
2959 while (bits_in) {
2960 mz_uint32 n = MZ_MIN(bits_in, 16);
2961 TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
2962 bit_buffer >>= n;
2963 bits_in -= n;
2964 }
2965
2966 TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
2967
2968 return (d->m_pOutput_buf < d->m_pOutput_buf_end);
2969 }
2970 #else
2971 static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
2972 mz_uint flags;
2973 mz_uint8 *pLZ_codes;
2974
2975 flags = 1;
2976 for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
2977 flags >>= 1) {
2978 if (flags == 1)
2979 flags = *pLZ_codes++ | 0x100;
2980 if (flags & 1) {
2981 mz_uint sym, num_extra_bits;
2982 mz_uint match_len = pLZ_codes[0],
2983 match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
2984 pLZ_codes += 3;
2985
2986 MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
2987 TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
2988 d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
2989 TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
2990 s_tdefl_len_extra[match_len]);
2991
2992 if (match_dist < 512) {
2993 sym = s_tdefl_small_dist_sym[match_dist];
2994 num_extra_bits = s_tdefl_small_dist_extra[match_dist];
2995 } else {
2996 sym = s_tdefl_large_dist_sym[match_dist >> 8];
2997 num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
2998 }
2999 MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
3000 TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
3001 TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
3002 } else {
3003 mz_uint lit = *pLZ_codes++;
3004 MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
3005 TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
3006 }
3007 }
3008
3009 TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
3010
3011 return (d->m_pOutput_buf < d->m_pOutput_buf_end);
3012 }
3013 #endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
3014 MINIZ_HAS_64BIT_REGISTERS */
3015
3016 static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
3017 if (static_block)
3018 tdefl_start_static_block(d);
3019 else
3020 tdefl_start_dynamic_block(d);
3021 return tdefl_compress_lz_codes(d);
3022 }
3023
3024 static int tdefl_flush_block(tdefl_compressor *d, int flush) {
3025 mz_uint saved_bit_buf, saved_bits_in;
3026 mz_uint8 *pSaved_output_buf;
3027 mz_bool comp_block_succeeded = MZ_FALSE;
3028 int n, use_raw_block =
3029 ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
3030 (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
3031 mz_uint8 *pOutput_buf_start =
3032 ((d->m_pPut_buf_func == NULL) &&
3033 ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
3034 ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
3035 : d->m_output_buf;
3036
3037 d->m_pOutput_buf = pOutput_buf_start;
3038 d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
3039
3040 MZ_ASSERT(!d->m_output_flush_remaining);
3041 d->m_output_flush_ofs = 0;
3042 d->m_output_flush_remaining = 0;
3043
3044 *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
3045 d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
3046
3047 if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
3048 TDEFL_PUT_BITS(0x78, 8);
3049 TDEFL_PUT_BITS(0x01, 8);
3050 }
3051
3052 TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
3053
3054 pSaved_output_buf = d->m_pOutput_buf;
3055 saved_bit_buf = d->m_bit_buffer;
3056 saved_bits_in = d->m_bits_in;
3057
3058 if (!use_raw_block)
3059 comp_block_succeeded =
3060 tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
3061 (d->m_total_lz_bytes < 48));
3062
3063 /* If the block gets expanded, forget the current contents of the output
3064 * buffer and send a raw block instead. */
3065 if (((use_raw_block) ||
3066 ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
3067 d->m_total_lz_bytes))) &&
3068 ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
3069 mz_uint i;
3070 d->m_pOutput_buf = pSaved_output_buf;
3071 d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
3072 TDEFL_PUT_BITS(0, 2);
3073 if (d->m_bits_in) {
3074 TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
3075 }
3076 for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
3077 TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
3078 }
3079 for (i = 0; i < d->m_total_lz_bytes; ++i) {
3080 TDEFL_PUT_BITS(
3081 d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
3082 8);
3083 }
3084 }
3085 /* Check for the extremely unlikely (if not impossible) case of the compressed
3086 block not fitting into the output buffer when using dynamic codes. */
3087 else if (!comp_block_succeeded) {
3088 d->m_pOutput_buf = pSaved_output_buf;
3089 d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
3090 tdefl_compress_block(d, MZ_TRUE);
3091 }
3092
3093 if (flush) {
3094 if (flush == TDEFL_FINISH) {
3095 if (d->m_bits_in) {
3096 TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
3097 }
3098 if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
3099 mz_uint i, a = d->m_adler32;
3100 for (i = 0; i < 4; i++) {
3101 TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
3102 a <<= 8;
3103 }
3104 }
3105 } else {
3106 mz_uint i, z = 0;
3107 TDEFL_PUT_BITS(0, 3);
3108 if (d->m_bits_in) {
3109 TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
3110 }
3111 for (i = 2; i; --i, z ^= 0xFFFF) {
3112 TDEFL_PUT_BITS(z & 0xFFFF, 16);
3113 }
3114 }
3115 }
3116
3117 MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
3118
3119 memset(&d->m_huff_count[0][0], 0,
3120 sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
3121 memset(&d->m_huff_count[1][0], 0,
3122 sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
3123
3124 d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
3125 d->m_pLZ_flags = d->m_lz_code_buf;
3126 d->m_num_flags_left = 8;
3127 d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
3128 d->m_total_lz_bytes = 0;
3129 d->m_block_index++;
3130
3131 if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
3132 if (d->m_pPut_buf_func) {
3133 *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
3134 if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
3135 return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
3136 } else if (pOutput_buf_start == d->m_output_buf) {
3137 int bytes_to_copy = (int)MZ_MIN(
3138 (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
3139 memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
3140 bytes_to_copy);
3141 d->m_out_buf_ofs += bytes_to_copy;
3142 if ((n -= bytes_to_copy) != 0) {
3143 d->m_output_flush_ofs = bytes_to_copy;
3144 d->m_output_flush_remaining = n;
3145 }
3146 } else {
3147 d->m_out_buf_ofs += n;
3148 }
3149 }
3150
3151 return d->m_output_flush_remaining;
3152 }
3153
3154 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
3155 #ifdef MINIZ_UNALIGNED_USE_MEMCPY
3156 static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8 *p) {
3157 mz_uint16 ret;
3158 memcpy(&ret, p, sizeof(mz_uint16));
3159 return ret;
3160 }
3161 static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16 *p) {
3162 mz_uint16 ret;
3163 memcpy(&ret, p, sizeof(mz_uint16));
3164 return ret;
3165 }
3166 #else
3167 #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
3168 #define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p)
3169 #endif
3170 static MZ_FORCEINLINE void
3171 tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
3172 mz_uint max_match_len, mz_uint *pMatch_dist,
3173 mz_uint *pMatch_len) {
3174 mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
3175 match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
3176 probe_len;
3177 mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
3178 const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
3179 mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
3180 s01 = TDEFL_READ_UNALIGNED_WORD2(s);
3181 MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
3182 if (max_match_len <= match_len)
3183 return;
3184 for (;;) {
3185 for (;;) {
3186 if (--num_probes_left == 0)
3187 return;
3188 #define TDEFL_PROBE \
3189 next_probe_pos = d->m_next[probe_pos]; \
3190 if ((!next_probe_pos) || \
3191 ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
3192 return; \
3193 probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
3194 if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
3195 break;
3196 TDEFL_PROBE;
3197 TDEFL_PROBE;
3198 TDEFL_PROBE;
3199 }
3200 if (!dist)
3201 break;
3202 q = (const mz_uint16 *)(d->m_dict + probe_pos);
3203 if (TDEFL_READ_UNALIGNED_WORD2(q) != s01)
3204 continue;
3205 p = s;
3206 probe_len = 32;
3207 do {
3208 } while (
3209 (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3210 (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3211 (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3212 (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3213 (--probe_len > 0));
3214 if (!probe_len) {
3215 *pMatch_dist = dist;
3216 *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN);
3217 break;
3218 } else if ((probe_len = ((mz_uint)(p - s) * 2) +
3219 (mz_uint)(*(const mz_uint8 *)p ==
3220 *(const mz_uint8 *)q)) > match_len) {
3221 *pMatch_dist = dist;
3222 if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
3223 max_match_len)
3224 break;
3225 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
3226 }
3227 }
3228 }
3229 #else
3230 static MZ_FORCEINLINE void
3231 tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
3232 mz_uint max_match_len, mz_uint *pMatch_dist,
3233 mz_uint *pMatch_len) {
3234 mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
3235 match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
3236 probe_len;
3237 mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
3238 const mz_uint8 *s = d->m_dict + pos, *p, *q;
3239 mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
3240 MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
3241 if (max_match_len <= match_len)
3242 return;
3243 for (;;) {
3244 for (;;) {
3245 if (--num_probes_left == 0)
3246 return;
3247 #define TDEFL_PROBE \
3248 next_probe_pos = d->m_next[probe_pos]; \
3249 if ((!next_probe_pos) || \
3250 ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
3251 return; \
3252 probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
3253 if ((d->m_dict[probe_pos + match_len] == c0) && \
3254 (d->m_dict[probe_pos + match_len - 1] == c1)) \
3255 break;
3256 TDEFL_PROBE;
3257 TDEFL_PROBE;
3258 TDEFL_PROBE;
3259 }
3260 if (!dist)
3261 break;
3262 p = s;
3263 q = d->m_dict + probe_pos;
3264 for (probe_len = 0; probe_len < max_match_len; probe_len++)
3265 if (*p++ != *q++)
3266 break;
3267 if (probe_len > match_len) {
3268 *pMatch_dist = dist;
3269 if ((*pMatch_len = match_len = probe_len) == max_match_len)
3270 return;
3271 c0 = d->m_dict[pos + match_len];
3272 c1 = d->m_dict[pos + match_len - 1];
3273 }
3274 }
3275 }
3276 #endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */
3277
3278 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
3279 #ifdef MINIZ_UNALIGNED_USE_MEMCPY
3280 static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8 *p) {
3281 mz_uint32 ret;
3282 memcpy(&ret, p, sizeof(mz_uint32));
3283 return ret;
3284 }
3285 #else
3286 #define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p)
3287 #endif
3288 static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
3289 /* Faster, minimally featured LZRW1-style match+parse loop with better
3290 * register utilization. Intended for applications where raw throughput is
3291 * valued more highly than ratio. */
3292 mz_uint lookahead_pos = d->m_lookahead_pos,
3293 lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
3294 total_lz_bytes = d->m_total_lz_bytes,
3295 num_flags_left = d->m_num_flags_left;
3296 mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
3297 mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
3298
3299 while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
3300 const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
3301 mz_uint dst_pos =
3302 (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
3303 mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
3304 d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
3305 d->m_src_buf_left -= num_bytes_to_process;
3306 lookahead_size += num_bytes_to_process;
3307
3308 while (num_bytes_to_process) {
3309 mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
3310 memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
3311 if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
3312 memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
3313 MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
3314 d->m_pSrc += n;
3315 dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
3316 num_bytes_to_process -= n;
3317 }
3318
3319 dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
3320 if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
3321 break;
3322
3323 while (lookahead_size >= 4) {
3324 mz_uint cur_match_dist, cur_match_len = 1;
3325 mz_uint8 *pCur_dict = d->m_dict + cur_pos;
3326 mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF;
3327 mz_uint hash =
3328 (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
3329 TDEFL_LEVEL1_HASH_SIZE_MASK;
3330 mz_uint probe_pos = d->m_hash[hash];
3331 d->m_hash[hash] = (mz_uint16)lookahead_pos;
3332
3333 if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
3334 dict_size) &&
3335 ((TDEFL_READ_UNALIGNED_WORD32(
3336 d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
3337 0xFFFFFF) == first_trigram)) {
3338 const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
3339 const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
3340 mz_uint32 probe_len = 32;
3341 do {
3342 } while ((TDEFL_READ_UNALIGNED_WORD2(++p) ==
3343 TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3344 (TDEFL_READ_UNALIGNED_WORD2(++p) ==
3345 TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3346 (TDEFL_READ_UNALIGNED_WORD2(++p) ==
3347 TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3348 (TDEFL_READ_UNALIGNED_WORD2(++p) ==
3349 TDEFL_READ_UNALIGNED_WORD2(++q)) &&
3350 (--probe_len > 0));
3351 cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
3352 (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
3353 if (!probe_len)
3354 cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
3355
3356 if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
3357 ((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
3358 (cur_match_dist >= 8U * 1024U))) {
3359 cur_match_len = 1;
3360 *pLZ_code_buf++ = (mz_uint8)first_trigram;
3361 *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
3362 d->m_huff_count[0][(mz_uint8)first_trigram]++;
3363 } else {
3364 mz_uint32 s0, s1;
3365 cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
3366
3367 MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
3368 (cur_match_dist >= 1) &&
3369 (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
3370
3371 cur_match_dist--;
3372
3373 pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
3374 #ifdef MINIZ_UNALIGNED_USE_MEMCPY
3375 memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist));
3376 #else
3377 *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
3378 #endif
3379 pLZ_code_buf += 3;
3380 *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
3381
3382 s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
3383 s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
3384 d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
3385
3386 d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
3387 TDEFL_MIN_MATCH_LEN]]++;
3388 }
3389 } else {
3390 *pLZ_code_buf++ = (mz_uint8)first_trigram;
3391 *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
3392 d->m_huff_count[0][(mz_uint8)first_trigram]++;
3393 }
3394
3395 if (--num_flags_left == 0) {
3396 num_flags_left = 8;
3397 pLZ_flags = pLZ_code_buf++;
3398 }
3399
3400 total_lz_bytes += cur_match_len;
3401 lookahead_pos += cur_match_len;
3402 dict_size =
3403 MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE);
3404 cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
3405 MZ_ASSERT(lookahead_size >= cur_match_len);
3406 lookahead_size -= cur_match_len;
3407
3408 if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
3409 int n;
3410 d->m_lookahead_pos = lookahead_pos;
3411 d->m_lookahead_size = lookahead_size;
3412 d->m_dict_size = dict_size;
3413 d->m_total_lz_bytes = total_lz_bytes;
3414 d->m_pLZ_code_buf = pLZ_code_buf;
3415 d->m_pLZ_flags = pLZ_flags;
3416 d->m_num_flags_left = num_flags_left;
3417 if ((n = tdefl_flush_block(d, 0)) != 0)
3418 return (n < 0) ? MZ_FALSE : MZ_TRUE;
3419 total_lz_bytes = d->m_total_lz_bytes;
3420 pLZ_code_buf = d->m_pLZ_code_buf;
3421 pLZ_flags = d->m_pLZ_flags;
3422 num_flags_left = d->m_num_flags_left;
3423 }
3424 }
3425
3426 while (lookahead_size) {
3427 mz_uint8 lit = d->m_dict[cur_pos];
3428
3429 total_lz_bytes++;
3430 *pLZ_code_buf++ = lit;
3431 *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
3432 if (--num_flags_left == 0) {
3433 num_flags_left = 8;
3434 pLZ_flags = pLZ_code_buf++;
3435 }
3436
3437 d->m_huff_count[0][lit]++;
3438
3439 lookahead_pos++;
3440 dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE);
3441 cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
3442 lookahead_size--;
3443
3444 if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
3445 int n;
3446 d->m_lookahead_pos = lookahead_pos;
3447 d->m_lookahead_size = lookahead_size;
3448 d->m_dict_size = dict_size;
3449 d->m_total_lz_bytes = total_lz_bytes;
3450 d->m_pLZ_code_buf = pLZ_code_buf;
3451 d->m_pLZ_flags = pLZ_flags;
3452 d->m_num_flags_left = num_flags_left;
3453 if ((n = tdefl_flush_block(d, 0)) != 0)
3454 return (n < 0) ? MZ_FALSE : MZ_TRUE;
3455 total_lz_bytes = d->m_total_lz_bytes;
3456 pLZ_code_buf = d->m_pLZ_code_buf;
3457 pLZ_flags = d->m_pLZ_flags;
3458 num_flags_left = d->m_num_flags_left;
3459 }
3460 }
3461 }
3462
3463 d->m_lookahead_pos = lookahead_pos;
3464 d->m_lookahead_size = lookahead_size;
3465 d->m_dict_size = dict_size;
3466 d->m_total_lz_bytes = total_lz_bytes;
3467 d->m_pLZ_code_buf = pLZ_code_buf;
3468 d->m_pLZ_flags = pLZ_flags;
3469 d->m_num_flags_left = num_flags_left;
3470 return MZ_TRUE;
3471 }
3472 #endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */
3473
3474 static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
3475 mz_uint8 lit) {
3476 d->m_total_lz_bytes++;
3477 *d->m_pLZ_code_buf++ = lit;
3478 *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
3479 if (--d->m_num_flags_left == 0) {
3480 d->m_num_flags_left = 8;
3481 d->m_pLZ_flags = d->m_pLZ_code_buf++;
3482 }
3483 d->m_huff_count[0][lit]++;
3484 }
3485
3486 static MZ_FORCEINLINE void
3487 tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) {
3488 mz_uint32 s0, s1;
3489
3490 MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
3491 (match_dist <= TDEFL_LZ_DICT_SIZE));
3492
3493 d->m_total_lz_bytes += match_len;
3494
3495 d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
3496
3497 match_dist -= 1;
3498 d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
3499 d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
3500 d->m_pLZ_code_buf += 3;
3501
3502 *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
3503 if (--d->m_num_flags_left == 0) {
3504 d->m_num_flags_left = 8;
3505 d->m_pLZ_flags = d->m_pLZ_code_buf++;
3506 }
3507
3508 s0 = s_tdefl_small_dist_sym[match_dist & 511];
3509 s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
3510 d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
3511 d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
3512 }
3513
3514 static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
3515 const mz_uint8 *pSrc = d->m_pSrc;
3516 size_t src_buf_left = d->m_src_buf_left;
3517 tdefl_flush flush = d->m_flush;
3518
3519 while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
3520 mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
3521 /* Update dictionary and hash chains. Keeps the lookahead size equal to
3522 * TDEFL_MAX_MATCH_LEN. */
3523 if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
3524 mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
3525 TDEFL_LZ_DICT_SIZE_MASK,
3526 ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
3527 mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
3528 << TDEFL_LZ_HASH_SHIFT) ^
3529 d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
3530 mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
3531 src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
3532 const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
3533 src_buf_left -= num_bytes_to_process;
3534 d->m_lookahead_size += num_bytes_to_process;
3535 while (pSrc != pSrc_end) {
3536 mz_uint8 c = *pSrc++;
3537 d->m_dict[dst_pos] = c;
3538 if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
3539 d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
3540 hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
3541 d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
3542 d->m_hash[hash] = (mz_uint16)(ins_pos);
3543 dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
3544 ins_pos++;
3545 }
3546 } else {
3547 while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
3548 mz_uint8 c = *pSrc++;
3549 mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
3550 TDEFL_LZ_DICT_SIZE_MASK;
3551 src_buf_left--;
3552 d->m_dict[dst_pos] = c;
3553 if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
3554 d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
3555 if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
3556 mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
3557 mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
3558 << (TDEFL_LZ_HASH_SHIFT * 2)) ^
3559 (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
3560 << TDEFL_LZ_HASH_SHIFT) ^
3561 c) &
3562 (TDEFL_LZ_HASH_SIZE - 1);
3563 d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
3564 d->m_hash[hash] = (mz_uint16)(ins_pos);
3565 }
3566 }
3567 }
3568 d->m_dict_size =
3569 MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
3570 if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
3571 break;
3572
3573 /* Simple lazy/greedy parsing state machine. */
3574 len_to_move = 1;
3575 cur_match_dist = 0;
3576 cur_match_len =
3577 d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
3578 cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
3579 if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
3580 if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
3581 mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
3582 cur_match_len = 0;
3583 while (cur_match_len < d->m_lookahead_size) {
3584 if (d->m_dict[cur_pos + cur_match_len] != c)
3585 break;
3586 cur_match_len++;
3587 }
3588 if (cur_match_len < TDEFL_MIN_MATCH_LEN)
3589 cur_match_len = 0;
3590 else
3591 cur_match_dist = 1;
3592 }
3593 } else {
3594 tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
3595 d->m_lookahead_size, &cur_match_dist, &cur_match_len);
3596 }
3597 if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
3598 (cur_match_dist >= 8U * 1024U)) ||
3599 (cur_pos == cur_match_dist) ||
3600 ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
3601 cur_match_dist = cur_match_len = 0;
3602 }
3603 if (d->m_saved_match_len) {
3604 if (cur_match_len > d->m_saved_match_len) {
3605 tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
3606 if (cur_match_len >= 128) {
3607 tdefl_record_match(d, cur_match_len, cur_match_dist);
3608 d->m_saved_match_len = 0;
3609 len_to_move = cur_match_len;
3610 } else {
3611 d->m_saved_lit = d->m_dict[cur_pos];
3612 d->m_saved_match_dist = cur_match_dist;
3613 d->m_saved_match_len = cur_match_len;
3614 }
3615 } else {
3616 tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
3617 len_to_move = d->m_saved_match_len - 1;
3618 d->m_saved_match_len = 0;
3619 }
3620 } else if (!cur_match_dist)
3621 tdefl_record_literal(d,
3622 d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
3623 else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
3624 (cur_match_len >= 128)) {
3625 tdefl_record_match(d, cur_match_len, cur_match_dist);
3626 len_to_move = cur_match_len;
3627 } else {
3628 d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
3629 d->m_saved_match_dist = cur_match_dist;
3630 d->m_saved_match_len = cur_match_len;
3631 }
3632 /* Move the lookahead forward by len_to_move bytes. */
3633 d->m_lookahead_pos += len_to_move;
3634 MZ_ASSERT(d->m_lookahead_size >= len_to_move);
3635 d->m_lookahead_size -= len_to_move;
3636 d->m_dict_size =
3637 MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
3638 /* Check if it's time to flush the current LZ codes to the internal output
3639 * buffer. */
3640 if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
3641 ((d->m_total_lz_bytes > 31 * 1024) &&
3642 (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
3643 d->m_total_lz_bytes) ||
3644 (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
3645 int n;
3646 d->m_pSrc = pSrc;
3647 d->m_src_buf_left = src_buf_left;
3648 if ((n = tdefl_flush_block(d, 0)) != 0)
3649 return (n < 0) ? MZ_FALSE : MZ_TRUE;
3650 }
3651 }
3652
3653 d->m_pSrc = pSrc;
3654 d->m_src_buf_left = src_buf_left;
3655 return MZ_TRUE;
3656 }
3657
3658 static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
3659 if (d->m_pIn_buf_size) {
3660 *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
3661 }
3662
3663 if (d->m_pOut_buf_size) {
3664 size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
3665 d->m_output_flush_remaining);
3666 memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
3667 d->m_output_buf + d->m_output_flush_ofs, n);
3668 d->m_output_flush_ofs += (mz_uint)n;
3669 d->m_output_flush_remaining -= (mz_uint)n;
3670 d->m_out_buf_ofs += n;
3671
3672 *d->m_pOut_buf_size = d->m_out_buf_ofs;
3673 }
3674
3675 return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
3676 : TDEFL_STATUS_OKAY;
3677 }
3678
3679 tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
3680 size_t *pIn_buf_size, void *pOut_buf,
3681 size_t *pOut_buf_size, tdefl_flush flush) {
3682 if (!d) {
3683 if (pIn_buf_size)
3684 *pIn_buf_size = 0;
3685 if (pOut_buf_size)
3686 *pOut_buf_size = 0;
3687 return TDEFL_STATUS_BAD_PARAM;
3688 }
3689
3690 d->m_pIn_buf = pIn_buf;
3691 d->m_pIn_buf_size = pIn_buf_size;
3692 d->m_pOut_buf = pOut_buf;
3693 d->m_pOut_buf_size = pOut_buf_size;
3694 d->m_pSrc = (const mz_uint8 *)(pIn_buf);
3695 d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
3696 d->m_out_buf_ofs = 0;
3697 d->m_flush = flush;
3698
3699 if (((d->m_pPut_buf_func != NULL) ==
3700 ((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
3701 (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
3702 (d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
3703 (pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
3704 (pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
3705 if (pIn_buf_size)
3706 *pIn_buf_size = 0;
3707 if (pOut_buf_size)
3708 *pOut_buf_size = 0;
3709 return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
3710 }
3711 d->m_wants_to_finish |= (flush == TDEFL_FINISH);
3712
3713 if ((d->m_output_flush_remaining) || (d->m_finished))
3714 return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
3715
3716 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
3717 if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
3718 ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
3719 ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
3720 TDEFL_RLE_MATCHES)) == 0)) {
3721 if (!tdefl_compress_fast(d))
3722 return d->m_prev_return_status;
3723 } else
3724 #endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */
3725 {
3726 if (!tdefl_compress_normal(d))
3727 return d->m_prev_return_status;
3728 }
3729
3730 if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
3731 (pIn_buf))
3732 d->m_adler32 =
3733 (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
3734 d->m_pSrc - (const mz_uint8 *)pIn_buf);
3735
3736 if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
3737 (!d->m_output_flush_remaining)) {
3738 if (tdefl_flush_block(d, flush) < 0)
3739 return d->m_prev_return_status;
3740 d->m_finished = (flush == TDEFL_FINISH);
3741 if (flush == TDEFL_FULL_FLUSH) {
3742 MZ_CLEAR_OBJ(d->m_hash);
3743 MZ_CLEAR_OBJ(d->m_next);
3744 d->m_dict_size = 0;
3745 }
3746 }
3747
3748 return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
3749 }
3750
3751 tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
3752 size_t in_buf_size, tdefl_flush flush) {
3753 MZ_ASSERT(d->m_pPut_buf_func);
3754 return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
3755 }
3756
3757 tdefl_status tdefl_init(tdefl_compressor *d,
3758 tdefl_put_buf_func_ptr pPut_buf_func,
3759 void *pPut_buf_user, int flags) {
3760 d->m_pPut_buf_func = pPut_buf_func;
3761 d->m_pPut_buf_user = pPut_buf_user;
3762 d->m_flags = (mz_uint)(flags);
3763 d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
3764 d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
3765 d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
3766 if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))
3767 MZ_CLEAR_OBJ(d->m_hash);
3768 d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
3769 d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
3770 d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
3771 d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
3772 d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
3773 d->m_pLZ_flags = d->m_lz_code_buf;
3774 *d->m_pLZ_flags = 0;
3775 d->m_num_flags_left = 8;
3776 d->m_pOutput_buf = d->m_output_buf;
3777 d->m_pOutput_buf_end = d->m_output_buf;
3778 d->m_prev_return_status = TDEFL_STATUS_OKAY;
3779 d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
3780 d->m_adler32 = 1;
3781 d->m_pIn_buf = NULL;
3782 d->m_pOut_buf = NULL;
3783 d->m_pIn_buf_size = NULL;
3784 d->m_pOut_buf_size = NULL;
3785 d->m_flush = TDEFL_NO_FLUSH;
3786 d->m_pSrc = NULL;
3787 d->m_src_buf_left = 0;
3788 d->m_out_buf_ofs = 0;
3789 if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))
3790 MZ_CLEAR_OBJ(d->m_dict);
3791 memset(&d->m_huff_count[0][0], 0,
3792 sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
3793 memset(&d->m_huff_count[1][0], 0,
3794 sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
3795 return TDEFL_STATUS_OKAY;
3796 }
3797
3798 tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
3799 return d->m_prev_return_status;
3800 }
3801
3802 mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
3803
3804 mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
3805 tdefl_put_buf_func_ptr pPut_buf_func,
3806 void *pPut_buf_user, int flags) {
3807 tdefl_compressor *pComp;
3808 mz_bool succeeded;
3809 if (((buf_len) && (!pBuf)) || (!pPut_buf_func))
3810 return MZ_FALSE;
3811 pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
3812 if (!pComp)
3813 return MZ_FALSE;
3814 succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
3815 TDEFL_STATUS_OKAY);
3816 succeeded =
3817 succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
3818 TDEFL_STATUS_DONE);
3819 MZ_FREE(pComp);
3820 return succeeded;
3821 }
3822
3823 typedef struct {
3824 size_t m_size, m_capacity;
3825 mz_uint8 *m_pBuf;
3826 mz_bool m_expandable;
3827 } tdefl_output_buffer;
3828
3829 static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
3830 void *pUser) {
3831 tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
3832 size_t new_size = p->m_size + len;
3833 if (new_size > p->m_capacity) {
3834 size_t new_capacity = p->m_capacity;
3835 mz_uint8 *pNew_buf;
3836 if (!p->m_expandable)
3837 return MZ_FALSE;
3838 do {
3839 new_capacity = MZ_MAX(128U, new_capacity << 1U);
3840 } while (new_size > new_capacity);
3841 pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
3842 if (!pNew_buf)
3843 return MZ_FALSE;
3844 p->m_pBuf = pNew_buf;
3845 p->m_capacity = new_capacity;
3846 }
3847 memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
3848 p->m_size = new_size;
3849 return MZ_TRUE;
3850 }
3851
3852 void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
3853 size_t *pOut_len, int flags) {
3854 tdefl_output_buffer out_buf;
3855 MZ_CLEAR_OBJ(out_buf);
3856 if (!pOut_len)
3857 return MZ_FALSE;
3858 else
3859 *pOut_len = 0;
3860 out_buf.m_expandable = MZ_TRUE;
3861 if (!tdefl_compress_mem_to_output(
3862 pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
3863 return NULL;
3864 *pOut_len = out_buf.m_size;
3865 return out_buf.m_pBuf;
3866 }
3867
3868 size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
3869 const void *pSrc_buf, size_t src_buf_len,
3870 int flags) {
3871 tdefl_output_buffer out_buf;
3872 MZ_CLEAR_OBJ(out_buf);
3873 if (!pOut_buf)
3874 return 0;
3875 out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
3876 out_buf.m_capacity = out_buf_len;
3877 if (!tdefl_compress_mem_to_output(
3878 pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
3879 return 0;
3880 return out_buf.m_size;
3881 }
3882
3883 static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
3884 128, 256, 512, 768, 1500};
3885
3886 /* level may actually range from [0,10] (10 is a "hidden" max level, where we
3887 * want a bit more compression and it's fine if throughput to fall off a cliff
3888 * on some files). */
3889 mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
3890 int strategy) {
3891 mz_uint comp_flags =
3892 s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
3893 ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
3894 if (window_bits > 0)
3895 comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
3896
3897 if (!level)
3898 comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
3899 else if (strategy == MZ_FILTERED)
3900 comp_flags |= TDEFL_FILTER_MATCHES;
3901 else if (strategy == MZ_HUFFMAN_ONLY)
3902 comp_flags &= ~TDEFL_MAX_PROBES_MASK;
3903 else if (strategy == MZ_FIXED)
3904 comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
3905 else if (strategy == MZ_RLE)
3906 comp_flags |= TDEFL_RLE_MATCHES;
3907
3908 return comp_flags;
3909 }
3910
3911 #ifdef _MSC_VER
3912 #pragma warning(push)
3913 #pragma warning(disable : 4204) /* nonstandard extension used : non-constant \
3914 aggregate initializer (also supported by \
3915 GNU C and C99, so no big deal) */
3916 #endif
3917
3918 /* Simple PNG writer function by Alex Evans, 2011. Released into the public
3919 domain: https://gist.github.com/908299, more context at
3920 http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
3921 This is actually a modification of Alex's original code so PNG files generated
3922 by this function pass pngcheck. */
3923 void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
3924 int h, int num_chans,
3925 size_t *pLen_out,
3926 mz_uint level, mz_bool flip) {
3927 /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
3928 * defined. */
3929 static const mz_uint s_tdefl_png_num_probes[11] = {
3930 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
3931 tdefl_compressor *pComp =
3932 (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
3933 tdefl_output_buffer out_buf;
3934 int i, bpl = w * num_chans, y, z;
3935 mz_uint32 c;
3936 *pLen_out = 0;
3937 if (!pComp)
3938 return NULL;
3939 MZ_CLEAR_OBJ(out_buf);
3940 out_buf.m_expandable = MZ_TRUE;
3941 out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
3942 if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
3943 MZ_FREE(pComp);
3944 return NULL;
3945 }
3946 /* write dummy header */
3947 for (z = 41; z; --z)
3948 tdefl_output_buffer_putter(&z, 1, &out_buf);
3949 /* compress image data */
3950 tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf,
3951 s_tdefl_png_num_probes[MZ_MIN(10, level)] |
3952 TDEFL_WRITE_ZLIB_HEADER);
3953 for (y = 0; y < h; ++y) {
3954 tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
3955 tdefl_compress_buffer(pComp,
3956 (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
3957 bpl, TDEFL_NO_FLUSH);
3958 }
3959 if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
3960 TDEFL_STATUS_DONE) {
3961 MZ_FREE(pComp);
3962 MZ_FREE(out_buf.m_pBuf);
3963 return NULL;
3964 }
3965 /* write real header */
3966 *pLen_out = out_buf.m_size - 41;
3967 {
3968 static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
3969 mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00,
3970 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00,
3971 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
3972 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3973 0x00, 0x49, 0x44, 0x41, 0x54};
3974 pnghdr[18] = (mz_uint8)(w >> 8);
3975 pnghdr[19] = (mz_uint8)w;
3976 pnghdr[22] = (mz_uint8)(h >> 8);
3977 pnghdr[23] = (mz_uint8)h;
3978 pnghdr[25] = chans[num_chans];
3979 pnghdr[33] = (mz_uint8)(*pLen_out >> 24);
3980 pnghdr[34] = (mz_uint8)(*pLen_out >> 16);
3981 pnghdr[35] = (mz_uint8)(*pLen_out >> 8);
3982 pnghdr[36] = (mz_uint8)*pLen_out;
3983 c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
3984 for (i = 0; i < 4; ++i, c <<= 8)
3985 ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
3986 memcpy(out_buf.m_pBuf, pnghdr, 41);
3987 }
3988 /* write footer (IDAT CRC-32, followed by IEND chunk) */
3989 if (!tdefl_output_buffer_putter(
3990 "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
3991 *pLen_out = 0;
3992 MZ_FREE(pComp);
3993 MZ_FREE(out_buf.m_pBuf);
3994 return NULL;
3995 }
3996 c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
3997 *pLen_out + 4);
3998 for (i = 0; i < 4; ++i, c <<= 8)
3999 (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
4000 /* compute final size of file, grab compressed data buffer and return */
4001 *pLen_out += 57;
4002 MZ_FREE(pComp);
4003 return out_buf.m_pBuf;
4004 }
4005 void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
4006 int num_chans, size_t *pLen_out) {
4007 /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
4008 * can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
4009 * where #defined out) */
4010 return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
4011 pLen_out, 6, MZ_FALSE);
4012 }
4013
4014 #ifndef MINIZ_NO_MALLOC
4015 /* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that
4016 */
4017 /* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */
4018 /* structure size and allocation mechanism. */
4019 tdefl_compressor *tdefl_compressor_alloc(void) {
4020 return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
4021 }
4022
4023 void tdefl_compressor_free(tdefl_compressor *pComp) { MZ_FREE(pComp); }
4024 #endif
4025
4026 #ifdef _MSC_VER
4027 #pragma warning(pop)
4028 #endif
4029
4030 #ifdef __cplusplus
4031 }
4032 #endif
4033 /**************************************************************************
4034 *
4035 * Copyright 2013-2014 RAD Game Tools and Valve Software
4036 * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
4037 * All Rights Reserved.
4038 *
4039 * Permission is hereby granted, free of charge, to any person obtaining a copy
4040 * of this software and associated documentation files (the "Software"), to deal
4041 * in the Software without restriction, including without limitation the rights
4042 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4043 * copies of the Software, and to permit persons to whom the Software is
4044 * furnished to do so, subject to the following conditions:
4045 *
4046 * The above copyright notice and this permission notice shall be included in
4047 * all copies or substantial portions of the Software.
4048 *
4049 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4050 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4051 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4052 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4053 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4054 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4055 * THE SOFTWARE.
4056 *
4057 **************************************************************************/
4058
4059 #ifdef __cplusplus
4060 extern "C" {
4061 #endif
4062
4063 /* ------------------- Low-level Decompression (completely independent from all
4064 * compression API's) */
4065
4066 #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
4067 #define TINFL_MEMSET(p, c, l) memset(p, c, l)
4068
4069 #define TINFL_CR_BEGIN \
4070 switch (r->m_state) { \
4071 case 0:
4072 #define TINFL_CR_RETURN(state_index, result) \
4073 do { \
4074 status = result; \
4075 r->m_state = state_index; \
4076 goto common_exit; \
4077 case state_index:; \
4078 } \
4079 MZ_MACRO_END
4080 #define TINFL_CR_RETURN_FOREVER(state_index, result) \
4081 do { \
4082 for (;;) { \
4083 TINFL_CR_RETURN(state_index, result); \
4084 } \
4085 } \
4086 MZ_MACRO_END
4087 #define TINFL_CR_FINISH }
4088
4089 #define TINFL_GET_BYTE(state_index, c) \
4090 do { \
4091 while (pIn_buf_cur >= pIn_buf_end) { \
4092 TINFL_CR_RETURN(state_index, \
4093 (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) \
4094 ? TINFL_STATUS_NEEDS_MORE_INPUT \
4095 : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \
4096 } \
4097 c = *pIn_buf_cur++; \
4098 } \
4099 MZ_MACRO_END
4100
4101 #define TINFL_NEED_BITS(state_index, n) \
4102 do { \
4103 mz_uint c; \
4104 TINFL_GET_BYTE(state_index, c); \
4105 bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
4106 num_bits += 8; \
4107 } while (num_bits < (mz_uint)(n))
4108 #define TINFL_SKIP_BITS(state_index, n) \
4109 do { \
4110 if (num_bits < (mz_uint)(n)) { \
4111 TINFL_NEED_BITS(state_index, n); \
4112 } \
4113 bit_buf >>= (n); \
4114 num_bits -= (n); \
4115 } \
4116 MZ_MACRO_END
4117 #define TINFL_GET_BITS(state_index, b, n) \
4118 do { \
4119 if (num_bits < (mz_uint)(n)) { \
4120 TINFL_NEED_BITS(state_index, n); \
4121 } \
4122 b = bit_buf & ((1 << (n)) - 1); \
4123 bit_buf >>= (n); \
4124 num_bits -= (n); \
4125 } \
4126 MZ_MACRO_END
4127
4128 /* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
4129 * remaining in the input buffer falls below 2. */
4130 /* It reads just enough bytes from the input stream that are needed to decode
4131 * the next Huffman code (and absolutely no more). It works by trying to fully
4132 * decode a */
4133 /* Huffman code by using whatever bits are currently present in the bit buffer.
4134 * If this fails, it reads another byte, and tries again until it succeeds or
4135 * until the */
4136 /* bit buffer contains >=15 bits (deflate's max. Huffman code size). */
4137 #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
4138 do { \
4139 temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
4140 if (temp >= 0) { \
4141 code_len = temp >> 9; \
4142 if ((code_len) && (num_bits >= code_len)) \
4143 break; \
4144 } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
4145 code_len = TINFL_FAST_LOOKUP_BITS; \
4146 do { \
4147 temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
4148 } while ((temp < 0) && (num_bits >= (code_len + 1))); \
4149 if (temp >= 0) \
4150 break; \
4151 } \
4152 TINFL_GET_BYTE(state_index, c); \
4153 bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
4154 num_bits += 8; \
4155 } while (num_bits < 15);
4156
4157 /* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
4158 * than you would initially expect because the zlib API expects the decompressor
4159 * to never read */
4160 /* beyond the final byte of the deflate stream. (In other words, when this macro
4161 * wants to read another byte from the input, it REALLY needs another byte in
4162 * order to fully */
4163 /* decode the next Huffman code.) Handling this properly is particularly
4164 * important on raw deflate (non-zlib) streams, which aren't followed by a byte
4165 * aligned adler-32. */
4166 /* The slow path is only executed at the very end of the input buffer. */
4167 /* v1.16: The original macro handled the case at the very end of the passed-in
4168 * input buffer, but we also need to handle the case where the user passes in
4169 * 1+zillion bytes */
4170 /* following the deflate data and our non-conservative read-ahead path won't
4171 * kick in here on this code. This is much trickier. */
4172 #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
4173 do { \
4174 int temp; \
4175 mz_uint code_len, c; \
4176 if (num_bits < 15) { \
4177 if ((pIn_buf_end - pIn_buf_cur) < 2) { \
4178 TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
4179 } else { \
4180 bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
4181 (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
4182 pIn_buf_cur += 2; \
4183 num_bits += 16; \
4184 } \
4185 } \
4186 if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
4187 0) \
4188 code_len = temp >> 9, temp &= 511; \
4189 else { \
4190 code_len = TINFL_FAST_LOOKUP_BITS; \
4191 do { \
4192 temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
4193 } while (temp < 0); \
4194 } \
4195 sym = temp; \
4196 bit_buf >>= code_len; \
4197 num_bits -= code_len; \
4198 } \
4199 MZ_MACRO_END
4200
4201 tinfl_status tinfl_decompress(tinfl_decompressor *r,
4202 const mz_uint8 *pIn_buf_next,
4203 size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
4204 mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
4205 const mz_uint32 decomp_flags) {
4206 static const int s_length_base[31] = {
4207 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
4208 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
4209 static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
4210 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
4211 4, 4, 5, 5, 5, 5, 0, 0, 0};
4212 static const int s_dist_base[32] = {
4213 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
4214 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
4215 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
4216 static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
4217 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
4218 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
4219 static const mz_uint8 s_length_dezigzag[19] = {
4220 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
4221 static const int s_min_table_sizes[3] = {257, 1, 4};
4222
4223 tinfl_status status = TINFL_STATUS_FAILED;
4224 mz_uint32 num_bits, dist, counter, num_extra;
4225 tinfl_bit_buf_t bit_buf;
4226 const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end =
4227 pIn_buf_next + *pIn_buf_size;
4228 mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end =
4229 pOut_buf_next + *pOut_buf_size;
4230 size_t out_buf_size_mask =
4231 (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
4232 ? (size_t)-1
4233 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
4234 dist_from_out_buf_start;
4235
4236 /* Ensure the output buffer's size is a power of 2, unless the output buffer
4237 * is large enough to hold the entire output file (in which case it doesn't
4238 * matter). */
4239 if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
4240 (pOut_buf_next < pOut_buf_start)) {
4241 *pIn_buf_size = *pOut_buf_size = 0;
4242 return TINFL_STATUS_BAD_PARAM;
4243 }
4244
4245 num_bits = r->m_num_bits;
4246 bit_buf = r->m_bit_buf;
4247 dist = r->m_dist;
4248 counter = r->m_counter;
4249 num_extra = r->m_num_extra;
4250 dist_from_out_buf_start = r->m_dist_from_out_buf_start;
4251 TINFL_CR_BEGIN
4252
4253 bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
4254 r->m_z_adler32 = r->m_check_adler32 = 1;
4255 if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
4256 TINFL_GET_BYTE(1, r->m_zhdr0);
4257 TINFL_GET_BYTE(2, r->m_zhdr1);
4258 counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
4259 (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
4260 if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
4261 counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
4262 ((out_buf_size_mask + 1) <
4263 (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
4264 if (counter) {
4265 TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
4266 }
4267 }
4268
4269 do {
4270 TINFL_GET_BITS(3, r->m_final, 3);
4271 r->m_type = r->m_final >> 1;
4272 if (r->m_type == 0) {
4273 TINFL_SKIP_BITS(5, num_bits & 7);
4274 for (counter = 0; counter < 4; ++counter) {
4275 if (num_bits)
4276 TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
4277 else
4278 TINFL_GET_BYTE(7, r->m_raw_header[counter]);
4279 }
4280 if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
4281 (mz_uint)(0xFFFF ^
4282 (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
4283 TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
4284 }
4285 while ((counter) && (num_bits)) {
4286 TINFL_GET_BITS(51, dist, 8);
4287 while (pOut_buf_cur >= pOut_buf_end) {
4288 TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
4289 }
4290 *pOut_buf_cur++ = (mz_uint8)dist;
4291 counter--;
4292 }
4293 while (counter) {
4294 size_t n;
4295 while (pOut_buf_cur >= pOut_buf_end) {
4296 TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
4297 }
4298 while (pIn_buf_cur >= pIn_buf_end) {
4299 TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
4300 ? TINFL_STATUS_NEEDS_MORE_INPUT
4301 : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS);
4302 }
4303 n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
4304 (size_t)(pIn_buf_end - pIn_buf_cur)),
4305 counter);
4306 TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
4307 pIn_buf_cur += n;
4308 pOut_buf_cur += n;
4309 counter -= (mz_uint)n;
4310 }
4311 } else if (r->m_type == 3) {
4312 TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
4313 } else {
4314 if (r->m_type == 1) {
4315 mz_uint8 *p = r->m_tables[0].m_code_size;
4316 mz_uint i;
4317 r->m_table_sizes[0] = 288;
4318 r->m_table_sizes[1] = 32;
4319 TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
4320 for (i = 0; i <= 143; ++i)
4321 *p++ = 8;
4322 for (; i <= 255; ++i)
4323 *p++ = 9;
4324 for (; i <= 279; ++i)
4325 *p++ = 7;
4326 for (; i <= 287; ++i)
4327 *p++ = 8;
4328 } else {
4329 for (counter = 0; counter < 3; counter++) {
4330 TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
4331 r->m_table_sizes[counter] += s_min_table_sizes[counter];
4332 }
4333 MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
4334 for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
4335 mz_uint s;
4336 TINFL_GET_BITS(14, s, 3);
4337 r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
4338 }
4339 r->m_table_sizes[2] = 19;
4340 }
4341 for (; (int)r->m_type >= 0; r->m_type--) {
4342 int tree_next, tree_cur;
4343 tinfl_huff_table *pTable;
4344 mz_uint i, j, used_syms, total, sym_index, next_code[17],
4345 total_syms[16];
4346 pTable = &r->m_tables[r->m_type];
4347 MZ_CLEAR_OBJ(total_syms);
4348 MZ_CLEAR_OBJ(pTable->m_look_up);
4349 MZ_CLEAR_OBJ(pTable->m_tree);
4350 for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
4351 total_syms[pTable->m_code_size[i]]++;
4352 used_syms = 0, total = 0;
4353 next_code[0] = next_code[1] = 0;
4354 for (i = 1; i <= 15; ++i) {
4355 used_syms += total_syms[i];
4356 next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
4357 }
4358 if ((65536 != total) && (used_syms > 1)) {
4359 TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
4360 }
4361 for (tree_next = -1, sym_index = 0;
4362 sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
4363 mz_uint rev_code = 0, l, cur_code,
4364 code_size = pTable->m_code_size[sym_index];
4365
4366 if (!code_size)
4367 continue;
4368 cur_code = next_code[code_size]++;
4369 for (l = code_size; l > 0; l--, cur_code >>= 1)
4370 rev_code = (rev_code << 1) | (cur_code & 1);
4371 if (code_size <= TINFL_FAST_LOOKUP_BITS) {
4372 mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
4373 while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
4374 pTable->m_look_up[rev_code] = k;
4375 rev_code += (1 << code_size);
4376 }
4377 continue;
4378 }
4379 if (0 ==
4380 (tree_cur = pTable->m_look_up[rev_code &
4381 (TINFL_FAST_LOOKUP_SIZE - 1)])) {
4382 pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
4383 (mz_int16)tree_next;
4384 tree_cur = tree_next;
4385 tree_next -= 2;
4386 }
4387 rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
4388 for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
4389 tree_cur -= ((rev_code >>= 1) & 1);
4390 if (!pTable->m_tree[-tree_cur - 1]) {
4391 pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
4392 tree_cur = tree_next;
4393 tree_next -= 2;
4394 } else
4395 tree_cur = pTable->m_tree[-tree_cur - 1];
4396 }
4397 tree_cur -= ((rev_code >>= 1) & 1);
4398 (void)rev_code; // unused
4399 pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
4400 }
4401 if (r->m_type == 2) {
4402 for (counter = 0;
4403 counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
4404 mz_uint s;
4405 TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
4406 if (dist < 16) {
4407 r->m_len_codes[counter++] = (mz_uint8)dist;
4408 continue;
4409 }
4410 if ((dist == 16) && (!counter)) {
4411 TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
4412 }
4413 num_extra = "\02\03\07"[dist - 16];
4414 TINFL_GET_BITS(18, s, num_extra);
4415 s += "\03\03\013"[dist - 16];
4416 TINFL_MEMSET(r->m_len_codes + counter,
4417 (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
4418 counter += s;
4419 }
4420 if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
4421 TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
4422 }
4423 TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
4424 r->m_table_sizes[0]);
4425 TINFL_MEMCPY(r->m_tables[1].m_code_size,
4426 r->m_len_codes + r->m_table_sizes[0],
4427 r->m_table_sizes[1]);
4428 }
4429 }
4430 for (;;) {
4431 mz_uint8 *pSrc;
4432 for (;;) {
4433 if (((pIn_buf_end - pIn_buf_cur) < 4) ||
4434 ((pOut_buf_end - pOut_buf_cur) < 2)) {
4435 TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
4436 if (counter >= 256)
4437 break;
4438 while (pOut_buf_cur >= pOut_buf_end) {
4439 TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
4440 }
4441 *pOut_buf_cur++ = (mz_uint8)counter;
4442 } else {
4443 int sym2;
4444 mz_uint code_len;
4445 #if TINFL_USE_64BIT_BITBUF
4446 if (num_bits < 30) {
4447 bit_buf |=
4448 (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
4449 pIn_buf_cur += 4;
4450 num_bits += 32;
4451 }
4452 #else
4453 if (num_bits < 15) {
4454 bit_buf |=
4455 (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
4456 pIn_buf_cur += 2;
4457 num_bits += 16;
4458 }
4459 #endif
4460 if ((sym2 =
4461 r->m_tables[0]
4462 .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
4463 0)
4464 code_len = sym2 >> 9;
4465 else {
4466 code_len = TINFL_FAST_LOOKUP_BITS;
4467 do {
4468 sym2 = r->m_tables[0]
4469 .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
4470 } while (sym2 < 0);
4471 }
4472 counter = sym2;
4473 bit_buf >>= code_len;
4474 num_bits -= code_len;
4475 if (counter & 256)
4476 break;
4477
4478 #if !TINFL_USE_64BIT_BITBUF
4479 if (num_bits < 15) {
4480 bit_buf |=
4481 (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
4482 pIn_buf_cur += 2;
4483 num_bits += 16;
4484 }
4485 #endif
4486 if ((sym2 =
4487 r->m_tables[0]
4488 .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
4489 0)
4490 code_len = sym2 >> 9;
4491 else {
4492 code_len = TINFL_FAST_LOOKUP_BITS;
4493 do {
4494 sym2 = r->m_tables[0]
4495 .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
4496 } while (sym2 < 0);
4497 }
4498 bit_buf >>= code_len;
4499 num_bits -= code_len;
4500
4501 pOut_buf_cur[0] = (mz_uint8)counter;
4502 if (sym2 & 256) {
4503 pOut_buf_cur++;
4504 counter = sym2;
4505 break;
4506 }
4507 pOut_buf_cur[1] = (mz_uint8)sym2;
4508 pOut_buf_cur += 2;
4509 }
4510 }
4511 if ((counter &= 511) == 256)
4512 break;
4513
4514 num_extra = s_length_extra[counter - 257];
4515 counter = s_length_base[counter - 257];
4516 if (num_extra) {
4517 mz_uint extra_bits;
4518 TINFL_GET_BITS(25, extra_bits, num_extra);
4519 counter += extra_bits;
4520 }
4521
4522 TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
4523 num_extra = s_dist_extra[dist];
4524 dist = s_dist_base[dist];
4525 if (num_extra) {
4526 mz_uint extra_bits;
4527 TINFL_GET_BITS(27, extra_bits, num_extra);
4528 dist += extra_bits;
4529 }
4530
4531 dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
4532 if ((dist == 0 || dist > dist_from_out_buf_start ||
4533 dist_from_out_buf_start == 0) &&
4534 (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
4535 TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
4536 }
4537
4538 pSrc = pOut_buf_start +
4539 ((dist_from_out_buf_start - dist) & out_buf_size_mask);
4540
4541 if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
4542 while (counter--) {
4543 while (pOut_buf_cur >= pOut_buf_end) {
4544 TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
4545 }
4546 *pOut_buf_cur++ =
4547 pOut_buf_start[(dist_from_out_buf_start++ - dist) &
4548 out_buf_size_mask];
4549 }
4550 continue;
4551 }
4552 #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
4553 else if ((counter >= 9) && (counter <= dist)) {
4554 const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
4555 do {
4556 #ifdef MINIZ_UNALIGNED_USE_MEMCPY
4557 memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32) * 2);
4558 #else
4559 ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
4560 ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
4561 #endif
4562 pOut_buf_cur += 8;
4563 } while ((pSrc += 8) < pSrc_end);
4564 if ((counter &= 7) < 3) {
4565 if (counter) {
4566 pOut_buf_cur[0] = pSrc[0];
4567 if (counter > 1)
4568 pOut_buf_cur[1] = pSrc[1];
4569 pOut_buf_cur += counter;
4570 }
4571 continue;
4572 }
4573 }
4574 #endif
4575 while (counter > 2) {
4576 pOut_buf_cur[0] = pSrc[0];
4577 pOut_buf_cur[1] = pSrc[1];
4578 pOut_buf_cur[2] = pSrc[2];
4579 pOut_buf_cur += 3;
4580 pSrc += 3;
4581 counter -= 3;
4582 }
4583 if (counter > 0) {
4584 pOut_buf_cur[0] = pSrc[0];
4585 if (counter > 1)
4586 pOut_buf_cur[1] = pSrc[1];
4587 pOut_buf_cur += counter;
4588 }
4589 }
4590 }
4591 } while (!(r->m_final & 1));
4592
4593 /* Ensure byte alignment and put back any bytes from the bitbuf if we've
4594 * looked ahead too far on gzip, or other Deflate streams followed by
4595 * arbitrary data. */
4596 /* I'm being super conservative here. A number of simplifications can be made
4597 * to the byte alignment part, and the Adler32 check shouldn't ever need to
4598 * worry about reading from the bitbuf now. */
4599 TINFL_SKIP_BITS(32, num_bits & 7);
4600 while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) {
4601 --pIn_buf_cur;
4602 num_bits -= 8;
4603 }
4604 bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);
4605 MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end
4606 of non-deflate/zlib streams with following data (such
4607 as gzip streams). */
4608
4609 if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
4610 for (counter = 0; counter < 4; ++counter) {
4611 mz_uint s;
4612 if (num_bits)
4613 TINFL_GET_BITS(41, s, 8);
4614 else
4615 TINFL_GET_BYTE(42, s);
4616 r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
4617 }
4618 }
4619 TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
4620
4621 TINFL_CR_FINISH
4622
4623 common_exit:
4624 /* As long as we aren't telling the caller that we NEED more input to make
4625 * forward progress: */
4626 /* Put back any bytes from the bitbuf in case we've looked ahead too far on
4627 * gzip, or other Deflate streams followed by arbitrary data. */
4628 /* We need to be very careful here to NOT push back any bytes we definitely
4629 * know we need to make forward progress, though, or we'll lock the caller up
4630 * into an inf loop. */
4631 if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) &&
4632 (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) {
4633 while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) {
4634 --pIn_buf_cur;
4635 num_bits -= 8;
4636 }
4637 }
4638 r->m_num_bits = num_bits;
4639 r->m_bit_buf =
4640 bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1);
4641 r->m_dist = dist;
4642 r->m_counter = counter;
4643 r->m_num_extra = num_extra;
4644 r->m_dist_from_out_buf_start = dist_from_out_buf_start;
4645 *pIn_buf_size = pIn_buf_cur - pIn_buf_next;
4646 *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
4647 if ((decomp_flags &
4648 (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
4649 (status >= 0)) {
4650 const mz_uint8 *ptr = pOut_buf_next;
4651 size_t buf_len = *pOut_buf_size;
4652 mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
4653 s2 = r->m_check_adler32 >> 16;
4654 size_t block_len = buf_len % 5552;
4655 while (buf_len) {
4656 for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
4657 s1 += ptr[0], s2 += s1;
4658 s1 += ptr[1], s2 += s1;
4659 s1 += ptr[2], s2 += s1;
4660 s1 += ptr[3], s2 += s1;
4661 s1 += ptr[4], s2 += s1;
4662 s1 += ptr[5], s2 += s1;
4663 s1 += ptr[6], s2 += s1;
4664 s1 += ptr[7], s2 += s1;
4665 }
4666 for (; i < block_len; ++i)
4667 s1 += *ptr++, s2 += s1;
4668 s1 %= 65521U, s2 %= 65521U;
4669 buf_len -= block_len;
4670 block_len = 5552;
4671 }
4672 r->m_check_adler32 = (s2 << 16) + s1;
4673 if ((status == TINFL_STATUS_DONE) &&
4674 (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
4675 (r->m_check_adler32 != r->m_z_adler32))
4676 status = TINFL_STATUS_ADLER32_MISMATCH;
4677 }
4678 return status;
4679 }
4680
4681 /* Higher level helper functions. */
4682 void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
4683 size_t *pOut_len, int flags) {
4684 tinfl_decompressor decomp;
4685 void *pBuf = NULL, *pNew_buf;
4686 size_t src_buf_ofs = 0, out_buf_capacity = 0;
4687 *pOut_len = 0;
4688 tinfl_init(&decomp);
4689 for (;;) {
4690 size_t src_buf_size = src_buf_len - src_buf_ofs,
4691 dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
4692 tinfl_status status = tinfl_decompress(
4693 &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
4694 (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
4695 &dst_buf_size,
4696 (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
4697 TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
4698 if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
4699 MZ_FREE(pBuf);
4700 *pOut_len = 0;
4701 return NULL;
4702 }
4703 src_buf_ofs += src_buf_size;
4704 *pOut_len += dst_buf_size;
4705 if (status == TINFL_STATUS_DONE)
4706 break;
4707 new_out_buf_capacity = out_buf_capacity * 2;
4708 if (new_out_buf_capacity < 128)
4709 new_out_buf_capacity = 128;
4710 pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
4711 if (!pNew_buf) {
4712 MZ_FREE(pBuf);
4713 *pOut_len = 0;
4714 return NULL;
4715 }
4716 pBuf = pNew_buf;
4717 out_buf_capacity = new_out_buf_capacity;
4718 }
4719 return pBuf;
4720 }
4721
4722 size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
4723 const void *pSrc_buf, size_t src_buf_len,
4724 int flags) {
4725 tinfl_decompressor decomp;
4726 tinfl_status status;
4727 tinfl_init(&decomp);
4728 status =
4729 tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
4730 (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
4731 (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
4732 TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
4733 return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
4734 : out_buf_len;
4735 }
4736
4737 int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
4738 tinfl_put_buf_func_ptr pPut_buf_func,
4739 void *pPut_buf_user, int flags) {
4740 int result = 0;
4741 tinfl_decompressor decomp;
4742 mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
4743 size_t in_buf_ofs = 0, dict_ofs = 0;
4744 if (!pDict)
4745 return TINFL_STATUS_FAILED;
4746 tinfl_init(&decomp);
4747 for (;;) {
4748 size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
4749 dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
4750 tinfl_status status =
4751 tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
4752 &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
4753 (flags & ~(TINFL_FLAG_HAS_MORE_INPUT |
4754 TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
4755 in_buf_ofs += in_buf_size;
4756 if ((dst_buf_size) &&
4757 (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
4758 break;
4759 if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
4760 result = (status == TINFL_STATUS_DONE);
4761 break;
4762 }
4763 dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
4764 }
4765 MZ_FREE(pDict);
4766 *pIn_buf_size = in_buf_ofs;
4767 return result;
4768 }
4769
4770 #ifndef MINIZ_NO_MALLOC
4771 tinfl_decompressor *tinfl_decompressor_alloc(void) {
4772 tinfl_decompressor *pDecomp =
4773 (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor));
4774 if (pDecomp)
4775 tinfl_init(pDecomp);
4776 return pDecomp;
4777 }
4778
4779 void tinfl_decompressor_free(tinfl_decompressor *pDecomp) { MZ_FREE(pDecomp); }
4780 #endif
4781
4782 #ifdef __cplusplus
4783 }
4784 #endif
4785 /**************************************************************************
4786 *
4787 * Copyright 2013-2014 RAD Game Tools and Valve Software
4788 * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
4789 * Copyright 2016 Martin Raiber
4790 * All Rights Reserved.
4791 *
4792 * Permission is hereby granted, free of charge, to any person obtaining a copy
4793 * of this software and associated documentation files (the "Software"), to deal
4794 * in the Software without restriction, including without limitation the rights
4795 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4796 * copies of the Software, and to permit persons to whom the Software is
4797 * furnished to do so, subject to the following conditions:
4798 *
4799 * The above copyright notice and this permission notice shall be included in
4800 * all copies or substantial portions of the Software.
4801 *
4802 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4803 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4804 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4805 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4806 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4807 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4808 * THE SOFTWARE.
4809 *
4810 **************************************************************************/
4811
4812 #ifndef MINIZ_NO_ARCHIVE_APIS
4813
4814 #ifdef __cplusplus
4815 extern "C" {
4816 #endif
4817
4818 /* ------------------- .ZIP archive reading */
4819
4820 #ifdef MINIZ_NO_STDIO
4821 #define MZ_FILE void *
4822 #else
4823 #include <sys/stat.h>
4824
4825 #if defined(_MSC_VER)
4826 #include <windows.h>
4827 #ifndef MINIZ_NO_TIME
4828 #include <sys/utime.h>
4829 #endif
4830 static wchar_t *str2wstr(const char *str) {
4831 size_t len = strlen(str) + 1;
4832 wchar_t *wstr = (wchar_t *)malloc(len * sizeof(wchar_t));
4833 MultiByteToWideChar(CP_UTF8, 0, str, (int)(len * sizeof(char)), wstr,
4834 (int)len);
4835 return wstr;
4836 }
4837
4838 static FILE *mz_fopen(const char *pFilename, const char *pMode) {
4839 FILE *pFile = NULL;
4840 wchar_t *wFilename = str2wstr(pFilename);
4841 wchar_t *wMode = str2wstr(pMode);
4842
4843 #ifdef ZIP_ENABLE_SHARABLE_FILE_OPEN
4844 pFile = _wfopen(wFilename, wMode);
4845 #else
4846 _wfopen_s(&pFile, wFilename, wMode);
4847 #endif
4848 free(wFilename);
4849 free(wMode);
4850
4851 return pFile;
4852 }
4853
4854 static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
4855 FILE *pFile = NULL;
4856 int res = 0;
4857
4858 wchar_t *wPath = str2wstr(pPath);
4859 wchar_t *wMode = str2wstr(pMode);
4860
4861 #ifdef ZIP_ENABLE_SHARABLE_FILE_OPEN
4862 pFile = _wfreopen(wPath, wMode, pStream);
4863 #else
4864 res = _wfreopen_s(&pFile, wPath, wMode, pStream);
4865 #endif
4866
4867 free(wPath);
4868 free(wMode);
4869
4870 #ifndef ZIP_ENABLE_SHARABLE_FILE_OPEN
4871 if (res) {
4872 return NULL;
4873 }
4874 #endif
4875
4876 return pFile;
4877 }
4878
4879 static int mz_stat(const char *pPath, struct _stat64 *buffer) {
4880 wchar_t *wPath = str2wstr(pPath);
4881 int res = _wstat64(wPath, buffer);
4882
4883 free(wPath);
4884
4885 return res;
4886 }
4887
4888 static int mz_mkdir(const char *pDirname) {
4889 wchar_t *wDirname = str2wstr(pDirname);
4890 int res = _wmkdir(wDirname);
4891
4892 free(wDirname);
4893
4894 return res;
4895 }
4896
4897 #define MZ_FOPEN mz_fopen
4898 #define MZ_FCLOSE fclose
4899 #define MZ_FREAD fread
4900 #define MZ_FWRITE fwrite
4901 #define MZ_FTELL64 _ftelli64
4902 #define MZ_FSEEK64 _fseeki64
4903 #define MZ_FILE_STAT_STRUCT _stat64
4904 #define MZ_FILE_STAT mz_stat
4905 #define MZ_FFLUSH fflush
4906 #define MZ_FREOPEN mz_freopen
4907 #define MZ_DELETE_FILE remove
4908 #define MZ_MKDIR(d) mz_mkdir(d)
4909
4910 #elif defined(__MINGW32__) || defined(__MINGW64__)
4911 #include <windows.h>
4912 #ifndef MINIZ_NO_TIME
4913 #include <sys/utime.h>
4914 #endif
4915
4916 #define MZ_FOPEN(f, m) fopen(f, m)
4917 #define MZ_FCLOSE fclose
4918 #define MZ_FREAD fread
4919 #define MZ_FWRITE fwrite
4920 #define MZ_FTELL64 ftell
4921 #define MZ_FSEEK64 fseek
4922 #define MZ_FILE_STAT_STRUCT stat
4923 #define MZ_FILE_STAT stat
4924 #define MZ_FFLUSH fflush
4925 #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
4926 #define MZ_DELETE_FILE remove
4927 #define MZ_MKDIR(d) _mkdir(d)
4928
4929 #elif defined(__TINYC__)
4930 #ifndef MINIZ_NO_TIME
4931 #include <sys/utime.h>
4932 #endif
4933
4934 #define MZ_FOPEN(f, m) fopen(f, m)
4935 #define MZ_FCLOSE fclose
4936 #define MZ_FREAD fread
4937 #define MZ_FWRITE fwrite
4938 #define MZ_FTELL64 ftell
4939 #define MZ_FSEEK64 fseek
4940 #define MZ_FILE_STAT_STRUCT stat
4941 #define MZ_FILE_STAT stat
4942 #define MZ_FFLUSH fflush
4943 #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
4944 #define MZ_DELETE_FILE remove
4945 #if defined(_WIN32) || defined(_WIN64)
4946 #define MZ_MKDIR(d) _mkdir(d)
4947 #else
4948 #define MZ_MKDIR(d) mkdir(d, 0755)
4949 #endif
4950
4951 #elif defined(__USE_LARGEFILE64) /* gcc, clang */
4952 #ifndef MINIZ_NO_TIME
4953 #include <utime.h>
4954 #endif
4955
4956 #define MZ_FOPEN(f, m) fopen64(f, m)
4957 #define MZ_FCLOSE fclose
4958 #define MZ_FREAD fread
4959 #define MZ_FWRITE fwrite
4960 #define MZ_FTELL64 ftello64
4961 #define MZ_FSEEK64 fseeko64
4962 #define MZ_FILE_STAT_STRUCT stat64
4963 #define MZ_FILE_STAT stat64
4964 #define MZ_FFLUSH fflush
4965 #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
4966 #define MZ_DELETE_FILE remove
4967 #define MZ_MKDIR(d) mkdir(d, 0755)
4968
4969 #elif defined(__APPLE__)
4970 #ifndef MINIZ_NO_TIME
4971 #include <utime.h>
4972 #endif
4973
4974 #define MZ_FOPEN(f, m) fopen(f, m)
4975 #define MZ_FCLOSE fclose
4976 #define MZ_FREAD fread
4977 #define MZ_FWRITE fwrite
4978 #define MZ_FTELL64 ftello
4979 #define MZ_FSEEK64 fseeko
4980 #define MZ_FILE_STAT_STRUCT stat
4981 #define MZ_FILE_STAT stat
4982 #define MZ_FFLUSH fflush
4983 #define MZ_FREOPEN(p, m, s) freopen(p, m, s)
4984 #define MZ_DELETE_FILE remove
4985 #define MZ_MKDIR(d) mkdir(d, 0755)
4986
4987 #else
4988 #pragma message( \
4989 "Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.")
4990 #ifndef MINIZ_NO_TIME
4991 #include <utime.h>
4992 #endif
4993
4994 #define MZ_FOPEN(f, m) fopen(f, m)
4995 #define MZ_FCLOSE fclose
4996 #define MZ_FREAD fread
4997 #define MZ_FWRITE fwrite
4998 #ifdef __STRICT_ANSI__
4999 #define MZ_FTELL64 ftell
5000 #define MZ_FSEEK64 fseek
5001 #else
5002 #define MZ_FTELL64 ftello
5003 #define MZ_FSEEK64 fseeko
5004 #endif
5005 #define MZ_FILE_STAT_STRUCT stat
5006 #define MZ_FILE_STAT stat
5007 #define MZ_FFLUSH fflush
5008 #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
5009 #define MZ_DELETE_FILE remove
5010 #define MZ_MKDIR(d) mkdir(d, 0755)
5011
5012 #endif /* #ifdef _MSC_VER */
5013 #endif /* #ifdef MINIZ_NO_STDIO */
5014
5015 #ifndef CHMOD
5016 // Upon successful completion, a value of 0 is returned.
5017 // Otherwise, a value of -1 is returned and errno is set to indicate the error.
5018 // int chmod(const char *path, mode_t mode);
5019 #define CHMOD(f, m) chmod(f, m)
5020 #endif
5021
5022 #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
5023
5024 /* Various ZIP archive enums. To completely avoid cross platform compiler
5025 * alignment and platform endian issues, miniz.c doesn't use structs for any of
5026 * this stuff. */
5027 enum {
5028 /* ZIP archive identifiers and record sizes */
5029 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
5030 MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
5031 MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
5032 MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
5033 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
5034 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
5035
5036 /* ZIP64 archive identifier and record sizes */
5037 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50,
5038 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50,
5039 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56,
5040 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20,
5041 MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001,
5042 MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50,
5043 MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24,
5044 MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16,
5045
5046 /* Central directory header record offsets */
5047 MZ_ZIP_CDH_SIG_OFS = 0,
5048 MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
5049 MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
5050 MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
5051 MZ_ZIP_CDH_METHOD_OFS = 10,
5052 MZ_ZIP_CDH_FILE_TIME_OFS = 12,
5053 MZ_ZIP_CDH_FILE_DATE_OFS = 14,
5054 MZ_ZIP_CDH_CRC32_OFS = 16,
5055 MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
5056 MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
5057 MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
5058 MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
5059 MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
5060 MZ_ZIP_CDH_DISK_START_OFS = 34,
5061 MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
5062 MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
5063 MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
5064
5065 /* Local directory header offsets */
5066 MZ_ZIP_LDH_SIG_OFS = 0,
5067 MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
5068 MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
5069 MZ_ZIP_LDH_METHOD_OFS = 8,
5070 MZ_ZIP_LDH_FILE_TIME_OFS = 10,
5071 MZ_ZIP_LDH_FILE_DATE_OFS = 12,
5072 MZ_ZIP_LDH_CRC32_OFS = 14,
5073 MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
5074 MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
5075 MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
5076 MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
5077 MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3,
5078
5079 /* End of central directory offsets */
5080 MZ_ZIP_ECDH_SIG_OFS = 0,
5081 MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
5082 MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
5083 MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
5084 MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
5085 MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
5086 MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
5087 MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
5088
5089 /* ZIP64 End of central directory locator offsets */
5090 MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */
5091 MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */
5092 MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */
5093 MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */
5094
5095 /* ZIP64 End of central directory header offsets */
5096 MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */
5097 MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */
5098 MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */
5099 MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */
5100 MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */
5101 MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */
5102 MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */
5103 MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */
5104 MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */
5105 MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */
5106 MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0,
5107 MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10,
5108 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1,
5109 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32,
5110 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64,
5111 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192,
5112 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11
5113 };
5114
5115 typedef struct {
5116 void *m_p;
5117 size_t m_size, m_capacity;
5118 mz_uint m_element_size;
5119 } mz_zip_array;
5120
5121 struct mz_zip_internal_state_tag {
5122 mz_zip_array m_central_dir;
5123 mz_zip_array m_central_dir_offsets;
5124 mz_zip_array m_sorted_central_dir_offsets;
5125
5126 /* The flags passed in when the archive is initially opened. */
5127 uint32_t m_init_flags;
5128
5129 /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc.
5130 */
5131 mz_bool m_zip64;
5132
5133 /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64
5134 * will also be slammed to true too, even if we didn't find a zip64 end of
5135 * central dir header, etc.) */
5136 mz_bool m_zip64_has_extended_info_fields;
5137
5138 /* These fields are used by the file, FILE, memory, and memory/heap read/write
5139 * helpers. */
5140 MZ_FILE *m_pFile;
5141 mz_uint64 m_file_archive_start_ofs;
5142
5143 void *m_pMem;
5144 size_t m_mem_size;
5145 size_t m_mem_capacity;
5146 };
5147
5148 #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
5149 (array_ptr)->m_element_size = element_size
5150
5151 #if defined(DEBUG) || defined(_DEBUG)
5152 static MZ_FORCEINLINE mz_uint
5153 mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) {
5154 MZ_ASSERT(index < pArray->m_size);
5155 return index;
5156 }
5157 #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
5158 ((element_type *)((array_ptr) \
5159 ->m_p))[mz_zip_array_range_check(array_ptr, index)]
5160 #else
5161 #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
5162 ((element_type *)((array_ptr)->m_p))[index]
5163 #endif
5164
5165 static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray,
5166 mz_uint32 element_size) {
5167 memset(pArray, 0, sizeof(mz_zip_array));
5168 pArray->m_element_size = element_size;
5169 }
5170
5171 static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
5172 mz_zip_array *pArray) {
5173 pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
5174 memset(pArray, 0, sizeof(mz_zip_array));
5175 }
5176
5177 static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
5178 mz_zip_array *pArray,
5179 size_t min_new_capacity,
5180 mz_uint growing) {
5181 void *pNew_p;
5182 size_t new_capacity = min_new_capacity;
5183 MZ_ASSERT(pArray->m_element_size);
5184 if (pArray->m_capacity >= min_new_capacity)
5185 return MZ_TRUE;
5186 if (growing) {
5187 new_capacity = MZ_MAX(1, pArray->m_capacity);
5188 while (new_capacity < min_new_capacity)
5189 new_capacity *= 2;
5190 }
5191 if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
5192 pArray->m_element_size, new_capacity)))
5193 return MZ_FALSE;
5194 pArray->m_p = pNew_p;
5195 pArray->m_capacity = new_capacity;
5196 return MZ_TRUE;
5197 }
5198
5199 static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip,
5200 mz_zip_array *pArray,
5201 size_t new_capacity,
5202 mz_uint growing) {
5203 if (new_capacity > pArray->m_capacity) {
5204 if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
5205 return MZ_FALSE;
5206 }
5207 return MZ_TRUE;
5208 }
5209
5210 static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip,
5211 mz_zip_array *pArray,
5212 size_t new_size,
5213 mz_uint growing) {
5214 if (new_size > pArray->m_capacity) {
5215 if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
5216 return MZ_FALSE;
5217 }
5218 pArray->m_size = new_size;
5219 return MZ_TRUE;
5220 }
5221
5222 static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip,
5223 mz_zip_array *pArray,
5224 size_t n) {
5225 return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
5226 }
5227
5228 static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip,
5229 mz_zip_array *pArray,
5230 const void *pElements,
5231 size_t n) {
5232 size_t orig_size = pArray->m_size;
5233 if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
5234 return MZ_FALSE;
5235 if (n > 0)
5236 memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
5237 pElements, n * pArray->m_element_size);
5238 return MZ_TRUE;
5239 }
5240
5241 #ifndef MINIZ_NO_TIME
5242 static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) {
5243 struct tm tm;
5244 memset(&tm, 0, sizeof(tm));
5245 tm.tm_isdst = -1;
5246 tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
5247 tm.tm_mon = ((dos_date >> 5) & 15) - 1;
5248 tm.tm_mday = dos_date & 31;
5249 tm.tm_hour = (dos_time >> 11) & 31;
5250 tm.tm_min = (dos_time >> 5) & 63;
5251 tm.tm_sec = (dos_time << 1) & 62;
5252 return mktime(&tm);
5253 }
5254
5255 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
5256 static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time,
5257 mz_uint16 *pDOS_date) {
5258 #ifdef _MSC_VER
5259 struct tm tm_struct;
5260 struct tm *tm = &tm_struct;
5261 errno_t err = localtime_s(tm, &time);
5262 if (err) {
5263 *pDOS_date = 0;
5264 *pDOS_time = 0;
5265 return;
5266 }
5267 #else
5268 struct tm *tm = localtime(&time);
5269 #endif /* #ifdef _MSC_VER */
5270
5271 *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
5272 ((tm->tm_sec) >> 1));
5273 *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
5274 ((tm->tm_mon + 1) << 5) + tm->tm_mday);
5275 }
5276 #endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */
5277
5278 #ifndef MINIZ_NO_STDIO
5279 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
5280 static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
5281 MZ_TIME_T *pTime) {
5282 struct MZ_FILE_STAT_STRUCT file_stat;
5283
5284 /* On Linux with x86 glibc, this call will fail on large files (I think >=
5285 * 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */
5286 if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
5287 return MZ_FALSE;
5288
5289 *pTime = file_stat.st_mtime;
5290
5291 return MZ_TRUE;
5292 }
5293 #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/
5294
5295 static mz_bool mz_zip_set_file_times(const char *pFilename,
5296 MZ_TIME_T access_time,
5297 MZ_TIME_T modified_time) {
5298 struct utimbuf t;
5299
5300 memset(&t, 0, sizeof(t));
5301 t.actime = access_time;
5302 t.modtime = modified_time;
5303
5304 return !utime(pFilename, &t);
5305 }
5306 #endif /* #ifndef MINIZ_NO_STDIO */
5307 #endif /* #ifndef MINIZ_NO_TIME */
5308
5309 static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip,
5310 mz_zip_error err_num) {
5311 if (pZip)
5312 pZip->m_last_error = err_num;
5313 return MZ_FALSE;
5314 }
5315
5316 static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
5317 mz_uint flags) {
5318 (void)flags;
5319 if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
5320 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
5321
5322 if (!pZip->m_pAlloc)
5323 pZip->m_pAlloc = miniz_def_alloc_func;
5324 if (!pZip->m_pFree)
5325 pZip->m_pFree = miniz_def_free_func;
5326 if (!pZip->m_pRealloc)
5327 pZip->m_pRealloc = miniz_def_realloc_func;
5328
5329 pZip->m_archive_size = 0;
5330 pZip->m_central_directory_file_ofs = 0;
5331 pZip->m_total_files = 0;
5332 pZip->m_last_error = MZ_ZIP_NO_ERROR;
5333
5334 if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
5335 pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
5336 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
5337
5338 memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
5339 MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
5340 sizeof(mz_uint8));
5341 MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
5342 sizeof(mz_uint32));
5343 MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
5344 sizeof(mz_uint32));
5345 pZip->m_pState->m_init_flags = flags;
5346 pZip->m_pState->m_zip64 = MZ_FALSE;
5347 pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE;
5348
5349 pZip->m_zip_mode = MZ_ZIP_MODE_READING;
5350
5351 return MZ_TRUE;
5352 }
5353
5354 static MZ_FORCEINLINE mz_bool
5355 mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
5356 const mz_zip_array *pCentral_dir_offsets,
5357 mz_uint l_index, mz_uint r_index) {
5358 const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
5359 pCentral_dir_array, mz_uint8,
5360 MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
5361 l_index)),
5362 *pE;
5363 const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(
5364 pCentral_dir_array, mz_uint8,
5365 MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
5366 mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
5367 r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
5368 mz_uint8 l = 0, r = 0;
5369 pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
5370 pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
5371 pE = pL + MZ_MIN(l_len, r_len);
5372 while (pL < pE) {
5373 if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
5374 break;
5375 pL++;
5376 pR++;
5377 }
5378 return (pL == pE) ? (l_len < r_len) : (l < r);
5379 }
5380
5381 #define MZ_SWAP_UINT32(a, b) \
5382 do { \
5383 mz_uint32 t = a; \
5384 a = b; \
5385 b = t; \
5386 } \
5387 MZ_MACRO_END
5388
5389 /* Heap sort of lowercased filenames, used to help accelerate plain central
5390 * directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
5391 * but it could allocate memory.) */
5392 static void
5393 mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) {
5394 mz_zip_internal_state *pState = pZip->m_pState;
5395 const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
5396 const mz_zip_array *pCentral_dir = &pState->m_central_dir;
5397 mz_uint32 *pIndices;
5398 mz_uint32 start, end;
5399 const mz_uint32 size = pZip->m_total_files;
5400
5401 if (size <= 1U)
5402 return;
5403
5404 pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets,
5405 mz_uint32, 0);
5406
5407 start = (size - 2U) >> 1U;
5408 for (;;) {
5409 mz_uint64 child, root = start;
5410 for (;;) {
5411 if ((child = (root << 1U) + 1U) >= size)
5412 break;
5413 child += (((child + 1U) < size) &&
5414 (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
5415 pIndices[child],
5416 pIndices[child + 1U])));
5417 if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
5418 pIndices[root], pIndices[child]))
5419 break;
5420 MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
5421 root = child;
5422 }
5423 if (!start)
5424 break;
5425 start--;
5426 }
5427
5428 end = size - 1;
5429 while (end > 0) {
5430 mz_uint64 child, root = 0;
5431 MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
5432 for (;;) {
5433 if ((child = (root << 1U) + 1U) >= end)
5434 break;
5435 child +=
5436 (((child + 1U) < end) &&
5437 mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
5438 pIndices[child], pIndices[child + 1U]));
5439 if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
5440 pIndices[root], pIndices[child]))
5441 break;
5442 MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
5443 root = child;
5444 }
5445 end--;
5446 }
5447 }
5448
5449 static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip,
5450 mz_uint32 record_sig,
5451 mz_uint32 record_size,
5452 mz_int64 *pOfs) {
5453 mz_int64 cur_file_ofs;
5454 mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
5455 mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
5456
5457 /* Basic sanity checks - reject files which are too small */
5458 if (pZip->m_archive_size < record_size)
5459 return MZ_FALSE;
5460
5461 /* Find the record by scanning the file from the end towards the beginning. */
5462 cur_file_ofs =
5463 MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
5464 for (;;) {
5465 int i,
5466 n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
5467
5468 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
5469 return MZ_FALSE;
5470
5471 for (i = n - 4; i >= 0; --i) {
5472 mz_uint s = MZ_READ_LE32(pBuf + i);
5473 if (s == record_sig) {
5474 if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size)
5475 break;
5476 }
5477 }
5478
5479 if (i >= 0) {
5480 cur_file_ofs += i;
5481 break;
5482 }
5483
5484 /* Give up if we've searched the entire file, or we've gone back "too far"
5485 * (~64kb) */
5486 if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
5487 (MZ_UINT16_MAX + record_size)))
5488 return MZ_FALSE;
5489
5490 cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
5491 }
5492
5493 *pOfs = cur_file_ofs;
5494 return MZ_TRUE;
5495 }
5496
5497 static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
5498 mz_uint flags) {
5499 mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0,
5500 cdir_disk_index = 0;
5501 mz_uint64 cdir_ofs = 0;
5502 mz_int64 cur_file_ofs = 0;
5503 const mz_uint8 *p;
5504
5505 mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
5506 mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
5507 mz_bool sort_central_dir =
5508 ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
5509 mz_uint32 zip64_end_of_central_dir_locator_u32
5510 [(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) /
5511 sizeof(mz_uint32)];
5512 mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32;
5513
5514 mz_uint32 zip64_end_of_central_dir_header_u32
5515 [(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
5516 sizeof(mz_uint32)];
5517 mz_uint8 *pZip64_end_of_central_dir =
5518 (mz_uint8 *)zip64_end_of_central_dir_header_u32;
5519
5520 mz_uint64 zip64_end_of_central_dir_ofs = 0;
5521
5522 /* Basic sanity checks - reject files which are too small, and check the first
5523 * 4 bytes of the file to make sure a local header is there. */
5524 if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
5525 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
5526
5527 if (!mz_zip_reader_locate_header_sig(
5528 pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG,
5529 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs))
5530 return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR);
5531
5532 /* Read and verify the end of central directory record. */
5533 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
5534 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
5535 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
5536 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
5537
5538 if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
5539 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
5540 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
5541
5542 if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE +
5543 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) {
5544 if (pZip->m_pRead(pZip->m_pIO_opaque,
5545 cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE,
5546 pZip64_locator,
5547 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) ==
5548 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) {
5549 if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) ==
5550 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) {
5551 zip64_end_of_central_dir_ofs = MZ_READ_LE64(
5552 pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS);
5553 if (zip64_end_of_central_dir_ofs >
5554 (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE))
5555 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
5556
5557 if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs,
5558 pZip64_end_of_central_dir,
5559 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) ==
5560 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) {
5561 if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) ==
5562 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) {
5563 pZip->m_pState->m_zip64 = MZ_TRUE;
5564 }
5565 }
5566 }
5567 }
5568 }
5569
5570 pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS);
5571 cdir_entries_on_this_disk =
5572 MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS);
5573 num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
5574 cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
5575 cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS);
5576 cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
5577
5578 if (pZip->m_pState->m_zip64) {
5579 mz_uint32 zip64_total_num_of_disks =
5580 MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS);
5581 mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(
5582 pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS);
5583 mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(
5584 pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS);
5585 mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(
5586 pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS);
5587 mz_uint64 zip64_size_of_central_directory =
5588 MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS);
5589
5590 if (zip64_size_of_end_of_central_dir_record <
5591 (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12))
5592 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5593
5594 if (zip64_total_num_of_disks != 1U)
5595 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);
5596
5597 /* Check for miniz's practical limits */
5598 if (zip64_cdir_total_entries > MZ_UINT32_MAX)
5599 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
5600
5601 pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries;
5602
5603 if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX)
5604 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
5605
5606 cdir_entries_on_this_disk =
5607 (mz_uint32)zip64_cdir_total_entries_on_this_disk;
5608
5609 /* Check for miniz's current practical limits (sorry, this should be enough
5610 * for millions of files) */
5611 if (zip64_size_of_central_directory > MZ_UINT32_MAX)
5612 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);
5613
5614 cdir_size = (mz_uint32)zip64_size_of_central_directory;
5615
5616 num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir +
5617 MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS);
5618
5619 cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir +
5620 MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS);
5621
5622 cdir_ofs =
5623 MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS);
5624 }
5625
5626 if (pZip->m_total_files != cdir_entries_on_this_disk)
5627 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);
5628
5629 if (((num_this_disk | cdir_disk_index) != 0) &&
5630 ((num_this_disk != 1) || (cdir_disk_index != 1)))
5631 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);
5632
5633 if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
5634 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5635
5636 if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
5637 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5638
5639 pZip->m_central_directory_file_ofs = cdir_ofs;
5640
5641 if (pZip->m_total_files) {
5642 mz_uint i, n;
5643 /* Read the entire central directory into a heap block, and allocate another
5644 * heap block to hold the unsorted central dir file record offsets, and
5645 * possibly another to hold the sorted indices. */
5646 if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
5647 MZ_FALSE)) ||
5648 (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
5649 pZip->m_total_files, MZ_FALSE)))
5650 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
5651
5652 if (sort_central_dir) {
5653 if (!mz_zip_array_resize(pZip,
5654 &pZip->m_pState->m_sorted_central_dir_offsets,
5655 pZip->m_total_files, MZ_FALSE))
5656 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
5657 }
5658
5659 if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
5660 pZip->m_pState->m_central_dir.m_p,
5661 cdir_size) != cdir_size)
5662 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
5663
5664 /* Now create an index into the central directory file records, do some
5665 * basic sanity checking on each record */
5666 p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
5667 for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
5668 mz_uint total_header_size, disk_index, bit_flags, filename_size,
5669 ext_data_size;
5670 mz_uint64 comp_size, decomp_size, local_header_ofs;
5671
5672 if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
5673 (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
5674 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5675
5676 MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
5677 i) =
5678 (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
5679
5680 if (sort_central_dir)
5681 MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
5682 mz_uint32, i) = i;
5683
5684 comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
5685 decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
5686 local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
5687 filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
5688 ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS);
5689
5690 if ((!pZip->m_pState->m_zip64_has_extended_info_fields) &&
5691 (ext_data_size) &&
5692 (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) ==
5693 MZ_UINT32_MAX)) {
5694 /* Attempt to find zip64 extended information field in the entry's extra
5695 * data */
5696 mz_uint32 extra_size_remaining = ext_data_size;
5697
5698 if (extra_size_remaining) {
5699 const mz_uint8 *pExtra_data;
5700 void *buf = NULL;
5701
5702 if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size >
5703 n) {
5704 buf = MZ_MALLOC(ext_data_size);
5705 if (buf == NULL)
5706 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
5707
5708 if (pZip->m_pRead(pZip->m_pIO_opaque,
5709 cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
5710 filename_size,
5711 buf, ext_data_size) != ext_data_size) {
5712 MZ_FREE(buf);
5713 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
5714 }
5715
5716 pExtra_data = (mz_uint8 *)buf;
5717 } else {
5718 pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size;
5719 }
5720
5721 do {
5722 mz_uint32 field_id;
5723 mz_uint32 field_data_size;
5724
5725 if (extra_size_remaining < (sizeof(mz_uint16) * 2)) {
5726 MZ_FREE(buf);
5727 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5728 }
5729
5730 field_id = MZ_READ_LE16(pExtra_data);
5731 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));
5732
5733 if ((field_data_size + sizeof(mz_uint16) * 2) >
5734 extra_size_remaining) {
5735 MZ_FREE(buf);
5736 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5737 }
5738
5739 if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) {
5740 /* Ok, the archive didn't have any zip64 headers but it uses a
5741 * zip64 extended information field so mark it as zip64 anyway
5742 * (this can occur with infozip's zip util when it reads
5743 * compresses files from stdin). */
5744 pZip->m_pState->m_zip64 = MZ_TRUE;
5745 pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE;
5746 break;
5747 }
5748
5749 pExtra_data += sizeof(mz_uint16) * 2 + field_data_size;
5750 extra_size_remaining =
5751 extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size;
5752 } while (extra_size_remaining);
5753
5754 MZ_FREE(buf);
5755 }
5756 }
5757
5758 /* I've seen archives that aren't marked as zip64 that uses zip64 ext
5759 * data, argh */
5760 if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) {
5761 if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
5762 (decomp_size != comp_size)) ||
5763 (decomp_size && !comp_size))
5764 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5765 }
5766
5767 disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
5768 if ((disk_index == MZ_UINT16_MAX) ||
5769 ((disk_index != num_this_disk) && (disk_index != 1)))
5770 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK);
5771
5772 if (comp_size != MZ_UINT32_MAX) {
5773 if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
5774 MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
5775 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5776 }
5777
5778 bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
5779 if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED)
5780 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);
5781
5782 if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
5783 MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
5784 MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
5785 MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
5786 n)
5787 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
5788
5789 n -= total_header_size;
5790 p += total_header_size;
5791 }
5792 }
5793
5794 if (sort_central_dir)
5795 mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
5796
5797 return MZ_TRUE;
5798 }
5799
5800 void mz_zip_zero_struct(mz_zip_archive *pZip) {
5801 if (pZip)
5802 MZ_CLEAR_OBJ(*pZip);
5803 }
5804
5805 static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip,
5806 mz_bool set_last_error) {
5807 mz_bool status = MZ_TRUE;
5808
5809 if (!pZip)
5810 return MZ_FALSE;
5811
5812 if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
5813 (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) {
5814 if (set_last_error)
5815 pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER;
5816
5817 return MZ_FALSE;
5818 }
5819
5820 if (pZip->m_pState) {
5821 mz_zip_internal_state *pState = pZip->m_pState;
5822 pZip->m_pState = NULL;
5823
5824 mz_zip_array_clear(pZip, &pState->m_central_dir);
5825 mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
5826 mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
5827
5828 #ifndef MINIZ_NO_STDIO
5829 if (pState->m_pFile) {
5830 if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) {
5831 if (MZ_FCLOSE(pState->m_pFile) == EOF) {
5832 if (set_last_error)
5833 pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED;
5834 status = MZ_FALSE;
5835 }
5836 }
5837 pState->m_pFile = NULL;
5838 }
5839 #endif /* #ifndef MINIZ_NO_STDIO */
5840
5841 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
5842 }
5843 pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
5844
5845 return status;
5846 }
5847
5848 mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
5849 return mz_zip_reader_end_internal(pZip, MZ_TRUE);
5850 }
5851 mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
5852 mz_uint flags) {
5853 if ((!pZip) || (!pZip->m_pRead))
5854 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
5855
5856 if (!mz_zip_reader_init_internal(pZip, flags))
5857 return MZ_FALSE;
5858
5859 pZip->m_zip_type = MZ_ZIP_TYPE_USER;
5860 pZip->m_archive_size = size;
5861
5862 if (!mz_zip_reader_read_central_dir(pZip, flags)) {
5863 mz_zip_reader_end_internal(pZip, MZ_FALSE);
5864 return MZ_FALSE;
5865 }
5866
5867 return MZ_TRUE;
5868 }
5869
5870 static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
5871 void *pBuf, size_t n) {
5872 mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
5873 size_t s = (file_ofs >= pZip->m_archive_size)
5874 ? 0
5875 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
5876 memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
5877 return s;
5878 }
5879
5880 mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
5881 size_t size, mz_uint flags) {
5882 if (!pMem)
5883 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
5884
5885 if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
5886 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
5887
5888 if (!mz_zip_reader_init_internal(pZip, flags))
5889 return MZ_FALSE;
5890
5891 pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY;
5892 pZip->m_archive_size = size;
5893 pZip->m_pRead = mz_zip_mem_read_func;
5894 pZip->m_pIO_opaque = pZip;
5895 pZip->m_pNeeds_keepalive = NULL;
5896
5897 #ifdef __cplusplus
5898 pZip->m_pState->m_pMem = const_cast<void *>(pMem);
5899 #else
5900 pZip->m_pState->m_pMem = (void *)pMem;
5901 #endif
5902
5903 pZip->m_pState->m_mem_size = size;
5904
5905 if (!mz_zip_reader_read_central_dir(pZip, flags)) {
5906 mz_zip_reader_end_internal(pZip, MZ_FALSE);
5907 return MZ_FALSE;
5908 }
5909
5910 return MZ_TRUE;
5911 }
5912
5913 #ifndef MINIZ_NO_STDIO
5914 static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
5915 void *pBuf, size_t n) {
5916 mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
5917 mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
5918
5919 file_ofs += pZip->m_pState->m_file_archive_start_ofs;
5920
5921 if (((mz_int64)file_ofs < 0) ||
5922 (((cur_ofs != (mz_int64)file_ofs)) &&
5923 (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
5924 return 0;
5925
5926 return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
5927 }
5928
5929 mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
5930 mz_uint32 flags) {
5931 return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0);
5932 }
5933
5934 mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename,
5935 mz_uint flags, mz_uint64 file_start_ofs,
5936 mz_uint64 archive_size) {
5937 mz_uint64 file_size;
5938 MZ_FILE *pFile;
5939
5940 if ((!pZip) || (!pFilename) ||
5941 ((archive_size) &&
5942 (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
5943 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
5944
5945 pFile = MZ_FOPEN(pFilename, "rb");
5946 if (!pFile)
5947 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
5948
5949 file_size = archive_size;
5950 if (!file_size) {
5951 if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
5952 MZ_FCLOSE(pFile);
5953 return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);
5954 }
5955
5956 file_size = MZ_FTELL64(pFile);
5957 }
5958
5959 /* TODO: Better sanity check archive_size and the # of actual remaining bytes
5960 */
5961
5962 if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) {
5963 MZ_FCLOSE(pFile);
5964 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
5965 }
5966
5967 if (!mz_zip_reader_init_internal(pZip, flags)) {
5968 MZ_FCLOSE(pFile);
5969 return MZ_FALSE;
5970 }
5971
5972 pZip->m_zip_type = MZ_ZIP_TYPE_FILE;
5973 pZip->m_pRead = mz_zip_file_read_func;
5974 pZip->m_pIO_opaque = pZip;
5975 pZip->m_pState->m_pFile = pFile;
5976 pZip->m_archive_size = file_size;
5977 pZip->m_pState->m_file_archive_start_ofs = file_start_ofs;
5978
5979 if (!mz_zip_reader_read_central_dir(pZip, flags)) {
5980 mz_zip_reader_end_internal(pZip, MZ_FALSE);
5981 return MZ_FALSE;
5982 }
5983
5984 return MZ_TRUE;
5985 }
5986
5987 mz_bool mz_zip_reader_init_file_v2_rpb(mz_zip_archive *pZip,
5988 const char *pFilename, mz_uint flags,
5989 mz_uint64 file_start_ofs,
5990 mz_uint64 archive_size) {
5991 mz_uint64 file_size;
5992 MZ_FILE *pFile;
5993
5994 if ((!pZip) || (!pFilename) ||
5995 ((archive_size) &&
5996 (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
5997 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
5998
5999 pFile = MZ_FOPEN(pFilename, "r+b");
6000 if (!pFile)
6001 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
6002
6003 file_size = archive_size;
6004 if (!file_size) {
6005 if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
6006 MZ_FCLOSE(pFile);
6007 return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);
6008 }
6009
6010 file_size = MZ_FTELL64(pFile);
6011 }
6012
6013 /* TODO: Better sanity check archive_size and the # of actual remaining bytes
6014 */
6015
6016 if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) {
6017 MZ_FCLOSE(pFile);
6018 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
6019 }
6020
6021 if (!mz_zip_reader_init_internal(pZip, flags)) {
6022 MZ_FCLOSE(pFile);
6023 return MZ_FALSE;
6024 }
6025
6026 pZip->m_zip_type = MZ_ZIP_TYPE_FILE;
6027 pZip->m_pRead = mz_zip_file_read_func;
6028 pZip->m_pIO_opaque = pZip;
6029 pZip->m_pState->m_pFile = pFile;
6030 pZip->m_archive_size = file_size;
6031 pZip->m_pState->m_file_archive_start_ofs = file_start_ofs;
6032
6033 if (!mz_zip_reader_read_central_dir(pZip, flags)) {
6034 mz_zip_reader_end_internal(pZip, MZ_FALSE);
6035 return MZ_FALSE;
6036 }
6037
6038 return MZ_TRUE;
6039 }
6040
6041 mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile,
6042 mz_uint64 archive_size, mz_uint flags) {
6043 mz_uint64 cur_file_ofs;
6044
6045 if ((!pZip) || (!pFile))
6046 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
6047
6048 cur_file_ofs = MZ_FTELL64(pFile);
6049
6050 if (!archive_size) {
6051 if (MZ_FSEEK64(pFile, 0, SEEK_END))
6052 return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);
6053
6054 archive_size = MZ_FTELL64(pFile) - cur_file_ofs;
6055
6056 if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
6057 return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE);
6058 }
6059
6060 if (!mz_zip_reader_init_internal(pZip, flags))
6061 return MZ_FALSE;
6062
6063 pZip->m_zip_type = MZ_ZIP_TYPE_CFILE;
6064 pZip->m_pRead = mz_zip_file_read_func;
6065
6066 pZip->m_pIO_opaque = pZip;
6067 pZip->m_pState->m_pFile = pFile;
6068 pZip->m_archive_size = archive_size;
6069 pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs;
6070
6071 if (!mz_zip_reader_read_central_dir(pZip, flags)) {
6072 mz_zip_reader_end_internal(pZip, MZ_FALSE);
6073 return MZ_FALSE;
6074 }
6075
6076 return MZ_TRUE;
6077 }
6078
6079 #endif /* #ifndef MINIZ_NO_STDIO */
6080
6081 static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip,
6082 mz_uint file_index) {
6083 if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files))
6084 return NULL;
6085 return &MZ_ZIP_ARRAY_ELEMENT(
6086 &pZip->m_pState->m_central_dir, mz_uint8,
6087 MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
6088 file_index));
6089 }
6090
6091 mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
6092 mz_uint file_index) {
6093 mz_uint m_bit_flag;
6094 const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);
6095 if (!p) {
6096 mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6097 return MZ_FALSE;
6098 }
6099
6100 m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
6101 return (m_bit_flag &
6102 (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED |
6103 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0;
6104 }
6105
6106 mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip,
6107 mz_uint file_index) {
6108 mz_uint bit_flag;
6109 mz_uint method;
6110
6111 const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);
6112 if (!p) {
6113 mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6114 return MZ_FALSE;
6115 }
6116
6117 method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
6118 bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
6119
6120 if ((method != 0) && (method != MZ_DEFLATED)) {
6121 mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);
6122 return MZ_FALSE;
6123 }
6124
6125 if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED |
6126 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) {
6127 mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);
6128 return MZ_FALSE;
6129 }
6130
6131 if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) {
6132 mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);
6133 return MZ_FALSE;
6134 }
6135
6136 return MZ_TRUE;
6137 }
6138
6139 mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
6140 mz_uint file_index) {
6141 mz_uint filename_len, attribute_mapping_id, external_attr;
6142 const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);
6143 if (!p) {
6144 mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6145 return MZ_FALSE;
6146 }
6147
6148 filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
6149 if (filename_len) {
6150 if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
6151 return MZ_TRUE;
6152 }
6153
6154 /* Bugfix: This code was also checking if the internal attribute was non-zero,
6155 * which wasn't correct. */
6156 /* Most/all zip writers (hopefully) set DOS file/directory attributes in the
6157 * low 16-bits, so check for the DOS directory flag and ignore the source OS
6158 * ID in the created by field. */
6159 /* FIXME: Remove this check? Is it necessary - we already check the filename.
6160 */
6161 attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8;
6162 (void)attribute_mapping_id;
6163
6164 external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
6165 if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) {
6166 return MZ_TRUE;
6167 }
6168
6169 return MZ_FALSE;
6170 }
6171
6172 static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip,
6173 mz_uint file_index,
6174 const mz_uint8 *pCentral_dir_header,
6175 mz_zip_archive_file_stat *pStat,
6176 mz_bool *pFound_zip64_extra_data) {
6177 mz_uint n;
6178 const mz_uint8 *p = pCentral_dir_header;
6179
6180 if (pFound_zip64_extra_data)
6181 *pFound_zip64_extra_data = MZ_FALSE;
6182
6183 if ((!p) || (!pStat))
6184 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6185
6186 /* Extract fields from the central directory record. */
6187 pStat->m_file_index = file_index;
6188 pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
6189 &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
6190 pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
6191 pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
6192 pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
6193 pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
6194 #ifndef MINIZ_NO_TIME
6195 pStat->m_time =
6196 mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
6197 MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
6198 #endif
6199 pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
6200 pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
6201 pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
6202 pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
6203 pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
6204 pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
6205
6206 /* Copy as much of the filename and comment as possible. */
6207 n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
6208 n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
6209 memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
6210 pStat->m_filename[n] = '\0';
6211
6212 n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
6213 n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
6214 pStat->m_comment_size = n;
6215 memcpy(pStat->m_comment,
6216 p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
6217 MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
6218 MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
6219 n);
6220 pStat->m_comment[n] = '\0';
6221
6222 /* Set some flags for convienance */
6223 pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index);
6224 pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index);
6225 pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index);
6226
6227 /* See if we need to read any zip64 extended information fields. */
6228 /* Confusingly, these zip64 fields can be present even on non-zip64 archives
6229 * (Debian zip on a huge files from stdin piped to stdout creates them). */
6230 if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size),
6231 pStat->m_local_header_ofs) == MZ_UINT32_MAX) {
6232 /* Attempt to find zip64 extended information field in the entry's extra
6233 * data */
6234 mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS);
6235
6236 if (extra_size_remaining) {
6237 const mz_uint8 *pExtra_data =
6238 p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
6239 MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
6240
6241 do {
6242 mz_uint32 field_id;
6243 mz_uint32 field_data_size;
6244
6245 if (extra_size_remaining < (sizeof(mz_uint16) * 2))
6246 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6247
6248 field_id = MZ_READ_LE16(pExtra_data);
6249 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));
6250
6251 if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining)
6252 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6253
6254 if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) {
6255 const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2;
6256 mz_uint32 field_data_remaining = field_data_size;
6257
6258 if (pFound_zip64_extra_data)
6259 *pFound_zip64_extra_data = MZ_TRUE;
6260
6261 if (pStat->m_uncomp_size == MZ_UINT32_MAX) {
6262 if (field_data_remaining < sizeof(mz_uint64))
6263 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6264
6265 pStat->m_uncomp_size = MZ_READ_LE64(pField_data);
6266 pField_data += sizeof(mz_uint64);
6267 field_data_remaining -= sizeof(mz_uint64);
6268 }
6269
6270 if (pStat->m_comp_size == MZ_UINT32_MAX) {
6271 if (field_data_remaining < sizeof(mz_uint64))
6272 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6273
6274 pStat->m_comp_size = MZ_READ_LE64(pField_data);
6275 pField_data += sizeof(mz_uint64);
6276 field_data_remaining -= sizeof(mz_uint64);
6277 }
6278
6279 if (pStat->m_local_header_ofs == MZ_UINT32_MAX) {
6280 if (field_data_remaining < sizeof(mz_uint64))
6281 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6282
6283 pStat->m_local_header_ofs = MZ_READ_LE64(pField_data);
6284 pField_data += sizeof(mz_uint64);
6285 (void)pField_data; // unused
6286
6287 field_data_remaining -= sizeof(mz_uint64);
6288 (void)field_data_remaining; // unused
6289 }
6290
6291 break;
6292 }
6293
6294 pExtra_data += sizeof(mz_uint16) * 2 + field_data_size;
6295 extra_size_remaining =
6296 extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size;
6297 } while (extra_size_remaining);
6298 }
6299 }
6300
6301 return MZ_TRUE;
6302 }
6303
6304 static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA,
6305 const char *pB, mz_uint len,
6306 mz_uint flags) {
6307 mz_uint i;
6308 if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
6309 return 0 == memcmp(pA, pB, len);
6310 for (i = 0; i < len; ++i)
6311 if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
6312 return MZ_FALSE;
6313 return MZ_TRUE;
6314 }
6315
6316 static MZ_FORCEINLINE int
6317 mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array,
6318 const mz_zip_array *pCentral_dir_offsets,
6319 mz_uint l_index, const char *pR, mz_uint r_len) {
6320 const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
6321 pCentral_dir_array, mz_uint8,
6322 MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
6323 l_index)),
6324 *pE;
6325 mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
6326 mz_uint8 l = 0, r = 0;
6327 pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
6328 pE = pL + MZ_MIN(l_len, r_len);
6329 while (pL < pE) {
6330 if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
6331 break;
6332 pL++;
6333 pR++;
6334 }
6335 return (pL == pE) ? (int)(l_len - r_len) : (l - r);
6336 }
6337
6338 static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip,
6339 const char *pFilename,
6340 mz_uint32 *pIndex) {
6341 mz_zip_internal_state *pState = pZip->m_pState;
6342 const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
6343 const mz_zip_array *pCentral_dir = &pState->m_central_dir;
6344 mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
6345 &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
6346 const uint32_t size = pZip->m_total_files;
6347 const mz_uint filename_len = (mz_uint)strlen(pFilename);
6348
6349 if (pIndex)
6350 *pIndex = 0;
6351
6352 if (size) {
6353 /* yes I could use uint32_t's, but then we would have to add some special
6354 * case checks in the loop, argh, and */
6355 /* honestly the major expense here on 32-bit CPU's will still be the
6356 * filename compare */
6357 mz_int64 l = 0, h = (mz_int64)size - 1;
6358
6359 while (l <= h) {
6360 mz_int64 m = l + ((h - l) >> 1);
6361 uint32_t file_index = pIndices[(uint32_t)m];
6362
6363 int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets,
6364 file_index, pFilename, filename_len);
6365 if (!comp) {
6366 if (pIndex)
6367 *pIndex = file_index;
6368 return MZ_TRUE;
6369 } else if (comp < 0)
6370 l = m + 1;
6371 else
6372 h = m - 1;
6373 }
6374 }
6375
6376 return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND);
6377 }
6378
6379 int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
6380 const char *pComment, mz_uint flags) {
6381 mz_uint32 index;
6382 if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index))
6383 return -1;
6384 else
6385 return (int)index;
6386 }
6387
6388 mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName,
6389 const char *pComment, mz_uint flags,
6390 mz_uint32 *pIndex) {
6391 mz_uint file_index;
6392 size_t name_len, comment_len;
6393
6394 if (pIndex)
6395 *pIndex = 0;
6396
6397 if ((!pZip) || (!pZip->m_pState) || (!pName))
6398 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6399
6400 /* See if we can use a binary search */
6401 if (((pZip->m_pState->m_init_flags &
6402 MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) &&
6403 (pZip->m_zip_mode == MZ_ZIP_MODE_READING) &&
6404 ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
6405 (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) {
6406 return mz_zip_locate_file_binary_search(pZip, pName, pIndex);
6407 }
6408
6409 /* Locate the entry by scanning the entire central directory */
6410 name_len = strlen(pName);
6411 if (name_len > MZ_UINT16_MAX)
6412 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6413
6414 comment_len = pComment ? strlen(pComment) : 0;
6415 if (comment_len > MZ_UINT16_MAX)
6416 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6417
6418 for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
6419 const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(
6420 &pZip->m_pState->m_central_dir, mz_uint8,
6421 MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
6422 file_index));
6423 mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
6424 const char *pFilename =
6425 (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
6426 if (filename_len < name_len)
6427 continue;
6428 if (comment_len) {
6429 mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
6430 file_comment_len =
6431 MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
6432 const char *pFile_comment = pFilename + filename_len + file_extra_len;
6433 if ((file_comment_len != comment_len) ||
6434 (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len,
6435 flags)))
6436 continue;
6437 }
6438 if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
6439 int ofs = filename_len - 1;
6440 do {
6441 if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
6442 (pFilename[ofs] == ':'))
6443 break;
6444 } while (--ofs >= 0);
6445 ofs++;
6446 pFilename += ofs;
6447 filename_len -= ofs;
6448 }
6449 if ((filename_len == name_len) &&
6450 (mz_zip_string_equal(pName, pFilename, filename_len, flags))) {
6451 if (pIndex)
6452 *pIndex = file_index;
6453 return MZ_TRUE;
6454 }
6455 }
6456
6457 return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND);
6458 }
6459
6460 static mz_bool mz_zip_reader_extract_to_mem_no_alloc1(
6461 mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size,
6462 mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size,
6463 const mz_zip_archive_file_stat *st) {
6464 int status = TINFL_STATUS_DONE;
6465 mz_uint64 needed_size, cur_file_ofs, comp_remaining,
6466 out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
6467 mz_zip_archive_file_stat file_stat;
6468 void *pRead_buf;
6469 mz_uint32
6470 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
6471 sizeof(mz_uint32)];
6472 mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
6473 tinfl_decompressor inflator;
6474
6475 if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) ||
6476 ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead))
6477 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6478
6479 if (st) {
6480 file_stat = *st;
6481 } else if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
6482 return MZ_FALSE;
6483
6484 /* A directory or zero length file */
6485 if ((file_stat.m_is_directory) || (!file_stat.m_comp_size))
6486 return MZ_TRUE;
6487
6488 /* Encryption and patch files are not supported. */
6489 if (file_stat.m_bit_flag &
6490 (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED |
6491 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION |
6492 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG))
6493 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);
6494
6495 /* This function only supports decompressing stored and deflate. */
6496 if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
6497 (file_stat.m_method != MZ_DEFLATED))
6498 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);
6499
6500 /* Ensure supplied output buffer is large enough. */
6501 needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
6502 : file_stat.m_uncomp_size;
6503 if (buf_size < needed_size)
6504 return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL);
6505
6506 /* Read and parse the local directory entry. */
6507 cur_file_ofs = file_stat.m_local_header_ofs;
6508 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
6509 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
6510 MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
6511 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
6512
6513 if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
6514 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6515
6516 cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
6517 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
6518 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
6519 if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
6520 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6521
6522 if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
6523 /* The file is stored or the caller has requested the compressed data. */
6524 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
6525 (size_t)needed_size) != needed_size)
6526 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
6527
6528 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6529 if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) {
6530 if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
6531 (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)
6532 return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED);
6533 }
6534 #endif
6535
6536 return MZ_TRUE;
6537 }
6538
6539 /* Decompress the file either directly from memory or from a file input
6540 * buffer. */
6541 tinfl_init(&inflator);
6542
6543 if (pZip->m_pState->m_pMem) {
6544 /* Read directly from the archive in memory. */
6545 pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
6546 read_buf_size = read_buf_avail = file_stat.m_comp_size;
6547 comp_remaining = 0;
6548 } else if (pUser_read_buf) {
6549 /* Use a user provided read buffer. */
6550 if (!user_read_buf_size)
6551 return MZ_FALSE;
6552 pRead_buf = (mz_uint8 *)pUser_read_buf;
6553 read_buf_size = user_read_buf_size;
6554 read_buf_avail = 0;
6555 comp_remaining = file_stat.m_comp_size;
6556 } else {
6557 /* Temporarily allocate a read buffer. */
6558 read_buf_size =
6559 MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);
6560 if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
6561 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
6562
6563 if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
6564 (size_t)read_buf_size)))
6565 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
6566
6567 read_buf_avail = 0;
6568 comp_remaining = file_stat.m_comp_size;
6569 }
6570
6571 do {
6572 /* The size_t cast here should be OK because we've verified that the output
6573 * buffer is >= file_stat.m_uncomp_size above */
6574 size_t in_buf_size,
6575 out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
6576 if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
6577 read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
6578 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
6579 (size_t)read_buf_avail) != read_buf_avail) {
6580 status = TINFL_STATUS_FAILED;
6581 mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED);
6582 break;
6583 }
6584 cur_file_ofs += read_buf_avail;
6585 comp_remaining -= read_buf_avail;
6586 read_buf_ofs = 0;
6587 }
6588 in_buf_size = (size_t)read_buf_avail;
6589 status = tinfl_decompress(
6590 &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
6591 (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
6592 TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
6593 (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
6594 read_buf_avail -= in_buf_size;
6595 read_buf_ofs += in_buf_size;
6596 out_buf_ofs += out_buf_size;
6597 } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
6598
6599 if (status == TINFL_STATUS_DONE) {
6600 /* Make sure the entire file was decompressed, and check its CRC. */
6601 if (out_buf_ofs != file_stat.m_uncomp_size) {
6602 mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE);
6603 status = TINFL_STATUS_FAILED;
6604 }
6605 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6606 else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
6607 (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) {
6608 mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED);
6609 status = TINFL_STATUS_FAILED;
6610 }
6611 #endif
6612 }
6613
6614 if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
6615 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
6616
6617 return status == TINFL_STATUS_DONE;
6618 }
6619
6620 mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
6621 mz_uint file_index, void *pBuf,
6622 size_t buf_size, mz_uint flags,
6623 void *pUser_read_buf,
6624 size_t user_read_buf_size) {
6625 return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf,
6626 buf_size, flags, pUser_read_buf,
6627 user_read_buf_size, NULL);
6628 }
6629
6630 mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
6631 mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
6632 mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
6633 mz_uint32 file_index;
6634 if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))
6635 return MZ_FALSE;
6636 return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
6637 flags, pUser_read_buf,
6638 user_read_buf_size);
6639 }
6640
6641 mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
6642 void *pBuf, size_t buf_size,
6643 mz_uint flags) {
6644 return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
6645 flags, NULL, 0);
6646 }
6647
6648 mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
6649 const char *pFilename, void *pBuf,
6650 size_t buf_size, mz_uint flags) {
6651 return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
6652 buf_size, flags, NULL, 0);
6653 }
6654
6655 void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
6656 size_t *pSize, mz_uint flags) {
6657 mz_zip_archive_file_stat file_stat;
6658 mz_uint64 alloc_size;
6659 void *pBuf;
6660
6661 if (pSize)
6662 *pSize = 0;
6663
6664 if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
6665 return NULL;
6666
6667 alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
6668 : file_stat.m_uncomp_size;
6669 if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) {
6670 mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
6671 return NULL;
6672 }
6673
6674 if (NULL ==
6675 (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) {
6676 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
6677 return NULL;
6678 }
6679
6680 if (!mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf,
6681 (size_t)alloc_size, flags, NULL,
6682 0, &file_stat)) {
6683 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
6684 return NULL;
6685 }
6686
6687 if (pSize)
6688 *pSize = (size_t)alloc_size;
6689 return pBuf;
6690 }
6691
6692 void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
6693 const char *pFilename, size_t *pSize,
6694 mz_uint flags) {
6695 mz_uint32 file_index;
6696 if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags,
6697 &file_index)) {
6698 if (pSize)
6699 *pSize = 0;
6700 return MZ_FALSE;
6701 }
6702 return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
6703 }
6704
6705 mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
6706 mz_uint file_index,
6707 mz_file_write_func pCallback,
6708 void *pOpaque, mz_uint flags) {
6709 int status = TINFL_STATUS_DONE;
6710 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6711 mz_uint file_crc32 = MZ_CRC32_INIT;
6712 #endif
6713 mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
6714 out_buf_ofs = 0, cur_file_ofs;
6715 mz_zip_archive_file_stat file_stat;
6716 void *pRead_buf = NULL;
6717 void *pWrite_buf = NULL;
6718 mz_uint32
6719 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
6720 sizeof(mz_uint32)];
6721 mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
6722
6723 if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead))
6724 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
6725
6726 if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
6727 return MZ_FALSE;
6728
6729 /* A directory or zero length file */
6730 if (file_stat.m_is_directory || (!file_stat.m_comp_size))
6731 return MZ_TRUE;
6732
6733 /* Encryption and patch files are not supported. */
6734 if (file_stat.m_bit_flag &
6735 (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED |
6736 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION |
6737 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG))
6738 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);
6739
6740 /* This function only supports decompressing stored and deflate. */
6741 if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
6742 (file_stat.m_method != MZ_DEFLATED))
6743 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);
6744
6745 /* Read and do some minimal validation of the local directory entry (this
6746 * doesn't crack the zip64 stuff, which we already have from the central dir)
6747 */
6748 cur_file_ofs = file_stat.m_local_header_ofs;
6749 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
6750 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
6751 MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
6752 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
6753
6754 if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
6755 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6756
6757 cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
6758 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
6759 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
6760 if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
6761 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6762
6763 /* Decompress the file either directly from memory or from a file input
6764 * buffer. */
6765 if (pZip->m_pState->m_pMem) {
6766 pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
6767 read_buf_size = read_buf_avail = file_stat.m_comp_size;
6768 comp_remaining = 0;
6769 } else {
6770 read_buf_size =
6771 MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);
6772 if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
6773 (size_t)read_buf_size)))
6774 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
6775
6776 read_buf_avail = 0;
6777 comp_remaining = file_stat.m_comp_size;
6778 }
6779
6780 if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
6781 /* The file is stored or the caller has requested the compressed data. */
6782 if (pZip->m_pState->m_pMem) {
6783 if (((sizeof(size_t) == sizeof(mz_uint32))) &&
6784 (file_stat.m_comp_size > MZ_UINT32_MAX))
6785 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
6786
6787 if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
6788 (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) {
6789 mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED);
6790 status = TINFL_STATUS_FAILED;
6791 } else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
6792 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6793 file_crc32 =
6794 (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
6795 (size_t)file_stat.m_comp_size);
6796 #endif
6797 }
6798
6799 cur_file_ofs += file_stat.m_comp_size;
6800 out_buf_ofs += file_stat.m_comp_size;
6801 comp_remaining = 0;
6802 } else {
6803 while (comp_remaining) {
6804 read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
6805 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
6806 (size_t)read_buf_avail) != read_buf_avail) {
6807 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
6808 status = TINFL_STATUS_FAILED;
6809 break;
6810 }
6811
6812 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6813 if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
6814 file_crc32 = (mz_uint32)mz_crc32(
6815 file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
6816 }
6817 #endif
6818
6819 if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
6820 (size_t)read_buf_avail) != read_buf_avail) {
6821 mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED);
6822 status = TINFL_STATUS_FAILED;
6823 break;
6824 }
6825
6826 cur_file_ofs += read_buf_avail;
6827 out_buf_ofs += read_buf_avail;
6828 comp_remaining -= read_buf_avail;
6829 }
6830 }
6831 } else {
6832 tinfl_decompressor inflator;
6833 tinfl_init(&inflator);
6834
6835 if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
6836 TINFL_LZ_DICT_SIZE))) {
6837 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
6838 status = TINFL_STATUS_FAILED;
6839 } else {
6840 do {
6841 mz_uint8 *pWrite_buf_cur =
6842 (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
6843 size_t in_buf_size,
6844 out_buf_size =
6845 TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
6846 if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
6847 read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
6848 if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
6849 (size_t)read_buf_avail) != read_buf_avail) {
6850 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
6851 status = TINFL_STATUS_FAILED;
6852 break;
6853 }
6854 cur_file_ofs += read_buf_avail;
6855 comp_remaining -= read_buf_avail;
6856 read_buf_ofs = 0;
6857 }
6858
6859 in_buf_size = (size_t)read_buf_avail;
6860 status = tinfl_decompress(
6861 &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
6862 (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
6863 comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
6864 read_buf_avail -= in_buf_size;
6865 read_buf_ofs += in_buf_size;
6866
6867 if (out_buf_size) {
6868 if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
6869 out_buf_size) {
6870 mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED);
6871 status = TINFL_STATUS_FAILED;
6872 break;
6873 }
6874
6875 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6876 file_crc32 =
6877 (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
6878 #endif
6879 if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
6880 mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED);
6881 status = TINFL_STATUS_FAILED;
6882 break;
6883 }
6884 }
6885 } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
6886 (status == TINFL_STATUS_HAS_MORE_OUTPUT));
6887 }
6888 }
6889
6890 if ((status == TINFL_STATUS_DONE) &&
6891 (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
6892 /* Make sure the entire file was decompressed, and check its CRC. */
6893 if (out_buf_ofs != file_stat.m_uncomp_size) {
6894 mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE);
6895 status = TINFL_STATUS_FAILED;
6896 }
6897 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6898 else if (file_crc32 != file_stat.m_crc32) {
6899 mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED);
6900 status = TINFL_STATUS_FAILED;
6901 }
6902 #endif
6903 }
6904
6905 if (!pZip->m_pState->m_pMem)
6906 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
6907
6908 if (pWrite_buf)
6909 pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
6910
6911 return status == TINFL_STATUS_DONE;
6912 }
6913
6914 mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
6915 const char *pFilename,
6916 mz_file_write_func pCallback,
6917 void *pOpaque, mz_uint flags) {
6918 mz_uint32 file_index;
6919 if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))
6920 return MZ_FALSE;
6921
6922 return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
6923 flags);
6924 }
6925
6926 mz_zip_reader_extract_iter_state *
6927 mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index,
6928 mz_uint flags) {
6929 mz_zip_reader_extract_iter_state *pState;
6930 mz_uint32
6931 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
6932 sizeof(mz_uint32)];
6933 mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
6934
6935 /* Argument sanity check */
6936 if ((!pZip) || (!pZip->m_pState))
6937 return NULL;
6938
6939 /* Allocate an iterator status structure */
6940 pState = (mz_zip_reader_extract_iter_state *)pZip->m_pAlloc(
6941 pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state));
6942 if (!pState) {
6943 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
6944 return NULL;
6945 }
6946
6947 /* Fetch file details */
6948 if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) {
6949 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
6950 return NULL;
6951 }
6952
6953 /* Encryption and patch files are not supported. */
6954 if (pState->file_stat.m_bit_flag &
6955 (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED |
6956 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION |
6957 MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) {
6958 mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);
6959 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
6960 return NULL;
6961 }
6962
6963 /* This function only supports decompressing stored and deflate. */
6964 if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) &&
6965 (pState->file_stat.m_method != 0) &&
6966 (pState->file_stat.m_method != MZ_DEFLATED)) {
6967 mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);
6968 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
6969 return NULL;
6970 }
6971
6972 /* Init state - save args */
6973 pState->pZip = pZip;
6974 pState->flags = flags;
6975
6976 /* Init state - reset variables to defaults */
6977 pState->status = TINFL_STATUS_DONE;
6978 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
6979 pState->file_crc32 = MZ_CRC32_INIT;
6980 #endif
6981 pState->read_buf_ofs = 0;
6982 pState->out_buf_ofs = 0;
6983 pState->pRead_buf = NULL;
6984 pState->pWrite_buf = NULL;
6985 pState->out_blk_remain = 0;
6986
6987 /* Read and parse the local directory entry. */
6988 pState->cur_file_ofs = pState->file_stat.m_local_header_ofs;
6989 if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header,
6990 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
6991 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) {
6992 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
6993 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
6994 return NULL;
6995 }
6996
6997 if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) {
6998 mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
6999 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
7000 return NULL;
7001 }
7002
7003 pState->cur_file_ofs +=
7004 MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
7005 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
7006 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
7007 if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) >
7008 pZip->m_archive_size) {
7009 mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7010 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
7011 return NULL;
7012 }
7013
7014 /* Decompress the file either directly from memory or from a file input
7015 * buffer. */
7016 if (pZip->m_pState->m_pMem) {
7017 pState->pRead_buf =
7018 (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs;
7019 pState->read_buf_size = pState->read_buf_avail =
7020 pState->file_stat.m_comp_size;
7021 pState->comp_remaining = pState->file_stat.m_comp_size;
7022 } else {
7023 if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ||
7024 (!pState->file_stat.m_method))) {
7025 /* Decompression required, therefore intermediate read buffer required */
7026 pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size,
7027 (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE);
7028 if (NULL ==
7029 (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
7030 (size_t)pState->read_buf_size))) {
7031 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
7032 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
7033 return NULL;
7034 }
7035 } else {
7036 /* Decompression not required - we will be reading directly into user
7037 * buffer, no temp buf required */
7038 pState->read_buf_size = 0;
7039 }
7040 pState->read_buf_avail = 0;
7041 pState->comp_remaining = pState->file_stat.m_comp_size;
7042 }
7043
7044 if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ||
7045 (!pState->file_stat.m_method))) {
7046 /* Decompression required, init decompressor */
7047 tinfl_init(&pState->inflator);
7048
7049 /* Allocate write buffer */
7050 if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
7051 TINFL_LZ_DICT_SIZE))) {
7052 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
7053 if (pState->pRead_buf)
7054 pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf);
7055 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
7056 return NULL;
7057 }
7058 }
7059
7060 return pState;
7061 }
7062
7063 mz_zip_reader_extract_iter_state *
7064 mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename,
7065 mz_uint flags) {
7066 mz_uint32 file_index;
7067
7068 /* Locate file index by name */
7069 if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index))
7070 return NULL;
7071
7072 /* Construct iterator */
7073 return mz_zip_reader_extract_iter_new(pZip, file_index, flags);
7074 }
7075
7076 size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state *pState,
7077 void *pvBuf, size_t buf_size) {
7078 size_t copied_to_caller = 0;
7079
7080 /* Argument sanity check */
7081 if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf))
7082 return 0;
7083
7084 if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ||
7085 (!pState->file_stat.m_method)) {
7086 /* The file is stored or the caller has requested the compressed data, calc
7087 * amount to return. */
7088 copied_to_caller = (size_t)MZ_MIN(buf_size, pState->comp_remaining);
7089
7090 /* Zip is in memory....or requires reading from a file? */
7091 if (pState->pZip->m_pState->m_pMem) {
7092 /* Copy data to caller's buffer */
7093 memcpy(pvBuf, pState->pRead_buf, copied_to_caller);
7094 pState->pRead_buf = ((mz_uint8 *)pState->pRead_buf) + copied_to_caller;
7095 } else {
7096 /* Read directly into caller's buffer */
7097 if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque,
7098 pState->cur_file_ofs, pvBuf,
7099 copied_to_caller) != copied_to_caller) {
7100 /* Failed to read all that was asked for, flag failure and alert user */
7101 mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED);
7102 pState->status = TINFL_STATUS_FAILED;
7103 copied_to_caller = 0;
7104 }
7105 }
7106
7107 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
7108 /* Compute CRC if not returning compressed data only */
7109 if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
7110 pState->file_crc32 = (mz_uint32)mz_crc32(
7111 pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller);
7112 #endif
7113
7114 /* Advance offsets, dec counters */
7115 pState->cur_file_ofs += copied_to_caller;
7116 pState->out_buf_ofs += copied_to_caller;
7117 pState->comp_remaining -= copied_to_caller;
7118 } else {
7119 do {
7120 /* Calc ptr to write buffer - given current output pos and block size */
7121 mz_uint8 *pWrite_buf_cur =
7122 (mz_uint8 *)pState->pWrite_buf +
7123 (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
7124
7125 /* Calc max output size - given current output pos and block size */
7126 size_t in_buf_size,
7127 out_buf_size = TINFL_LZ_DICT_SIZE -
7128 (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
7129
7130 if (!pState->out_blk_remain) {
7131 /* Read more data from file if none available (and reading from file) */
7132 if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) {
7133 /* Calc read size */
7134 pState->read_buf_avail =
7135 MZ_MIN(pState->read_buf_size, pState->comp_remaining);
7136 if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque,
7137 pState->cur_file_ofs, pState->pRead_buf,
7138 (size_t)pState->read_buf_avail) !=
7139 pState->read_buf_avail) {
7140 mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED);
7141 pState->status = TINFL_STATUS_FAILED;
7142 break;
7143 }
7144
7145 /* Advance offsets, dec counters */
7146 pState->cur_file_ofs += pState->read_buf_avail;
7147 pState->comp_remaining -= pState->read_buf_avail;
7148 pState->read_buf_ofs = 0;
7149 }
7150
7151 /* Perform decompression */
7152 in_buf_size = (size_t)pState->read_buf_avail;
7153 pState->status = tinfl_decompress(
7154 &pState->inflator,
7155 (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs,
7156 &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur,
7157 &out_buf_size,
7158 pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
7159 pState->read_buf_avail -= in_buf_size;
7160 pState->read_buf_ofs += in_buf_size;
7161
7162 /* Update current output block size remaining */
7163 pState->out_blk_remain = out_buf_size;
7164 }
7165
7166 if (pState->out_blk_remain) {
7167 /* Calc amount to return. */
7168 size_t to_copy =
7169 MZ_MIN((buf_size - copied_to_caller), pState->out_blk_remain);
7170
7171 /* Copy data to caller's buffer */
7172 memcpy((uint8_t *)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy);
7173
7174 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
7175 /* Perform CRC */
7176 pState->file_crc32 =
7177 (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy);
7178 #endif
7179
7180 /* Decrement data consumed from block */
7181 pState->out_blk_remain -= to_copy;
7182
7183 /* Inc output offset, while performing sanity check */
7184 if ((pState->out_buf_ofs += to_copy) >
7185 pState->file_stat.m_uncomp_size) {
7186 mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED);
7187 pState->status = TINFL_STATUS_FAILED;
7188 break;
7189 }
7190
7191 /* Increment counter of data copied to caller */
7192 copied_to_caller += to_copy;
7193 }
7194 } while ((copied_to_caller < buf_size) &&
7195 ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
7196 (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)));
7197 }
7198
7199 /* Return how many bytes were copied into user buffer */
7200 return copied_to_caller;
7201 }
7202
7203 mz_bool
7204 mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState) {
7205 int status;
7206
7207 /* Argument sanity check */
7208 if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState))
7209 return MZ_FALSE;
7210
7211 /* Was decompression completed and requested? */
7212 if ((pState->status == TINFL_STATUS_DONE) &&
7213 (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
7214 /* Make sure the entire file was decompressed, and check its CRC. */
7215 if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) {
7216 mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE);
7217 pState->status = TINFL_STATUS_FAILED;
7218 }
7219 #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
7220 else if (pState->file_crc32 != pState->file_stat.m_crc32) {
7221 mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED);
7222 pState->status = TINFL_STATUS_FAILED;
7223 }
7224 #endif
7225 }
7226
7227 /* Free buffers */
7228 if (!pState->pZip->m_pState->m_pMem)
7229 pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf);
7230 if (pState->pWrite_buf)
7231 pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf);
7232
7233 /* Save status */
7234 status = pState->status;
7235
7236 /* Free context */
7237 pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState);
7238
7239 return status == TINFL_STATUS_DONE;
7240 }
7241
7242 #ifndef MINIZ_NO_STDIO
7243 static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
7244 const void *pBuf, size_t n) {
7245 (void)ofs;
7246
7247 return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
7248 }
7249
7250 mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
7251 const char *pDst_filename,
7252 mz_uint flags) {
7253 mz_bool status;
7254 mz_zip_archive_file_stat file_stat;
7255 MZ_FILE *pFile;
7256
7257 if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
7258 return MZ_FALSE;
7259
7260 if (file_stat.m_is_directory || (!file_stat.m_is_supported))
7261 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);
7262
7263 pFile = MZ_FOPEN(pDst_filename, "wb");
7264 if (!pFile)
7265 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
7266
7267 status = mz_zip_reader_extract_to_callback(
7268 pZip, file_index, mz_zip_file_write_callback, pFile, flags);
7269
7270 if (MZ_FCLOSE(pFile) == EOF) {
7271 if (status)
7272 mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED);
7273
7274 status = MZ_FALSE;
7275 }
7276
7277 #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO)
7278 if (status)
7279 mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
7280 #endif
7281
7282 return status;
7283 }
7284
7285 mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
7286 const char *pArchive_filename,
7287 const char *pDst_filename,
7288 mz_uint flags) {
7289 mz_uint32 file_index;
7290 if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags,
7291 &file_index))
7292 return MZ_FALSE;
7293
7294 return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
7295 }
7296
7297 mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index,
7298 MZ_FILE *pFile, mz_uint flags) {
7299 mz_zip_archive_file_stat file_stat;
7300
7301 if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
7302 return MZ_FALSE;
7303
7304 if (file_stat.m_is_directory || (!file_stat.m_is_supported))
7305 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);
7306
7307 return mz_zip_reader_extract_to_callback(
7308 pZip, file_index, mz_zip_file_write_callback, pFile, flags);
7309 }
7310
7311 mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip,
7312 const char *pArchive_filename,
7313 MZ_FILE *pFile, mz_uint flags) {
7314 mz_uint32 file_index;
7315 if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags,
7316 &file_index))
7317 return MZ_FALSE;
7318
7319 return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags);
7320 }
7321 #endif /* #ifndef MINIZ_NO_STDIO */
7322
7323 static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs,
7324 const void *pBuf, size_t n) {
7325 mz_uint32 *p = (mz_uint32 *)pOpaque;
7326 (void)file_ofs;
7327 *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n);
7328 return n;
7329 }
7330
7331 mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index,
7332 mz_uint flags) {
7333 mz_zip_archive_file_stat file_stat;
7334 mz_zip_internal_state *pState;
7335 const mz_uint8 *pCentral_dir_header;
7336 mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE;
7337 mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE;
7338 mz_uint32
7339 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
7340 sizeof(mz_uint32)];
7341 mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
7342 mz_uint64 local_header_ofs = 0;
7343 mz_uint32 local_header_filename_len, local_header_extra_len,
7344 local_header_crc32;
7345 mz_uint64 local_header_comp_size, local_header_uncomp_size;
7346 mz_uint32 uncomp_crc32 = MZ_CRC32_INIT;
7347 mz_bool has_data_descriptor;
7348 mz_uint32 local_header_bit_flags;
7349
7350 mz_zip_array file_data_array;
7351 mz_zip_array_init(&file_data_array, 1);
7352
7353 if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
7354 (!pZip->m_pRead))
7355 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7356
7357 if (file_index > pZip->m_total_files)
7358 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7359
7360 pState = pZip->m_pState;
7361
7362 pCentral_dir_header = mz_zip_get_cdh(pZip, file_index);
7363
7364 if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header,
7365 &file_stat, &found_zip64_ext_data_in_cdir))
7366 return MZ_FALSE;
7367
7368 /* A directory or zero length file */
7369 if (file_stat.m_is_directory || (!file_stat.m_uncomp_size))
7370 return MZ_TRUE;
7371
7372 /* Encryption and patch files are not supported. */
7373 if (file_stat.m_is_encrypted)
7374 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION);
7375
7376 /* This function only supports stored and deflate. */
7377 if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
7378 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD);
7379
7380 if (!file_stat.m_is_supported)
7381 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE);
7382
7383 /* Read and parse the local directory entry. */
7384 local_header_ofs = file_stat.m_local_header_ofs;
7385 if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header,
7386 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
7387 MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
7388 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
7389
7390 if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
7391 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7392
7393 local_header_filename_len =
7394 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS);
7395 local_header_extra_len =
7396 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
7397 local_header_comp_size =
7398 MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS);
7399 local_header_uncomp_size =
7400 MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS);
7401 local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS);
7402 local_header_bit_flags =
7403 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
7404 has_data_descriptor = (local_header_bit_flags & 8) != 0;
7405
7406 if (local_header_filename_len != strlen(file_stat.m_filename))
7407 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7408
7409 if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
7410 local_header_filename_len + local_header_extra_len +
7411 file_stat.m_comp_size) > pZip->m_archive_size)
7412 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7413
7414 if (!mz_zip_array_resize(
7415 pZip, &file_data_array,
7416 MZ_MAX(local_header_filename_len, local_header_extra_len),
7417 MZ_FALSE)) {
7418 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
7419 goto handle_failure;
7420 }
7421
7422 if (local_header_filename_len) {
7423 if (pZip->m_pRead(pZip->m_pIO_opaque,
7424 local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE,
7425 file_data_array.m_p,
7426 local_header_filename_len) != local_header_filename_len) {
7427 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
7428 goto handle_failure;
7429 }
7430
7431 /* I've seen 1 archive that had the same pathname, but used backslashes in
7432 * the local dir and forward slashes in the central dir. Do we care about
7433 * this? For now, this case will fail validation. */
7434 if (memcmp(file_stat.m_filename, file_data_array.m_p,
7435 local_header_filename_len) != 0) {
7436 mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);
7437 goto handle_failure;
7438 }
7439 }
7440
7441 if ((local_header_extra_len) &&
7442 ((local_header_comp_size == MZ_UINT32_MAX) ||
7443 (local_header_uncomp_size == MZ_UINT32_MAX))) {
7444 mz_uint32 extra_size_remaining = local_header_extra_len;
7445 const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p;
7446
7447 if (pZip->m_pRead(pZip->m_pIO_opaque,
7448 local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
7449 local_header_filename_len,
7450 file_data_array.m_p,
7451 local_header_extra_len) != local_header_extra_len) {
7452 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
7453 goto handle_failure;
7454 }
7455
7456 do {
7457 mz_uint32 field_id, field_data_size, field_total_size;
7458
7459 if (extra_size_remaining < (sizeof(mz_uint16) * 2)) {
7460 mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7461 goto handle_failure;
7462 }
7463
7464 field_id = MZ_READ_LE16(pExtra_data);
7465 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));
7466 field_total_size = field_data_size + sizeof(mz_uint16) * 2;
7467
7468 if (field_total_size > extra_size_remaining) {
7469 mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7470 goto handle_failure;
7471 }
7472
7473 if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) {
7474 const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32);
7475
7476 if (field_data_size < sizeof(mz_uint64) * 2) {
7477 mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
7478 goto handle_failure;
7479 }
7480
7481 local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data);
7482 local_header_comp_size =
7483 MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64));
7484
7485 found_zip64_ext_data_in_ldir = MZ_TRUE;
7486 break;
7487 }
7488
7489 pExtra_data += field_total_size;
7490 extra_size_remaining -= field_total_size;
7491 } while (extra_size_remaining);
7492 }
7493
7494 /* TODO: parse local header extra data when local_header_comp_size is
7495 * 0xFFFFFFFF! (big_descriptor.zip) */
7496 /* I've seen zips in the wild with the data descriptor bit set, but proper
7497 * local header values and bogus data descriptors */
7498 if ((has_data_descriptor) && (!local_header_comp_size) &&
7499 (!local_header_crc32)) {
7500 mz_uint8 descriptor_buf[32];
7501 mz_bool has_id;
7502 const mz_uint8 *pSrc;
7503 mz_uint32 file_crc32;
7504 mz_uint64 comp_size = 0, uncomp_size = 0;
7505
7506 mz_uint32 num_descriptor_uint32s =
7507 ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4;
7508
7509 if (pZip->m_pRead(pZip->m_pIO_opaque,
7510 local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
7511 local_header_filename_len + local_header_extra_len +
7512 file_stat.m_comp_size,
7513 descriptor_buf,
7514 sizeof(mz_uint32) * num_descriptor_uint32s) !=
7515 (sizeof(mz_uint32) * num_descriptor_uint32s)) {
7516 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
7517 goto handle_failure;
7518 }
7519
7520 has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID);
7521 pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf;
7522
7523 file_crc32 = MZ_READ_LE32(pSrc);
7524
7525 if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) {
7526 comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32));
7527 uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64));
7528 } else {
7529 comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32));
7530 uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32));
7531 }
7532
7533 if ((file_crc32 != file_stat.m_crc32) ||
7534 (comp_size != file_stat.m_comp_size) ||
7535 (uncomp_size != file_stat.m_uncomp_size)) {
7536 mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);
7537 goto handle_failure;
7538 }
7539 } else {
7540 if ((local_header_crc32 != file_stat.m_crc32) ||
7541 (local_header_comp_size != file_stat.m_comp_size) ||
7542 (local_header_uncomp_size != file_stat.m_uncomp_size)) {
7543 mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);
7544 goto handle_failure;
7545 }
7546 }
7547
7548 mz_zip_array_clear(pZip, &file_data_array);
7549
7550 if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) {
7551 if (!mz_zip_reader_extract_to_callback(
7552 pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0))
7553 return MZ_FALSE;
7554
7555 /* 1 more check to be sure, although the extract checks too. */
7556 if (uncomp_crc32 != file_stat.m_crc32) {
7557 mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);
7558 return MZ_FALSE;
7559 }
7560 }
7561
7562 return MZ_TRUE;
7563
7564 handle_failure:
7565 mz_zip_array_clear(pZip, &file_data_array);
7566 return MZ_FALSE;
7567 }
7568
7569 mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) {
7570 mz_zip_internal_state *pState;
7571 uint32_t i;
7572
7573 if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
7574 (!pZip->m_pRead))
7575 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7576
7577 pState = pZip->m_pState;
7578
7579 /* Basic sanity checks */
7580 if (!pState->m_zip64) {
7581 if (pZip->m_total_files > MZ_UINT16_MAX)
7582 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
7583
7584 if (pZip->m_archive_size > MZ_UINT32_MAX)
7585 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
7586 } else {
7587 if (pZip->m_total_files >= MZ_UINT32_MAX)
7588 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
7589
7590 if (pState->m_central_dir.m_size >= MZ_UINT32_MAX)
7591 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
7592 }
7593
7594 for (i = 0; i < pZip->m_total_files; i++) {
7595 if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) {
7596 mz_uint32 found_index;
7597 mz_zip_archive_file_stat stat;
7598
7599 if (!mz_zip_reader_file_stat(pZip, i, &stat))
7600 return MZ_FALSE;
7601
7602 if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0,
7603 &found_index))
7604 return MZ_FALSE;
7605
7606 /* This check can fail if there are duplicate filenames in the archive
7607 * (which we don't check for when writing - that's up to the user) */
7608 if (found_index != i)
7609 return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED);
7610 }
7611
7612 if (!mz_zip_validate_file(pZip, i, flags))
7613 return MZ_FALSE;
7614 }
7615
7616 return MZ_TRUE;
7617 }
7618
7619 mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size,
7620 mz_uint flags, mz_zip_error *pErr) {
7621 mz_bool success = MZ_TRUE;
7622 mz_zip_archive zip;
7623 mz_zip_error actual_err = MZ_ZIP_NO_ERROR;
7624
7625 if ((!pMem) || (!size)) {
7626 if (pErr)
7627 *pErr = MZ_ZIP_INVALID_PARAMETER;
7628 return MZ_FALSE;
7629 }
7630
7631 mz_zip_zero_struct(&zip);
7632
7633 if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) {
7634 if (pErr)
7635 *pErr = zip.m_last_error;
7636 return MZ_FALSE;
7637 }
7638
7639 if (!mz_zip_validate_archive(&zip, flags)) {
7640 actual_err = zip.m_last_error;
7641 success = MZ_FALSE;
7642 }
7643
7644 if (!mz_zip_reader_end_internal(&zip, success)) {
7645 if (!actual_err)
7646 actual_err = zip.m_last_error;
7647 success = MZ_FALSE;
7648 }
7649
7650 if (pErr)
7651 *pErr = actual_err;
7652
7653 return success;
7654 }
7655
7656 #ifndef MINIZ_NO_STDIO
7657 mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags,
7658 mz_zip_error *pErr) {
7659 mz_bool success = MZ_TRUE;
7660 mz_zip_archive zip;
7661 mz_zip_error actual_err = MZ_ZIP_NO_ERROR;
7662
7663 if (!pFilename) {
7664 if (pErr)
7665 *pErr = MZ_ZIP_INVALID_PARAMETER;
7666 return MZ_FALSE;
7667 }
7668
7669 mz_zip_zero_struct(&zip);
7670
7671 if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) {
7672 if (pErr)
7673 *pErr = zip.m_last_error;
7674 return MZ_FALSE;
7675 }
7676
7677 if (!mz_zip_validate_archive(&zip, flags)) {
7678 actual_err = zip.m_last_error;
7679 success = MZ_FALSE;
7680 }
7681
7682 if (!mz_zip_reader_end_internal(&zip, success)) {
7683 if (!actual_err)
7684 actual_err = zip.m_last_error;
7685 success = MZ_FALSE;
7686 }
7687
7688 if (pErr)
7689 *pErr = actual_err;
7690
7691 return success;
7692 }
7693 #endif /* #ifndef MINIZ_NO_STDIO */
7694
7695 /* ------------------- .ZIP archive writing */
7696
7697 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
7698
7699 static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
7700 p[0] = (mz_uint8)v;
7701 p[1] = (mz_uint8)(v >> 8);
7702 }
7703 static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
7704 p[0] = (mz_uint8)v;
7705 p[1] = (mz_uint8)(v >> 8);
7706 p[2] = (mz_uint8)(v >> 16);
7707 p[3] = (mz_uint8)(v >> 24);
7708 }
7709 static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) {
7710 mz_write_le32(p, (mz_uint32)v);
7711 mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32));
7712 }
7713
7714 #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
7715 #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
7716 #define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v))
7717
7718 static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
7719 const void *pBuf, size_t n) {
7720 mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
7721 mz_zip_internal_state *pState = pZip->m_pState;
7722 mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
7723
7724 if (!n)
7725 return 0;
7726
7727 /* An allocation this big is likely to just fail on 32-bit systems, so don't
7728 * even go there. */
7729 if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) {
7730 mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);
7731 return 0;
7732 }
7733
7734 if (new_size > pState->m_mem_capacity) {
7735 void *pNew_block;
7736 size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
7737
7738 while (new_capacity < new_size)
7739 new_capacity *= 2;
7740
7741 if (NULL == (pNew_block = pZip->m_pRealloc(
7742 pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) {
7743 mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
7744 return 0;
7745 }
7746
7747 pState->m_pMem = pNew_block;
7748 pState->m_mem_capacity = new_capacity;
7749 }
7750 memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
7751 pState->m_mem_size = (size_t)new_size;
7752 return n;
7753 }
7754
7755 static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip,
7756 mz_bool set_last_error) {
7757 mz_zip_internal_state *pState;
7758 mz_bool status = MZ_TRUE;
7759
7760 if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
7761 ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
7762 (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) {
7763 if (set_last_error)
7764 mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7765 return MZ_FALSE;
7766 }
7767
7768 pState = pZip->m_pState;
7769 pZip->m_pState = NULL;
7770 mz_zip_array_clear(pZip, &pState->m_central_dir);
7771 mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
7772 mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
7773
7774 #ifndef MINIZ_NO_STDIO
7775 if (pState->m_pFile) {
7776 if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) {
7777 if (MZ_FCLOSE(pState->m_pFile) == EOF) {
7778 if (set_last_error)
7779 mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED);
7780 status = MZ_FALSE;
7781 }
7782 }
7783
7784 pState->m_pFile = NULL;
7785 }
7786 #endif /* #ifndef MINIZ_NO_STDIO */
7787
7788 if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
7789 pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
7790 pState->m_pMem = NULL;
7791 }
7792
7793 pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
7794 pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
7795 return status;
7796 }
7797
7798 mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size,
7799 mz_uint flags) {
7800 mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0;
7801
7802 if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
7803 (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
7804 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7805
7806 if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) {
7807 if (!pZip->m_pRead)
7808 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7809 }
7810
7811 if (pZip->m_file_offset_alignment) {
7812 /* Ensure user specified file offset alignment is a power of 2. */
7813 if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
7814 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7815 }
7816
7817 if (!pZip->m_pAlloc)
7818 pZip->m_pAlloc = miniz_def_alloc_func;
7819 if (!pZip->m_pFree)
7820 pZip->m_pFree = miniz_def_free_func;
7821 if (!pZip->m_pRealloc)
7822 pZip->m_pRealloc = miniz_def_realloc_func;
7823
7824 pZip->m_archive_size = existing_size;
7825 pZip->m_central_directory_file_ofs = 0;
7826 pZip->m_total_files = 0;
7827
7828 if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
7829 pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
7830 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
7831
7832 memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
7833
7834 MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
7835 sizeof(mz_uint8));
7836 MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
7837 sizeof(mz_uint32));
7838 MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
7839 sizeof(mz_uint32));
7840
7841 pZip->m_pState->m_zip64 = zip64;
7842 pZip->m_pState->m_zip64_has_extended_info_fields = zip64;
7843
7844 pZip->m_zip_type = MZ_ZIP_TYPE_USER;
7845 pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
7846
7847 return MZ_TRUE;
7848 }
7849
7850 mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
7851 return mz_zip_writer_init_v2(pZip, existing_size, 0);
7852 }
7853
7854 mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip,
7855 size_t size_to_reserve_at_beginning,
7856 size_t initial_allocation_size,
7857 mz_uint flags) {
7858 pZip->m_pWrite = mz_zip_heap_write_func;
7859 pZip->m_pNeeds_keepalive = NULL;
7860
7861 if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)
7862 pZip->m_pRead = mz_zip_mem_read_func;
7863
7864 pZip->m_pIO_opaque = pZip;
7865
7866 if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags))
7867 return MZ_FALSE;
7868
7869 pZip->m_zip_type = MZ_ZIP_TYPE_HEAP;
7870
7871 if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
7872 size_to_reserve_at_beginning))) {
7873 if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
7874 pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
7875 mz_zip_writer_end_internal(pZip, MZ_FALSE);
7876 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
7877 }
7878 pZip->m_pState->m_mem_capacity = initial_allocation_size;
7879 }
7880
7881 return MZ_TRUE;
7882 }
7883
7884 mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
7885 size_t size_to_reserve_at_beginning,
7886 size_t initial_allocation_size) {
7887 return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning,
7888 initial_allocation_size, 0);
7889 }
7890
7891 #ifndef MINIZ_NO_STDIO
7892 static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
7893 const void *pBuf, size_t n) {
7894 mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
7895 mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
7896
7897 file_ofs += pZip->m_pState->m_file_archive_start_ofs;
7898
7899 if (((mz_int64)file_ofs < 0) ||
7900 (((cur_ofs != (mz_int64)file_ofs)) &&
7901 (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) {
7902 mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED);
7903 return 0;
7904 }
7905
7906 return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
7907 }
7908
7909 mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
7910 mz_uint64 size_to_reserve_at_beginning) {
7911 return mz_zip_writer_init_file_v2(pZip, pFilename,
7912 size_to_reserve_at_beginning, 0);
7913 }
7914
7915 mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename,
7916 mz_uint64 size_to_reserve_at_beginning,
7917 mz_uint flags) {
7918 MZ_FILE *pFile;
7919
7920 pZip->m_pWrite = mz_zip_file_write_func;
7921 pZip->m_pNeeds_keepalive = NULL;
7922
7923 if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)
7924 pZip->m_pRead = mz_zip_file_read_func;
7925
7926 pZip->m_pIO_opaque = pZip;
7927
7928 if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags))
7929 return MZ_FALSE;
7930
7931 if (NULL == (pFile = MZ_FOPEN(
7932 pFilename,
7933 (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) {
7934 mz_zip_writer_end(pZip);
7935 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
7936 }
7937
7938 pZip->m_pState->m_pFile = pFile;
7939 pZip->m_zip_type = MZ_ZIP_TYPE_FILE;
7940
7941 if (size_to_reserve_at_beginning) {
7942 mz_uint64 cur_ofs = 0;
7943 char buf[4096];
7944
7945 MZ_CLEAR_OBJ(buf);
7946
7947 do {
7948 size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
7949 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
7950 mz_zip_writer_end(pZip);
7951 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
7952 }
7953 cur_ofs += n;
7954 size_to_reserve_at_beginning -= n;
7955 } while (size_to_reserve_at_beginning);
7956 }
7957
7958 return MZ_TRUE;
7959 }
7960
7961 mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile,
7962 mz_uint flags) {
7963 pZip->m_pWrite = mz_zip_file_write_func;
7964 pZip->m_pNeeds_keepalive = NULL;
7965
7966 if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING)
7967 pZip->m_pRead = mz_zip_file_read_func;
7968
7969 pZip->m_pIO_opaque = pZip;
7970
7971 if (!mz_zip_writer_init_v2(pZip, 0, flags))
7972 return MZ_FALSE;
7973
7974 pZip->m_pState->m_pFile = pFile;
7975 pZip->m_pState->m_file_archive_start_ofs =
7976 MZ_FTELL64(pZip->m_pState->m_pFile);
7977 pZip->m_zip_type = MZ_ZIP_TYPE_CFILE;
7978
7979 return MZ_TRUE;
7980 }
7981 #endif /* #ifndef MINIZ_NO_STDIO */
7982
7983 mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip,
7984 const char *pFilename,
7985 mz_uint flags) {
7986 mz_zip_internal_state *pState;
7987
7988 if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
7989 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7990
7991 if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) {
7992 /* We don't support converting a non-zip64 file to zip64 - this seems like
7993 * more trouble than it's worth. (What about the existing 32-bit data
7994 * descriptors that could follow the compressed data?) */
7995 if (!pZip->m_pState->m_zip64)
7996 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
7997 }
7998
7999 /* No sense in trying to write to an archive that's already at the support max
8000 * size */
8001 if (pZip->m_pState->m_zip64) {
8002 if (pZip->m_total_files == MZ_UINT32_MAX)
8003 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
8004 } else {
8005 if (pZip->m_total_files == MZ_UINT16_MAX)
8006 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
8007
8008 if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
8009 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)
8010 return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);
8011 }
8012
8013 pState = pZip->m_pState;
8014
8015 if (pState->m_pFile) {
8016 #ifdef MINIZ_NO_STDIO
8017 (void)pFilename;
8018 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8019 #else
8020 if (pZip->m_pIO_opaque != pZip)
8021 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8022
8023 if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) {
8024 if (!pFilename)
8025 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8026
8027 /* Archive is being read from stdio and was originally opened only for
8028 * reading. Try to reopen as writable. */
8029 if (NULL ==
8030 (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
8031 /* The mz_zip_archive is now in a bogus state because pState->m_pFile is
8032 * NULL, so just close it. */
8033 mz_zip_reader_end_internal(pZip, MZ_FALSE);
8034 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
8035 }
8036 }
8037
8038 pZip->m_pWrite = mz_zip_file_write_func;
8039 pZip->m_pNeeds_keepalive = NULL;
8040 #endif /* #ifdef MINIZ_NO_STDIO */
8041 } else if (pState->m_pMem) {
8042 /* Archive lives in a memory block. Assume it's from the heap that we can
8043 * resize using the realloc callback. */
8044 if (pZip->m_pIO_opaque != pZip)
8045 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8046
8047 pState->m_mem_capacity = pState->m_mem_size;
8048 pZip->m_pWrite = mz_zip_heap_write_func;
8049 pZip->m_pNeeds_keepalive = NULL;
8050 }
8051 /* Archive is being read via a user provided read function - make sure the
8052 user has specified a write function too. */
8053 else if (!pZip->m_pWrite)
8054 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8055
8056 /* Start writing new files at the archive's current central directory
8057 * location. */
8058 /* TODO: We could add a flag that lets the user start writing immediately
8059 * AFTER the existing central dir - this would be safer. */
8060 pZip->m_archive_size = pZip->m_central_directory_file_ofs;
8061 pZip->m_central_directory_file_ofs = 0;
8062
8063 /* Clear the sorted central dir offsets, they aren't useful or maintained now.
8064 */
8065 /* Even though we're now in write mode, files can still be extracted and
8066 * verified, but file locates will be slow. */
8067 /* TODO: We could easily maintain the sorted central directory offsets. */
8068 mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets);
8069
8070 pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
8071
8072 return MZ_TRUE;
8073 }
8074
8075 mz_bool mz_zip_writer_init_from_reader_v2_noreopen(mz_zip_archive *pZip,
8076 const char *pFilename,
8077 mz_uint flags) {
8078 mz_zip_internal_state *pState;
8079
8080 if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
8081 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8082
8083 if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) {
8084 /* We don't support converting a non-zip64 file to zip64 - this seems like
8085 * more trouble than it's worth. (What about the existing 32-bit data
8086 * descriptors that could follow the compressed data?) */
8087 if (!pZip->m_pState->m_zip64)
8088 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8089 }
8090
8091 /* No sense in trying to write to an archive that's already at the support max
8092 * size */
8093 if (pZip->m_pState->m_zip64) {
8094 if (pZip->m_total_files == MZ_UINT32_MAX)
8095 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
8096 } else {
8097 if (pZip->m_total_files == MZ_UINT16_MAX)
8098 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
8099
8100 if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
8101 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)
8102 return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);
8103 }
8104
8105 pState = pZip->m_pState;
8106
8107 if (pState->m_pFile) {
8108 #ifdef MINIZ_NO_STDIO
8109 (void)pFilename;
8110 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8111 #else
8112 if (pZip->m_pIO_opaque != pZip)
8113 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8114
8115 if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) {
8116 if (!pFilename)
8117 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8118 }
8119
8120 pZip->m_pWrite = mz_zip_file_write_func;
8121 pZip->m_pNeeds_keepalive = NULL;
8122 #endif /* #ifdef MINIZ_NO_STDIO */
8123 } else if (pState->m_pMem) {
8124 /* Archive lives in a memory block. Assume it's from the heap that we can
8125 * resize using the realloc callback. */
8126 if (pZip->m_pIO_opaque != pZip)
8127 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8128
8129 pState->m_mem_capacity = pState->m_mem_size;
8130 pZip->m_pWrite = mz_zip_heap_write_func;
8131 pZip->m_pNeeds_keepalive = NULL;
8132 }
8133 /* Archive is being read via a user provided read function - make sure the
8134 user has specified a write function too. */
8135 else if (!pZip->m_pWrite)
8136 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8137
8138 /* Start writing new files at the archive's current central directory
8139 * location. */
8140 /* TODO: We could add a flag that lets the user start writing immediately
8141 * AFTER the existing central dir - this would be safer. */
8142 pZip->m_archive_size = pZip->m_central_directory_file_ofs;
8143 pZip->m_central_directory_file_ofs = 0;
8144
8145 /* Clear the sorted central dir offsets, they aren't useful or maintained now.
8146 */
8147 /* Even though we're now in write mode, files can still be extracted and
8148 * verified, but file locates will be slow. */
8149 /* TODO: We could easily maintain the sorted central directory offsets. */
8150 mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets);
8151
8152 pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
8153
8154 return MZ_TRUE;
8155 }
8156
8157 mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
8158 const char *pFilename) {
8159 return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0);
8160 }
8161
8162 /* TODO: pArchive_name is a terrible name here! */
8163 mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
8164 const void *pBuf, size_t buf_size,
8165 mz_uint level_and_flags) {
8166 return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
8167 level_and_flags, 0, 0);
8168 }
8169
8170 typedef struct {
8171 mz_zip_archive *m_pZip;
8172 mz_uint64 m_cur_archive_file_ofs;
8173 mz_uint64 m_comp_size;
8174 } mz_zip_writer_add_state;
8175
8176 static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
8177 void *pUser) {
8178 mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
8179 if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
8180 pState->m_cur_archive_file_ofs, pBuf,
8181 len) != len)
8182 return MZ_FALSE;
8183
8184 pState->m_cur_archive_file_ofs += len;
8185 pState->m_comp_size += len;
8186 return MZ_TRUE;
8187 }
8188
8189 #define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE \
8190 (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2)
8191 #define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE \
8192 (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3)
8193 static mz_uint32
8194 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size,
8195 mz_uint64 *pComp_size,
8196 mz_uint64 *pLocal_header_ofs) {
8197 mz_uint8 *pDst = pBuf;
8198 mz_uint32 field_size = 0;
8199
8200 MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID);
8201 MZ_WRITE_LE16(pDst + 2, 0);
8202 pDst += sizeof(mz_uint16) * 2;
8203
8204 if (pUncomp_size) {
8205 MZ_WRITE_LE64(pDst, *pUncomp_size);
8206 pDst += sizeof(mz_uint64);
8207 field_size += sizeof(mz_uint64);
8208 }
8209
8210 if (pComp_size) {
8211 MZ_WRITE_LE64(pDst, *pComp_size);
8212 pDst += sizeof(mz_uint64);
8213 field_size += sizeof(mz_uint64);
8214 }
8215
8216 if (pLocal_header_ofs) {
8217 MZ_WRITE_LE64(pDst, *pLocal_header_ofs);
8218 pDst += sizeof(mz_uint64);
8219 field_size += sizeof(mz_uint64);
8220 }
8221
8222 MZ_WRITE_LE16(pBuf + 2, field_size);
8223
8224 return (mz_uint32)(pDst - pBuf);
8225 }
8226
8227 static mz_bool mz_zip_writer_create_local_dir_header(
8228 mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
8229 mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
8230 mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
8231 mz_uint16 dos_time, mz_uint16 dos_date) {
8232 (void)pZip;
8233 memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
8234 MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
8235 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
8236 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
8237 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
8238 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
8239 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
8240 MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
8241 MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS,
8242 MZ_MIN(comp_size, MZ_UINT32_MAX));
8243 MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS,
8244 MZ_MIN(uncomp_size, MZ_UINT32_MAX));
8245 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
8246 MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
8247 return MZ_TRUE;
8248 }
8249
8250 static mz_bool mz_zip_writer_create_central_dir_header(
8251 mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
8252 mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
8253 mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
8254 mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
8255 mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
8256 (void)pZip;
8257 memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
8258 MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
8259 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
8260 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
8261 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
8262 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
8263 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
8264 MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
8265 MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS,
8266 MZ_MIN(comp_size, MZ_UINT32_MAX));
8267 MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS,
8268 MZ_MIN(uncomp_size, MZ_UINT32_MAX));
8269 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
8270 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
8271 MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
8272 MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
8273 MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
8274 MZ_MIN(local_header_ofs, MZ_UINT32_MAX));
8275 return MZ_TRUE;
8276 }
8277
8278 static mz_bool mz_zip_writer_add_to_central_dir(
8279 mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
8280 const void *pExtra, mz_uint16 extra_size, const void *pComment,
8281 mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
8282 mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
8283 mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
8284 mz_uint32 ext_attributes, const char *user_extra_data,
8285 mz_uint user_extra_data_len) {
8286 mz_zip_internal_state *pState = pZip->m_pState;
8287 mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
8288 size_t orig_central_dir_size = pState->m_central_dir.m_size;
8289 mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
8290
8291 if (!pZip->m_pState->m_zip64) {
8292 if (local_header_ofs > 0xFFFFFFFF)
8293 return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE);
8294 }
8295
8296 /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */
8297 if (((mz_uint64)pState->m_central_dir.m_size +
8298 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
8299 user_extra_data_len + comment_size) >= MZ_UINT32_MAX)
8300 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);
8301
8302 if (!mz_zip_writer_create_central_dir_header(
8303 pZip, central_dir_header, filename_size,
8304 (mz_uint16)(extra_size + user_extra_data_len), comment_size,
8305 uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
8306 dos_date, local_header_ofs, ext_attributes))
8307 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
8308
8309 if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
8310 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
8311 (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
8312 filename_size)) ||
8313 (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
8314 extra_size)) ||
8315 (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data,
8316 user_extra_data_len)) ||
8317 (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
8318 comment_size)) ||
8319 (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
8320 &central_dir_ofs, 1))) {
8321 /* Try to resize the central directory array back into its original state.
8322 */
8323 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
8324 MZ_FALSE);
8325 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
8326 }
8327
8328 return MZ_TRUE;
8329 }
8330
8331 static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
8332 /* Basic ZIP archive filename validity checks: Valid filenames cannot start
8333 * with a forward slash, cannot contain a drive letter, and cannot use
8334 * DOS-style backward slashes. */
8335 if (*pArchive_name == '/')
8336 return MZ_FALSE;
8337
8338 /* Making sure the name does not contain drive letters or DOS style backward
8339 * slashes is the responsibility of the program using miniz*/
8340
8341 return MZ_TRUE;
8342 }
8343
8344 static mz_uint
8345 mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) {
8346 mz_uint32 n;
8347 if (!pZip->m_file_offset_alignment)
8348 return 0;
8349 n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
8350 return (mz_uint)((pZip->m_file_offset_alignment - n) &
8351 (pZip->m_file_offset_alignment - 1));
8352 }
8353
8354 static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
8355 mz_uint64 cur_file_ofs, mz_uint32 n) {
8356 char buf[4096];
8357 memset(buf, 0, MZ_MIN(sizeof(buf), n));
8358 while (n) {
8359 mz_uint32 s = MZ_MIN(sizeof(buf), n);
8360 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
8361 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8362
8363 cur_file_ofs += s;
8364 n -= s;
8365 }
8366 return MZ_TRUE;
8367 }
8368
8369 mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
8370 const char *pArchive_name, const void *pBuf,
8371 size_t buf_size, const void *pComment,
8372 mz_uint16 comment_size,
8373 mz_uint level_and_flags, mz_uint64 uncomp_size,
8374 mz_uint32 uncomp_crc32) {
8375 return mz_zip_writer_add_mem_ex_v2(
8376 pZip, pArchive_name, pBuf, buf_size, pComment, comment_size,
8377 level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0);
8378 }
8379
8380 mz_bool mz_zip_writer_add_mem_ex_v2(
8381 mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf,
8382 size_t buf_size, const void *pComment, mz_uint16 comment_size,
8383 mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32,
8384 MZ_TIME_T *last_modified, const char *user_extra_data,
8385 mz_uint user_extra_data_len, const char *user_extra_data_central,
8386 mz_uint user_extra_data_central_len) {
8387 mz_uint16 method = 0, dos_time = 0, dos_date = 0;
8388 mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
8389 mz_uint64 local_dir_header_ofs = 0, cur_archive_file_ofs = 0, comp_size = 0;
8390 size_t archive_name_size;
8391 mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
8392 tdefl_compressor *pComp = NULL;
8393 mz_bool store_data_uncompressed;
8394 mz_zip_internal_state *pState;
8395 mz_uint8 *pExtra_data = NULL;
8396 mz_uint32 extra_size = 0;
8397 mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE];
8398 mz_uint16 bit_flags = 0;
8399
8400 if ((int)level_and_flags < 0)
8401 level_and_flags = MZ_DEFAULT_LEVEL;
8402
8403 if (uncomp_size ||
8404 (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))
8405 bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR;
8406
8407 if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME))
8408 bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8;
8409
8410 level = level_and_flags & 0xF;
8411 store_data_uncompressed =
8412 ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
8413
8414 if ((!pZip) || (!pZip->m_pState) ||
8415 (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
8416 (!pArchive_name) || ((comment_size) && (!pComment)) ||
8417 (level > MZ_UBER_COMPRESSION))
8418 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8419
8420 pState = pZip->m_pState;
8421 local_dir_header_ofs = pZip->m_archive_size;
8422 cur_archive_file_ofs = pZip->m_archive_size;
8423
8424 if (pState->m_zip64) {
8425 if (pZip->m_total_files == MZ_UINT32_MAX)
8426 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
8427 } else {
8428 if (pZip->m_total_files == MZ_UINT16_MAX) {
8429 pState->m_zip64 = MZ_TRUE;
8430 /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */
8431 }
8432 if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) {
8433 pState->m_zip64 = MZ_TRUE;
8434 /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */
8435 }
8436 }
8437
8438 if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
8439 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8440
8441 if (!mz_zip_writer_validate_archive_name(pArchive_name))
8442 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);
8443
8444 #ifndef MINIZ_NO_TIME
8445 if (last_modified != NULL) {
8446 mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date);
8447 } else {
8448 MZ_TIME_T cur_time;
8449 time(&cur_time);
8450 mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date);
8451 }
8452 #endif /* #ifndef MINIZ_NO_TIME */
8453
8454 if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
8455 uncomp_crc32 =
8456 (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
8457 uncomp_size = buf_size;
8458 if (uncomp_size <= 3) {
8459 level = 0;
8460 store_data_uncompressed = MZ_TRUE;
8461 }
8462 }
8463
8464 archive_name_size = strlen(pArchive_name);
8465 if (archive_name_size > MZ_UINT16_MAX)
8466 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);
8467
8468 num_alignment_padding_bytes =
8469 mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
8470
8471 /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */
8472 if (((mz_uint64)pState->m_central_dir.m_size +
8473 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size +
8474 MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX)
8475 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);
8476
8477 if (!pState->m_zip64) {
8478 /* Bail early if the archive would obviously become too large */
8479 if ((pZip->m_archive_size + num_alignment_padding_bytes +
8480 MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size +
8481 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size +
8482 user_extra_data_len + pState->m_central_dir.m_size +
8483 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len +
8484 MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) {
8485 pState->m_zip64 = MZ_TRUE;
8486 /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */
8487 }
8488 }
8489
8490 if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
8491 /* Set DOS Subdirectory attribute bit. */
8492 ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG;
8493
8494 /* Subdirectories cannot contain data. */
8495 if ((buf_size) || (uncomp_size))
8496 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8497 }
8498
8499 /* Try to do any allocations before writing to the archive, so if an
8500 * allocation fails the file remains unmodified. (A good idea if we're doing
8501 * an in-place modification.) */
8502 if ((!mz_zip_array_ensure_room(
8503 pZip, &pState->m_central_dir,
8504 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size +
8505 (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) ||
8506 (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
8507 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
8508
8509 if ((!store_data_uncompressed) && (buf_size)) {
8510 if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
8511 pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
8512 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
8513 }
8514
8515 if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
8516 num_alignment_padding_bytes)) {
8517 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8518 return MZ_FALSE;
8519 }
8520
8521 local_dir_header_ofs += num_alignment_padding_bytes;
8522 if (pZip->m_file_offset_alignment) {
8523 MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
8524 0);
8525 }
8526 cur_archive_file_ofs += num_alignment_padding_bytes;
8527
8528 MZ_CLEAR_OBJ(local_dir_header);
8529
8530 if (!store_data_uncompressed ||
8531 (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
8532 method = MZ_DEFLATED;
8533 }
8534
8535 if (pState->m_zip64) {
8536 if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) {
8537 pExtra_data = extra_data;
8538 extra_size = mz_zip_writer_create_zip64_extra_data(
8539 extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,
8540 (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL,
8541 (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs
8542 : NULL);
8543 }
8544
8545 if (!mz_zip_writer_create_local_dir_header(
8546 pZip, local_dir_header, (mz_uint16)archive_name_size,
8547 (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method,
8548 bit_flags, dos_time, dos_date))
8549 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
8550
8551 if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs,
8552 local_dir_header,
8553 sizeof(local_dir_header)) != sizeof(local_dir_header))
8554 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8555
8556 cur_archive_file_ofs += sizeof(local_dir_header);
8557
8558 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
8559 archive_name_size) != archive_name_size) {
8560 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8561 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8562 }
8563 cur_archive_file_ofs += archive_name_size;
8564
8565 if (pExtra_data != NULL) {
8566 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data,
8567 extra_size) != extra_size)
8568 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8569
8570 cur_archive_file_ofs += extra_size;
8571 }
8572 } else {
8573 if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX))
8574 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
8575 if (!mz_zip_writer_create_local_dir_header(
8576 pZip, local_dir_header, (mz_uint16)archive_name_size,
8577 (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags,
8578 dos_time, dos_date))
8579 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
8580
8581 if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs,
8582 local_dir_header,
8583 sizeof(local_dir_header)) != sizeof(local_dir_header))
8584 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8585
8586 cur_archive_file_ofs += sizeof(local_dir_header);
8587
8588 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
8589 archive_name_size) != archive_name_size) {
8590 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8591 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8592 }
8593 cur_archive_file_ofs += archive_name_size;
8594 }
8595
8596 if (user_extra_data_len > 0) {
8597 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs,
8598 user_extra_data,
8599 user_extra_data_len) != user_extra_data_len)
8600 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8601
8602 cur_archive_file_ofs += user_extra_data_len;
8603 }
8604
8605 if (store_data_uncompressed) {
8606 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
8607 buf_size) != buf_size) {
8608 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8609 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8610 }
8611
8612 cur_archive_file_ofs += buf_size;
8613 comp_size = buf_size;
8614 } else if (buf_size) {
8615 mz_zip_writer_add_state state;
8616
8617 state.m_pZip = pZip;
8618 state.m_cur_archive_file_ofs = cur_archive_file_ofs;
8619 state.m_comp_size = 0;
8620
8621 if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
8622 tdefl_create_comp_flags_from_zip_params(
8623 level, -15, MZ_DEFAULT_STRATEGY)) !=
8624 TDEFL_STATUS_OKAY) ||
8625 (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
8626 TDEFL_STATUS_DONE)) {
8627 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8628 return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED);
8629 }
8630
8631 comp_size = state.m_comp_size;
8632 cur_archive_file_ofs = state.m_cur_archive_file_ofs;
8633 }
8634
8635 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8636 pComp = NULL;
8637
8638 if (uncomp_size) {
8639 mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64];
8640 mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32;
8641
8642 MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR);
8643
8644 MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID);
8645 MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32);
8646 if (pExtra_data == NULL) {
8647 if (comp_size > MZ_UINT32_MAX)
8648 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
8649
8650 MZ_WRITE_LE32(local_dir_footer + 8, comp_size);
8651 MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size);
8652 } else {
8653 MZ_WRITE_LE64(local_dir_footer + 8, comp_size);
8654 MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size);
8655 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64;
8656 }
8657
8658 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs,
8659 local_dir_footer,
8660 local_dir_footer_size) != local_dir_footer_size)
8661 return MZ_FALSE;
8662
8663 cur_archive_file_ofs += local_dir_footer_size;
8664 }
8665
8666 if (pExtra_data != NULL) {
8667 extra_size = mz_zip_writer_create_zip64_extra_data(
8668 extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,
8669 (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL,
8670 (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL);
8671 }
8672
8673 if (!mz_zip_writer_add_to_central_dir(
8674 pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data,
8675 (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size,
8676 uncomp_crc32, method, bit_flags, dos_time, dos_date,
8677 local_dir_header_ofs, ext_attributes, user_extra_data_central,
8678 user_extra_data_central_len))
8679 return MZ_FALSE;
8680
8681 pZip->m_total_files++;
8682 pZip->m_archive_size = cur_archive_file_ofs;
8683
8684 return MZ_TRUE;
8685 }
8686
8687 mz_bool mz_zip_writer_add_read_buf_callback(
8688 mz_zip_archive *pZip, const char *pArchive_name,
8689 mz_file_read_func read_callback, void *callback_opaque, mz_uint64 max_size,
8690 const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size,
8691 mz_uint level_and_flags, mz_uint32 ext_attributes,
8692 const char *user_extra_data, mz_uint user_extra_data_len,
8693 const char *user_extra_data_central, mz_uint user_extra_data_central_len) {
8694 mz_uint16 gen_flags = (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)
8695 ? 0
8696 : MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR;
8697 mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
8698 mz_uint16 method = 0, dos_time = 0, dos_date = 0;
8699 mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = 0, uncomp_size = 0,
8700 comp_size = 0;
8701 size_t archive_name_size;
8702 mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
8703 mz_uint8 *pExtra_data = NULL;
8704 mz_uint32 extra_size = 0;
8705 mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE];
8706 mz_zip_internal_state *pState;
8707 mz_uint64 file_ofs = 0, cur_archive_header_file_ofs;
8708
8709 if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME))
8710 gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8;
8711
8712 if ((int)level_and_flags < 0)
8713 level_and_flags = MZ_DEFAULT_LEVEL;
8714 level = level_and_flags & 0xF;
8715
8716 /* Sanity checks */
8717 if ((!pZip) || (!pZip->m_pState) ||
8718 (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
8719 ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
8720 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8721
8722 pState = pZip->m_pState;
8723 cur_archive_file_ofs = pZip->m_archive_size;
8724
8725 if ((!pState->m_zip64) && (max_size > MZ_UINT32_MAX)) {
8726 /* Source file is too large for non-zip64 */
8727 /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */
8728 pState->m_zip64 = MZ_TRUE;
8729 }
8730
8731 /* We could support this, but why? */
8732 if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
8733 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
8734
8735 if (!mz_zip_writer_validate_archive_name(pArchive_name))
8736 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);
8737
8738 if (pState->m_zip64) {
8739 if (pZip->m_total_files == MZ_UINT32_MAX)
8740 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
8741 } else {
8742 if (pZip->m_total_files == MZ_UINT16_MAX) {
8743 pState->m_zip64 = MZ_TRUE;
8744 /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */
8745 }
8746 }
8747
8748 archive_name_size = strlen(pArchive_name);
8749 if (archive_name_size > MZ_UINT16_MAX)
8750 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME);
8751
8752 num_alignment_padding_bytes =
8753 mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
8754
8755 /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */
8756 if (((mz_uint64)pState->m_central_dir.m_size +
8757 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size +
8758 MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX)
8759 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);
8760
8761 if (!pState->m_zip64) {
8762 /* Bail early if the archive would obviously become too large */
8763 if ((pZip->m_archive_size + num_alignment_padding_bytes +
8764 MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size +
8765 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size +
8766 user_extra_data_len + pState->m_central_dir.m_size +
8767 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 +
8768 MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) >
8769 0xFFFFFFFF) {
8770 pState->m_zip64 = MZ_TRUE;
8771 /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */
8772 }
8773 }
8774
8775 #ifndef MINIZ_NO_TIME
8776 if (pFile_time) {
8777 mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date);
8778 }
8779 #endif
8780
8781 if (max_size <= 3)
8782 level = 0;
8783
8784 if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
8785 num_alignment_padding_bytes)) {
8786 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8787 }
8788
8789 cur_archive_file_ofs += num_alignment_padding_bytes;
8790 local_dir_header_ofs = cur_archive_file_ofs;
8791
8792 if (pZip->m_file_offset_alignment) {
8793 MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) ==
8794 0);
8795 }
8796
8797 if (max_size && level) {
8798 method = MZ_DEFLATED;
8799 }
8800
8801 MZ_CLEAR_OBJ(local_dir_header);
8802 if (pState->m_zip64) {
8803 if (max_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) {
8804 pExtra_data = extra_data;
8805 if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)
8806 extra_size = mz_zip_writer_create_zip64_extra_data(
8807 extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,
8808 (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL,
8809 (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs
8810 : NULL);
8811 else
8812 extra_size = mz_zip_writer_create_zip64_extra_data(
8813 extra_data, NULL, NULL,
8814 (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs
8815 : NULL);
8816 }
8817
8818 if (!mz_zip_writer_create_local_dir_header(
8819 pZip, local_dir_header, (mz_uint16)archive_name_size,
8820 (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method,
8821 gen_flags, dos_time, dos_date))
8822 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
8823
8824 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs,
8825 local_dir_header,
8826 sizeof(local_dir_header)) != sizeof(local_dir_header))
8827 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8828
8829 cur_archive_file_ofs += sizeof(local_dir_header);
8830
8831 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
8832 archive_name_size) != archive_name_size) {
8833 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8834 }
8835
8836 cur_archive_file_ofs += archive_name_size;
8837
8838 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data,
8839 extra_size) != extra_size)
8840 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8841
8842 cur_archive_file_ofs += extra_size;
8843 } else {
8844 if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX))
8845 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
8846 if (!mz_zip_writer_create_local_dir_header(
8847 pZip, local_dir_header, (mz_uint16)archive_name_size,
8848 (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags,
8849 dos_time, dos_date))
8850 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
8851
8852 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs,
8853 local_dir_header,
8854 sizeof(local_dir_header)) != sizeof(local_dir_header))
8855 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8856
8857 cur_archive_file_ofs += sizeof(local_dir_header);
8858
8859 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
8860 archive_name_size) != archive_name_size) {
8861 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8862 }
8863
8864 cur_archive_file_ofs += archive_name_size;
8865 }
8866
8867 if (user_extra_data_len > 0) {
8868 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs,
8869 user_extra_data,
8870 user_extra_data_len) != user_extra_data_len)
8871 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8872
8873 cur_archive_file_ofs += user_extra_data_len;
8874 }
8875
8876 if (max_size) {
8877 void *pRead_buf =
8878 pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
8879 if (!pRead_buf) {
8880 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
8881 }
8882
8883 if (!level) {
8884 while (1) {
8885 size_t n = read_callback(callback_opaque, file_ofs, pRead_buf,
8886 MZ_ZIP_MAX_IO_BUF_SIZE);
8887 if (n == 0)
8888 break;
8889
8890 if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) {
8891 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
8892 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
8893 }
8894 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
8895 n) != n) {
8896 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
8897 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
8898 }
8899 file_ofs += n;
8900 uncomp_crc32 =
8901 (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
8902 cur_archive_file_ofs += n;
8903 }
8904 uncomp_size = file_ofs;
8905 comp_size = uncomp_size;
8906 } else {
8907 mz_bool result = MZ_FALSE;
8908 mz_zip_writer_add_state state;
8909 tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
8910 pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
8911 if (!pComp) {
8912 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
8913 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
8914 }
8915
8916 state.m_pZip = pZip;
8917 state.m_cur_archive_file_ofs = cur_archive_file_ofs;
8918 state.m_comp_size = 0;
8919
8920 if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
8921 tdefl_create_comp_flags_from_zip_params(
8922 level, -15, MZ_DEFAULT_STRATEGY)) !=
8923 TDEFL_STATUS_OKAY) {
8924 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8925 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
8926 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
8927 }
8928
8929 for (;;) {
8930 tdefl_status status;
8931 tdefl_flush flush = TDEFL_NO_FLUSH;
8932
8933 size_t n = read_callback(callback_opaque, file_ofs, pRead_buf,
8934 MZ_ZIP_MAX_IO_BUF_SIZE);
8935 if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) {
8936 mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
8937 break;
8938 }
8939
8940 file_ofs += n;
8941 uncomp_crc32 =
8942 (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
8943
8944 if (pZip->m_pNeeds_keepalive != NULL &&
8945 pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque))
8946 flush = TDEFL_FULL_FLUSH;
8947
8948 if (n == 0)
8949 flush = TDEFL_FINISH;
8950
8951 status = tdefl_compress_buffer(pComp, pRead_buf, n, flush);
8952 if (status == TDEFL_STATUS_DONE) {
8953 result = MZ_TRUE;
8954 break;
8955 } else if (status != TDEFL_STATUS_OKAY) {
8956 mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED);
8957 break;
8958 }
8959 }
8960
8961 pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
8962
8963 if (!result) {
8964 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
8965 return MZ_FALSE;
8966 }
8967
8968 uncomp_size = file_ofs;
8969 comp_size = state.m_comp_size;
8970 cur_archive_file_ofs = state.m_cur_archive_file_ofs;
8971 }
8972
8973 pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
8974 }
8975
8976 if (!(level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)) {
8977 mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64];
8978 mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32;
8979
8980 MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID);
8981 MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32);
8982 if (pExtra_data == NULL) {
8983 if (comp_size > MZ_UINT32_MAX)
8984 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
8985
8986 MZ_WRITE_LE32(local_dir_footer + 8, comp_size);
8987 MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size);
8988 } else {
8989 MZ_WRITE_LE64(local_dir_footer + 8, comp_size);
8990 MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size);
8991 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64;
8992 }
8993
8994 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs,
8995 local_dir_footer,
8996 local_dir_footer_size) != local_dir_footer_size)
8997 return MZ_FALSE;
8998
8999 cur_archive_file_ofs += local_dir_footer_size;
9000 }
9001
9002 if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) {
9003 if (pExtra_data != NULL) {
9004 extra_size = mz_zip_writer_create_zip64_extra_data(
9005 extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,
9006 (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL,
9007 (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs
9008 : NULL);
9009 }
9010
9011 if (!mz_zip_writer_create_local_dir_header(
9012 pZip, local_dir_header, (mz_uint16)archive_name_size,
9013 (mz_uint16)(extra_size + user_extra_data_len),
9014 (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : uncomp_size,
9015 (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : comp_size,
9016 uncomp_crc32, method, gen_flags, dos_time, dos_date))
9017 return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR);
9018
9019 cur_archive_header_file_ofs = local_dir_header_ofs;
9020
9021 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs,
9022 local_dir_header,
9023 sizeof(local_dir_header)) != sizeof(local_dir_header))
9024 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9025
9026 if (pExtra_data != NULL) {
9027 cur_archive_header_file_ofs += sizeof(local_dir_header);
9028
9029 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs,
9030 pArchive_name,
9031 archive_name_size) != archive_name_size) {
9032 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9033 }
9034
9035 cur_archive_header_file_ofs += archive_name_size;
9036
9037 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs,
9038 extra_data, extra_size) != extra_size)
9039 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9040
9041 cur_archive_header_file_ofs += extra_size;
9042 }
9043 }
9044
9045 if (pExtra_data != NULL) {
9046 extra_size = mz_zip_writer_create_zip64_extra_data(
9047 extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL,
9048 (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL,
9049 (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL);
9050 }
9051
9052 if (!mz_zip_writer_add_to_central_dir(
9053 pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data,
9054 (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size,
9055 uncomp_crc32, method, gen_flags, dos_time, dos_date,
9056 local_dir_header_ofs, ext_attributes, user_extra_data_central,
9057 user_extra_data_central_len))
9058 return MZ_FALSE;
9059
9060 pZip->m_total_files++;
9061 pZip->m_archive_size = cur_archive_file_ofs;
9062
9063 return MZ_TRUE;
9064 }
9065
9066 #ifndef MINIZ_NO_STDIO
9067
9068 static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs,
9069 void *pBuf, size_t n) {
9070 MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque;
9071 mz_int64 cur_ofs = MZ_FTELL64(pSrc_file);
9072
9073 if (((mz_int64)file_ofs < 0) ||
9074 (((cur_ofs != (mz_int64)file_ofs)) &&
9075 (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET))))
9076 return 0;
9077
9078 return MZ_FREAD(pBuf, 1, n, pSrc_file);
9079 }
9080
9081 mz_bool mz_zip_writer_add_cfile(
9082 mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file,
9083 mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment,
9084 mz_uint16 comment_size, mz_uint level_and_flags, mz_uint32 ext_attributes,
9085 const char *user_extra_data, mz_uint user_extra_data_len,
9086 const char *user_extra_data_central, mz_uint user_extra_data_central_len) {
9087 return mz_zip_writer_add_read_buf_callback(
9088 pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, max_size,
9089 pFile_time, pComment, comment_size, level_and_flags, ext_attributes,
9090 user_extra_data, user_extra_data_len, user_extra_data_central,
9091 user_extra_data_central_len);
9092 }
9093
9094 mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
9095 const char *pSrc_filename, const void *pComment,
9096 mz_uint16 comment_size, mz_uint level_and_flags,
9097 mz_uint32 ext_attributes) {
9098 MZ_FILE *pSrc_file = NULL;
9099 mz_uint64 uncomp_size = 0;
9100 MZ_TIME_T file_modified_time;
9101 MZ_TIME_T *pFile_time = NULL;
9102 mz_bool status;
9103
9104 memset(&file_modified_time, 0, sizeof(file_modified_time));
9105
9106 #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO)
9107 pFile_time = &file_modified_time;
9108 if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time))
9109 return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED);
9110 #endif
9111
9112 pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
9113 if (!pSrc_file)
9114 return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED);
9115
9116 MZ_FSEEK64(pSrc_file, 0, SEEK_END);
9117 uncomp_size = MZ_FTELL64(pSrc_file);
9118 MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
9119
9120 status = mz_zip_writer_add_cfile(
9121 pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment,
9122 comment_size, level_and_flags, ext_attributes, NULL, 0, NULL, 0);
9123
9124 MZ_FCLOSE(pSrc_file);
9125
9126 return status;
9127 }
9128 #endif /* #ifndef MINIZ_NO_STDIO */
9129
9130 static mz_bool mz_zip_writer_update_zip64_extension_block(
9131 mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt,
9132 uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size,
9133 mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) {
9134 /* + 64 should be enough for any new zip64 data */
9135 if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE))
9136 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9137
9138 mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE);
9139
9140 if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) {
9141 mz_uint8 new_ext_block[64];
9142 mz_uint8 *pDst = new_ext_block;
9143 mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID);
9144 mz_write_le16(pDst + sizeof(mz_uint16), 0);
9145 pDst += sizeof(mz_uint16) * 2;
9146
9147 if (pUncomp_size) {
9148 mz_write_le64(pDst, *pUncomp_size);
9149 pDst += sizeof(mz_uint64);
9150 }
9151
9152 if (pComp_size) {
9153 mz_write_le64(pDst, *pComp_size);
9154 pDst += sizeof(mz_uint64);
9155 }
9156
9157 if (pLocal_header_ofs) {
9158 mz_write_le64(pDst, *pLocal_header_ofs);
9159 pDst += sizeof(mz_uint64);
9160 }
9161
9162 if (pDisk_start) {
9163 mz_write_le32(pDst, *pDisk_start);
9164 pDst += sizeof(mz_uint32);
9165 }
9166
9167 mz_write_le16(new_ext_block + sizeof(mz_uint16),
9168 (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2));
9169
9170 if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block,
9171 pDst - new_ext_block))
9172 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9173 }
9174
9175 if ((pExt) && (ext_len)) {
9176 mz_uint32 extra_size_remaining = ext_len;
9177 const mz_uint8 *pExtra_data = pExt;
9178
9179 do {
9180 mz_uint32 field_id, field_data_size, field_total_size;
9181
9182 if (extra_size_remaining < (sizeof(mz_uint16) * 2))
9183 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9184
9185 field_id = MZ_READ_LE16(pExtra_data);
9186 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));
9187 field_total_size = field_data_size + sizeof(mz_uint16) * 2;
9188
9189 if (field_total_size > extra_size_remaining)
9190 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9191
9192 if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) {
9193 if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data,
9194 field_total_size))
9195 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9196 }
9197
9198 pExtra_data += field_total_size;
9199 extra_size_remaining -= field_total_size;
9200 } while (extra_size_remaining);
9201 }
9202
9203 return MZ_TRUE;
9204 }
9205
9206 /* TODO: This func is now pretty freakin complex due to zip64, split it up? */
9207 mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
9208 mz_zip_archive *pSource_zip,
9209 mz_uint src_file_index) {
9210 mz_uint n, bit_flags, num_alignment_padding_bytes,
9211 src_central_dir_following_data_size;
9212 mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs;
9213 mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
9214 mz_uint32
9215 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
9216 sizeof(mz_uint32)];
9217 mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
9218 mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
9219 size_t orig_central_dir_size;
9220 mz_zip_internal_state *pState;
9221 void *pBuf;
9222 const mz_uint8 *pSrc_central_header;
9223 mz_zip_archive_file_stat src_file_stat;
9224 mz_uint32 src_filename_len, src_comment_len, src_ext_len;
9225 mz_uint32 local_header_filename_size, local_header_extra_len;
9226 mz_uint64 local_header_comp_size, local_header_uncomp_size;
9227 mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE;
9228
9229 /* Sanity checks */
9230 if ((!pZip) || (!pZip->m_pState) ||
9231 (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead))
9232 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9233
9234 pState = pZip->m_pState;
9235
9236 /* Don't support copying files from zip64 archives to non-zip64, even though
9237 * in some cases this is possible */
9238 if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64))
9239 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9240
9241 /* Get pointer to the source central dir header and crack it */
9242 if (NULL ==
9243 (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index)))
9244 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9245
9246 if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) !=
9247 MZ_ZIP_CENTRAL_DIR_HEADER_SIG)
9248 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9249
9250 src_filename_len =
9251 MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS);
9252 src_comment_len =
9253 MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
9254 src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS);
9255 src_central_dir_following_data_size =
9256 src_filename_len + src_ext_len + src_comment_len;
9257
9258 /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32
9259 * fudge factor in case we need to add more extra data) */
9260 if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
9261 src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX)
9262 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);
9263
9264 num_alignment_padding_bytes =
9265 mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
9266
9267 if (!pState->m_zip64) {
9268 if (pZip->m_total_files == MZ_UINT16_MAX)
9269 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
9270 } else {
9271 /* TODO: Our zip64 support still has some 32-bit limits that may not be
9272 * worth fixing. */
9273 if (pZip->m_total_files == MZ_UINT32_MAX)
9274 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
9275 }
9276
9277 if (!mz_zip_file_stat_internal(pSource_zip, src_file_index,
9278 pSrc_central_header, &src_file_stat, NULL))
9279 return MZ_FALSE;
9280
9281 cur_src_file_ofs = src_file_stat.m_local_header_ofs;
9282 cur_dst_file_ofs = pZip->m_archive_size;
9283
9284 /* Read the source archive's local dir header */
9285 if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
9286 pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
9287 MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
9288 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
9289
9290 if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
9291 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9292
9293 cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
9294
9295 /* Compute the total size we need to copy (filename+extra data+compressed
9296 * data) */
9297 local_header_filename_size =
9298 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS);
9299 local_header_extra_len =
9300 MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
9301 local_header_comp_size =
9302 MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS);
9303 local_header_uncomp_size =
9304 MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS);
9305 src_archive_bytes_remaining = local_header_filename_size +
9306 local_header_extra_len +
9307 src_file_stat.m_comp_size;
9308
9309 /* Try to find a zip64 extended information field */
9310 if ((local_header_extra_len) &&
9311 ((local_header_comp_size == MZ_UINT32_MAX) ||
9312 (local_header_uncomp_size == MZ_UINT32_MAX))) {
9313 mz_zip_array file_data_array;
9314 const mz_uint8 *pExtra_data;
9315 mz_uint32 extra_size_remaining = local_header_extra_len;
9316
9317 mz_zip_array_init(&file_data_array, 1);
9318 if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len,
9319 MZ_FALSE)) {
9320 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9321 }
9322
9323 if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque,
9324 src_file_stat.m_local_header_ofs +
9325 MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
9326 local_header_filename_size,
9327 file_data_array.m_p, local_header_extra_len) !=
9328 local_header_extra_len) {
9329 mz_zip_array_clear(pZip, &file_data_array);
9330 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
9331 }
9332
9333 pExtra_data = (const mz_uint8 *)file_data_array.m_p;
9334
9335 do {
9336 mz_uint32 field_id, field_data_size, field_total_size;
9337
9338 if (extra_size_remaining < (sizeof(mz_uint16) * 2)) {
9339 mz_zip_array_clear(pZip, &file_data_array);
9340 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9341 }
9342
9343 field_id = MZ_READ_LE16(pExtra_data);
9344 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16));
9345 field_total_size = field_data_size + sizeof(mz_uint16) * 2;
9346
9347 if (field_total_size > extra_size_remaining) {
9348 mz_zip_array_clear(pZip, &file_data_array);
9349 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9350 }
9351
9352 if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) {
9353 const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32);
9354
9355 if (field_data_size < sizeof(mz_uint64) * 2) {
9356 mz_zip_array_clear(pZip, &file_data_array);
9357 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED);
9358 }
9359
9360 local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data);
9361 local_header_comp_size = MZ_READ_LE64(
9362 pSrc_field_data +
9363 sizeof(mz_uint64)); /* may be 0 if there's a descriptor */
9364
9365 found_zip64_ext_data_in_ldir = MZ_TRUE;
9366 break;
9367 }
9368
9369 pExtra_data += field_total_size;
9370 extra_size_remaining -= field_total_size;
9371 } while (extra_size_remaining);
9372
9373 mz_zip_array_clear(pZip, &file_data_array);
9374 }
9375
9376 if (!pState->m_zip64) {
9377 /* Try to detect if the new archive will most likely wind up too big and
9378 * bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which
9379 * could be present, +64 is a fudge factor). */
9380 /* We also check when the archive is finalized so this doesn't need to be
9381 * perfect. */
9382 mz_uint64 approx_new_archive_size =
9383 cur_dst_file_ofs + num_alignment_padding_bytes +
9384 MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining +
9385 (sizeof(mz_uint32) * 4) + pState->m_central_dir.m_size +
9386 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size +
9387 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64;
9388
9389 if (approx_new_archive_size >= MZ_UINT32_MAX)
9390 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
9391 }
9392
9393 /* Write dest archive padding */
9394 if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
9395 num_alignment_padding_bytes))
9396 return MZ_FALSE;
9397
9398 cur_dst_file_ofs += num_alignment_padding_bytes;
9399
9400 local_dir_header_ofs = cur_dst_file_ofs;
9401 if (pZip->m_file_offset_alignment) {
9402 MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
9403 0);
9404 }
9405
9406 /* The original zip's local header+ext block doesn't change, even with zip64,
9407 * so we can just copy it over to the dest zip */
9408 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
9409 MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
9410 MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
9411 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9412
9413 cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
9414
9415 /* Copy over the source archive bytes to the dest archive, also ensure we have
9416 * enough buf space to handle optional data descriptor */
9417 if (NULL == (pBuf = pZip->m_pAlloc(
9418 pZip->m_pAlloc_opaque, 1,
9419 (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE,
9420 src_archive_bytes_remaining)))))
9421 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9422
9423 while (src_archive_bytes_remaining) {
9424 n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE,
9425 src_archive_bytes_remaining);
9426 if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
9427 n) != n) {
9428 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
9429 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
9430 }
9431 cur_src_file_ofs += n;
9432
9433 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
9434 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
9435 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9436 }
9437 cur_dst_file_ofs += n;
9438
9439 src_archive_bytes_remaining -= n;
9440 }
9441
9442 /* Now deal with the optional data descriptor */
9443 bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
9444 if (bit_flags & 8) {
9445 /* Copy data descriptor */
9446 if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) {
9447 /* src is zip64, dest must be zip64 */
9448
9449 /* name uint32_t's */
9450 /* id 1 (optional in zip64?) */
9451 /* crc 1 */
9452 /* comp_size 2 */
9453 /* uncomp_size 2 */
9454 if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
9455 pBuf, (sizeof(mz_uint32) * 6)) !=
9456 (sizeof(mz_uint32) * 6)) {
9457 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
9458 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
9459 }
9460
9461 n = sizeof(mz_uint32) *
9462 ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5);
9463 } else {
9464 /* src is NOT zip64 */
9465 mz_bool has_id;
9466
9467 if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
9468 pBuf, sizeof(mz_uint32) * 4) !=
9469 sizeof(mz_uint32) * 4) {
9470 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
9471 return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED);
9472 }
9473
9474 has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID);
9475
9476 if (pZip->m_pState->m_zip64) {
9477 /* dest is zip64, so upgrade the data descriptor */
9478 const mz_uint32 *pSrc_descriptor =
9479 (const mz_uint32 *)((const mz_uint8 *)pBuf +
9480 (has_id ? sizeof(mz_uint32) : 0));
9481 const mz_uint32 src_crc32 = pSrc_descriptor[0];
9482 const mz_uint64 src_comp_size = pSrc_descriptor[1];
9483 const mz_uint64 src_uncomp_size = pSrc_descriptor[2];
9484
9485 mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID);
9486 mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32);
9487 mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size);
9488 mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4,
9489 src_uncomp_size);
9490
9491 n = sizeof(mz_uint32) * 6;
9492 } else {
9493 /* dest is NOT zip64, just copy it as-is */
9494 n = sizeof(mz_uint32) * (has_id ? 4 : 3);
9495 }
9496 }
9497
9498 if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
9499 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
9500 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9501 }
9502
9503 cur_src_file_ofs += n;
9504 cur_dst_file_ofs += n;
9505 }
9506 pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
9507
9508 /* Finally, add the new central dir header */
9509 orig_central_dir_size = pState->m_central_dir.m_size;
9510
9511 memcpy(new_central_header, pSrc_central_header,
9512 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
9513
9514 if (pState->m_zip64) {
9515 /* This is the painful part: We need to write a new central dir header + ext
9516 * block with updated zip64 fields, and ensure the old fields (if any) are
9517 * not included. */
9518 const mz_uint8 *pSrc_ext =
9519 pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len;
9520 mz_zip_array new_ext_block;
9521
9522 mz_zip_array_init(&new_ext_block, sizeof(mz_uint8));
9523
9524 MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS,
9525 MZ_UINT32_MAX);
9526 MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS,
9527 MZ_UINT32_MAX);
9528 MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
9529 MZ_UINT32_MAX);
9530
9531 if (!mz_zip_writer_update_zip64_extension_block(
9532 &new_ext_block, pZip, pSrc_ext, src_ext_len,
9533 &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size,
9534 &local_dir_header_ofs, NULL)) {
9535 mz_zip_array_clear(pZip, &new_ext_block);
9536 return MZ_FALSE;
9537 }
9538
9539 MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS,
9540 new_ext_block.m_size);
9541
9542 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir,
9543 new_central_header,
9544 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) {
9545 mz_zip_array_clear(pZip, &new_ext_block);
9546 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9547 }
9548
9549 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir,
9550 pSrc_central_header +
9551 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE,
9552 src_filename_len)) {
9553 mz_zip_array_clear(pZip, &new_ext_block);
9554 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
9555 MZ_FALSE);
9556 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9557 }
9558
9559 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p,
9560 new_ext_block.m_size)) {
9561 mz_zip_array_clear(pZip, &new_ext_block);
9562 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
9563 MZ_FALSE);
9564 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9565 }
9566
9567 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir,
9568 pSrc_central_header +
9569 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
9570 src_filename_len + src_ext_len,
9571 src_comment_len)) {
9572 mz_zip_array_clear(pZip, &new_ext_block);
9573 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
9574 MZ_FALSE);
9575 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9576 }
9577
9578 mz_zip_array_clear(pZip, &new_ext_block);
9579 } else {
9580 /* sanity checks */
9581 if (cur_dst_file_ofs > MZ_UINT32_MAX)
9582 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
9583
9584 if (local_dir_header_ofs >= MZ_UINT32_MAX)
9585 return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE);
9586
9587 MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
9588 local_dir_header_ofs);
9589
9590 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir,
9591 new_central_header,
9592 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
9593 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9594
9595 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir,
9596 pSrc_central_header +
9597 MZ_ZIP_CENTRAL_DIR_HEADER_SIZE,
9598 src_central_dir_following_data_size)) {
9599 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
9600 MZ_FALSE);
9601 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9602 }
9603 }
9604
9605 /* This shouldn't trigger unless we screwed up during the initial sanity
9606 * checks */
9607 if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) {
9608 /* TODO: Support central dirs >= 32-bits in size */
9609 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
9610 MZ_FALSE);
9611 return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE);
9612 }
9613
9614 n = (mz_uint32)orig_central_dir_size;
9615 if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
9616 mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
9617 MZ_FALSE);
9618 return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED);
9619 }
9620
9621 pZip->m_total_files++;
9622 pZip->m_archive_size = cur_dst_file_ofs;
9623
9624 return MZ_TRUE;
9625 }
9626
9627 mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
9628 mz_zip_internal_state *pState;
9629 mz_uint64 central_dir_ofs, central_dir_size;
9630 mz_uint8 hdr[256];
9631
9632 if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
9633 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9634
9635 pState = pZip->m_pState;
9636
9637 if (pState->m_zip64) {
9638 if ((pZip->m_total_files > MZ_UINT32_MAX) ||
9639 (pState->m_central_dir.m_size >= MZ_UINT32_MAX))
9640 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
9641 } else {
9642 if ((pZip->m_total_files > MZ_UINT16_MAX) ||
9643 ((pZip->m_archive_size + pState->m_central_dir.m_size +
9644 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX))
9645 return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES);
9646 }
9647
9648 central_dir_ofs = 0;
9649 central_dir_size = 0;
9650 if (pZip->m_total_files) {
9651 /* Write central directory */
9652 central_dir_ofs = pZip->m_archive_size;
9653 central_dir_size = pState->m_central_dir.m_size;
9654 pZip->m_central_directory_file_ofs = central_dir_ofs;
9655 if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
9656 pState->m_central_dir.m_p,
9657 (size_t)central_dir_size) != central_dir_size)
9658 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9659
9660 pZip->m_archive_size += central_dir_size;
9661 }
9662
9663 if (pState->m_zip64) {
9664 /* Write zip64 end of central directory header */
9665 mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size;
9666
9667 MZ_CLEAR_OBJ(hdr);
9668 MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS,
9669 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG);
9670 MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS,
9671 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) -
9672 sizeof(mz_uint64));
9673 MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS,
9674 0x031E); /* TODO: always Unix */
9675 MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D);
9676 MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
9677 pZip->m_total_files);
9678 MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS,
9679 pZip->m_total_files);
9680 MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size);
9681 MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs);
9682 if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
9683 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
9684 MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)
9685 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9686
9687 pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE;
9688
9689 /* Write zip64 end of central directory locator */
9690 MZ_CLEAR_OBJ(hdr);
9691 MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS,
9692 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG);
9693 MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS,
9694 rel_ofs_to_zip64_ecdr);
9695 MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1);
9696 if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
9697 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) !=
9698 MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE)
9699 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9700
9701 pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE;
9702 }
9703
9704 /* Write end of central directory record */
9705 MZ_CLEAR_OBJ(hdr);
9706 MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
9707 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
9708 MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
9709 MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files));
9710 MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS,
9711 MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files));
9712 MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS,
9713 MZ_MIN(MZ_UINT32_MAX, central_dir_size));
9714 MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS,
9715 MZ_MIN(MZ_UINT32_MAX, central_dir_ofs));
9716
9717 if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
9718 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
9719 MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
9720 return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED);
9721
9722 #ifndef MINIZ_NO_STDIO
9723 if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
9724 return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED);
9725 #endif /* #ifndef MINIZ_NO_STDIO */
9726
9727 pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE;
9728
9729 pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
9730 return MZ_TRUE;
9731 }
9732
9733 mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf,
9734 size_t *pSize) {
9735 if ((!ppBuf) || (!pSize))
9736 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9737
9738 *ppBuf = NULL;
9739 *pSize = 0;
9740
9741 if ((!pZip) || (!pZip->m_pState))
9742 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9743
9744 if (pZip->m_pWrite != mz_zip_heap_write_func)
9745 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
9746
9747 if (!mz_zip_writer_finalize_archive(pZip))
9748 return MZ_FALSE;
9749
9750 *ppBuf = pZip->m_pState->m_pMem;
9751 *pSize = pZip->m_pState->m_mem_size;
9752 pZip->m_pState->m_pMem = NULL;
9753 pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
9754
9755 return MZ_TRUE;
9756 }
9757
9758 mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
9759 return mz_zip_writer_end_internal(pZip, MZ_TRUE);
9760 }
9761
9762 #ifndef MINIZ_NO_STDIO
9763 mz_bool mz_zip_add_mem_to_archive_file_in_place(
9764 const char *pZip_filename, const char *pArchive_name, const void *pBuf,
9765 size_t buf_size, const void *pComment, mz_uint16 comment_size,
9766 mz_uint level_and_flags) {
9767 return mz_zip_add_mem_to_archive_file_in_place_v2(
9768 pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size,
9769 level_and_flags, NULL);
9770 }
9771
9772 mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(
9773 const char *pZip_filename, const char *pArchive_name, const void *pBuf,
9774 size_t buf_size, const void *pComment, mz_uint16 comment_size,
9775 mz_uint level_and_flags, mz_zip_error *pErr) {
9776 mz_bool status, created_new_archive = MZ_FALSE;
9777 mz_zip_archive zip_archive;
9778 struct MZ_FILE_STAT_STRUCT file_stat;
9779 mz_zip_error actual_err = MZ_ZIP_NO_ERROR;
9780
9781 mz_zip_zero_struct(&zip_archive);
9782 if ((int)level_and_flags < 0)
9783 level_and_flags = MZ_DEFAULT_LEVEL;
9784
9785 if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
9786 ((comment_size) && (!pComment)) ||
9787 ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) {
9788 if (pErr)
9789 *pErr = MZ_ZIP_INVALID_PARAMETER;
9790 return MZ_FALSE;
9791 }
9792
9793 if (!mz_zip_writer_validate_archive_name(pArchive_name)) {
9794 if (pErr)
9795 *pErr = MZ_ZIP_INVALID_FILENAME;
9796 return MZ_FALSE;
9797 }
9798
9799 /* Important: The regular non-64 bit version of stat() can fail here if the
9800 * file is very large, which could cause the archive to be overwritten. */
9801 /* So be sure to compile with _LARGEFILE64_SOURCE 1 */
9802 if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
9803 /* Create a new archive. */
9804 if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0,
9805 level_and_flags)) {
9806 if (pErr)
9807 *pErr = zip_archive.m_last_error;
9808 return MZ_FALSE;
9809 }
9810
9811 created_new_archive = MZ_TRUE;
9812 } else {
9813 /* Append to an existing archive. */
9814 if (!mz_zip_reader_init_file_v2(
9815 &zip_archive, pZip_filename,
9816 level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0,
9817 0)) {
9818 if (pErr)
9819 *pErr = zip_archive.m_last_error;
9820 return MZ_FALSE;
9821 }
9822
9823 if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename,
9824 level_and_flags)) {
9825 if (pErr)
9826 *pErr = zip_archive.m_last_error;
9827
9828 mz_zip_reader_end_internal(&zip_archive, MZ_FALSE);
9829
9830 return MZ_FALSE;
9831 }
9832 }
9833
9834 status =
9835 mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
9836 pComment, comment_size, level_and_flags, 0, 0);
9837 actual_err = zip_archive.m_last_error;
9838
9839 /* Always finalize, even if adding failed for some reason, so we have a valid
9840 * central directory. (This may not always succeed, but we can try.) */
9841 if (!mz_zip_writer_finalize_archive(&zip_archive)) {
9842 if (!actual_err)
9843 actual_err = zip_archive.m_last_error;
9844
9845 status = MZ_FALSE;
9846 }
9847
9848 if (!mz_zip_writer_end_internal(&zip_archive, status)) {
9849 if (!actual_err)
9850 actual_err = zip_archive.m_last_error;
9851
9852 status = MZ_FALSE;
9853 }
9854
9855 if ((!status) && (created_new_archive)) {
9856 /* It's a new archive and something went wrong, so just delete it. */
9857 int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
9858 (void)ignoredStatus;
9859 }
9860
9861 if (pErr)
9862 *pErr = actual_err;
9863
9864 return status;
9865 }
9866
9867 void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename,
9868 const char *pArchive_name,
9869 const char *pComment,
9870 size_t *pSize, mz_uint flags,
9871 mz_zip_error *pErr) {
9872 mz_uint32 file_index;
9873 mz_zip_archive zip_archive;
9874 void *p = NULL;
9875
9876 if (pSize)
9877 *pSize = 0;
9878
9879 if ((!pZip_filename) || (!pArchive_name)) {
9880 if (pErr)
9881 *pErr = MZ_ZIP_INVALID_PARAMETER;
9882
9883 return NULL;
9884 }
9885
9886 mz_zip_zero_struct(&zip_archive);
9887 if (!mz_zip_reader_init_file_v2(
9888 &zip_archive, pZip_filename,
9889 flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) {
9890 if (pErr)
9891 *pErr = zip_archive.m_last_error;
9892
9893 return NULL;
9894 }
9895
9896 if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags,
9897 &file_index)) {
9898 p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
9899 }
9900
9901 mz_zip_reader_end_internal(&zip_archive, p != NULL);
9902
9903 if (pErr)
9904 *pErr = zip_archive.m_last_error;
9905
9906 return p;
9907 }
9908
9909 void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
9910 const char *pArchive_name,
9911 size_t *pSize, mz_uint flags) {
9912 return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name,
9913 NULL, pSize, flags, NULL);
9914 }
9915
9916 #endif /* #ifndef MINIZ_NO_STDIO */
9917
9918 #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */
9919
9920 /* ------------------- Misc utils */
9921
9922 mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) {
9923 return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID;
9924 }
9925
9926 mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) {
9927 return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID;
9928 }
9929
9930 mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) {
9931 mz_zip_error prev_err;
9932
9933 if (!pZip)
9934 return MZ_ZIP_INVALID_PARAMETER;
9935
9936 prev_err = pZip->m_last_error;
9937
9938 pZip->m_last_error = err_num;
9939 return prev_err;
9940 }
9941
9942 mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) {
9943 if (!pZip)
9944 return MZ_ZIP_INVALID_PARAMETER;
9945
9946 return pZip->m_last_error;
9947 }
9948
9949 mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) {
9950 return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR);
9951 }
9952
9953 mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) {
9954 mz_zip_error prev_err;
9955
9956 if (!pZip)
9957 return MZ_ZIP_INVALID_PARAMETER;
9958
9959 prev_err = pZip->m_last_error;
9960
9961 pZip->m_last_error = MZ_ZIP_NO_ERROR;
9962 return prev_err;
9963 }
9964
9965 const char *mz_zip_get_error_string(mz_zip_error mz_err) {
9966 switch (mz_err) {
9967 case MZ_ZIP_NO_ERROR:
9968 return "no error";
9969 case MZ_ZIP_UNDEFINED_ERROR:
9970 return "undefined error";
9971 case MZ_ZIP_TOO_MANY_FILES:
9972 return "too many files";
9973 case MZ_ZIP_FILE_TOO_LARGE:
9974 return "file too large";
9975 case MZ_ZIP_UNSUPPORTED_METHOD:
9976 return "unsupported method";
9977 case MZ_ZIP_UNSUPPORTED_ENCRYPTION:
9978 return "unsupported encryption";
9979 case MZ_ZIP_UNSUPPORTED_FEATURE:
9980 return "unsupported feature";
9981 case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR:
9982 return "failed finding central directory";
9983 case MZ_ZIP_NOT_AN_ARCHIVE:
9984 return "not a ZIP archive";
9985 case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED:
9986 return "invalid header or archive is corrupted";
9987 case MZ_ZIP_UNSUPPORTED_MULTIDISK:
9988 return "unsupported multidisk archive";
9989 case MZ_ZIP_DECOMPRESSION_FAILED:
9990 return "decompression failed or archive is corrupted";
9991 case MZ_ZIP_COMPRESSION_FAILED:
9992 return "compression failed";
9993 case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE:
9994 return "unexpected decompressed size";
9995 case MZ_ZIP_CRC_CHECK_FAILED:
9996 return "CRC-32 check failed";
9997 case MZ_ZIP_UNSUPPORTED_CDIR_SIZE:
9998 return "unsupported central directory size";
9999 case MZ_ZIP_ALLOC_FAILED:
10000 return "allocation failed";
10001 case MZ_ZIP_FILE_OPEN_FAILED:
10002 return "file open failed";
10003 case MZ_ZIP_FILE_CREATE_FAILED:
10004 return "file create failed";
10005 case MZ_ZIP_FILE_WRITE_FAILED:
10006 return "file write failed";
10007 case MZ_ZIP_FILE_READ_FAILED:
10008 return "file read failed";
10009 case MZ_ZIP_FILE_CLOSE_FAILED:
10010 return "file close failed";
10011 case MZ_ZIP_FILE_SEEK_FAILED:
10012 return "file seek failed";
10013 case MZ_ZIP_FILE_STAT_FAILED:
10014 return "file stat failed";
10015 case MZ_ZIP_INVALID_PARAMETER:
10016 return "invalid parameter";
10017 case MZ_ZIP_INVALID_FILENAME:
10018 return "invalid filename";
10019 case MZ_ZIP_BUF_TOO_SMALL:
10020 return "buffer too small";
10021 case MZ_ZIP_INTERNAL_ERROR:
10022 return "internal error";
10023 case MZ_ZIP_FILE_NOT_FOUND:
10024 return "file not found";
10025 case MZ_ZIP_ARCHIVE_TOO_LARGE:
10026 return "archive is too large";
10027 case MZ_ZIP_VALIDATION_FAILED:
10028 return "validation failed";
10029 case MZ_ZIP_WRITE_CALLBACK_FAILED:
10030 return "write callback failed";
10031 case MZ_ZIP_TOTAL_ERRORS:
10032 return "total errors";
10033 default:
10034 break;
10035 }
10036
10037 return "unknown error";
10038 }
10039
10040 /* Note: Just because the archive is not zip64 doesn't necessarily mean it
10041 * doesn't have Zip64 extended information extra field, argh. */
10042 mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) {
10043 if ((!pZip) || (!pZip->m_pState))
10044 return MZ_FALSE;
10045
10046 return pZip->m_pState->m_zip64;
10047 }
10048
10049 size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) {
10050 if ((!pZip) || (!pZip->m_pState))
10051 return 0;
10052
10053 return pZip->m_pState->m_central_dir.m_size;
10054 }
10055
10056 mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
10057 return pZip ? pZip->m_total_files : 0;
10058 }
10059
10060 mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) {
10061 if (!pZip)
10062 return 0;
10063 return pZip->m_archive_size;
10064 }
10065
10066 mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) {
10067 if ((!pZip) || (!pZip->m_pState))
10068 return 0;
10069 return pZip->m_pState->m_file_archive_start_ofs;
10070 }
10071
10072 MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) {
10073 if ((!pZip) || (!pZip->m_pState))
10074 return 0;
10075 return pZip->m_pState->m_pFile;
10076 }
10077
10078 size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs,
10079 void *pBuf, size_t n) {
10080 if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead))
10081 return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
10082
10083 return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n);
10084 }
10085
10086 mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
10087 char *pFilename, mz_uint filename_buf_size) {
10088 mz_uint n;
10089 const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index);
10090 if (!p) {
10091 if (filename_buf_size)
10092 pFilename[0] = '\0';
10093 mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER);
10094 return 0;
10095 }
10096 n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
10097 if (filename_buf_size) {
10098 n = MZ_MIN(n, filename_buf_size - 1);
10099 memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
10100 pFilename[n] = '\0';
10101 }
10102 return n + 1;
10103 }
10104
10105 mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
10106 mz_zip_archive_file_stat *pStat) {
10107 return mz_zip_file_stat_internal(
10108 pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL);
10109 }
10110
10111 mz_bool mz_zip_end(mz_zip_archive *pZip) {
10112 if (!pZip)
10113 return MZ_FALSE;
10114
10115 if (pZip->m_zip_mode == MZ_ZIP_MODE_READING)
10116 return mz_zip_reader_end(pZip);
10117 #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
10118 else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) ||
10119 (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))
10120 return mz_zip_writer_end(pZip);
10121 #endif
10122
10123 return MZ_FALSE;
10124 }
10125
10126 #ifdef __cplusplus
10127 }
10128 #endif
10129
10130 #endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/