1 /*
2  * Copyright (c) Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  * You may select, at your option, one of the above-listed licenses.
9  */
10 
11 /*-*************************************
12 *  Dependencies
13 ***************************************/
14 #include "../common/zstd_deps.h"  /* INT_MAX, ZSTD_memset, ZSTD_memcpy */
15 #include "../common/cpu.h"
16 #include "../common/mem.h"
17 #include "hist.h"           /* HIST_countFast_wksp */
18 #define FSE_STATIC_LINKING_ONLY   /* FSE_encodeSymbol */
19 #include "../common/fse.h"
20 #define HUF_STATIC_LINKING_ONLY
21 #include "../common/huf.h"
22 #include "zstd_compress_internal.h"
23 #include "zstd_compress_sequences.h"
24 #include "zstd_compress_literals.h"
25 #include "zstd_fast.h"
26 #include "zstd_double_fast.h"
27 #include "zstd_lazy.h"
28 #include "zstd_opt.h"
29 #include "zstd_ldm.h"
30 #include "zstd_compress_superblock.h"
31 
32 /* ***************************************************************
33 *  Tuning parameters
34 *****************************************************************/
35 /*!
36  * COMPRESS_HEAPMODE :
37  * Select how default decompression function ZSTD_compress() allocates its context,
38  * on stack (0, default), or into heap (1).
39  * Note that functions with explicit context such as ZSTD_compressCCtx() are unaffected.
40  */
41 #ifndef ZSTD_COMPRESS_HEAPMODE
42 #  define ZSTD_COMPRESS_HEAPMODE 0
43 #endif
44 
45 
46 /*-*************************************
47 *  Helper functions
48 ***************************************/
49 /* ZSTD_compressBound()
50  * Note that the result from this function is only compatible with the "normal"
51  * full-block strategy.
52  * When there are a lot of small blocks due to frequent flush in streaming mode
53  * the overhead of headers can make the compressed data to be larger than the
54  * return value of ZSTD_compressBound().
55  */
ZSTD_compressBound(size_t srcSize)56 size_t ZSTD_compressBound(size_t srcSize) {
57     return ZSTD_COMPRESSBOUND(srcSize);
58 }
59 
60 
61 /*-*************************************
62 *  Context memory management
63 ***************************************/
64 struct ZSTD_CDict_s {
65     const void* dictContent;
66     size_t dictContentSize;
67     ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */
68     U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
69     ZSTD_cwksp workspace;
70     ZSTD_matchState_t matchState;
71     ZSTD_compressedBlockState_t cBlockState;
72     ZSTD_customMem customMem;
73     U32 dictID;
74     int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
75     ZSTD_useRowMatchFinderMode_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
76                                                      * row-based matchfinder. Unless the cdict is reloaded, we will use
77                                                      * the same greedy/lazy matchfinder at compression time.
78                                                      */
79 };  /* typedef'd to ZSTD_CDict within "zstd.h" */
80 
ZSTD_createCCtx(void)81 ZSTD_CCtx* ZSTD_createCCtx(void)
82 {
83     return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
84 }
85 
ZSTD_initCCtx(ZSTD_CCtx * cctx,ZSTD_customMem memManager)86 static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
87 {
88     assert(cctx != NULL);
89     ZSTD_memset(cctx, 0, sizeof(*cctx));
90     cctx->customMem = memManager;
91     cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
92     {   size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
93         assert(!ZSTD_isError(err));
94         (void)err;
95     }
96 }
97 
ZSTD_createCCtx_advanced(ZSTD_customMem customMem)98 ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
99 {
100     ZSTD_STATIC_ASSERT(zcss_init==0);
101     ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
102     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
103     {   ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_customMalloc(sizeof(ZSTD_CCtx), customMem);
104         if (!cctx) return NULL;
105         ZSTD_initCCtx(cctx, customMem);
106         return cctx;
107     }
108 }
109 
ZSTD_initStaticCCtx(void * workspace,size_t workspaceSize)110 ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
111 {
112     ZSTD_cwksp ws;
113     ZSTD_CCtx* cctx;
114     if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL;  /* minimum size */
115     if ((size_t)workspace & 7) return NULL;  /* must be 8-aligned */
116     ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
117 
118     cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));
119     if (cctx == NULL) return NULL;
120 
121     ZSTD_memset(cctx, 0, sizeof(ZSTD_CCtx));
122     ZSTD_cwksp_move(&cctx->workspace, &ws);
123     cctx->staticSize = workspaceSize;
124 
125     /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */
126     if (!ZSTD_cwksp_check_available(&cctx->workspace, ENTROPY_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;
127     cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
128     cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
129     cctx->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cctx->workspace, ENTROPY_WORKSPACE_SIZE);
130     cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
131     return cctx;
132 }
133 
134 /**
135  * Clears and frees all of the dictionaries in the CCtx.
136  */
ZSTD_clearAllDicts(ZSTD_CCtx * cctx)137 static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx)
138 {
139     ZSTD_customFree(cctx->localDict.dictBuffer, cctx->customMem);
140     ZSTD_freeCDict(cctx->localDict.cdict);
141     ZSTD_memset(&cctx->localDict, 0, sizeof(cctx->localDict));
142     ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
143     cctx->cdict = NULL;
144 }
145 
ZSTD_sizeof_localDict(ZSTD_localDict dict)146 static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)
147 {
148     size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;
149     size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
150     return bufferSize + cdictSize;
151 }
152 
ZSTD_freeCCtxContent(ZSTD_CCtx * cctx)153 static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
154 {
155     assert(cctx != NULL);
156     assert(cctx->staticSize == 0);
157     ZSTD_clearAllDicts(cctx);
158 #ifdef ZSTD_MULTITHREAD
159     ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
160 #endif
161     ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
162 }
163 
ZSTD_freeCCtx(ZSTD_CCtx * cctx)164 size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
165 {
166     if (cctx==NULL) return 0;   /* support free on NULL */
167     RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
168                     "not compatible with static CCtx");
169     {
170         int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
171         ZSTD_freeCCtxContent(cctx);
172         if (!cctxInWorkspace) {
173             ZSTD_customFree(cctx, cctx->customMem);
174         }
175     }
176     return 0;
177 }
178 
179 
ZSTD_sizeof_mtctx(const ZSTD_CCtx * cctx)180 static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
181 {
182 #ifdef ZSTD_MULTITHREAD
183     return ZSTDMT_sizeof_CCtx(cctx->mtctx);
184 #else
185     (void)cctx;
186     return 0;
187 #endif
188 }
189 
190 
ZSTD_sizeof_CCtx(const ZSTD_CCtx * cctx)191 size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
192 {
193     if (cctx==NULL) return 0;   /* support sizeof on NULL */
194     /* cctx may be in the workspace */
195     return (cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx))
196            + ZSTD_cwksp_sizeof(&cctx->workspace)
197            + ZSTD_sizeof_localDict(cctx->localDict)
198            + ZSTD_sizeof_mtctx(cctx);
199 }
200 
ZSTD_sizeof_CStream(const ZSTD_CStream * zcs)201 size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
202 {
203     return ZSTD_sizeof_CCtx(zcs);  /* same object */
204 }
205 
206 /* private API call, for dictBuilder only */
ZSTD_getSeqStore(const ZSTD_CCtx * ctx)207 const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
208 
209 /* Returns true if the strategy supports using a row based matchfinder */
ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy)210 static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {
211     return (strategy >= ZSTD_greedy && strategy <= ZSTD_lazy2);
212 }
213 
214 /* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder
215  * for this compression.
216  */
ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy,const ZSTD_useRowMatchFinderMode_e mode)217 static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_useRowMatchFinderMode_e mode) {
218     assert(mode != ZSTD_urm_auto);
219     return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_urm_enableRowMatchFinder);
220 }
221 
222 /* Returns row matchfinder usage enum given an initial mode and cParams */
ZSTD_resolveRowMatchFinderMode(ZSTD_useRowMatchFinderMode_e mode,const ZSTD_compressionParameters * const cParams)223 static ZSTD_useRowMatchFinderMode_e ZSTD_resolveRowMatchFinderMode(ZSTD_useRowMatchFinderMode_e mode,
224                                                                    const ZSTD_compressionParameters* const cParams) {
225 #if !defined(ZSTD_NO_INTRINSICS) && (defined(__SSE2__) || defined(__ARM_NEON))
226     int const kHasSIMD128 = 1;
227 #else
228     int const kHasSIMD128 = 0;
229 #endif
230     if (mode != ZSTD_urm_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */
231     mode = ZSTD_urm_disableRowMatchFinder;
232     if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;
233     if (kHasSIMD128) {
234         if (cParams->windowLog > 14) mode = ZSTD_urm_enableRowMatchFinder;
235     } else {
236         if (cParams->windowLog > 17) mode = ZSTD_urm_enableRowMatchFinder;
237     }
238     return mode;
239 }
240 
241 /* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
ZSTD_allocateChainTable(const ZSTD_strategy strategy,const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,const U32 forDDSDict)242 static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
243                                    const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
244                                    const U32 forDDSDict) {
245     assert(useRowMatchFinder != ZSTD_urm_auto);
246     /* We always should allocate a chaintable if we are allocating a matchstate for a DDS dictionary matchstate.
247      * We do not allocate a chaintable if we are using ZSTD_fast, or are using the row-based matchfinder.
248      */
249     return forDDSDict || ((strategy != ZSTD_fast) && !ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder));
250 }
251 
252 /* Returns 1 if compression parameters are such that we should
253  * enable long distance matching (wlog >= 27, strategy >= btopt).
254  * Returns 0 otherwise.
255  */
ZSTD_CParams_shouldEnableLdm(const ZSTD_compressionParameters * const cParams)256 static U32 ZSTD_CParams_shouldEnableLdm(const ZSTD_compressionParameters* const cParams) {
257     return cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 27;
258 }
259 
260 /* Returns 1 if compression parameters are such that we should
261  * enable blockSplitter (wlog >= 17, strategy >= btopt).
262  * Returns 0 otherwise.
263  */
ZSTD_CParams_useBlockSplitter(const ZSTD_compressionParameters * const cParams)264 static U32 ZSTD_CParams_useBlockSplitter(const ZSTD_compressionParameters* const cParams) {
265     return cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17;
266 }
267 
ZSTD_makeCCtxParamsFromCParams(ZSTD_compressionParameters cParams)268 static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
269         ZSTD_compressionParameters cParams)
270 {
271     ZSTD_CCtx_params cctxParams;
272     /* should not matter, as all cParams are presumed properly defined */
273     ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);
274     cctxParams.cParams = cParams;
275 
276     /* Adjust advanced params according to cParams */
277     if (ZSTD_CParams_shouldEnableLdm(&cParams)) {
278         DEBUGLOG(4, "ZSTD_makeCCtxParamsFromCParams(): Including LDM into cctx params");
279         cctxParams.ldmParams.enableLdm = 1;
280         /* LDM is enabled by default for optimal parser and window size >= 128MB */
281         ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);
282         assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);
283         assert(cctxParams.ldmParams.hashRateLog < 32);
284     }
285 
286     if (ZSTD_CParams_useBlockSplitter(&cParams)) {
287         DEBUGLOG(4, "ZSTD_makeCCtxParamsFromCParams(): Including block splitting into cctx params");
288         cctxParams.splitBlocks = 1;
289     }
290 
291     cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
292     assert(!ZSTD_checkCParams(cParams));
293     return cctxParams;
294 }
295 
ZSTD_createCCtxParams_advanced(ZSTD_customMem customMem)296 static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
297         ZSTD_customMem customMem)
298 {
299     ZSTD_CCtx_params* params;
300     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
301     params = (ZSTD_CCtx_params*)ZSTD_customCalloc(
302             sizeof(ZSTD_CCtx_params), customMem);
303     if (!params) { return NULL; }
304     ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
305     params->customMem = customMem;
306     return params;
307 }
308 
ZSTD_createCCtxParams(void)309 ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
310 {
311     return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
312 }
313 
ZSTD_freeCCtxParams(ZSTD_CCtx_params * params)314 size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
315 {
316     if (params == NULL) { return 0; }
317     ZSTD_customFree(params, params->customMem);
318     return 0;
319 }
320 
ZSTD_CCtxParams_reset(ZSTD_CCtx_params * params)321 size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
322 {
323     return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
324 }
325 
ZSTD_CCtxParams_init(ZSTD_CCtx_params * cctxParams,int compressionLevel)326 size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
327     RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
328     ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
329     cctxParams->compressionLevel = compressionLevel;
330     cctxParams->fParams.contentSizeFlag = 1;
331     return 0;
332 }
333 
334 #define ZSTD_NO_CLEVEL 0
335 
336 /**
337  * Initializes the cctxParams from params and compressionLevel.
338  * @param compressionLevel If params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.
339  */
ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params * cctxParams,ZSTD_parameters const * params,int compressionLevel)340 static void ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams, ZSTD_parameters const* params, int compressionLevel)
341 {
342     assert(!ZSTD_checkCParams(params->cParams));
343     ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
344     cctxParams->cParams = params->cParams;
345     cctxParams->fParams = params->fParams;
346     /* Should not matter, as all cParams are presumed properly defined.
347      * But, set it for tracing anyway.
348      */
349     cctxParams->compressionLevel = compressionLevel;
350     cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, &params->cParams);
351     DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d", cctxParams->useRowMatchFinder);
352 }
353 
ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params * cctxParams,ZSTD_parameters params)354 size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
355 {
356     RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
357     FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
358     ZSTD_CCtxParams_init_internal(cctxParams, &params, ZSTD_NO_CLEVEL);
359     return 0;
360 }
361 
362 /**
363  * Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.
364  * @param param Validated zstd parameters.
365  */
ZSTD_CCtxParams_setZstdParams(ZSTD_CCtx_params * cctxParams,const ZSTD_parameters * params)366 static void ZSTD_CCtxParams_setZstdParams(
367         ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)
368 {
369     assert(!ZSTD_checkCParams(params->cParams));
370     cctxParams->cParams = params->cParams;
371     cctxParams->fParams = params->fParams;
372     /* Should not matter, as all cParams are presumed properly defined.
373      * But, set it for tracing anyway.
374      */
375     cctxParams->compressionLevel = ZSTD_NO_CLEVEL;
376 }
377 
ZSTD_cParam_getBounds(ZSTD_cParameter param)378 ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
379 {
380     ZSTD_bounds bounds = { 0, 0, 0 };
381 
382     switch(param)
383     {
384     case ZSTD_c_compressionLevel:
385         bounds.lowerBound = ZSTD_minCLevel();
386         bounds.upperBound = ZSTD_maxCLevel();
387         return bounds;
388 
389     case ZSTD_c_windowLog:
390         bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
391         bounds.upperBound = ZSTD_WINDOWLOG_MAX;
392         return bounds;
393 
394     case ZSTD_c_hashLog:
395         bounds.lowerBound = ZSTD_HASHLOG_MIN;
396         bounds.upperBound = ZSTD_HASHLOG_MAX;
397         return bounds;
398 
399     case ZSTD_c_chainLog:
400         bounds.lowerBound = ZSTD_CHAINLOG_MIN;
401         bounds.upperBound = ZSTD_CHAINLOG_MAX;
402         return bounds;
403 
404     case ZSTD_c_searchLog:
405         bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
406         bounds.upperBound = ZSTD_SEARCHLOG_MAX;
407         return bounds;
408 
409     case ZSTD_c_minMatch:
410         bounds.lowerBound = ZSTD_MINMATCH_MIN;
411         bounds.upperBound = ZSTD_MINMATCH_MAX;
412         return bounds;
413 
414     case ZSTD_c_targetLength:
415         bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
416         bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
417         return bounds;
418 
419     case ZSTD_c_strategy:
420         bounds.lowerBound = ZSTD_STRATEGY_MIN;
421         bounds.upperBound = ZSTD_STRATEGY_MAX;
422         return bounds;
423 
424     case ZSTD_c_contentSizeFlag:
425         bounds.lowerBound = 0;
426         bounds.upperBound = 1;
427         return bounds;
428 
429     case ZSTD_c_checksumFlag:
430         bounds.lowerBound = 0;
431         bounds.upperBound = 1;
432         return bounds;
433 
434     case ZSTD_c_dictIDFlag:
435         bounds.lowerBound = 0;
436         bounds.upperBound = 1;
437         return bounds;
438 
439     case ZSTD_c_nbWorkers:
440         bounds.lowerBound = 0;
441 #ifdef ZSTD_MULTITHREAD
442         bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
443 #else
444         bounds.upperBound = 0;
445 #endif
446         return bounds;
447 
448     case ZSTD_c_jobSize:
449         bounds.lowerBound = 0;
450 #ifdef ZSTD_MULTITHREAD
451         bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
452 #else
453         bounds.upperBound = 0;
454 #endif
455         return bounds;
456 
457     case ZSTD_c_overlapLog:
458 #ifdef ZSTD_MULTITHREAD
459         bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
460         bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
461 #else
462         bounds.lowerBound = 0;
463         bounds.upperBound = 0;
464 #endif
465         return bounds;
466 
467     case ZSTD_c_enableDedicatedDictSearch:
468         bounds.lowerBound = 0;
469         bounds.upperBound = 1;
470         return bounds;
471 
472     case ZSTD_c_enableLongDistanceMatching:
473         bounds.lowerBound = 0;
474         bounds.upperBound = 1;
475         return bounds;
476 
477     case ZSTD_c_ldmHashLog:
478         bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
479         bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
480         return bounds;
481 
482     case ZSTD_c_ldmMinMatch:
483         bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
484         bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
485         return bounds;
486 
487     case ZSTD_c_ldmBucketSizeLog:
488         bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
489         bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
490         return bounds;
491 
492     case ZSTD_c_ldmHashRateLog:
493         bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
494         bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
495         return bounds;
496 
497     /* experimental parameters */
498     case ZSTD_c_rsyncable:
499         bounds.lowerBound = 0;
500         bounds.upperBound = 1;
501         return bounds;
502 
503     case ZSTD_c_forceMaxWindow :
504         bounds.lowerBound = 0;
505         bounds.upperBound = 1;
506         return bounds;
507 
508     case ZSTD_c_format:
509         ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
510         bounds.lowerBound = ZSTD_f_zstd1;
511         bounds.upperBound = ZSTD_f_zstd1_magicless;   /* note : how to ensure at compile time that this is the highest value enum ? */
512         return bounds;
513 
514     case ZSTD_c_forceAttachDict:
515         ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceLoad);
516         bounds.lowerBound = ZSTD_dictDefaultAttach;
517         bounds.upperBound = ZSTD_dictForceLoad;       /* note : how to ensure at compile time that this is the highest value enum ? */
518         return bounds;
519 
520     case ZSTD_c_literalCompressionMode:
521         ZSTD_STATIC_ASSERT(ZSTD_lcm_auto < ZSTD_lcm_huffman && ZSTD_lcm_huffman < ZSTD_lcm_uncompressed);
522         bounds.lowerBound = ZSTD_lcm_auto;
523         bounds.upperBound = ZSTD_lcm_uncompressed;
524         return bounds;
525 
526     case ZSTD_c_targetCBlockSize:
527         bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
528         bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
529         return bounds;
530 
531     case ZSTD_c_srcSizeHint:
532         bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
533         bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
534         return bounds;
535 
536     case ZSTD_c_stableInBuffer:
537     case ZSTD_c_stableOutBuffer:
538         bounds.lowerBound = (int)ZSTD_bm_buffered;
539         bounds.upperBound = (int)ZSTD_bm_stable;
540         return bounds;
541 
542     case ZSTD_c_blockDelimiters:
543         bounds.lowerBound = (int)ZSTD_sf_noBlockDelimiters;
544         bounds.upperBound = (int)ZSTD_sf_explicitBlockDelimiters;
545         return bounds;
546 
547     case ZSTD_c_validateSequences:
548         bounds.lowerBound = 0;
549         bounds.upperBound = 1;
550         return bounds;
551 
552     case ZSTD_c_splitBlocks:
553         bounds.lowerBound = 0;
554         bounds.upperBound = 1;
555         return bounds;
556 
557     case ZSTD_c_useRowMatchFinder:
558         bounds.lowerBound = (int)ZSTD_urm_auto;
559         bounds.upperBound = (int)ZSTD_urm_enableRowMatchFinder;
560         return bounds;
561 
562     case ZSTD_c_deterministicRefPrefix:
563         bounds.lowerBound = 0;
564         bounds.upperBound = 1;
565         return bounds;
566 
567     default:
568         bounds.error = ERROR(parameter_unsupported);
569         return bounds;
570     }
571 }
572 
573 /* ZSTD_cParam_clampBounds:
574  * Clamps the value into the bounded range.
575  */
ZSTD_cParam_clampBounds(ZSTD_cParameter cParam,int * value)576 static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)
577 {
578     ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
579     if (ZSTD_isError(bounds.error)) return bounds.error;
580     if (*value < bounds.lowerBound) *value = bounds.lowerBound;
581     if (*value > bounds.upperBound) *value = bounds.upperBound;
582     return 0;
583 }
584 
585 #define BOUNDCHECK(cParam, val) { \
586     RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \
587                     parameter_outOfBound, "Param out of bounds"); \
588 }
589 
590 
ZSTD_isUpdateAuthorized(ZSTD_cParameter param)591 static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
592 {
593     switch(param)
594     {
595     case ZSTD_c_compressionLevel:
596     case ZSTD_c_hashLog:
597     case ZSTD_c_chainLog:
598     case ZSTD_c_searchLog:
599     case ZSTD_c_minMatch:
600     case ZSTD_c_targetLength:
601     case ZSTD_c_strategy:
602         return 1;
603 
604     case ZSTD_c_format:
605     case ZSTD_c_windowLog:
606     case ZSTD_c_contentSizeFlag:
607     case ZSTD_c_checksumFlag:
608     case ZSTD_c_dictIDFlag:
609     case ZSTD_c_forceMaxWindow :
610     case ZSTD_c_nbWorkers:
611     case ZSTD_c_jobSize:
612     case ZSTD_c_overlapLog:
613     case ZSTD_c_rsyncable:
614     case ZSTD_c_enableDedicatedDictSearch:
615     case ZSTD_c_enableLongDistanceMatching:
616     case ZSTD_c_ldmHashLog:
617     case ZSTD_c_ldmMinMatch:
618     case ZSTD_c_ldmBucketSizeLog:
619     case ZSTD_c_ldmHashRateLog:
620     case ZSTD_c_forceAttachDict:
621     case ZSTD_c_literalCompressionMode:
622     case ZSTD_c_targetCBlockSize:
623     case ZSTD_c_srcSizeHint:
624     case ZSTD_c_stableInBuffer:
625     case ZSTD_c_stableOutBuffer:
626     case ZSTD_c_blockDelimiters:
627     case ZSTD_c_validateSequences:
628     case ZSTD_c_splitBlocks:
629     case ZSTD_c_useRowMatchFinder:
630     case ZSTD_c_deterministicRefPrefix:
631     default:
632         return 0;
633     }
634 }
635 
ZSTD_CCtx_setParameter(ZSTD_CCtx * cctx,ZSTD_cParameter param,int value)636 size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
637 {
638     DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
639     if (cctx->streamStage != zcss_init) {
640         if (ZSTD_isUpdateAuthorized(param)) {
641             cctx->cParamsChanged = 1;
642         } else {
643             RETURN_ERROR(stage_wrong, "can only set params in ctx init stage");
644     }   }
645 
646     switch(param)
647     {
648     case ZSTD_c_nbWorkers:
649         RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,
650                         "MT not compatible with static alloc");
651         break;
652 
653     case ZSTD_c_compressionLevel:
654     case ZSTD_c_windowLog:
655     case ZSTD_c_hashLog:
656     case ZSTD_c_chainLog:
657     case ZSTD_c_searchLog:
658     case ZSTD_c_minMatch:
659     case ZSTD_c_targetLength:
660     case ZSTD_c_strategy:
661     case ZSTD_c_ldmHashRateLog:
662     case ZSTD_c_format:
663     case ZSTD_c_contentSizeFlag:
664     case ZSTD_c_checksumFlag:
665     case ZSTD_c_dictIDFlag:
666     case ZSTD_c_forceMaxWindow:
667     case ZSTD_c_forceAttachDict:
668     case ZSTD_c_literalCompressionMode:
669     case ZSTD_c_jobSize:
670     case ZSTD_c_overlapLog:
671     case ZSTD_c_rsyncable:
672     case ZSTD_c_enableDedicatedDictSearch:
673     case ZSTD_c_enableLongDistanceMatching:
674     case ZSTD_c_ldmHashLog:
675     case ZSTD_c_ldmMinMatch:
676     case ZSTD_c_ldmBucketSizeLog:
677     case ZSTD_c_targetCBlockSize:
678     case ZSTD_c_srcSizeHint:
679     case ZSTD_c_stableInBuffer:
680     case ZSTD_c_stableOutBuffer:
681     case ZSTD_c_blockDelimiters:
682     case ZSTD_c_validateSequences:
683     case ZSTD_c_splitBlocks:
684     case ZSTD_c_useRowMatchFinder:
685     case ZSTD_c_deterministicRefPrefix:
686         break;
687 
688     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
689     }
690     return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);
691 }
692 
ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params * CCtxParams,ZSTD_cParameter param,int value)693 size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
694                                     ZSTD_cParameter param, int value)
695 {
696     DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value);
697     switch(param)
698     {
699     case ZSTD_c_format :
700         BOUNDCHECK(ZSTD_c_format, value);
701         CCtxParams->format = (ZSTD_format_e)value;
702         return (size_t)CCtxParams->format;
703 
704     case ZSTD_c_compressionLevel : {
705         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
706         if (value == 0)
707             CCtxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
708         else
709             CCtxParams->compressionLevel = value;
710         if (CCtxParams->compressionLevel >= 0) return (size_t)CCtxParams->compressionLevel;
711         return 0;  /* return type (size_t) cannot represent negative values */
712     }
713 
714     case ZSTD_c_windowLog :
715         if (value!=0)   /* 0 => use default */
716             BOUNDCHECK(ZSTD_c_windowLog, value);
717         CCtxParams->cParams.windowLog = (U32)value;
718         return CCtxParams->cParams.windowLog;
719 
720     case ZSTD_c_hashLog :
721         if (value!=0)   /* 0 => use default */
722             BOUNDCHECK(ZSTD_c_hashLog, value);
723         CCtxParams->cParams.hashLog = (U32)value;
724         return CCtxParams->cParams.hashLog;
725 
726     case ZSTD_c_chainLog :
727         if (value!=0)   /* 0 => use default */
728             BOUNDCHECK(ZSTD_c_chainLog, value);
729         CCtxParams->cParams.chainLog = (U32)value;
730         return CCtxParams->cParams.chainLog;
731 
732     case ZSTD_c_searchLog :
733         if (value!=0)   /* 0 => use default */
734             BOUNDCHECK(ZSTD_c_searchLog, value);
735         CCtxParams->cParams.searchLog = (U32)value;
736         return (size_t)value;
737 
738     case ZSTD_c_minMatch :
739         if (value!=0)   /* 0 => use default */
740             BOUNDCHECK(ZSTD_c_minMatch, value);
741         CCtxParams->cParams.minMatch = value;
742         return CCtxParams->cParams.minMatch;
743 
744     case ZSTD_c_targetLength :
745         BOUNDCHECK(ZSTD_c_targetLength, value);
746         CCtxParams->cParams.targetLength = value;
747         return CCtxParams->cParams.targetLength;
748 
749     case ZSTD_c_strategy :
750         if (value!=0)   /* 0 => use default */
751             BOUNDCHECK(ZSTD_c_strategy, value);
752         CCtxParams->cParams.strategy = (ZSTD_strategy)value;
753         return (size_t)CCtxParams->cParams.strategy;
754 
755     case ZSTD_c_contentSizeFlag :
756         /* Content size written in frame header _when known_ (default:1) */
757         DEBUGLOG(4, "set content size flag = %u", (value!=0));
758         CCtxParams->fParams.contentSizeFlag = value != 0;
759         return CCtxParams->fParams.contentSizeFlag;
760 
761     case ZSTD_c_checksumFlag :
762         /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
763         CCtxParams->fParams.checksumFlag = value != 0;
764         return CCtxParams->fParams.checksumFlag;
765 
766     case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
767         DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
768         CCtxParams->fParams.noDictIDFlag = !value;
769         return !CCtxParams->fParams.noDictIDFlag;
770 
771     case ZSTD_c_forceMaxWindow :
772         CCtxParams->forceWindow = (value != 0);
773         return CCtxParams->forceWindow;
774 
775     case ZSTD_c_forceAttachDict : {
776         const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
777         BOUNDCHECK(ZSTD_c_forceAttachDict, pref);
778         CCtxParams->attachDictPref = pref;
779         return CCtxParams->attachDictPref;
780     }
781 
782     case ZSTD_c_literalCompressionMode : {
783         const ZSTD_literalCompressionMode_e lcm = (ZSTD_literalCompressionMode_e)value;
784         BOUNDCHECK(ZSTD_c_literalCompressionMode, lcm);
785         CCtxParams->literalCompressionMode = lcm;
786         return CCtxParams->literalCompressionMode;
787     }
788 
789     case ZSTD_c_nbWorkers :
790 #ifndef ZSTD_MULTITHREAD
791         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
792         return 0;
793 #else
794         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
795         CCtxParams->nbWorkers = value;
796         return CCtxParams->nbWorkers;
797 #endif
798 
799     case ZSTD_c_jobSize :
800 #ifndef ZSTD_MULTITHREAD
801         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
802         return 0;
803 #else
804         /* Adjust to the minimum non-default value. */
805         if (value != 0 && value < ZSTDMT_JOBSIZE_MIN)
806             value = ZSTDMT_JOBSIZE_MIN;
807         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
808         assert(value >= 0);
809         CCtxParams->jobSize = value;
810         return CCtxParams->jobSize;
811 #endif
812 
813     case ZSTD_c_overlapLog :
814 #ifndef ZSTD_MULTITHREAD
815         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
816         return 0;
817 #else
818         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
819         CCtxParams->overlapLog = value;
820         return CCtxParams->overlapLog;
821 #endif
822 
823     case ZSTD_c_rsyncable :
824 #ifndef ZSTD_MULTITHREAD
825         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
826         return 0;
827 #else
828         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
829         CCtxParams->rsyncable = value;
830         return CCtxParams->rsyncable;
831 #endif
832 
833     case ZSTD_c_enableDedicatedDictSearch :
834         CCtxParams->enableDedicatedDictSearch = (value!=0);
835         return CCtxParams->enableDedicatedDictSearch;
836 
837     case ZSTD_c_enableLongDistanceMatching :
838         CCtxParams->ldmParams.enableLdm = (value!=0);
839         return CCtxParams->ldmParams.enableLdm;
840 
841     case ZSTD_c_ldmHashLog :
842         if (value!=0)   /* 0 ==> auto */
843             BOUNDCHECK(ZSTD_c_ldmHashLog, value);
844         CCtxParams->ldmParams.hashLog = value;
845         return CCtxParams->ldmParams.hashLog;
846 
847     case ZSTD_c_ldmMinMatch :
848         if (value!=0)   /* 0 ==> default */
849             BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
850         CCtxParams->ldmParams.minMatchLength = value;
851         return CCtxParams->ldmParams.minMatchLength;
852 
853     case ZSTD_c_ldmBucketSizeLog :
854         if (value!=0)   /* 0 ==> default */
855             BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
856         CCtxParams->ldmParams.bucketSizeLog = value;
857         return CCtxParams->ldmParams.bucketSizeLog;
858 
859     case ZSTD_c_ldmHashRateLog :
860         RETURN_ERROR_IF(value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN,
861                         parameter_outOfBound, "Param out of bounds!");
862         CCtxParams->ldmParams.hashRateLog = value;
863         return CCtxParams->ldmParams.hashRateLog;
864 
865     case ZSTD_c_targetCBlockSize :
866         if (value!=0)   /* 0 ==> default */
867             BOUNDCHECK(ZSTD_c_targetCBlockSize, value);
868         CCtxParams->targetCBlockSize = value;
869         return CCtxParams->targetCBlockSize;
870 
871     case ZSTD_c_srcSizeHint :
872         if (value!=0)    /* 0 ==> default */
873             BOUNDCHECK(ZSTD_c_srcSizeHint, value);
874         CCtxParams->srcSizeHint = value;
875         return CCtxParams->srcSizeHint;
876 
877     case ZSTD_c_stableInBuffer:
878         BOUNDCHECK(ZSTD_c_stableInBuffer, value);
879         CCtxParams->inBufferMode = (ZSTD_bufferMode_e)value;
880         return CCtxParams->inBufferMode;
881 
882     case ZSTD_c_stableOutBuffer:
883         BOUNDCHECK(ZSTD_c_stableOutBuffer, value);
884         CCtxParams->outBufferMode = (ZSTD_bufferMode_e)value;
885         return CCtxParams->outBufferMode;
886 
887     case ZSTD_c_blockDelimiters:
888         BOUNDCHECK(ZSTD_c_blockDelimiters, value);
889         CCtxParams->blockDelimiters = (ZSTD_sequenceFormat_e)value;
890         return CCtxParams->blockDelimiters;
891 
892     case ZSTD_c_validateSequences:
893         BOUNDCHECK(ZSTD_c_validateSequences, value);
894         CCtxParams->validateSequences = value;
895         return CCtxParams->validateSequences;
896 
897     case ZSTD_c_splitBlocks:
898         BOUNDCHECK(ZSTD_c_splitBlocks, value);
899         CCtxParams->splitBlocks = value;
900         return CCtxParams->splitBlocks;
901 
902     case ZSTD_c_useRowMatchFinder:
903         BOUNDCHECK(ZSTD_c_useRowMatchFinder, value);
904         CCtxParams->useRowMatchFinder = (ZSTD_useRowMatchFinderMode_e)value;
905         return CCtxParams->useRowMatchFinder;
906 
907     case ZSTD_c_deterministicRefPrefix:
908         BOUNDCHECK(ZSTD_c_deterministicRefPrefix, value);
909         CCtxParams->deterministicRefPrefix = !!value;
910         return CCtxParams->deterministicRefPrefix;
911 
912     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
913     }
914 }
915 
ZSTD_CCtx_getParameter(ZSTD_CCtx const * cctx,ZSTD_cParameter param,int * value)916 size_t ZSTD_CCtx_getParameter(ZSTD_CCtx const* cctx, ZSTD_cParameter param, int* value)
917 {
918     return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);
919 }
920 
ZSTD_CCtxParams_getParameter(ZSTD_CCtx_params const * CCtxParams,ZSTD_cParameter param,int * value)921 size_t ZSTD_CCtxParams_getParameter(
922         ZSTD_CCtx_params const* CCtxParams, ZSTD_cParameter param, int* value)
923 {
924     switch(param)
925     {
926     case ZSTD_c_format :
927         *value = CCtxParams->format;
928         break;
929     case ZSTD_c_compressionLevel :
930         *value = CCtxParams->compressionLevel;
931         break;
932     case ZSTD_c_windowLog :
933         *value = (int)CCtxParams->cParams.windowLog;
934         break;
935     case ZSTD_c_hashLog :
936         *value = (int)CCtxParams->cParams.hashLog;
937         break;
938     case ZSTD_c_chainLog :
939         *value = (int)CCtxParams->cParams.chainLog;
940         break;
941     case ZSTD_c_searchLog :
942         *value = CCtxParams->cParams.searchLog;
943         break;
944     case ZSTD_c_minMatch :
945         *value = CCtxParams->cParams.minMatch;
946         break;
947     case ZSTD_c_targetLength :
948         *value = CCtxParams->cParams.targetLength;
949         break;
950     case ZSTD_c_strategy :
951         *value = (unsigned)CCtxParams->cParams.strategy;
952         break;
953     case ZSTD_c_contentSizeFlag :
954         *value = CCtxParams->fParams.contentSizeFlag;
955         break;
956     case ZSTD_c_checksumFlag :
957         *value = CCtxParams->fParams.checksumFlag;
958         break;
959     case ZSTD_c_dictIDFlag :
960         *value = !CCtxParams->fParams.noDictIDFlag;
961         break;
962     case ZSTD_c_forceMaxWindow :
963         *value = CCtxParams->forceWindow;
964         break;
965     case ZSTD_c_forceAttachDict :
966         *value = CCtxParams->attachDictPref;
967         break;
968     case ZSTD_c_literalCompressionMode :
969         *value = CCtxParams->literalCompressionMode;
970         break;
971     case ZSTD_c_nbWorkers :
972 #ifndef ZSTD_MULTITHREAD
973         assert(CCtxParams->nbWorkers == 0);
974 #endif
975         *value = CCtxParams->nbWorkers;
976         break;
977     case ZSTD_c_jobSize :
978 #ifndef ZSTD_MULTITHREAD
979         RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
980 #else
981         assert(CCtxParams->jobSize <= INT_MAX);
982         *value = (int)CCtxParams->jobSize;
983         break;
984 #endif
985     case ZSTD_c_overlapLog :
986 #ifndef ZSTD_MULTITHREAD
987         RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
988 #else
989         *value = CCtxParams->overlapLog;
990         break;
991 #endif
992     case ZSTD_c_rsyncable :
993 #ifndef ZSTD_MULTITHREAD
994         RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
995 #else
996         *value = CCtxParams->rsyncable;
997         break;
998 #endif
999     case ZSTD_c_enableDedicatedDictSearch :
1000         *value = CCtxParams->enableDedicatedDictSearch;
1001         break;
1002     case ZSTD_c_enableLongDistanceMatching :
1003         *value = CCtxParams->ldmParams.enableLdm;
1004         break;
1005     case ZSTD_c_ldmHashLog :
1006         *value = CCtxParams->ldmParams.hashLog;
1007         break;
1008     case ZSTD_c_ldmMinMatch :
1009         *value = CCtxParams->ldmParams.minMatchLength;
1010         break;
1011     case ZSTD_c_ldmBucketSizeLog :
1012         *value = CCtxParams->ldmParams.bucketSizeLog;
1013         break;
1014     case ZSTD_c_ldmHashRateLog :
1015         *value = CCtxParams->ldmParams.hashRateLog;
1016         break;
1017     case ZSTD_c_targetCBlockSize :
1018         *value = (int)CCtxParams->targetCBlockSize;
1019         break;
1020     case ZSTD_c_srcSizeHint :
1021         *value = (int)CCtxParams->srcSizeHint;
1022         break;
1023     case ZSTD_c_stableInBuffer :
1024         *value = (int)CCtxParams->inBufferMode;
1025         break;
1026     case ZSTD_c_stableOutBuffer :
1027         *value = (int)CCtxParams->outBufferMode;
1028         break;
1029     case ZSTD_c_blockDelimiters :
1030         *value = (int)CCtxParams->blockDelimiters;
1031         break;
1032     case ZSTD_c_validateSequences :
1033         *value = (int)CCtxParams->validateSequences;
1034         break;
1035     case ZSTD_c_splitBlocks :
1036         *value = (int)CCtxParams->splitBlocks;
1037         break;
1038     case ZSTD_c_useRowMatchFinder :
1039         *value = (int)CCtxParams->useRowMatchFinder;
1040         break;
1041     case ZSTD_c_deterministicRefPrefix:
1042         *value = (int)CCtxParams->deterministicRefPrefix;
1043         break;
1044     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
1045     }
1046     return 0;
1047 }
1048 
1049 /** ZSTD_CCtx_setParametersUsingCCtxParams() :
1050  *  just applies `params` into `cctx`
1051  *  no action is performed, parameters are merely stored.
1052  *  If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
1053  *    This is possible even if a compression is ongoing.
1054  *    In which case, new parameters will be applied on the fly, starting with next compression job.
1055  */
ZSTD_CCtx_setParametersUsingCCtxParams(ZSTD_CCtx * cctx,const ZSTD_CCtx_params * params)1056 size_t ZSTD_CCtx_setParametersUsingCCtxParams(
1057         ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
1058 {
1059     DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
1060     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1061                     "The context is in the wrong stage!");
1062     RETURN_ERROR_IF(cctx->cdict, stage_wrong,
1063                     "Can't override parameters with cdict attached (some must "
1064                     "be inherited from the cdict).");
1065 
1066     cctx->requestedParams = *params;
1067     return 0;
1068 }
1069 
ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx * cctx,unsigned long long pledgedSrcSize)1070 ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
1071 {
1072     DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %u bytes", (U32)pledgedSrcSize);
1073     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1074                     "Can't set pledgedSrcSize when not in init stage.");
1075     cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
1076     return 0;
1077 }
1078 
1079 static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(
1080         int const compressionLevel,
1081         size_t const dictSize);
1082 static int ZSTD_dedicatedDictSearch_isSupported(
1083         const ZSTD_compressionParameters* cParams);
1084 static void ZSTD_dedicatedDictSearch_revertCParams(
1085         ZSTD_compressionParameters* cParams);
1086 
1087 /**
1088  * Initializes the local dict using the requested parameters.
1089  * NOTE: This does not use the pledged src size, because it may be used for more
1090  * than one compression.
1091  */
ZSTD_initLocalDict(ZSTD_CCtx * cctx)1092 static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
1093 {
1094     ZSTD_localDict* const dl = &cctx->localDict;
1095     if (dl->dict == NULL) {
1096         /* No local dictionary. */
1097         assert(dl->dictBuffer == NULL);
1098         assert(dl->cdict == NULL);
1099         assert(dl->dictSize == 0);
1100         return 0;
1101     }
1102     if (dl->cdict != NULL) {
1103         assert(cctx->cdict == dl->cdict);
1104         /* Local dictionary already initialized. */
1105         return 0;
1106     }
1107     assert(dl->dictSize > 0);
1108     assert(cctx->cdict == NULL);
1109     assert(cctx->prefixDict.dict == NULL);
1110 
1111     dl->cdict = ZSTD_createCDict_advanced2(
1112             dl->dict,
1113             dl->dictSize,
1114             ZSTD_dlm_byRef,
1115             dl->dictContentType,
1116             &cctx->requestedParams,
1117             cctx->customMem);
1118     RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
1119     cctx->cdict = dl->cdict;
1120     return 0;
1121 }
1122 
ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType)1123 size_t ZSTD_CCtx_loadDictionary_advanced(
1124         ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
1125         ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
1126 {
1127     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1128                     "Can't load a dictionary when ctx is not in init stage.");
1129     DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
1130     ZSTD_clearAllDicts(cctx);  /* in case one already exists */
1131     if (dict == NULL || dictSize == 0)  /* no dictionary mode */
1132         return 0;
1133     if (dictLoadMethod == ZSTD_dlm_byRef) {
1134         cctx->localDict.dict = dict;
1135     } else {
1136         void* dictBuffer;
1137         RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
1138                         "no malloc for static CCtx");
1139         dictBuffer = ZSTD_customMalloc(dictSize, cctx->customMem);
1140         RETURN_ERROR_IF(!dictBuffer, memory_allocation, "NULL pointer!");
1141         ZSTD_memcpy(dictBuffer, dict, dictSize);
1142         cctx->localDict.dictBuffer = dictBuffer;
1143         cctx->localDict.dict = dictBuffer;
1144     }
1145     cctx->localDict.dictSize = dictSize;
1146     cctx->localDict.dictContentType = dictContentType;
1147     return 0;
1148 }
1149 
ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx * cctx,const void * dict,size_t dictSize)1150 ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
1151       ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
1152 {
1153     return ZSTD_CCtx_loadDictionary_advanced(
1154             cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
1155 }
1156 
ZSTD_CCtx_loadDictionary(ZSTD_CCtx * cctx,const void * dict,size_t dictSize)1157 ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
1158 {
1159     return ZSTD_CCtx_loadDictionary_advanced(
1160             cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1161 }
1162 
1163 
ZSTD_CCtx_refCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict)1164 size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
1165 {
1166     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1167                     "Can't ref a dict when ctx not in init stage.");
1168     /* Free the existing local cdict (if any) to save memory. */
1169     ZSTD_clearAllDicts(cctx);
1170     cctx->cdict = cdict;
1171     return 0;
1172 }
1173 
ZSTD_CCtx_refThreadPool(ZSTD_CCtx * cctx,ZSTD_threadPool * pool)1174 size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)
1175 {
1176     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1177                     "Can't ref a pool when ctx not in init stage.");
1178     cctx->pool = pool;
1179     return 0;
1180 }
1181 
ZSTD_CCtx_refPrefix(ZSTD_CCtx * cctx,const void * prefix,size_t prefixSize)1182 size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
1183 {
1184     return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
1185 }
1186 
ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx * cctx,const void * prefix,size_t prefixSize,ZSTD_dictContentType_e dictContentType)1187 size_t ZSTD_CCtx_refPrefix_advanced(
1188         ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
1189 {
1190     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1191                     "Can't ref a prefix when ctx not in init stage.");
1192     ZSTD_clearAllDicts(cctx);
1193     if (prefix != NULL && prefixSize > 0) {
1194         cctx->prefixDict.dict = prefix;
1195         cctx->prefixDict.dictSize = prefixSize;
1196         cctx->prefixDict.dictContentType = dictContentType;
1197     }
1198     return 0;
1199 }
1200 
1201 /*! ZSTD_CCtx_reset() :
1202  *  Also dumps dictionary */
ZSTD_CCtx_reset(ZSTD_CCtx * cctx,ZSTD_ResetDirective reset)1203 size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
1204 {
1205     if ( (reset == ZSTD_reset_session_only)
1206       || (reset == ZSTD_reset_session_and_parameters) ) {
1207         cctx->streamStage = zcss_init;
1208         cctx->pledgedSrcSizePlusOne = 0;
1209     }
1210     if ( (reset == ZSTD_reset_parameters)
1211       || (reset == ZSTD_reset_session_and_parameters) ) {
1212         RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1213                         "Can't reset parameters only when not in init stage.");
1214         ZSTD_clearAllDicts(cctx);
1215         return ZSTD_CCtxParams_reset(&cctx->requestedParams);
1216     }
1217     return 0;
1218 }
1219 
1220 
1221 /** ZSTD_checkCParams() :
1222     control CParam values remain within authorized range.
1223     @return : 0, or an error code if one value is beyond authorized range */
ZSTD_checkCParams(ZSTD_compressionParameters cParams)1224 size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
1225 {
1226     BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog);
1227     BOUNDCHECK(ZSTD_c_chainLog,  (int)cParams.chainLog);
1228     BOUNDCHECK(ZSTD_c_hashLog,   (int)cParams.hashLog);
1229     BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog);
1230     BOUNDCHECK(ZSTD_c_minMatch,  (int)cParams.minMatch);
1231     BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength);
1232     BOUNDCHECK(ZSTD_c_strategy,  cParams.strategy);
1233     return 0;
1234 }
1235 
1236 /** ZSTD_clampCParams() :
1237  *  make CParam values within valid range.
1238  *  @return : valid CParams */
1239 static ZSTD_compressionParameters
ZSTD_clampCParams(ZSTD_compressionParameters cParams)1240 ZSTD_clampCParams(ZSTD_compressionParameters cParams)
1241 {
1242 #   define CLAMP_TYPE(cParam, val, type) {                                \
1243         ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);         \
1244         if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound;      \
1245         else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
1246     }
1247 #   define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
1248     CLAMP(ZSTD_c_windowLog, cParams.windowLog);
1249     CLAMP(ZSTD_c_chainLog,  cParams.chainLog);
1250     CLAMP(ZSTD_c_hashLog,   cParams.hashLog);
1251     CLAMP(ZSTD_c_searchLog, cParams.searchLog);
1252     CLAMP(ZSTD_c_minMatch,  cParams.minMatch);
1253     CLAMP(ZSTD_c_targetLength,cParams.targetLength);
1254     CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
1255     return cParams;
1256 }
1257 
1258 /** ZSTD_cycleLog() :
1259  *  condition for correct operation : hashLog > 1 */
ZSTD_cycleLog(U32 hashLog,ZSTD_strategy strat)1260 U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
1261 {
1262     U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
1263     return hashLog - btScale;
1264 }
1265 
1266 /** ZSTD_dictAndWindowLog() :
1267  * Returns an adjusted window log that is large enough to fit the source and the dictionary.
1268  * The zstd format says that the entire dictionary is valid if one byte of the dictionary
1269  * is within the window. So the hashLog and chainLog should be large enough to reference both
1270  * the dictionary and the window. So we must use this adjusted dictAndWindowLog when downsizing
1271  * the hashLog and windowLog.
1272  * NOTE: srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.
1273  */
ZSTD_dictAndWindowLog(U32 windowLog,U64 srcSize,U64 dictSize)1274 static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
1275 {
1276     const U64 maxWindowSize = 1ULL << ZSTD_WINDOWLOG_MAX;
1277     /* No dictionary ==> No change */
1278     if (dictSize == 0) {
1279         return windowLog;
1280     }
1281     assert(windowLog <= ZSTD_WINDOWLOG_MAX);
1282     assert(srcSize != ZSTD_CONTENTSIZE_UNKNOWN); /* Handled in ZSTD_adjustCParams_internal() */
1283     {
1284         U64 const windowSize = 1ULL << windowLog;
1285         U64 const dictAndWindowSize = dictSize + windowSize;
1286         /* If the window size is already large enough to fit both the source and the dictionary
1287          * then just use the window size. Otherwise adjust so that it fits the dictionary and
1288          * the window.
1289          */
1290         if (windowSize >= dictSize + srcSize) {
1291             return windowLog; /* Window size large enough already */
1292         } else if (dictAndWindowSize >= maxWindowSize) {
1293             return ZSTD_WINDOWLOG_MAX; /* Larger than max window log */
1294         } else  {
1295             return ZSTD_highbit32((U32)dictAndWindowSize - 1) + 1;
1296         }
1297     }
1298 }
1299 
1300 /** ZSTD_adjustCParams_internal() :
1301  *  optimize `cPar` for a specified input (`srcSize` and `dictSize`).
1302  *  mostly downsize to reduce memory consumption and initialization latency.
1303  * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.
1304  * `mode` is the mode for parameter adjustment. See docs for `ZSTD_cParamMode_e`.
1305  *  note : `srcSize==0` means 0!
1306  *  condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
1307 static ZSTD_compressionParameters
ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,unsigned long long srcSize,size_t dictSize,ZSTD_cParamMode_e mode)1308 ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
1309                             unsigned long long srcSize,
1310                             size_t dictSize,
1311                             ZSTD_cParamMode_e mode)
1312 {
1313     const U64 minSrcSize = 513; /* (1<<9) + 1 */
1314     const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
1315     assert(ZSTD_checkCParams(cPar)==0);
1316 
1317     switch (mode) {
1318     case ZSTD_cpm_unknown:
1319     case ZSTD_cpm_noAttachDict:
1320         /* If we don't know the source size, don't make any
1321          * assumptions about it. We will already have selected
1322          * smaller parameters if a dictionary is in use.
1323          */
1324         break;
1325     case ZSTD_cpm_createCDict:
1326         /* Assume a small source size when creating a dictionary
1327          * with an unkown source size.
1328          */
1329         if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)
1330             srcSize = minSrcSize;
1331         break;
1332     case ZSTD_cpm_attachDict:
1333         /* Dictionary has its own dedicated parameters which have
1334          * already been selected. We are selecting parameters
1335          * for only the source.
1336          */
1337         dictSize = 0;
1338         break;
1339     default:
1340         assert(0);
1341         break;
1342     }
1343 
1344     /* resize windowLog if input is small enough, to use less memory */
1345     if ( (srcSize < maxWindowResize)
1346       && (dictSize < maxWindowResize) )  {
1347         U32 const tSize = (U32)(srcSize + dictSize);
1348         static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
1349         U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
1350                             ZSTD_highbit32(tSize-1) + 1;
1351         if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
1352     }
1353     if (srcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
1354         U32 const dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, (U64)srcSize, (U64)dictSize);
1355         U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
1356         if (cPar.hashLog > dictAndWindowLog+1) cPar.hashLog = dictAndWindowLog+1;
1357         if (cycleLog > dictAndWindowLog)
1358             cPar.chainLog -= (cycleLog - dictAndWindowLog);
1359     }
1360 
1361     if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
1362         cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN;  /* minimum wlog required for valid frame header */
1363 
1364     return cPar;
1365 }
1366 
1367 ZSTD_compressionParameters
ZSTD_adjustCParams(ZSTD_compressionParameters cPar,unsigned long long srcSize,size_t dictSize)1368 ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
1369                    unsigned long long srcSize,
1370                    size_t dictSize)
1371 {
1372     cPar = ZSTD_clampCParams(cPar);   /* resulting cPar is necessarily valid (all parameters within range) */
1373     if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
1374     return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown);
1375 }
1376 
1377 static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
1378 static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
1379 
ZSTD_overrideCParams(ZSTD_compressionParameters * cParams,const ZSTD_compressionParameters * overrides)1380 static void ZSTD_overrideCParams(
1381               ZSTD_compressionParameters* cParams,
1382         const ZSTD_compressionParameters* overrides)
1383 {
1384     if (overrides->windowLog)    cParams->windowLog    = overrides->windowLog;
1385     if (overrides->hashLog)      cParams->hashLog      = overrides->hashLog;
1386     if (overrides->chainLog)     cParams->chainLog     = overrides->chainLog;
1387     if (overrides->searchLog)    cParams->searchLog    = overrides->searchLog;
1388     if (overrides->minMatch)     cParams->minMatch     = overrides->minMatch;
1389     if (overrides->targetLength) cParams->targetLength = overrides->targetLength;
1390     if (overrides->strategy)     cParams->strategy     = overrides->strategy;
1391 }
1392 
ZSTD_getCParamsFromCCtxParams(const ZSTD_CCtx_params * CCtxParams,U64 srcSizeHint,size_t dictSize,ZSTD_cParamMode_e mode)1393 ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
1394         const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
1395 {
1396     ZSTD_compressionParameters cParams;
1397     if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
1398       srcSizeHint = CCtxParams->srcSizeHint;
1399     }
1400     cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode);
1401     if (CCtxParams->ldmParams.enableLdm) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
1402     ZSTD_overrideCParams(&cParams, &CCtxParams->cParams);
1403     assert(!ZSTD_checkCParams(cParams));
1404     /* srcSizeHint == 0 means 0 */
1405     return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize, mode);
1406 }
1407 
1408 static size_t
ZSTD_sizeof_matchState(const ZSTD_compressionParameters * const cParams,const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,const U32 enableDedicatedDictSearch,const U32 forCCtx)1409 ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
1410                        const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
1411                        const U32 enableDedicatedDictSearch,
1412                        const U32 forCCtx)
1413 {
1414     /* chain table size should be 0 for fast or row-hash strategies */
1415     size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder, enableDedicatedDictSearch && !forCCtx)
1416                                 ? ((size_t)1 << cParams->chainLog)
1417                                 : 0;
1418     size_t const hSize = ((size_t)1) << cParams->hashLog;
1419     U32    const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
1420     size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
1421     /* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't
1422      * surrounded by redzones in ASAN. */
1423     size_t const tableSpace = chainSize * sizeof(U32)
1424                             + hSize * sizeof(U32)
1425                             + h3Size * sizeof(U32);
1426     size_t const optPotentialSpace =
1427         ZSTD_cwksp_aligned_alloc_size((MaxML+1) * sizeof(U32))
1428       + ZSTD_cwksp_aligned_alloc_size((MaxLL+1) * sizeof(U32))
1429       + ZSTD_cwksp_aligned_alloc_size((MaxOff+1) * sizeof(U32))
1430       + ZSTD_cwksp_aligned_alloc_size((1<<Litbits) * sizeof(U32))
1431       + ZSTD_cwksp_aligned_alloc_size((ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t))
1432       + ZSTD_cwksp_aligned_alloc_size((ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
1433     size_t const lazyAdditionalSpace = ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)
1434                                             ? ZSTD_cwksp_aligned_alloc_size(hSize*sizeof(U16))
1435                                             : 0;
1436     size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
1437                                 ? optPotentialSpace
1438                                 : 0;
1439     size_t const slackSpace = ZSTD_cwksp_slack_space_required();
1440 
1441     /* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */
1442     ZSTD_STATIC_ASSERT(ZSTD_HASHLOG_MIN >= 4 && ZSTD_WINDOWLOG_MIN >= 4 && ZSTD_CHAINLOG_MIN >= 4);
1443     assert(useRowMatchFinder != ZSTD_urm_auto);
1444 
1445     DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
1446                 (U32)chainSize, (U32)hSize, (U32)h3Size);
1447     return tableSpace + optSpace + slackSpace + lazyAdditionalSpace;
1448 }
1449 
ZSTD_estimateCCtxSize_usingCCtxParams_internal(const ZSTD_compressionParameters * cParams,const ldmParams_t * ldmParams,const int isStatic,const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,const size_t buffInSize,const size_t buffOutSize,const U64 pledgedSrcSize)1450 static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1451         const ZSTD_compressionParameters* cParams,
1452         const ldmParams_t* ldmParams,
1453         const int isStatic,
1454         const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
1455         const size_t buffInSize,
1456         const size_t buffOutSize,
1457         const U64 pledgedSrcSize)
1458 {
1459     size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << cParams->windowLog), pledgedSrcSize));
1460     size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
1461     U32    const divider = (cParams->minMatch==3) ? 3 : 4;
1462     size_t const maxNbSeq = blockSize / divider;
1463     size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
1464                             + ZSTD_cwksp_aligned_alloc_size(maxNbSeq * sizeof(seqDef))
1465                             + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
1466     size_t const entropySpace = ZSTD_cwksp_alloc_size(ENTROPY_WORKSPACE_SIZE);
1467     size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
1468     size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);
1469 
1470     size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
1471     size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
1472     size_t const ldmSeqSpace = ldmParams->enableLdm ?
1473         ZSTD_cwksp_aligned_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;
1474 
1475 
1476     size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)
1477                              + ZSTD_cwksp_alloc_size(buffOutSize);
1478 
1479     size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
1480 
1481     size_t const neededSpace =
1482         cctxSpace +
1483         entropySpace +
1484         blockStateSpace +
1485         ldmSpace +
1486         ldmSeqSpace +
1487         matchStateSize +
1488         tokenSpace +
1489         bufferSpace;
1490 
1491     DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);
1492     return neededSpace;
1493 }
1494 
ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params * params)1495 size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1496 {
1497     ZSTD_compressionParameters const cParams =
1498                 ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1499     ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
1500                                                                                          &cParams);
1501 
1502     RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1503     /* estimateCCtxSize is for one-shot compression. So no buffers should
1504      * be needed. However, we still allocate two 0-sized buffers, which can
1505      * take space under ASAN. */
1506     return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1507         &cParams, &params->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN);
1508 }
1509 
ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)1510 size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
1511 {
1512     ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
1513     if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
1514         /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
1515         size_t noRowCCtxSize;
1516         size_t rowCCtxSize;
1517         initialParams.useRowMatchFinder = ZSTD_urm_disableRowMatchFinder;
1518         noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1519         initialParams.useRowMatchFinder = ZSTD_urm_enableRowMatchFinder;
1520         rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1521         return MAX(noRowCCtxSize, rowCCtxSize);
1522     } else {
1523         return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1524     }
1525 }
1526 
ZSTD_estimateCCtxSize_internal(int compressionLevel)1527 static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
1528 {
1529     int tier = 0;
1530     size_t largestSize = 0;
1531     static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};
1532     for (; tier < 4; ++tier) {
1533         /* Choose the set of cParams for a given level across all srcSizes that give the largest cctxSize */
1534         ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeTiers[tier], 0, ZSTD_cpm_noAttachDict);
1535         largestSize = MAX(ZSTD_estimateCCtxSize_usingCParams(cParams), largestSize);
1536     }
1537     return largestSize;
1538 }
1539 
ZSTD_estimateCCtxSize(int compressionLevel)1540 size_t ZSTD_estimateCCtxSize(int compressionLevel)
1541 {
1542     int level;
1543     size_t memBudget = 0;
1544     for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1545         /* Ensure monotonically increasing memory usage as compression level increases */
1546         size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
1547         if (newMB > memBudget) memBudget = newMB;
1548     }
1549     return memBudget;
1550 }
1551 
ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params * params)1552 size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1553 {
1554     RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1555     {   ZSTD_compressionParameters const cParams =
1556                 ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1557         size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
1558         size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)
1559                 ? ((size_t)1 << cParams.windowLog) + blockSize
1560                 : 0;
1561         size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)
1562                 ? ZSTD_compressBound(blockSize) + 1
1563                 : 0;
1564         ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, &params->cParams);
1565 
1566         return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1567             &cParams, &params->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
1568             ZSTD_CONTENTSIZE_UNKNOWN);
1569     }
1570 }
1571 
ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)1572 size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
1573 {
1574     ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
1575     if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
1576         /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
1577         size_t noRowCCtxSize;
1578         size_t rowCCtxSize;
1579         initialParams.useRowMatchFinder = ZSTD_urm_disableRowMatchFinder;
1580         noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1581         initialParams.useRowMatchFinder = ZSTD_urm_enableRowMatchFinder;
1582         rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1583         return MAX(noRowCCtxSize, rowCCtxSize);
1584     } else {
1585         return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1586     }
1587 }
1588 
ZSTD_estimateCStreamSize_internal(int compressionLevel)1589 static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
1590 {
1591     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1592     return ZSTD_estimateCStreamSize_usingCParams(cParams);
1593 }
1594 
ZSTD_estimateCStreamSize(int compressionLevel)1595 size_t ZSTD_estimateCStreamSize(int compressionLevel)
1596 {
1597     int level;
1598     size_t memBudget = 0;
1599     for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1600         size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
1601         if (newMB > memBudget) memBudget = newMB;
1602     }
1603     return memBudget;
1604 }
1605 
1606 /* ZSTD_getFrameProgression():
1607  * tells how much data has been consumed (input) and produced (output) for current frame.
1608  * able to count progression inside worker threads (non-blocking mode).
1609  */
ZSTD_getFrameProgression(const ZSTD_CCtx * cctx)1610 ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
1611 {
1612 #ifdef ZSTD_MULTITHREAD
1613     if (cctx->appliedParams.nbWorkers > 0) {
1614         return ZSTDMT_getFrameProgression(cctx->mtctx);
1615     }
1616 #endif
1617     {   ZSTD_frameProgression fp;
1618         size_t const buffered = (cctx->inBuff == NULL) ? 0 :
1619                                 cctx->inBuffPos - cctx->inToCompress;
1620         if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
1621         assert(buffered <= ZSTD_BLOCKSIZE_MAX);
1622         fp.ingested = cctx->consumedSrcSize + buffered;
1623         fp.consumed = cctx->consumedSrcSize;
1624         fp.produced = cctx->producedCSize;
1625         fp.flushed  = cctx->producedCSize;   /* simplified; some data might still be left within streaming output buffer */
1626         fp.currentJobID = 0;
1627         fp.nbActiveWorkers = 0;
1628         return fp;
1629 }   }
1630 
1631 /*! ZSTD_toFlushNow()
1632  *  Only useful for multithreading scenarios currently (nbWorkers >= 1).
1633  */
ZSTD_toFlushNow(ZSTD_CCtx * cctx)1634 size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
1635 {
1636 #ifdef ZSTD_MULTITHREAD
1637     if (cctx->appliedParams.nbWorkers > 0) {
1638         return ZSTDMT_toFlushNow(cctx->mtctx);
1639     }
1640 #endif
1641     (void)cctx;
1642     return 0;   /* over-simplification; could also check if context is currently running in streaming mode, and in which case, report how many bytes are left to be flushed within output buffer */
1643 }
1644 
ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,ZSTD_compressionParameters cParams2)1645 static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
1646                                     ZSTD_compressionParameters cParams2)
1647 {
1648     (void)cParams1;
1649     (void)cParams2;
1650     assert(cParams1.windowLog    == cParams2.windowLog);
1651     assert(cParams1.chainLog     == cParams2.chainLog);
1652     assert(cParams1.hashLog      == cParams2.hashLog);
1653     assert(cParams1.searchLog    == cParams2.searchLog);
1654     assert(cParams1.minMatch     == cParams2.minMatch);
1655     assert(cParams1.targetLength == cParams2.targetLength);
1656     assert(cParams1.strategy     == cParams2.strategy);
1657 }
1658 
ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t * bs)1659 void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
1660 {
1661     int i;
1662     for (i = 0; i < ZSTD_REP_NUM; ++i)
1663         bs->rep[i] = repStartValue[i];
1664     bs->entropy.huf.repeatMode = HUF_repeat_none;
1665     bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
1666     bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
1667     bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
1668 }
1669 
1670 /*! ZSTD_invalidateMatchState()
1671  *  Invalidate all the matches in the match finder tables.
1672  *  Requires nextSrc and base to be set (can be NULL).
1673  */
ZSTD_invalidateMatchState(ZSTD_matchState_t * ms)1674 static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms)
1675 {
1676     ZSTD_window_clear(&ms->window);
1677 
1678     ms->nextToUpdate = ms->window.dictLimit;
1679     ms->loadedDictEnd = 0;
1680     ms->opt.litLengthSum = 0;  /* force reset of btopt stats */
1681     ms->dictMatchState = NULL;
1682 }
1683 
1684 /**
1685  * Controls, for this matchState reset, whether the tables need to be cleared /
1686  * prepared for the coming compression (ZSTDcrp_makeClean), or whether the
1687  * tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a
1688  * subsequent operation will overwrite the table space anyways (e.g., copying
1689  * the matchState contents in from a CDict).
1690  */
1691 typedef enum {
1692     ZSTDcrp_makeClean,
1693     ZSTDcrp_leaveDirty
1694 } ZSTD_compResetPolicy_e;
1695 
1696 /**
1697  * Controls, for this matchState reset, whether indexing can continue where it
1698  * left off (ZSTDirp_continue), or whether it needs to be restarted from zero
1699  * (ZSTDirp_reset).
1700  */
1701 typedef enum {
1702     ZSTDirp_continue,
1703     ZSTDirp_reset
1704 } ZSTD_indexResetPolicy_e;
1705 
1706 typedef enum {
1707     ZSTD_resetTarget_CDict,
1708     ZSTD_resetTarget_CCtx
1709 } ZSTD_resetTarget_e;
1710 
1711 
1712 static size_t
ZSTD_reset_matchState(ZSTD_matchState_t * ms,ZSTD_cwksp * ws,const ZSTD_compressionParameters * cParams,const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,const ZSTD_compResetPolicy_e crp,const ZSTD_indexResetPolicy_e forceResetIndex,const ZSTD_resetTarget_e forWho)1713 ZSTD_reset_matchState(ZSTD_matchState_t* ms,
1714                       ZSTD_cwksp* ws,
1715                 const ZSTD_compressionParameters* cParams,
1716                 const ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
1717                 const ZSTD_compResetPolicy_e crp,
1718                 const ZSTD_indexResetPolicy_e forceResetIndex,
1719                 const ZSTD_resetTarget_e forWho)
1720 {
1721     /* disable chain table allocation for fast or row-based strategies */
1722     size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,
1723                                                      ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))
1724                                 ? ((size_t)1 << cParams->chainLog)
1725                                 : 0;
1726     size_t const hSize = ((size_t)1) << cParams->hashLog;
1727     U32    const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
1728     size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
1729 
1730     DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
1731     assert(useRowMatchFinder != ZSTD_urm_auto);
1732     if (forceResetIndex == ZSTDirp_reset) {
1733         ZSTD_window_init(&ms->window);
1734         ZSTD_cwksp_mark_tables_dirty(ws);
1735     }
1736 
1737     ms->hashLog3 = hashLog3;
1738 
1739     ZSTD_invalidateMatchState(ms);
1740 
1741     assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
1742 
1743     ZSTD_cwksp_clear_tables(ws);
1744 
1745     DEBUGLOG(5, "reserving table space");
1746     /* table Space */
1747     ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
1748     ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
1749     ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
1750     RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
1751                     "failed a workspace allocation in ZSTD_reset_matchState");
1752 
1753     DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
1754     if (crp!=ZSTDcrp_leaveDirty) {
1755         /* reset tables only */
1756         ZSTD_cwksp_clean_tables(ws);
1757     }
1758 
1759     /* opt parser space */
1760     if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
1761         DEBUGLOG(4, "reserving optimal parser space");
1762         ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (1<<Litbits) * sizeof(unsigned));
1763         ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned));
1764         ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned));
1765         ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned));
1766         ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t));
1767         ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
1768     }
1769 
1770     if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {
1771         {   /* Row match finder needs an additional table of hashes ("tags") */
1772             size_t const tagTableSize = hSize*sizeof(U16);
1773             ms->tagTable = (U16*)ZSTD_cwksp_reserve_aligned(ws, tagTableSize);
1774             if (ms->tagTable) ZSTD_memset(ms->tagTable, 0, tagTableSize);
1775         }
1776         {   /* Switch to 32-entry rows if searchLog is 5 (or more) */
1777             U32 const rowLog = cParams->searchLog < 5 ? 4 : 5;
1778             assert(cParams->hashLog > rowLog);
1779             ms->rowHashLog = cParams->hashLog - rowLog;
1780         }
1781     }
1782 
1783     ms->cParams = *cParams;
1784 
1785     RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
1786                     "failed a workspace allocation in ZSTD_reset_matchState");
1787     return 0;
1788 }
1789 
1790 /* ZSTD_indexTooCloseToMax() :
1791  * minor optimization : prefer memset() rather than reduceIndex()
1792  * which is measurably slow in some circumstances (reported for Visual Studio).
1793  * Works when re-using a context for a lot of smallish inputs :
1794  * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,
1795  * memset() will be triggered before reduceIndex().
1796  */
1797 #define ZSTD_INDEXOVERFLOW_MARGIN (16 MB)
ZSTD_indexTooCloseToMax(ZSTD_window_t w)1798 static int ZSTD_indexTooCloseToMax(ZSTD_window_t w)
1799 {
1800     return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN);
1801 }
1802 
1803 /** ZSTD_dictTooBig():
1804  * When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in
1805  * one go generically. So we ensure that in that case we reset the tables to zero,
1806  * so that we can load as much of the dictionary as possible.
1807  */
ZSTD_dictTooBig(size_t const loadedDictSize)1808 static int ZSTD_dictTooBig(size_t const loadedDictSize)
1809 {
1810     return loadedDictSize > ZSTD_CHUNKSIZE_MAX;
1811 }
1812 
1813 /*! ZSTD_resetCCtx_internal() :
1814  * @param loadedDictSize The size of the dictionary to be loaded
1815  * into the context, if any. If no dictionary is used, or the
1816  * dictionary is being attached / copied, then pass 0.
1817  * note : `params` are assumed fully validated at this stage.
1818  */
ZSTD_resetCCtx_internal(ZSTD_CCtx * zc,ZSTD_CCtx_params const * params,U64 const pledgedSrcSize,size_t const loadedDictSize,ZSTD_compResetPolicy_e const crp,ZSTD_buffered_policy_e const zbuff)1819 static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
1820                                       ZSTD_CCtx_params const* params,
1821                                       U64 const pledgedSrcSize,
1822                                       size_t const loadedDictSize,
1823                                       ZSTD_compResetPolicy_e const crp,
1824                                       ZSTD_buffered_policy_e const zbuff)
1825 {
1826     ZSTD_cwksp* const ws = &zc->workspace;
1827     DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d",
1828                 (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder);
1829     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
1830 
1831     zc->isFirstBlock = 1;
1832 
1833     /* Set applied params early so we can modify them for LDM,
1834      * and point params at the applied params.
1835      */
1836     zc->appliedParams = *params;
1837     params = &zc->appliedParams;
1838 
1839     assert(params->useRowMatchFinder != ZSTD_urm_auto);
1840     if (params->ldmParams.enableLdm) {
1841         /* Adjust long distance matching parameters */
1842         ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, &params->cParams);
1843         assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);
1844         assert(params->ldmParams.hashRateLog < 32);
1845     }
1846 
1847     {   size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
1848         size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
1849         U32    const divider = (params->cParams.minMatch==3) ? 3 : 4;
1850         size_t const maxNbSeq = blockSize / divider;
1851         size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
1852                 ? ZSTD_compressBound(blockSize) + 1
1853                 : 0;
1854         size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)
1855                 ? windowSize + blockSize
1856                 : 0;
1857         size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);
1858 
1859         int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);
1860         int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);
1861         ZSTD_indexResetPolicy_e needsIndexReset =
1862             (indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;
1863 
1864         size_t const neededSpace =
1865             ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1866                 &params->cParams, &params->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
1867                 buffInSize, buffOutSize, pledgedSrcSize);
1868         int resizeWorkspace;
1869 
1870         FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
1871 
1872         if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
1873 
1874         {   /* Check if workspace is large enough, alloc a new one if needed */
1875             int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
1876             int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
1877             resizeWorkspace = workspaceTooSmall || workspaceWasteful;
1878             DEBUGLOG(4, "Need %zu B workspace", neededSpace);
1879             DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
1880 
1881             if (resizeWorkspace) {
1882                 DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
1883                             ZSTD_cwksp_sizeof(ws) >> 10,
1884                             neededSpace >> 10);
1885 
1886                 RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
1887 
1888                 needsIndexReset = ZSTDirp_reset;
1889 
1890                 ZSTD_cwksp_free(ws, zc->customMem);
1891                 FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
1892 
1893                 DEBUGLOG(5, "reserving object space");
1894                 /* Statically sized space.
1895                  * entropyWorkspace never moves,
1896                  * though prev/next block swap places */
1897                 assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
1898                 zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
1899                 RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
1900                 zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
1901                 RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
1902                 zc->entropyWorkspace = (U32*) ZSTD_cwksp_reserve_object(ws, ENTROPY_WORKSPACE_SIZE);
1903                 RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate entropyWorkspace");
1904         }   }
1905 
1906         ZSTD_cwksp_clear(ws);
1907 
1908         /* init params */
1909         zc->blockState.matchState.cParams = params->cParams;
1910         zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
1911         zc->consumedSrcSize = 0;
1912         zc->producedCSize = 0;
1913         if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
1914             zc->appliedParams.fParams.contentSizeFlag = 0;
1915         DEBUGLOG(4, "pledged content size : %u ; flag : %u",
1916             (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
1917         zc->blockSize = blockSize;
1918 
1919         XXH64_reset(&zc->xxhState, 0);
1920         zc->stage = ZSTDcs_init;
1921         zc->dictID = 0;
1922         zc->dictContentSize = 0;
1923 
1924         ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
1925 
1926         /* ZSTD_wildcopy() is used to copy into the literals buffer,
1927          * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
1928          */
1929         zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
1930         zc->seqStore.maxNbLit = blockSize;
1931 
1932         /* buffers */
1933         zc->bufferedPolicy = zbuff;
1934         zc->inBuffSize = buffInSize;
1935         zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
1936         zc->outBuffSize = buffOutSize;
1937         zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
1938 
1939         /* ldm bucketOffsets table */
1940         if (params->ldmParams.enableLdm) {
1941             /* TODO: avoid memset? */
1942             size_t const numBuckets =
1943                   ((size_t)1) << (params->ldmParams.hashLog -
1944                                   params->ldmParams.bucketSizeLog);
1945             zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
1946             ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);
1947         }
1948 
1949         /* sequences storage */
1950         ZSTD_referenceExternalSequences(zc, NULL, 0);
1951         zc->seqStore.maxNbSeq = maxNbSeq;
1952         zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
1953         zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
1954         zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
1955         zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned(ws, maxNbSeq * sizeof(seqDef));
1956 
1957         FORWARD_IF_ERROR(ZSTD_reset_matchState(
1958             &zc->blockState.matchState,
1959             ws,
1960             &params->cParams,
1961             params->useRowMatchFinder,
1962             crp,
1963             needsIndexReset,
1964             ZSTD_resetTarget_CCtx), "");
1965 
1966         /* ldm hash table */
1967         if (params->ldmParams.enableLdm) {
1968             /* TODO: avoid memset? */
1969             size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;
1970             zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned(ws, ldmHSize * sizeof(ldmEntry_t));
1971             ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
1972             zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned(ws, maxNbLdmSeq * sizeof(rawSeq));
1973             zc->maxNbLdmSequences = maxNbLdmSeq;
1974 
1975             ZSTD_window_init(&zc->ldmState.window);
1976             zc->ldmState.loadedDictEnd = 0;
1977         }
1978 
1979         assert(ZSTD_cwksp_estimated_space_within_bounds(ws, neededSpace, resizeWorkspace));
1980         DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
1981 
1982         zc->initialized = 1;
1983 
1984         return 0;
1985     }
1986 }
1987 
1988 /* ZSTD_invalidateRepCodes() :
1989  * ensures next compression will not use repcodes from previous block.
1990  * Note : only works with regular variant;
1991  *        do not use with extDict variant ! */
ZSTD_invalidateRepCodes(ZSTD_CCtx * cctx)1992 void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
1993     int i;
1994     for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
1995     assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
1996 }
1997 
1998 /* These are the approximate sizes for each strategy past which copying the
1999  * dictionary tables into the working context is faster than using them
2000  * in-place.
2001  */
2002 static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
2003     8 KB,  /* unused */
2004     8 KB,  /* ZSTD_fast */
2005     16 KB, /* ZSTD_dfast */
2006     32 KB, /* ZSTD_greedy */
2007     32 KB, /* ZSTD_lazy */
2008     32 KB, /* ZSTD_lazy2 */
2009     32 KB, /* ZSTD_btlazy2 */
2010     32 KB, /* ZSTD_btopt */
2011     8 KB,  /* ZSTD_btultra */
2012     8 KB   /* ZSTD_btultra2 */
2013 };
2014 
ZSTD_shouldAttachDict(const ZSTD_CDict * cdict,const ZSTD_CCtx_params * params,U64 pledgedSrcSize)2015 static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
2016                                  const ZSTD_CCtx_params* params,
2017                                  U64 pledgedSrcSize)
2018 {
2019     size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
2020     int const dedicatedDictSearch = cdict->matchState.dedicatedDictSearch;
2021     return dedicatedDictSearch
2022         || ( ( pledgedSrcSize <= cutoff
2023             || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
2024             || params->attachDictPref == ZSTD_dictForceAttach )
2025           && params->attachDictPref != ZSTD_dictForceCopy
2026           && !params->forceWindow ); /* dictMatchState isn't correctly
2027                                       * handled in _enforceMaxDist */
2028 }
2029 
2030 static size_t
ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict,ZSTD_CCtx_params params,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)2031 ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
2032                         const ZSTD_CDict* cdict,
2033                         ZSTD_CCtx_params params,
2034                         U64 pledgedSrcSize,
2035                         ZSTD_buffered_policy_e zbuff)
2036 {
2037     DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",
2038                 (unsigned long long)pledgedSrcSize);
2039     {
2040         ZSTD_compressionParameters adjusted_cdict_cParams = cdict->matchState.cParams;
2041         unsigned const windowLog = params.cParams.windowLog;
2042         assert(windowLog != 0);
2043         /* Resize working context table params for input only, since the dict
2044          * has its own tables. */
2045         /* pledgedSrcSize == 0 means 0! */
2046 
2047         if (cdict->matchState.dedicatedDictSearch) {
2048             ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);
2049         }
2050 
2051         params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,
2052                                                      cdict->dictContentSize, ZSTD_cpm_attachDict);
2053         params.cParams.windowLog = windowLog;
2054         params.useRowMatchFinder = cdict->useRowMatchFinder;    /* cdict overrides */
2055         FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
2056                                                  /* loadedDictSize */ 0,
2057                                                  ZSTDcrp_makeClean, zbuff), "");
2058         assert(cctx->appliedParams.cParams.strategy == adjusted_cdict_cParams.strategy);
2059     }
2060 
2061     {   const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
2062                                   - cdict->matchState.window.base);
2063         const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
2064         if (cdictLen == 0) {
2065             /* don't even attach dictionaries with no contents */
2066             DEBUGLOG(4, "skipping attaching empty dictionary");
2067         } else {
2068             DEBUGLOG(4, "attaching dictionary into context");
2069             cctx->blockState.matchState.dictMatchState = &cdict->matchState;
2070 
2071             /* prep working match state so dict matches never have negative indices
2072              * when they are translated to the working context's index space. */
2073             if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
2074                 cctx->blockState.matchState.window.nextSrc =
2075                     cctx->blockState.matchState.window.base + cdictEnd;
2076                 ZSTD_window_clear(&cctx->blockState.matchState.window);
2077             }
2078             /* loadedDictEnd is expressed within the referential of the active context */
2079             cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
2080     }   }
2081 
2082     cctx->dictID = cdict->dictID;
2083     cctx->dictContentSize = cdict->dictContentSize;
2084 
2085     /* copy block state */
2086     ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
2087 
2088     return 0;
2089 }
2090 
ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict,ZSTD_CCtx_params params,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)2091 static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
2092                             const ZSTD_CDict* cdict,
2093                             ZSTD_CCtx_params params,
2094                             U64 pledgedSrcSize,
2095                             ZSTD_buffered_policy_e zbuff)
2096 {
2097     const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
2098 
2099     assert(!cdict->matchState.dedicatedDictSearch);
2100     DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",
2101                 (unsigned long long)pledgedSrcSize);
2102 
2103     {   unsigned const windowLog = params.cParams.windowLog;
2104         assert(windowLog != 0);
2105         /* Copy only compression parameters related to tables. */
2106         params.cParams = *cdict_cParams;
2107         params.cParams.windowLog = windowLog;
2108         params.useRowMatchFinder = cdict->useRowMatchFinder;
2109         FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
2110                                                  /* loadedDictSize */ 0,
2111                                                  ZSTDcrp_leaveDirty, zbuff), "");
2112         assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
2113         assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
2114         assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
2115     }
2116 
2117     ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
2118     assert(params.useRowMatchFinder != ZSTD_urm_auto);
2119 
2120     /* copy tables */
2121     {   size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)
2122                                                             ? ((size_t)1 << cdict_cParams->chainLog)
2123                                                             : 0;
2124         size_t const hSize =  (size_t)1 << cdict_cParams->hashLog;
2125 
2126         ZSTD_memcpy(cctx->blockState.matchState.hashTable,
2127                cdict->matchState.hashTable,
2128                hSize * sizeof(U32));
2129         /* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */
2130         if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {
2131             ZSTD_memcpy(cctx->blockState.matchState.chainTable,
2132                cdict->matchState.chainTable,
2133                chainSize * sizeof(U32));
2134         }
2135         /* copy tag table */
2136         if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {
2137             size_t const tagTableSize = hSize*sizeof(U16);
2138             ZSTD_memcpy(cctx->blockState.matchState.tagTable,
2139                 cdict->matchState.tagTable,
2140                 tagTableSize);
2141         }
2142     }
2143 
2144     /* Zero the hashTable3, since the cdict never fills it */
2145     {   int const h3log = cctx->blockState.matchState.hashLog3;
2146         size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2147         assert(cdict->matchState.hashLog3 == 0);
2148         ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
2149     }
2150 
2151     ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
2152 
2153     /* copy dictionary offsets */
2154     {   ZSTD_matchState_t const* srcMatchState = &cdict->matchState;
2155         ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState;
2156         dstMatchState->window       = srcMatchState->window;
2157         dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2158         dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2159     }
2160 
2161     cctx->dictID = cdict->dictID;
2162     cctx->dictContentSize = cdict->dictContentSize;
2163 
2164     /* copy block state */
2165     ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
2166 
2167     return 0;
2168 }
2169 
2170 /* We have a choice between copying the dictionary context into the working
2171  * context, or referencing the dictionary context from the working context
2172  * in-place. We decide here which strategy to use. */
ZSTD_resetCCtx_usingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict,const ZSTD_CCtx_params * params,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)2173 static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
2174                             const ZSTD_CDict* cdict,
2175                             const ZSTD_CCtx_params* params,
2176                             U64 pledgedSrcSize,
2177                             ZSTD_buffered_policy_e zbuff)
2178 {
2179 
2180     DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
2181                 (unsigned)pledgedSrcSize);
2182 
2183     if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
2184         return ZSTD_resetCCtx_byAttachingCDict(
2185             cctx, cdict, *params, pledgedSrcSize, zbuff);
2186     } else {
2187         return ZSTD_resetCCtx_byCopyingCDict(
2188             cctx, cdict, *params, pledgedSrcSize, zbuff);
2189     }
2190 }
2191 
2192 /*! ZSTD_copyCCtx_internal() :
2193  *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2194  *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2195  *  The "context", in this case, refers to the hash and chain tables,
2196  *  entropy tables, and dictionary references.
2197  * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
2198  * @return : 0, or an error code */
ZSTD_copyCCtx_internal(ZSTD_CCtx * dstCCtx,const ZSTD_CCtx * srcCCtx,ZSTD_frameParameters fParams,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)2199 static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
2200                             const ZSTD_CCtx* srcCCtx,
2201                             ZSTD_frameParameters fParams,
2202                             U64 pledgedSrcSize,
2203                             ZSTD_buffered_policy_e zbuff)
2204 {
2205     RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
2206                     "Can't copy a ctx that's not in init stage.");
2207     DEBUGLOG(5, "ZSTD_copyCCtx_internal");
2208     ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
2209     {   ZSTD_CCtx_params params = dstCCtx->requestedParams;
2210         /* Copy only compression parameters related to tables. */
2211         params.cParams = srcCCtx->appliedParams.cParams;
2212         assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_urm_auto);
2213         params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
2214         params.fParams = fParams;
2215         ZSTD_resetCCtx_internal(dstCCtx, &params, pledgedSrcSize,
2216                                 /* loadedDictSize */ 0,
2217                                 ZSTDcrp_leaveDirty, zbuff);
2218         assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
2219         assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
2220         assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
2221         assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
2222         assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
2223     }
2224 
2225     ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
2226 
2227     /* copy tables */
2228     {   size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
2229                                                          srcCCtx->appliedParams.useRowMatchFinder,
2230                                                          0 /* forDDSDict */)
2231                                     ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
2232                                     : 0;
2233         size_t const hSize =  (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
2234         int const h3log = srcCCtx->blockState.matchState.hashLog3;
2235         size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2236 
2237         ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
2238                srcCCtx->blockState.matchState.hashTable,
2239                hSize * sizeof(U32));
2240         ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
2241                srcCCtx->blockState.matchState.chainTable,
2242                chainSize * sizeof(U32));
2243         ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
2244                srcCCtx->blockState.matchState.hashTable3,
2245                h3Size * sizeof(U32));
2246     }
2247 
2248     ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
2249 
2250     /* copy dictionary offsets */
2251     {
2252         const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState;
2253         ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState;
2254         dstMatchState->window       = srcMatchState->window;
2255         dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2256         dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2257     }
2258     dstCCtx->dictID = srcCCtx->dictID;
2259     dstCCtx->dictContentSize = srcCCtx->dictContentSize;
2260 
2261     /* copy block state */
2262     ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
2263 
2264     return 0;
2265 }
2266 
2267 /*! ZSTD_copyCCtx() :
2268  *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2269  *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2270  *  pledgedSrcSize==0 means "unknown".
2271 *   @return : 0, or an error code */
ZSTD_copyCCtx(ZSTD_CCtx * dstCCtx,const ZSTD_CCtx * srcCCtx,unsigned long long pledgedSrcSize)2272 size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
2273 {
2274     ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
2275     ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy;
2276     ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
2277     if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
2278     fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
2279 
2280     return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
2281                                 fParams, pledgedSrcSize,
2282                                 zbuff);
2283 }
2284 
2285 
2286 #define ZSTD_ROWSIZE 16
2287 /*! ZSTD_reduceTable() :
2288  *  reduce table indexes by `reducerValue`, or squash to zero.
2289  *  PreserveMark preserves "unsorted mark" for btlazy2 strategy.
2290  *  It must be set to a clear 0/1 value, to remove branch during inlining.
2291  *  Presume table size is a multiple of ZSTD_ROWSIZE
2292  *  to help auto-vectorization */
2293 FORCE_INLINE_TEMPLATE void
ZSTD_reduceTable_internal(U32 * const table,U32 const size,U32 const reducerValue,int const preserveMark)2294 ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
2295 {
2296     int const nbRows = (int)size / ZSTD_ROWSIZE;
2297     int cellNb = 0;
2298     int rowNb;
2299     assert((size & (ZSTD_ROWSIZE-1)) == 0);  /* multiple of ZSTD_ROWSIZE */
2300     assert(size < (1U<<31));   /* can be casted to int */
2301 
2302 #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
2303     /* To validate that the table re-use logic is sound, and that we don't
2304      * access table space that we haven't cleaned, we re-"poison" the table
2305      * space every time we mark it dirty.
2306      *
2307      * This function however is intended to operate on those dirty tables and
2308      * re-clean them. So when this function is used correctly, we can unpoison
2309      * the memory it operated on. This introduces a blind spot though, since
2310      * if we now try to operate on __actually__ poisoned memory, we will not
2311      * detect that. */
2312     __msan_unpoison(table, size * sizeof(U32));
2313 #endif
2314 
2315     for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
2316         int column;
2317         for (column=0; column<ZSTD_ROWSIZE; column++) {
2318             if (preserveMark) {
2319                 U32 const adder = (table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) ? reducerValue : 0;
2320                 table[cellNb] += adder;
2321             }
2322             if (table[cellNb] < reducerValue) table[cellNb] = 0;
2323             else table[cellNb] -= reducerValue;
2324             cellNb++;
2325     }   }
2326 }
2327 
ZSTD_reduceTable(U32 * const table,U32 const size,U32 const reducerValue)2328 static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
2329 {
2330     ZSTD_reduceTable_internal(table, size, reducerValue, 0);
2331 }
2332 
ZSTD_reduceTable_btlazy2(U32 * const table,U32 const size,U32 const reducerValue)2333 static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
2334 {
2335     ZSTD_reduceTable_internal(table, size, reducerValue, 1);
2336 }
2337 
2338 /*! ZSTD_reduceIndex() :
2339 *   rescale all indexes to avoid future overflow (indexes are U32) */
ZSTD_reduceIndex(ZSTD_matchState_t * ms,ZSTD_CCtx_params const * params,const U32 reducerValue)2340 static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)
2341 {
2342     {   U32 const hSize = (U32)1 << params->cParams.hashLog;
2343         ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
2344     }
2345 
2346     if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {
2347         U32 const chainSize = (U32)1 << params->cParams.chainLog;
2348         if (params->cParams.strategy == ZSTD_btlazy2)
2349             ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
2350         else
2351             ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
2352     }
2353 
2354     if (ms->hashLog3) {
2355         U32 const h3Size = (U32)1 << ms->hashLog3;
2356         ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
2357     }
2358 }
2359 
2360 
2361 /*-*******************************************************
2362 *  Block entropic compression
2363 *********************************************************/
2364 
2365 /* See doc/zstd_compression_format.md for detailed format description */
2366 
ZSTD_seqToCodes(const seqStore_t * seqStorePtr)2367 void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
2368 {
2369     const seqDef* const sequences = seqStorePtr->sequencesStart;
2370     BYTE* const llCodeTable = seqStorePtr->llCode;
2371     BYTE* const ofCodeTable = seqStorePtr->ofCode;
2372     BYTE* const mlCodeTable = seqStorePtr->mlCode;
2373     U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2374     U32 u;
2375     assert(nbSeq <= seqStorePtr->maxNbSeq);
2376     for (u=0; u<nbSeq; u++) {
2377         U32 const llv = sequences[u].litLength;
2378         U32 const mlv = sequences[u].matchLength;
2379         llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
2380         ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
2381         mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
2382     }
2383     if (seqStorePtr->longLengthType==ZSTD_llt_literalLength)
2384         llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
2385     if (seqStorePtr->longLengthType==ZSTD_llt_matchLength)
2386         mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
2387 }
2388 
2389 /* ZSTD_useTargetCBlockSize():
2390  * Returns if target compressed block size param is being used.
2391  * If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.
2392  * Returns 1 if true, 0 otherwise. */
ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params * cctxParams)2393 static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)
2394 {
2395     DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);
2396     return (cctxParams->targetCBlockSize != 0);
2397 }
2398 
2399 /* ZSTD_blockSplitterEnabled():
2400  * Returns if block splitting param is being used
2401  * If used, compression will do best effort to split a block in order to improve compression ratio.
2402  * Returns 1 if true, 0 otherwise. */
ZSTD_blockSplitterEnabled(ZSTD_CCtx_params * cctxParams)2403 static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams)
2404 {
2405     DEBUGLOG(5, "ZSTD_blockSplitterEnabled(splitBlocks=%d)", cctxParams->splitBlocks);
2406     return (cctxParams->splitBlocks != 0);
2407 }
2408 
2409 /* Type returned by ZSTD_buildSequencesStatistics containing finalized symbol encoding types
2410  * and size of the sequences statistics
2411  */
2412 typedef struct {
2413     U32 LLtype;
2414     U32 Offtype;
2415     U32 MLtype;
2416     size_t size;
2417     size_t lastCountSize; /* Accounts for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
2418 } ZSTD_symbolEncodingTypeStats_t;
2419 
2420 /* ZSTD_buildSequencesStatistics():
2421  * Returns a ZSTD_symbolEncodingTypeStats_t, or a zstd error code in the `size` field.
2422  * Modifies `nextEntropy` to have the appropriate values as a side effect.
2423  * nbSeq must be greater than 0.
2424  *
2425  * entropyWkspSize must be of size at least ENTROPY_WORKSPACE_SIZE - (MaxSeq + 1)*sizeof(U32)
2426  */
2427 static ZSTD_symbolEncodingTypeStats_t
ZSTD_buildSequencesStatistics(seqStore_t * seqStorePtr,size_t nbSeq,const ZSTD_fseCTables_t * prevEntropy,ZSTD_fseCTables_t * nextEntropy,BYTE * dst,const BYTE * const dstEnd,ZSTD_strategy strategy,unsigned * countWorkspace,void * entropyWorkspace,size_t entropyWkspSize)2428 ZSTD_buildSequencesStatistics(seqStore_t* seqStorePtr, size_t nbSeq,
2429                         const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy,
2430                               BYTE* dst, const BYTE* const dstEnd,
2431                               ZSTD_strategy strategy, unsigned* countWorkspace,
2432                               void* entropyWorkspace, size_t entropyWkspSize) {
2433     BYTE* const ostart = dst;
2434     const BYTE* const oend = dstEnd;
2435     BYTE* op = ostart;
2436     FSE_CTable* CTable_LitLength = nextEntropy->litlengthCTable;
2437     FSE_CTable* CTable_OffsetBits = nextEntropy->offcodeCTable;
2438     FSE_CTable* CTable_MatchLength = nextEntropy->matchlengthCTable;
2439     const BYTE* const ofCodeTable = seqStorePtr->ofCode;
2440     const BYTE* const llCodeTable = seqStorePtr->llCode;
2441     const BYTE* const mlCodeTable = seqStorePtr->mlCode;
2442     ZSTD_symbolEncodingTypeStats_t stats;
2443 
2444     stats.lastCountSize = 0;
2445     /* convert length/distances into codes */
2446     ZSTD_seqToCodes(seqStorePtr);
2447     assert(op <= oend);
2448     assert(nbSeq != 0); /* ZSTD_selectEncodingType() divides by nbSeq */
2449     /* build CTable for Literal Lengths */
2450     {   unsigned max = MaxLL;
2451         size_t const mostFrequent = HIST_countFast_wksp(countWorkspace, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2452         DEBUGLOG(5, "Building LL table");
2453         nextEntropy->litlength_repeatMode = prevEntropy->litlength_repeatMode;
2454         stats.LLtype = ZSTD_selectEncodingType(&nextEntropy->litlength_repeatMode,
2455                                         countWorkspace, max, mostFrequent, nbSeq,
2456                                         LLFSELog, prevEntropy->litlengthCTable,
2457                                         LL_defaultNorm, LL_defaultNormLog,
2458                                         ZSTD_defaultAllowed, strategy);
2459         assert(set_basic < set_compressed && set_rle < set_compressed);
2460         assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2461         {   size_t const countSize = ZSTD_buildCTable(
2462                 op, (size_t)(oend - op),
2463                 CTable_LitLength, LLFSELog, (symbolEncodingType_e)stats.LLtype,
2464                 countWorkspace, max, llCodeTable, nbSeq,
2465                 LL_defaultNorm, LL_defaultNormLog, MaxLL,
2466                 prevEntropy->litlengthCTable,
2467                 sizeof(prevEntropy->litlengthCTable),
2468                 entropyWorkspace, entropyWkspSize);
2469             if (ZSTD_isError(countSize)) {
2470                 DEBUGLOG(3, "ZSTD_buildCTable for LitLens failed");
2471                 stats.size = countSize;
2472                 return stats;
2473             }
2474             if (stats.LLtype == set_compressed)
2475                 stats.lastCountSize = countSize;
2476             op += countSize;
2477             assert(op <= oend);
2478     }   }
2479     /* build CTable for Offsets */
2480     {   unsigned max = MaxOff;
2481         size_t const mostFrequent = HIST_countFast_wksp(
2482             countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);  /* can't fail */
2483         /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
2484         ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
2485         DEBUGLOG(5, "Building OF table");
2486         nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode;
2487         stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode,
2488                                         countWorkspace, max, mostFrequent, nbSeq,
2489                                         OffFSELog, prevEntropy->offcodeCTable,
2490                                         OF_defaultNorm, OF_defaultNormLog,
2491                                         defaultPolicy, strategy);
2492         assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2493         {   size_t const countSize = ZSTD_buildCTable(
2494                 op, (size_t)(oend - op),
2495                 CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)stats.Offtype,
2496                 countWorkspace, max, ofCodeTable, nbSeq,
2497                 OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
2498                 prevEntropy->offcodeCTable,
2499                 sizeof(prevEntropy->offcodeCTable),
2500                 entropyWorkspace, entropyWkspSize);
2501             if (ZSTD_isError(countSize)) {
2502                 DEBUGLOG(3, "ZSTD_buildCTable for Offsets failed");
2503                 stats.size = countSize;
2504                 return stats;
2505             }
2506             if (stats.Offtype == set_compressed)
2507                 stats.lastCountSize = countSize;
2508             op += countSize;
2509             assert(op <= oend);
2510     }   }
2511     /* build CTable for MatchLengths */
2512     {   unsigned max = MaxML;
2513         size_t const mostFrequent = HIST_countFast_wksp(
2514             countWorkspace, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2515         DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
2516         nextEntropy->matchlength_repeatMode = prevEntropy->matchlength_repeatMode;
2517         stats.MLtype = ZSTD_selectEncodingType(&nextEntropy->matchlength_repeatMode,
2518                                         countWorkspace, max, mostFrequent, nbSeq,
2519                                         MLFSELog, prevEntropy->matchlengthCTable,
2520                                         ML_defaultNorm, ML_defaultNormLog,
2521                                         ZSTD_defaultAllowed, strategy);
2522         assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2523         {   size_t const countSize = ZSTD_buildCTable(
2524                 op, (size_t)(oend - op),
2525                 CTable_MatchLength, MLFSELog, (symbolEncodingType_e)stats.MLtype,
2526                 countWorkspace, max, mlCodeTable, nbSeq,
2527                 ML_defaultNorm, ML_defaultNormLog, MaxML,
2528                 prevEntropy->matchlengthCTable,
2529                 sizeof(prevEntropy->matchlengthCTable),
2530                 entropyWorkspace, entropyWkspSize);
2531             if (ZSTD_isError(countSize)) {
2532                 DEBUGLOG(3, "ZSTD_buildCTable for MatchLengths failed");
2533                 stats.size = countSize;
2534                 return stats;
2535             }
2536             if (stats.MLtype == set_compressed)
2537                 stats.lastCountSize = countSize;
2538             op += countSize;
2539             assert(op <= oend);
2540     }   }
2541     stats.size = (size_t)(op-ostart);
2542     return stats;
2543 }
2544 
2545 /* ZSTD_entropyCompressSeqStore_internal():
2546  * compresses both literals and sequences
2547  * Returns compressed size of block, or a zstd error.
2548  */
2549 MEM_STATIC size_t
ZSTD_entropyCompressSeqStore_internal(seqStore_t * seqStorePtr,const ZSTD_entropyCTables_t * prevEntropy,ZSTD_entropyCTables_t * nextEntropy,const ZSTD_CCtx_params * cctxParams,void * dst,size_t dstCapacity,void * entropyWorkspace,size_t entropyWkspSize,const int bmi2)2550 ZSTD_entropyCompressSeqStore_internal(seqStore_t* seqStorePtr,
2551                           const ZSTD_entropyCTables_t* prevEntropy,
2552                                 ZSTD_entropyCTables_t* nextEntropy,
2553                           const ZSTD_CCtx_params* cctxParams,
2554                                 void* dst, size_t dstCapacity,
2555                                 void* entropyWorkspace, size_t entropyWkspSize,
2556                           const int bmi2)
2557 {
2558     const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
2559     ZSTD_strategy const strategy = cctxParams->cParams.strategy;
2560     unsigned* count = (unsigned*)entropyWorkspace;
2561     FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
2562     FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
2563     FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
2564     const seqDef* const sequences = seqStorePtr->sequencesStart;
2565     const size_t nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
2566     const BYTE* const ofCodeTable = seqStorePtr->ofCode;
2567     const BYTE* const llCodeTable = seqStorePtr->llCode;
2568     const BYTE* const mlCodeTable = seqStorePtr->mlCode;
2569     BYTE* const ostart = (BYTE*)dst;
2570     BYTE* const oend = ostart + dstCapacity;
2571     BYTE* op = ostart;
2572     size_t lastCountSize;
2573 
2574     entropyWorkspace = count + (MaxSeq + 1);
2575     entropyWkspSize -= (MaxSeq + 1) * sizeof(*count);
2576 
2577     DEBUGLOG(4, "ZSTD_entropyCompressSeqStore_internal (nbSeq=%zu)", nbSeq);
2578     ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
2579     assert(entropyWkspSize >= HUF_WORKSPACE_SIZE);
2580 
2581     /* Compress literals */
2582     {   const BYTE* const literals = seqStorePtr->litStart;
2583         size_t const litSize = (size_t)(seqStorePtr->lit - literals);
2584         size_t const cSize = ZSTD_compressLiterals(
2585                                     &prevEntropy->huf, &nextEntropy->huf,
2586                                     cctxParams->cParams.strategy,
2587                                     ZSTD_disableLiteralsCompression(cctxParams),
2588                                     op, dstCapacity,
2589                                     literals, litSize,
2590                                     entropyWorkspace, entropyWkspSize,
2591                                     bmi2);
2592         FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");
2593         assert(cSize <= dstCapacity);
2594         op += cSize;
2595     }
2596 
2597     /* Sequences Header */
2598     RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
2599                     dstSize_tooSmall, "Can't fit seq hdr in output buf!");
2600     if (nbSeq < 128) {
2601         *op++ = (BYTE)nbSeq;
2602     } else if (nbSeq < LONGNBSEQ) {
2603         op[0] = (BYTE)((nbSeq>>8) + 0x80);
2604         op[1] = (BYTE)nbSeq;
2605         op+=2;
2606     } else {
2607         op[0]=0xFF;
2608         MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));
2609         op+=3;
2610     }
2611     assert(op <= oend);
2612     if (nbSeq==0) {
2613         /* Copy the old tables over as if we repeated them */
2614         ZSTD_memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
2615         return (size_t)(op - ostart);
2616     }
2617     {
2618         ZSTD_symbolEncodingTypeStats_t stats;
2619         BYTE* seqHead = op++;
2620         /* build stats for sequences */
2621         stats = ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
2622                                              &prevEntropy->fse, &nextEntropy->fse,
2623                                               op, oend,
2624                                               strategy, count,
2625                                               entropyWorkspace, entropyWkspSize);
2626         FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
2627         *seqHead = (BYTE)((stats.LLtype<<6) + (stats.Offtype<<4) + (stats.MLtype<<2));
2628         lastCountSize = stats.lastCountSize;
2629         op += stats.size;
2630     }
2631 
2632     {   size_t const bitstreamSize = ZSTD_encodeSequences(
2633                                         op, (size_t)(oend - op),
2634                                         CTable_MatchLength, mlCodeTable,
2635                                         CTable_OffsetBits, ofCodeTable,
2636                                         CTable_LitLength, llCodeTable,
2637                                         sequences, nbSeq,
2638                                         longOffsets, bmi2);
2639         FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
2640         op += bitstreamSize;
2641         assert(op <= oend);
2642         /* zstd versions <= 1.3.4 mistakenly report corruption when
2643          * FSE_readNCount() receives a buffer < 4 bytes.
2644          * Fixed by https://github.com/facebook/zstd/pull/1146.
2645          * This can happen when the last set_compressed table present is 2
2646          * bytes and the bitstream is only one byte.
2647          * In this exceedingly rare case, we will simply emit an uncompressed
2648          * block, since it isn't worth optimizing.
2649          */
2650         if (lastCountSize && (lastCountSize + bitstreamSize) < 4) {
2651             /* lastCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
2652             assert(lastCountSize + bitstreamSize == 3);
2653             DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
2654                         "emitting an uncompressed block.");
2655             return 0;
2656         }
2657     }
2658 
2659     DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
2660     return (size_t)(op - ostart);
2661 }
2662 
2663 MEM_STATIC size_t
ZSTD_entropyCompressSeqStore(seqStore_t * seqStorePtr,const ZSTD_entropyCTables_t * prevEntropy,ZSTD_entropyCTables_t * nextEntropy,const ZSTD_CCtx_params * cctxParams,void * dst,size_t dstCapacity,size_t srcSize,void * entropyWorkspace,size_t entropyWkspSize,int bmi2)2664 ZSTD_entropyCompressSeqStore(seqStore_t* seqStorePtr,
2665                        const ZSTD_entropyCTables_t* prevEntropy,
2666                              ZSTD_entropyCTables_t* nextEntropy,
2667                        const ZSTD_CCtx_params* cctxParams,
2668                              void* dst, size_t dstCapacity,
2669                              size_t srcSize,
2670                              void* entropyWorkspace, size_t entropyWkspSize,
2671                              int bmi2)
2672 {
2673     size_t const cSize = ZSTD_entropyCompressSeqStore_internal(
2674                             seqStorePtr, prevEntropy, nextEntropy, cctxParams,
2675                             dst, dstCapacity,
2676                             entropyWorkspace, entropyWkspSize, bmi2);
2677     if (cSize == 0) return 0;
2678     /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
2679      * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
2680      */
2681     if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity))
2682         return 0;  /* block not compressed */
2683     FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed");
2684 
2685     /* Check compressibility */
2686     {   size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy);
2687         if (cSize >= maxCSize) return 0;  /* block not compressed */
2688     }
2689     DEBUGLOG(4, "ZSTD_entropyCompressSeqStore() cSize: %zu", cSize);
2690     return cSize;
2691 }
2692 
2693 /* ZSTD_selectBlockCompressor() :
2694  * Not static, but internal use only (used by long distance matcher)
2695  * assumption : strat is a valid strategy */
ZSTD_selectBlockCompressor(ZSTD_strategy strat,ZSTD_useRowMatchFinderMode_e useRowMatchFinder,ZSTD_dictMode_e dictMode)2696 ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_useRowMatchFinderMode_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
2697 {
2698     static const ZSTD_blockCompressor blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
2699         { ZSTD_compressBlock_fast  /* default for 0 */,
2700           ZSTD_compressBlock_fast,
2701           ZSTD_compressBlock_doubleFast,
2702           ZSTD_compressBlock_greedy,
2703           ZSTD_compressBlock_lazy,
2704           ZSTD_compressBlock_lazy2,
2705           ZSTD_compressBlock_btlazy2,
2706           ZSTD_compressBlock_btopt,
2707           ZSTD_compressBlock_btultra,
2708           ZSTD_compressBlock_btultra2 },
2709         { ZSTD_compressBlock_fast_extDict  /* default for 0 */,
2710           ZSTD_compressBlock_fast_extDict,
2711           ZSTD_compressBlock_doubleFast_extDict,
2712           ZSTD_compressBlock_greedy_extDict,
2713           ZSTD_compressBlock_lazy_extDict,
2714           ZSTD_compressBlock_lazy2_extDict,
2715           ZSTD_compressBlock_btlazy2_extDict,
2716           ZSTD_compressBlock_btopt_extDict,
2717           ZSTD_compressBlock_btultra_extDict,
2718           ZSTD_compressBlock_btultra_extDict },
2719         { ZSTD_compressBlock_fast_dictMatchState  /* default for 0 */,
2720           ZSTD_compressBlock_fast_dictMatchState,
2721           ZSTD_compressBlock_doubleFast_dictMatchState,
2722           ZSTD_compressBlock_greedy_dictMatchState,
2723           ZSTD_compressBlock_lazy_dictMatchState,
2724           ZSTD_compressBlock_lazy2_dictMatchState,
2725           ZSTD_compressBlock_btlazy2_dictMatchState,
2726           ZSTD_compressBlock_btopt_dictMatchState,
2727           ZSTD_compressBlock_btultra_dictMatchState,
2728           ZSTD_compressBlock_btultra_dictMatchState },
2729         { NULL  /* default for 0 */,
2730           NULL,
2731           NULL,
2732           ZSTD_compressBlock_greedy_dedicatedDictSearch,
2733           ZSTD_compressBlock_lazy_dedicatedDictSearch,
2734           ZSTD_compressBlock_lazy2_dedicatedDictSearch,
2735           NULL,
2736           NULL,
2737           NULL,
2738           NULL }
2739     };
2740     ZSTD_blockCompressor selectedCompressor;
2741     ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
2742 
2743     assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
2744     DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);
2745     if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) {
2746         static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = {
2747             { ZSTD_compressBlock_greedy_row,
2748             ZSTD_compressBlock_lazy_row,
2749             ZSTD_compressBlock_lazy2_row },
2750             { ZSTD_compressBlock_greedy_extDict_row,
2751             ZSTD_compressBlock_lazy_extDict_row,
2752             ZSTD_compressBlock_lazy2_extDict_row },
2753             { ZSTD_compressBlock_greedy_dictMatchState_row,
2754             ZSTD_compressBlock_lazy_dictMatchState_row,
2755             ZSTD_compressBlock_lazy2_dictMatchState_row },
2756             { ZSTD_compressBlock_greedy_dedicatedDictSearch_row,
2757             ZSTD_compressBlock_lazy_dedicatedDictSearch_row,
2758             ZSTD_compressBlock_lazy2_dedicatedDictSearch_row }
2759         };
2760         DEBUGLOG(4, "Selecting a row-based matchfinder");
2761         assert(useRowMatchFinder != ZSTD_urm_auto);
2762         selectedCompressor = rowBasedBlockCompressors[(int)dictMode][(int)strat - (int)ZSTD_greedy];
2763     } else {
2764         selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
2765     }
2766     assert(selectedCompressor != NULL);
2767     return selectedCompressor;
2768 }
2769 
ZSTD_storeLastLiterals(seqStore_t * seqStorePtr,const BYTE * anchor,size_t lastLLSize)2770 static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
2771                                    const BYTE* anchor, size_t lastLLSize)
2772 {
2773     ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize);
2774     seqStorePtr->lit += lastLLSize;
2775 }
2776 
ZSTD_resetSeqStore(seqStore_t * ssPtr)2777 void ZSTD_resetSeqStore(seqStore_t* ssPtr)
2778 {
2779     ssPtr->lit = ssPtr->litStart;
2780     ssPtr->sequences = ssPtr->sequencesStart;
2781     ssPtr->longLengthType = ZSTD_llt_none;
2782 }
2783 
2784 typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_buildSeqStore_e;
2785 
ZSTD_buildSeqStore(ZSTD_CCtx * zc,const void * src,size_t srcSize)2786 static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
2787 {
2788     ZSTD_matchState_t* const ms = &zc->blockState.matchState;
2789     DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
2790     assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
2791     /* Assert that we have correctly flushed the ctx params into the ms's copy */
2792     ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
2793     if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
2794         if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
2795             ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
2796         } else {
2797             ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
2798         }
2799         return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
2800     }
2801     ZSTD_resetSeqStore(&(zc->seqStore));
2802     /* required for optimal parser to read stats from dictionary */
2803     ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
2804     /* tell the optimal parser how we expect to compress literals */
2805     ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
2806     /* a gap between an attached dict and the current window is not safe,
2807      * they must remain adjacent,
2808      * and when that stops being the case, the dict must be unset */
2809     assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
2810 
2811     /* limited update after a very long match */
2812     {   const BYTE* const base = ms->window.base;
2813         const BYTE* const istart = (const BYTE*)src;
2814         const U32 curr = (U32)(istart-base);
2815         if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1));   /* ensure no overflow */
2816         if (curr > ms->nextToUpdate + 384)
2817             ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
2818     }
2819 
2820     /* select and store sequences */
2821     {   ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
2822         size_t lastLLSize;
2823         {   int i;
2824             for (i = 0; i < ZSTD_REP_NUM; ++i)
2825                 zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
2826         }
2827         if (zc->externSeqStore.pos < zc->externSeqStore.size) {
2828             assert(!zc->appliedParams.ldmParams.enableLdm);
2829             /* Updates ldmSeqStore.pos */
2830             lastLLSize =
2831                 ZSTD_ldm_blockCompress(&zc->externSeqStore,
2832                                        ms, &zc->seqStore,
2833                                        zc->blockState.nextCBlock->rep,
2834                                        zc->appliedParams.useRowMatchFinder,
2835                                        src, srcSize);
2836             assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
2837         } else if (zc->appliedParams.ldmParams.enableLdm) {
2838             rawSeqStore_t ldmSeqStore = kNullRawSeqStore;
2839 
2840             ldmSeqStore.seq = zc->ldmSequences;
2841             ldmSeqStore.capacity = zc->maxNbLdmSequences;
2842             /* Updates ldmSeqStore.size */
2843             FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
2844                                                &zc->appliedParams.ldmParams,
2845                                                src, srcSize), "");
2846             /* Updates ldmSeqStore.pos */
2847             lastLLSize =
2848                 ZSTD_ldm_blockCompress(&ldmSeqStore,
2849                                        ms, &zc->seqStore,
2850                                        zc->blockState.nextCBlock->rep,
2851                                        zc->appliedParams.useRowMatchFinder,
2852                                        src, srcSize);
2853             assert(ldmSeqStore.pos == ldmSeqStore.size);
2854         } else {   /* not long range mode */
2855             ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy,
2856                                                                                     zc->appliedParams.useRowMatchFinder,
2857                                                                                     dictMode);
2858             ms->ldmSeqStore = NULL;
2859             lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
2860         }
2861         {   const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
2862             ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
2863     }   }
2864     return ZSTDbss_compress;
2865 }
2866 
ZSTD_copyBlockSequences(ZSTD_CCtx * zc)2867 static void ZSTD_copyBlockSequences(ZSTD_CCtx* zc)
2868 {
2869     const seqStore_t* seqStore = ZSTD_getSeqStore(zc);
2870     const seqDef* seqStoreSeqs = seqStore->sequencesStart;
2871     size_t seqStoreSeqSize = seqStore->sequences - seqStoreSeqs;
2872     size_t seqStoreLiteralsSize = (size_t)(seqStore->lit - seqStore->litStart);
2873     size_t literalsRead = 0;
2874     size_t lastLLSize;
2875 
2876     ZSTD_Sequence* outSeqs = &zc->seqCollector.seqStart[zc->seqCollector.seqIndex];
2877     size_t i;
2878     repcodes_t updatedRepcodes;
2879 
2880     assert(zc->seqCollector.seqIndex + 1 < zc->seqCollector.maxSequences);
2881     /* Ensure we have enough space for last literals "sequence" */
2882     assert(zc->seqCollector.maxSequences >= seqStoreSeqSize + 1);
2883     ZSTD_memcpy(updatedRepcodes.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
2884     for (i = 0; i < seqStoreSeqSize; ++i) {
2885         U32 rawOffset = seqStoreSeqs[i].offset - ZSTD_REP_NUM;
2886         outSeqs[i].litLength = seqStoreSeqs[i].litLength;
2887         outSeqs[i].matchLength = seqStoreSeqs[i].matchLength + MINMATCH;
2888         outSeqs[i].rep = 0;
2889 
2890         if (i == seqStore->longLengthPos) {
2891             if (seqStore->longLengthType == ZSTD_llt_literalLength) {
2892                 outSeqs[i].litLength += 0x10000;
2893             } else if (seqStore->longLengthType == ZSTD_llt_matchLength) {
2894                 outSeqs[i].matchLength += 0x10000;
2895             }
2896         }
2897 
2898         if (seqStoreSeqs[i].offset <= ZSTD_REP_NUM) {
2899             /* Derive the correct offset corresponding to a repcode */
2900             outSeqs[i].rep = seqStoreSeqs[i].offset;
2901             if (outSeqs[i].litLength != 0) {
2902                 rawOffset = updatedRepcodes.rep[outSeqs[i].rep - 1];
2903             } else {
2904                 if (outSeqs[i].rep == 3) {
2905                     rawOffset = updatedRepcodes.rep[0] - 1;
2906                 } else {
2907                     rawOffset = updatedRepcodes.rep[outSeqs[i].rep];
2908                 }
2909             }
2910         }
2911         outSeqs[i].offset = rawOffset;
2912         /* seqStoreSeqs[i].offset == offCode+1, and ZSTD_updateRep() expects offCode
2913            so we provide seqStoreSeqs[i].offset - 1 */
2914         updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep,
2915                                          seqStoreSeqs[i].offset - 1,
2916                                          seqStoreSeqs[i].litLength == 0);
2917         literalsRead += outSeqs[i].litLength;
2918     }
2919     /* Insert last literals (if any exist) in the block as a sequence with ml == off == 0.
2920      * If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker
2921      * for the block boundary, according to the API.
2922      */
2923     assert(seqStoreLiteralsSize >= literalsRead);
2924     lastLLSize = seqStoreLiteralsSize - literalsRead;
2925     outSeqs[i].litLength = (U32)lastLLSize;
2926     outSeqs[i].matchLength = outSeqs[i].offset = outSeqs[i].rep = 0;
2927     seqStoreSeqSize++;
2928     zc->seqCollector.seqIndex += seqStoreSeqSize;
2929 }
2930 
ZSTD_generateSequences(ZSTD_CCtx * zc,ZSTD_Sequence * outSeqs,size_t outSeqsSize,const void * src,size_t srcSize)2931 size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
2932                               size_t outSeqsSize, const void* src, size_t srcSize)
2933 {
2934     const size_t dstCapacity = ZSTD_compressBound(srcSize);
2935     void* dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem);
2936     SeqCollector seqCollector;
2937 
2938     RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");
2939 
2940     seqCollector.collectSequences = 1;
2941     seqCollector.seqStart = outSeqs;
2942     seqCollector.seqIndex = 0;
2943     seqCollector.maxSequences = outSeqsSize;
2944     zc->seqCollector = seqCollector;
2945 
2946     ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
2947     ZSTD_customFree(dst, ZSTD_defaultCMem);
2948     return zc->seqCollector.seqIndex;
2949 }
2950 
ZSTD_mergeBlockDelimiters(ZSTD_Sequence * sequences,size_t seqsSize)2951 size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize) {
2952     size_t in = 0;
2953     size_t out = 0;
2954     for (; in < seqsSize; ++in) {
2955         if (sequences[in].offset == 0 && sequences[in].matchLength == 0) {
2956             if (in != seqsSize - 1) {
2957                 sequences[in+1].litLength += sequences[in].litLength;
2958             }
2959         } else {
2960             sequences[out] = sequences[in];
2961             ++out;
2962         }
2963     }
2964     return out;
2965 }
2966 
2967 /* Unrolled loop to read four size_ts of input at a time. Returns 1 if is RLE, 0 if not. */
ZSTD_isRLE(const BYTE * src,size_t length)2968 static int ZSTD_isRLE(const BYTE* src, size_t length) {
2969     const BYTE* ip = src;
2970     const BYTE value = ip[0];
2971     const size_t valueST = (size_t)((U64)value * 0x0101010101010101ULL);
2972     const size_t unrollSize = sizeof(size_t) * 4;
2973     const size_t unrollMask = unrollSize - 1;
2974     const size_t prefixLength = length & unrollMask;
2975     size_t i;
2976     size_t u;
2977     if (length == 1) return 1;
2978     /* Check if prefix is RLE first before using unrolled loop */
2979     if (prefixLength && ZSTD_count(ip+1, ip, ip+prefixLength) != prefixLength-1) {
2980         return 0;
2981     }
2982     for (i = prefixLength; i != length; i += unrollSize) {
2983         for (u = 0; u < unrollSize; u += sizeof(size_t)) {
2984             if (MEM_readST(ip + i + u) != valueST) {
2985                 return 0;
2986             }
2987         }
2988     }
2989     return 1;
2990 }
2991 
2992 /* Returns true if the given block may be RLE.
2993  * This is just a heuristic based on the compressibility.
2994  * It may return both false positives and false negatives.
2995  */
ZSTD_maybeRLE(seqStore_t const * seqStore)2996 static int ZSTD_maybeRLE(seqStore_t const* seqStore)
2997 {
2998     size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
2999     size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart);
3000 
3001     return nbSeqs < 4 && nbLits < 10;
3002 }
3003 
ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t * const bs)3004 static void ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t* const bs)
3005 {
3006     ZSTD_compressedBlockState_t* const tmp = bs->prevCBlock;
3007     bs->prevCBlock = bs->nextCBlock;
3008     bs->nextCBlock = tmp;
3009 }
3010 
3011 /* Writes the block header */
writeBlockHeader(void * op,size_t cSize,size_t blockSize,U32 lastBlock)3012 static void writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock) {
3013     U32 const cBlockHeader = cSize == 1 ?
3014                         lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
3015                         lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
3016     MEM_writeLE24(op, cBlockHeader);
3017     DEBUGLOG(3, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock);
3018 }
3019 
3020 /** ZSTD_buildBlockEntropyStats_literals() :
3021  *  Builds entropy for the literals.
3022  *  Stores literals block type (raw, rle, compressed, repeat) and
3023  *  huffman description table to hufMetadata.
3024  *  Requires ENTROPY_WORKSPACE_SIZE workspace
3025  *  @return : size of huffman description table or error code */
ZSTD_buildBlockEntropyStats_literals(void * const src,size_t srcSize,const ZSTD_hufCTables_t * prevHuf,ZSTD_hufCTables_t * nextHuf,ZSTD_hufCTablesMetadata_t * hufMetadata,const int disableLiteralsCompression,void * workspace,size_t wkspSize)3026 static size_t ZSTD_buildBlockEntropyStats_literals(void* const src, size_t srcSize,
3027                                             const ZSTD_hufCTables_t* prevHuf,
3028                                                   ZSTD_hufCTables_t* nextHuf,
3029                                                   ZSTD_hufCTablesMetadata_t* hufMetadata,
3030                                                   const int disableLiteralsCompression,
3031                                                   void* workspace, size_t wkspSize)
3032 {
3033     BYTE* const wkspStart = (BYTE*)workspace;
3034     BYTE* const wkspEnd = wkspStart + wkspSize;
3035     BYTE* const countWkspStart = wkspStart;
3036     unsigned* const countWksp = (unsigned*)workspace;
3037     const size_t countWkspSize = (HUF_SYMBOLVALUE_MAX + 1) * sizeof(unsigned);
3038     BYTE* const nodeWksp = countWkspStart + countWkspSize;
3039     const size_t nodeWkspSize = wkspEnd-nodeWksp;
3040     unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
3041     unsigned huffLog = HUF_TABLELOG_DEFAULT;
3042     HUF_repeat repeat = prevHuf->repeatMode;
3043     DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_literals (srcSize=%zu)", srcSize);
3044 
3045     /* Prepare nextEntropy assuming reusing the existing table */
3046     ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3047 
3048     if (disableLiteralsCompression) {
3049         DEBUGLOG(5, "set_basic - disabled");
3050         hufMetadata->hType = set_basic;
3051         return 0;
3052     }
3053 
3054     /* small ? don't even attempt compression (speed opt) */
3055 #ifndef COMPRESS_LITERALS_SIZE_MIN
3056 #define COMPRESS_LITERALS_SIZE_MIN 63
3057 #endif
3058     {   size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
3059         if (srcSize <= minLitSize) {
3060             DEBUGLOG(5, "set_basic - too small");
3061             hufMetadata->hType = set_basic;
3062             return 0;
3063         }
3064     }
3065 
3066     /* Scan input and build symbol stats */
3067     {   size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)src, srcSize, workspace, wkspSize);
3068         FORWARD_IF_ERROR(largest, "HIST_count_wksp failed");
3069         if (largest == srcSize) {
3070             DEBUGLOG(5, "set_rle");
3071             hufMetadata->hType = set_rle;
3072             return 0;
3073         }
3074         if (largest <= (srcSize >> 7)+4) {
3075             DEBUGLOG(5, "set_basic - no gain");
3076             hufMetadata->hType = set_basic;
3077             return 0;
3078         }
3079     }
3080 
3081     /* Validate the previous Huffman table */
3082     if (repeat == HUF_repeat_check && !HUF_validateCTable((HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue)) {
3083         repeat = HUF_repeat_none;
3084     }
3085 
3086     /* Build Huffman Tree */
3087     ZSTD_memset(nextHuf->CTable, 0, sizeof(nextHuf->CTable));
3088     huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue);
3089     {   size_t const maxBits = HUF_buildCTable_wksp((HUF_CElt*)nextHuf->CTable, countWksp,
3090                                                     maxSymbolValue, huffLog,
3091                                                     nodeWksp, nodeWkspSize);
3092         FORWARD_IF_ERROR(maxBits, "HUF_buildCTable_wksp");
3093         huffLog = (U32)maxBits;
3094         {   /* Build and write the CTable */
3095             size_t const newCSize = HUF_estimateCompressedSize(
3096                     (HUF_CElt*)nextHuf->CTable, countWksp, maxSymbolValue);
3097             size_t const hSize = HUF_writeCTable_wksp(
3098                     hufMetadata->hufDesBuffer, sizeof(hufMetadata->hufDesBuffer),
3099                     (HUF_CElt*)nextHuf->CTable, maxSymbolValue, huffLog,
3100                     nodeWksp, nodeWkspSize);
3101             /* Check against repeating the previous CTable */
3102             if (repeat != HUF_repeat_none) {
3103                 size_t const oldCSize = HUF_estimateCompressedSize(
3104                         (HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue);
3105                 if (oldCSize < srcSize && (oldCSize <= hSize + newCSize || hSize + 12 >= srcSize)) {
3106                     DEBUGLOG(5, "set_repeat - smaller");
3107                     ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3108                     hufMetadata->hType = set_repeat;
3109                     return 0;
3110                 }
3111             }
3112             if (newCSize + hSize >= srcSize) {
3113                 DEBUGLOG(5, "set_basic - no gains");
3114                 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3115                 hufMetadata->hType = set_basic;
3116                 return 0;
3117             }
3118             DEBUGLOG(5, "set_compressed (hSize=%u)", (U32)hSize);
3119             hufMetadata->hType = set_compressed;
3120             nextHuf->repeatMode = HUF_repeat_check;
3121             return hSize;
3122         }
3123     }
3124 }
3125 
3126 
3127 /* ZSTD_buildDummySequencesStatistics():
3128  * Returns a ZSTD_symbolEncodingTypeStats_t with all encoding types as set_basic,
3129  * and updates nextEntropy to the appropriate repeatMode.
3130  */
3131 static ZSTD_symbolEncodingTypeStats_t
ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t * nextEntropy)3132 ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t* nextEntropy) {
3133     ZSTD_symbolEncodingTypeStats_t stats = {set_basic, set_basic, set_basic, 0, 0};
3134     nextEntropy->litlength_repeatMode = FSE_repeat_none;
3135     nextEntropy->offcode_repeatMode = FSE_repeat_none;
3136     nextEntropy->matchlength_repeatMode = FSE_repeat_none;
3137     return stats;
3138 }
3139 
3140 /** ZSTD_buildBlockEntropyStats_sequences() :
3141  *  Builds entropy for the sequences.
3142  *  Stores symbol compression modes and fse table to fseMetadata.
3143  *  Requires ENTROPY_WORKSPACE_SIZE wksp.
3144  *  @return : size of fse tables or error code */
ZSTD_buildBlockEntropyStats_sequences(seqStore_t * seqStorePtr,const ZSTD_fseCTables_t * prevEntropy,ZSTD_fseCTables_t * nextEntropy,const ZSTD_CCtx_params * cctxParams,ZSTD_fseCTablesMetadata_t * fseMetadata,void * workspace,size_t wkspSize)3145 static size_t ZSTD_buildBlockEntropyStats_sequences(seqStore_t* seqStorePtr,
3146                                               const ZSTD_fseCTables_t* prevEntropy,
3147                                                     ZSTD_fseCTables_t* nextEntropy,
3148                                               const ZSTD_CCtx_params* cctxParams,
3149                                                     ZSTD_fseCTablesMetadata_t* fseMetadata,
3150                                                     void* workspace, size_t wkspSize)
3151 {
3152     ZSTD_strategy const strategy = cctxParams->cParams.strategy;
3153     size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
3154     BYTE* const ostart = fseMetadata->fseTablesBuffer;
3155     BYTE* const oend = ostart + sizeof(fseMetadata->fseTablesBuffer);
3156     BYTE* op = ostart;
3157     unsigned* countWorkspace = (unsigned*)workspace;
3158     unsigned* entropyWorkspace = countWorkspace + (MaxSeq + 1);
3159     size_t entropyWorkspaceSize = wkspSize - (MaxSeq + 1) * sizeof(*countWorkspace);
3160     ZSTD_symbolEncodingTypeStats_t stats;
3161 
3162     DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_sequences (nbSeq=%zu)", nbSeq);
3163     stats = nbSeq != 0 ? ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
3164                                           prevEntropy, nextEntropy, op, oend,
3165                                           strategy, countWorkspace,
3166                                           entropyWorkspace, entropyWorkspaceSize)
3167                        : ZSTD_buildDummySequencesStatistics(nextEntropy);
3168     FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
3169     fseMetadata->llType = (symbolEncodingType_e) stats.LLtype;
3170     fseMetadata->ofType = (symbolEncodingType_e) stats.Offtype;
3171     fseMetadata->mlType = (symbolEncodingType_e) stats.MLtype;
3172     fseMetadata->lastCountSize = stats.lastCountSize;
3173     return stats.size;
3174 }
3175 
3176 
3177 /** ZSTD_buildBlockEntropyStats() :
3178  *  Builds entropy for the block.
3179  *  Requires workspace size ENTROPY_WORKSPACE_SIZE
3180  *
3181  *  @return : 0 on success or error code
3182  */
ZSTD_buildBlockEntropyStats(seqStore_t * seqStorePtr,const ZSTD_entropyCTables_t * prevEntropy,ZSTD_entropyCTables_t * nextEntropy,const ZSTD_CCtx_params * cctxParams,ZSTD_entropyCTablesMetadata_t * entropyMetadata,void * workspace,size_t wkspSize)3183 size_t ZSTD_buildBlockEntropyStats(seqStore_t* seqStorePtr,
3184                              const ZSTD_entropyCTables_t* prevEntropy,
3185                                    ZSTD_entropyCTables_t* nextEntropy,
3186                              const ZSTD_CCtx_params* cctxParams,
3187                                    ZSTD_entropyCTablesMetadata_t* entropyMetadata,
3188                                    void* workspace, size_t wkspSize)
3189 {
3190     size_t const litSize = seqStorePtr->lit - seqStorePtr->litStart;
3191     entropyMetadata->hufMetadata.hufDesSize =
3192         ZSTD_buildBlockEntropyStats_literals(seqStorePtr->litStart, litSize,
3193                                             &prevEntropy->huf, &nextEntropy->huf,
3194                                             &entropyMetadata->hufMetadata,
3195                                             ZSTD_disableLiteralsCompression(cctxParams),
3196                                             workspace, wkspSize);
3197     FORWARD_IF_ERROR(entropyMetadata->hufMetadata.hufDesSize, "ZSTD_buildBlockEntropyStats_literals failed");
3198     entropyMetadata->fseMetadata.fseTablesSize =
3199         ZSTD_buildBlockEntropyStats_sequences(seqStorePtr,
3200                                               &prevEntropy->fse, &nextEntropy->fse,
3201                                               cctxParams,
3202                                               &entropyMetadata->fseMetadata,
3203                                               workspace, wkspSize);
3204     FORWARD_IF_ERROR(entropyMetadata->fseMetadata.fseTablesSize, "ZSTD_buildBlockEntropyStats_sequences failed");
3205     return 0;
3206 }
3207 
3208 /* Returns the size estimate for the literals section (header + content) of a block */
ZSTD_estimateBlockSize_literal(const BYTE * literals,size_t litSize,const ZSTD_hufCTables_t * huf,const ZSTD_hufCTablesMetadata_t * hufMetadata,void * workspace,size_t wkspSize,int writeEntropy)3209 static size_t ZSTD_estimateBlockSize_literal(const BYTE* literals, size_t litSize,
3210                                                 const ZSTD_hufCTables_t* huf,
3211                                                 const ZSTD_hufCTablesMetadata_t* hufMetadata,
3212                                                 void* workspace, size_t wkspSize,
3213                                                 int writeEntropy)
3214 {
3215     unsigned* const countWksp = (unsigned*)workspace;
3216     unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
3217     size_t literalSectionHeaderSize = 3 + (litSize >= 1 KB) + (litSize >= 16 KB);
3218     U32 singleStream = litSize < 256;
3219 
3220     if (hufMetadata->hType == set_basic) return litSize;
3221     else if (hufMetadata->hType == set_rle) return 1;
3222     else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
3223         size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
3224         if (ZSTD_isError(largest)) return litSize;
3225         {   size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
3226             if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
3227             if (!singleStream) cLitSizeEstimate += 6; /* multi-stream huffman uses 6-byte jump table */
3228             return cLitSizeEstimate + literalSectionHeaderSize;
3229     }   }
3230     assert(0); /* impossible */
3231     return 0;
3232 }
3233 
3234 /* Returns the size estimate for the FSE-compressed symbols (of, ml, ll) of a block */
ZSTD_estimateBlockSize_symbolType(symbolEncodingType_e type,const BYTE * codeTable,size_t nbSeq,unsigned maxCode,const FSE_CTable * fseCTable,const U32 * additionalBits,short const * defaultNorm,U32 defaultNormLog,U32 defaultMax,void * workspace,size_t wkspSize)3235 static size_t ZSTD_estimateBlockSize_symbolType(symbolEncodingType_e type,
3236                         const BYTE* codeTable, size_t nbSeq, unsigned maxCode,
3237                         const FSE_CTable* fseCTable,
3238                         const U32* additionalBits,
3239                         short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
3240                         void* workspace, size_t wkspSize)
3241 {
3242     unsigned* const countWksp = (unsigned*)workspace;
3243     const BYTE* ctp = codeTable;
3244     const BYTE* const ctStart = ctp;
3245     const BYTE* const ctEnd = ctStart + nbSeq;
3246     size_t cSymbolTypeSizeEstimateInBits = 0;
3247     unsigned max = maxCode;
3248 
3249     HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize);  /* can't fail */
3250     if (type == set_basic) {
3251         /* We selected this encoding type, so it must be valid. */
3252         assert(max <= defaultMax);
3253         (void)defaultMax;
3254         cSymbolTypeSizeEstimateInBits = ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);
3255     } else if (type == set_rle) {
3256         cSymbolTypeSizeEstimateInBits = 0;
3257     } else if (type == set_compressed || type == set_repeat) {
3258         cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
3259     }
3260     if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) {
3261         return nbSeq * 10;
3262     }
3263     while (ctp < ctEnd) {
3264         if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
3265         else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
3266         ctp++;
3267     }
3268     return cSymbolTypeSizeEstimateInBits >> 3;
3269 }
3270 
3271 /* Returns the size estimate for the sequences section (header + content) of a block */
ZSTD_estimateBlockSize_sequences(const BYTE * ofCodeTable,const BYTE * llCodeTable,const BYTE * mlCodeTable,size_t nbSeq,const ZSTD_fseCTables_t * fseTables,const ZSTD_fseCTablesMetadata_t * fseMetadata,void * workspace,size_t wkspSize,int writeEntropy)3272 static size_t ZSTD_estimateBlockSize_sequences(const BYTE* ofCodeTable,
3273                                                   const BYTE* llCodeTable,
3274                                                   const BYTE* mlCodeTable,
3275                                                   size_t nbSeq,
3276                                                   const ZSTD_fseCTables_t* fseTables,
3277                                                   const ZSTD_fseCTablesMetadata_t* fseMetadata,
3278                                                   void* workspace, size_t wkspSize,
3279                                                   int writeEntropy)
3280 {
3281     size_t sequencesSectionHeaderSize = 1 /* seqHead */ + 1 /* min seqSize size */ + (nbSeq >= 128) + (nbSeq >= LONGNBSEQ);
3282     size_t cSeqSizeEstimate = 0;
3283     cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, nbSeq, MaxOff,
3284                                          fseTables->offcodeCTable, NULL,
3285                                          OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
3286                                          workspace, wkspSize);
3287     cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->llType, llCodeTable, nbSeq, MaxLL,
3288                                          fseTables->litlengthCTable, LL_bits,
3289                                          LL_defaultNorm, LL_defaultNormLog, MaxLL,
3290                                          workspace, wkspSize);
3291     cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, nbSeq, MaxML,
3292                                          fseTables->matchlengthCTable, ML_bits,
3293                                          ML_defaultNorm, ML_defaultNormLog, MaxML,
3294                                          workspace, wkspSize);
3295     if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
3296     return cSeqSizeEstimate + sequencesSectionHeaderSize;
3297 }
3298 
3299 /* Returns the size estimate for a given stream of literals, of, ll, ml */
ZSTD_estimateBlockSize(const BYTE * literals,size_t litSize,const BYTE * ofCodeTable,const BYTE * llCodeTable,const BYTE * mlCodeTable,size_t nbSeq,const ZSTD_entropyCTables_t * entropy,const ZSTD_entropyCTablesMetadata_t * entropyMetadata,void * workspace,size_t wkspSize,int writeLitEntropy,int writeSeqEntropy)3300 static size_t ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize,
3301                                      const BYTE* ofCodeTable,
3302                                      const BYTE* llCodeTable,
3303                                      const BYTE* mlCodeTable,
3304                                      size_t nbSeq,
3305                                      const ZSTD_entropyCTables_t* entropy,
3306                                      const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
3307                                      void* workspace, size_t wkspSize,
3308                                      int writeLitEntropy, int writeSeqEntropy) {
3309     size_t const literalsSize = ZSTD_estimateBlockSize_literal(literals, litSize,
3310                                                          &entropy->huf, &entropyMetadata->hufMetadata,
3311                                                          workspace, wkspSize, writeLitEntropy);
3312     size_t const seqSize = ZSTD_estimateBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
3313                                                          nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
3314                                                          workspace, wkspSize, writeSeqEntropy);
3315     return seqSize + literalsSize + ZSTD_blockHeaderSize;
3316 }
3317 
3318 /* Builds entropy statistics and uses them for blocksize estimation.
3319  *
3320  * Returns the estimated compressed size of the seqStore, or a zstd error.
3321  */
ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(seqStore_t * seqStore,const ZSTD_CCtx * zc)3322 static size_t ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(seqStore_t* seqStore, const ZSTD_CCtx* zc) {
3323     ZSTD_entropyCTablesMetadata_t entropyMetadata;
3324     FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(seqStore,
3325                     &zc->blockState.prevCBlock->entropy,
3326                     &zc->blockState.nextCBlock->entropy,
3327                     &zc->appliedParams,
3328                     &entropyMetadata,
3329                     zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */), "");
3330     return ZSTD_estimateBlockSize(seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),
3331                     seqStore->ofCode, seqStore->llCode, seqStore->mlCode,
3332                     (size_t)(seqStore->sequences - seqStore->sequencesStart),
3333                     &zc->blockState.nextCBlock->entropy, &entropyMetadata, zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE,
3334                     (int)(entropyMetadata.hufMetadata.hType == set_compressed), 1);
3335 }
3336 
3337 /* Returns literals bytes represented in a seqStore */
ZSTD_countSeqStoreLiteralsBytes(const seqStore_t * const seqStore)3338 static size_t ZSTD_countSeqStoreLiteralsBytes(const seqStore_t* const seqStore) {
3339     size_t literalsBytes = 0;
3340     size_t const nbSeqs = seqStore->sequences - seqStore->sequencesStart;
3341     size_t i;
3342     for (i = 0; i < nbSeqs; ++i) {
3343         seqDef seq = seqStore->sequencesStart[i];
3344         literalsBytes += seq.litLength;
3345         if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_literalLength) {
3346             literalsBytes += 0x10000;
3347         }
3348     }
3349     return literalsBytes;
3350 }
3351 
3352 /* Returns match bytes represented in a seqStore */
ZSTD_countSeqStoreMatchBytes(const seqStore_t * const seqStore)3353 static size_t ZSTD_countSeqStoreMatchBytes(const seqStore_t* const seqStore) {
3354     size_t matchBytes = 0;
3355     size_t const nbSeqs = seqStore->sequences - seqStore->sequencesStart;
3356     size_t i;
3357     for (i = 0; i < nbSeqs; ++i) {
3358         seqDef seq = seqStore->sequencesStart[i];
3359         matchBytes += seq.matchLength + MINMATCH;
3360         if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_matchLength) {
3361             matchBytes += 0x10000;
3362         }
3363     }
3364     return matchBytes;
3365 }
3366 
3367 /* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).
3368  * Stores the result in resultSeqStore.
3369  */
ZSTD_deriveSeqStoreChunk(seqStore_t * resultSeqStore,const seqStore_t * originalSeqStore,size_t startIdx,size_t endIdx)3370 static void ZSTD_deriveSeqStoreChunk(seqStore_t* resultSeqStore,
3371                                const seqStore_t* originalSeqStore,
3372                                      size_t startIdx, size_t endIdx) {
3373     BYTE* const litEnd = originalSeqStore->lit;
3374     size_t literalsBytes;
3375     size_t literalsBytesPreceding = 0;
3376 
3377     *resultSeqStore = *originalSeqStore;
3378     if (startIdx > 0) {
3379         resultSeqStore->sequences = originalSeqStore->sequencesStart + startIdx;
3380         literalsBytesPreceding = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
3381     }
3382 
3383     /* Move longLengthPos into the correct position if necessary */
3384     if (originalSeqStore->longLengthType != ZSTD_llt_none) {
3385         if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {
3386             resultSeqStore->longLengthType = ZSTD_llt_none;
3387         } else {
3388             resultSeqStore->longLengthPos -= (U32)startIdx;
3389         }
3390     }
3391     resultSeqStore->sequencesStart = originalSeqStore->sequencesStart + startIdx;
3392     resultSeqStore->sequences = originalSeqStore->sequencesStart + endIdx;
3393     literalsBytes = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
3394     resultSeqStore->litStart += literalsBytesPreceding;
3395     if (endIdx == (size_t)(originalSeqStore->sequences - originalSeqStore->sequencesStart)) {
3396         /* This accounts for possible last literals if the derived chunk reaches the end of the block */
3397         resultSeqStore->lit = litEnd;
3398     } else {
3399         resultSeqStore->lit = resultSeqStore->litStart+literalsBytes;
3400     }
3401     resultSeqStore->llCode += startIdx;
3402     resultSeqStore->mlCode += startIdx;
3403     resultSeqStore->ofCode += startIdx;
3404 }
3405 
3406 /**
3407  * Returns the raw offset represented by the combination of offCode, ll0, and repcode history.
3408  * offCode must be an offCode representing a repcode, therefore in the range of [0, 2].
3409  */
ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM],const U32 offCode,const U32 ll0)3410 static U32 ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offCode, const U32 ll0) {
3411     U32 const adjustedOffCode = offCode + ll0;
3412     assert(offCode < ZSTD_REP_NUM);
3413     if (adjustedOffCode == ZSTD_REP_NUM) {
3414         /* litlength == 0 and offCode == 2 implies selection of first repcode - 1 */
3415         assert(rep[0] > 0);
3416         return rep[0] - 1;
3417     }
3418     return rep[adjustedOffCode];
3419 }
3420 
3421 /**
3422  * ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise
3423  * due to emission of RLE/raw blocks that disturb the offset history, and replaces any repcodes within
3424  * the seqStore that may be invalid.
3425  *
3426  * dRepcodes are updated as would be on the decompression side. cRepcodes are updated exactly in
3427  * accordance with the seqStore.
3428  */
ZSTD_seqStore_resolveOffCodes(repcodes_t * const dRepcodes,repcodes_t * const cRepcodes,seqStore_t * const seqStore,U32 const nbSeq)3429 static void ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRepcodes,
3430                                           seqStore_t* const seqStore, U32 const nbSeq) {
3431     U32 idx = 0;
3432     for (; idx < nbSeq; ++idx) {
3433         seqDef* const seq = seqStore->sequencesStart + idx;
3434         U32 const ll0 = (seq->litLength == 0);
3435         U32 offCode = seq->offset - 1;
3436         assert(seq->offset > 0);
3437         if (offCode <= ZSTD_REP_MOVE) {
3438             U32 const dRawOffset = ZSTD_resolveRepcodeToRawOffset(dRepcodes->rep, offCode, ll0);
3439             U32 const cRawOffset = ZSTD_resolveRepcodeToRawOffset(cRepcodes->rep, offCode, ll0);
3440             /* Adjust simulated decompression repcode history if we come across a mismatch. Replace
3441              * the repcode with the offset it actually references, determined by the compression
3442              * repcode history.
3443              */
3444             if (dRawOffset != cRawOffset) {
3445                 seq->offset = cRawOffset + ZSTD_REP_NUM;
3446             }
3447         }
3448         /* Compression repcode history is always updated with values directly from the unmodified seqStore.
3449          * Decompression repcode history may use modified seq->offset value taken from compression repcode history.
3450          */
3451         *dRepcodes = ZSTD_updateRep(dRepcodes->rep, seq->offset - 1, ll0);
3452         *cRepcodes = ZSTD_updateRep(cRepcodes->rep, offCode, ll0);
3453     }
3454 }
3455 
3456 /* ZSTD_compressSeqStore_singleBlock():
3457  * Compresses a seqStore into a block with a block header, into the buffer dst.
3458  *
3459  * Returns the total size of that block (including header) or a ZSTD error code.
3460  */
ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx * zc,seqStore_t * const seqStore,repcodes_t * const dRep,repcodes_t * const cRep,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastBlock,U32 isPartition)3461 static size_t ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, seqStore_t* const seqStore,
3462                                                 repcodes_t* const dRep, repcodes_t* const cRep,
3463                                                 void* dst, size_t dstCapacity,
3464                                                 const void* src, size_t srcSize,
3465                                                 U32 lastBlock, U32 isPartition) {
3466     const U32 rleMaxLength = 25;
3467     BYTE* op = (BYTE*)dst;
3468     const BYTE* ip = (const BYTE*)src;
3469     size_t cSize;
3470     size_t cSeqsSize;
3471 
3472     /* In case of an RLE or raw block, the simulated decompression repcode history must be reset */
3473     repcodes_t const dRepOriginal = *dRep;
3474     if (isPartition)
3475         ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));
3476 
3477     cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,
3478                 &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
3479                 &zc->appliedParams,
3480                 op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
3481                 srcSize,
3482                 zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
3483                 zc->bmi2);
3484     FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
3485 
3486     if (!zc->isFirstBlock &&
3487         cSeqsSize < rleMaxLength &&
3488         ZSTD_isRLE((BYTE const*)src, srcSize)) {
3489         /* We don't want to emit our first block as a RLE even if it qualifies because
3490         * doing so will cause the decoder (cli only) to throw a "should consume all input error."
3491         * This is only an issue for zstd <= v1.4.3
3492         */
3493         cSeqsSize = 1;
3494     }
3495 
3496     if (zc->seqCollector.collectSequences) {
3497         ZSTD_copyBlockSequences(zc);
3498         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
3499         return 0;
3500     }
3501 
3502     if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
3503         zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
3504 
3505     if (cSeqsSize == 0) {
3506         cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
3507         FORWARD_IF_ERROR(cSize, "Nocompress block failed");
3508         DEBUGLOG(4, "Writing out nocompress block, size: %zu", cSize);
3509         *dRep = dRepOriginal; /* reset simulated decompression repcode history */
3510     } else if (cSeqsSize == 1) {
3511         cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);
3512         FORWARD_IF_ERROR(cSize, "RLE compress block failed");
3513         DEBUGLOG(4, "Writing out RLE block, size: %zu", cSize);
3514         *dRep = dRepOriginal; /* reset simulated decompression repcode history */
3515     } else {
3516         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
3517         writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);
3518         cSize = ZSTD_blockHeaderSize + cSeqsSize;
3519         DEBUGLOG(4, "Writing out compressed block, size: %zu", cSize);
3520     }
3521     return cSize;
3522 }
3523 
3524 /* Struct to keep track of where we are in our recursive calls. */
3525 typedef struct {
3526     U32* splitLocations;    /* Array of split indices */
3527     size_t idx;             /* The current index within splitLocations being worked on */
3528 } seqStoreSplits;
3529 
3530 #define MIN_SEQUENCES_BLOCK_SPLITTING 300
3531 #define MAX_NB_SPLITS 196
3532 
3533 /* Helper function to perform the recursive search for block splits.
3534  * Estimates the cost of seqStore prior to split, and estimates the cost of splitting the sequences in half.
3535  * If advantageous to split, then we recurse down the two sub-blocks. If not, or if an error occurred in estimation, then
3536  * we do not recurse.
3537  *
3538  * Note: The recursion depth is capped by a heuristic minimum number of sequences, defined by MIN_SEQUENCES_BLOCK_SPLITTING.
3539  * In theory, this means the absolute largest recursion depth is 10 == log2(maxNbSeqInBlock/MIN_SEQUENCES_BLOCK_SPLITTING).
3540  * In practice, recursion depth usually doesn't go beyond 4.
3541  *
3542  * Furthermore, the number of splits is capped by MAX_NB_SPLITS. At MAX_NB_SPLITS == 196 with the current existing blockSize
3543  * maximum of 128 KB, this value is actually impossible to reach.
3544  */
ZSTD_deriveBlockSplitsHelper(seqStoreSplits * splits,size_t startIdx,size_t endIdx,const ZSTD_CCtx * zc,const seqStore_t * origSeqStore)3545 static void ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx,
3546                                          const ZSTD_CCtx* zc, const seqStore_t* origSeqStore) {
3547     seqStore_t fullSeqStoreChunk;
3548     seqStore_t firstHalfSeqStore;
3549     seqStore_t secondHalfSeqStore;
3550     size_t estimatedOriginalSize;
3551     size_t estimatedFirstHalfSize;
3552     size_t estimatedSecondHalfSize;
3553     size_t midIdx = (startIdx + endIdx)/2;
3554 
3555     if (endIdx - startIdx < MIN_SEQUENCES_BLOCK_SPLITTING || splits->idx >= MAX_NB_SPLITS) {
3556         return;
3557     }
3558     ZSTD_deriveSeqStoreChunk(&fullSeqStoreChunk, origSeqStore, startIdx, endIdx);
3559     ZSTD_deriveSeqStoreChunk(&firstHalfSeqStore, origSeqStore, startIdx, midIdx);
3560     ZSTD_deriveSeqStoreChunk(&secondHalfSeqStore, origSeqStore, midIdx, endIdx);
3561     estimatedOriginalSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&fullSeqStoreChunk, zc);
3562     estimatedFirstHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&firstHalfSeqStore, zc);
3563     estimatedSecondHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&secondHalfSeqStore, zc);
3564     DEBUGLOG(5, "Estimated original block size: %zu -- First half split: %zu -- Second half split: %zu",
3565              estimatedOriginalSize, estimatedFirstHalfSize, estimatedSecondHalfSize);
3566     if (ZSTD_isError(estimatedOriginalSize) || ZSTD_isError(estimatedFirstHalfSize) || ZSTD_isError(estimatedSecondHalfSize)) {
3567         return;
3568     }
3569     if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {
3570         ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);
3571         splits->splitLocations[splits->idx] = (U32)midIdx;
3572         splits->idx++;
3573         ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);
3574     }
3575 }
3576 
3577 /* Base recursive function. Populates a table with intra-block partition indices that can improve compression ratio.
3578  *
3579  * Returns the number of splits made (which equals the size of the partition table - 1).
3580  */
ZSTD_deriveBlockSplits(ZSTD_CCtx * zc,U32 partitions[],U32 nbSeq)3581 static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq) {
3582     seqStoreSplits splits = {partitions, 0};
3583     if (nbSeq <= 4) {
3584         DEBUGLOG(4, "ZSTD_deriveBlockSplits: Too few sequences to split");
3585         /* Refuse to try and split anything with less than 4 sequences */
3586         return 0;
3587     }
3588     ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore);
3589     splits.splitLocations[splits.idx] = nbSeq;
3590     DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1);
3591     return splits.idx;
3592 }
3593 
3594 /* ZSTD_compressBlock_splitBlock():
3595  * Attempts to split a given block into multiple blocks to improve compression ratio.
3596  *
3597  * Returns combined size of all blocks (which includes headers), or a ZSTD error code.
3598  */
ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t blockSize,U32 lastBlock,U32 nbSeq)3599 static size_t ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, void* dst, size_t dstCapacity,
3600                                                      const void* src, size_t blockSize, U32 lastBlock, U32 nbSeq) {
3601     size_t cSize = 0;
3602     const BYTE* ip = (const BYTE*)src;
3603     BYTE* op = (BYTE*)dst;
3604     U32 partitions[MAX_NB_SPLITS];
3605     size_t i = 0;
3606     size_t srcBytesTotal = 0;
3607     size_t numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
3608     seqStore_t nextSeqStore;
3609     seqStore_t currSeqStore;
3610 
3611     /* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history
3612      * may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two
3613      * separate repcode histories that simulate repcode history on compression and decompression side,
3614      * and use the histories to determine whether we must replace a particular repcode with its raw offset.
3615      *
3616      * 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed
3617      *    or RLE. This allows us to retrieve the offset value that an invalid repcode references within
3618      *    a nocompress/RLE block.
3619      * 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use
3620      *    the replacement offset value rather than the original repcode to update the repcode history.
3621      *    dRep also will be the final repcode history sent to the next block.
3622      *
3623      * See ZSTD_seqStore_resolveOffCodes() for more details.
3624      */
3625     repcodes_t dRep;
3626     repcodes_t cRep;
3627     ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
3628     ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t));
3629 
3630     DEBUGLOG(4, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
3631                 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
3632                 (unsigned)zc->blockState.matchState.nextToUpdate);
3633 
3634     if (numSplits == 0) {
3635         size_t cSizeSingleBlock = ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,
3636                                                                    &dRep, &cRep,
3637                                                                     op, dstCapacity,
3638                                                                     ip, blockSize,
3639                                                                     lastBlock, 0 /* isPartition */);
3640         FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");
3641         DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");
3642         assert(cSizeSingleBlock <= ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize);
3643         return cSizeSingleBlock;
3644     }
3645 
3646     ZSTD_deriveSeqStoreChunk(&currSeqStore, &zc->seqStore, 0, partitions[0]);
3647     for (i = 0; i <= numSplits; ++i) {
3648         size_t srcBytes;
3649         size_t cSizeChunk;
3650         U32 const lastPartition = (i == numSplits);
3651         U32 lastBlockEntireSrc = 0;
3652 
3653         srcBytes = ZSTD_countSeqStoreLiteralsBytes(&currSeqStore) + ZSTD_countSeqStoreMatchBytes(&currSeqStore);
3654         srcBytesTotal += srcBytes;
3655         if (lastPartition) {
3656             /* This is the final partition, need to account for possible last literals */
3657             srcBytes += blockSize - srcBytesTotal;
3658             lastBlockEntireSrc = lastBlock;
3659         } else {
3660             ZSTD_deriveSeqStoreChunk(&nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);
3661         }
3662 
3663         cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, &currSeqStore,
3664                                                       &dRep, &cRep,
3665                                                        op, dstCapacity,
3666                                                        ip, srcBytes,
3667                                                        lastBlockEntireSrc, 1 /* isPartition */);
3668         DEBUGLOG(5, "Estimated size: %zu actual size: %zu", ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(&currSeqStore, zc), cSizeChunk);
3669         FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");
3670 
3671         ip += srcBytes;
3672         op += cSizeChunk;
3673         dstCapacity -= cSizeChunk;
3674         cSize += cSizeChunk;
3675         currSeqStore = nextSeqStore;
3676         assert(cSizeChunk <= ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize);
3677     }
3678     /* cRep and dRep may have diverged during the compression. If so, we use the dRep repcodes
3679      * for the next block.
3680      */
3681     ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(repcodes_t));
3682     return cSize;
3683 }
3684 
ZSTD_compressBlock_splitBlock(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastBlock)3685 static size_t ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc,
3686                                         void* dst, size_t dstCapacity,
3687                                         const void* src, size_t srcSize, U32 lastBlock) {
3688     const BYTE* ip = (const BYTE*)src;
3689     BYTE* op = (BYTE*)dst;
3690     U32 nbSeq;
3691     size_t cSize;
3692     DEBUGLOG(4, "ZSTD_compressBlock_splitBlock");
3693 
3694     {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
3695         FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
3696         if (bss == ZSTDbss_noCompress) {
3697             if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
3698                 zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
3699             cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
3700             FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
3701             DEBUGLOG(4, "ZSTD_compressBlock_splitBlock: Nocompress block");
3702             return cSize;
3703         }
3704         nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);
3705     }
3706 
3707     assert(zc->appliedParams.splitBlocks == 1);
3708     cSize = ZSTD_compressBlock_splitBlock_internal(zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq);
3709     FORWARD_IF_ERROR(cSize, "Splitting blocks failed!");
3710     return cSize;
3711 }
3712 
ZSTD_compressBlock_internal(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 frame)3713 static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
3714                                         void* dst, size_t dstCapacity,
3715                                         const void* src, size_t srcSize, U32 frame)
3716 {
3717     /* This the upper bound for the length of an rle block.
3718      * This isn't the actual upper bound. Finding the real threshold
3719      * needs further investigation.
3720      */
3721     const U32 rleMaxLength = 25;
3722     size_t cSize;
3723     const BYTE* ip = (const BYTE*)src;
3724     BYTE* op = (BYTE*)dst;
3725     DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
3726                 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
3727                 (unsigned)zc->blockState.matchState.nextToUpdate);
3728 
3729     {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
3730         FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
3731         if (bss == ZSTDbss_noCompress) { cSize = 0; goto out; }
3732     }
3733 
3734     if (zc->seqCollector.collectSequences) {
3735         ZSTD_copyBlockSequences(zc);
3736         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
3737         return 0;
3738     }
3739 
3740     /* encode sequences and literals */
3741     cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,
3742             &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
3743             &zc->appliedParams,
3744             dst, dstCapacity,
3745             srcSize,
3746             zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
3747             zc->bmi2);
3748 
3749     if (zc->seqCollector.collectSequences) {
3750         ZSTD_copyBlockSequences(zc);
3751         return 0;
3752     }
3753 
3754 
3755     if (frame &&
3756         /* We don't want to emit our first block as a RLE even if it qualifies because
3757          * doing so will cause the decoder (cli only) to throw a "should consume all input error."
3758          * This is only an issue for zstd <= v1.4.3
3759          */
3760         !zc->isFirstBlock &&
3761         cSize < rleMaxLength &&
3762         ZSTD_isRLE(ip, srcSize))
3763     {
3764         cSize = 1;
3765         op[0] = ip[0];
3766     }
3767 
3768 out:
3769     if (!ZSTD_isError(cSize) && cSize > 1) {
3770         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
3771     }
3772     /* We check that dictionaries have offset codes available for the first
3773      * block. After the first block, the offcode table might not have large
3774      * enough codes to represent the offsets in the data.
3775      */
3776     if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
3777         zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
3778 
3779     return cSize;
3780 }
3781 
ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const size_t bss,U32 lastBlock)3782 static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,
3783                                void* dst, size_t dstCapacity,
3784                                const void* src, size_t srcSize,
3785                                const size_t bss, U32 lastBlock)
3786 {
3787     DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
3788     if (bss == ZSTDbss_compress) {
3789         if (/* We don't want to emit our first block as a RLE even if it qualifies because
3790             * doing so will cause the decoder (cli only) to throw a "should consume all input error."
3791             * This is only an issue for zstd <= v1.4.3
3792             */
3793             !zc->isFirstBlock &&
3794             ZSTD_maybeRLE(&zc->seqStore) &&
3795             ZSTD_isRLE((BYTE const*)src, srcSize))
3796         {
3797             return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
3798         }
3799         /* Attempt superblock compression.
3800          *
3801          * Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
3802          * standard ZSTD_compressBound(). This is a problem, because even if we have
3803          * space now, taking an extra byte now could cause us to run out of space later
3804          * and violate ZSTD_compressBound().
3805          *
3806          * Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
3807          *
3808          * In order to respect ZSTD_compressBound() we must attempt to emit a raw
3809          * uncompressed block in these cases:
3810          *   * cSize == 0: Return code for an uncompressed block.
3811          *   * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
3812          *     ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
3813          *     output space.
3814          *   * cSize >= blockBound(srcSize): We have expanded the block too much so
3815          *     emit an uncompressed block.
3816          */
3817         {
3818             size_t const cSize = ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
3819             if (cSize != ERROR(dstSize_tooSmall)) {
3820                 size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);
3821                 FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
3822                 if (cSize != 0 && cSize < maxCSize + ZSTD_blockHeaderSize) {
3823                     ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
3824                     return cSize;
3825                 }
3826             }
3827         }
3828     }
3829 
3830     DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");
3831     /* Superblock compression failed, attempt to emit a single no compress block.
3832      * The decoder will be able to stream this block since it is uncompressed.
3833      */
3834     return ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
3835 }
3836 
ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastBlock)3837 static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,
3838                                void* dst, size_t dstCapacity,
3839                                const void* src, size_t srcSize,
3840                                U32 lastBlock)
3841 {
3842     size_t cSize = 0;
3843     const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
3844     DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
3845                 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
3846     FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
3847 
3848     cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);
3849     FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
3850 
3851     if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
3852         zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
3853 
3854     return cSize;
3855 }
3856 
ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t * ms,ZSTD_cwksp * ws,ZSTD_CCtx_params const * params,void const * ip,void const * iend)3857 static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms,
3858                                          ZSTD_cwksp* ws,
3859                                          ZSTD_CCtx_params const* params,
3860                                          void const* ip,
3861                                          void const* iend)
3862 {
3863     U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
3864     U32 const maxDist = (U32)1 << params->cParams.windowLog;
3865     if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {
3866         U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
3867         ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
3868         ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
3869         ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
3870         ZSTD_cwksp_mark_tables_dirty(ws);
3871         ZSTD_reduceIndex(ms, params, correction);
3872         ZSTD_cwksp_mark_tables_clean(ws);
3873         if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
3874         else ms->nextToUpdate -= correction;
3875         /* invalidate dictionaries on overflow correction */
3876         ms->loadedDictEnd = 0;
3877         ms->dictMatchState = NULL;
3878     }
3879 }
3880 
3881 /*! ZSTD_compress_frameChunk() :
3882 *   Compress a chunk of data into one or multiple blocks.
3883 *   All blocks will be terminated, all input will be consumed.
3884 *   Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
3885 *   Frame is supposed already started (header already produced)
3886 *   @return : compressed size, or an error code
3887 */
ZSTD_compress_frameChunk(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastFrameChunk)3888 static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx,
3889                                      void* dst, size_t dstCapacity,
3890                                const void* src, size_t srcSize,
3891                                      U32 lastFrameChunk)
3892 {
3893     size_t blockSize = cctx->blockSize;
3894     size_t remaining = srcSize;
3895     const BYTE* ip = (const BYTE*)src;
3896     BYTE* const ostart = (BYTE*)dst;
3897     BYTE* op = ostart;
3898     U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
3899 
3900     assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
3901 
3902     DEBUGLOG(4, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize);
3903     if (cctx->appliedParams.fParams.checksumFlag && srcSize)
3904         XXH64_update(&cctx->xxhState, src, srcSize);
3905 
3906     while (remaining) {
3907         ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
3908         U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
3909 
3910         RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE,
3911                         dstSize_tooSmall,
3912                         "not enough space to store compressed block");
3913         if (remaining < blockSize) blockSize = remaining;
3914 
3915         ZSTD_overflowCorrectIfNeeded(
3916             ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
3917         ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
3918 
3919         /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
3920         if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
3921 
3922         {   size_t cSize;
3923             if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
3924                 cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
3925                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
3926                 assert(cSize > 0);
3927                 assert(cSize <= blockSize + ZSTD_blockHeaderSize);
3928             } else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
3929                 cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
3930                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
3931                 assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
3932             } else {
3933                 cSize = ZSTD_compressBlock_internal(cctx,
3934                                         op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
3935                                         ip, blockSize, 1 /* frame */);
3936                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
3937 
3938                 if (cSize == 0) {  /* block is not compressible */
3939                     cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
3940                     FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
3941                 } else {
3942                     U32 const cBlockHeader = cSize == 1 ?
3943                         lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
3944                         lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
3945                     MEM_writeLE24(op, cBlockHeader);
3946                     cSize += ZSTD_blockHeaderSize;
3947                 }
3948             }
3949 
3950 
3951             ip += blockSize;
3952             assert(remaining >= blockSize);
3953             remaining -= blockSize;
3954             op += cSize;
3955             assert(dstCapacity >= cSize);
3956             dstCapacity -= cSize;
3957             cctx->isFirstBlock = 0;
3958             DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
3959                         (unsigned)cSize);
3960     }   }
3961 
3962     if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
3963     return (size_t)(op-ostart);
3964 }
3965 
3966 
ZSTD_writeFrameHeader(void * dst,size_t dstCapacity,const ZSTD_CCtx_params * params,U64 pledgedSrcSize,U32 dictID)3967 static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
3968                                     const ZSTD_CCtx_params* params, U64 pledgedSrcSize, U32 dictID)
3969 {   BYTE* const op = (BYTE*)dst;
3970     U32   const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536);   /* 0-3 */
3971     U32   const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength;   /* 0-3 */
3972     U32   const checksumFlag = params->fParams.checksumFlag>0;
3973     U32   const windowSize = (U32)1 << params->cParams.windowLog;
3974     U32   const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
3975     BYTE  const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
3976     U32   const fcsCode = params->fParams.contentSizeFlag ?
3977                      (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0;  /* 0-3 */
3978     BYTE  const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
3979     size_t pos=0;
3980 
3981     assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
3982     RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
3983                     "dst buf is too small to fit worst-case frame header size.");
3984     DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
3985                 !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
3986     if (params->format == ZSTD_f_zstd1) {
3987         MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
3988         pos = 4;
3989     }
3990     op[pos++] = frameHeaderDescriptionByte;
3991     if (!singleSegment) op[pos++] = windowLogByte;
3992     switch(dictIDSizeCode)
3993     {
3994         default:  assert(0); /* impossible */
3995         case 0 : break;
3996         case 1 : op[pos] = (BYTE)(dictID); pos++; break;
3997         case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
3998         case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
3999     }
4000     switch(fcsCode)
4001     {
4002         default:  assert(0); /* impossible */
4003         case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
4004         case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
4005         case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
4006         case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
4007     }
4008     return pos;
4009 }
4010 
4011 /* ZSTD_writeSkippableFrame_advanced() :
4012  * Writes out a skippable frame with the specified magic number variant (16 are supported),
4013  * from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15, and the desired source data.
4014  *
4015  * Returns the total number of bytes written, or a ZSTD error code.
4016  */
ZSTD_writeSkippableFrame(void * dst,size_t dstCapacity,const void * src,size_t srcSize,unsigned magicVariant)4017 size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
4018                                 const void* src, size_t srcSize, unsigned magicVariant) {
4019     BYTE* op = (BYTE*)dst;
4020     RETURN_ERROR_IF(dstCapacity < srcSize + ZSTD_SKIPPABLEHEADERSIZE /* Skippable frame overhead */,
4021                     dstSize_tooSmall, "Not enough room for skippable frame");
4022     RETURN_ERROR_IF(srcSize > (unsigned)0xFFFFFFFF, srcSize_wrong, "Src size too large for skippable frame");
4023     RETURN_ERROR_IF(magicVariant > 15, parameter_outOfBound, "Skippable frame magic number variant not supported");
4024 
4025     MEM_writeLE32(op, (U32)(ZSTD_MAGIC_SKIPPABLE_START + magicVariant));
4026     MEM_writeLE32(op+4, (U32)srcSize);
4027     ZSTD_memcpy(op+8, src, srcSize);
4028     return srcSize + ZSTD_SKIPPABLEHEADERSIZE;
4029 }
4030 
4031 /* ZSTD_writeLastEmptyBlock() :
4032  * output an empty Block with end-of-frame mark to complete a frame
4033  * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
4034  *           or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
4035  */
ZSTD_writeLastEmptyBlock(void * dst,size_t dstCapacity)4036 size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
4037 {
4038     RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall,
4039                     "dst buf is too small to write frame trailer empty block.");
4040     {   U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1);  /* 0 size */
4041         MEM_writeLE24(dst, cBlockHeader24);
4042         return ZSTD_blockHeaderSize;
4043     }
4044 }
4045 
ZSTD_referenceExternalSequences(ZSTD_CCtx * cctx,rawSeq * seq,size_t nbSeq)4046 size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
4047 {
4048     RETURN_ERROR_IF(cctx->stage != ZSTDcs_init, stage_wrong,
4049                     "wrong cctx stage");
4050     RETURN_ERROR_IF(cctx->appliedParams.ldmParams.enableLdm,
4051                     parameter_unsupported,
4052                     "incompatible with ldm");
4053     cctx->externSeqStore.seq = seq;
4054     cctx->externSeqStore.size = nbSeq;
4055     cctx->externSeqStore.capacity = nbSeq;
4056     cctx->externSeqStore.pos = 0;
4057     cctx->externSeqStore.posInSequence = 0;
4058     return 0;
4059 }
4060 
4061 
ZSTD_compressContinue_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 frame,U32 lastFrameChunk)4062 static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
4063                               void* dst, size_t dstCapacity,
4064                         const void* src, size_t srcSize,
4065                                U32 frame, U32 lastFrameChunk)
4066 {
4067     ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
4068     size_t fhSize = 0;
4069 
4070     DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
4071                 cctx->stage, (unsigned)srcSize);
4072     RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
4073                     "missing init (ZSTD_compressBegin)");
4074 
4075     if (frame && (cctx->stage==ZSTDcs_init)) {
4076         fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
4077                                        cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
4078         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
4079         assert(fhSize <= dstCapacity);
4080         dstCapacity -= fhSize;
4081         dst = (char*)dst + fhSize;
4082         cctx->stage = ZSTDcs_ongoing;
4083     }
4084 
4085     if (!srcSize) return fhSize;  /* do not generate an empty block if no input */
4086 
4087     if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
4088         ms->forceNonContiguous = 0;
4089         ms->nextToUpdate = ms->window.dictLimit;
4090     }
4091     if (cctx->appliedParams.ldmParams.enableLdm) {
4092         ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
4093     }
4094 
4095     if (!frame) {
4096         /* overflow check and correction for block mode */
4097         ZSTD_overflowCorrectIfNeeded(
4098             ms, &cctx->workspace, &cctx->appliedParams,
4099             src, (BYTE const*)src + srcSize);
4100     }
4101 
4102     DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
4103     {   size_t const cSize = frame ?
4104                              ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
4105                              ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
4106         FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
4107         cctx->consumedSrcSize += srcSize;
4108         cctx->producedCSize += (cSize + fhSize);
4109         assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
4110         if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
4111             ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
4112             RETURN_ERROR_IF(
4113                 cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
4114                 srcSize_wrong,
4115                 "error : pledgedSrcSize = %u, while realSrcSize >= %u",
4116                 (unsigned)cctx->pledgedSrcSizePlusOne-1,
4117                 (unsigned)cctx->consumedSrcSize);
4118         }
4119         return cSize + fhSize;
4120     }
4121 }
4122 
ZSTD_compressContinue(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4123 size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
4124                               void* dst, size_t dstCapacity,
4125                         const void* src, size_t srcSize)
4126 {
4127     DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
4128     return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
4129 }
4130 
4131 
ZSTD_getBlockSize(const ZSTD_CCtx * cctx)4132 size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
4133 {
4134     ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
4135     assert(!ZSTD_checkCParams(cParams));
4136     return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
4137 }
4138 
ZSTD_compressBlock(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4139 size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
4140 {
4141     DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
4142     { size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
4143       RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
4144 
4145     return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
4146 }
4147 
4148 /*! ZSTD_loadDictionaryContent() :
4149  *  @return : 0, or an error code
4150  */
ZSTD_loadDictionaryContent(ZSTD_matchState_t * ms,ldmState_t * ls,ZSTD_cwksp * ws,ZSTD_CCtx_params const * params,const void * src,size_t srcSize,ZSTD_dictTableLoadMethod_e dtlm)4151 static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
4152                                          ldmState_t* ls,
4153                                          ZSTD_cwksp* ws,
4154                                          ZSTD_CCtx_params const* params,
4155                                          const void* src, size_t srcSize,
4156                                          ZSTD_dictTableLoadMethod_e dtlm)
4157 {
4158     const BYTE* ip = (const BYTE*) src;
4159     const BYTE* const iend = ip + srcSize;
4160     int const loadLdmDict = params->ldmParams.enableLdm && ls != NULL;
4161 
4162     /* Assert that we the ms params match the params we're being given */
4163     ZSTD_assertEqualCParams(params->cParams, ms->cParams);
4164 
4165     if (srcSize > ZSTD_CHUNKSIZE_MAX) {
4166         /* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
4167          * Dictionaries right at the edge will immediately trigger overflow
4168          * correction, but I don't want to insert extra constraints here.
4169          */
4170         U32 const maxDictSize = ZSTD_CURRENT_MAX - 1;
4171         /* We must have cleared our windows when our source is this large. */
4172         assert(ZSTD_window_isEmpty(ms->window));
4173         if (loadLdmDict)
4174             assert(ZSTD_window_isEmpty(ls->window));
4175         /* If the dictionary is too large, only load the suffix of the dictionary. */
4176         if (srcSize > maxDictSize) {
4177             ip = iend - maxDictSize;
4178             src = ip;
4179             srcSize = maxDictSize;
4180         }
4181     }
4182 
4183     DEBUGLOG(4, "ZSTD_loadDictionaryContent(): useRowMatchFinder=%d", (int)params->useRowMatchFinder);
4184     ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
4185     ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
4186     ms->forceNonContiguous = params->deterministicRefPrefix;
4187 
4188     if (loadLdmDict) {
4189         ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
4190         ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
4191     }
4192 
4193     if (srcSize <= HASH_READ_SIZE) return 0;
4194 
4195     ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
4196 
4197     if (loadLdmDict)
4198         ZSTD_ldm_fillHashTable(ls, ip, iend, &params->ldmParams);
4199 
4200     switch(params->cParams.strategy)
4201     {
4202     case ZSTD_fast:
4203         ZSTD_fillHashTable(ms, iend, dtlm);
4204         break;
4205     case ZSTD_dfast:
4206         ZSTD_fillDoubleHashTable(ms, iend, dtlm);
4207         break;
4208 
4209     case ZSTD_greedy:
4210     case ZSTD_lazy:
4211     case ZSTD_lazy2:
4212         assert(srcSize >= HASH_READ_SIZE);
4213         if (ms->dedicatedDictSearch) {
4214             assert(ms->chainTable != NULL);
4215             ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
4216         } else {
4217             assert(params->useRowMatchFinder != ZSTD_urm_auto);
4218             if (params->useRowMatchFinder == ZSTD_urm_enableRowMatchFinder) {
4219                 size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog) * sizeof(U16);
4220                 ZSTD_memset(ms->tagTable, 0, tagTableSize);
4221                 ZSTD_row_update(ms, iend-HASH_READ_SIZE);
4222                 DEBUGLOG(4, "Using row-based hash table for lazy dict");
4223             } else {
4224                 ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
4225                 DEBUGLOG(4, "Using chain-based hash table for lazy dict");
4226             }
4227         }
4228         break;
4229 
4230     case ZSTD_btlazy2:   /* we want the dictionary table fully sorted */
4231     case ZSTD_btopt:
4232     case ZSTD_btultra:
4233     case ZSTD_btultra2:
4234         assert(srcSize >= HASH_READ_SIZE);
4235         ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
4236         break;
4237 
4238     default:
4239         assert(0);  /* not possible : not a valid strategy id */
4240     }
4241 
4242     ms->nextToUpdate = (U32)(iend - ms->window.base);
4243     return 0;
4244 }
4245 
4246 
4247 /* Dictionaries that assign zero probability to symbols that show up causes problems
4248  * when FSE encoding. Mark dictionaries with zero probability symbols as FSE_repeat_check
4249  * and only dictionaries with 100% valid symbols can be assumed valid.
4250  */
ZSTD_dictNCountRepeat(short * normalizedCounter,unsigned dictMaxSymbolValue,unsigned maxSymbolValue)4251 static FSE_repeat ZSTD_dictNCountRepeat(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)
4252 {
4253     U32 s;
4254     if (dictMaxSymbolValue < maxSymbolValue) {
4255         return FSE_repeat_check;
4256     }
4257     for (s = 0; s <= maxSymbolValue; ++s) {
4258         if (normalizedCounter[s] == 0) {
4259             return FSE_repeat_check;
4260         }
4261     }
4262     return FSE_repeat_valid;
4263 }
4264 
ZSTD_loadCEntropy(ZSTD_compressedBlockState_t * bs,void * workspace,const void * const dict,size_t dictSize)4265 size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
4266                          const void* const dict, size_t dictSize)
4267 {
4268     short offcodeNCount[MaxOff+1];
4269     unsigned offcodeMaxValue = MaxOff;
4270     const BYTE* dictPtr = (const BYTE*)dict;    /* skip magic num and dict ID */
4271     const BYTE* const dictEnd = dictPtr + dictSize;
4272     dictPtr += 8;
4273     bs->entropy.huf.repeatMode = HUF_repeat_check;
4274 
4275     {   unsigned maxSymbolValue = 255;
4276         unsigned hasZeroWeights = 1;
4277         size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
4278             dictEnd-dictPtr, &hasZeroWeights);
4279 
4280         /* We only set the loaded table as valid if it contains all non-zero
4281          * weights. Otherwise, we set it to check */
4282         if (!hasZeroWeights)
4283             bs->entropy.huf.repeatMode = HUF_repeat_valid;
4284 
4285         RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
4286         RETURN_ERROR_IF(maxSymbolValue < 255, dictionary_corrupted, "");
4287         dictPtr += hufHeaderSize;
4288     }
4289 
4290     {   unsigned offcodeLog;
4291         size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
4292         RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
4293         RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
4294         /* fill all offset symbols to avoid garbage at end of table */
4295         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
4296                 bs->entropy.fse.offcodeCTable,
4297                 offcodeNCount, MaxOff, offcodeLog,
4298                 workspace, HUF_WORKSPACE_SIZE)),
4299             dictionary_corrupted, "");
4300         /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
4301         dictPtr += offcodeHeaderSize;
4302     }
4303 
4304     {   short matchlengthNCount[MaxML+1];
4305         unsigned matchlengthMaxValue = MaxML, matchlengthLog;
4306         size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
4307         RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
4308         RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
4309         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
4310                 bs->entropy.fse.matchlengthCTable,
4311                 matchlengthNCount, matchlengthMaxValue, matchlengthLog,
4312                 workspace, HUF_WORKSPACE_SIZE)),
4313             dictionary_corrupted, "");
4314         bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
4315         dictPtr += matchlengthHeaderSize;
4316     }
4317 
4318     {   short litlengthNCount[MaxLL+1];
4319         unsigned litlengthMaxValue = MaxLL, litlengthLog;
4320         size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
4321         RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
4322         RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
4323         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
4324                 bs->entropy.fse.litlengthCTable,
4325                 litlengthNCount, litlengthMaxValue, litlengthLog,
4326                 workspace, HUF_WORKSPACE_SIZE)),
4327             dictionary_corrupted, "");
4328         bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
4329         dictPtr += litlengthHeaderSize;
4330     }
4331 
4332     RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
4333     bs->rep[0] = MEM_readLE32(dictPtr+0);
4334     bs->rep[1] = MEM_readLE32(dictPtr+4);
4335     bs->rep[2] = MEM_readLE32(dictPtr+8);
4336     dictPtr += 12;
4337 
4338     {   size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
4339         U32 offcodeMax = MaxOff;
4340         if (dictContentSize <= ((U32)-1) - 128 KB) {
4341             U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
4342             offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
4343         }
4344         /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
4345         bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
4346 
4347         /* All repCodes must be <= dictContentSize and != 0 */
4348         {   U32 u;
4349             for (u=0; u<3; u++) {
4350                 RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
4351                 RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
4352     }   }   }
4353 
4354     return dictPtr - (const BYTE*)dict;
4355 }
4356 
4357 /* Dictionary format :
4358  * See :
4359  * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
4360  */
4361 /*! ZSTD_loadZstdDictionary() :
4362  * @return : dictID, or an error code
4363  *  assumptions : magic number supposed already checked
4364  *                dictSize supposed >= 8
4365  */
ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t * bs,ZSTD_matchState_t * ms,ZSTD_cwksp * ws,ZSTD_CCtx_params const * params,const void * dict,size_t dictSize,ZSTD_dictTableLoadMethod_e dtlm,void * workspace)4366 static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
4367                                       ZSTD_matchState_t* ms,
4368                                       ZSTD_cwksp* ws,
4369                                       ZSTD_CCtx_params const* params,
4370                                       const void* dict, size_t dictSize,
4371                                       ZSTD_dictTableLoadMethod_e dtlm,
4372                                       void* workspace)
4373 {
4374     const BYTE* dictPtr = (const BYTE*)dict;
4375     const BYTE* const dictEnd = dictPtr + dictSize;
4376     size_t dictID;
4377     size_t eSize;
4378     ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
4379     assert(dictSize >= 8);
4380     assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
4381 
4382     dictID = params->fParams.noDictIDFlag ? 0 :  MEM_readLE32(dictPtr + 4 /* skip magic number */ );
4383     eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
4384     FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
4385     dictPtr += eSize;
4386 
4387     {
4388         size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
4389         FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
4390             ms, NULL, ws, params, dictPtr, dictContentSize, dtlm), "");
4391     }
4392     return dictID;
4393 }
4394 
4395 /** ZSTD_compress_insertDictionary() :
4396 *   @return : dictID, or an error code */
4397 static size_t
ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t * bs,ZSTD_matchState_t * ms,ldmState_t * ls,ZSTD_cwksp * ws,const ZSTD_CCtx_params * params,const void * dict,size_t dictSize,ZSTD_dictContentType_e dictContentType,ZSTD_dictTableLoadMethod_e dtlm,void * workspace)4398 ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
4399                                ZSTD_matchState_t* ms,
4400                                ldmState_t* ls,
4401                                ZSTD_cwksp* ws,
4402                          const ZSTD_CCtx_params* params,
4403                          const void* dict, size_t dictSize,
4404                                ZSTD_dictContentType_e dictContentType,
4405                                ZSTD_dictTableLoadMethod_e dtlm,
4406                                void* workspace)
4407 {
4408     DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
4409     if ((dict==NULL) || (dictSize<8)) {
4410         RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
4411         return 0;
4412     }
4413 
4414     ZSTD_reset_compressedBlockState(bs);
4415 
4416     /* dict restricted modes */
4417     if (dictContentType == ZSTD_dct_rawContent)
4418         return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm);
4419 
4420     if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
4421         if (dictContentType == ZSTD_dct_auto) {
4422             DEBUGLOG(4, "raw content dictionary detected");
4423             return ZSTD_loadDictionaryContent(
4424                 ms, ls, ws, params, dict, dictSize, dtlm);
4425         }
4426         RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
4427         assert(0);   /* impossible */
4428     }
4429 
4430     /* dict as full zstd dictionary */
4431     return ZSTD_loadZstdDictionary(
4432         bs, ms, ws, params, dict, dictSize, dtlm, workspace);
4433 }
4434 
4435 #define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
4436 #define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)
4437 
4438 /*! ZSTD_compressBegin_internal() :
4439  * @return : 0, or an error code */
ZSTD_compressBegin_internal(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,ZSTD_dictContentType_e dictContentType,ZSTD_dictTableLoadMethod_e dtlm,const ZSTD_CDict * cdict,const ZSTD_CCtx_params * params,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)4440 static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
4441                                     const void* dict, size_t dictSize,
4442                                     ZSTD_dictContentType_e dictContentType,
4443                                     ZSTD_dictTableLoadMethod_e dtlm,
4444                                     const ZSTD_CDict* cdict,
4445                                     const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
4446                                     ZSTD_buffered_policy_e zbuff)
4447 {
4448     size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
4449 #if ZSTD_TRACE
4450     cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
4451 #endif
4452     DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
4453     /* params are supposed to be fully validated at this point */
4454     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
4455     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
4456     if ( (cdict)
4457       && (cdict->dictContentSize > 0)
4458       && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
4459         || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
4460         || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
4461         || cdict->compressionLevel == 0)
4462       && (params->attachDictPref != ZSTD_dictForceLoad) ) {
4463         return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
4464     }
4465 
4466     FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
4467                                      dictContentSize,
4468                                      ZSTDcrp_makeClean, zbuff) , "");
4469     {   size_t const dictID = cdict ?
4470                 ZSTD_compress_insertDictionary(
4471                         cctx->blockState.prevCBlock, &cctx->blockState.matchState,
4472                         &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
4473                         cdict->dictContentSize, cdict->dictContentType, dtlm,
4474                         cctx->entropyWorkspace)
4475               : ZSTD_compress_insertDictionary(
4476                         cctx->blockState.prevCBlock, &cctx->blockState.matchState,
4477                         &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
4478                         dictContentType, dtlm, cctx->entropyWorkspace);
4479         FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
4480         assert(dictID <= UINT_MAX);
4481         cctx->dictID = (U32)dictID;
4482         cctx->dictContentSize = dictContentSize;
4483     }
4484     return 0;
4485 }
4486 
ZSTD_compressBegin_advanced_internal(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,ZSTD_dictContentType_e dictContentType,ZSTD_dictTableLoadMethod_e dtlm,const ZSTD_CDict * cdict,const ZSTD_CCtx_params * params,unsigned long long pledgedSrcSize)4487 size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
4488                                     const void* dict, size_t dictSize,
4489                                     ZSTD_dictContentType_e dictContentType,
4490                                     ZSTD_dictTableLoadMethod_e dtlm,
4491                                     const ZSTD_CDict* cdict,
4492                                     const ZSTD_CCtx_params* params,
4493                                     unsigned long long pledgedSrcSize)
4494 {
4495     DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
4496     /* compression parameters verification and optimization */
4497     FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
4498     return ZSTD_compressBegin_internal(cctx,
4499                                        dict, dictSize, dictContentType, dtlm,
4500                                        cdict,
4501                                        params, pledgedSrcSize,
4502                                        ZSTDb_not_buffered);
4503 }
4504 
4505 /*! ZSTD_compressBegin_advanced() :
4506 *   @return : 0, or an error code */
ZSTD_compressBegin_advanced(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,ZSTD_parameters params,unsigned long long pledgedSrcSize)4507 size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
4508                              const void* dict, size_t dictSize,
4509                                    ZSTD_parameters params, unsigned long long pledgedSrcSize)
4510 {
4511     ZSTD_CCtx_params cctxParams;
4512     ZSTD_CCtxParams_init_internal(&cctxParams, &params, ZSTD_NO_CLEVEL);
4513     return ZSTD_compressBegin_advanced_internal(cctx,
4514                                             dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
4515                                             NULL /*cdict*/,
4516                                             &cctxParams, pledgedSrcSize);
4517 }
4518 
ZSTD_compressBegin_usingDict(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,int compressionLevel)4519 size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
4520 {
4521     ZSTD_CCtx_params cctxParams;
4522     {
4523         ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);
4524         ZSTD_CCtxParams_init_internal(&cctxParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
4525     }
4526     DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
4527     return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
4528                                        &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
4529 }
4530 
ZSTD_compressBegin(ZSTD_CCtx * cctx,int compressionLevel)4531 size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
4532 {
4533     return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
4534 }
4535 
4536 
4537 /*! ZSTD_writeEpilogue() :
4538 *   Ends a frame.
4539 *   @return : nb of bytes written into dst (or an error code) */
ZSTD_writeEpilogue(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity)4540 static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
4541 {
4542     BYTE* const ostart = (BYTE*)dst;
4543     BYTE* op = ostart;
4544     size_t fhSize = 0;
4545 
4546     DEBUGLOG(4, "ZSTD_writeEpilogue");
4547     RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
4548 
4549     /* special case : empty frame */
4550     if (cctx->stage == ZSTDcs_init) {
4551         fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
4552         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
4553         dstCapacity -= fhSize;
4554         op += fhSize;
4555         cctx->stage = ZSTDcs_ongoing;
4556     }
4557 
4558     if (cctx->stage != ZSTDcs_ending) {
4559         /* write one last empty block, make it the "last" block */
4560         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
4561         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for epilogue");
4562         MEM_writeLE32(op, cBlockHeader24);
4563         op += ZSTD_blockHeaderSize;
4564         dstCapacity -= ZSTD_blockHeaderSize;
4565     }
4566 
4567     if (cctx->appliedParams.fParams.checksumFlag) {
4568         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
4569         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
4570         DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
4571         MEM_writeLE32(op, checksum);
4572         op += 4;
4573     }
4574 
4575     cctx->stage = ZSTDcs_created;  /* return to "created but no init" status */
4576     return op-ostart;
4577 }
4578 
ZSTD_CCtx_trace(ZSTD_CCtx * cctx,size_t extraCSize)4579 void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)
4580 {
4581 #if ZSTD_TRACE
4582     if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
4583         int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
4584         ZSTD_Trace trace;
4585         ZSTD_memset(&trace, 0, sizeof(trace));
4586         trace.version = ZSTD_VERSION_NUMBER;
4587         trace.streaming = streaming;
4588         trace.dictionaryID = cctx->dictID;
4589         trace.dictionarySize = cctx->dictContentSize;
4590         trace.uncompressedSize = cctx->consumedSrcSize;
4591         trace.compressedSize = cctx->producedCSize + extraCSize;
4592         trace.params = &cctx->appliedParams;
4593         trace.cctx = cctx;
4594         ZSTD_trace_compress_end(cctx->traceCtx, &trace);
4595     }
4596     cctx->traceCtx = 0;
4597 #else
4598     (void)cctx;
4599     (void)extraCSize;
4600 #endif
4601 }
4602 
ZSTD_compressEnd(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4603 size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
4604                          void* dst, size_t dstCapacity,
4605                    const void* src, size_t srcSize)
4606 {
4607     size_t endResult;
4608     size_t const cSize = ZSTD_compressContinue_internal(cctx,
4609                                 dst, dstCapacity, src, srcSize,
4610                                 1 /* frame mode */, 1 /* last chunk */);
4611     FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
4612     endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
4613     FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
4614     assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
4615     if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
4616         ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
4617         DEBUGLOG(4, "end of frame : controlling src size");
4618         RETURN_ERROR_IF(
4619             cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
4620             srcSize_wrong,
4621              "error : pledgedSrcSize = %u, while realSrcSize = %u",
4622             (unsigned)cctx->pledgedSrcSizePlusOne-1,
4623             (unsigned)cctx->consumedSrcSize);
4624     }
4625     ZSTD_CCtx_trace(cctx, endResult);
4626     return cSize + endResult;
4627 }
4628 
ZSTD_compress_advanced(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize,ZSTD_parameters params)4629 size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
4630                                void* dst, size_t dstCapacity,
4631                          const void* src, size_t srcSize,
4632                          const void* dict,size_t dictSize,
4633                                ZSTD_parameters params)
4634 {
4635     DEBUGLOG(4, "ZSTD_compress_advanced");
4636     FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
4637     ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, ZSTD_NO_CLEVEL);
4638     return ZSTD_compress_advanced_internal(cctx,
4639                                            dst, dstCapacity,
4640                                            src, srcSize,
4641                                            dict, dictSize,
4642                                            &cctx->simpleApiParams);
4643 }
4644 
4645 /* Internal */
ZSTD_compress_advanced_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize,const ZSTD_CCtx_params * params)4646 size_t ZSTD_compress_advanced_internal(
4647         ZSTD_CCtx* cctx,
4648         void* dst, size_t dstCapacity,
4649         const void* src, size_t srcSize,
4650         const void* dict,size_t dictSize,
4651         const ZSTD_CCtx_params* params)
4652 {
4653     DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
4654     FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
4655                          dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
4656                          params, srcSize, ZSTDb_not_buffered) , "");
4657     return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
4658 }
4659 
ZSTD_compress_usingDict(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize,int compressionLevel)4660 size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
4661                                void* dst, size_t dstCapacity,
4662                          const void* src, size_t srcSize,
4663                          const void* dict, size_t dictSize,
4664                                int compressionLevel)
4665 {
4666     {
4667         ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);
4668         assert(params.fParams.contentSizeFlag == 1);
4669         ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);
4670     }
4671     DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
4672     return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
4673 }
4674 
ZSTD_compressCCtx(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,int compressionLevel)4675 size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
4676                          void* dst, size_t dstCapacity,
4677                    const void* src, size_t srcSize,
4678                          int compressionLevel)
4679 {
4680     DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
4681     assert(cctx != NULL);
4682     return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
4683 }
4684 
ZSTD_compress(void * dst,size_t dstCapacity,const void * src,size_t srcSize,int compressionLevel)4685 size_t ZSTD_compress(void* dst, size_t dstCapacity,
4686                const void* src, size_t srcSize,
4687                      int compressionLevel)
4688 {
4689     size_t result;
4690 #if ZSTD_COMPRESS_HEAPMODE
4691     ZSTD_CCtx* cctx = ZSTD_createCCtx();
4692     RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");
4693     result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);
4694     ZSTD_freeCCtx(cctx);
4695 #else
4696     ZSTD_CCtx ctxBody;
4697     ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
4698     result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
4699     ZSTD_freeCCtxContent(&ctxBody);   /* can't free ctxBody itself, as it's on stack; free only heap content */
4700 #endif
4701     return result;
4702 }
4703 
4704 
4705 /* =====  Dictionary API  ===== */
4706 
4707 /*! ZSTD_estimateCDictSize_advanced() :
4708  *  Estimate amount of memory that will be needed to create a dictionary with following arguments */
ZSTD_estimateCDictSize_advanced(size_t dictSize,ZSTD_compressionParameters cParams,ZSTD_dictLoadMethod_e dictLoadMethod)4709 size_t ZSTD_estimateCDictSize_advanced(
4710         size_t dictSize, ZSTD_compressionParameters cParams,
4711         ZSTD_dictLoadMethod_e dictLoadMethod)
4712 {
4713     DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
4714     return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
4715          + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
4716          /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
4717           * in case we are using DDS with row-hash. */
4718          + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_urm_auto, &cParams),
4719                                   /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)
4720          + (dictLoadMethod == ZSTD_dlm_byRef ? 0
4721             : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
4722 }
4723 
ZSTD_estimateCDictSize(size_t dictSize,int compressionLevel)4724 size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
4725 {
4726     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4727     return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
4728 }
4729 
ZSTD_sizeof_CDict(const ZSTD_CDict * cdict)4730 size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
4731 {
4732     if (cdict==NULL) return 0;   /* support sizeof on NULL */
4733     DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
4734     /* cdict may be in the workspace */
4735     return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
4736         + ZSTD_cwksp_sizeof(&cdict->workspace);
4737 }
4738 
ZSTD_initCDict_internal(ZSTD_CDict * cdict,const void * dictBuffer,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_CCtx_params params)4739 static size_t ZSTD_initCDict_internal(
4740                     ZSTD_CDict* cdict,
4741               const void* dictBuffer, size_t dictSize,
4742                     ZSTD_dictLoadMethod_e dictLoadMethod,
4743                     ZSTD_dictContentType_e dictContentType,
4744                     ZSTD_CCtx_params params)
4745 {
4746     DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
4747     assert(!ZSTD_checkCParams(params.cParams));
4748     cdict->matchState.cParams = params.cParams;
4749     cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
4750     if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
4751         cdict->dictContent = dictBuffer;
4752     } else {
4753          void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
4754         RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
4755         cdict->dictContent = internalBuffer;
4756         ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
4757     }
4758     cdict->dictContentSize = dictSize;
4759     cdict->dictContentType = dictContentType;
4760 
4761     cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
4762 
4763 
4764     /* Reset the state to no dictionary */
4765     ZSTD_reset_compressedBlockState(&cdict->cBlockState);
4766     FORWARD_IF_ERROR(ZSTD_reset_matchState(
4767         &cdict->matchState,
4768         &cdict->workspace,
4769         &params.cParams,
4770         params.useRowMatchFinder,
4771         ZSTDcrp_makeClean,
4772         ZSTDirp_reset,
4773         ZSTD_resetTarget_CDict), "");
4774     /* (Maybe) load the dictionary
4775      * Skips loading the dictionary if it is < 8 bytes.
4776      */
4777     {   params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
4778         params.fParams.contentSizeFlag = 1;
4779         {   size_t const dictID = ZSTD_compress_insertDictionary(
4780                     &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
4781                     &params, cdict->dictContent, cdict->dictContentSize,
4782                     dictContentType, ZSTD_dtlm_full, cdict->entropyWorkspace);
4783             FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
4784             assert(dictID <= (size_t)(U32)-1);
4785             cdict->dictID = (U32)dictID;
4786         }
4787     }
4788 
4789     return 0;
4790 }
4791 
ZSTD_createCDict_advanced_internal(size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_compressionParameters cParams,ZSTD_useRowMatchFinderMode_e useRowMatchFinder,U32 enableDedicatedDictSearch,ZSTD_customMem customMem)4792 static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize,
4793                                       ZSTD_dictLoadMethod_e dictLoadMethod,
4794                                       ZSTD_compressionParameters cParams,
4795                                       ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
4796                                       U32 enableDedicatedDictSearch,
4797                                       ZSTD_customMem customMem)
4798 {
4799     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
4800 
4801     {   size_t const workspaceSize =
4802             ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
4803             ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
4804             ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
4805             (dictLoadMethod == ZSTD_dlm_byRef ? 0
4806              : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
4807         void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
4808         ZSTD_cwksp ws;
4809         ZSTD_CDict* cdict;
4810 
4811         if (!workspace) {
4812             ZSTD_customFree(workspace, customMem);
4813             return NULL;
4814         }
4815 
4816         ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
4817 
4818         cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
4819         assert(cdict != NULL);
4820         ZSTD_cwksp_move(&cdict->workspace, &ws);
4821         cdict->customMem = customMem;
4822         cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */
4823         cdict->useRowMatchFinder = useRowMatchFinder;
4824         return cdict;
4825     }
4826 }
4827 
ZSTD_createCDict_advanced(const void * dictBuffer,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_compressionParameters cParams,ZSTD_customMem customMem)4828 ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
4829                                       ZSTD_dictLoadMethod_e dictLoadMethod,
4830                                       ZSTD_dictContentType_e dictContentType,
4831                                       ZSTD_compressionParameters cParams,
4832                                       ZSTD_customMem customMem)
4833 {
4834     ZSTD_CCtx_params cctxParams;
4835     ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));
4836     ZSTD_CCtxParams_init(&cctxParams, 0);
4837     cctxParams.cParams = cParams;
4838     cctxParams.customMem = customMem;
4839     return ZSTD_createCDict_advanced2(
4840         dictBuffer, dictSize,
4841         dictLoadMethod, dictContentType,
4842         &cctxParams, customMem);
4843 }
4844 
ZSTD_createCDict_advanced2(const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,const ZSTD_CCtx_params * originalCctxParams,ZSTD_customMem customMem)4845 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced2(
4846         const void* dict, size_t dictSize,
4847         ZSTD_dictLoadMethod_e dictLoadMethod,
4848         ZSTD_dictContentType_e dictContentType,
4849         const ZSTD_CCtx_params* originalCctxParams,
4850         ZSTD_customMem customMem)
4851 {
4852     ZSTD_CCtx_params cctxParams = *originalCctxParams;
4853     ZSTD_compressionParameters cParams;
4854     ZSTD_CDict* cdict;
4855 
4856     DEBUGLOG(3, "ZSTD_createCDict_advanced2, mode %u", (unsigned)dictContentType);
4857     if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
4858 
4859     if (cctxParams.enableDedicatedDictSearch) {
4860         cParams = ZSTD_dedicatedDictSearch_getCParams(
4861             cctxParams.compressionLevel, dictSize);
4862         ZSTD_overrideCParams(&cParams, &cctxParams.cParams);
4863     } else {
4864         cParams = ZSTD_getCParamsFromCCtxParams(
4865             &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4866     }
4867 
4868     if (!ZSTD_dedicatedDictSearch_isSupported(&cParams)) {
4869         /* Fall back to non-DDSS params */
4870         cctxParams.enableDedicatedDictSearch = 0;
4871         cParams = ZSTD_getCParamsFromCCtxParams(
4872             &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4873     }
4874 
4875     DEBUGLOG(3, "ZSTD_createCDict_advanced2: DDS: %u", cctxParams.enableDedicatedDictSearch);
4876     cctxParams.cParams = cParams;
4877     cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
4878 
4879     cdict = ZSTD_createCDict_advanced_internal(dictSize,
4880                         dictLoadMethod, cctxParams.cParams,
4881                         cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
4882                         customMem);
4883 
4884     if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
4885                                     dict, dictSize,
4886                                     dictLoadMethod, dictContentType,
4887                                     cctxParams) )) {
4888         ZSTD_freeCDict(cdict);
4889         return NULL;
4890     }
4891 
4892     return cdict;
4893 }
4894 
ZSTD_createCDict(const void * dict,size_t dictSize,int compressionLevel)4895 ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
4896 {
4897     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4898     ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
4899                                                   ZSTD_dlm_byCopy, ZSTD_dct_auto,
4900                                                   cParams, ZSTD_defaultCMem);
4901     if (cdict)
4902         cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
4903     return cdict;
4904 }
4905 
ZSTD_createCDict_byReference(const void * dict,size_t dictSize,int compressionLevel)4906 ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
4907 {
4908     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4909     ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
4910                                      ZSTD_dlm_byRef, ZSTD_dct_auto,
4911                                      cParams, ZSTD_defaultCMem);
4912     if (cdict)
4913         cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
4914     return cdict;
4915 }
4916 
ZSTD_freeCDict(ZSTD_CDict * cdict)4917 size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
4918 {
4919     if (cdict==NULL) return 0;   /* support free on NULL */
4920     {   ZSTD_customMem const cMem = cdict->customMem;
4921         int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
4922         ZSTD_cwksp_free(&cdict->workspace, cMem);
4923         if (!cdictInWorkspace) {
4924             ZSTD_customFree(cdict, cMem);
4925         }
4926         return 0;
4927     }
4928 }
4929 
4930 /*! ZSTD_initStaticCDict_advanced() :
4931  *  Generate a digested dictionary in provided memory area.
4932  *  workspace: The memory area to emplace the dictionary into.
4933  *             Provided pointer must 8-bytes aligned.
4934  *             It must outlive dictionary usage.
4935  *  workspaceSize: Use ZSTD_estimateCDictSize()
4936  *                 to determine how large workspace must be.
4937  *  cParams : use ZSTD_getCParams() to transform a compression level
4938  *            into its relevants cParams.
4939  * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
4940  *  Note : there is no corresponding "free" function.
4941  *         Since workspace was allocated externally, it must be freed externally.
4942  */
ZSTD_initStaticCDict(void * workspace,size_t workspaceSize,const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_compressionParameters cParams)4943 const ZSTD_CDict* ZSTD_initStaticCDict(
4944                                  void* workspace, size_t workspaceSize,
4945                            const void* dict, size_t dictSize,
4946                                  ZSTD_dictLoadMethod_e dictLoadMethod,
4947                                  ZSTD_dictContentType_e dictContentType,
4948                                  ZSTD_compressionParameters cParams)
4949 {
4950     ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_urm_auto, &cParams);
4951     /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
4952     size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
4953     size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
4954                             + (dictLoadMethod == ZSTD_dlm_byRef ? 0
4955                                : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
4956                             + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
4957                             + matchStateSize;
4958     ZSTD_CDict* cdict;
4959     ZSTD_CCtx_params params;
4960 
4961     if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
4962 
4963     {
4964         ZSTD_cwksp ws;
4965         ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
4966         cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
4967         if (cdict == NULL) return NULL;
4968         ZSTD_cwksp_move(&cdict->workspace, &ws);
4969     }
4970 
4971     DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u",
4972         (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize));
4973     if (workspaceSize < neededSize) return NULL;
4974 
4975     ZSTD_CCtxParams_init(&params, 0);
4976     params.cParams = cParams;
4977     params.useRowMatchFinder = useRowMatchFinder;
4978     cdict->useRowMatchFinder = useRowMatchFinder;
4979 
4980     if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
4981                                               dict, dictSize,
4982                                               dictLoadMethod, dictContentType,
4983                                               params) ))
4984         return NULL;
4985 
4986     return cdict;
4987 }
4988 
ZSTD_getCParamsFromCDict(const ZSTD_CDict * cdict)4989 ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
4990 {
4991     assert(cdict != NULL);
4992     return cdict->matchState.cParams;
4993 }
4994 
4995 /*! ZSTD_getDictID_fromCDict() :
4996  *  Provides the dictID of the dictionary loaded into `cdict`.
4997  *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
4998  *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
ZSTD_getDictID_fromCDict(const ZSTD_CDict * cdict)4999 unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)
5000 {
5001     if (cdict==NULL) return 0;
5002     return cdict->dictID;
5003 }
5004 
5005 /* ZSTD_compressBegin_usingCDict_internal() :
5006  * Implementation of various ZSTD_compressBegin_usingCDict* functions.
5007  */
ZSTD_compressBegin_usingCDict_internal(ZSTD_CCtx * const cctx,const ZSTD_CDict * const cdict,ZSTD_frameParameters const fParams,unsigned long long const pledgedSrcSize)5008 static size_t ZSTD_compressBegin_usingCDict_internal(
5009     ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5010     ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5011 {
5012     ZSTD_CCtx_params cctxParams;
5013     DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
5014     RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
5015     /* Initialize the cctxParams from the cdict */
5016     {
5017         ZSTD_parameters params;
5018         params.fParams = fParams;
5019         params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
5020                         || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
5021                         || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
5022                         || cdict->compressionLevel == 0 ) ?
5023                 ZSTD_getCParamsFromCDict(cdict)
5024               : ZSTD_getCParams(cdict->compressionLevel,
5025                                 pledgedSrcSize,
5026                                 cdict->dictContentSize);
5027         ZSTD_CCtxParams_init_internal(&cctxParams, &params, cdict->compressionLevel);
5028     }
5029     /* Increase window log to fit the entire dictionary and source if the
5030      * source size is known. Limit the increase to 19, which is the
5031      * window log for compression level 1 with the largest source size.
5032      */
5033     if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
5034         U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
5035         U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
5036         cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
5037     }
5038     return ZSTD_compressBegin_internal(cctx,
5039                                         NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
5040                                         cdict,
5041                                         &cctxParams, pledgedSrcSize,
5042                                         ZSTDb_not_buffered);
5043 }
5044 
5045 
5046 /* ZSTD_compressBegin_usingCDict_advanced() :
5047  * This function is DEPRECATED.
5048  * cdict must be != NULL */
ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx * const cctx,const ZSTD_CDict * const cdict,ZSTD_frameParameters const fParams,unsigned long long const pledgedSrcSize)5049 size_t ZSTD_compressBegin_usingCDict_advanced(
5050     ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5051     ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5052 {
5053     return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
5054 }
5055 
5056 /* ZSTD_compressBegin_usingCDict() :
5057  * cdict must be != NULL */
ZSTD_compressBegin_usingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict)5058 size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
5059 {
5060     ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5061     return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
5062 }
5063 
5064 /*! ZSTD_compress_usingCDict_internal():
5065  * Implementation of various ZSTD_compress_usingCDict* functions.
5066  */
ZSTD_compress_usingCDict_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const ZSTD_CDict * cdict,ZSTD_frameParameters fParams)5067 static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
5068                                 void* dst, size_t dstCapacity,
5069                                 const void* src, size_t srcSize,
5070                                 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5071 {
5072     FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */
5073     return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
5074 }
5075 
5076 /*! ZSTD_compress_usingCDict_advanced():
5077  * This function is DEPRECATED.
5078  */
ZSTD_compress_usingCDict_advanced(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const ZSTD_CDict * cdict,ZSTD_frameParameters fParams)5079 size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
5080                                 void* dst, size_t dstCapacity,
5081                                 const void* src, size_t srcSize,
5082                                 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5083 {
5084     return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5085 }
5086 
5087 /*! ZSTD_compress_usingCDict() :
5088  *  Compression using a digested Dictionary.
5089  *  Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
5090  *  Note that compression parameters are decided at CDict creation time
5091  *  while frame parameters are hardcoded */
ZSTD_compress_usingCDict(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const ZSTD_CDict * cdict)5092 size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
5093                                 void* dst, size_t dstCapacity,
5094                                 const void* src, size_t srcSize,
5095                                 const ZSTD_CDict* cdict)
5096 {
5097     ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5098     return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5099 }
5100 
5101 
5102 
5103 /* ******************************************************************
5104 *  Streaming
5105 ********************************************************************/
5106 
ZSTD_createCStream(void)5107 ZSTD_CStream* ZSTD_createCStream(void)
5108 {
5109     DEBUGLOG(3, "ZSTD_createCStream");
5110     return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
5111 }
5112 
ZSTD_initStaticCStream(void * workspace,size_t workspaceSize)5113 ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
5114 {
5115     return ZSTD_initStaticCCtx(workspace, workspaceSize);
5116 }
5117 
ZSTD_createCStream_advanced(ZSTD_customMem customMem)5118 ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
5119 {   /* CStream and CCtx are now same object */
5120     return ZSTD_createCCtx_advanced(customMem);
5121 }
5122 
ZSTD_freeCStream(ZSTD_CStream * zcs)5123 size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
5124 {
5125     return ZSTD_freeCCtx(zcs);   /* same object */
5126 }
5127 
5128 
5129 
5130 /*======   Initialization   ======*/
5131 
ZSTD_CStreamInSize(void)5132 size_t ZSTD_CStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX; }
5133 
ZSTD_CStreamOutSize(void)5134 size_t ZSTD_CStreamOutSize(void)
5135 {
5136     return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
5137 }
5138 
ZSTD_getCParamMode(ZSTD_CDict const * cdict,ZSTD_CCtx_params const * params,U64 pledgedSrcSize)5139 static ZSTD_cParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
5140 {
5141     if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))
5142         return ZSTD_cpm_attachDict;
5143     else
5144         return ZSTD_cpm_noAttachDict;
5145 }
5146 
5147 /* ZSTD_resetCStream():
5148  * pledgedSrcSize == 0 means "unknown" */
ZSTD_resetCStream(ZSTD_CStream * zcs,unsigned long long pss)5149 size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
5150 {
5151     /* temporary : 0 interpreted as "unknown" during transition period.
5152      * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
5153      * 0 will be interpreted as "empty" in the future.
5154      */
5155     U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5156     DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
5157     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5158     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5159     return 0;
5160 }
5161 
5162 /*! ZSTD_initCStream_internal() :
5163  *  Note : for lib/compress only. Used by zstdmt_compress.c.
5164  *  Assumption 1 : params are valid
5165  *  Assumption 2 : either dict, or cdict, is defined, not both */
ZSTD_initCStream_internal(ZSTD_CStream * zcs,const void * dict,size_t dictSize,const ZSTD_CDict * cdict,const ZSTD_CCtx_params * params,unsigned long long pledgedSrcSize)5166 size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
5167                     const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
5168                     const ZSTD_CCtx_params* params,
5169                     unsigned long long pledgedSrcSize)
5170 {
5171     DEBUGLOG(4, "ZSTD_initCStream_internal");
5172     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5173     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5174     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
5175     zcs->requestedParams = *params;
5176     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
5177     if (dict) {
5178         FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5179     } else {
5180         /* Dictionary is cleared if !cdict */
5181         FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
5182     }
5183     return 0;
5184 }
5185 
5186 /* ZSTD_initCStream_usingCDict_advanced() :
5187  * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream * zcs,const ZSTD_CDict * cdict,ZSTD_frameParameters fParams,unsigned long long pledgedSrcSize)5188 size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
5189                                             const ZSTD_CDict* cdict,
5190                                             ZSTD_frameParameters fParams,
5191                                             unsigned long long pledgedSrcSize)
5192 {
5193     DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
5194     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5195     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5196     zcs->requestedParams.fParams = fParams;
5197     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
5198     return 0;
5199 }
5200 
5201 /* note : cdict must outlive compression session */
ZSTD_initCStream_usingCDict(ZSTD_CStream * zcs,const ZSTD_CDict * cdict)5202 size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
5203 {
5204     DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
5205     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5206     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
5207     return 0;
5208 }
5209 
5210 
5211 /* ZSTD_initCStream_advanced() :
5212  * pledgedSrcSize must be exact.
5213  * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
5214  * dict is loaded with default parameters ZSTD_dct_auto and ZSTD_dlm_byCopy. */
ZSTD_initCStream_advanced(ZSTD_CStream * zcs,const void * dict,size_t dictSize,ZSTD_parameters params,unsigned long long pss)5215 size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
5216                                  const void* dict, size_t dictSize,
5217                                  ZSTD_parameters params, unsigned long long pss)
5218 {
5219     /* for compatibility with older programs relying on this behavior.
5220      * Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
5221      * This line will be removed in the future.
5222      */
5223     U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5224     DEBUGLOG(4, "ZSTD_initCStream_advanced");
5225     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5226     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5227     FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
5228     ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, &params);
5229     FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5230     return 0;
5231 }
5232 
ZSTD_initCStream_usingDict(ZSTD_CStream * zcs,const void * dict,size_t dictSize,int compressionLevel)5233 size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
5234 {
5235     DEBUGLOG(4, "ZSTD_initCStream_usingDict");
5236     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5237     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
5238     FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5239     return 0;
5240 }
5241 
ZSTD_initCStream_srcSize(ZSTD_CStream * zcs,int compressionLevel,unsigned long long pss)5242 size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
5243 {
5244     /* temporary : 0 interpreted as "unknown" during transition period.
5245      * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
5246      * 0 will be interpreted as "empty" in the future.
5247      */
5248     U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5249     DEBUGLOG(4, "ZSTD_initCStream_srcSize");
5250     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5251     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
5252     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
5253     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5254     return 0;
5255 }
5256 
ZSTD_initCStream(ZSTD_CStream * zcs,int compressionLevel)5257 size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
5258 {
5259     DEBUGLOG(4, "ZSTD_initCStream");
5260     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5261     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
5262     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
5263     return 0;
5264 }
5265 
5266 /*======   Compression   ======*/
5267 
ZSTD_nextInputSizeHint(const ZSTD_CCtx * cctx)5268 static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
5269 {
5270     size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
5271     if (hintInSize==0) hintInSize = cctx->blockSize;
5272     return hintInSize;
5273 }
5274 
5275 /** ZSTD_compressStream_generic():
5276  *  internal function for all *compressStream*() variants
5277  *  non-static, because can be called from zstdmt_compress.c
5278  * @return : hint size for next input */
ZSTD_compressStream_generic(ZSTD_CStream * zcs,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective const flushMode)5279 static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
5280                                           ZSTD_outBuffer* output,
5281                                           ZSTD_inBuffer* input,
5282                                           ZSTD_EndDirective const flushMode)
5283 {
5284     const char* const istart = (const char*)input->src;
5285     const char* const iend = input->size != 0 ? istart + input->size : istart;
5286     const char* ip = input->pos != 0 ? istart + input->pos : istart;
5287     char* const ostart = (char*)output->dst;
5288     char* const oend = output->size != 0 ? ostart + output->size : ostart;
5289     char* op = output->pos != 0 ? ostart + output->pos : ostart;
5290     U32 someMoreWork = 1;
5291 
5292     /* check expectations */
5293     DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (unsigned)flushMode);
5294     if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
5295         assert(zcs->inBuff != NULL);
5296         assert(zcs->inBuffSize > 0);
5297     }
5298     if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
5299         assert(zcs->outBuff !=  NULL);
5300         assert(zcs->outBuffSize > 0);
5301     }
5302     assert(output->pos <= output->size);
5303     assert(input->pos <= input->size);
5304     assert((U32)flushMode <= (U32)ZSTD_e_end);
5305 
5306     while (someMoreWork) {
5307         switch(zcs->streamStage)
5308         {
5309         case zcss_init:
5310             RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
5311 
5312         case zcss_load:
5313             if ( (flushMode == ZSTD_e_end)
5314               && ( (size_t)(oend-op) >= ZSTD_compressBound(iend-ip)     /* Enough output space */
5315                 || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)  /* OR we are allowed to return dstSizeTooSmall */
5316               && (zcs->inBuffPos == 0) ) {
5317                 /* shortcut to compression pass directly into output buffer */
5318                 size_t const cSize = ZSTD_compressEnd(zcs,
5319                                                 op, oend-op, ip, iend-ip);
5320                 DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
5321                 FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
5322                 ip = iend;
5323                 op += cSize;
5324                 zcs->frameEnded = 1;
5325                 ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
5326                 someMoreWork = 0; break;
5327             }
5328             /* complete loading into inBuffer in buffered mode */
5329             if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
5330                 size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
5331                 size_t const loaded = ZSTD_limitCopy(
5332                                         zcs->inBuff + zcs->inBuffPos, toLoad,
5333                                         ip, iend-ip);
5334                 zcs->inBuffPos += loaded;
5335                 if (loaded != 0)
5336                     ip += loaded;
5337                 if ( (flushMode == ZSTD_e_continue)
5338                   && (zcs->inBuffPos < zcs->inBuffTarget) ) {
5339                     /* not enough input to fill full block : stop here */
5340                     someMoreWork = 0; break;
5341                 }
5342                 if ( (flushMode == ZSTD_e_flush)
5343                   && (zcs->inBuffPos == zcs->inToCompress) ) {
5344                     /* empty */
5345                     someMoreWork = 0; break;
5346                 }
5347             }
5348             /* compress current block (note : this stage cannot be stopped in the middle) */
5349             DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
5350             {   int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
5351                 void* cDst;
5352                 size_t cSize;
5353                 size_t oSize = oend-op;
5354                 size_t const iSize = inputBuffered
5355                     ? zcs->inBuffPos - zcs->inToCompress
5356                     : MIN((size_t)(iend - ip), zcs->blockSize);
5357                 if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
5358                     cDst = op;   /* compress into output buffer, to skip flush stage */
5359                 else
5360                     cDst = zcs->outBuff, oSize = zcs->outBuffSize;
5361                 if (inputBuffered) {
5362                     unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
5363                     cSize = lastBlock ?
5364                             ZSTD_compressEnd(zcs, cDst, oSize,
5365                                         zcs->inBuff + zcs->inToCompress, iSize) :
5366                             ZSTD_compressContinue(zcs, cDst, oSize,
5367                                         zcs->inBuff + zcs->inToCompress, iSize);
5368                     FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
5369                     zcs->frameEnded = lastBlock;
5370                     /* prepare next block */
5371                     zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
5372                     if (zcs->inBuffTarget > zcs->inBuffSize)
5373                         zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
5374                     DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
5375                             (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
5376                     if (!lastBlock)
5377                         assert(zcs->inBuffTarget <= zcs->inBuffSize);
5378                     zcs->inToCompress = zcs->inBuffPos;
5379                 } else {
5380                     unsigned const lastBlock = (ip + iSize == iend);
5381                     assert(flushMode == ZSTD_e_end /* Already validated */);
5382                     cSize = lastBlock ?
5383                             ZSTD_compressEnd(zcs, cDst, oSize, ip, iSize) :
5384                             ZSTD_compressContinue(zcs, cDst, oSize, ip, iSize);
5385                     /* Consume the input prior to error checking to mirror buffered mode. */
5386                     if (iSize > 0)
5387                         ip += iSize;
5388                     FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
5389                     zcs->frameEnded = lastBlock;
5390                     if (lastBlock)
5391                         assert(ip == iend);
5392                 }
5393                 if (cDst == op) {  /* no need to flush */
5394                     op += cSize;
5395                     if (zcs->frameEnded) {
5396                         DEBUGLOG(5, "Frame completed directly in outBuffer");
5397                         someMoreWork = 0;
5398                         ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
5399                     }
5400                     break;
5401                 }
5402                 zcs->outBuffContentSize = cSize;
5403                 zcs->outBuffFlushedSize = 0;
5404                 zcs->streamStage = zcss_flush; /* pass-through to flush stage */
5405             }
5406 	    /* fall-through */
5407         case zcss_flush:
5408             DEBUGLOG(5, "flush stage");
5409             assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
5410             {   size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
5411                 size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
5412                             zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
5413                 DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
5414                             (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
5415                 if (flushed)
5416                     op += flushed;
5417                 zcs->outBuffFlushedSize += flushed;
5418                 if (toFlush!=flushed) {
5419                     /* flush not fully completed, presumably because dst is too small */
5420                     assert(op==oend);
5421                     someMoreWork = 0;
5422                     break;
5423                 }
5424                 zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
5425                 if (zcs->frameEnded) {
5426                     DEBUGLOG(5, "Frame completed on flush");
5427                     someMoreWork = 0;
5428                     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
5429                     break;
5430                 }
5431                 zcs->streamStage = zcss_load;
5432                 break;
5433             }
5434 
5435         default: /* impossible */
5436             assert(0);
5437         }
5438     }
5439 
5440     input->pos = ip - istart;
5441     output->pos = op - ostart;
5442     if (zcs->frameEnded) return 0;
5443     return ZSTD_nextInputSizeHint(zcs);
5444 }
5445 
ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx * cctx)5446 static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
5447 {
5448 #ifdef ZSTD_MULTITHREAD
5449     if (cctx->appliedParams.nbWorkers >= 1) {
5450         assert(cctx->mtctx != NULL);
5451         return ZSTDMT_nextInputSizeHint(cctx->mtctx);
5452     }
5453 #endif
5454     return ZSTD_nextInputSizeHint(cctx);
5455 
5456 }
5457 
ZSTD_compressStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output,ZSTD_inBuffer * input)5458 size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
5459 {
5460     FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
5461     return ZSTD_nextInputSizeHint_MTorST(zcs);
5462 }
5463 
5464 /* After a compression call set the expected input/output buffer.
5465  * This is validated at the start of the next compression call.
5466  */
ZSTD_setBufferExpectations(ZSTD_CCtx * cctx,ZSTD_outBuffer const * output,ZSTD_inBuffer const * input)5467 static void ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, ZSTD_outBuffer const* output, ZSTD_inBuffer const* input)
5468 {
5469     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
5470         cctx->expectedInBuffer = *input;
5471     }
5472     if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
5473         cctx->expectedOutBufferSize = output->size - output->pos;
5474     }
5475 }
5476 
5477 /* Validate that the input/output buffers match the expectations set by
5478  * ZSTD_setBufferExpectations.
5479  */
ZSTD_checkBufferStability(ZSTD_CCtx const * cctx,ZSTD_outBuffer const * output,ZSTD_inBuffer const * input,ZSTD_EndDirective endOp)5480 static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
5481                                         ZSTD_outBuffer const* output,
5482                                         ZSTD_inBuffer const* input,
5483                                         ZSTD_EndDirective endOp)
5484 {
5485     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
5486         ZSTD_inBuffer const expect = cctx->expectedInBuffer;
5487         if (expect.src != input->src || expect.pos != input->pos || expect.size != input->size)
5488             RETURN_ERROR(srcBuffer_wrong, "ZSTD_c_stableInBuffer enabled but input differs!");
5489         if (endOp != ZSTD_e_end)
5490             RETURN_ERROR(srcBuffer_wrong, "ZSTD_c_stableInBuffer can only be used with ZSTD_e_end!");
5491     }
5492     if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
5493         size_t const outBufferSize = output->size - output->pos;
5494         if (cctx->expectedOutBufferSize != outBufferSize)
5495             RETURN_ERROR(dstBuffer_wrong, "ZSTD_c_stableOutBuffer enabled but output size differs!");
5496     }
5497     return 0;
5498 }
5499 
ZSTD_CCtx_init_compressStream2(ZSTD_CCtx * cctx,ZSTD_EndDirective endOp,size_t inSize)5500 static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
5501                                              ZSTD_EndDirective endOp,
5502                                              size_t inSize) {
5503     ZSTD_CCtx_params params = cctx->requestedParams;
5504     ZSTD_prefixDict const prefixDict = cctx->prefixDict;
5505     FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
5506     ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));   /* single usage */
5507     assert(prefixDict.dict==NULL || cctx->cdict==NULL);    /* only one can be set */
5508     if (cctx->cdict && !cctx->localDict.cdict) {
5509         /* Let the cdict's compression level take priority over the requested params.
5510          * But do not take the cdict's compression level if the "cdict" is actually a localDict
5511          * generated from ZSTD_initLocalDict().
5512          */
5513         params.compressionLevel = cctx->cdict->compressionLevel;
5514     }
5515     DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
5516     if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1;  /* auto-fix pledgedSrcSize */
5517     {
5518         size_t const dictSize = prefixDict.dict
5519                 ? prefixDict.dictSize
5520                 : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
5521         ZSTD_cParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, &params, cctx->pledgedSrcSizePlusOne - 1);
5522         params.cParams = ZSTD_getCParamsFromCCtxParams(
5523                 &params, cctx->pledgedSrcSizePlusOne-1,
5524                 dictSize, mode);
5525     }
5526 
5527     if (ZSTD_CParams_shouldEnableLdm(&params.cParams)) {
5528         /* Enable LDM by default for optimal parser and window size >= 128MB */
5529         DEBUGLOG(4, "LDM enabled by default (window size >= 128MB, strategy >= btopt)");
5530         params.ldmParams.enableLdm = 1;
5531     }
5532 
5533     if (ZSTD_CParams_useBlockSplitter(&params.cParams)) {
5534         DEBUGLOG(4, "Block splitter enabled by default (window size >= 128K, strategy >= btopt)");
5535         params.splitBlocks = 1;
5536     }
5537 
5538     params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
5539 
5540 #ifdef ZSTD_MULTITHREAD
5541     if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
5542         params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
5543     }
5544     if (params.nbWorkers > 0) {
5545 #if ZSTD_TRACE
5546         cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
5547 #endif
5548         /* mt context creation */
5549         if (cctx->mtctx == NULL) {
5550             DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
5551                         params.nbWorkers);
5552             cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
5553             RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
5554         }
5555         /* mt compression */
5556         DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
5557         FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
5558                     cctx->mtctx,
5559                     prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
5560                     cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
5561         cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
5562         cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
5563         cctx->consumedSrcSize = 0;
5564         cctx->producedCSize = 0;
5565         cctx->streamStage = zcss_load;
5566         cctx->appliedParams = params;
5567     } else
5568 #endif
5569     {   U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
5570         assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
5571         FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
5572                 prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
5573                 cctx->cdict,
5574                 &params, pledgedSrcSize,
5575                 ZSTDb_buffered) , "");
5576         assert(cctx->appliedParams.nbWorkers == 0);
5577         cctx->inToCompress = 0;
5578         cctx->inBuffPos = 0;
5579         if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
5580             /* for small input: avoid automatic flush on reaching end of block, since
5581             * it would require to add a 3-bytes null block to end frame
5582             */
5583             cctx->inBuffTarget = cctx->blockSize + (cctx->blockSize == pledgedSrcSize);
5584         } else {
5585             cctx->inBuffTarget = 0;
5586         }
5587         cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
5588         cctx->streamStage = zcss_load;
5589         cctx->frameEnded = 0;
5590     }
5591     return 0;
5592 }
5593 
ZSTD_compressStream2(ZSTD_CCtx * cctx,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective endOp)5594 size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
5595                              ZSTD_outBuffer* output,
5596                              ZSTD_inBuffer* input,
5597                              ZSTD_EndDirective endOp)
5598 {
5599     DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
5600     /* check conditions */
5601     RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
5602     RETURN_ERROR_IF(input->pos  > input->size, srcSize_wrong, "invalid input buffer");
5603     RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
5604     assert(cctx != NULL);
5605 
5606     /* transparent initialization stage */
5607     if (cctx->streamStage == zcss_init) {
5608         FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, input->size), "CompressStream2 initialization failed");
5609         ZSTD_setBufferExpectations(cctx, output, input);    /* Set initial buffer expectations now that we've initialized */
5610     }
5611     /* end of transparent initialization stage */
5612 
5613     FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");
5614     /* compression stage */
5615 #ifdef ZSTD_MULTITHREAD
5616     if (cctx->appliedParams.nbWorkers > 0) {
5617         size_t flushMin;
5618         if (cctx->cParamsChanged) {
5619             ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
5620             cctx->cParamsChanged = 0;
5621         }
5622         for (;;) {
5623             size_t const ipos = input->pos;
5624             size_t const opos = output->pos;
5625             flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
5626             cctx->consumedSrcSize += (U64)(input->pos - ipos);
5627             cctx->producedCSize += (U64)(output->pos - opos);
5628             if ( ZSTD_isError(flushMin)
5629               || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
5630                 if (flushMin == 0)
5631                     ZSTD_CCtx_trace(cctx, 0);
5632                 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
5633             }
5634             FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
5635 
5636             if (endOp == ZSTD_e_continue) {
5637                 /* We only require some progress with ZSTD_e_continue, not maximal progress.
5638                  * We're done if we've consumed or produced any bytes, or either buffer is
5639                  * full.
5640                  */
5641                 if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
5642                     break;
5643             } else {
5644                 assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
5645                 /* We require maximal progress. We're done when the flush is complete or the
5646                  * output buffer is full.
5647                  */
5648                 if (flushMin == 0 || output->pos == output->size)
5649                     break;
5650             }
5651         }
5652         DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
5653         /* Either we don't require maximum forward progress, we've finished the
5654          * flush, or we are out of output space.
5655          */
5656         assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
5657         ZSTD_setBufferExpectations(cctx, output, input);
5658         return flushMin;
5659     }
5660 #endif
5661     FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
5662     DEBUGLOG(5, "completed ZSTD_compressStream2");
5663     ZSTD_setBufferExpectations(cctx, output, input);
5664     return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
5665 }
5666 
ZSTD_compressStream2_simpleArgs(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,size_t * dstPos,const void * src,size_t srcSize,size_t * srcPos,ZSTD_EndDirective endOp)5667 size_t ZSTD_compressStream2_simpleArgs (
5668                             ZSTD_CCtx* cctx,
5669                             void* dst, size_t dstCapacity, size_t* dstPos,
5670                       const void* src, size_t srcSize, size_t* srcPos,
5671                             ZSTD_EndDirective endOp)
5672 {
5673     ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
5674     ZSTD_inBuffer  input  = { src, srcSize, *srcPos };
5675     /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
5676     size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
5677     *dstPos = output.pos;
5678     *srcPos = input.pos;
5679     return cErr;
5680 }
5681 
ZSTD_compress2(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)5682 size_t ZSTD_compress2(ZSTD_CCtx* cctx,
5683                       void* dst, size_t dstCapacity,
5684                       const void* src, size_t srcSize)
5685 {
5686     ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
5687     ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
5688     DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
5689     ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
5690     /* Enable stable input/output buffers. */
5691     cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
5692     cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
5693     {   size_t oPos = 0;
5694         size_t iPos = 0;
5695         size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
5696                                         dst, dstCapacity, &oPos,
5697                                         src, srcSize, &iPos,
5698                                         ZSTD_e_end);
5699         /* Reset to the original values. */
5700         cctx->requestedParams.inBufferMode = originalInBufferMode;
5701         cctx->requestedParams.outBufferMode = originalOutBufferMode;
5702         FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
5703         if (result != 0) {  /* compression not completed, due to lack of output space */
5704             assert(oPos == dstCapacity);
5705             RETURN_ERROR(dstSize_tooSmall, "");
5706         }
5707         assert(iPos == srcSize);   /* all input is expected consumed */
5708         return oPos;
5709     }
5710 }
5711 
5712 typedef struct {
5713     U32 idx;             /* Index in array of ZSTD_Sequence */
5714     U32 posInSequence;   /* Position within sequence at idx */
5715     size_t posInSrc;        /* Number of bytes given by sequences provided so far */
5716 } ZSTD_sequencePosition;
5717 
5718 /* Returns a ZSTD error code if sequence is not valid */
ZSTD_validateSequence(U32 offCode,U32 matchLength,size_t posInSrc,U32 windowLog,size_t dictSize,U32 minMatch)5719 static size_t ZSTD_validateSequence(U32 offCode, U32 matchLength,
5720                                     size_t posInSrc, U32 windowLog, size_t dictSize, U32 minMatch) {
5721     size_t offsetBound;
5722     U32 windowSize = 1 << windowLog;
5723     /* posInSrc represents the amount of data the the decoder would decode up to this point.
5724      * As long as the amount of data decoded is less than or equal to window size, offsets may be
5725      * larger than the total length of output decoded in order to reference the dict, even larger than
5726      * window size. After output surpasses windowSize, we're limited to windowSize offsets again.
5727      */
5728     offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize;
5729     RETURN_ERROR_IF(offCode > offsetBound + ZSTD_REP_MOVE, corruption_detected, "Offset too large!");
5730     RETURN_ERROR_IF(matchLength < minMatch, corruption_detected, "Matchlength too small");
5731     return 0;
5732 }
5733 
5734 /* Returns an offset code, given a sequence's raw offset, the ongoing repcode array, and whether litLength == 0 */
ZSTD_finalizeOffCode(U32 rawOffset,const U32 rep[ZSTD_REP_NUM],U32 ll0)5735 static U32 ZSTD_finalizeOffCode(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0) {
5736     U32 offCode = rawOffset + ZSTD_REP_MOVE;
5737     U32 repCode = 0;
5738 
5739     if (!ll0 && rawOffset == rep[0]) {
5740         repCode = 1;
5741     } else if (rawOffset == rep[1]) {
5742         repCode = 2 - ll0;
5743     } else if (rawOffset == rep[2]) {
5744         repCode = 3 - ll0;
5745     } else if (ll0 && rawOffset == rep[0] - 1) {
5746         repCode = 3;
5747     }
5748     if (repCode) {
5749         /* ZSTD_storeSeq expects a number in the range [0, 2] to represent a repcode */
5750         offCode = repCode - 1;
5751     }
5752     return offCode;
5753 }
5754 
5755 /* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of
5756  * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.
5757  */
ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx * cctx,ZSTD_sequencePosition * seqPos,const ZSTD_Sequence * const inSeqs,size_t inSeqsSize,const void * src,size_t blockSize)5758 static size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
5759                                                              const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
5760                                                              const void* src, size_t blockSize) {
5761     U32 idx = seqPos->idx;
5762     BYTE const* ip = (BYTE const*)(src);
5763     const BYTE* const iend = ip + blockSize;
5764     repcodes_t updatedRepcodes;
5765     U32 dictSize;
5766     U32 litLength;
5767     U32 matchLength;
5768     U32 ll0;
5769     U32 offCode;
5770 
5771     if (cctx->cdict) {
5772         dictSize = (U32)cctx->cdict->dictContentSize;
5773     } else if (cctx->prefixDict.dict) {
5774         dictSize = (U32)cctx->prefixDict.dictSize;
5775     } else {
5776         dictSize = 0;
5777     }
5778     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
5779     for (; (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0) && idx < inSeqsSize; ++idx) {
5780         litLength = inSeqs[idx].litLength;
5781         matchLength = inSeqs[idx].matchLength;
5782         ll0 = litLength == 0;
5783         offCode = ZSTD_finalizeOffCode(inSeqs[idx].offset, updatedRepcodes.rep, ll0);
5784         updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep, offCode, ll0);
5785 
5786         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offCode, matchLength, litLength);
5787         if (cctx->appliedParams.validateSequences) {
5788             seqPos->posInSrc += litLength + matchLength;
5789             FORWARD_IF_ERROR(ZSTD_validateSequence(offCode, matchLength, seqPos->posInSrc,
5790                                                 cctx->appliedParams.cParams.windowLog, dictSize,
5791                                                 cctx->appliedParams.cParams.minMatch),
5792                                                 "Sequence validation failed");
5793         }
5794         RETURN_ERROR_IF(idx - seqPos->idx > cctx->seqStore.maxNbSeq, memory_allocation,
5795                         "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
5796         ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offCode, matchLength - MINMATCH);
5797         ip += matchLength + litLength;
5798     }
5799     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
5800 
5801     if (inSeqs[idx].litLength) {
5802         DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);
5803         ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);
5804         ip += inSeqs[idx].litLength;
5805         seqPos->posInSrc += inSeqs[idx].litLength;
5806     }
5807     RETURN_ERROR_IF(ip != iend, corruption_detected, "Blocksize doesn't agree with block delimiter!");
5808     seqPos->idx = idx+1;
5809     return 0;
5810 }
5811 
5812 /* Returns the number of bytes to move the current read position back by. Only non-zero
5813  * if we ended up splitting a sequence. Otherwise, it may return a ZSTD error if something
5814  * went wrong.
5815  *
5816  * This function will attempt to scan through blockSize bytes represented by the sequences
5817  * in inSeqs, storing any (partial) sequences.
5818  *
5819  * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
5820  * avoid splitting a match, or to avoid splitting a match such that it would produce a match
5821  * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
5822  */
ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx * cctx,ZSTD_sequencePosition * seqPos,const ZSTD_Sequence * const inSeqs,size_t inSeqsSize,const void * src,size_t blockSize)5823 static size_t ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
5824                                                        const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
5825                                                        const void* src, size_t blockSize) {
5826     U32 idx = seqPos->idx;
5827     U32 startPosInSequence = seqPos->posInSequence;
5828     U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
5829     size_t dictSize;
5830     BYTE const* ip = (BYTE const*)(src);
5831     BYTE const* iend = ip + blockSize;  /* May be adjusted if we decide to process fewer than blockSize bytes */
5832     repcodes_t updatedRepcodes;
5833     U32 bytesAdjustment = 0;
5834     U32 finalMatchSplit = 0;
5835     U32 litLength;
5836     U32 matchLength;
5837     U32 rawOffset;
5838     U32 offCode;
5839 
5840     if (cctx->cdict) {
5841         dictSize = cctx->cdict->dictContentSize;
5842     } else if (cctx->prefixDict.dict) {
5843         dictSize = cctx->prefixDict.dictSize;
5844     } else {
5845         dictSize = 0;
5846     }
5847     DEBUGLOG(5, "ZSTD_copySequencesToSeqStore: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
5848     DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
5849     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
5850     while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
5851         const ZSTD_Sequence currSeq = inSeqs[idx];
5852         litLength = currSeq.litLength;
5853         matchLength = currSeq.matchLength;
5854         rawOffset = currSeq.offset;
5855 
5856         /* Modify the sequence depending on where endPosInSequence lies */
5857         if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
5858             if (startPosInSequence >= litLength) {
5859                 startPosInSequence -= litLength;
5860                 litLength = 0;
5861                 matchLength -= startPosInSequence;
5862             } else {
5863                 litLength -= startPosInSequence;
5864             }
5865             /* Move to the next sequence */
5866             endPosInSequence -= currSeq.litLength + currSeq.matchLength;
5867             startPosInSequence = 0;
5868             idx++;
5869         } else {
5870             /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
5871                does not reach the end of the match. So, we have to split the sequence */
5872             DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
5873                      currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
5874             if (endPosInSequence > litLength) {
5875                 U32 firstHalfMatchLength;
5876                 litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
5877                 firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
5878                 if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
5879                     /* Only ever split the match if it is larger than the block size */
5880                     U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
5881                     if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
5882                         /* Move the endPosInSequence backward so that it creates match of minMatch length */
5883                         endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
5884                         bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
5885                         firstHalfMatchLength -= bytesAdjustment;
5886                     }
5887                     matchLength = firstHalfMatchLength;
5888                     /* Flag that we split the last match - after storing the sequence, exit the loop,
5889                        but keep the value of endPosInSequence */
5890                     finalMatchSplit = 1;
5891                 } else {
5892                     /* Move the position in sequence backwards so that we don't split match, and break to store
5893                      * the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence
5894                      * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
5895                      * would cause the first half of the match to be too small
5896                      */
5897                     bytesAdjustment = endPosInSequence - currSeq.litLength;
5898                     endPosInSequence = currSeq.litLength;
5899                     break;
5900                 }
5901             } else {
5902                 /* This sequence ends inside the literals, break to store the last literals */
5903                 break;
5904             }
5905         }
5906         /* Check if this offset can be represented with a repcode */
5907         {   U32 ll0 = (litLength == 0);
5908             offCode = ZSTD_finalizeOffCode(rawOffset, updatedRepcodes.rep, ll0);
5909             updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep, offCode, ll0);
5910         }
5911 
5912         if (cctx->appliedParams.validateSequences) {
5913             seqPos->posInSrc += litLength + matchLength;
5914             FORWARD_IF_ERROR(ZSTD_validateSequence(offCode, matchLength, seqPos->posInSrc,
5915                                                    cctx->appliedParams.cParams.windowLog, dictSize,
5916                                                    cctx->appliedParams.cParams.minMatch),
5917                                                    "Sequence validation failed");
5918         }
5919         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offCode, matchLength, litLength);
5920         RETURN_ERROR_IF(idx - seqPos->idx > cctx->seqStore.maxNbSeq, memory_allocation,
5921                         "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
5922         ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offCode, matchLength - MINMATCH);
5923         ip += matchLength + litLength;
5924     }
5925     DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
5926     assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
5927     seqPos->idx = idx;
5928     seqPos->posInSequence = endPosInSequence;
5929     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
5930 
5931     iend -= bytesAdjustment;
5932     if (ip != iend) {
5933         /* Store any last literals */
5934         U32 lastLLSize = (U32)(iend - ip);
5935         assert(ip <= iend);
5936         DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);
5937         ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);
5938         seqPos->posInSrc += lastLLSize;
5939     }
5940 
5941     return bytesAdjustment;
5942 }
5943 
5944 typedef size_t (*ZSTD_sequenceCopier) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
5945                                        const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
5946                                        const void* src, size_t blockSize);
ZSTD_selectSequenceCopier(ZSTD_sequenceFormat_e mode)5947 static ZSTD_sequenceCopier ZSTD_selectSequenceCopier(ZSTD_sequenceFormat_e mode) {
5948     ZSTD_sequenceCopier sequenceCopier = NULL;
5949     assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, mode));
5950     if (mode == ZSTD_sf_explicitBlockDelimiters) {
5951         return ZSTD_copySequencesToSeqStoreExplicitBlockDelim;
5952     } else if (mode == ZSTD_sf_noBlockDelimiters) {
5953         return ZSTD_copySequencesToSeqStoreNoBlockDelim;
5954     }
5955     assert(sequenceCopier != NULL);
5956     return sequenceCopier;
5957 }
5958 
5959 /* Compress, block-by-block, all of the sequences given.
5960  *
5961  * Returns the cumulative size of all compressed blocks (including their headers), otherwise a ZSTD error.
5962  */
ZSTD_compressSequences_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * src,size_t srcSize)5963 static size_t ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
5964                                               void* dst, size_t dstCapacity,
5965                                               const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
5966                                               const void* src, size_t srcSize) {
5967     size_t cSize = 0;
5968     U32 lastBlock;
5969     size_t blockSize;
5970     size_t compressedSeqsSize;
5971     size_t remaining = srcSize;
5972     ZSTD_sequencePosition seqPos = {0, 0, 0};
5973 
5974     BYTE const* ip = (BYTE const*)src;
5975     BYTE* op = (BYTE*)dst;
5976     ZSTD_sequenceCopier sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
5977 
5978     DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
5979     /* Special case: empty frame */
5980     if (remaining == 0) {
5981         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
5982         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
5983         MEM_writeLE32(op, cBlockHeader24);
5984         op += ZSTD_blockHeaderSize;
5985         dstCapacity -= ZSTD_blockHeaderSize;
5986         cSize += ZSTD_blockHeaderSize;
5987     }
5988 
5989     while (remaining) {
5990         size_t cBlockSize;
5991         size_t additionalByteAdjustment;
5992         lastBlock = remaining <= cctx->blockSize;
5993         blockSize = lastBlock ? (U32)remaining : (U32)cctx->blockSize;
5994         ZSTD_resetSeqStore(&cctx->seqStore);
5995         DEBUGLOG(4, "Working on new block. Blocksize: %zu", blockSize);
5996 
5997         additionalByteAdjustment = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize);
5998         FORWARD_IF_ERROR(additionalByteAdjustment, "Bad sequence copy");
5999         blockSize -= additionalByteAdjustment;
6000 
6001         /* If blocks are too small, emit as a nocompress block */
6002         if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
6003             cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
6004             FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
6005             DEBUGLOG(4, "Block too small, writing out nocompress block: cSize: %zu", cBlockSize);
6006             cSize += cBlockSize;
6007             ip += blockSize;
6008             op += cBlockSize;
6009             remaining -= blockSize;
6010             dstCapacity -= cBlockSize;
6011             continue;
6012         }
6013 
6014         compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
6015                                 &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
6016                                 &cctx->appliedParams,
6017                                 op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
6018                                 blockSize,
6019                                 cctx->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
6020                                 cctx->bmi2);
6021         FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
6022         DEBUGLOG(4, "Compressed sequences size: %zu", compressedSeqsSize);
6023 
6024         if (!cctx->isFirstBlock &&
6025             ZSTD_maybeRLE(&cctx->seqStore) &&
6026             ZSTD_isRLE((BYTE const*)src, srcSize)) {
6027             /* We don't want to emit our first block as a RLE even if it qualifies because
6028             * doing so will cause the decoder (cli only) to throw a "should consume all input error."
6029             * This is only an issue for zstd <= v1.4.3
6030             */
6031             compressedSeqsSize = 1;
6032         }
6033 
6034         if (compressedSeqsSize == 0) {
6035             /* ZSTD_noCompressBlock writes the block header as well */
6036             cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
6037             FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
6038             DEBUGLOG(4, "Writing out nocompress block, size: %zu", cBlockSize);
6039         } else if (compressedSeqsSize == 1) {
6040             cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
6041             FORWARD_IF_ERROR(cBlockSize, "RLE compress block failed");
6042             DEBUGLOG(4, "Writing out RLE block, size: %zu", cBlockSize);
6043         } else {
6044             U32 cBlockHeader;
6045             /* Error checking and repcodes update */
6046             ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
6047             if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
6048                 cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
6049 
6050             /* Write block header into beginning of block*/
6051             cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
6052             MEM_writeLE24(op, cBlockHeader);
6053             cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
6054             DEBUGLOG(4, "Writing out compressed block, size: %zu", cBlockSize);
6055         }
6056 
6057         cSize += cBlockSize;
6058         DEBUGLOG(4, "cSize running total: %zu", cSize);
6059 
6060         if (lastBlock) {
6061             break;
6062         } else {
6063             ip += blockSize;
6064             op += cBlockSize;
6065             remaining -= blockSize;
6066             dstCapacity -= cBlockSize;
6067             cctx->isFirstBlock = 0;
6068         }
6069     }
6070 
6071     return cSize;
6072 }
6073 
ZSTD_compressSequences(ZSTD_CCtx * const cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * src,size_t srcSize)6074 size_t ZSTD_compressSequences(ZSTD_CCtx* const cctx, void* dst, size_t dstCapacity,
6075                               const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
6076                               const void* src, size_t srcSize) {
6077     BYTE* op = (BYTE*)dst;
6078     size_t cSize = 0;
6079     size_t compressedBlocksSize = 0;
6080     size_t frameHeaderSize = 0;
6081 
6082     /* Transparent initialization stage, same as compressStream2() */
6083     DEBUGLOG(3, "ZSTD_compressSequences()");
6084     assert(cctx != NULL);
6085     FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
6086     /* Begin writing output, starting with frame header */
6087     frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, srcSize, cctx->dictID);
6088     op += frameHeaderSize;
6089     dstCapacity -= frameHeaderSize;
6090     cSize += frameHeaderSize;
6091     if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
6092         XXH64_update(&cctx->xxhState, src, srcSize);
6093     }
6094     /* cSize includes block header size and compressed sequences size */
6095     compressedBlocksSize = ZSTD_compressSequences_internal(cctx,
6096                                                            op, dstCapacity,
6097                                                            inSeqs, inSeqsSize,
6098                                                            src, srcSize);
6099     FORWARD_IF_ERROR(compressedBlocksSize, "Compressing blocks failed!");
6100     cSize += compressedBlocksSize;
6101     dstCapacity -= compressedBlocksSize;
6102 
6103     if (cctx->appliedParams.fParams.checksumFlag) {
6104         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
6105         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
6106         DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
6107         MEM_writeLE32((char*)dst + cSize, checksum);
6108         cSize += 4;
6109     }
6110 
6111     DEBUGLOG(3, "Final compressed size: %zu", cSize);
6112     return cSize;
6113 }
6114 
6115 /*======   Finalize   ======*/
6116 
6117 /*! ZSTD_flushStream() :
6118  * @return : amount of data remaining to flush */
ZSTD_flushStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output)6119 size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
6120 {
6121     ZSTD_inBuffer input = { NULL, 0, 0 };
6122     return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
6123 }
6124 
6125 
ZSTD_endStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output)6126 size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
6127 {
6128     ZSTD_inBuffer input = { NULL, 0, 0 };
6129     size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
6130     FORWARD_IF_ERROR( remainingToFlush , "ZSTD_compressStream2 failed");
6131     if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush;   /* minimal estimation */
6132     /* single thread mode : attempt to calculate remaining to flush more precisely */
6133     {   size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
6134         size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);
6135         size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
6136         DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
6137         return toFlush;
6138     }
6139 }
6140 
6141 
6142 /*-=====  Pre-defined compression levels  =====-*/
6143 
6144 #define ZSTD_MAX_CLEVEL     22
ZSTD_maxCLevel(void)6145 int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
ZSTD_minCLevel(void)6146 int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
ZSTD_defaultCLevel(void)6147 int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }
6148 
6149 static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
6150 {   /* "default" - for any srcSize > 256 KB */
6151     /* W,  C,  H,  S,  L, TL, strat */
6152     { 19, 12, 13,  1,  6,  1, ZSTD_fast    },  /* base for negative levels */
6153     { 19, 13, 14,  1,  7,  0, ZSTD_fast    },  /* level  1 */
6154     { 20, 15, 16,  1,  6,  0, ZSTD_fast    },  /* level  2 */
6155     { 21, 16, 17,  1,  5,  0, ZSTD_dfast   },  /* level  3 */
6156     { 21, 18, 18,  1,  5,  0, ZSTD_dfast   },  /* level  4 */
6157     { 21, 18, 19,  2,  5,  2, ZSTD_greedy  },  /* level  5 */
6158     { 21, 19, 19,  3,  5,  4, ZSTD_greedy  },  /* level  6 */
6159     { 21, 19, 19,  3,  5,  8, ZSTD_lazy    },  /* level  7 */
6160     { 21, 19, 19,  3,  5, 16, ZSTD_lazy2   },  /* level  8 */
6161     { 21, 19, 20,  4,  5, 16, ZSTD_lazy2   },  /* level  9 */
6162     { 22, 20, 21,  4,  5, 16, ZSTD_lazy2   },  /* level 10 */
6163     { 22, 21, 22,  4,  5, 16, ZSTD_lazy2   },  /* level 11 */
6164     { 22, 21, 22,  5,  5, 16, ZSTD_lazy2   },  /* level 12 */
6165     { 22, 21, 22,  5,  5, 32, ZSTD_btlazy2 },  /* level 13 */
6166     { 22, 22, 23,  5,  5, 32, ZSTD_btlazy2 },  /* level 14 */
6167     { 22, 23, 23,  6,  5, 32, ZSTD_btlazy2 },  /* level 15 */
6168     { 22, 22, 22,  5,  5, 48, ZSTD_btopt   },  /* level 16 */
6169     { 23, 23, 22,  5,  4, 64, ZSTD_btopt   },  /* level 17 */
6170     { 23, 23, 22,  6,  3, 64, ZSTD_btultra },  /* level 18 */
6171     { 23, 24, 22,  7,  3,256, ZSTD_btultra2},  /* level 19 */
6172     { 25, 25, 23,  7,  3,256, ZSTD_btultra2},  /* level 20 */
6173     { 26, 26, 24,  7,  3,512, ZSTD_btultra2},  /* level 21 */
6174     { 27, 27, 25,  9,  3,999, ZSTD_btultra2},  /* level 22 */
6175 },
6176 {   /* for srcSize <= 256 KB */
6177     /* W,  C,  H,  S,  L,  T, strat */
6178     { 18, 12, 13,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
6179     { 18, 13, 14,  1,  6,  0, ZSTD_fast    },  /* level  1 */
6180     { 18, 14, 14,  1,  5,  0, ZSTD_dfast   },  /* level  2 */
6181     { 18, 16, 16,  1,  4,  0, ZSTD_dfast   },  /* level  3 */
6182     { 18, 16, 17,  2,  5,  2, ZSTD_greedy  },  /* level  4.*/
6183     { 18, 18, 18,  3,  5,  2, ZSTD_greedy  },  /* level  5.*/
6184     { 18, 18, 19,  3,  5,  4, ZSTD_lazy    },  /* level  6.*/
6185     { 18, 18, 19,  4,  4,  4, ZSTD_lazy    },  /* level  7 */
6186     { 18, 18, 19,  4,  4,  8, ZSTD_lazy2   },  /* level  8 */
6187     { 18, 18, 19,  5,  4,  8, ZSTD_lazy2   },  /* level  9 */
6188     { 18, 18, 19,  6,  4,  8, ZSTD_lazy2   },  /* level 10 */
6189     { 18, 18, 19,  5,  4, 12, ZSTD_btlazy2 },  /* level 11.*/
6190     { 18, 19, 19,  7,  4, 12, ZSTD_btlazy2 },  /* level 12.*/
6191     { 18, 18, 19,  4,  4, 16, ZSTD_btopt   },  /* level 13 */
6192     { 18, 18, 19,  4,  3, 32, ZSTD_btopt   },  /* level 14.*/
6193     { 18, 18, 19,  6,  3,128, ZSTD_btopt   },  /* level 15.*/
6194     { 18, 19, 19,  6,  3,128, ZSTD_btultra },  /* level 16.*/
6195     { 18, 19, 19,  8,  3,256, ZSTD_btultra },  /* level 17.*/
6196     { 18, 19, 19,  6,  3,128, ZSTD_btultra2},  /* level 18.*/
6197     { 18, 19, 19,  8,  3,256, ZSTD_btultra2},  /* level 19.*/
6198     { 18, 19, 19, 10,  3,512, ZSTD_btultra2},  /* level 20.*/
6199     { 18, 19, 19, 12,  3,512, ZSTD_btultra2},  /* level 21.*/
6200     { 18, 19, 19, 13,  3,999, ZSTD_btultra2},  /* level 22.*/
6201 },
6202 {   /* for srcSize <= 128 KB */
6203     /* W,  C,  H,  S,  L,  T, strat */
6204     { 17, 12, 12,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
6205     { 17, 12, 13,  1,  6,  0, ZSTD_fast    },  /* level  1 */
6206     { 17, 13, 15,  1,  5,  0, ZSTD_fast    },  /* level  2 */
6207     { 17, 15, 16,  2,  5,  0, ZSTD_dfast   },  /* level  3 */
6208     { 17, 17, 17,  2,  4,  0, ZSTD_dfast   },  /* level  4 */
6209     { 17, 16, 17,  3,  4,  2, ZSTD_greedy  },  /* level  5 */
6210     { 17, 17, 17,  3,  4,  4, ZSTD_lazy    },  /* level  6 */
6211     { 17, 17, 17,  3,  4,  8, ZSTD_lazy2   },  /* level  7 */
6212     { 17, 17, 17,  4,  4,  8, ZSTD_lazy2   },  /* level  8 */
6213     { 17, 17, 17,  5,  4,  8, ZSTD_lazy2   },  /* level  9 */
6214     { 17, 17, 17,  6,  4,  8, ZSTD_lazy2   },  /* level 10 */
6215     { 17, 17, 17,  5,  4,  8, ZSTD_btlazy2 },  /* level 11 */
6216     { 17, 18, 17,  7,  4, 12, ZSTD_btlazy2 },  /* level 12 */
6217     { 17, 18, 17,  3,  4, 12, ZSTD_btopt   },  /* level 13.*/
6218     { 17, 18, 17,  4,  3, 32, ZSTD_btopt   },  /* level 14.*/
6219     { 17, 18, 17,  6,  3,256, ZSTD_btopt   },  /* level 15.*/
6220     { 17, 18, 17,  6,  3,128, ZSTD_btultra },  /* level 16.*/
6221     { 17, 18, 17,  8,  3,256, ZSTD_btultra },  /* level 17.*/
6222     { 17, 18, 17, 10,  3,512, ZSTD_btultra },  /* level 18.*/
6223     { 17, 18, 17,  5,  3,256, ZSTD_btultra2},  /* level 19.*/
6224     { 17, 18, 17,  7,  3,512, ZSTD_btultra2},  /* level 20.*/
6225     { 17, 18, 17,  9,  3,512, ZSTD_btultra2},  /* level 21.*/
6226     { 17, 18, 17, 11,  3,999, ZSTD_btultra2},  /* level 22.*/
6227 },
6228 {   /* for srcSize <= 16 KB */
6229     /* W,  C,  H,  S,  L,  T, strat */
6230     { 14, 12, 13,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
6231     { 14, 14, 15,  1,  5,  0, ZSTD_fast    },  /* level  1 */
6232     { 14, 14, 15,  1,  4,  0, ZSTD_fast    },  /* level  2 */
6233     { 14, 14, 15,  2,  4,  0, ZSTD_dfast   },  /* level  3 */
6234     { 14, 14, 14,  4,  4,  2, ZSTD_greedy  },  /* level  4 */
6235     { 14, 14, 14,  3,  4,  4, ZSTD_lazy    },  /* level  5.*/
6236     { 14, 14, 14,  4,  4,  8, ZSTD_lazy2   },  /* level  6 */
6237     { 14, 14, 14,  6,  4,  8, ZSTD_lazy2   },  /* level  7 */
6238     { 14, 14, 14,  8,  4,  8, ZSTD_lazy2   },  /* level  8.*/
6239     { 14, 15, 14,  5,  4,  8, ZSTD_btlazy2 },  /* level  9.*/
6240     { 14, 15, 14,  9,  4,  8, ZSTD_btlazy2 },  /* level 10.*/
6241     { 14, 15, 14,  3,  4, 12, ZSTD_btopt   },  /* level 11.*/
6242     { 14, 15, 14,  4,  3, 24, ZSTD_btopt   },  /* level 12.*/
6243     { 14, 15, 14,  5,  3, 32, ZSTD_btultra },  /* level 13.*/
6244     { 14, 15, 15,  6,  3, 64, ZSTD_btultra },  /* level 14.*/
6245     { 14, 15, 15,  7,  3,256, ZSTD_btultra },  /* level 15.*/
6246     { 14, 15, 15,  5,  3, 48, ZSTD_btultra2},  /* level 16.*/
6247     { 14, 15, 15,  6,  3,128, ZSTD_btultra2},  /* level 17.*/
6248     { 14, 15, 15,  7,  3,256, ZSTD_btultra2},  /* level 18.*/
6249     { 14, 15, 15,  8,  3,256, ZSTD_btultra2},  /* level 19.*/
6250     { 14, 15, 15,  8,  3,512, ZSTD_btultra2},  /* level 20.*/
6251     { 14, 15, 15,  9,  3,512, ZSTD_btultra2},  /* level 21.*/
6252     { 14, 15, 15, 10,  3,999, ZSTD_btultra2},  /* level 22.*/
6253 },
6254 };
6255 
ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel,size_t const dictSize)6256 static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
6257 {
6258     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
6259     switch (cParams.strategy) {
6260         case ZSTD_fast:
6261         case ZSTD_dfast:
6262             break;
6263         case ZSTD_greedy:
6264         case ZSTD_lazy:
6265         case ZSTD_lazy2:
6266             cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;
6267             break;
6268         case ZSTD_btlazy2:
6269         case ZSTD_btopt:
6270         case ZSTD_btultra:
6271         case ZSTD_btultra2:
6272             break;
6273     }
6274     return cParams;
6275 }
6276 
ZSTD_dedicatedDictSearch_isSupported(ZSTD_compressionParameters const * cParams)6277 static int ZSTD_dedicatedDictSearch_isSupported(
6278         ZSTD_compressionParameters const* cParams)
6279 {
6280     return (cParams->strategy >= ZSTD_greedy)
6281         && (cParams->strategy <= ZSTD_lazy2)
6282         && (cParams->hashLog > cParams->chainLog)
6283         && (cParams->chainLog <= 24);
6284 }
6285 
6286 /**
6287  * Reverses the adjustment applied to cparams when enabling dedicated dict
6288  * search. This is used to recover the params set to be used in the working
6289  * context. (Otherwise, those tables would also grow.)
6290  */
ZSTD_dedicatedDictSearch_revertCParams(ZSTD_compressionParameters * cParams)6291 static void ZSTD_dedicatedDictSearch_revertCParams(
6292         ZSTD_compressionParameters* cParams) {
6293     switch (cParams->strategy) {
6294         case ZSTD_fast:
6295         case ZSTD_dfast:
6296             break;
6297         case ZSTD_greedy:
6298         case ZSTD_lazy:
6299         case ZSTD_lazy2:
6300             cParams->hashLog -= ZSTD_LAZY_DDSS_BUCKET_LOG;
6301             if (cParams->hashLog < ZSTD_HASHLOG_MIN) {
6302                 cParams->hashLog = ZSTD_HASHLOG_MIN;
6303             }
6304             break;
6305         case ZSTD_btlazy2:
6306         case ZSTD_btopt:
6307         case ZSTD_btultra:
6308         case ZSTD_btultra2:
6309             break;
6310     }
6311 }
6312 
ZSTD_getCParamRowSize(U64 srcSizeHint,size_t dictSize,ZSTD_cParamMode_e mode)6313 static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
6314 {
6315     switch (mode) {
6316     case ZSTD_cpm_unknown:
6317     case ZSTD_cpm_noAttachDict:
6318     case ZSTD_cpm_createCDict:
6319         break;
6320     case ZSTD_cpm_attachDict:
6321         dictSize = 0;
6322         break;
6323     default:
6324         assert(0);
6325         break;
6326     }
6327     {   int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;
6328         size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;
6329         return unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;
6330     }
6331 }
6332 
6333 /*! ZSTD_getCParams_internal() :
6334  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
6335  *  Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
6336  *        Use dictSize == 0 for unknown or unused.
6337  *  Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_cParamMode_e`. */
ZSTD_getCParams_internal(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize,ZSTD_cParamMode_e mode)6338 static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
6339 {
6340     U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
6341     U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
6342     int row;
6343     DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
6344 
6345     /* row */
6346     if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT;   /* 0 == default */
6347     else if (compressionLevel < 0) row = 0;   /* entry 0 is baseline for fast mode */
6348     else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
6349     else row = compressionLevel;
6350 
6351     {   ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
6352         DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);
6353         /* acceleration factor */
6354         if (compressionLevel < 0) {
6355             int const clampedCompressionLevel = MAX(ZSTD_minCLevel(), compressionLevel);
6356             cp.targetLength = (unsigned)(-clampedCompressionLevel);
6357         }
6358         /* refine parameters based on srcSize & dictSize */
6359         return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode);
6360     }
6361 }
6362 
6363 /*! ZSTD_getCParams() :
6364  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
6365  *  Size values are optional, provide 0 if not known or unused */
ZSTD_getCParams(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize)6366 ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
6367 {
6368     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
6369     return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
6370 }
6371 
6372 /*! ZSTD_getParams() :
6373  *  same idea as ZSTD_getCParams()
6374  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
6375  *  Fields of `ZSTD_frameParameters` are set to default values */
ZSTD_getParams_internal(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize,ZSTD_cParamMode_e mode)6376 static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode) {
6377     ZSTD_parameters params;
6378     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
6379     DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
6380     ZSTD_memset(&params, 0, sizeof(params));
6381     params.cParams = cParams;
6382     params.fParams.contentSizeFlag = 1;
6383     return params;
6384 }
6385 
6386 /*! ZSTD_getParams() :
6387  *  same idea as ZSTD_getCParams()
6388  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
6389  *  Fields of `ZSTD_frameParameters` are set to default values */
ZSTD_getParams(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize)6390 ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
6391     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
6392     return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
6393 }
6394