deflate.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. /* deflate.c -- compress data using the deflation algorithm
  2. * Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. */
  5. /*
  6. * ALGORITHM
  7. *
  8. * The "deflation" process depends on being able to identify portions
  9. * of the input text which are identical to earlier input (within a
  10. * sliding window trailing behind the input currently being processed).
  11. *
  12. * The most straightforward technique turns out to be the fastest for
  13. * most input files: try all possible matches and select the longest.
  14. * The key feature of this algorithm is that insertions into the string
  15. * dictionary are very simple and thus fast, and deletions are avoided
  16. * completely. Insertions are performed at each input character, whereas
  17. * string matches are performed only when the previous match ends. So it
  18. * is preferable to spend more time in matches to allow very fast string
  19. * insertions and avoid deletions. The matching algorithm for small
  20. * strings is inspired from that of Rabin & Karp. A brute force approach
  21. * is used to find longer strings when a small match has been found.
  22. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  23. * (by Leonid Broukhis).
  24. * A previous version of this file used a more sophisticated algorithm
  25. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  26. * time, but has a larger average cost, uses more memory and is patented.
  27. * However the F&G algorithm may be faster for some highly redundant
  28. * files if the parameter max_chain_length (described below) is too large.
  29. *
  30. * ACKNOWLEDGEMENTS
  31. *
  32. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  33. * I found it in 'freeze' written by Leonid Broukhis.
  34. * Thanks to many people for bug reports and testing.
  35. *
  36. * REFERENCES
  37. *
  38. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  39. * Available in https://tools.ietf.org/html/rfc1951
  40. *
  41. * A description of the Rabin and Karp algorithm is given in the book
  42. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  43. *
  44. * Fiala,E.R., and Greene,D.H.
  45. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  46. *
  47. */
  48. #include "zbuild.h"
  49. #include "deflate.h"
  50. #include "deflate_p.h"
  51. #include "functable.h"
  52. /* Avoid conflicts with zlib.h macros */
  53. #ifdef ZLIB_COMPAT
  54. # undef deflateInit
  55. # undef deflateInit2
  56. #endif
  57. const char PREFIX(deflate_copyright)[] = " deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler ";
  58. /*
  59. If you use the zlib library in a product, an acknowledgment is welcome
  60. in the documentation of your product. If for some reason you cannot
  61. include such an acknowledgment, I would appreciate that you keep this
  62. copyright string in the executable of your product.
  63. */
  64. /* ===========================================================================
  65. * Architecture-specific hooks.
  66. */
  67. #ifdef S390_DFLTCC_DEFLATE
  68. # include "arch/s390/dfltcc_deflate.h"
  69. /* DFLTCC instructions require window to be page-aligned */
  70. # define PAD_WINDOW PAD_4096
  71. # define WINDOW_PAD_SIZE 4096
  72. # define HINT_ALIGNED_WINDOW HINT_ALIGNED_4096
  73. #else
  74. # define PAD_WINDOW PAD_64
  75. # define WINDOW_PAD_SIZE 64
  76. # define HINT_ALIGNED_WINDOW HINT_ALIGNED_64
  77. /* Adjust the window size for the arch-specific deflate code. */
  78. # define DEFLATE_ADJUST_WINDOW_SIZE(n) (n)
  79. /* Invoked at the beginning of deflateSetDictionary(). Useful for checking arch-specific window data. */
  80. # define DEFLATE_SET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
  81. /* Invoked at the beginning of deflateGetDictionary(). Useful for adjusting arch-specific window data. */
  82. # define DEFLATE_GET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
  83. /* Invoked at the end of deflateResetKeep(). Useful for initializing arch-specific extension blocks. */
  84. # define DEFLATE_RESET_KEEP_HOOK(strm) do {} while (0)
  85. /* Invoked at the beginning of deflateParams(). Useful for updating arch-specific compression parameters. */
  86. # define DEFLATE_PARAMS_HOOK(strm, level, strategy, hook_flush) do {} while (0)
  87. /* Returns whether the last deflate(flush) operation did everything it's supposed to do. */
  88. # define DEFLATE_DONE(strm, flush) 1
  89. /* Adjusts the upper bound on compressed data length based on compression parameters and uncompressed data length.
  90. * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
  91. # define DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen) do {} while (0)
  92. /* Returns whether an optimistic upper bound on compressed data length should *not* be used.
  93. * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
  94. # define DEFLATE_NEED_CONSERVATIVE_BOUND(strm) 0
  95. /* Invoked for each deflate() call. Useful for plugging arch-specific deflation code. */
  96. # define DEFLATE_HOOK(strm, flush, bstate) 0
  97. /* Returns whether zlib-ng should compute a checksum. Set to 0 if arch-specific deflation code already does that. */
  98. # define DEFLATE_NEED_CHECKSUM(strm) 1
  99. /* Returns whether reproducibility parameter can be set to a given value. */
  100. # define DEFLATE_CAN_SET_REPRODUCIBLE(strm, reproducible) 1
  101. #endif
  102. /* ===========================================================================
  103. * Function prototypes.
  104. */
  105. static int deflateStateCheck (PREFIX3(stream) *strm);
  106. Z_INTERNAL block_state deflate_stored(deflate_state *s, int flush);
  107. Z_INTERNAL block_state deflate_fast (deflate_state *s, int flush);
  108. Z_INTERNAL block_state deflate_quick (deflate_state *s, int flush);
  109. #ifndef NO_MEDIUM_STRATEGY
  110. Z_INTERNAL block_state deflate_medium(deflate_state *s, int flush);
  111. #endif
  112. Z_INTERNAL block_state deflate_slow (deflate_state *s, int flush);
  113. Z_INTERNAL block_state deflate_rle (deflate_state *s, int flush);
  114. Z_INTERNAL block_state deflate_huff (deflate_state *s, int flush);
  115. static void lm_set_level (deflate_state *s, int level);
  116. static void lm_init (deflate_state *s);
  117. Z_INTERNAL unsigned read_buf (PREFIX3(stream) *strm, unsigned char *buf, unsigned size);
  118. /* ===========================================================================
  119. * Local data
  120. */
  121. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  122. * the desired pack level (0..9). The values given below have been tuned to
  123. * exclude worst case performance for pathological files. Better values may be
  124. * found for specific files.
  125. */
  126. typedef struct config_s {
  127. uint16_t good_length; /* reduce lazy search above this match length */
  128. uint16_t max_lazy; /* do not perform lazy search above this match length */
  129. uint16_t nice_length; /* quit search above this match length */
  130. uint16_t max_chain;
  131. compress_func func;
  132. } config;
  133. static const config configuration_table[10] = {
  134. /* good lazy nice chain */
  135. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  136. #ifdef NO_QUICK_STRATEGY
  137. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  138. /* 2 */ {4, 5, 16, 8, deflate_fast},
  139. #else
  140. /* 1 */ {0, 0, 0, 0, deflate_quick},
  141. /* 2 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  142. #endif
  143. #ifdef NO_MEDIUM_STRATEGY
  144. /* 3 */ {4, 6, 32, 32, deflate_fast},
  145. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  146. /* 5 */ {8, 16, 32, 32, deflate_slow},
  147. /* 6 */ {8, 16, 128, 128, deflate_slow},
  148. #else
  149. /* 3 */ {4, 6, 16, 6, deflate_medium},
  150. /* 4 */ {4, 12, 32, 24, deflate_medium}, /* lazy matches */
  151. /* 5 */ {8, 16, 32, 32, deflate_medium},
  152. /* 6 */ {8, 16, 128, 128, deflate_medium},
  153. #endif
  154. /* 7 */ {8, 32, 128, 256, deflate_slow},
  155. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  156. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  157. /* Note: the deflate() code requires max_lazy >= STD_MIN_MATCH and max_chain >= 4
  158. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  159. * meaning.
  160. */
  161. /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
  162. #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
  163. /* ===========================================================================
  164. * Initialize the hash table. prev[] will be initialized on the fly.
  165. */
  166. #define CLEAR_HASH(s) do { \
  167. memset((unsigned char *)s->head, 0, HASH_SIZE * sizeof(*s->head)); \
  168. } while (0)
  169. #ifdef DEF_ALLOC_DEBUG
  170. # include <stdio.h>
  171. # define LOGSZ(name,size) fprintf(stderr, "%s is %d bytes\n", name, size)
  172. # define LOGSZP(name,size,loc,pad) fprintf(stderr, "%s is %d bytes, offset %d, padded %d\n", name, size, loc, pad)
  173. # define LOGSZPL(name,size,loc,pad) fprintf(stderr, "%s is %d bytes, offset %ld, padded %d\n", name, size, loc, pad)
  174. #else
  175. # define LOGSZ(name,size)
  176. # define LOGSZP(name,size,loc,pad)
  177. # define LOGSZPL(name,size,loc,pad)
  178. #endif
  179. /* ===========================================================================
  180. * Allocate a big buffer and divide it up into the various buffers deflate needs.
  181. * Handles alignment of allocated buffer and alignment of individual buffers.
  182. */
  183. Z_INTERNAL deflate_allocs* alloc_deflate(PREFIX3(stream) *strm, int windowBits, int lit_bufsize) {
  184. int curr_size = 0;
  185. /* Define sizes */
  186. int window_size = DEFLATE_ADJUST_WINDOW_SIZE((1 << windowBits) * 2);
  187. int prev_size = (1 << windowBits) * sizeof(Pos);
  188. int head_size = HASH_SIZE * sizeof(Pos);
  189. int pending_size = lit_bufsize * LIT_BUFS;
  190. int state_size = sizeof(deflate_state);
  191. int alloc_size = sizeof(deflate_allocs);
  192. /* Calculate relative buffer positions and paddings */
  193. LOGSZP("window", window_size, PAD_WINDOW(curr_size), PADSZ(curr_size,WINDOW_PAD_SIZE));
  194. int window_pos = PAD_WINDOW(curr_size);
  195. curr_size = window_pos + window_size;
  196. LOGSZP("prev", prev_size, PAD_64(curr_size), PADSZ(curr_size,64));
  197. int prev_pos = PAD_64(curr_size);
  198. curr_size = prev_pos + prev_size;
  199. LOGSZP("head", head_size, PAD_64(curr_size), PADSZ(curr_size,64));
  200. int head_pos = PAD_64(curr_size);
  201. curr_size = head_pos + head_size;
  202. LOGSZP("pending", pending_size, PAD_64(curr_size), PADSZ(curr_size,64));
  203. int pending_pos = PAD_64(curr_size);
  204. curr_size = pending_pos + pending_size;
  205. LOGSZP("state", state_size, PAD_64(curr_size), PADSZ(curr_size,64));
  206. int state_pos = PAD_64(curr_size);
  207. curr_size = state_pos + state_size;
  208. LOGSZP("alloc", alloc_size, PAD_16(curr_size), PADSZ(curr_size,16));
  209. int alloc_pos = PAD_16(curr_size);
  210. curr_size = alloc_pos + alloc_size;
  211. /* Add 64-1 or 4096-1 to allow window alignment, and round size of buffer up to multiple of 64 */
  212. int total_size = PAD_64(curr_size + (WINDOW_PAD_SIZE - 1));
  213. /* Allocate buffer, align to 64-byte cacheline, and zerofill the resulting buffer */
  214. char *original_buf = strm->zalloc(strm->opaque, 1, total_size);
  215. if (original_buf == NULL)
  216. return NULL;
  217. char *buff = (char *)HINT_ALIGNED_WINDOW((char *)PAD_WINDOW(original_buf));
  218. LOGSZPL("Buffer alloc", total_size, PADSZ((uintptr_t)original_buf,WINDOW_PAD_SIZE), PADSZ(curr_size,WINDOW_PAD_SIZE));
  219. /* Initialize alloc_bufs */
  220. deflate_allocs *alloc_bufs = (struct deflate_allocs_s *)(buff + alloc_pos);
  221. alloc_bufs->buf_start = (char *)original_buf;
  222. alloc_bufs->zfree = strm->zfree;
  223. /* Assign buffers */
  224. alloc_bufs->window = (unsigned char *)HINT_ALIGNED_WINDOW(buff + window_pos);
  225. alloc_bufs->prev = (Pos *)HINT_ALIGNED_64(buff + prev_pos);
  226. alloc_bufs->head = (Pos *)HINT_ALIGNED_64(buff + head_pos);
  227. alloc_bufs->pending_buf = (unsigned char *)HINT_ALIGNED_64(buff + pending_pos);
  228. alloc_bufs->state = (deflate_state *)HINT_ALIGNED_16(buff + state_pos);
  229. memset((char *)alloc_bufs->prev, 0, prev_size);
  230. return alloc_bufs;
  231. }
  232. /* ===========================================================================
  233. * Free all allocated deflate buffers
  234. */
  235. static inline void free_deflate(PREFIX3(stream) *strm) {
  236. deflate_state *state = (deflate_state *)strm->state;
  237. if (state->alloc_bufs != NULL) {
  238. deflate_allocs *alloc_bufs = state->alloc_bufs;
  239. alloc_bufs->zfree(strm->opaque, alloc_bufs->buf_start);
  240. strm->state = NULL;
  241. }
  242. }
  243. /* ===========================================================================
  244. * Initialize deflate state and buffers.
  245. * This function is hidden in ZLIB_COMPAT builds.
  246. */
  247. int32_t ZNG_CONDEXPORT PREFIX(deflateInit2)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
  248. int32_t memLevel, int32_t strategy) {
  249. /* Todo: ignore strm->next_in if we use it as window */
  250. deflate_state *s;
  251. int wrap = 1;
  252. /* Initialize functable */
  253. FUNCTABLE_INIT;
  254. if (strm == NULL)
  255. return Z_STREAM_ERROR;
  256. strm->msg = NULL;
  257. if (strm->zalloc == NULL) {
  258. strm->zalloc = PREFIX(zcalloc);
  259. strm->opaque = NULL;
  260. }
  261. if (strm->zfree == NULL)
  262. strm->zfree = PREFIX(zcfree);
  263. if (level == Z_DEFAULT_COMPRESSION)
  264. level = 6;
  265. if (windowBits < 0) { /* suppress zlib wrapper */
  266. wrap = 0;
  267. if (windowBits < -MAX_WBITS)
  268. return Z_STREAM_ERROR;
  269. windowBits = -windowBits;
  270. #ifdef GZIP
  271. } else if (windowBits > MAX_WBITS) {
  272. wrap = 2; /* write gzip wrapper instead */
  273. windowBits -= 16;
  274. #endif
  275. }
  276. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < MIN_WBITS ||
  277. windowBits > MAX_WBITS || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED ||
  278. (windowBits == 8 && wrap != 1)) {
  279. return Z_STREAM_ERROR;
  280. }
  281. if (windowBits == 8)
  282. windowBits = 9; /* until 256-byte window bug fixed */
  283. /* Allocate buffers */
  284. int lit_bufsize = 1 << (memLevel + 6);
  285. deflate_allocs *alloc_bufs = alloc_deflate(strm, windowBits, lit_bufsize);
  286. if (alloc_bufs == NULL)
  287. return Z_MEM_ERROR;
  288. s = alloc_bufs->state;
  289. s->alloc_bufs = alloc_bufs;
  290. s->window = alloc_bufs->window;
  291. s->prev = alloc_bufs->prev;
  292. s->head = alloc_bufs->head;
  293. s->pending_buf = alloc_bufs->pending_buf;
  294. strm->state = (struct internal_state *)s;
  295. s->strm = strm;
  296. s->status = INIT_STATE; /* to pass state test in deflateReset() */
  297. s->wrap = wrap;
  298. s->gzhead = NULL;
  299. s->w_bits = (unsigned int)windowBits;
  300. s->w_size = 1 << s->w_bits;
  301. s->w_mask = s->w_size - 1;
  302. s->high_water = 0; /* nothing written to s->window yet */
  303. s->lit_bufsize = lit_bufsize; /* 16K elements by default */
  304. /* We overlay pending_buf and sym_buf. This works since the average size
  305. * for length/distance pairs over any compressed block is assured to be 31
  306. * bits or less.
  307. *
  308. * Analysis: The longest fixed codes are a length code of 8 bits plus 5
  309. * extra bits, for lengths 131 to 257. The longest fixed distance codes are
  310. * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
  311. * possible fixed-codes length/distance pair is then 31 bits total.
  312. *
  313. * sym_buf starts one-fourth of the way into pending_buf. So there are
  314. * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
  315. * in sym_buf is three bytes -- two for the distance and one for the
  316. * literal/length. As each symbol is consumed, the pointer to the next
  317. * sym_buf value to read moves forward three bytes. From that symbol, up to
  318. * 31 bits are written to pending_buf. The closest the written pending_buf
  319. * bits gets to the next sym_buf symbol to read is just before the last
  320. * code is written. At that time, 31*(n-2) bits have been written, just
  321. * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
  322. * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
  323. * symbols are written.) The closest the writing gets to what is unread is
  324. * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
  325. * can range from 128 to 32768.
  326. *
  327. * Therefore, at a minimum, there are 142 bits of space between what is
  328. * written and what is read in the overlain buffers, so the symbols cannot
  329. * be overwritten by the compressed data. That space is actually 139 bits,
  330. * due to the three-bit fixed-code block header.
  331. *
  332. * That covers the case where either Z_FIXED is specified, forcing fixed
  333. * codes, or when the use of fixed codes is chosen, because that choice
  334. * results in a smaller compressed block than dynamic codes. That latter
  335. * condition then assures that the above analysis also covers all dynamic
  336. * blocks. A dynamic-code block will only be chosen to be emitted if it has
  337. * fewer bits than a fixed-code block would for the same set of symbols.
  338. * Therefore its average symbol length is assured to be less than 31. So
  339. * the compressed data for a dynamic block also cannot overwrite the
  340. * symbols from which it is being constructed.
  341. */
  342. s->pending_buf_size = s->lit_bufsize * 4;
  343. if (s->window == NULL || s->prev == NULL || s->head == NULL || s->pending_buf == NULL) {
  344. s->status = FINISH_STATE;
  345. strm->msg = ERR_MSG(Z_MEM_ERROR);
  346. PREFIX(deflateEnd)(strm);
  347. return Z_MEM_ERROR;
  348. }
  349. #ifdef LIT_MEM
  350. s->d_buf = (uint16_t *)(s->pending_buf + (s->lit_bufsize << 1));
  351. s->l_buf = s->pending_buf + (s->lit_bufsize << 2);
  352. s->sym_end = s->lit_bufsize - 1;
  353. #else
  354. s->sym_buf = s->pending_buf + s->lit_bufsize;
  355. s->sym_end = (s->lit_bufsize - 1) * 3;
  356. #endif
  357. /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
  358. * on 16 bit machines and because stored blocks are restricted to
  359. * 64K-1 bytes.
  360. */
  361. s->level = level;
  362. s->strategy = strategy;
  363. s->block_open = 0;
  364. s->reproducible = 0;
  365. return PREFIX(deflateReset)(strm);
  366. }
  367. #ifndef ZLIB_COMPAT
  368. int32_t Z_EXPORT PREFIX(deflateInit)(PREFIX3(stream) *strm, int32_t level) {
  369. return PREFIX(deflateInit2)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  370. }
  371. #endif
  372. /* Function used by zlib.h and zlib-ng version 2.0 macros */
  373. int32_t Z_EXPORT PREFIX(deflateInit_)(PREFIX3(stream) *strm, int32_t level, const char *version, int32_t stream_size) {
  374. if (CHECK_VER_STSIZE(version, stream_size))
  375. return Z_VERSION_ERROR;
  376. return PREFIX(deflateInit2)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  377. }
  378. /* Function used by zlib.h and zlib-ng version 2.0 macros */
  379. int32_t Z_EXPORT PREFIX(deflateInit2_)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
  380. int32_t memLevel, int32_t strategy, const char *version, int32_t stream_size) {
  381. if (CHECK_VER_STSIZE(version, stream_size))
  382. return Z_VERSION_ERROR;
  383. return PREFIX(deflateInit2)(strm, level, method, windowBits, memLevel, strategy);
  384. }
  385. /* =========================================================================
  386. * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
  387. */
  388. static int deflateStateCheck(PREFIX3(stream) *strm) {
  389. deflate_state *s;
  390. if (strm == NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
  391. return 1;
  392. s = strm->state;
  393. if (s == NULL || s->alloc_bufs == NULL || s->strm != strm || (s->status < INIT_STATE || s->status > MAX_STATE))
  394. return 1;
  395. return 0;
  396. }
  397. /* ========================================================================= */
  398. int32_t Z_EXPORT PREFIX(deflateSetDictionary)(PREFIX3(stream) *strm, const uint8_t *dictionary, uint32_t dictLength) {
  399. deflate_state *s;
  400. unsigned int str, n;
  401. int wrap;
  402. uint32_t avail;
  403. const unsigned char *next;
  404. if (deflateStateCheck(strm) || dictionary == NULL)
  405. return Z_STREAM_ERROR;
  406. s = strm->state;
  407. wrap = s->wrap;
  408. if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
  409. return Z_STREAM_ERROR;
  410. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  411. if (wrap == 1)
  412. strm->adler = FUNCTABLE_CALL(adler32)(strm->adler, dictionary, dictLength);
  413. DEFLATE_SET_DICTIONARY_HOOK(strm, dictionary, dictLength); /* hook for IBM Z DFLTCC */
  414. s->wrap = 0; /* avoid computing Adler-32 in read_buf */
  415. /* if dictionary would fill window, just replace the history */
  416. if (dictLength >= s->w_size) {
  417. if (wrap == 0) { /* already empty otherwise */
  418. CLEAR_HASH(s);
  419. s->strstart = 0;
  420. s->block_start = 0;
  421. s->insert = 0;
  422. }
  423. dictionary += dictLength - s->w_size; /* use the tail */
  424. dictLength = s->w_size;
  425. }
  426. /* insert dictionary into window and hash */
  427. avail = strm->avail_in;
  428. next = strm->next_in;
  429. strm->avail_in = dictLength;
  430. strm->next_in = (z_const unsigned char *)dictionary;
  431. PREFIX(fill_window)(s);
  432. while (s->lookahead >= STD_MIN_MATCH) {
  433. str = s->strstart;
  434. n = s->lookahead - (STD_MIN_MATCH - 1);
  435. s->insert_string(s, str, n);
  436. s->strstart = str + n;
  437. s->lookahead = STD_MIN_MATCH - 1;
  438. PREFIX(fill_window)(s);
  439. }
  440. s->strstart += s->lookahead;
  441. s->block_start = (int)s->strstart;
  442. s->insert = s->lookahead;
  443. s->lookahead = 0;
  444. s->prev_length = 0;
  445. s->match_available = 0;
  446. strm->next_in = (z_const unsigned char *)next;
  447. strm->avail_in = avail;
  448. s->wrap = wrap;
  449. return Z_OK;
  450. }
  451. /* ========================================================================= */
  452. int32_t Z_EXPORT PREFIX(deflateGetDictionary)(PREFIX3(stream) *strm, uint8_t *dictionary, uint32_t *dictLength) {
  453. deflate_state *s;
  454. unsigned int len;
  455. if (deflateStateCheck(strm))
  456. return Z_STREAM_ERROR;
  457. DEFLATE_GET_DICTIONARY_HOOK(strm, dictionary, dictLength); /* hook for IBM Z DFLTCC */
  458. s = strm->state;
  459. len = s->strstart + s->lookahead;
  460. if (len > s->w_size)
  461. len = s->w_size;
  462. if (dictionary != NULL && len)
  463. memcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
  464. if (dictLength != NULL)
  465. *dictLength = len;
  466. return Z_OK;
  467. }
  468. /* ========================================================================= */
  469. int32_t Z_EXPORT PREFIX(deflateResetKeep)(PREFIX3(stream) *strm) {
  470. deflate_state *s;
  471. if (deflateStateCheck(strm))
  472. return Z_STREAM_ERROR;
  473. strm->total_in = strm->total_out = 0;
  474. strm->msg = NULL; /* use zfree if we ever allocate msg dynamically */
  475. strm->data_type = Z_UNKNOWN;
  476. s = (deflate_state *)strm->state;
  477. s->pending = 0;
  478. s->pending_out = s->pending_buf;
  479. if (s->wrap < 0)
  480. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  481. s->status =
  482. #ifdef GZIP
  483. s->wrap == 2 ? GZIP_STATE :
  484. #endif
  485. INIT_STATE;
  486. #ifdef GZIP
  487. if (s->wrap == 2) {
  488. strm->adler = FUNCTABLE_CALL(crc32_fold_reset)(&s->crc_fold);
  489. } else
  490. #endif
  491. strm->adler = ADLER32_INITIAL_VALUE;
  492. s->last_flush = -2;
  493. zng_tr_init(s);
  494. DEFLATE_RESET_KEEP_HOOK(strm); /* hook for IBM Z DFLTCC */
  495. return Z_OK;
  496. }
  497. /* ========================================================================= */
  498. int32_t Z_EXPORT PREFIX(deflateReset)(PREFIX3(stream) *strm) {
  499. int ret = PREFIX(deflateResetKeep)(strm);
  500. if (ret == Z_OK)
  501. lm_init(strm->state);
  502. return ret;
  503. }
  504. /* ========================================================================= */
  505. int32_t Z_EXPORT PREFIX(deflateSetHeader)(PREFIX3(stream) *strm, PREFIX(gz_headerp) head) {
  506. if (deflateStateCheck(strm) || strm->state->wrap != 2)
  507. return Z_STREAM_ERROR;
  508. strm->state->gzhead = head;
  509. return Z_OK;
  510. }
  511. /* ========================================================================= */
  512. int32_t Z_EXPORT PREFIX(deflatePending)(PREFIX3(stream) *strm, uint32_t *pending, int32_t *bits) {
  513. if (deflateStateCheck(strm))
  514. return Z_STREAM_ERROR;
  515. if (pending != NULL)
  516. *pending = strm->state->pending;
  517. if (bits != NULL)
  518. *bits = strm->state->bi_valid;
  519. return Z_OK;
  520. }
  521. /* ========================================================================= */
  522. int32_t Z_EXPORT PREFIX(deflatePrime)(PREFIX3(stream) *strm, int32_t bits, int32_t value) {
  523. deflate_state *s;
  524. uint64_t value64 = (uint64_t)value;
  525. int32_t put;
  526. if (deflateStateCheck(strm))
  527. return Z_STREAM_ERROR;
  528. s = strm->state;
  529. #ifdef LIT_MEM
  530. if (bits < 0 || bits > BIT_BUF_SIZE ||
  531. (unsigned char *)s->d_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
  532. return Z_BUF_ERROR;
  533. #else
  534. if (bits < 0 || bits > BIT_BUF_SIZE || bits > (int32_t)(sizeof(value) << 3) ||
  535. s->sym_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
  536. return Z_BUF_ERROR;
  537. #endif
  538. do {
  539. put = BIT_BUF_SIZE - s->bi_valid;
  540. put = MIN(put, bits);
  541. if (s->bi_valid == 0)
  542. s->bi_buf = value64;
  543. else
  544. s->bi_buf |= (value64 & ((UINT64_C(1) << put) - 1)) << s->bi_valid;
  545. s->bi_valid += put;
  546. zng_tr_flush_bits(s);
  547. value64 >>= put;
  548. bits -= put;
  549. } while (bits);
  550. return Z_OK;
  551. }
  552. /* ========================================================================= */
  553. int32_t Z_EXPORT PREFIX(deflateParams)(PREFIX3(stream) *strm, int32_t level, int32_t strategy) {
  554. deflate_state *s;
  555. compress_func func;
  556. int hook_flush = Z_NO_FLUSH;
  557. if (deflateStateCheck(strm))
  558. return Z_STREAM_ERROR;
  559. s = strm->state;
  560. if (level == Z_DEFAULT_COMPRESSION)
  561. level = 6;
  562. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED)
  563. return Z_STREAM_ERROR;
  564. DEFLATE_PARAMS_HOOK(strm, level, strategy, &hook_flush); /* hook for IBM Z DFLTCC */
  565. func = configuration_table[s->level].func;
  566. if (((strategy != s->strategy || func != configuration_table[level].func) && s->last_flush != -2)
  567. || hook_flush != Z_NO_FLUSH) {
  568. /* Flush the last buffer. Use Z_BLOCK mode, unless the hook requests a "stronger" one. */
  569. int flush = RANK(hook_flush) > RANK(Z_BLOCK) ? hook_flush : Z_BLOCK;
  570. int err = PREFIX(deflate)(strm, flush);
  571. if (err == Z_STREAM_ERROR)
  572. return err;
  573. if (strm->avail_in || ((int)s->strstart - s->block_start) + s->lookahead || !DEFLATE_DONE(strm, flush))
  574. return Z_BUF_ERROR;
  575. }
  576. if (s->level != level) {
  577. if (s->level == 0 && s->matches != 0) {
  578. if (s->matches == 1) {
  579. FUNCTABLE_CALL(slide_hash)(s);
  580. } else {
  581. CLEAR_HASH(s);
  582. }
  583. s->matches = 0;
  584. }
  585. lm_set_level(s, level);
  586. }
  587. s->strategy = strategy;
  588. return Z_OK;
  589. }
  590. /* ========================================================================= */
  591. int32_t Z_EXPORT PREFIX(deflateTune)(PREFIX3(stream) *strm, int32_t good_length, int32_t max_lazy, int32_t nice_length, int32_t max_chain) {
  592. deflate_state *s;
  593. if (deflateStateCheck(strm))
  594. return Z_STREAM_ERROR;
  595. s = strm->state;
  596. s->good_match = (unsigned int)good_length;
  597. s->max_lazy_match = (unsigned int)max_lazy;
  598. s->nice_match = nice_length;
  599. s->max_chain_length = (unsigned int)max_chain;
  600. return Z_OK;
  601. }
  602. /* =========================================================================
  603. * For the default windowBits of 15 and memLevel of 8, this function returns
  604. * a close to exact, as well as small, upper bound on the compressed size.
  605. * They are coded as constants here for a reason--if the #define's are
  606. * changed, then this function needs to be changed as well. The return
  607. * value for 15 and 8 only works for those exact settings.
  608. *
  609. * For any setting other than those defaults for windowBits and memLevel,
  610. * the value returned is a conservative worst case for the maximum expansion
  611. * resulting from using fixed blocks instead of stored blocks, which deflate
  612. * can emit on compressed data for some combinations of the parameters.
  613. *
  614. * This function could be more sophisticated to provide closer upper bounds for
  615. * every combination of windowBits and memLevel. But even the conservative
  616. * upper bound of about 14% expansion does not seem onerous for output buffer
  617. * allocation.
  618. */
  619. unsigned long Z_EXPORT PREFIX(deflateBound)(PREFIX3(stream) *strm, unsigned long sourceLen) {
  620. deflate_state *s;
  621. unsigned long complen, wraplen;
  622. /* conservative upper bound for compressed data */
  623. complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
  624. DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen); /* hook for IBM Z DFLTCC */
  625. /* if can't get parameters, return conservative bound plus zlib wrapper */
  626. if (deflateStateCheck(strm))
  627. return complen + 6;
  628. /* compute wrapper length */
  629. s = strm->state;
  630. switch (s->wrap) {
  631. case 0: /* raw deflate */
  632. wraplen = 0;
  633. break;
  634. case 1: /* zlib wrapper */
  635. wraplen = ZLIB_WRAPLEN + (s->strstart ? 4 : 0);
  636. break;
  637. #ifdef GZIP
  638. case 2: /* gzip wrapper */
  639. wraplen = GZIP_WRAPLEN;
  640. if (s->gzhead != NULL) { /* user-supplied gzip header */
  641. unsigned char *str;
  642. if (s->gzhead->extra != NULL) {
  643. wraplen += 2 + s->gzhead->extra_len;
  644. }
  645. str = s->gzhead->name;
  646. if (str != NULL) {
  647. do {
  648. wraplen++;
  649. } while (*str++);
  650. }
  651. str = s->gzhead->comment;
  652. if (str != NULL) {
  653. do {
  654. wraplen++;
  655. } while (*str++);
  656. }
  657. if (s->gzhead->hcrc)
  658. wraplen += 2;
  659. }
  660. break;
  661. #endif
  662. default: /* for compiler happiness */
  663. wraplen = ZLIB_WRAPLEN;
  664. }
  665. /* if not default parameters, return conservative bound */
  666. if (DEFLATE_NEED_CONSERVATIVE_BOUND(strm) || /* hook for IBM Z DFLTCC */
  667. s->w_bits != MAX_WBITS || HASH_BITS < 15) {
  668. if (s->level == 0) {
  669. /* upper bound for stored blocks with length 127 (memLevel == 1) --
  670. ~4% overhead plus a small constant */
  671. complen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) + (sourceLen >> 11) + 7;
  672. }
  673. return complen + wraplen;
  674. }
  675. #ifndef NO_QUICK_STRATEGY
  676. return sourceLen /* The source size itself */
  677. + (sourceLen == 0 ? 1 : 0) /* Always at least one byte for any input */
  678. + (sourceLen < 9 ? 1 : 0) /* One extra byte for lengths less than 9 */
  679. + DEFLATE_QUICK_OVERHEAD(sourceLen) /* Source encoding overhead, padded to next full byte */
  680. + DEFLATE_BLOCK_OVERHEAD /* Deflate block overhead bytes */
  681. + wraplen; /* none, zlib or gzip wrapper */
  682. #else
  683. return sourceLen + (sourceLen >> 4) + 7 + wraplen;
  684. #endif
  685. }
  686. /* =========================================================================
  687. * Flush as much pending output as possible. All deflate() output, except for
  688. * some deflate_stored() output, goes through this function so some
  689. * applications may wish to modify it to avoid allocating a large
  690. * strm->next_out buffer and copying into it. (See also read_buf()).
  691. */
  692. Z_INTERNAL void PREFIX(flush_pending)(PREFIX3(stream) *strm) {
  693. uint32_t len;
  694. deflate_state *s = strm->state;
  695. zng_tr_flush_bits(s);
  696. len = MIN(s->pending, strm->avail_out);
  697. if (len == 0)
  698. return;
  699. Tracev((stderr, "[FLUSH]"));
  700. memcpy(strm->next_out, s->pending_out, len);
  701. strm->next_out += len;
  702. s->pending_out += len;
  703. strm->total_out += len;
  704. strm->avail_out -= len;
  705. s->pending -= len;
  706. if (s->pending == 0)
  707. s->pending_out = s->pending_buf;
  708. }
  709. /* ===========================================================================
  710. * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
  711. */
  712. #define HCRC_UPDATE(beg) \
  713. do { \
  714. if (s->gzhead->hcrc && s->pending > (beg)) \
  715. strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf + (beg), s->pending - (beg)); \
  716. } while (0)
  717. /* ========================================================================= */
  718. int32_t Z_EXPORT PREFIX(deflate)(PREFIX3(stream) *strm, int32_t flush) {
  719. int32_t old_flush; /* value of flush param for previous deflate call */
  720. deflate_state *s;
  721. if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0)
  722. return Z_STREAM_ERROR;
  723. s = strm->state;
  724. if (strm->next_out == NULL || (strm->avail_in != 0 && strm->next_in == NULL)
  725. || (s->status == FINISH_STATE && flush != Z_FINISH)) {
  726. ERR_RETURN(strm, Z_STREAM_ERROR);
  727. }
  728. if (strm->avail_out == 0) {
  729. ERR_RETURN(strm, Z_BUF_ERROR);
  730. }
  731. old_flush = s->last_flush;
  732. s->last_flush = flush;
  733. /* Flush as much pending output as possible */
  734. if (s->pending != 0) {
  735. PREFIX(flush_pending)(strm);
  736. if (strm->avail_out == 0) {
  737. /* Since avail_out is 0, deflate will be called again with
  738. * more output space, but possibly with both pending and
  739. * avail_in equal to zero. There won't be anything to do,
  740. * but this is not an error situation so make sure we
  741. * return OK instead of BUF_ERROR at next call of deflate:
  742. */
  743. s->last_flush = -1;
  744. return Z_OK;
  745. }
  746. /* Make sure there is something to do and avoid duplicate consecutive
  747. * flushes. For repeated and useless calls with Z_FINISH, we keep
  748. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  749. */
  750. } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) {
  751. ERR_RETURN(strm, Z_BUF_ERROR);
  752. }
  753. /* User must not provide more input after the first FINISH: */
  754. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  755. ERR_RETURN(strm, Z_BUF_ERROR);
  756. }
  757. /* Write the header */
  758. if (s->status == INIT_STATE && s->wrap == 0)
  759. s->status = BUSY_STATE;
  760. if (s->status == INIT_STATE) {
  761. /* zlib header */
  762. unsigned int header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  763. unsigned int level_flags;
  764. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  765. level_flags = 0;
  766. else if (s->level < 6)
  767. level_flags = 1;
  768. else if (s->level == 6)
  769. level_flags = 2;
  770. else
  771. level_flags = 3;
  772. header |= (level_flags << 6);
  773. if (s->strstart != 0)
  774. header |= PRESET_DICT;
  775. header += 31 - (header % 31);
  776. put_short_msb(s, (uint16_t)header);
  777. /* Save the adler32 of the preset dictionary: */
  778. if (s->strstart != 0)
  779. put_uint32_msb(s, strm->adler);
  780. strm->adler = ADLER32_INITIAL_VALUE;
  781. s->status = BUSY_STATE;
  782. /* Compression must start with an empty pending buffer */
  783. PREFIX(flush_pending)(strm);
  784. if (s->pending != 0) {
  785. s->last_flush = -1;
  786. return Z_OK;
  787. }
  788. }
  789. #ifdef GZIP
  790. if (s->status == GZIP_STATE) {
  791. /* gzip header */
  792. FUNCTABLE_CALL(crc32_fold_reset)(&s->crc_fold);
  793. put_byte(s, 31);
  794. put_byte(s, 139);
  795. put_byte(s, 8);
  796. if (s->gzhead == NULL) {
  797. put_uint32(s, 0);
  798. put_byte(s, 0);
  799. put_byte(s, s->level == 9 ? 2 :
  800. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
  801. put_byte(s, OS_CODE);
  802. s->status = BUSY_STATE;
  803. /* Compression must start with an empty pending buffer */
  804. PREFIX(flush_pending)(strm);
  805. if (s->pending != 0) {
  806. s->last_flush = -1;
  807. return Z_OK;
  808. }
  809. } else {
  810. put_byte(s, (s->gzhead->text ? 1 : 0) +
  811. (s->gzhead->hcrc ? 2 : 0) +
  812. (s->gzhead->extra == NULL ? 0 : 4) +
  813. (s->gzhead->name == NULL ? 0 : 8) +
  814. (s->gzhead->comment == NULL ? 0 : 16)
  815. );
  816. put_uint32(s, s->gzhead->time);
  817. put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
  818. put_byte(s, s->gzhead->os & 0xff);
  819. if (s->gzhead->extra != NULL)
  820. put_short(s, (uint16_t)s->gzhead->extra_len);
  821. if (s->gzhead->hcrc)
  822. strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf, s->pending);
  823. s->gzindex = 0;
  824. s->status = EXTRA_STATE;
  825. }
  826. }
  827. if (s->status == EXTRA_STATE) {
  828. if (s->gzhead->extra != NULL) {
  829. uint32_t beg = s->pending; /* start of bytes to update crc */
  830. uint32_t left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
  831. while (s->pending + left > s->pending_buf_size) {
  832. uint32_t copy = s->pending_buf_size - s->pending;
  833. memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, copy);
  834. s->pending = s->pending_buf_size;
  835. HCRC_UPDATE(beg);
  836. s->gzindex += copy;
  837. PREFIX(flush_pending)(strm);
  838. if (s->pending != 0) {
  839. s->last_flush = -1;
  840. return Z_OK;
  841. }
  842. beg = 0;
  843. left -= copy;
  844. }
  845. memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, left);
  846. s->pending += left;
  847. HCRC_UPDATE(beg);
  848. s->gzindex = 0;
  849. }
  850. s->status = NAME_STATE;
  851. }
  852. if (s->status == NAME_STATE) {
  853. if (s->gzhead->name != NULL) {
  854. uint32_t beg = s->pending; /* start of bytes to update crc */
  855. unsigned char val;
  856. do {
  857. if (s->pending == s->pending_buf_size) {
  858. HCRC_UPDATE(beg);
  859. PREFIX(flush_pending)(strm);
  860. if (s->pending != 0) {
  861. s->last_flush = -1;
  862. return Z_OK;
  863. }
  864. beg = 0;
  865. }
  866. val = s->gzhead->name[s->gzindex++];
  867. put_byte(s, val);
  868. } while (val != 0);
  869. HCRC_UPDATE(beg);
  870. s->gzindex = 0;
  871. }
  872. s->status = COMMENT_STATE;
  873. }
  874. if (s->status == COMMENT_STATE) {
  875. if (s->gzhead->comment != NULL) {
  876. uint32_t beg = s->pending; /* start of bytes to update crc */
  877. unsigned char val;
  878. do {
  879. if (s->pending == s->pending_buf_size) {
  880. HCRC_UPDATE(beg);
  881. PREFIX(flush_pending)(strm);
  882. if (s->pending != 0) {
  883. s->last_flush = -1;
  884. return Z_OK;
  885. }
  886. beg = 0;
  887. }
  888. val = s->gzhead->comment[s->gzindex++];
  889. put_byte(s, val);
  890. } while (val != 0);
  891. HCRC_UPDATE(beg);
  892. }
  893. s->status = HCRC_STATE;
  894. }
  895. if (s->status == HCRC_STATE) {
  896. if (s->gzhead->hcrc) {
  897. if (s->pending + 2 > s->pending_buf_size) {
  898. PREFIX(flush_pending)(strm);
  899. if (s->pending != 0) {
  900. s->last_flush = -1;
  901. return Z_OK;
  902. }
  903. }
  904. put_short(s, (uint16_t)strm->adler);
  905. FUNCTABLE_CALL(crc32_fold_reset)(&s->crc_fold);
  906. }
  907. s->status = BUSY_STATE;
  908. /* Compression must start with an empty pending buffer */
  909. PREFIX(flush_pending)(strm);
  910. if (s->pending != 0) {
  911. s->last_flush = -1;
  912. return Z_OK;
  913. }
  914. }
  915. #endif
  916. /* Start a new block or continue the current one.
  917. */
  918. if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  919. block_state bstate;
  920. bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate : /* hook for IBM Z DFLTCC */
  921. s->level == 0 ? deflate_stored(s, flush) :
  922. s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
  923. s->strategy == Z_RLE ? deflate_rle(s, flush) :
  924. (*(configuration_table[s->level].func))(s, flush);
  925. if (bstate == finish_started || bstate == finish_done) {
  926. s->status = FINISH_STATE;
  927. }
  928. if (bstate == need_more || bstate == finish_started) {
  929. if (strm->avail_out == 0) {
  930. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  931. }
  932. return Z_OK;
  933. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  934. * of deflate should use the same flush parameter to make sure
  935. * that the flush is complete. So we don't have to output an
  936. * empty block here, this will be done at next call. This also
  937. * ensures that for a very small output buffer, we emit at most
  938. * one empty block.
  939. */
  940. }
  941. if (bstate == block_done) {
  942. if (flush == Z_PARTIAL_FLUSH) {
  943. zng_tr_align(s);
  944. } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  945. zng_tr_stored_block(s, (char*)0, 0L, 0);
  946. /* For a full flush, this empty block will be recognized
  947. * as a special marker by inflate_sync().
  948. */
  949. if (flush == Z_FULL_FLUSH) {
  950. CLEAR_HASH(s); /* forget history */
  951. if (s->lookahead == 0) {
  952. s->strstart = 0;
  953. s->block_start = 0;
  954. s->insert = 0;
  955. }
  956. }
  957. }
  958. PREFIX(flush_pending)(strm);
  959. if (strm->avail_out == 0) {
  960. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  961. return Z_OK;
  962. }
  963. }
  964. }
  965. if (flush != Z_FINISH)
  966. return Z_OK;
  967. /* Write the trailer */
  968. #ifdef GZIP
  969. if (s->wrap == 2) {
  970. strm->adler = FUNCTABLE_CALL(crc32_fold_final)(&s->crc_fold);
  971. put_uint32(s, strm->adler);
  972. put_uint32(s, (uint32_t)strm->total_in);
  973. } else
  974. #endif
  975. {
  976. if (s->wrap == 1)
  977. put_uint32_msb(s, strm->adler);
  978. }
  979. PREFIX(flush_pending)(strm);
  980. /* If avail_out is zero, the application will call deflate again
  981. * to flush the rest.
  982. */
  983. if (s->wrap > 0)
  984. s->wrap = -s->wrap; /* write the trailer only once! */
  985. if (s->pending == 0) {
  986. Assert(s->bi_valid == 0, "bi_buf not flushed");
  987. return Z_STREAM_END;
  988. }
  989. return Z_OK;
  990. }
  991. /* ========================================================================= */
  992. int32_t Z_EXPORT PREFIX(deflateEnd)(PREFIX3(stream) *strm) {
  993. if (deflateStateCheck(strm))
  994. return Z_STREAM_ERROR;
  995. int32_t status = strm->state->status;
  996. /* Free allocated buffers */
  997. free_deflate(strm);
  998. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  999. }
  1000. /* =========================================================================
  1001. * Copy the source state to the destination state.
  1002. */
  1003. int32_t Z_EXPORT PREFIX(deflateCopy)(PREFIX3(stream) *dest, PREFIX3(stream) *source) {
  1004. deflate_state *ds;
  1005. deflate_state *ss;
  1006. if (deflateStateCheck(source) || dest == NULL)
  1007. return Z_STREAM_ERROR;
  1008. ss = source->state;
  1009. memcpy((void *)dest, (void *)source, sizeof(PREFIX3(stream)));
  1010. deflate_allocs *alloc_bufs = alloc_deflate(dest, ss->w_bits, ss->lit_bufsize);
  1011. if (alloc_bufs == NULL)
  1012. return Z_MEM_ERROR;
  1013. ds = alloc_bufs->state;
  1014. dest->state = (struct internal_state *) ds;
  1015. memcpy(ds, ss, sizeof(deflate_state));
  1016. ds->strm = dest;
  1017. ds->alloc_bufs = alloc_bufs;
  1018. ds->window = alloc_bufs->window;
  1019. ds->prev = alloc_bufs->prev;
  1020. ds->head = alloc_bufs->head;
  1021. ds->pending_buf = alloc_bufs->pending_buf;
  1022. if (ds->window == NULL || ds->prev == NULL || ds->head == NULL || ds->pending_buf == NULL) {
  1023. PREFIX(deflateEnd)(dest);
  1024. return Z_MEM_ERROR;
  1025. }
  1026. memcpy(ds->window, ss->window, DEFLATE_ADJUST_WINDOW_SIZE(ds->w_size * 2 * sizeof(unsigned char)));
  1027. memcpy((void *)ds->prev, (void *)ss->prev, ds->w_size * sizeof(Pos));
  1028. memcpy((void *)ds->head, (void *)ss->head, HASH_SIZE * sizeof(Pos));
  1029. memcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS);
  1030. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  1031. #ifdef LIT_MEM
  1032. ds->d_buf = (uint16_t *)(ds->pending_buf + (ds->lit_bufsize << 1));
  1033. ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2);
  1034. #else
  1035. ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
  1036. #endif
  1037. ds->l_desc.dyn_tree = ds->dyn_ltree;
  1038. ds->d_desc.dyn_tree = ds->dyn_dtree;
  1039. ds->bl_desc.dyn_tree = ds->bl_tree;
  1040. return Z_OK;
  1041. }
  1042. /* ===========================================================================
  1043. * Read a new buffer from the current input stream, update the adler32
  1044. * and total number of bytes read. All deflate() input goes through
  1045. * this function so some applications may wish to modify it to avoid
  1046. * allocating a large strm->next_in buffer and copying from it.
  1047. * (See also flush_pending()).
  1048. */
  1049. Z_INTERNAL unsigned PREFIX(read_buf)(PREFIX3(stream) *strm, unsigned char *buf, unsigned size) {
  1050. uint32_t len = MIN(strm->avail_in, size);
  1051. if (len == 0)
  1052. return 0;
  1053. strm->avail_in -= len;
  1054. if (!DEFLATE_NEED_CHECKSUM(strm)) {
  1055. memcpy(buf, strm->next_in, len);
  1056. #ifdef GZIP
  1057. } else if (strm->state->wrap == 2) {
  1058. FUNCTABLE_CALL(crc32_fold_copy)(&strm->state->crc_fold, buf, strm->next_in, len);
  1059. #endif
  1060. } else if (strm->state->wrap == 1) {
  1061. strm->adler = FUNCTABLE_CALL(adler32_fold_copy)(strm->adler, buf, strm->next_in, len);
  1062. } else {
  1063. memcpy(buf, strm->next_in, len);
  1064. }
  1065. strm->next_in += len;
  1066. strm->total_in += len;
  1067. return len;
  1068. }
  1069. /* ===========================================================================
  1070. * Set longest match variables based on level configuration
  1071. */
  1072. static void lm_set_level(deflate_state *s, int level) {
  1073. s->max_lazy_match = configuration_table[level].max_lazy;
  1074. s->good_match = configuration_table[level].good_length;
  1075. s->nice_match = configuration_table[level].nice_length;
  1076. s->max_chain_length = configuration_table[level].max_chain;
  1077. /* Use rolling hash for deflate_slow algorithm with level 9. It allows us to
  1078. * properly lookup different hash chains to speed up longest_match search. Since hashing
  1079. * method changes depending on the level we cannot put this into functable. */
  1080. if (s->max_chain_length > 1024) {
  1081. s->update_hash = &update_hash_roll;
  1082. s->insert_string = &insert_string_roll;
  1083. s->quick_insert_string = &quick_insert_string_roll;
  1084. } else {
  1085. s->update_hash = update_hash;
  1086. s->insert_string = insert_string;
  1087. s->quick_insert_string = quick_insert_string;
  1088. }
  1089. s->level = level;
  1090. }
  1091. /* ===========================================================================
  1092. * Initialize the "longest match" routines for a new zlib stream
  1093. */
  1094. static void lm_init(deflate_state *s) {
  1095. s->window_size = 2 * s->w_size;
  1096. CLEAR_HASH(s);
  1097. /* Set the default configuration parameters:
  1098. */
  1099. lm_set_level(s, s->level);
  1100. s->strstart = 0;
  1101. s->block_start = 0;
  1102. s->lookahead = 0;
  1103. s->insert = 0;
  1104. s->prev_length = 0;
  1105. s->match_available = 0;
  1106. s->match_start = 0;
  1107. s->ins_h = 0;
  1108. }
  1109. /* ===========================================================================
  1110. * Fill the window when the lookahead becomes insufficient.
  1111. * Updates strstart and lookahead.
  1112. *
  1113. * IN assertion: lookahead < MIN_LOOKAHEAD
  1114. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1115. * At least one byte has been read, or avail_in == 0; reads are
  1116. * performed for at least two bytes (required for the zip translate_eol
  1117. * option -- not supported here).
  1118. */
  1119. void Z_INTERNAL PREFIX(fill_window)(deflate_state *s) {
  1120. unsigned n;
  1121. unsigned int more; /* Amount of free space at the end of the window. */
  1122. unsigned int wsize = s->w_size;
  1123. Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  1124. do {
  1125. more = s->window_size - s->lookahead - s->strstart;
  1126. /* If the window is almost full and there is insufficient lookahead,
  1127. * move the upper half to the lower one to make room in the upper half.
  1128. */
  1129. if (s->strstart >= wsize+MAX_DIST(s)) {
  1130. memcpy(s->window, s->window+wsize, (unsigned)wsize);
  1131. if (s->match_start >= wsize) {
  1132. s->match_start -= wsize;
  1133. } else {
  1134. s->match_start = 0;
  1135. s->prev_length = 0;
  1136. }
  1137. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  1138. s->block_start -= (int)wsize;
  1139. if (s->insert > s->strstart)
  1140. s->insert = s->strstart;
  1141. FUNCTABLE_CALL(slide_hash)(s);
  1142. more += wsize;
  1143. }
  1144. if (s->strm->avail_in == 0)
  1145. break;
  1146. /* If there was no sliding:
  1147. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1148. * more == window_size - lookahead - strstart
  1149. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1150. * => more >= window_size - 2*WSIZE + 2
  1151. * In the BIG_MEM or MMAP case (not yet supported),
  1152. * window_size == input_size + MIN_LOOKAHEAD &&
  1153. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1154. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1155. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1156. */
  1157. Assert(more >= 2, "more < 2");
  1158. n = PREFIX(read_buf)(s->strm, s->window + s->strstart + s->lookahead, more);
  1159. s->lookahead += n;
  1160. /* Initialize the hash value now that we have some input: */
  1161. if (s->lookahead + s->insert >= STD_MIN_MATCH) {
  1162. unsigned int str = s->strstart - s->insert;
  1163. if (UNLIKELY(s->max_chain_length > 1024)) {
  1164. s->ins_h = s->update_hash(s->window[str], s->window[str+1]);
  1165. } else if (str >= 1) {
  1166. s->quick_insert_string(s, str + 2 - STD_MIN_MATCH);
  1167. }
  1168. unsigned int count = s->insert;
  1169. if (UNLIKELY(s->lookahead == 1)) {
  1170. count -= 1;
  1171. }
  1172. if (count > 0) {
  1173. s->insert_string(s, str, count);
  1174. s->insert -= count;
  1175. }
  1176. }
  1177. /* If the whole input has less than STD_MIN_MATCH bytes, ins_h is garbage,
  1178. * but this is not important since only literal bytes will be emitted.
  1179. */
  1180. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  1181. /* If the WIN_INIT bytes after the end of the current data have never been
  1182. * written, then zero those bytes in order to avoid memory check reports of
  1183. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  1184. * the longest match routines. Update the high water mark for the next
  1185. * time through here. WIN_INIT is set to STD_MAX_MATCH since the longest match
  1186. * routines allow scanning to strstart + STD_MAX_MATCH, ignoring lookahead.
  1187. */
  1188. if (s->high_water < s->window_size) {
  1189. unsigned int curr = s->strstart + s->lookahead;
  1190. unsigned int init;
  1191. if (s->high_water < curr) {
  1192. /* Previous high water mark below current data -- zero WIN_INIT
  1193. * bytes or up to end of window, whichever is less.
  1194. */
  1195. init = s->window_size - curr;
  1196. if (init > WIN_INIT)
  1197. init = WIN_INIT;
  1198. memset(s->window + curr, 0, init);
  1199. s->high_water = curr + init;
  1200. } else if (s->high_water < curr + WIN_INIT) {
  1201. /* High water mark at or above current data, but below current data
  1202. * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  1203. * to end of window, whichever is less.
  1204. */
  1205. init = curr + WIN_INIT - s->high_water;
  1206. if (init > s->window_size - s->high_water)
  1207. init = s->window_size - s->high_water;
  1208. memset(s->window + s->high_water, 0, init);
  1209. s->high_water += init;
  1210. }
  1211. }
  1212. Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  1213. "not enough room for search");
  1214. }
  1215. #ifndef ZLIB_COMPAT
  1216. /* =========================================================================
  1217. * Checks whether buffer size is sufficient and whether this parameter is a duplicate.
  1218. */
  1219. static int32_t deflateSetParamPre(zng_deflate_param_value **out, size_t min_size, zng_deflate_param_value *param) {
  1220. int32_t buf_error = param->size < min_size;
  1221. if (*out != NULL) {
  1222. (*out)->status = Z_BUF_ERROR;
  1223. buf_error = 1;
  1224. }
  1225. *out = param;
  1226. return buf_error;
  1227. }
  1228. /* ========================================================================= */
  1229. int32_t Z_EXPORT zng_deflateSetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
  1230. size_t i;
  1231. deflate_state *s;
  1232. zng_deflate_param_value *new_level = NULL;
  1233. zng_deflate_param_value *new_strategy = NULL;
  1234. zng_deflate_param_value *new_reproducible = NULL;
  1235. int param_buf_error;
  1236. int version_error = 0;
  1237. int buf_error = 0;
  1238. int stream_error = 0;
  1239. /* Initialize the statuses. */
  1240. for (i = 0; i < count; i++)
  1241. params[i].status = Z_OK;
  1242. /* Check whether the stream state is consistent. */
  1243. if (deflateStateCheck(strm))
  1244. return Z_STREAM_ERROR;
  1245. s = strm->state;
  1246. /* Check buffer sizes and detect duplicates. */
  1247. for (i = 0; i < count; i++) {
  1248. switch (params[i].param) {
  1249. case Z_DEFLATE_LEVEL:
  1250. param_buf_error = deflateSetParamPre(&new_level, sizeof(int), &params[i]);
  1251. break;
  1252. case Z_DEFLATE_STRATEGY:
  1253. param_buf_error = deflateSetParamPre(&new_strategy, sizeof(int), &params[i]);
  1254. break;
  1255. case Z_DEFLATE_REPRODUCIBLE:
  1256. param_buf_error = deflateSetParamPre(&new_reproducible, sizeof(int), &params[i]);
  1257. break;
  1258. default:
  1259. params[i].status = Z_VERSION_ERROR;
  1260. version_error = 1;
  1261. param_buf_error = 0;
  1262. break;
  1263. }
  1264. if (param_buf_error) {
  1265. params[i].status = Z_BUF_ERROR;
  1266. buf_error = 1;
  1267. }
  1268. }
  1269. /* Exit early if small buffers or duplicates are detected. */
  1270. if (buf_error)
  1271. return Z_BUF_ERROR;
  1272. /* Apply changes, remember if there were errors. */
  1273. if (new_level != NULL || new_strategy != NULL) {
  1274. int ret = PREFIX(deflateParams)(strm, new_level == NULL ? s->level : *(int *)new_level->buf,
  1275. new_strategy == NULL ? s->strategy : *(int *)new_strategy->buf);
  1276. if (ret != Z_OK) {
  1277. if (new_level != NULL)
  1278. new_level->status = Z_STREAM_ERROR;
  1279. if (new_strategy != NULL)
  1280. new_strategy->status = Z_STREAM_ERROR;
  1281. stream_error = 1;
  1282. }
  1283. }
  1284. if (new_reproducible != NULL) {
  1285. int val = *(int *)new_reproducible->buf;
  1286. if (DEFLATE_CAN_SET_REPRODUCIBLE(strm, val)) {
  1287. s->reproducible = val;
  1288. } else {
  1289. new_reproducible->status = Z_STREAM_ERROR;
  1290. stream_error = 1;
  1291. }
  1292. }
  1293. /* Report version errors only if there are no real errors. */
  1294. return stream_error ? Z_STREAM_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
  1295. }
  1296. /* ========================================================================= */
  1297. int32_t Z_EXPORT zng_deflateGetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
  1298. deflate_state *s;
  1299. size_t i;
  1300. int32_t buf_error = 0;
  1301. int32_t version_error = 0;
  1302. /* Initialize the statuses. */
  1303. for (i = 0; i < count; i++)
  1304. params[i].status = Z_OK;
  1305. /* Check whether the stream state is consistent. */
  1306. if (deflateStateCheck(strm))
  1307. return Z_STREAM_ERROR;
  1308. s = strm->state;
  1309. for (i = 0; i < count; i++) {
  1310. switch (params[i].param) {
  1311. case Z_DEFLATE_LEVEL:
  1312. if (params[i].size < sizeof(int))
  1313. params[i].status = Z_BUF_ERROR;
  1314. else
  1315. *(int *)params[i].buf = s->level;
  1316. break;
  1317. case Z_DEFLATE_STRATEGY:
  1318. if (params[i].size < sizeof(int))
  1319. params[i].status = Z_BUF_ERROR;
  1320. else
  1321. *(int *)params[i].buf = s->strategy;
  1322. break;
  1323. case Z_DEFLATE_REPRODUCIBLE:
  1324. if (params[i].size < sizeof(int))
  1325. params[i].status = Z_BUF_ERROR;
  1326. else
  1327. *(int *)params[i].buf = s->reproducible;
  1328. break;
  1329. default:
  1330. params[i].status = Z_VERSION_ERROR;
  1331. version_error = 1;
  1332. break;
  1333. }
  1334. if (params[i].status == Z_BUF_ERROR)
  1335. buf_error = 1;
  1336. }
  1337. return buf_error ? Z_BUF_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
  1338. }
  1339. #endif