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(_M_AMD64)  || 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         ZSTD_window_enforceMaxDist(&ms->window, ip, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
3919 
3920         /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
3921         if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
3922 
3923         {   size_t cSize;
3924             if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
3925                 cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
3926                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
3927                 assert(cSize > 0);
3928                 assert(cSize <= blockSize + ZSTD_blockHeaderSize);
3929             } else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
3930                 cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
3931                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
3932                 assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
3933             } else {
3934                 cSize = ZSTD_compressBlock_internal(cctx,
3935                                         op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
3936                                         ip, blockSize, 1 /* frame */);
3937                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
3938 
3939                 if (cSize == 0) {  /* block is not compressible */
3940                     cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
3941                     FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
3942                 } else {
3943                     U32 const cBlockHeader = cSize == 1 ?
3944                         lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
3945                         lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
3946                     MEM_writeLE24(op, cBlockHeader);
3947                     cSize += ZSTD_blockHeaderSize;
3948                 }
3949             }
3950 
3951 
3952             ip += blockSize;
3953             assert(remaining >= blockSize);
3954             remaining -= blockSize;
3955             op += cSize;
3956             assert(dstCapacity >= cSize);
3957             dstCapacity -= cSize;
3958             cctx->isFirstBlock = 0;
3959             DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
3960                         (unsigned)cSize);
3961     }   }
3962 
3963     if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
3964     return (size_t)(op-ostart);
3965 }
3966 
3967 
ZSTD_writeFrameHeader(void * dst,size_t dstCapacity,const ZSTD_CCtx_params * params,U64 pledgedSrcSize,U32 dictID)3968 static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
3969                                     const ZSTD_CCtx_params* params, U64 pledgedSrcSize, U32 dictID)
3970 {   BYTE* const op = (BYTE*)dst;
3971     U32   const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536);   /* 0-3 */
3972     U32   const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength;   /* 0-3 */
3973     U32   const checksumFlag = params->fParams.checksumFlag>0;
3974     U32   const windowSize = (U32)1 << params->cParams.windowLog;
3975     U32   const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
3976     BYTE  const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
3977     U32   const fcsCode = params->fParams.contentSizeFlag ?
3978                      (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0;  /* 0-3 */
3979     BYTE  const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
3980     size_t pos=0;
3981 
3982     assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
3983     RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
3984                     "dst buf is too small to fit worst-case frame header size.");
3985     DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
3986                 !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
3987     if (params->format == ZSTD_f_zstd1) {
3988         MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
3989         pos = 4;
3990     }
3991     op[pos++] = frameHeaderDescriptionByte;
3992     if (!singleSegment) op[pos++] = windowLogByte;
3993     switch(dictIDSizeCode)
3994     {
3995         default:  assert(0); /* impossible */
3996         case 0 : break;
3997         case 1 : op[pos] = (BYTE)(dictID); pos++; break;
3998         case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
3999         case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
4000     }
4001     switch(fcsCode)
4002     {
4003         default:  assert(0); /* impossible */
4004         case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
4005         case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
4006         case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
4007         case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
4008     }
4009     return pos;
4010 }
4011 
4012 /* ZSTD_writeSkippableFrame_advanced() :
4013  * Writes out a skippable frame with the specified magic number variant (16 are supported),
4014  * from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15, and the desired source data.
4015  *
4016  * Returns the total number of bytes written, or a ZSTD error code.
4017  */
ZSTD_writeSkippableFrame(void * dst,size_t dstCapacity,const void * src,size_t srcSize,unsigned magicVariant)4018 size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
4019                                 const void* src, size_t srcSize, unsigned magicVariant) {
4020     BYTE* op = (BYTE*)dst;
4021     RETURN_ERROR_IF(dstCapacity < srcSize + ZSTD_SKIPPABLEHEADERSIZE /* Skippable frame overhead */,
4022                     dstSize_tooSmall, "Not enough room for skippable frame");
4023     RETURN_ERROR_IF(srcSize > (unsigned)0xFFFFFFFF, srcSize_wrong, "Src size too large for skippable frame");
4024     RETURN_ERROR_IF(magicVariant > 15, parameter_outOfBound, "Skippable frame magic number variant not supported");
4025 
4026     MEM_writeLE32(op, (U32)(ZSTD_MAGIC_SKIPPABLE_START + magicVariant));
4027     MEM_writeLE32(op+4, (U32)srcSize);
4028     ZSTD_memcpy(op+8, src, srcSize);
4029     return srcSize + ZSTD_SKIPPABLEHEADERSIZE;
4030 }
4031 
4032 /* ZSTD_writeLastEmptyBlock() :
4033  * output an empty Block with end-of-frame mark to complete a frame
4034  * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
4035  *           or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
4036  */
ZSTD_writeLastEmptyBlock(void * dst,size_t dstCapacity)4037 size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
4038 {
4039     RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall,
4040                     "dst buf is too small to write frame trailer empty block.");
4041     {   U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1);  /* 0 size */
4042         MEM_writeLE24(dst, cBlockHeader24);
4043         return ZSTD_blockHeaderSize;
4044     }
4045 }
4046 
ZSTD_referenceExternalSequences(ZSTD_CCtx * cctx,rawSeq * seq,size_t nbSeq)4047 size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
4048 {
4049     RETURN_ERROR_IF(cctx->stage != ZSTDcs_init, stage_wrong,
4050                     "wrong cctx stage");
4051     RETURN_ERROR_IF(cctx->appliedParams.ldmParams.enableLdm,
4052                     parameter_unsupported,
4053                     "incompatible with ldm");
4054     cctx->externSeqStore.seq = seq;
4055     cctx->externSeqStore.size = nbSeq;
4056     cctx->externSeqStore.capacity = nbSeq;
4057     cctx->externSeqStore.pos = 0;
4058     cctx->externSeqStore.posInSequence = 0;
4059     return 0;
4060 }
4061 
4062 
ZSTD_compressContinue_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 frame,U32 lastFrameChunk)4063 static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
4064                               void* dst, size_t dstCapacity,
4065                         const void* src, size_t srcSize,
4066                                U32 frame, U32 lastFrameChunk)
4067 {
4068     ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
4069     size_t fhSize = 0;
4070 
4071     DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
4072                 cctx->stage, (unsigned)srcSize);
4073     RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
4074                     "missing init (ZSTD_compressBegin)");
4075 
4076     if (frame && (cctx->stage==ZSTDcs_init)) {
4077         fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
4078                                        cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
4079         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
4080         assert(fhSize <= dstCapacity);
4081         dstCapacity -= fhSize;
4082         dst = (char*)dst + fhSize;
4083         cctx->stage = ZSTDcs_ongoing;
4084     }
4085 
4086     if (!srcSize) return fhSize;  /* do not generate an empty block if no input */
4087 
4088     if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
4089         ms->forceNonContiguous = 0;
4090         ms->nextToUpdate = ms->window.dictLimit;
4091     }
4092     if (cctx->appliedParams.ldmParams.enableLdm) {
4093         ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
4094     }
4095 
4096     if (!frame) {
4097         /* overflow check and correction for block mode */
4098         ZSTD_overflowCorrectIfNeeded(
4099             ms, &cctx->workspace, &cctx->appliedParams,
4100             src, (BYTE const*)src + srcSize);
4101     }
4102 
4103     DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
4104     {   size_t const cSize = frame ?
4105                              ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
4106                              ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
4107         FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
4108         cctx->consumedSrcSize += srcSize;
4109         cctx->producedCSize += (cSize + fhSize);
4110         assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
4111         if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
4112             ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
4113             RETURN_ERROR_IF(
4114                 cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
4115                 srcSize_wrong,
4116                 "error : pledgedSrcSize = %u, while realSrcSize >= %u",
4117                 (unsigned)cctx->pledgedSrcSizePlusOne-1,
4118                 (unsigned)cctx->consumedSrcSize);
4119         }
4120         return cSize + fhSize;
4121     }
4122 }
4123 
ZSTD_compressContinue(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4124 size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
4125                               void* dst, size_t dstCapacity,
4126                         const void* src, size_t srcSize)
4127 {
4128     DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
4129     return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
4130 }
4131 
4132 
ZSTD_getBlockSize(const ZSTD_CCtx * cctx)4133 size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
4134 {
4135     ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
4136     assert(!ZSTD_checkCParams(cParams));
4137     return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
4138 }
4139 
ZSTD_compressBlock(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4140 size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
4141 {
4142     DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
4143     { size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
4144       RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
4145 
4146     return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
4147 }
4148 
4149 /*! ZSTD_loadDictionaryContent() :
4150  *  @return : 0, or an error code
4151  */
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)4152 static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
4153                                          ldmState_t* ls,
4154                                          ZSTD_cwksp* ws,
4155                                          ZSTD_CCtx_params const* params,
4156                                          const void* src, size_t srcSize,
4157                                          ZSTD_dictTableLoadMethod_e dtlm)
4158 {
4159     const BYTE* ip = (const BYTE*) src;
4160     const BYTE* const iend = ip + srcSize;
4161     int const loadLdmDict = params->ldmParams.enableLdm && ls != NULL;
4162 
4163     /* Assert that we the ms params match the params we're being given */
4164     ZSTD_assertEqualCParams(params->cParams, ms->cParams);
4165 
4166     if (srcSize > ZSTD_CHUNKSIZE_MAX) {
4167         /* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
4168          * Dictionaries right at the edge will immediately trigger overflow
4169          * correction, but I don't want to insert extra constraints here.
4170          */
4171         U32 const maxDictSize = ZSTD_CURRENT_MAX - 1;
4172         /* We must have cleared our windows when our source is this large. */
4173         assert(ZSTD_window_isEmpty(ms->window));
4174         if (loadLdmDict)
4175             assert(ZSTD_window_isEmpty(ls->window));
4176         /* If the dictionary is too large, only load the suffix of the dictionary. */
4177         if (srcSize > maxDictSize) {
4178             ip = iend - maxDictSize;
4179             src = ip;
4180             srcSize = maxDictSize;
4181         }
4182     }
4183 
4184     DEBUGLOG(4, "ZSTD_loadDictionaryContent(): useRowMatchFinder=%d", (int)params->useRowMatchFinder);
4185     ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
4186     ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
4187     ms->forceNonContiguous = params->deterministicRefPrefix;
4188 
4189     if (loadLdmDict) {
4190         ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
4191         ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
4192     }
4193 
4194     if (srcSize <= HASH_READ_SIZE) return 0;
4195 
4196     ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
4197 
4198     if (loadLdmDict)
4199         ZSTD_ldm_fillHashTable(ls, ip, iend, &params->ldmParams);
4200 
4201     switch(params->cParams.strategy)
4202     {
4203     case ZSTD_fast:
4204         ZSTD_fillHashTable(ms, iend, dtlm);
4205         break;
4206     case ZSTD_dfast:
4207         ZSTD_fillDoubleHashTable(ms, iend, dtlm);
4208         break;
4209 
4210     case ZSTD_greedy:
4211     case ZSTD_lazy:
4212     case ZSTD_lazy2:
4213         assert(srcSize >= HASH_READ_SIZE);
4214         if (ms->dedicatedDictSearch) {
4215             assert(ms->chainTable != NULL);
4216             ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
4217         } else {
4218             assert(params->useRowMatchFinder != ZSTD_urm_auto);
4219             if (params->useRowMatchFinder == ZSTD_urm_enableRowMatchFinder) {
4220                 size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog) * sizeof(U16);
4221                 ZSTD_memset(ms->tagTable, 0, tagTableSize);
4222                 ZSTD_row_update(ms, iend-HASH_READ_SIZE);
4223                 DEBUGLOG(4, "Using row-based hash table for lazy dict");
4224             } else {
4225                 ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
4226                 DEBUGLOG(4, "Using chain-based hash table for lazy dict");
4227             }
4228         }
4229         break;
4230 
4231     case ZSTD_btlazy2:   /* we want the dictionary table fully sorted */
4232     case ZSTD_btopt:
4233     case ZSTD_btultra:
4234     case ZSTD_btultra2:
4235         assert(srcSize >= HASH_READ_SIZE);
4236         ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
4237         break;
4238 
4239     default:
4240         assert(0);  /* not possible : not a valid strategy id */
4241     }
4242 
4243     ms->nextToUpdate = (U32)(iend - ms->window.base);
4244     return 0;
4245 }
4246 
4247 
4248 /* Dictionaries that assign zero probability to symbols that show up causes problems
4249  * when FSE encoding. Mark dictionaries with zero probability symbols as FSE_repeat_check
4250  * and only dictionaries with 100% valid symbols can be assumed valid.
4251  */
ZSTD_dictNCountRepeat(short * normalizedCounter,unsigned dictMaxSymbolValue,unsigned maxSymbolValue)4252 static FSE_repeat ZSTD_dictNCountRepeat(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)
4253 {
4254     U32 s;
4255     if (dictMaxSymbolValue < maxSymbolValue) {
4256         return FSE_repeat_check;
4257     }
4258     for (s = 0; s <= maxSymbolValue; ++s) {
4259         if (normalizedCounter[s] == 0) {
4260             return FSE_repeat_check;
4261         }
4262     }
4263     return FSE_repeat_valid;
4264 }
4265 
ZSTD_loadCEntropy(ZSTD_compressedBlockState_t * bs,void * workspace,const void * const dict,size_t dictSize)4266 size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
4267                          const void* const dict, size_t dictSize)
4268 {
4269     short offcodeNCount[MaxOff+1];
4270     unsigned offcodeMaxValue = MaxOff;
4271     const BYTE* dictPtr = (const BYTE*)dict;    /* skip magic num and dict ID */
4272     const BYTE* const dictEnd = dictPtr + dictSize;
4273     dictPtr += 8;
4274     bs->entropy.huf.repeatMode = HUF_repeat_check;
4275 
4276     {   unsigned maxSymbolValue = 255;
4277         unsigned hasZeroWeights = 1;
4278         size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
4279             dictEnd-dictPtr, &hasZeroWeights);
4280 
4281         /* We only set the loaded table as valid if it contains all non-zero
4282          * weights. Otherwise, we set it to check */
4283         if (!hasZeroWeights)
4284             bs->entropy.huf.repeatMode = HUF_repeat_valid;
4285 
4286         RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
4287         RETURN_ERROR_IF(maxSymbolValue < 255, dictionary_corrupted, "");
4288         dictPtr += hufHeaderSize;
4289     }
4290 
4291     {   unsigned offcodeLog;
4292         size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
4293         RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
4294         RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
4295         /* fill all offset symbols to avoid garbage at end of table */
4296         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
4297                 bs->entropy.fse.offcodeCTable,
4298                 offcodeNCount, MaxOff, offcodeLog,
4299                 workspace, HUF_WORKSPACE_SIZE)),
4300             dictionary_corrupted, "");
4301         /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
4302         dictPtr += offcodeHeaderSize;
4303     }
4304 
4305     {   short matchlengthNCount[MaxML+1];
4306         unsigned matchlengthMaxValue = MaxML, matchlengthLog;
4307         size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
4308         RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
4309         RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
4310         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
4311                 bs->entropy.fse.matchlengthCTable,
4312                 matchlengthNCount, matchlengthMaxValue, matchlengthLog,
4313                 workspace, HUF_WORKSPACE_SIZE)),
4314             dictionary_corrupted, "");
4315         bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
4316         dictPtr += matchlengthHeaderSize;
4317     }
4318 
4319     {   short litlengthNCount[MaxLL+1];
4320         unsigned litlengthMaxValue = MaxLL, litlengthLog;
4321         size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
4322         RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
4323         RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
4324         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
4325                 bs->entropy.fse.litlengthCTable,
4326                 litlengthNCount, litlengthMaxValue, litlengthLog,
4327                 workspace, HUF_WORKSPACE_SIZE)),
4328             dictionary_corrupted, "");
4329         bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
4330         dictPtr += litlengthHeaderSize;
4331     }
4332 
4333     RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
4334     bs->rep[0] = MEM_readLE32(dictPtr+0);
4335     bs->rep[1] = MEM_readLE32(dictPtr+4);
4336     bs->rep[2] = MEM_readLE32(dictPtr+8);
4337     dictPtr += 12;
4338 
4339     {   size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
4340         U32 offcodeMax = MaxOff;
4341         if (dictContentSize <= ((U32)-1) - 128 KB) {
4342             U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
4343             offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
4344         }
4345         /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
4346         bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
4347 
4348         /* All repCodes must be <= dictContentSize and != 0 */
4349         {   U32 u;
4350             for (u=0; u<3; u++) {
4351                 RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
4352                 RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
4353     }   }   }
4354 
4355     return dictPtr - (const BYTE*)dict;
4356 }
4357 
4358 /* Dictionary format :
4359  * See :
4360  * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
4361  */
4362 /*! ZSTD_loadZstdDictionary() :
4363  * @return : dictID, or an error code
4364  *  assumptions : magic number supposed already checked
4365  *                dictSize supposed >= 8
4366  */
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)4367 static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
4368                                       ZSTD_matchState_t* ms,
4369                                       ZSTD_cwksp* ws,
4370                                       ZSTD_CCtx_params const* params,
4371                                       const void* dict, size_t dictSize,
4372                                       ZSTD_dictTableLoadMethod_e dtlm,
4373                                       void* workspace)
4374 {
4375     const BYTE* dictPtr = (const BYTE*)dict;
4376     const BYTE* const dictEnd = dictPtr + dictSize;
4377     size_t dictID;
4378     size_t eSize;
4379     ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
4380     assert(dictSize >= 8);
4381     assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
4382 
4383     dictID = params->fParams.noDictIDFlag ? 0 :  MEM_readLE32(dictPtr + 4 /* skip magic number */ );
4384     eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
4385     FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
4386     dictPtr += eSize;
4387 
4388     {
4389         size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
4390         FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
4391             ms, NULL, ws, params, dictPtr, dictContentSize, dtlm), "");
4392     }
4393     return dictID;
4394 }
4395 
4396 /** ZSTD_compress_insertDictionary() :
4397 *   @return : dictID, or an error code */
4398 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)4399 ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
4400                                ZSTD_matchState_t* ms,
4401                                ldmState_t* ls,
4402                                ZSTD_cwksp* ws,
4403                          const ZSTD_CCtx_params* params,
4404                          const void* dict, size_t dictSize,
4405                                ZSTD_dictContentType_e dictContentType,
4406                                ZSTD_dictTableLoadMethod_e dtlm,
4407                                void* workspace)
4408 {
4409     DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
4410     if ((dict==NULL) || (dictSize<8)) {
4411         RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
4412         return 0;
4413     }
4414 
4415     ZSTD_reset_compressedBlockState(bs);
4416 
4417     /* dict restricted modes */
4418     if (dictContentType == ZSTD_dct_rawContent)
4419         return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm);
4420 
4421     if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
4422         if (dictContentType == ZSTD_dct_auto) {
4423             DEBUGLOG(4, "raw content dictionary detected");
4424             return ZSTD_loadDictionaryContent(
4425                 ms, ls, ws, params, dict, dictSize, dtlm);
4426         }
4427         RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
4428         assert(0);   /* impossible */
4429     }
4430 
4431     /* dict as full zstd dictionary */
4432     return ZSTD_loadZstdDictionary(
4433         bs, ms, ws, params, dict, dictSize, dtlm, workspace);
4434 }
4435 
4436 #define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
4437 #define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)
4438 
4439 /*! ZSTD_compressBegin_internal() :
4440  * @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)4441 static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
4442                                     const void* dict, size_t dictSize,
4443                                     ZSTD_dictContentType_e dictContentType,
4444                                     ZSTD_dictTableLoadMethod_e dtlm,
4445                                     const ZSTD_CDict* cdict,
4446                                     const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
4447                                     ZSTD_buffered_policy_e zbuff)
4448 {
4449     size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
4450 #if ZSTD_TRACE
4451     cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
4452 #endif
4453     DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
4454     /* params are supposed to be fully validated at this point */
4455     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
4456     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
4457     if ( (cdict)
4458       && (cdict->dictContentSize > 0)
4459       && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
4460         || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
4461         || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
4462         || cdict->compressionLevel == 0)
4463       && (params->attachDictPref != ZSTD_dictForceLoad) ) {
4464         return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
4465     }
4466 
4467     FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
4468                                      dictContentSize,
4469                                      ZSTDcrp_makeClean, zbuff) , "");
4470     {   size_t const dictID = cdict ?
4471                 ZSTD_compress_insertDictionary(
4472                         cctx->blockState.prevCBlock, &cctx->blockState.matchState,
4473                         &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
4474                         cdict->dictContentSize, cdict->dictContentType, dtlm,
4475                         cctx->entropyWorkspace)
4476               : ZSTD_compress_insertDictionary(
4477                         cctx->blockState.prevCBlock, &cctx->blockState.matchState,
4478                         &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
4479                         dictContentType, dtlm, cctx->entropyWorkspace);
4480         FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
4481         assert(dictID <= UINT_MAX);
4482         cctx->dictID = (U32)dictID;
4483         cctx->dictContentSize = dictContentSize;
4484     }
4485     return 0;
4486 }
4487 
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)4488 size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
4489                                     const void* dict, size_t dictSize,
4490                                     ZSTD_dictContentType_e dictContentType,
4491                                     ZSTD_dictTableLoadMethod_e dtlm,
4492                                     const ZSTD_CDict* cdict,
4493                                     const ZSTD_CCtx_params* params,
4494                                     unsigned long long pledgedSrcSize)
4495 {
4496     DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
4497     /* compression parameters verification and optimization */
4498     FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
4499     return ZSTD_compressBegin_internal(cctx,
4500                                        dict, dictSize, dictContentType, dtlm,
4501                                        cdict,
4502                                        params, pledgedSrcSize,
4503                                        ZSTDb_not_buffered);
4504 }
4505 
4506 /*! ZSTD_compressBegin_advanced() :
4507 *   @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)4508 size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
4509                              const void* dict, size_t dictSize,
4510                                    ZSTD_parameters params, unsigned long long pledgedSrcSize)
4511 {
4512     ZSTD_CCtx_params cctxParams;
4513     ZSTD_CCtxParams_init_internal(&cctxParams, &params, ZSTD_NO_CLEVEL);
4514     return ZSTD_compressBegin_advanced_internal(cctx,
4515                                             dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
4516                                             NULL /*cdict*/,
4517                                             &cctxParams, pledgedSrcSize);
4518 }
4519 
ZSTD_compressBegin_usingDict(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,int compressionLevel)4520 size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
4521 {
4522     ZSTD_CCtx_params cctxParams;
4523     {
4524         ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);
4525         ZSTD_CCtxParams_init_internal(&cctxParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
4526     }
4527     DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
4528     return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
4529                                        &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
4530 }
4531 
ZSTD_compressBegin(ZSTD_CCtx * cctx,int compressionLevel)4532 size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
4533 {
4534     return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
4535 }
4536 
4537 
4538 /*! ZSTD_writeEpilogue() :
4539 *   Ends a frame.
4540 *   @return : nb of bytes written into dst (or an error code) */
ZSTD_writeEpilogue(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity)4541 static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
4542 {
4543     BYTE* const ostart = (BYTE*)dst;
4544     BYTE* op = ostart;
4545     size_t fhSize = 0;
4546 
4547     DEBUGLOG(4, "ZSTD_writeEpilogue");
4548     RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
4549 
4550     /* special case : empty frame */
4551     if (cctx->stage == ZSTDcs_init) {
4552         fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
4553         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
4554         dstCapacity -= fhSize;
4555         op += fhSize;
4556         cctx->stage = ZSTDcs_ongoing;
4557     }
4558 
4559     if (cctx->stage != ZSTDcs_ending) {
4560         /* write one last empty block, make it the "last" block */
4561         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
4562         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for epilogue");
4563         MEM_writeLE32(op, cBlockHeader24);
4564         op += ZSTD_blockHeaderSize;
4565         dstCapacity -= ZSTD_blockHeaderSize;
4566     }
4567 
4568     if (cctx->appliedParams.fParams.checksumFlag) {
4569         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
4570         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
4571         DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
4572         MEM_writeLE32(op, checksum);
4573         op += 4;
4574     }
4575 
4576     cctx->stage = ZSTDcs_created;  /* return to "created but no init" status */
4577     return op-ostart;
4578 }
4579 
ZSTD_CCtx_trace(ZSTD_CCtx * cctx,size_t extraCSize)4580 void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)
4581 {
4582 #if ZSTD_TRACE
4583     if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
4584         int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
4585         ZSTD_Trace trace;
4586         ZSTD_memset(&trace, 0, sizeof(trace));
4587         trace.version = ZSTD_VERSION_NUMBER;
4588         trace.streaming = streaming;
4589         trace.dictionaryID = cctx->dictID;
4590         trace.dictionarySize = cctx->dictContentSize;
4591         trace.uncompressedSize = cctx->consumedSrcSize;
4592         trace.compressedSize = cctx->producedCSize + extraCSize;
4593         trace.params = &cctx->appliedParams;
4594         trace.cctx = cctx;
4595         ZSTD_trace_compress_end(cctx->traceCtx, &trace);
4596     }
4597     cctx->traceCtx = 0;
4598 #else
4599     (void)cctx;
4600     (void)extraCSize;
4601 #endif
4602 }
4603 
ZSTD_compressEnd(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4604 size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
4605                          void* dst, size_t dstCapacity,
4606                    const void* src, size_t srcSize)
4607 {
4608     size_t endResult;
4609     size_t const cSize = ZSTD_compressContinue_internal(cctx,
4610                                 dst, dstCapacity, src, srcSize,
4611                                 1 /* frame mode */, 1 /* last chunk */);
4612     FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
4613     endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
4614     FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
4615     assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
4616     if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
4617         ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
4618         DEBUGLOG(4, "end of frame : controlling src size");
4619         RETURN_ERROR_IF(
4620             cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
4621             srcSize_wrong,
4622              "error : pledgedSrcSize = %u, while realSrcSize = %u",
4623             (unsigned)cctx->pledgedSrcSizePlusOne-1,
4624             (unsigned)cctx->consumedSrcSize);
4625     }
4626     ZSTD_CCtx_trace(cctx, endResult);
4627     return cSize + endResult;
4628 }
4629 
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)4630 size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
4631                                void* dst, size_t dstCapacity,
4632                          const void* src, size_t srcSize,
4633                          const void* dict,size_t dictSize,
4634                                ZSTD_parameters params)
4635 {
4636     DEBUGLOG(4, "ZSTD_compress_advanced");
4637     FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
4638     ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, ZSTD_NO_CLEVEL);
4639     return ZSTD_compress_advanced_internal(cctx,
4640                                            dst, dstCapacity,
4641                                            src, srcSize,
4642                                            dict, dictSize,
4643                                            &cctx->simpleApiParams);
4644 }
4645 
4646 /* 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)4647 size_t ZSTD_compress_advanced_internal(
4648         ZSTD_CCtx* cctx,
4649         void* dst, size_t dstCapacity,
4650         const void* src, size_t srcSize,
4651         const void* dict,size_t dictSize,
4652         const ZSTD_CCtx_params* params)
4653 {
4654     DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
4655     FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
4656                          dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
4657                          params, srcSize, ZSTDb_not_buffered) , "");
4658     return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
4659 }
4660 
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)4661 size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
4662                                void* dst, size_t dstCapacity,
4663                          const void* src, size_t srcSize,
4664                          const void* dict, size_t dictSize,
4665                                int compressionLevel)
4666 {
4667     {
4668         ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);
4669         assert(params.fParams.contentSizeFlag == 1);
4670         ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);
4671     }
4672     DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
4673     return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
4674 }
4675 
ZSTD_compressCCtx(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,int compressionLevel)4676 size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
4677                          void* dst, size_t dstCapacity,
4678                    const void* src, size_t srcSize,
4679                          int compressionLevel)
4680 {
4681     DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
4682     assert(cctx != NULL);
4683     return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
4684 }
4685 
ZSTD_compress(void * dst,size_t dstCapacity,const void * src,size_t srcSize,int compressionLevel)4686 size_t ZSTD_compress(void* dst, size_t dstCapacity,
4687                const void* src, size_t srcSize,
4688                      int compressionLevel)
4689 {
4690     size_t result;
4691 #if ZSTD_COMPRESS_HEAPMODE
4692     ZSTD_CCtx* cctx = ZSTD_createCCtx();
4693     RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");
4694     result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);
4695     ZSTD_freeCCtx(cctx);
4696 #else
4697     ZSTD_CCtx ctxBody;
4698     ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
4699     result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
4700     ZSTD_freeCCtxContent(&ctxBody);   /* can't free ctxBody itself, as it's on stack; free only heap content */
4701 #endif
4702     return result;
4703 }
4704 
4705 
4706 /* =====  Dictionary API  ===== */
4707 
4708 /*! ZSTD_estimateCDictSize_advanced() :
4709  *  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)4710 size_t ZSTD_estimateCDictSize_advanced(
4711         size_t dictSize, ZSTD_compressionParameters cParams,
4712         ZSTD_dictLoadMethod_e dictLoadMethod)
4713 {
4714     DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
4715     return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
4716          + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
4717          /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
4718           * in case we are using DDS with row-hash. */
4719          + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_urm_auto, &cParams),
4720                                   /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)
4721          + (dictLoadMethod == ZSTD_dlm_byRef ? 0
4722             : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
4723 }
4724 
ZSTD_estimateCDictSize(size_t dictSize,int compressionLevel)4725 size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
4726 {
4727     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4728     return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
4729 }
4730 
ZSTD_sizeof_CDict(const ZSTD_CDict * cdict)4731 size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
4732 {
4733     if (cdict==NULL) return 0;   /* support sizeof on NULL */
4734     DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
4735     /* cdict may be in the workspace */
4736     return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
4737         + ZSTD_cwksp_sizeof(&cdict->workspace);
4738 }
4739 
ZSTD_initCDict_internal(ZSTD_CDict * cdict,const void * dictBuffer,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_CCtx_params params)4740 static size_t ZSTD_initCDict_internal(
4741                     ZSTD_CDict* cdict,
4742               const void* dictBuffer, size_t dictSize,
4743                     ZSTD_dictLoadMethod_e dictLoadMethod,
4744                     ZSTD_dictContentType_e dictContentType,
4745                     ZSTD_CCtx_params params)
4746 {
4747     DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
4748     assert(!ZSTD_checkCParams(params.cParams));
4749     cdict->matchState.cParams = params.cParams;
4750     cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
4751     if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
4752         cdict->dictContent = dictBuffer;
4753     } else {
4754          void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
4755         RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
4756         cdict->dictContent = internalBuffer;
4757         ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
4758     }
4759     cdict->dictContentSize = dictSize;
4760     cdict->dictContentType = dictContentType;
4761 
4762     cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
4763 
4764 
4765     /* Reset the state to no dictionary */
4766     ZSTD_reset_compressedBlockState(&cdict->cBlockState);
4767     FORWARD_IF_ERROR(ZSTD_reset_matchState(
4768         &cdict->matchState,
4769         &cdict->workspace,
4770         &params.cParams,
4771         params.useRowMatchFinder,
4772         ZSTDcrp_makeClean,
4773         ZSTDirp_reset,
4774         ZSTD_resetTarget_CDict), "");
4775     /* (Maybe) load the dictionary
4776      * Skips loading the dictionary if it is < 8 bytes.
4777      */
4778     {   params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
4779         params.fParams.contentSizeFlag = 1;
4780         {   size_t const dictID = ZSTD_compress_insertDictionary(
4781                     &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
4782                     &params, cdict->dictContent, cdict->dictContentSize,
4783                     dictContentType, ZSTD_dtlm_full, cdict->entropyWorkspace);
4784             FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
4785             assert(dictID <= (size_t)(U32)-1);
4786             cdict->dictID = (U32)dictID;
4787         }
4788     }
4789 
4790     return 0;
4791 }
4792 
ZSTD_createCDict_advanced_internal(size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_compressionParameters cParams,ZSTD_useRowMatchFinderMode_e useRowMatchFinder,U32 enableDedicatedDictSearch,ZSTD_customMem customMem)4793 static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize,
4794                                       ZSTD_dictLoadMethod_e dictLoadMethod,
4795                                       ZSTD_compressionParameters cParams,
4796                                       ZSTD_useRowMatchFinderMode_e useRowMatchFinder,
4797                                       U32 enableDedicatedDictSearch,
4798                                       ZSTD_customMem customMem)
4799 {
4800     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
4801 
4802     {   size_t const workspaceSize =
4803             ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
4804             ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
4805             ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
4806             (dictLoadMethod == ZSTD_dlm_byRef ? 0
4807              : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
4808         void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
4809         ZSTD_cwksp ws;
4810         ZSTD_CDict* cdict;
4811 
4812         if (!workspace) {
4813             ZSTD_customFree(workspace, customMem);
4814             return NULL;
4815         }
4816 
4817         ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
4818 
4819         cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
4820         assert(cdict != NULL);
4821         ZSTD_cwksp_move(&cdict->workspace, &ws);
4822         cdict->customMem = customMem;
4823         cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */
4824         cdict->useRowMatchFinder = useRowMatchFinder;
4825         return cdict;
4826     }
4827 }
4828 
ZSTD_createCDict_advanced(const void * dictBuffer,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_compressionParameters cParams,ZSTD_customMem customMem)4829 ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
4830                                       ZSTD_dictLoadMethod_e dictLoadMethod,
4831                                       ZSTD_dictContentType_e dictContentType,
4832                                       ZSTD_compressionParameters cParams,
4833                                       ZSTD_customMem customMem)
4834 {
4835     ZSTD_CCtx_params cctxParams;
4836     ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));
4837     ZSTD_CCtxParams_init(&cctxParams, 0);
4838     cctxParams.cParams = cParams;
4839     cctxParams.customMem = customMem;
4840     return ZSTD_createCDict_advanced2(
4841         dictBuffer, dictSize,
4842         dictLoadMethod, dictContentType,
4843         &cctxParams, customMem);
4844 }
4845 
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)4846 ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced2(
4847         const void* dict, size_t dictSize,
4848         ZSTD_dictLoadMethod_e dictLoadMethod,
4849         ZSTD_dictContentType_e dictContentType,
4850         const ZSTD_CCtx_params* originalCctxParams,
4851         ZSTD_customMem customMem)
4852 {
4853     ZSTD_CCtx_params cctxParams = *originalCctxParams;
4854     ZSTD_compressionParameters cParams;
4855     ZSTD_CDict* cdict;
4856 
4857     DEBUGLOG(3, "ZSTD_createCDict_advanced2, mode %u", (unsigned)dictContentType);
4858     if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
4859 
4860     if (cctxParams.enableDedicatedDictSearch) {
4861         cParams = ZSTD_dedicatedDictSearch_getCParams(
4862             cctxParams.compressionLevel, dictSize);
4863         ZSTD_overrideCParams(&cParams, &cctxParams.cParams);
4864     } else {
4865         cParams = ZSTD_getCParamsFromCCtxParams(
4866             &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4867     }
4868 
4869     if (!ZSTD_dedicatedDictSearch_isSupported(&cParams)) {
4870         /* Fall back to non-DDSS params */
4871         cctxParams.enableDedicatedDictSearch = 0;
4872         cParams = ZSTD_getCParamsFromCCtxParams(
4873             &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4874     }
4875 
4876     DEBUGLOG(3, "ZSTD_createCDict_advanced2: DDS: %u", cctxParams.enableDedicatedDictSearch);
4877     cctxParams.cParams = cParams;
4878     cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
4879 
4880     cdict = ZSTD_createCDict_advanced_internal(dictSize,
4881                         dictLoadMethod, cctxParams.cParams,
4882                         cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
4883                         customMem);
4884 
4885     if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
4886                                     dict, dictSize,
4887                                     dictLoadMethod, dictContentType,
4888                                     cctxParams) )) {
4889         ZSTD_freeCDict(cdict);
4890         return NULL;
4891     }
4892 
4893     return cdict;
4894 }
4895 
ZSTD_createCDict(const void * dict,size_t dictSize,int compressionLevel)4896 ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
4897 {
4898     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4899     ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
4900                                                   ZSTD_dlm_byCopy, ZSTD_dct_auto,
4901                                                   cParams, ZSTD_defaultCMem);
4902     if (cdict)
4903         cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
4904     return cdict;
4905 }
4906 
ZSTD_createCDict_byReference(const void * dict,size_t dictSize,int compressionLevel)4907 ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
4908 {
4909     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
4910     ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
4911                                      ZSTD_dlm_byRef, ZSTD_dct_auto,
4912                                      cParams, ZSTD_defaultCMem);
4913     if (cdict)
4914         cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
4915     return cdict;
4916 }
4917 
ZSTD_freeCDict(ZSTD_CDict * cdict)4918 size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
4919 {
4920     if (cdict==NULL) return 0;   /* support free on NULL */
4921     {   ZSTD_customMem const cMem = cdict->customMem;
4922         int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
4923         ZSTD_cwksp_free(&cdict->workspace, cMem);
4924         if (!cdictInWorkspace) {
4925             ZSTD_customFree(cdict, cMem);
4926         }
4927         return 0;
4928     }
4929 }
4930 
4931 /*! ZSTD_initStaticCDict_advanced() :
4932  *  Generate a digested dictionary in provided memory area.
4933  *  workspace: The memory area to emplace the dictionary into.
4934  *             Provided pointer must 8-bytes aligned.
4935  *             It must outlive dictionary usage.
4936  *  workspaceSize: Use ZSTD_estimateCDictSize()
4937  *                 to determine how large workspace must be.
4938  *  cParams : use ZSTD_getCParams() to transform a compression level
4939  *            into its relevants cParams.
4940  * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
4941  *  Note : there is no corresponding "free" function.
4942  *         Since workspace was allocated externally, it must be freed externally.
4943  */
ZSTD_initStaticCDict(void * workspace,size_t workspaceSize,const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_compressionParameters cParams)4944 const ZSTD_CDict* ZSTD_initStaticCDict(
4945                                  void* workspace, size_t workspaceSize,
4946                            const void* dict, size_t dictSize,
4947                                  ZSTD_dictLoadMethod_e dictLoadMethod,
4948                                  ZSTD_dictContentType_e dictContentType,
4949                                  ZSTD_compressionParameters cParams)
4950 {
4951     ZSTD_useRowMatchFinderMode_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_urm_auto, &cParams);
4952     /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
4953     size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
4954     size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
4955                             + (dictLoadMethod == ZSTD_dlm_byRef ? 0
4956                                : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
4957                             + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
4958                             + matchStateSize;
4959     ZSTD_CDict* cdict;
4960     ZSTD_CCtx_params params;
4961 
4962     if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
4963 
4964     {
4965         ZSTD_cwksp ws;
4966         ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
4967         cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
4968         if (cdict == NULL) return NULL;
4969         ZSTD_cwksp_move(&cdict->workspace, &ws);
4970     }
4971 
4972     DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u",
4973         (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize));
4974     if (workspaceSize < neededSize) return NULL;
4975 
4976     ZSTD_CCtxParams_init(&params, 0);
4977     params.cParams = cParams;
4978     params.useRowMatchFinder = useRowMatchFinder;
4979     cdict->useRowMatchFinder = useRowMatchFinder;
4980 
4981     if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
4982                                               dict, dictSize,
4983                                               dictLoadMethod, dictContentType,
4984                                               params) ))
4985         return NULL;
4986 
4987     return cdict;
4988 }
4989 
ZSTD_getCParamsFromCDict(const ZSTD_CDict * cdict)4990 ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
4991 {
4992     assert(cdict != NULL);
4993     return cdict->matchState.cParams;
4994 }
4995 
4996 /*! ZSTD_getDictID_fromCDict() :
4997  *  Provides the dictID of the dictionary loaded into `cdict`.
4998  *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
4999  *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
ZSTD_getDictID_fromCDict(const ZSTD_CDict * cdict)5000 unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)
5001 {
5002     if (cdict==NULL) return 0;
5003     return cdict->dictID;
5004 }
5005 
5006 /* ZSTD_compressBegin_usingCDict_internal() :
5007  * Implementation of various ZSTD_compressBegin_usingCDict* functions.
5008  */
ZSTD_compressBegin_usingCDict_internal(ZSTD_CCtx * const cctx,const ZSTD_CDict * const cdict,ZSTD_frameParameters const fParams,unsigned long long const pledgedSrcSize)5009 static size_t ZSTD_compressBegin_usingCDict_internal(
5010     ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5011     ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5012 {
5013     ZSTD_CCtx_params cctxParams;
5014     DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
5015     RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
5016     /* Initialize the cctxParams from the cdict */
5017     {
5018         ZSTD_parameters params;
5019         params.fParams = fParams;
5020         params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
5021                         || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
5022                         || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
5023                         || cdict->compressionLevel == 0 ) ?
5024                 ZSTD_getCParamsFromCDict(cdict)
5025               : ZSTD_getCParams(cdict->compressionLevel,
5026                                 pledgedSrcSize,
5027                                 cdict->dictContentSize);
5028         ZSTD_CCtxParams_init_internal(&cctxParams, &params, cdict->compressionLevel);
5029     }
5030     /* Increase window log to fit the entire dictionary and source if the
5031      * source size is known. Limit the increase to 19, which is the
5032      * window log for compression level 1 with the largest source size.
5033      */
5034     if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
5035         U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
5036         U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
5037         cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
5038     }
5039     return ZSTD_compressBegin_internal(cctx,
5040                                         NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
5041                                         cdict,
5042                                         &cctxParams, pledgedSrcSize,
5043                                         ZSTDb_not_buffered);
5044 }
5045 
5046 
5047 /* ZSTD_compressBegin_usingCDict_advanced() :
5048  * This function is DEPRECATED.
5049  * 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)5050 size_t ZSTD_compressBegin_usingCDict_advanced(
5051     ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5052     ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5053 {
5054     return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
5055 }
5056 
5057 /* ZSTD_compressBegin_usingCDict() :
5058  * cdict must be != NULL */
ZSTD_compressBegin_usingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict)5059 size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
5060 {
5061     ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5062     return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
5063 }
5064 
5065 /*! ZSTD_compress_usingCDict_internal():
5066  * Implementation of various ZSTD_compress_usingCDict* functions.
5067  */
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)5068 static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
5069                                 void* dst, size_t dstCapacity,
5070                                 const void* src, size_t srcSize,
5071                                 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5072 {
5073     FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */
5074     return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
5075 }
5076 
5077 /*! ZSTD_compress_usingCDict_advanced():
5078  * This function is DEPRECATED.
5079  */
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)5080 size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
5081                                 void* dst, size_t dstCapacity,
5082                                 const void* src, size_t srcSize,
5083                                 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5084 {
5085     return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5086 }
5087 
5088 /*! ZSTD_compress_usingCDict() :
5089  *  Compression using a digested Dictionary.
5090  *  Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
5091  *  Note that compression parameters are decided at CDict creation time
5092  *  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)5093 size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
5094                                 void* dst, size_t dstCapacity,
5095                                 const void* src, size_t srcSize,
5096                                 const ZSTD_CDict* cdict)
5097 {
5098     ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5099     return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5100 }
5101 
5102 
5103 
5104 /* ******************************************************************
5105 *  Streaming
5106 ********************************************************************/
5107 
ZSTD_createCStream(void)5108 ZSTD_CStream* ZSTD_createCStream(void)
5109 {
5110     DEBUGLOG(3, "ZSTD_createCStream");
5111     return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
5112 }
5113 
ZSTD_initStaticCStream(void * workspace,size_t workspaceSize)5114 ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
5115 {
5116     return ZSTD_initStaticCCtx(workspace, workspaceSize);
5117 }
5118 
ZSTD_createCStream_advanced(ZSTD_customMem customMem)5119 ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
5120 {   /* CStream and CCtx are now same object */
5121     return ZSTD_createCCtx_advanced(customMem);
5122 }
5123 
ZSTD_freeCStream(ZSTD_CStream * zcs)5124 size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
5125 {
5126     return ZSTD_freeCCtx(zcs);   /* same object */
5127 }
5128 
5129 
5130 
5131 /*======   Initialization   ======*/
5132 
ZSTD_CStreamInSize(void)5133 size_t ZSTD_CStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX; }
5134 
ZSTD_CStreamOutSize(void)5135 size_t ZSTD_CStreamOutSize(void)
5136 {
5137     return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
5138 }
5139 
ZSTD_getCParamMode(ZSTD_CDict const * cdict,ZSTD_CCtx_params const * params,U64 pledgedSrcSize)5140 static ZSTD_cParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
5141 {
5142     if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))
5143         return ZSTD_cpm_attachDict;
5144     else
5145         return ZSTD_cpm_noAttachDict;
5146 }
5147 
5148 /* ZSTD_resetCStream():
5149  * pledgedSrcSize == 0 means "unknown" */
ZSTD_resetCStream(ZSTD_CStream * zcs,unsigned long long pss)5150 size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
5151 {
5152     /* temporary : 0 interpreted as "unknown" during transition period.
5153      * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
5154      * 0 will be interpreted as "empty" in the future.
5155      */
5156     U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5157     DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
5158     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5159     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5160     return 0;
5161 }
5162 
5163 /*! ZSTD_initCStream_internal() :
5164  *  Note : for lib/compress only. Used by zstdmt_compress.c.
5165  *  Assumption 1 : params are valid
5166  *  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)5167 size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
5168                     const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
5169                     const ZSTD_CCtx_params* params,
5170                     unsigned long long pledgedSrcSize)
5171 {
5172     DEBUGLOG(4, "ZSTD_initCStream_internal");
5173     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5174     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5175     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
5176     zcs->requestedParams = *params;
5177     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
5178     if (dict) {
5179         FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5180     } else {
5181         /* Dictionary is cleared if !cdict */
5182         FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
5183     }
5184     return 0;
5185 }
5186 
5187 /* ZSTD_initCStream_usingCDict_advanced() :
5188  * 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)5189 size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
5190                                             const ZSTD_CDict* cdict,
5191                                             ZSTD_frameParameters fParams,
5192                                             unsigned long long pledgedSrcSize)
5193 {
5194     DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
5195     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5196     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5197     zcs->requestedParams.fParams = fParams;
5198     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
5199     return 0;
5200 }
5201 
5202 /* note : cdict must outlive compression session */
ZSTD_initCStream_usingCDict(ZSTD_CStream * zcs,const ZSTD_CDict * cdict)5203 size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
5204 {
5205     DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
5206     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5207     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
5208     return 0;
5209 }
5210 
5211 
5212 /* ZSTD_initCStream_advanced() :
5213  * pledgedSrcSize must be exact.
5214  * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
5215  * 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)5216 size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
5217                                  const void* dict, size_t dictSize,
5218                                  ZSTD_parameters params, unsigned long long pss)
5219 {
5220     /* for compatibility with older programs relying on this behavior.
5221      * Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
5222      * This line will be removed in the future.
5223      */
5224     U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5225     DEBUGLOG(4, "ZSTD_initCStream_advanced");
5226     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5227     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5228     FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
5229     ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, &params);
5230     FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5231     return 0;
5232 }
5233 
ZSTD_initCStream_usingDict(ZSTD_CStream * zcs,const void * dict,size_t dictSize,int compressionLevel)5234 size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
5235 {
5236     DEBUGLOG(4, "ZSTD_initCStream_usingDict");
5237     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5238     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
5239     FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5240     return 0;
5241 }
5242 
ZSTD_initCStream_srcSize(ZSTD_CStream * zcs,int compressionLevel,unsigned long long pss)5243 size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
5244 {
5245     /* temporary : 0 interpreted as "unknown" during transition period.
5246      * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
5247      * 0 will be interpreted as "empty" in the future.
5248      */
5249     U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5250     DEBUGLOG(4, "ZSTD_initCStream_srcSize");
5251     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5252     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
5253     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
5254     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5255     return 0;
5256 }
5257 
ZSTD_initCStream(ZSTD_CStream * zcs,int compressionLevel)5258 size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
5259 {
5260     DEBUGLOG(4, "ZSTD_initCStream");
5261     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5262     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
5263     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
5264     return 0;
5265 }
5266 
5267 /*======   Compression   ======*/
5268 
ZSTD_nextInputSizeHint(const ZSTD_CCtx * cctx)5269 static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
5270 {
5271     size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
5272     if (hintInSize==0) hintInSize = cctx->blockSize;
5273     return hintInSize;
5274 }
5275 
5276 /** ZSTD_compressStream_generic():
5277  *  internal function for all *compressStream*() variants
5278  *  non-static, because can be called from zstdmt_compress.c
5279  * @return : hint size for next input */
ZSTD_compressStream_generic(ZSTD_CStream * zcs,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective const flushMode)5280 static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
5281                                           ZSTD_outBuffer* output,
5282                                           ZSTD_inBuffer* input,
5283                                           ZSTD_EndDirective const flushMode)
5284 {
5285     const char* const istart = (const char*)input->src;
5286     const char* const iend = input->size != 0 ? istart + input->size : istart;
5287     const char* ip = input->pos != 0 ? istart + input->pos : istart;
5288     char* const ostart = (char*)output->dst;
5289     char* const oend = output->size != 0 ? ostart + output->size : ostart;
5290     char* op = output->pos != 0 ? ostart + output->pos : ostart;
5291     U32 someMoreWork = 1;
5292 
5293     /* check expectations */
5294     DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (unsigned)flushMode);
5295     if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
5296         assert(zcs->inBuff != NULL);
5297         assert(zcs->inBuffSize > 0);
5298     }
5299     if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
5300         assert(zcs->outBuff !=  NULL);
5301         assert(zcs->outBuffSize > 0);
5302     }
5303     assert(output->pos <= output->size);
5304     assert(input->pos <= input->size);
5305     assert((U32)flushMode <= (U32)ZSTD_e_end);
5306 
5307     while (someMoreWork) {
5308         switch(zcs->streamStage)
5309         {
5310         case zcss_init:
5311             RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
5312 
5313         case zcss_load:
5314             if ( (flushMode == ZSTD_e_end)
5315               && ( (size_t)(oend-op) >= ZSTD_compressBound(iend-ip)     /* Enough output space */
5316                 || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)  /* OR we are allowed to return dstSizeTooSmall */
5317               && (zcs->inBuffPos == 0) ) {
5318                 /* shortcut to compression pass directly into output buffer */
5319                 size_t const cSize = ZSTD_compressEnd(zcs,
5320                                                 op, oend-op, ip, iend-ip);
5321                 DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
5322                 FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
5323                 ip = iend;
5324                 op += cSize;
5325                 zcs->frameEnded = 1;
5326                 ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
5327                 someMoreWork = 0; break;
5328             }
5329             /* complete loading into inBuffer in buffered mode */
5330             if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
5331                 size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
5332                 size_t const loaded = ZSTD_limitCopy(
5333                                         zcs->inBuff + zcs->inBuffPos, toLoad,
5334                                         ip, iend-ip);
5335                 zcs->inBuffPos += loaded;
5336                 if (loaded != 0)
5337                     ip += loaded;
5338                 if ( (flushMode == ZSTD_e_continue)
5339                   && (zcs->inBuffPos < zcs->inBuffTarget) ) {
5340                     /* not enough input to fill full block : stop here */
5341                     someMoreWork = 0; break;
5342                 }
5343                 if ( (flushMode == ZSTD_e_flush)
5344                   && (zcs->inBuffPos == zcs->inToCompress) ) {
5345                     /* empty */
5346                     someMoreWork = 0; break;
5347                 }
5348             }
5349             /* compress current block (note : this stage cannot be stopped in the middle) */
5350             DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
5351             {   int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
5352                 void* cDst;
5353                 size_t cSize;
5354                 size_t oSize = oend-op;
5355                 size_t const iSize = inputBuffered
5356                     ? zcs->inBuffPos - zcs->inToCompress
5357                     : MIN((size_t)(iend - ip), zcs->blockSize);
5358                 if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
5359                     cDst = op;   /* compress into output buffer, to skip flush stage */
5360                 else
5361                     cDst = zcs->outBuff, oSize = zcs->outBuffSize;
5362                 if (inputBuffered) {
5363                     unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
5364                     cSize = lastBlock ?
5365                             ZSTD_compressEnd(zcs, cDst, oSize,
5366                                         zcs->inBuff + zcs->inToCompress, iSize) :
5367                             ZSTD_compressContinue(zcs, cDst, oSize,
5368                                         zcs->inBuff + zcs->inToCompress, iSize);
5369                     FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
5370                     zcs->frameEnded = lastBlock;
5371                     /* prepare next block */
5372                     zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
5373                     if (zcs->inBuffTarget > zcs->inBuffSize)
5374                         zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
5375                     DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
5376                             (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
5377                     if (!lastBlock)
5378                         assert(zcs->inBuffTarget <= zcs->inBuffSize);
5379                     zcs->inToCompress = zcs->inBuffPos;
5380                 } else {
5381                     unsigned const lastBlock = (ip + iSize == iend);
5382                     assert(flushMode == ZSTD_e_end /* Already validated */);
5383                     cSize = lastBlock ?
5384                             ZSTD_compressEnd(zcs, cDst, oSize, ip, iSize) :
5385                             ZSTD_compressContinue(zcs, cDst, oSize, ip, iSize);
5386                     /* Consume the input prior to error checking to mirror buffered mode. */
5387                     if (iSize > 0)
5388                         ip += iSize;
5389                     FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
5390                     zcs->frameEnded = lastBlock;
5391                     if (lastBlock)
5392                         assert(ip == iend);
5393                 }
5394                 if (cDst == op) {  /* no need to flush */
5395                     op += cSize;
5396                     if (zcs->frameEnded) {
5397                         DEBUGLOG(5, "Frame completed directly in outBuffer");
5398                         someMoreWork = 0;
5399                         ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
5400                     }
5401                     break;
5402                 }
5403                 zcs->outBuffContentSize = cSize;
5404                 zcs->outBuffFlushedSize = 0;
5405                 zcs->streamStage = zcss_flush; /* pass-through to flush stage */
5406             }
5407 	    /* fall-through */
5408         case zcss_flush:
5409             DEBUGLOG(5, "flush stage");
5410             assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
5411             {   size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
5412                 size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
5413                             zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
5414                 DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
5415                             (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
5416                 if (flushed)
5417                     op += flushed;
5418                 zcs->outBuffFlushedSize += flushed;
5419                 if (toFlush!=flushed) {
5420                     /* flush not fully completed, presumably because dst is too small */
5421                     assert(op==oend);
5422                     someMoreWork = 0;
5423                     break;
5424                 }
5425                 zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
5426                 if (zcs->frameEnded) {
5427                     DEBUGLOG(5, "Frame completed on flush");
5428                     someMoreWork = 0;
5429                     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
5430                     break;
5431                 }
5432                 zcs->streamStage = zcss_load;
5433                 break;
5434             }
5435 
5436         default: /* impossible */
5437             assert(0);
5438         }
5439     }
5440 
5441     input->pos = ip - istart;
5442     output->pos = op - ostart;
5443     if (zcs->frameEnded) return 0;
5444     return ZSTD_nextInputSizeHint(zcs);
5445 }
5446 
ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx * cctx)5447 static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
5448 {
5449 #ifdef ZSTD_MULTITHREAD
5450     if (cctx->appliedParams.nbWorkers >= 1) {
5451         assert(cctx->mtctx != NULL);
5452         return ZSTDMT_nextInputSizeHint(cctx->mtctx);
5453     }
5454 #endif
5455     return ZSTD_nextInputSizeHint(cctx);
5456 
5457 }
5458 
ZSTD_compressStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output,ZSTD_inBuffer * input)5459 size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
5460 {
5461     FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
5462     return ZSTD_nextInputSizeHint_MTorST(zcs);
5463 }
5464 
5465 /* After a compression call set the expected input/output buffer.
5466  * This is validated at the start of the next compression call.
5467  */
ZSTD_setBufferExpectations(ZSTD_CCtx * cctx,ZSTD_outBuffer const * output,ZSTD_inBuffer const * input)5468 static void ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, ZSTD_outBuffer const* output, ZSTD_inBuffer const* input)
5469 {
5470     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
5471         cctx->expectedInBuffer = *input;
5472     }
5473     if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
5474         cctx->expectedOutBufferSize = output->size - output->pos;
5475     }
5476 }
5477 
5478 /* Validate that the input/output buffers match the expectations set by
5479  * ZSTD_setBufferExpectations.
5480  */
ZSTD_checkBufferStability(ZSTD_CCtx const * cctx,ZSTD_outBuffer const * output,ZSTD_inBuffer const * input,ZSTD_EndDirective endOp)5481 static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
5482                                         ZSTD_outBuffer const* output,
5483                                         ZSTD_inBuffer const* input,
5484                                         ZSTD_EndDirective endOp)
5485 {
5486     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
5487         ZSTD_inBuffer const expect = cctx->expectedInBuffer;
5488         if (expect.src != input->src || expect.pos != input->pos || expect.size != input->size)
5489             RETURN_ERROR(srcBuffer_wrong, "ZSTD_c_stableInBuffer enabled but input differs!");
5490         if (endOp != ZSTD_e_end)
5491             RETURN_ERROR(srcBuffer_wrong, "ZSTD_c_stableInBuffer can only be used with ZSTD_e_end!");
5492     }
5493     if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
5494         size_t const outBufferSize = output->size - output->pos;
5495         if (cctx->expectedOutBufferSize != outBufferSize)
5496             RETURN_ERROR(dstBuffer_wrong, "ZSTD_c_stableOutBuffer enabled but output size differs!");
5497     }
5498     return 0;
5499 }
5500 
ZSTD_CCtx_init_compressStream2(ZSTD_CCtx * cctx,ZSTD_EndDirective endOp,size_t inSize)5501 static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
5502                                              ZSTD_EndDirective endOp,
5503                                              size_t inSize) {
5504     ZSTD_CCtx_params params = cctx->requestedParams;
5505     ZSTD_prefixDict const prefixDict = cctx->prefixDict;
5506     FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
5507     ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));   /* single usage */
5508     assert(prefixDict.dict==NULL || cctx->cdict==NULL);    /* only one can be set */
5509     if (cctx->cdict && !cctx->localDict.cdict) {
5510         /* Let the cdict's compression level take priority over the requested params.
5511          * But do not take the cdict's compression level if the "cdict" is actually a localDict
5512          * generated from ZSTD_initLocalDict().
5513          */
5514         params.compressionLevel = cctx->cdict->compressionLevel;
5515     }
5516     DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
5517     if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1;  /* auto-fix pledgedSrcSize */
5518     {
5519         size_t const dictSize = prefixDict.dict
5520                 ? prefixDict.dictSize
5521                 : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
5522         ZSTD_cParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, &params, cctx->pledgedSrcSizePlusOne - 1);
5523         params.cParams = ZSTD_getCParamsFromCCtxParams(
5524                 &params, cctx->pledgedSrcSizePlusOne-1,
5525                 dictSize, mode);
5526     }
5527 
5528     if (ZSTD_CParams_shouldEnableLdm(&params.cParams)) {
5529         /* Enable LDM by default for optimal parser and window size >= 128MB */
5530         DEBUGLOG(4, "LDM enabled by default (window size >= 128MB, strategy >= btopt)");
5531         params.ldmParams.enableLdm = 1;
5532     }
5533 
5534     if (ZSTD_CParams_useBlockSplitter(&params.cParams)) {
5535         DEBUGLOG(4, "Block splitter enabled by default (window size >= 128K, strategy >= btopt)");
5536         params.splitBlocks = 1;
5537     }
5538 
5539     params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
5540 
5541 #ifdef ZSTD_MULTITHREAD
5542     if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
5543         params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
5544     }
5545     if (params.nbWorkers > 0) {
5546 #if ZSTD_TRACE
5547         cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
5548 #endif
5549         /* mt context creation */
5550         if (cctx->mtctx == NULL) {
5551             DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
5552                         params.nbWorkers);
5553             cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
5554             RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
5555         }
5556         /* mt compression */
5557         DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
5558         FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
5559                     cctx->mtctx,
5560                     prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
5561                     cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
5562         cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
5563         cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
5564         cctx->consumedSrcSize = 0;
5565         cctx->producedCSize = 0;
5566         cctx->streamStage = zcss_load;
5567         cctx->appliedParams = params;
5568     } else
5569 #endif
5570     {   U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
5571         assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
5572         FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
5573                 prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
5574                 cctx->cdict,
5575                 &params, pledgedSrcSize,
5576                 ZSTDb_buffered) , "");
5577         assert(cctx->appliedParams.nbWorkers == 0);
5578         cctx->inToCompress = 0;
5579         cctx->inBuffPos = 0;
5580         if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
5581             /* for small input: avoid automatic flush on reaching end of block, since
5582             * it would require to add a 3-bytes null block to end frame
5583             */
5584             cctx->inBuffTarget = cctx->blockSize + (cctx->blockSize == pledgedSrcSize);
5585         } else {
5586             cctx->inBuffTarget = 0;
5587         }
5588         cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
5589         cctx->streamStage = zcss_load;
5590         cctx->frameEnded = 0;
5591     }
5592     return 0;
5593 }
5594 
ZSTD_compressStream2(ZSTD_CCtx * cctx,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective endOp)5595 size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
5596                              ZSTD_outBuffer* output,
5597                              ZSTD_inBuffer* input,
5598                              ZSTD_EndDirective endOp)
5599 {
5600     DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
5601     /* check conditions */
5602     RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
5603     RETURN_ERROR_IF(input->pos  > input->size, srcSize_wrong, "invalid input buffer");
5604     RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
5605     assert(cctx != NULL);
5606 
5607     /* transparent initialization stage */
5608     if (cctx->streamStage == zcss_init) {
5609         FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, input->size), "CompressStream2 initialization failed");
5610         ZSTD_setBufferExpectations(cctx, output, input);    /* Set initial buffer expectations now that we've initialized */
5611     }
5612     /* end of transparent initialization stage */
5613 
5614     FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");
5615     /* compression stage */
5616 #ifdef ZSTD_MULTITHREAD
5617     if (cctx->appliedParams.nbWorkers > 0) {
5618         size_t flushMin;
5619         if (cctx->cParamsChanged) {
5620             ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
5621             cctx->cParamsChanged = 0;
5622         }
5623         for (;;) {
5624             size_t const ipos = input->pos;
5625             size_t const opos = output->pos;
5626             flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
5627             cctx->consumedSrcSize += (U64)(input->pos - ipos);
5628             cctx->producedCSize += (U64)(output->pos - opos);
5629             if ( ZSTD_isError(flushMin)
5630               || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
5631                 if (flushMin == 0)
5632                     ZSTD_CCtx_trace(cctx, 0);
5633                 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
5634             }
5635             FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
5636 
5637             if (endOp == ZSTD_e_continue) {
5638                 /* We only require some progress with ZSTD_e_continue, not maximal progress.
5639                  * We're done if we've consumed or produced any bytes, or either buffer is
5640                  * full.
5641                  */
5642                 if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
5643                     break;
5644             } else {
5645                 assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
5646                 /* We require maximal progress. We're done when the flush is complete or the
5647                  * output buffer is full.
5648                  */
5649                 if (flushMin == 0 || output->pos == output->size)
5650                     break;
5651             }
5652         }
5653         DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
5654         /* Either we don't require maximum forward progress, we've finished the
5655          * flush, or we are out of output space.
5656          */
5657         assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
5658         ZSTD_setBufferExpectations(cctx, output, input);
5659         return flushMin;
5660     }
5661 #endif
5662     FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
5663     DEBUGLOG(5, "completed ZSTD_compressStream2");
5664     ZSTD_setBufferExpectations(cctx, output, input);
5665     return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
5666 }
5667 
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)5668 size_t ZSTD_compressStream2_simpleArgs (
5669                             ZSTD_CCtx* cctx,
5670                             void* dst, size_t dstCapacity, size_t* dstPos,
5671                       const void* src, size_t srcSize, size_t* srcPos,
5672                             ZSTD_EndDirective endOp)
5673 {
5674     ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
5675     ZSTD_inBuffer  input  = { src, srcSize, *srcPos };
5676     /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
5677     size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
5678     *dstPos = output.pos;
5679     *srcPos = input.pos;
5680     return cErr;
5681 }
5682 
ZSTD_compress2(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)5683 size_t ZSTD_compress2(ZSTD_CCtx* cctx,
5684                       void* dst, size_t dstCapacity,
5685                       const void* src, size_t srcSize)
5686 {
5687     ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
5688     ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
5689     DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
5690     ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
5691     /* Enable stable input/output buffers. */
5692     cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
5693     cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
5694     {   size_t oPos = 0;
5695         size_t iPos = 0;
5696         size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
5697                                         dst, dstCapacity, &oPos,
5698                                         src, srcSize, &iPos,
5699                                         ZSTD_e_end);
5700         /* Reset to the original values. */
5701         cctx->requestedParams.inBufferMode = originalInBufferMode;
5702         cctx->requestedParams.outBufferMode = originalOutBufferMode;
5703         FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
5704         if (result != 0) {  /* compression not completed, due to lack of output space */
5705             assert(oPos == dstCapacity);
5706             RETURN_ERROR(dstSize_tooSmall, "");
5707         }
5708         assert(iPos == srcSize);   /* all input is expected consumed */
5709         return oPos;
5710     }
5711 }
5712 
5713 typedef struct {
5714     U32 idx;             /* Index in array of ZSTD_Sequence */
5715     U32 posInSequence;   /* Position within sequence at idx */
5716     size_t posInSrc;        /* Number of bytes given by sequences provided so far */
5717 } ZSTD_sequencePosition;
5718 
5719 /* 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)5720 static size_t ZSTD_validateSequence(U32 offCode, U32 matchLength,
5721                                     size_t posInSrc, U32 windowLog, size_t dictSize, U32 minMatch) {
5722     size_t offsetBound;
5723     U32 windowSize = 1 << windowLog;
5724     /* posInSrc represents the amount of data the the decoder would decode up to this point.
5725      * As long as the amount of data decoded is less than or equal to window size, offsets may be
5726      * larger than the total length of output decoded in order to reference the dict, even larger than
5727      * window size. After output surpasses windowSize, we're limited to windowSize offsets again.
5728      */
5729     offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize;
5730     RETURN_ERROR_IF(offCode > offsetBound + ZSTD_REP_MOVE, corruption_detected, "Offset too large!");
5731     RETURN_ERROR_IF(matchLength < minMatch, corruption_detected, "Matchlength too small");
5732     return 0;
5733 }
5734 
5735 /* 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)5736 static U32 ZSTD_finalizeOffCode(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0) {
5737     U32 offCode = rawOffset + ZSTD_REP_MOVE;
5738     U32 repCode = 0;
5739 
5740     if (!ll0 && rawOffset == rep[0]) {
5741         repCode = 1;
5742     } else if (rawOffset == rep[1]) {
5743         repCode = 2 - ll0;
5744     } else if (rawOffset == rep[2]) {
5745         repCode = 3 - ll0;
5746     } else if (ll0 && rawOffset == rep[0] - 1) {
5747         repCode = 3;
5748     }
5749     if (repCode) {
5750         /* ZSTD_storeSeq expects a number in the range [0, 2] to represent a repcode */
5751         offCode = repCode - 1;
5752     }
5753     return offCode;
5754 }
5755 
5756 /* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of
5757  * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter.
5758  */
ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx * cctx,ZSTD_sequencePosition * seqPos,const ZSTD_Sequence * const inSeqs,size_t inSeqsSize,const void * src,size_t blockSize)5759 static size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
5760                                                              const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
5761                                                              const void* src, size_t blockSize) {
5762     U32 idx = seqPos->idx;
5763     BYTE const* ip = (BYTE const*)(src);
5764     const BYTE* const iend = ip + blockSize;
5765     repcodes_t updatedRepcodes;
5766     U32 dictSize;
5767     U32 litLength;
5768     U32 matchLength;
5769     U32 ll0;
5770     U32 offCode;
5771 
5772     if (cctx->cdict) {
5773         dictSize = (U32)cctx->cdict->dictContentSize;
5774     } else if (cctx->prefixDict.dict) {
5775         dictSize = (U32)cctx->prefixDict.dictSize;
5776     } else {
5777         dictSize = 0;
5778     }
5779     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
5780     for (; (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0) && idx < inSeqsSize; ++idx) {
5781         litLength = inSeqs[idx].litLength;
5782         matchLength = inSeqs[idx].matchLength;
5783         ll0 = litLength == 0;
5784         offCode = ZSTD_finalizeOffCode(inSeqs[idx].offset, updatedRepcodes.rep, ll0);
5785         updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep, offCode, ll0);
5786 
5787         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offCode, matchLength, litLength);
5788         if (cctx->appliedParams.validateSequences) {
5789             seqPos->posInSrc += litLength + matchLength;
5790             FORWARD_IF_ERROR(ZSTD_validateSequence(offCode, matchLength, seqPos->posInSrc,
5791                                                 cctx->appliedParams.cParams.windowLog, dictSize,
5792                                                 cctx->appliedParams.cParams.minMatch),
5793                                                 "Sequence validation failed");
5794         }
5795         RETURN_ERROR_IF(idx - seqPos->idx > cctx->seqStore.maxNbSeq, memory_allocation,
5796                         "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
5797         ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offCode, matchLength - MINMATCH);
5798         ip += matchLength + litLength;
5799     }
5800     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
5801 
5802     if (inSeqs[idx].litLength) {
5803         DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);
5804         ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);
5805         ip += inSeqs[idx].litLength;
5806         seqPos->posInSrc += inSeqs[idx].litLength;
5807     }
5808     RETURN_ERROR_IF(ip != iend, corruption_detected, "Blocksize doesn't agree with block delimiter!");
5809     seqPos->idx = idx+1;
5810     return 0;
5811 }
5812 
5813 /* Returns the number of bytes to move the current read position back by. Only non-zero
5814  * if we ended up splitting a sequence. Otherwise, it may return a ZSTD error if something
5815  * went wrong.
5816  *
5817  * This function will attempt to scan through blockSize bytes represented by the sequences
5818  * in inSeqs, storing any (partial) sequences.
5819  *
5820  * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
5821  * avoid splitting a match, or to avoid splitting a match such that it would produce a match
5822  * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
5823  */
ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx * cctx,ZSTD_sequencePosition * seqPos,const ZSTD_Sequence * const inSeqs,size_t inSeqsSize,const void * src,size_t blockSize)5824 static size_t ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
5825                                                        const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
5826                                                        const void* src, size_t blockSize) {
5827     U32 idx = seqPos->idx;
5828     U32 startPosInSequence = seqPos->posInSequence;
5829     U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
5830     size_t dictSize;
5831     BYTE const* ip = (BYTE const*)(src);
5832     BYTE const* iend = ip + blockSize;  /* May be adjusted if we decide to process fewer than blockSize bytes */
5833     repcodes_t updatedRepcodes;
5834     U32 bytesAdjustment = 0;
5835     U32 finalMatchSplit = 0;
5836     U32 litLength;
5837     U32 matchLength;
5838     U32 rawOffset;
5839     U32 offCode;
5840 
5841     if (cctx->cdict) {
5842         dictSize = cctx->cdict->dictContentSize;
5843     } else if (cctx->prefixDict.dict) {
5844         dictSize = cctx->prefixDict.dictSize;
5845     } else {
5846         dictSize = 0;
5847     }
5848     DEBUGLOG(5, "ZSTD_copySequencesToSeqStore: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
5849     DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
5850     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t));
5851     while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
5852         const ZSTD_Sequence currSeq = inSeqs[idx];
5853         litLength = currSeq.litLength;
5854         matchLength = currSeq.matchLength;
5855         rawOffset = currSeq.offset;
5856 
5857         /* Modify the sequence depending on where endPosInSequence lies */
5858         if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
5859             if (startPosInSequence >= litLength) {
5860                 startPosInSequence -= litLength;
5861                 litLength = 0;
5862                 matchLength -= startPosInSequence;
5863             } else {
5864                 litLength -= startPosInSequence;
5865             }
5866             /* Move to the next sequence */
5867             endPosInSequence -= currSeq.litLength + currSeq.matchLength;
5868             startPosInSequence = 0;
5869             idx++;
5870         } else {
5871             /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
5872                does not reach the end of the match. So, we have to split the sequence */
5873             DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
5874                      currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
5875             if (endPosInSequence > litLength) {
5876                 U32 firstHalfMatchLength;
5877                 litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
5878                 firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
5879                 if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
5880                     /* Only ever split the match if it is larger than the block size */
5881                     U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
5882                     if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
5883                         /* Move the endPosInSequence backward so that it creates match of minMatch length */
5884                         endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
5885                         bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
5886                         firstHalfMatchLength -= bytesAdjustment;
5887                     }
5888                     matchLength = firstHalfMatchLength;
5889                     /* Flag that we split the last match - after storing the sequence, exit the loop,
5890                        but keep the value of endPosInSequence */
5891                     finalMatchSplit = 1;
5892                 } else {
5893                     /* Move the position in sequence backwards so that we don't split match, and break to store
5894                      * the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence
5895                      * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
5896                      * would cause the first half of the match to be too small
5897                      */
5898                     bytesAdjustment = endPosInSequence - currSeq.litLength;
5899                     endPosInSequence = currSeq.litLength;
5900                     break;
5901                 }
5902             } else {
5903                 /* This sequence ends inside the literals, break to store the last literals */
5904                 break;
5905             }
5906         }
5907         /* Check if this offset can be represented with a repcode */
5908         {   U32 ll0 = (litLength == 0);
5909             offCode = ZSTD_finalizeOffCode(rawOffset, updatedRepcodes.rep, ll0);
5910             updatedRepcodes = ZSTD_updateRep(updatedRepcodes.rep, offCode, ll0);
5911         }
5912 
5913         if (cctx->appliedParams.validateSequences) {
5914             seqPos->posInSrc += litLength + matchLength;
5915             FORWARD_IF_ERROR(ZSTD_validateSequence(offCode, matchLength, seqPos->posInSrc,
5916                                                    cctx->appliedParams.cParams.windowLog, dictSize,
5917                                                    cctx->appliedParams.cParams.minMatch),
5918                                                    "Sequence validation failed");
5919         }
5920         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offCode, matchLength, litLength);
5921         RETURN_ERROR_IF(idx - seqPos->idx > cctx->seqStore.maxNbSeq, memory_allocation,
5922                         "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
5923         ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offCode, matchLength - MINMATCH);
5924         ip += matchLength + litLength;
5925     }
5926     DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
5927     assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
5928     seqPos->idx = idx;
5929     seqPos->posInSequence = endPosInSequence;
5930     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t));
5931 
5932     iend -= bytesAdjustment;
5933     if (ip != iend) {
5934         /* Store any last literals */
5935         U32 lastLLSize = (U32)(iend - ip);
5936         assert(ip <= iend);
5937         DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);
5938         ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);
5939         seqPos->posInSrc += lastLLSize;
5940     }
5941 
5942     return bytesAdjustment;
5943 }
5944 
5945 typedef size_t (*ZSTD_sequenceCopier) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
5946                                        const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
5947                                        const void* src, size_t blockSize);
ZSTD_selectSequenceCopier(ZSTD_sequenceFormat_e mode)5948 static ZSTD_sequenceCopier ZSTD_selectSequenceCopier(ZSTD_sequenceFormat_e mode) {
5949     ZSTD_sequenceCopier sequenceCopier = NULL;
5950     assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, mode));
5951     if (mode == ZSTD_sf_explicitBlockDelimiters) {
5952         return ZSTD_copySequencesToSeqStoreExplicitBlockDelim;
5953     } else if (mode == ZSTD_sf_noBlockDelimiters) {
5954         return ZSTD_copySequencesToSeqStoreNoBlockDelim;
5955     }
5956     assert(sequenceCopier != NULL);
5957     return sequenceCopier;
5958 }
5959 
5960 /* Compress, block-by-block, all of the sequences given.
5961  *
5962  * Returns the cumulative size of all compressed blocks (including their headers), otherwise a ZSTD error.
5963  */
ZSTD_compressSequences_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * src,size_t srcSize)5964 static size_t ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
5965                                               void* dst, size_t dstCapacity,
5966                                               const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
5967                                               const void* src, size_t srcSize) {
5968     size_t cSize = 0;
5969     U32 lastBlock;
5970     size_t blockSize;
5971     size_t compressedSeqsSize;
5972     size_t remaining = srcSize;
5973     ZSTD_sequencePosition seqPos = {0, 0, 0};
5974 
5975     BYTE const* ip = (BYTE const*)src;
5976     BYTE* op = (BYTE*)dst;
5977     ZSTD_sequenceCopier sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
5978 
5979     DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
5980     /* Special case: empty frame */
5981     if (remaining == 0) {
5982         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
5983         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
5984         MEM_writeLE32(op, cBlockHeader24);
5985         op += ZSTD_blockHeaderSize;
5986         dstCapacity -= ZSTD_blockHeaderSize;
5987         cSize += ZSTD_blockHeaderSize;
5988     }
5989 
5990     while (remaining) {
5991         size_t cBlockSize;
5992         size_t additionalByteAdjustment;
5993         lastBlock = remaining <= cctx->blockSize;
5994         blockSize = lastBlock ? (U32)remaining : (U32)cctx->blockSize;
5995         ZSTD_resetSeqStore(&cctx->seqStore);
5996         DEBUGLOG(4, "Working on new block. Blocksize: %zu", blockSize);
5997 
5998         additionalByteAdjustment = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize);
5999         FORWARD_IF_ERROR(additionalByteAdjustment, "Bad sequence copy");
6000         blockSize -= additionalByteAdjustment;
6001 
6002         /* If blocks are too small, emit as a nocompress block */
6003         if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
6004             cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
6005             FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
6006             DEBUGLOG(4, "Block too small, writing out nocompress block: cSize: %zu", cBlockSize);
6007             cSize += cBlockSize;
6008             ip += blockSize;
6009             op += cBlockSize;
6010             remaining -= blockSize;
6011             dstCapacity -= cBlockSize;
6012             continue;
6013         }
6014 
6015         compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
6016                                 &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
6017                                 &cctx->appliedParams,
6018                                 op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
6019                                 blockSize,
6020                                 cctx->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
6021                                 cctx->bmi2);
6022         FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
6023         DEBUGLOG(4, "Compressed sequences size: %zu", compressedSeqsSize);
6024 
6025         if (!cctx->isFirstBlock &&
6026             ZSTD_maybeRLE(&cctx->seqStore) &&
6027             ZSTD_isRLE((BYTE const*)src, srcSize)) {
6028             /* We don't want to emit our first block as a RLE even if it qualifies because
6029             * doing so will cause the decoder (cli only) to throw a "should consume all input error."
6030             * This is only an issue for zstd <= v1.4.3
6031             */
6032             compressedSeqsSize = 1;
6033         }
6034 
6035         if (compressedSeqsSize == 0) {
6036             /* ZSTD_noCompressBlock writes the block header as well */
6037             cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
6038             FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
6039             DEBUGLOG(4, "Writing out nocompress block, size: %zu", cBlockSize);
6040         } else if (compressedSeqsSize == 1) {
6041             cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
6042             FORWARD_IF_ERROR(cBlockSize, "RLE compress block failed");
6043             DEBUGLOG(4, "Writing out RLE block, size: %zu", cBlockSize);
6044         } else {
6045             U32 cBlockHeader;
6046             /* Error checking and repcodes update */
6047             ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
6048             if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
6049                 cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
6050 
6051             /* Write block header into beginning of block*/
6052             cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
6053             MEM_writeLE24(op, cBlockHeader);
6054             cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
6055             DEBUGLOG(4, "Writing out compressed block, size: %zu", cBlockSize);
6056         }
6057 
6058         cSize += cBlockSize;
6059         DEBUGLOG(4, "cSize running total: %zu", cSize);
6060 
6061         if (lastBlock) {
6062             break;
6063         } else {
6064             ip += blockSize;
6065             op += cBlockSize;
6066             remaining -= blockSize;
6067             dstCapacity -= cBlockSize;
6068             cctx->isFirstBlock = 0;
6069         }
6070     }
6071 
6072     return cSize;
6073 }
6074 
ZSTD_compressSequences(ZSTD_CCtx * const cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * src,size_t srcSize)6075 size_t ZSTD_compressSequences(ZSTD_CCtx* const cctx, void* dst, size_t dstCapacity,
6076                               const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
6077                               const void* src, size_t srcSize) {
6078     BYTE* op = (BYTE*)dst;
6079     size_t cSize = 0;
6080     size_t compressedBlocksSize = 0;
6081     size_t frameHeaderSize = 0;
6082 
6083     /* Transparent initialization stage, same as compressStream2() */
6084     DEBUGLOG(3, "ZSTD_compressSequences()");
6085     assert(cctx != NULL);
6086     FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
6087     /* Begin writing output, starting with frame header */
6088     frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, srcSize, cctx->dictID);
6089     op += frameHeaderSize;
6090     dstCapacity -= frameHeaderSize;
6091     cSize += frameHeaderSize;
6092     if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
6093         XXH64_update(&cctx->xxhState, src, srcSize);
6094     }
6095     /* cSize includes block header size and compressed sequences size */
6096     compressedBlocksSize = ZSTD_compressSequences_internal(cctx,
6097                                                            op, dstCapacity,
6098                                                            inSeqs, inSeqsSize,
6099                                                            src, srcSize);
6100     FORWARD_IF_ERROR(compressedBlocksSize, "Compressing blocks failed!");
6101     cSize += compressedBlocksSize;
6102     dstCapacity -= compressedBlocksSize;
6103 
6104     if (cctx->appliedParams.fParams.checksumFlag) {
6105         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
6106         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
6107         DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
6108         MEM_writeLE32((char*)dst + cSize, checksum);
6109         cSize += 4;
6110     }
6111 
6112     DEBUGLOG(3, "Final compressed size: %zu", cSize);
6113     return cSize;
6114 }
6115 
6116 /*======   Finalize   ======*/
6117 
6118 /*! ZSTD_flushStream() :
6119  * @return : amount of data remaining to flush */
ZSTD_flushStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output)6120 size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
6121 {
6122     ZSTD_inBuffer input = { NULL, 0, 0 };
6123     return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
6124 }
6125 
6126 
ZSTD_endStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output)6127 size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
6128 {
6129     ZSTD_inBuffer input = { NULL, 0, 0 };
6130     size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
6131     FORWARD_IF_ERROR( remainingToFlush , "ZSTD_compressStream2 failed");
6132     if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush;   /* minimal estimation */
6133     /* single thread mode : attempt to calculate remaining to flush more precisely */
6134     {   size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
6135         size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);
6136         size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
6137         DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
6138         return toFlush;
6139     }
6140 }
6141 
6142 
6143 /*-=====  Pre-defined compression levels  =====-*/
6144 
6145 #define ZSTD_MAX_CLEVEL     22
ZSTD_maxCLevel(void)6146 int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
ZSTD_minCLevel(void)6147 int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
ZSTD_defaultCLevel(void)6148 int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }
6149 
6150 static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
6151 {   /* "default" - for any srcSize > 256 KB */
6152     /* W,  C,  H,  S,  L, TL, strat */
6153     { 19, 12, 13,  1,  6,  1, ZSTD_fast    },  /* base for negative levels */
6154     { 19, 13, 14,  1,  7,  0, ZSTD_fast    },  /* level  1 */
6155     { 20, 15, 16,  1,  6,  0, ZSTD_fast    },  /* level  2 */
6156     { 21, 16, 17,  1,  5,  0, ZSTD_dfast   },  /* level  3 */
6157     { 21, 18, 18,  1,  5,  0, ZSTD_dfast   },  /* level  4 */
6158     { 21, 18, 19,  2,  5,  2, ZSTD_greedy  },  /* level  5 */
6159     { 21, 19, 19,  3,  5,  4, ZSTD_greedy  },  /* level  6 */
6160     { 21, 19, 19,  3,  5,  8, ZSTD_lazy    },  /* level  7 */
6161     { 21, 19, 19,  3,  5, 16, ZSTD_lazy2   },  /* level  8 */
6162     { 21, 19, 20,  4,  5, 16, ZSTD_lazy2   },  /* level  9 */
6163     { 22, 20, 21,  4,  5, 16, ZSTD_lazy2   },  /* level 10 */
6164     { 22, 21, 22,  4,  5, 16, ZSTD_lazy2   },  /* level 11 */
6165     { 22, 21, 22,  5,  5, 16, ZSTD_lazy2   },  /* level 12 */
6166     { 22, 21, 22,  5,  5, 32, ZSTD_btlazy2 },  /* level 13 */
6167     { 22, 22, 23,  5,  5, 32, ZSTD_btlazy2 },  /* level 14 */
6168     { 22, 23, 23,  6,  5, 32, ZSTD_btlazy2 },  /* level 15 */
6169     { 22, 22, 22,  5,  5, 48, ZSTD_btopt   },  /* level 16 */
6170     { 23, 23, 22,  5,  4, 64, ZSTD_btopt   },  /* level 17 */
6171     { 23, 23, 22,  6,  3, 64, ZSTD_btultra },  /* level 18 */
6172     { 23, 24, 22,  7,  3,256, ZSTD_btultra2},  /* level 19 */
6173     { 25, 25, 23,  7,  3,256, ZSTD_btultra2},  /* level 20 */
6174     { 26, 26, 24,  7,  3,512, ZSTD_btultra2},  /* level 21 */
6175     { 27, 27, 25,  9,  3,999, ZSTD_btultra2},  /* level 22 */
6176 },
6177 {   /* for srcSize <= 256 KB */
6178     /* W,  C,  H,  S,  L,  T, strat */
6179     { 18, 12, 13,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
6180     { 18, 13, 14,  1,  6,  0, ZSTD_fast    },  /* level  1 */
6181     { 18, 14, 14,  1,  5,  0, ZSTD_dfast   },  /* level  2 */
6182     { 18, 16, 16,  1,  4,  0, ZSTD_dfast   },  /* level  3 */
6183     { 18, 16, 17,  2,  5,  2, ZSTD_greedy  },  /* level  4.*/
6184     { 18, 18, 18,  3,  5,  2, ZSTD_greedy  },  /* level  5.*/
6185     { 18, 18, 19,  3,  5,  4, ZSTD_lazy    },  /* level  6.*/
6186     { 18, 18, 19,  4,  4,  4, ZSTD_lazy    },  /* level  7 */
6187     { 18, 18, 19,  4,  4,  8, ZSTD_lazy2   },  /* level  8 */
6188     { 18, 18, 19,  5,  4,  8, ZSTD_lazy2   },  /* level  9 */
6189     { 18, 18, 19,  6,  4,  8, ZSTD_lazy2   },  /* level 10 */
6190     { 18, 18, 19,  5,  4, 12, ZSTD_btlazy2 },  /* level 11.*/
6191     { 18, 19, 19,  7,  4, 12, ZSTD_btlazy2 },  /* level 12.*/
6192     { 18, 18, 19,  4,  4, 16, ZSTD_btopt   },  /* level 13 */
6193     { 18, 18, 19,  4,  3, 32, ZSTD_btopt   },  /* level 14.*/
6194     { 18, 18, 19,  6,  3,128, ZSTD_btopt   },  /* level 15.*/
6195     { 18, 19, 19,  6,  3,128, ZSTD_btultra },  /* level 16.*/
6196     { 18, 19, 19,  8,  3,256, ZSTD_btultra },  /* level 17.*/
6197     { 18, 19, 19,  6,  3,128, ZSTD_btultra2},  /* level 18.*/
6198     { 18, 19, 19,  8,  3,256, ZSTD_btultra2},  /* level 19.*/
6199     { 18, 19, 19, 10,  3,512, ZSTD_btultra2},  /* level 20.*/
6200     { 18, 19, 19, 12,  3,512, ZSTD_btultra2},  /* level 21.*/
6201     { 18, 19, 19, 13,  3,999, ZSTD_btultra2},  /* level 22.*/
6202 },
6203 {   /* for srcSize <= 128 KB */
6204     /* W,  C,  H,  S,  L,  T, strat */
6205     { 17, 12, 12,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
6206     { 17, 12, 13,  1,  6,  0, ZSTD_fast    },  /* level  1 */
6207     { 17, 13, 15,  1,  5,  0, ZSTD_fast    },  /* level  2 */
6208     { 17, 15, 16,  2,  5,  0, ZSTD_dfast   },  /* level  3 */
6209     { 17, 17, 17,  2,  4,  0, ZSTD_dfast   },  /* level  4 */
6210     { 17, 16, 17,  3,  4,  2, ZSTD_greedy  },  /* level  5 */
6211     { 17, 17, 17,  3,  4,  4, ZSTD_lazy    },  /* level  6 */
6212     { 17, 17, 17,  3,  4,  8, ZSTD_lazy2   },  /* level  7 */
6213     { 17, 17, 17,  4,  4,  8, ZSTD_lazy2   },  /* level  8 */
6214     { 17, 17, 17,  5,  4,  8, ZSTD_lazy2   },  /* level  9 */
6215     { 17, 17, 17,  6,  4,  8, ZSTD_lazy2   },  /* level 10 */
6216     { 17, 17, 17,  5,  4,  8, ZSTD_btlazy2 },  /* level 11 */
6217     { 17, 18, 17,  7,  4, 12, ZSTD_btlazy2 },  /* level 12 */
6218     { 17, 18, 17,  3,  4, 12, ZSTD_btopt   },  /* level 13.*/
6219     { 17, 18, 17,  4,  3, 32, ZSTD_btopt   },  /* level 14.*/
6220     { 17, 18, 17,  6,  3,256, ZSTD_btopt   },  /* level 15.*/
6221     { 17, 18, 17,  6,  3,128, ZSTD_btultra },  /* level 16.*/
6222     { 17, 18, 17,  8,  3,256, ZSTD_btultra },  /* level 17.*/
6223     { 17, 18, 17, 10,  3,512, ZSTD_btultra },  /* level 18.*/
6224     { 17, 18, 17,  5,  3,256, ZSTD_btultra2},  /* level 19.*/
6225     { 17, 18, 17,  7,  3,512, ZSTD_btultra2},  /* level 20.*/
6226     { 17, 18, 17,  9,  3,512, ZSTD_btultra2},  /* level 21.*/
6227     { 17, 18, 17, 11,  3,999, ZSTD_btultra2},  /* level 22.*/
6228 },
6229 {   /* for srcSize <= 16 KB */
6230     /* W,  C,  H,  S,  L,  T, strat */
6231     { 14, 12, 13,  1,  5,  1, ZSTD_fast    },  /* base for negative levels */
6232     { 14, 14, 15,  1,  5,  0, ZSTD_fast    },  /* level  1 */
6233     { 14, 14, 15,  1,  4,  0, ZSTD_fast    },  /* level  2 */
6234     { 14, 14, 15,  2,  4,  0, ZSTD_dfast   },  /* level  3 */
6235     { 14, 14, 14,  4,  4,  2, ZSTD_greedy  },  /* level  4 */
6236     { 14, 14, 14,  3,  4,  4, ZSTD_lazy    },  /* level  5.*/
6237     { 14, 14, 14,  4,  4,  8, ZSTD_lazy2   },  /* level  6 */
6238     { 14, 14, 14,  6,  4,  8, ZSTD_lazy2   },  /* level  7 */
6239     { 14, 14, 14,  8,  4,  8, ZSTD_lazy2   },  /* level  8.*/
6240     { 14, 15, 14,  5,  4,  8, ZSTD_btlazy2 },  /* level  9.*/
6241     { 14, 15, 14,  9,  4,  8, ZSTD_btlazy2 },  /* level 10.*/
6242     { 14, 15, 14,  3,  4, 12, ZSTD_btopt   },  /* level 11.*/
6243     { 14, 15, 14,  4,  3, 24, ZSTD_btopt   },  /* level 12.*/
6244     { 14, 15, 14,  5,  3, 32, ZSTD_btultra },  /* level 13.*/
6245     { 14, 15, 15,  6,  3, 64, ZSTD_btultra },  /* level 14.*/
6246     { 14, 15, 15,  7,  3,256, ZSTD_btultra },  /* level 15.*/
6247     { 14, 15, 15,  5,  3, 48, ZSTD_btultra2},  /* level 16.*/
6248     { 14, 15, 15,  6,  3,128, ZSTD_btultra2},  /* level 17.*/
6249     { 14, 15, 15,  7,  3,256, ZSTD_btultra2},  /* level 18.*/
6250     { 14, 15, 15,  8,  3,256, ZSTD_btultra2},  /* level 19.*/
6251     { 14, 15, 15,  8,  3,512, ZSTD_btultra2},  /* level 20.*/
6252     { 14, 15, 15,  9,  3,512, ZSTD_btultra2},  /* level 21.*/
6253     { 14, 15, 15, 10,  3,999, ZSTD_btultra2},  /* level 22.*/
6254 },
6255 };
6256 
ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel,size_t const dictSize)6257 static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
6258 {
6259     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
6260     switch (cParams.strategy) {
6261         case ZSTD_fast:
6262         case ZSTD_dfast:
6263             break;
6264         case ZSTD_greedy:
6265         case ZSTD_lazy:
6266         case ZSTD_lazy2:
6267             cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;
6268             break;
6269         case ZSTD_btlazy2:
6270         case ZSTD_btopt:
6271         case ZSTD_btultra:
6272         case ZSTD_btultra2:
6273             break;
6274     }
6275     return cParams;
6276 }
6277 
ZSTD_dedicatedDictSearch_isSupported(ZSTD_compressionParameters const * cParams)6278 static int ZSTD_dedicatedDictSearch_isSupported(
6279         ZSTD_compressionParameters const* cParams)
6280 {
6281     return (cParams->strategy >= ZSTD_greedy)
6282         && (cParams->strategy <= ZSTD_lazy2)
6283         && (cParams->hashLog > cParams->chainLog)
6284         && (cParams->chainLog <= 24);
6285 }
6286 
6287 /**
6288  * Reverses the adjustment applied to cparams when enabling dedicated dict
6289  * search. This is used to recover the params set to be used in the working
6290  * context. (Otherwise, those tables would also grow.)
6291  */
ZSTD_dedicatedDictSearch_revertCParams(ZSTD_compressionParameters * cParams)6292 static void ZSTD_dedicatedDictSearch_revertCParams(
6293         ZSTD_compressionParameters* cParams) {
6294     switch (cParams->strategy) {
6295         case ZSTD_fast:
6296         case ZSTD_dfast:
6297             break;
6298         case ZSTD_greedy:
6299         case ZSTD_lazy:
6300         case ZSTD_lazy2:
6301             cParams->hashLog -= ZSTD_LAZY_DDSS_BUCKET_LOG;
6302             if (cParams->hashLog < ZSTD_HASHLOG_MIN) {
6303                 cParams->hashLog = ZSTD_HASHLOG_MIN;
6304             }
6305             break;
6306         case ZSTD_btlazy2:
6307         case ZSTD_btopt:
6308         case ZSTD_btultra:
6309         case ZSTD_btultra2:
6310             break;
6311     }
6312 }
6313 
ZSTD_getCParamRowSize(U64 srcSizeHint,size_t dictSize,ZSTD_cParamMode_e mode)6314 static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
6315 {
6316     switch (mode) {
6317     case ZSTD_cpm_unknown:
6318     case ZSTD_cpm_noAttachDict:
6319     case ZSTD_cpm_createCDict:
6320         break;
6321     case ZSTD_cpm_attachDict:
6322         dictSize = 0;
6323         break;
6324     default:
6325         assert(0);
6326         break;
6327     }
6328     {   int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;
6329         size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;
6330         return unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;
6331     }
6332 }
6333 
6334 /*! ZSTD_getCParams_internal() :
6335  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
6336  *  Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
6337  *        Use dictSize == 0 for unknown or unused.
6338  *  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)6339 static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
6340 {
6341     U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
6342     U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
6343     int row;
6344     DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
6345 
6346     /* row */
6347     if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT;   /* 0 == default */
6348     else if (compressionLevel < 0) row = 0;   /* entry 0 is baseline for fast mode */
6349     else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
6350     else row = compressionLevel;
6351 
6352     {   ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
6353         DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);
6354         /* acceleration factor */
6355         if (compressionLevel < 0) {
6356             int const clampedCompressionLevel = MAX(ZSTD_minCLevel(), compressionLevel);
6357             cp.targetLength = (unsigned)(-clampedCompressionLevel);
6358         }
6359         /* refine parameters based on srcSize & dictSize */
6360         return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode);
6361     }
6362 }
6363 
6364 /*! ZSTD_getCParams() :
6365  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
6366  *  Size values are optional, provide 0 if not known or unused */
ZSTD_getCParams(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize)6367 ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
6368 {
6369     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
6370     return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
6371 }
6372 
6373 /*! ZSTD_getParams() :
6374  *  same idea as ZSTD_getCParams()
6375  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
6376  *  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)6377 static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode) {
6378     ZSTD_parameters params;
6379     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
6380     DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
6381     ZSTD_memset(&params, 0, sizeof(params));
6382     params.cParams = cParams;
6383     params.fParams.contentSizeFlag = 1;
6384     return params;
6385 }
6386 
6387 /*! ZSTD_getParams() :
6388  *  same idea as ZSTD_getCParams()
6389  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
6390  *  Fields of `ZSTD_frameParameters` are set to default values */
ZSTD_getParams(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize)6391 ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
6392     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
6393     return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
6394 }
6395