• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
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/allocations.h"  /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
15 #include "../common/zstd_deps.h"  /* INT_MAX, ZSTD_memset, ZSTD_memcpy */
16 #include "../common/mem.h"
17 #include "../common/error_private.h"
18 #include "hist.h"           /* HIST_countFast_wksp */
19 #define FSE_STATIC_LINKING_ONLY   /* FSE_encodeSymbol */
20 #include "../common/fse.h"
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 #include  "../common/bits.h"      /* ZSTD_highbit32, ZSTD_rotateRight_U64 */
32 
33 /* ***************************************************************
34 *  Tuning parameters
35 *****************************************************************/
36 /*!
37  * COMPRESS_HEAPMODE :
38  * Select how default decompression function ZSTD_compress() allocates its context,
39  * on stack (0, default), or into heap (1).
40  * Note that functions with explicit context such as ZSTD_compressCCtx() are unaffected.
41  */
42 #ifndef ZSTD_COMPRESS_HEAPMODE
43 #  define ZSTD_COMPRESS_HEAPMODE 0
44 #endif
45 
46 /*!
47  * ZSTD_HASHLOG3_MAX :
48  * Maximum size of the hash table dedicated to find 3-bytes matches,
49  * in log format, aka 17 => 1 << 17 == 128Ki positions.
50  * This structure is only used in zstd_opt.
51  * Since allocation is centralized for all strategies, it has to be known here.
52  * The actual (selected) size of the hash table is then stored in ZSTD_MatchState_t.hashLog3,
53  * so that zstd_opt.c doesn't need to know about this constant.
54  */
55 #ifndef ZSTD_HASHLOG3_MAX
56 #  define ZSTD_HASHLOG3_MAX 17
57 #endif
58 
59 /*-*************************************
60 *  Helper functions
61 ***************************************/
62 /* ZSTD_compressBound()
63  * Note that the result from this function is only valid for
64  * the one-pass compression functions.
65  * When employing the streaming mode,
66  * if flushes are frequently altering the size of blocks,
67  * the overhead from block headers can make the compressed data larger
68  * than the return value of ZSTD_compressBound().
69  */
ZSTD_compressBound(size_t srcSize)70 size_t ZSTD_compressBound(size_t srcSize) {
71     size_t const r = ZSTD_COMPRESSBOUND(srcSize);
72     if (r==0) return ERROR(srcSize_wrong);
73     return r;
74 }
75 
76 
77 /*-*************************************
78 *  Context memory management
79 ***************************************/
80 struct ZSTD_CDict_s {
81     const void* dictContent;
82     size_t dictContentSize;
83     ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */
84     U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
85     ZSTD_cwksp workspace;
86     ZSTD_MatchState_t matchState;
87     ZSTD_compressedBlockState_t cBlockState;
88     ZSTD_customMem customMem;
89     U32 dictID;
90     int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
91     ZSTD_ParamSwitch_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
92                                            * row-based matchfinder. Unless the cdict is reloaded, we will use
93                                            * the same greedy/lazy matchfinder at compression time.
94                                            */
95 };  /* typedef'd to ZSTD_CDict within "zstd.h" */
96 
ZSTD_createCCtx(void)97 ZSTD_CCtx* ZSTD_createCCtx(void)
98 {
99     return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
100 }
101 
ZSTD_initCCtx(ZSTD_CCtx * cctx,ZSTD_customMem memManager)102 static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
103 {
104     assert(cctx != NULL);
105     ZSTD_memset(cctx, 0, sizeof(*cctx));
106     cctx->customMem = memManager;
107     cctx->bmi2 = ZSTD_cpuSupportsBmi2();
108     {   size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
109         assert(!ZSTD_isError(err));
110         (void)err;
111     }
112 }
113 
ZSTD_createCCtx_advanced(ZSTD_customMem customMem)114 ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
115 {
116     ZSTD_STATIC_ASSERT(zcss_init==0);
117     ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
118     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
119     {   ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_customMalloc(sizeof(ZSTD_CCtx), customMem);
120         if (!cctx) return NULL;
121         ZSTD_initCCtx(cctx, customMem);
122         return cctx;
123     }
124 }
125 
ZSTD_initStaticCCtx(void * workspace,size_t workspaceSize)126 ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize)
127 {
128     ZSTD_cwksp ws;
129     ZSTD_CCtx* cctx;
130     if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL;  /* minimum size */
131     if ((size_t)workspace & 7) return NULL;  /* must be 8-aligned */
132     ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
133 
134     cctx = (ZSTD_CCtx*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CCtx));
135     if (cctx == NULL) return NULL;
136 
137     ZSTD_memset(cctx, 0, sizeof(ZSTD_CCtx));
138     ZSTD_cwksp_move(&cctx->workspace, &ws);
139     cctx->staticSize = workspaceSize;
140 
141     /* statically sized space. tmpWorkspace never moves (but prev/next block swap places) */
142     if (!ZSTD_cwksp_check_available(&cctx->workspace, TMP_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL;
143     cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
144     cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t));
145     cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE);
146     cctx->tmpWkspSize = TMP_WORKSPACE_SIZE;
147     cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
148     return cctx;
149 }
150 
151 /**
152  * Clears and frees all of the dictionaries in the CCtx.
153  */
ZSTD_clearAllDicts(ZSTD_CCtx * cctx)154 static void ZSTD_clearAllDicts(ZSTD_CCtx* cctx)
155 {
156     ZSTD_customFree(cctx->localDict.dictBuffer, cctx->customMem);
157     ZSTD_freeCDict(cctx->localDict.cdict);
158     ZSTD_memset(&cctx->localDict, 0, sizeof(cctx->localDict));
159     ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));
160     cctx->cdict = NULL;
161 }
162 
ZSTD_sizeof_localDict(ZSTD_localDict dict)163 static size_t ZSTD_sizeof_localDict(ZSTD_localDict dict)
164 {
165     size_t const bufferSize = dict.dictBuffer != NULL ? dict.dictSize : 0;
166     size_t const cdictSize = ZSTD_sizeof_CDict(dict.cdict);
167     return bufferSize + cdictSize;
168 }
169 
ZSTD_freeCCtxContent(ZSTD_CCtx * cctx)170 static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
171 {
172     assert(cctx != NULL);
173     assert(cctx->staticSize == 0);
174     ZSTD_clearAllDicts(cctx);
175 #ifdef ZSTD_MULTITHREAD
176     ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
177 #endif
178     ZSTD_cwksp_free(&cctx->workspace, cctx->customMem);
179 }
180 
ZSTD_freeCCtx(ZSTD_CCtx * cctx)181 size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
182 {
183     DEBUGLOG(3, "ZSTD_freeCCtx (address: %p)", (void*)cctx);
184     if (cctx==NULL) return 0;   /* support free on NULL */
185     RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
186                     "not compatible with static CCtx");
187     {   int cctxInWorkspace = ZSTD_cwksp_owns_buffer(&cctx->workspace, cctx);
188         ZSTD_freeCCtxContent(cctx);
189         if (!cctxInWorkspace) ZSTD_customFree(cctx, cctx->customMem);
190     }
191     return 0;
192 }
193 
194 
ZSTD_sizeof_mtctx(const ZSTD_CCtx * cctx)195 static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
196 {
197 #ifdef ZSTD_MULTITHREAD
198     return ZSTDMT_sizeof_CCtx(cctx->mtctx);
199 #else
200     (void)cctx;
201     return 0;
202 #endif
203 }
204 
205 
ZSTD_sizeof_CCtx(const ZSTD_CCtx * cctx)206 size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
207 {
208     if (cctx==NULL) return 0;   /* support sizeof on NULL */
209     /* cctx may be in the workspace */
210     return (cctx->workspace.workspace == cctx ? 0 : sizeof(*cctx))
211            + ZSTD_cwksp_sizeof(&cctx->workspace)
212            + ZSTD_sizeof_localDict(cctx->localDict)
213            + ZSTD_sizeof_mtctx(cctx);
214 }
215 
ZSTD_sizeof_CStream(const ZSTD_CStream * zcs)216 size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
217 {
218     return ZSTD_sizeof_CCtx(zcs);  /* same object */
219 }
220 
221 /* private API call, for dictBuilder only */
ZSTD_getSeqStore(const ZSTD_CCtx * ctx)222 const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
223 
224 /* Returns true if the strategy supports using a row based matchfinder */
ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy)225 static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {
226     return (strategy >= ZSTD_greedy && strategy <= ZSTD_lazy2);
227 }
228 
229 /* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder
230  * for this compression.
231  */
ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy,const ZSTD_ParamSwitch_e mode)232 static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_ParamSwitch_e mode) {
233     assert(mode != ZSTD_ps_auto);
234     return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_ps_enable);
235 }
236 
237 /* Returns row matchfinder usage given an initial mode and cParams */
ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,const ZSTD_compressionParameters * const cParams)238 static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,
239                                                          const ZSTD_compressionParameters* const cParams) {
240     if (mode != ZSTD_ps_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */
241     mode = ZSTD_ps_disable;
242     if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode;
243     if (cParams->windowLog > 14) mode = ZSTD_ps_enable;
244     return mode;
245 }
246 
247 /* Returns block splitter usage (generally speaking, when using slower/stronger compression modes) */
ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e mode,const ZSTD_compressionParameters * const cParams)248 static ZSTD_ParamSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e mode,
249                                                         const ZSTD_compressionParameters* const cParams) {
250     if (mode != ZSTD_ps_auto) return mode;
251     return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17) ? ZSTD_ps_enable : ZSTD_ps_disable;
252 }
253 
254 /* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
ZSTD_allocateChainTable(const ZSTD_strategy strategy,const ZSTD_ParamSwitch_e useRowMatchFinder,const U32 forDDSDict)255 static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
256                                    const ZSTD_ParamSwitch_e useRowMatchFinder,
257                                    const U32 forDDSDict) {
258     assert(useRowMatchFinder != ZSTD_ps_auto);
259     /* We always should allocate a chaintable if we are allocating a matchstate for a DDS dictionary matchstate.
260      * We do not allocate a chaintable if we are using ZSTD_fast, or are using the row-based matchfinder.
261      */
262     return forDDSDict || ((strategy != ZSTD_fast) && !ZSTD_rowMatchFinderUsed(strategy, useRowMatchFinder));
263 }
264 
265 /* Returns ZSTD_ps_enable if compression parameters are such that we should
266  * enable long distance matching (wlog >= 27, strategy >= btopt).
267  * Returns ZSTD_ps_disable otherwise.
268  */
ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e mode,const ZSTD_compressionParameters * const cParams)269 static ZSTD_ParamSwitch_e ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e mode,
270                                  const ZSTD_compressionParameters* const cParams) {
271     if (mode != ZSTD_ps_auto) return mode;
272     return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 27) ? ZSTD_ps_enable : ZSTD_ps_disable;
273 }
274 
ZSTD_resolveExternalSequenceValidation(int mode)275 static int ZSTD_resolveExternalSequenceValidation(int mode) {
276     return mode;
277 }
278 
279 /* Resolves maxBlockSize to the default if no value is present. */
ZSTD_resolveMaxBlockSize(size_t maxBlockSize)280 static size_t ZSTD_resolveMaxBlockSize(size_t maxBlockSize) {
281     if (maxBlockSize == 0) {
282         return ZSTD_BLOCKSIZE_MAX;
283     } else {
284         return maxBlockSize;
285     }
286 }
287 
ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e value,int cLevel)288 static ZSTD_ParamSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e value, int cLevel) {
289     if (value != ZSTD_ps_auto) return value;
290     if (cLevel < 10) {
291         return ZSTD_ps_disable;
292     } else {
293         return ZSTD_ps_enable;
294     }
295 }
296 
297 /* Returns 1 if compression parameters are such that CDict hashtable and chaintable indices are tagged.
298  * If so, the tags need to be removed in ZSTD_resetCCtx_byCopyingCDict. */
ZSTD_CDictIndicesAreTagged(const ZSTD_compressionParameters * const cParams)299 static int ZSTD_CDictIndicesAreTagged(const ZSTD_compressionParameters* const cParams) {
300     return cParams->strategy == ZSTD_fast || cParams->strategy == ZSTD_dfast;
301 }
302 
ZSTD_makeCCtxParamsFromCParams(ZSTD_compressionParameters cParams)303 static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
304         ZSTD_compressionParameters cParams)
305 {
306     ZSTD_CCtx_params cctxParams;
307     /* should not matter, as all cParams are presumed properly defined */
308     ZSTD_CCtxParams_init(&cctxParams, ZSTD_CLEVEL_DEFAULT);
309     cctxParams.cParams = cParams;
310 
311     /* Adjust advanced params according to cParams */
312     cctxParams.ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams.ldmParams.enableLdm, &cParams);
313     if (cctxParams.ldmParams.enableLdm == ZSTD_ps_enable) {
314         ZSTD_ldm_adjustParameters(&cctxParams.ldmParams, &cParams);
315         assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog);
316         assert(cctxParams.ldmParams.hashRateLog < 32);
317     }
318     cctxParams.postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.postBlockSplitter, &cParams);
319     cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
320     cctxParams.validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams.validateSequences);
321     cctxParams.maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams.maxBlockSize);
322     cctxParams.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams.searchForExternalRepcodes,
323                                                                              cctxParams.compressionLevel);
324     assert(!ZSTD_checkCParams(cParams));
325     return cctxParams;
326 }
327 
ZSTD_createCCtxParams_advanced(ZSTD_customMem customMem)328 static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
329         ZSTD_customMem customMem)
330 {
331     ZSTD_CCtx_params* params;
332     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
333     params = (ZSTD_CCtx_params*)ZSTD_customCalloc(
334             sizeof(ZSTD_CCtx_params), customMem);
335     if (!params) { return NULL; }
336     ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
337     params->customMem = customMem;
338     return params;
339 }
340 
ZSTD_createCCtxParams(void)341 ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
342 {
343     return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
344 }
345 
ZSTD_freeCCtxParams(ZSTD_CCtx_params * params)346 size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
347 {
348     if (params == NULL) { return 0; }
349     ZSTD_customFree(params, params->customMem);
350     return 0;
351 }
352 
ZSTD_CCtxParams_reset(ZSTD_CCtx_params * params)353 size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
354 {
355     return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
356 }
357 
ZSTD_CCtxParams_init(ZSTD_CCtx_params * cctxParams,int compressionLevel)358 size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
359     RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
360     ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
361     cctxParams->compressionLevel = compressionLevel;
362     cctxParams->fParams.contentSizeFlag = 1;
363     return 0;
364 }
365 
366 #define ZSTD_NO_CLEVEL 0
367 
368 /**
369  * Initializes `cctxParams` from `params` and `compressionLevel`.
370  * @param compressionLevel If params are derived from a compression level then that compression level, otherwise ZSTD_NO_CLEVEL.
371  */
372 static void
ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params * cctxParams,const ZSTD_parameters * params,int compressionLevel)373 ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams,
374                         const ZSTD_parameters* params,
375                               int compressionLevel)
376 {
377     assert(!ZSTD_checkCParams(params->cParams));
378     ZSTD_memset(cctxParams, 0, sizeof(*cctxParams));
379     cctxParams->cParams = params->cParams;
380     cctxParams->fParams = params->fParams;
381     /* Should not matter, as all cParams are presumed properly defined.
382      * But, set it for tracing anyway.
383      */
384     cctxParams->compressionLevel = compressionLevel;
385     cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, &params->cParams);
386     cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->postBlockSplitter, &params->cParams);
387     cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams->ldmParams.enableLdm, &params->cParams);
388     cctxParams->validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams->validateSequences);
389     cctxParams->maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams->maxBlockSize);
390     cctxParams->searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams->searchForExternalRepcodes, compressionLevel);
391     DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d, useBlockSplitter=%d ldm=%d",
392                 cctxParams->useRowMatchFinder, cctxParams->postBlockSplitter, cctxParams->ldmParams.enableLdm);
393 }
394 
ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params * cctxParams,ZSTD_parameters params)395 size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
396 {
397     RETURN_ERROR_IF(!cctxParams, GENERIC, "NULL pointer!");
398     FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
399     ZSTD_CCtxParams_init_internal(cctxParams, &params, ZSTD_NO_CLEVEL);
400     return 0;
401 }
402 
403 /**
404  * Sets cctxParams' cParams and fParams from params, but otherwise leaves them alone.
405  * @param params Validated zstd parameters.
406  */
ZSTD_CCtxParams_setZstdParams(ZSTD_CCtx_params * cctxParams,const ZSTD_parameters * params)407 static void ZSTD_CCtxParams_setZstdParams(
408         ZSTD_CCtx_params* cctxParams, const ZSTD_parameters* params)
409 {
410     assert(!ZSTD_checkCParams(params->cParams));
411     cctxParams->cParams = params->cParams;
412     cctxParams->fParams = params->fParams;
413     /* Should not matter, as all cParams are presumed properly defined.
414      * But, set it for tracing anyway.
415      */
416     cctxParams->compressionLevel = ZSTD_NO_CLEVEL;
417 }
418 
ZSTD_cParam_getBounds(ZSTD_cParameter param)419 ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
420 {
421     ZSTD_bounds bounds = { 0, 0, 0 };
422 
423     switch(param)
424     {
425     case ZSTD_c_compressionLevel:
426         bounds.lowerBound = ZSTD_minCLevel();
427         bounds.upperBound = ZSTD_maxCLevel();
428         return bounds;
429 
430     case ZSTD_c_windowLog:
431         bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
432         bounds.upperBound = ZSTD_WINDOWLOG_MAX;
433         return bounds;
434 
435     case ZSTD_c_hashLog:
436         bounds.lowerBound = ZSTD_HASHLOG_MIN;
437         bounds.upperBound = ZSTD_HASHLOG_MAX;
438         return bounds;
439 
440     case ZSTD_c_chainLog:
441         bounds.lowerBound = ZSTD_CHAINLOG_MIN;
442         bounds.upperBound = ZSTD_CHAINLOG_MAX;
443         return bounds;
444 
445     case ZSTD_c_searchLog:
446         bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
447         bounds.upperBound = ZSTD_SEARCHLOG_MAX;
448         return bounds;
449 
450     case ZSTD_c_minMatch:
451         bounds.lowerBound = ZSTD_MINMATCH_MIN;
452         bounds.upperBound = ZSTD_MINMATCH_MAX;
453         return bounds;
454 
455     case ZSTD_c_targetLength:
456         bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
457         bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
458         return bounds;
459 
460     case ZSTD_c_strategy:
461         bounds.lowerBound = ZSTD_STRATEGY_MIN;
462         bounds.upperBound = ZSTD_STRATEGY_MAX;
463         return bounds;
464 
465     case ZSTD_c_contentSizeFlag:
466         bounds.lowerBound = 0;
467         bounds.upperBound = 1;
468         return bounds;
469 
470     case ZSTD_c_checksumFlag:
471         bounds.lowerBound = 0;
472         bounds.upperBound = 1;
473         return bounds;
474 
475     case ZSTD_c_dictIDFlag:
476         bounds.lowerBound = 0;
477         bounds.upperBound = 1;
478         return bounds;
479 
480     case ZSTD_c_nbWorkers:
481         bounds.lowerBound = 0;
482 #ifdef ZSTD_MULTITHREAD
483         bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
484 #else
485         bounds.upperBound = 0;
486 #endif
487         return bounds;
488 
489     case ZSTD_c_jobSize:
490         bounds.lowerBound = 0;
491 #ifdef ZSTD_MULTITHREAD
492         bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
493 #else
494         bounds.upperBound = 0;
495 #endif
496         return bounds;
497 
498     case ZSTD_c_overlapLog:
499 #ifdef ZSTD_MULTITHREAD
500         bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
501         bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
502 #else
503         bounds.lowerBound = 0;
504         bounds.upperBound = 0;
505 #endif
506         return bounds;
507 
508     case ZSTD_c_enableDedicatedDictSearch:
509         bounds.lowerBound = 0;
510         bounds.upperBound = 1;
511         return bounds;
512 
513     case ZSTD_c_enableLongDistanceMatching:
514         bounds.lowerBound = (int)ZSTD_ps_auto;
515         bounds.upperBound = (int)ZSTD_ps_disable;
516         return bounds;
517 
518     case ZSTD_c_ldmHashLog:
519         bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
520         bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
521         return bounds;
522 
523     case ZSTD_c_ldmMinMatch:
524         bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
525         bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
526         return bounds;
527 
528     case ZSTD_c_ldmBucketSizeLog:
529         bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
530         bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
531         return bounds;
532 
533     case ZSTD_c_ldmHashRateLog:
534         bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
535         bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
536         return bounds;
537 
538     /* experimental parameters */
539     case ZSTD_c_rsyncable:
540         bounds.lowerBound = 0;
541         bounds.upperBound = 1;
542         return bounds;
543 
544     case ZSTD_c_forceMaxWindow :
545         bounds.lowerBound = 0;
546         bounds.upperBound = 1;
547         return bounds;
548 
549     case ZSTD_c_format:
550         ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
551         bounds.lowerBound = ZSTD_f_zstd1;
552         bounds.upperBound = ZSTD_f_zstd1_magicless;   /* note : how to ensure at compile time that this is the highest value enum ? */
553         return bounds;
554 
555     case ZSTD_c_forceAttachDict:
556         ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceLoad);
557         bounds.lowerBound = ZSTD_dictDefaultAttach;
558         bounds.upperBound = ZSTD_dictForceLoad;       /* note : how to ensure at compile time that this is the highest value enum ? */
559         return bounds;
560 
561     case ZSTD_c_literalCompressionMode:
562         ZSTD_STATIC_ASSERT(ZSTD_ps_auto < ZSTD_ps_enable && ZSTD_ps_enable < ZSTD_ps_disable);
563         bounds.lowerBound = (int)ZSTD_ps_auto;
564         bounds.upperBound = (int)ZSTD_ps_disable;
565         return bounds;
566 
567     case ZSTD_c_targetCBlockSize:
568         bounds.lowerBound = ZSTD_TARGETCBLOCKSIZE_MIN;
569         bounds.upperBound = ZSTD_TARGETCBLOCKSIZE_MAX;
570         return bounds;
571 
572     case ZSTD_c_srcSizeHint:
573         bounds.lowerBound = ZSTD_SRCSIZEHINT_MIN;
574         bounds.upperBound = ZSTD_SRCSIZEHINT_MAX;
575         return bounds;
576 
577     case ZSTD_c_stableInBuffer:
578     case ZSTD_c_stableOutBuffer:
579         bounds.lowerBound = (int)ZSTD_bm_buffered;
580         bounds.upperBound = (int)ZSTD_bm_stable;
581         return bounds;
582 
583     case ZSTD_c_blockDelimiters:
584         bounds.lowerBound = (int)ZSTD_sf_noBlockDelimiters;
585         bounds.upperBound = (int)ZSTD_sf_explicitBlockDelimiters;
586         return bounds;
587 
588     case ZSTD_c_validateSequences:
589         bounds.lowerBound = 0;
590         bounds.upperBound = 1;
591         return bounds;
592 
593     case ZSTD_c_splitAfterSequences:
594         bounds.lowerBound = (int)ZSTD_ps_auto;
595         bounds.upperBound = (int)ZSTD_ps_disable;
596         return bounds;
597 
598     case ZSTD_c_blockSplitterLevel:
599         bounds.lowerBound = 0;
600         bounds.upperBound = ZSTD_BLOCKSPLITTER_LEVEL_MAX;
601         return bounds;
602 
603     case ZSTD_c_useRowMatchFinder:
604         bounds.lowerBound = (int)ZSTD_ps_auto;
605         bounds.upperBound = (int)ZSTD_ps_disable;
606         return bounds;
607 
608     case ZSTD_c_deterministicRefPrefix:
609         bounds.lowerBound = 0;
610         bounds.upperBound = 1;
611         return bounds;
612 
613     case ZSTD_c_prefetchCDictTables:
614         bounds.lowerBound = (int)ZSTD_ps_auto;
615         bounds.upperBound = (int)ZSTD_ps_disable;
616         return bounds;
617 
618     case ZSTD_c_enableSeqProducerFallback:
619         bounds.lowerBound = 0;
620         bounds.upperBound = 1;
621         return bounds;
622 
623     case ZSTD_c_maxBlockSize:
624         bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
625         bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
626         return bounds;
627 
628     case ZSTD_c_repcodeResolution:
629         bounds.lowerBound = (int)ZSTD_ps_auto;
630         bounds.upperBound = (int)ZSTD_ps_disable;
631         return bounds;
632 
633     default:
634         bounds.error = ERROR(parameter_unsupported);
635         return bounds;
636     }
637 }
638 
639 /* ZSTD_cParam_clampBounds:
640  * Clamps the value into the bounded range.
641  */
ZSTD_cParam_clampBounds(ZSTD_cParameter cParam,int * value)642 static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)
643 {
644     ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
645     if (ZSTD_isError(bounds.error)) return bounds.error;
646     if (*value < bounds.lowerBound) *value = bounds.lowerBound;
647     if (*value > bounds.upperBound) *value = bounds.upperBound;
648     return 0;
649 }
650 
651 #define BOUNDCHECK(cParam, val)                                       \
652     do {                                                              \
653         RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val),        \
654                         parameter_outOfBound, "Param out of bounds"); \
655     } while (0)
656 
657 
ZSTD_isUpdateAuthorized(ZSTD_cParameter param)658 static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
659 {
660     switch(param)
661     {
662     case ZSTD_c_compressionLevel:
663     case ZSTD_c_hashLog:
664     case ZSTD_c_chainLog:
665     case ZSTD_c_searchLog:
666     case ZSTD_c_minMatch:
667     case ZSTD_c_targetLength:
668     case ZSTD_c_strategy:
669     case ZSTD_c_blockSplitterLevel:
670         return 1;
671 
672     case ZSTD_c_format:
673     case ZSTD_c_windowLog:
674     case ZSTD_c_contentSizeFlag:
675     case ZSTD_c_checksumFlag:
676     case ZSTD_c_dictIDFlag:
677     case ZSTD_c_forceMaxWindow :
678     case ZSTD_c_nbWorkers:
679     case ZSTD_c_jobSize:
680     case ZSTD_c_overlapLog:
681     case ZSTD_c_rsyncable:
682     case ZSTD_c_enableDedicatedDictSearch:
683     case ZSTD_c_enableLongDistanceMatching:
684     case ZSTD_c_ldmHashLog:
685     case ZSTD_c_ldmMinMatch:
686     case ZSTD_c_ldmBucketSizeLog:
687     case ZSTD_c_ldmHashRateLog:
688     case ZSTD_c_forceAttachDict:
689     case ZSTD_c_literalCompressionMode:
690     case ZSTD_c_targetCBlockSize:
691     case ZSTD_c_srcSizeHint:
692     case ZSTD_c_stableInBuffer:
693     case ZSTD_c_stableOutBuffer:
694     case ZSTD_c_blockDelimiters:
695     case ZSTD_c_validateSequences:
696     case ZSTD_c_splitAfterSequences:
697     case ZSTD_c_useRowMatchFinder:
698     case ZSTD_c_deterministicRefPrefix:
699     case ZSTD_c_prefetchCDictTables:
700     case ZSTD_c_enableSeqProducerFallback:
701     case ZSTD_c_maxBlockSize:
702     case ZSTD_c_repcodeResolution:
703     default:
704         return 0;
705     }
706 }
707 
ZSTD_CCtx_setParameter(ZSTD_CCtx * cctx,ZSTD_cParameter param,int value)708 size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
709 {
710     DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
711     if (cctx->streamStage != zcss_init) {
712         if (ZSTD_isUpdateAuthorized(param)) {
713             cctx->cParamsChanged = 1;
714         } else {
715             RETURN_ERROR(stage_wrong, "can only set params in cctx init stage");
716     }   }
717 
718     switch(param)
719     {
720     case ZSTD_c_nbWorkers:
721         RETURN_ERROR_IF((value!=0) && cctx->staticSize, parameter_unsupported,
722                         "MT not compatible with static alloc");
723         break;
724 
725     case ZSTD_c_compressionLevel:
726     case ZSTD_c_windowLog:
727     case ZSTD_c_hashLog:
728     case ZSTD_c_chainLog:
729     case ZSTD_c_searchLog:
730     case ZSTD_c_minMatch:
731     case ZSTD_c_targetLength:
732     case ZSTD_c_strategy:
733     case ZSTD_c_ldmHashRateLog:
734     case ZSTD_c_format:
735     case ZSTD_c_contentSizeFlag:
736     case ZSTD_c_checksumFlag:
737     case ZSTD_c_dictIDFlag:
738     case ZSTD_c_forceMaxWindow:
739     case ZSTD_c_forceAttachDict:
740     case ZSTD_c_literalCompressionMode:
741     case ZSTD_c_jobSize:
742     case ZSTD_c_overlapLog:
743     case ZSTD_c_rsyncable:
744     case ZSTD_c_enableDedicatedDictSearch:
745     case ZSTD_c_enableLongDistanceMatching:
746     case ZSTD_c_ldmHashLog:
747     case ZSTD_c_ldmMinMatch:
748     case ZSTD_c_ldmBucketSizeLog:
749     case ZSTD_c_targetCBlockSize:
750     case ZSTD_c_srcSizeHint:
751     case ZSTD_c_stableInBuffer:
752     case ZSTD_c_stableOutBuffer:
753     case ZSTD_c_blockDelimiters:
754     case ZSTD_c_validateSequences:
755     case ZSTD_c_splitAfterSequences:
756     case ZSTD_c_blockSplitterLevel:
757     case ZSTD_c_useRowMatchFinder:
758     case ZSTD_c_deterministicRefPrefix:
759     case ZSTD_c_prefetchCDictTables:
760     case ZSTD_c_enableSeqProducerFallback:
761     case ZSTD_c_maxBlockSize:
762     case ZSTD_c_repcodeResolution:
763         break;
764 
765     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
766     }
767     return ZSTD_CCtxParams_setParameter(&cctx->requestedParams, param, value);
768 }
769 
ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params * CCtxParams,ZSTD_cParameter param,int value)770 size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
771                                     ZSTD_cParameter param, int value)
772 {
773     DEBUGLOG(4, "ZSTD_CCtxParams_setParameter (%i, %i)", (int)param, value);
774     switch(param)
775     {
776     case ZSTD_c_format :
777         BOUNDCHECK(ZSTD_c_format, value);
778         CCtxParams->format = (ZSTD_format_e)value;
779         return (size_t)CCtxParams->format;
780 
781     case ZSTD_c_compressionLevel : {
782         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
783         if (value == 0)
784             CCtxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
785         else
786             CCtxParams->compressionLevel = value;
787         if (CCtxParams->compressionLevel >= 0) return (size_t)CCtxParams->compressionLevel;
788         return 0;  /* return type (size_t) cannot represent negative values */
789     }
790 
791     case ZSTD_c_windowLog :
792         if (value!=0)   /* 0 => use default */
793             BOUNDCHECK(ZSTD_c_windowLog, value);
794         CCtxParams->cParams.windowLog = (U32)value;
795         return CCtxParams->cParams.windowLog;
796 
797     case ZSTD_c_hashLog :
798         if (value!=0)   /* 0 => use default */
799             BOUNDCHECK(ZSTD_c_hashLog, value);
800         CCtxParams->cParams.hashLog = (U32)value;
801         return CCtxParams->cParams.hashLog;
802 
803     case ZSTD_c_chainLog :
804         if (value!=0)   /* 0 => use default */
805             BOUNDCHECK(ZSTD_c_chainLog, value);
806         CCtxParams->cParams.chainLog = (U32)value;
807         return CCtxParams->cParams.chainLog;
808 
809     case ZSTD_c_searchLog :
810         if (value!=0)   /* 0 => use default */
811             BOUNDCHECK(ZSTD_c_searchLog, value);
812         CCtxParams->cParams.searchLog = (U32)value;
813         return (size_t)value;
814 
815     case ZSTD_c_minMatch :
816         if (value!=0)   /* 0 => use default */
817             BOUNDCHECK(ZSTD_c_minMatch, value);
818         CCtxParams->cParams.minMatch = (U32)value;
819         return CCtxParams->cParams.minMatch;
820 
821     case ZSTD_c_targetLength :
822         BOUNDCHECK(ZSTD_c_targetLength, value);
823         CCtxParams->cParams.targetLength = (U32)value;
824         return CCtxParams->cParams.targetLength;
825 
826     case ZSTD_c_strategy :
827         if (value!=0)   /* 0 => use default */
828             BOUNDCHECK(ZSTD_c_strategy, value);
829         CCtxParams->cParams.strategy = (ZSTD_strategy)value;
830         return (size_t)CCtxParams->cParams.strategy;
831 
832     case ZSTD_c_contentSizeFlag :
833         /* Content size written in frame header _when known_ (default:1) */
834         DEBUGLOG(4, "set content size flag = %u", (value!=0));
835         CCtxParams->fParams.contentSizeFlag = value != 0;
836         return (size_t)CCtxParams->fParams.contentSizeFlag;
837 
838     case ZSTD_c_checksumFlag :
839         /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
840         CCtxParams->fParams.checksumFlag = value != 0;
841         return (size_t)CCtxParams->fParams.checksumFlag;
842 
843     case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
844         DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
845         CCtxParams->fParams.noDictIDFlag = !value;
846         return !CCtxParams->fParams.noDictIDFlag;
847 
848     case ZSTD_c_forceMaxWindow :
849         CCtxParams->forceWindow = (value != 0);
850         return (size_t)CCtxParams->forceWindow;
851 
852     case ZSTD_c_forceAttachDict : {
853         const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
854         BOUNDCHECK(ZSTD_c_forceAttachDict, (int)pref);
855         CCtxParams->attachDictPref = pref;
856         return CCtxParams->attachDictPref;
857     }
858 
859     case ZSTD_c_literalCompressionMode : {
860         const ZSTD_ParamSwitch_e lcm = (ZSTD_ParamSwitch_e)value;
861         BOUNDCHECK(ZSTD_c_literalCompressionMode, (int)lcm);
862         CCtxParams->literalCompressionMode = lcm;
863         return CCtxParams->literalCompressionMode;
864     }
865 
866     case ZSTD_c_nbWorkers :
867 #ifndef ZSTD_MULTITHREAD
868         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
869         return 0;
870 #else
871         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
872         CCtxParams->nbWorkers = value;
873         return (size_t)(CCtxParams->nbWorkers);
874 #endif
875 
876     case ZSTD_c_jobSize :
877 #ifndef ZSTD_MULTITHREAD
878         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
879         return 0;
880 #else
881         /* Adjust to the minimum non-default value. */
882         if (value != 0 && value < ZSTDMT_JOBSIZE_MIN)
883             value = ZSTDMT_JOBSIZE_MIN;
884         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), "");
885         assert(value >= 0);
886         CCtxParams->jobSize = (size_t)value;
887         return CCtxParams->jobSize;
888 #endif
889 
890     case ZSTD_c_overlapLog :
891 #ifndef ZSTD_MULTITHREAD
892         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
893         return 0;
894 #else
895         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
896         CCtxParams->overlapLog = value;
897         return (size_t)CCtxParams->overlapLog;
898 #endif
899 
900     case ZSTD_c_rsyncable :
901 #ifndef ZSTD_MULTITHREAD
902         RETURN_ERROR_IF(value!=0, parameter_unsupported, "not compiled with multithreading");
903         return 0;
904 #else
905         FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), "");
906         CCtxParams->rsyncable = value;
907         return (size_t)CCtxParams->rsyncable;
908 #endif
909 
910     case ZSTD_c_enableDedicatedDictSearch :
911         CCtxParams->enableDedicatedDictSearch = (value!=0);
912         return (size_t)CCtxParams->enableDedicatedDictSearch;
913 
914     case ZSTD_c_enableLongDistanceMatching :
915         BOUNDCHECK(ZSTD_c_enableLongDistanceMatching, value);
916         CCtxParams->ldmParams.enableLdm = (ZSTD_ParamSwitch_e)value;
917         return CCtxParams->ldmParams.enableLdm;
918 
919     case ZSTD_c_ldmHashLog :
920         if (value!=0)   /* 0 ==> auto */
921             BOUNDCHECK(ZSTD_c_ldmHashLog, value);
922         CCtxParams->ldmParams.hashLog = (U32)value;
923         return CCtxParams->ldmParams.hashLog;
924 
925     case ZSTD_c_ldmMinMatch :
926         if (value!=0)   /* 0 ==> default */
927             BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
928         CCtxParams->ldmParams.minMatchLength = (U32)value;
929         return CCtxParams->ldmParams.minMatchLength;
930 
931     case ZSTD_c_ldmBucketSizeLog :
932         if (value!=0)   /* 0 ==> default */
933             BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
934         CCtxParams->ldmParams.bucketSizeLog = (U32)value;
935         return CCtxParams->ldmParams.bucketSizeLog;
936 
937     case ZSTD_c_ldmHashRateLog :
938         if (value!=0)   /* 0 ==> default */
939             BOUNDCHECK(ZSTD_c_ldmHashRateLog, value);
940         CCtxParams->ldmParams.hashRateLog = (U32)value;
941         return CCtxParams->ldmParams.hashRateLog;
942 
943     case ZSTD_c_targetCBlockSize :
944         if (value!=0) {  /* 0 ==> default */
945             value = MAX(value, ZSTD_TARGETCBLOCKSIZE_MIN);
946             BOUNDCHECK(ZSTD_c_targetCBlockSize, value);
947         }
948         CCtxParams->targetCBlockSize = (U32)value;
949         return CCtxParams->targetCBlockSize;
950 
951     case ZSTD_c_srcSizeHint :
952         if (value!=0)    /* 0 ==> default */
953             BOUNDCHECK(ZSTD_c_srcSizeHint, value);
954         CCtxParams->srcSizeHint = value;
955         return (size_t)CCtxParams->srcSizeHint;
956 
957     case ZSTD_c_stableInBuffer:
958         BOUNDCHECK(ZSTD_c_stableInBuffer, value);
959         CCtxParams->inBufferMode = (ZSTD_bufferMode_e)value;
960         return CCtxParams->inBufferMode;
961 
962     case ZSTD_c_stableOutBuffer:
963         BOUNDCHECK(ZSTD_c_stableOutBuffer, value);
964         CCtxParams->outBufferMode = (ZSTD_bufferMode_e)value;
965         return CCtxParams->outBufferMode;
966 
967     case ZSTD_c_blockDelimiters:
968         BOUNDCHECK(ZSTD_c_blockDelimiters, value);
969         CCtxParams->blockDelimiters = (ZSTD_SequenceFormat_e)value;
970         return CCtxParams->blockDelimiters;
971 
972     case ZSTD_c_validateSequences:
973         BOUNDCHECK(ZSTD_c_validateSequences, value);
974         CCtxParams->validateSequences = value;
975         return (size_t)CCtxParams->validateSequences;
976 
977     case ZSTD_c_splitAfterSequences:
978         BOUNDCHECK(ZSTD_c_splitAfterSequences, value);
979         CCtxParams->postBlockSplitter = (ZSTD_ParamSwitch_e)value;
980         return CCtxParams->postBlockSplitter;
981 
982     case ZSTD_c_blockSplitterLevel:
983         BOUNDCHECK(ZSTD_c_blockSplitterLevel, value);
984         CCtxParams->preBlockSplitter_level = value;
985         return (size_t)CCtxParams->preBlockSplitter_level;
986 
987     case ZSTD_c_useRowMatchFinder:
988         BOUNDCHECK(ZSTD_c_useRowMatchFinder, value);
989         CCtxParams->useRowMatchFinder = (ZSTD_ParamSwitch_e)value;
990         return CCtxParams->useRowMatchFinder;
991 
992     case ZSTD_c_deterministicRefPrefix:
993         BOUNDCHECK(ZSTD_c_deterministicRefPrefix, value);
994         CCtxParams->deterministicRefPrefix = !!value;
995         return (size_t)CCtxParams->deterministicRefPrefix;
996 
997     case ZSTD_c_prefetchCDictTables:
998         BOUNDCHECK(ZSTD_c_prefetchCDictTables, value);
999         CCtxParams->prefetchCDictTables = (ZSTD_ParamSwitch_e)value;
1000         return CCtxParams->prefetchCDictTables;
1001 
1002     case ZSTD_c_enableSeqProducerFallback:
1003         BOUNDCHECK(ZSTD_c_enableSeqProducerFallback, value);
1004         CCtxParams->enableMatchFinderFallback = value;
1005         return (size_t)CCtxParams->enableMatchFinderFallback;
1006 
1007     case ZSTD_c_maxBlockSize:
1008         if (value!=0)    /* 0 ==> default */
1009             BOUNDCHECK(ZSTD_c_maxBlockSize, value);
1010         assert(value>=0);
1011         CCtxParams->maxBlockSize = (size_t)value;
1012         return CCtxParams->maxBlockSize;
1013 
1014     case ZSTD_c_repcodeResolution:
1015         BOUNDCHECK(ZSTD_c_repcodeResolution, value);
1016         CCtxParams->searchForExternalRepcodes = (ZSTD_ParamSwitch_e)value;
1017         return CCtxParams->searchForExternalRepcodes;
1018 
1019     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
1020     }
1021 }
1022 
ZSTD_CCtx_getParameter(ZSTD_CCtx const * cctx,ZSTD_cParameter param,int * value)1023 size_t ZSTD_CCtx_getParameter(ZSTD_CCtx const* cctx, ZSTD_cParameter param, int* value)
1024 {
1025     return ZSTD_CCtxParams_getParameter(&cctx->requestedParams, param, value);
1026 }
1027 
ZSTD_CCtxParams_getParameter(ZSTD_CCtx_params const * CCtxParams,ZSTD_cParameter param,int * value)1028 size_t ZSTD_CCtxParams_getParameter(
1029         ZSTD_CCtx_params const* CCtxParams, ZSTD_cParameter param, int* value)
1030 {
1031     switch(param)
1032     {
1033     case ZSTD_c_format :
1034         *value = (int)CCtxParams->format;
1035         break;
1036     case ZSTD_c_compressionLevel :
1037         *value = CCtxParams->compressionLevel;
1038         break;
1039     case ZSTD_c_windowLog :
1040         *value = (int)CCtxParams->cParams.windowLog;
1041         break;
1042     case ZSTD_c_hashLog :
1043         *value = (int)CCtxParams->cParams.hashLog;
1044         break;
1045     case ZSTD_c_chainLog :
1046         *value = (int)CCtxParams->cParams.chainLog;
1047         break;
1048     case ZSTD_c_searchLog :
1049         *value = (int)CCtxParams->cParams.searchLog;
1050         break;
1051     case ZSTD_c_minMatch :
1052         *value = (int)CCtxParams->cParams.minMatch;
1053         break;
1054     case ZSTD_c_targetLength :
1055         *value = (int)CCtxParams->cParams.targetLength;
1056         break;
1057     case ZSTD_c_strategy :
1058         *value = (int)CCtxParams->cParams.strategy;
1059         break;
1060     case ZSTD_c_contentSizeFlag :
1061         *value = CCtxParams->fParams.contentSizeFlag;
1062         break;
1063     case ZSTD_c_checksumFlag :
1064         *value = CCtxParams->fParams.checksumFlag;
1065         break;
1066     case ZSTD_c_dictIDFlag :
1067         *value = !CCtxParams->fParams.noDictIDFlag;
1068         break;
1069     case ZSTD_c_forceMaxWindow :
1070         *value = CCtxParams->forceWindow;
1071         break;
1072     case ZSTD_c_forceAttachDict :
1073         *value = (int)CCtxParams->attachDictPref;
1074         break;
1075     case ZSTD_c_literalCompressionMode :
1076         *value = (int)CCtxParams->literalCompressionMode;
1077         break;
1078     case ZSTD_c_nbWorkers :
1079 #ifndef ZSTD_MULTITHREAD
1080         assert(CCtxParams->nbWorkers == 0);
1081 #endif
1082         *value = CCtxParams->nbWorkers;
1083         break;
1084     case ZSTD_c_jobSize :
1085 #ifndef ZSTD_MULTITHREAD
1086         RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
1087 #else
1088         assert(CCtxParams->jobSize <= INT_MAX);
1089         *value = (int)CCtxParams->jobSize;
1090         break;
1091 #endif
1092     case ZSTD_c_overlapLog :
1093 #ifndef ZSTD_MULTITHREAD
1094         RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
1095 #else
1096         *value = CCtxParams->overlapLog;
1097         break;
1098 #endif
1099     case ZSTD_c_rsyncable :
1100 #ifndef ZSTD_MULTITHREAD
1101         RETURN_ERROR(parameter_unsupported, "not compiled with multithreading");
1102 #else
1103         *value = CCtxParams->rsyncable;
1104         break;
1105 #endif
1106     case ZSTD_c_enableDedicatedDictSearch :
1107         *value = CCtxParams->enableDedicatedDictSearch;
1108         break;
1109     case ZSTD_c_enableLongDistanceMatching :
1110         *value = (int)CCtxParams->ldmParams.enableLdm;
1111         break;
1112     case ZSTD_c_ldmHashLog :
1113         *value = (int)CCtxParams->ldmParams.hashLog;
1114         break;
1115     case ZSTD_c_ldmMinMatch :
1116         *value = (int)CCtxParams->ldmParams.minMatchLength;
1117         break;
1118     case ZSTD_c_ldmBucketSizeLog :
1119         *value = (int)CCtxParams->ldmParams.bucketSizeLog;
1120         break;
1121     case ZSTD_c_ldmHashRateLog :
1122         *value = (int)CCtxParams->ldmParams.hashRateLog;
1123         break;
1124     case ZSTD_c_targetCBlockSize :
1125         *value = (int)CCtxParams->targetCBlockSize;
1126         break;
1127     case ZSTD_c_srcSizeHint :
1128         *value = (int)CCtxParams->srcSizeHint;
1129         break;
1130     case ZSTD_c_stableInBuffer :
1131         *value = (int)CCtxParams->inBufferMode;
1132         break;
1133     case ZSTD_c_stableOutBuffer :
1134         *value = (int)CCtxParams->outBufferMode;
1135         break;
1136     case ZSTD_c_blockDelimiters :
1137         *value = (int)CCtxParams->blockDelimiters;
1138         break;
1139     case ZSTD_c_validateSequences :
1140         *value = (int)CCtxParams->validateSequences;
1141         break;
1142     case ZSTD_c_splitAfterSequences :
1143         *value = (int)CCtxParams->postBlockSplitter;
1144         break;
1145     case ZSTD_c_blockSplitterLevel :
1146         *value = CCtxParams->preBlockSplitter_level;
1147         break;
1148     case ZSTD_c_useRowMatchFinder :
1149         *value = (int)CCtxParams->useRowMatchFinder;
1150         break;
1151     case ZSTD_c_deterministicRefPrefix:
1152         *value = (int)CCtxParams->deterministicRefPrefix;
1153         break;
1154     case ZSTD_c_prefetchCDictTables:
1155         *value = (int)CCtxParams->prefetchCDictTables;
1156         break;
1157     case ZSTD_c_enableSeqProducerFallback:
1158         *value = CCtxParams->enableMatchFinderFallback;
1159         break;
1160     case ZSTD_c_maxBlockSize:
1161         *value = (int)CCtxParams->maxBlockSize;
1162         break;
1163     case ZSTD_c_repcodeResolution:
1164         *value = (int)CCtxParams->searchForExternalRepcodes;
1165         break;
1166     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
1167     }
1168     return 0;
1169 }
1170 
1171 /** ZSTD_CCtx_setParametersUsingCCtxParams() :
1172  *  just applies `params` into `cctx`
1173  *  no action is performed, parameters are merely stored.
1174  *  If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
1175  *    This is possible even if a compression is ongoing.
1176  *    In which case, new parameters will be applied on the fly, starting with next compression job.
1177  */
ZSTD_CCtx_setParametersUsingCCtxParams(ZSTD_CCtx * cctx,const ZSTD_CCtx_params * params)1178 size_t ZSTD_CCtx_setParametersUsingCCtxParams(
1179         ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
1180 {
1181     DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
1182     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1183                     "The context is in the wrong stage!");
1184     RETURN_ERROR_IF(cctx->cdict, stage_wrong,
1185                     "Can't override parameters with cdict attached (some must "
1186                     "be inherited from the cdict).");
1187 
1188     cctx->requestedParams = *params;
1189     return 0;
1190 }
1191 
ZSTD_CCtx_setCParams(ZSTD_CCtx * cctx,ZSTD_compressionParameters cparams)1192 size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams)
1193 {
1194     ZSTD_STATIC_ASSERT(sizeof(cparams) == 7 * 4 /* all params are listed below */);
1195     DEBUGLOG(4, "ZSTD_CCtx_setCParams");
1196     /* only update if all parameters are valid */
1197     FORWARD_IF_ERROR(ZSTD_checkCParams(cparams), "");
1198     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, (int)cparams.windowLog), "");
1199     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, (int)cparams.chainLog), "");
1200     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, (int)cparams.hashLog), "");
1201     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, (int)cparams.searchLog), "");
1202     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, (int)cparams.minMatch), "");
1203     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, (int)cparams.targetLength), "");
1204     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, (int)cparams.strategy), "");
1205     return 0;
1206 }
1207 
ZSTD_CCtx_setFParams(ZSTD_CCtx * cctx,ZSTD_frameParameters fparams)1208 size_t ZSTD_CCtx_setFParams(ZSTD_CCtx* cctx, ZSTD_frameParameters fparams)
1209 {
1210     ZSTD_STATIC_ASSERT(sizeof(fparams) == 3 * 4 /* all params are listed below */);
1211     DEBUGLOG(4, "ZSTD_CCtx_setFParams");
1212     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, fparams.contentSizeFlag != 0), "");
1213     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, fparams.checksumFlag != 0), "");
1214     FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_dictIDFlag, fparams.noDictIDFlag == 0), "");
1215     return 0;
1216 }
1217 
ZSTD_CCtx_setParams(ZSTD_CCtx * cctx,ZSTD_parameters params)1218 size_t ZSTD_CCtx_setParams(ZSTD_CCtx* cctx, ZSTD_parameters params)
1219 {
1220     DEBUGLOG(4, "ZSTD_CCtx_setParams");
1221     /* First check cParams, because we want to update all or none. */
1222     FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
1223     /* Next set fParams, because this could fail if the cctx isn't in init stage. */
1224     FORWARD_IF_ERROR(ZSTD_CCtx_setFParams(cctx, params.fParams), "");
1225     /* Finally set cParams, which should succeed. */
1226     FORWARD_IF_ERROR(ZSTD_CCtx_setCParams(cctx, params.cParams), "");
1227     return 0;
1228 }
1229 
ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx * cctx,unsigned long long pledgedSrcSize)1230 size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
1231 {
1232     DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %llu bytes", pledgedSrcSize);
1233     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1234                     "Can't set pledgedSrcSize when not in init stage.");
1235     cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
1236     return 0;
1237 }
1238 
1239 static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(
1240         int const compressionLevel,
1241         size_t const dictSize);
1242 static int ZSTD_dedicatedDictSearch_isSupported(
1243         const ZSTD_compressionParameters* cParams);
1244 static void ZSTD_dedicatedDictSearch_revertCParams(
1245         ZSTD_compressionParameters* cParams);
1246 
1247 /**
1248  * Initializes the local dictionary using requested parameters.
1249  * NOTE: Initialization does not employ the pledged src size,
1250  * because the dictionary may be used for multiple compressions.
1251  */
ZSTD_initLocalDict(ZSTD_CCtx * cctx)1252 static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx)
1253 {
1254     ZSTD_localDict* const dl = &cctx->localDict;
1255     if (dl->dict == NULL) {
1256         /* No local dictionary. */
1257         assert(dl->dictBuffer == NULL);
1258         assert(dl->cdict == NULL);
1259         assert(dl->dictSize == 0);
1260         return 0;
1261     }
1262     if (dl->cdict != NULL) {
1263         /* Local dictionary already initialized. */
1264         assert(cctx->cdict == dl->cdict);
1265         return 0;
1266     }
1267     assert(dl->dictSize > 0);
1268     assert(cctx->cdict == NULL);
1269     assert(cctx->prefixDict.dict == NULL);
1270 
1271     dl->cdict = ZSTD_createCDict_advanced2(
1272             dl->dict,
1273             dl->dictSize,
1274             ZSTD_dlm_byRef,
1275             dl->dictContentType,
1276             &cctx->requestedParams,
1277             cctx->customMem);
1278     RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed");
1279     cctx->cdict = dl->cdict;
1280     return 0;
1281 }
1282 
ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType)1283 size_t ZSTD_CCtx_loadDictionary_advanced(
1284         ZSTD_CCtx* cctx,
1285         const void* dict, size_t dictSize,
1286         ZSTD_dictLoadMethod_e dictLoadMethod,
1287         ZSTD_dictContentType_e dictContentType)
1288 {
1289     DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
1290     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1291                     "Can't load a dictionary when cctx is not in init stage.");
1292     ZSTD_clearAllDicts(cctx);  /* erase any previously set dictionary */
1293     if (dict == NULL || dictSize == 0)  /* no dictionary */
1294         return 0;
1295     if (dictLoadMethod == ZSTD_dlm_byRef) {
1296         cctx->localDict.dict = dict;
1297     } else {
1298         /* copy dictionary content inside CCtx to own its lifetime */
1299         void* dictBuffer;
1300         RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
1301                         "static CCtx can't allocate for an internal copy of dictionary");
1302         dictBuffer = ZSTD_customMalloc(dictSize, cctx->customMem);
1303         RETURN_ERROR_IF(dictBuffer==NULL, memory_allocation,
1304                         "allocation failed for dictionary content");
1305         ZSTD_memcpy(dictBuffer, dict, dictSize);
1306         cctx->localDict.dictBuffer = dictBuffer;  /* owned ptr to free */
1307         cctx->localDict.dict = dictBuffer;        /* read-only reference */
1308     }
1309     cctx->localDict.dictSize = dictSize;
1310     cctx->localDict.dictContentType = dictContentType;
1311     return 0;
1312 }
1313 
ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx * cctx,const void * dict,size_t dictSize)1314 size_t ZSTD_CCtx_loadDictionary_byReference(
1315       ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
1316 {
1317     return ZSTD_CCtx_loadDictionary_advanced(
1318             cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
1319 }
1320 
ZSTD_CCtx_loadDictionary(ZSTD_CCtx * cctx,const void * dict,size_t dictSize)1321 size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
1322 {
1323     return ZSTD_CCtx_loadDictionary_advanced(
1324             cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1325 }
1326 
1327 
ZSTD_CCtx_refCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict)1328 size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
1329 {
1330     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1331                     "Can't ref a dict when ctx not in init stage.");
1332     /* Free the existing local cdict (if any) to save memory. */
1333     ZSTD_clearAllDicts(cctx);
1334     cctx->cdict = cdict;
1335     return 0;
1336 }
1337 
ZSTD_CCtx_refThreadPool(ZSTD_CCtx * cctx,ZSTD_threadPool * pool)1338 size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool)
1339 {
1340     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1341                     "Can't ref a pool when ctx not in init stage.");
1342     cctx->pool = pool;
1343     return 0;
1344 }
1345 
ZSTD_CCtx_refPrefix(ZSTD_CCtx * cctx,const void * prefix,size_t prefixSize)1346 size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
1347 {
1348     return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
1349 }
1350 
ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx * cctx,const void * prefix,size_t prefixSize,ZSTD_dictContentType_e dictContentType)1351 size_t ZSTD_CCtx_refPrefix_advanced(
1352         ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
1353 {
1354     RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1355                     "Can't ref a prefix when ctx not in init stage.");
1356     ZSTD_clearAllDicts(cctx);
1357     if (prefix != NULL && prefixSize > 0) {
1358         cctx->prefixDict.dict = prefix;
1359         cctx->prefixDict.dictSize = prefixSize;
1360         cctx->prefixDict.dictContentType = dictContentType;
1361     }
1362     return 0;
1363 }
1364 
1365 /*! ZSTD_CCtx_reset() :
1366  *  Also dumps dictionary */
ZSTD_CCtx_reset(ZSTD_CCtx * cctx,ZSTD_ResetDirective reset)1367 size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
1368 {
1369     if ( (reset == ZSTD_reset_session_only)
1370       || (reset == ZSTD_reset_session_and_parameters) ) {
1371         cctx->streamStage = zcss_init;
1372         cctx->pledgedSrcSizePlusOne = 0;
1373     }
1374     if ( (reset == ZSTD_reset_parameters)
1375       || (reset == ZSTD_reset_session_and_parameters) ) {
1376         RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
1377                         "Reset parameters is only possible during init stage.");
1378         ZSTD_clearAllDicts(cctx);
1379         return ZSTD_CCtxParams_reset(&cctx->requestedParams);
1380     }
1381     return 0;
1382 }
1383 
1384 
1385 /** ZSTD_checkCParams() :
1386     control CParam values remain within authorized range.
1387     @return : 0, or an error code if one value is beyond authorized range */
ZSTD_checkCParams(ZSTD_compressionParameters cParams)1388 size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
1389 {
1390     BOUNDCHECK(ZSTD_c_windowLog, (int)cParams.windowLog);
1391     BOUNDCHECK(ZSTD_c_chainLog,  (int)cParams.chainLog);
1392     BOUNDCHECK(ZSTD_c_hashLog,   (int)cParams.hashLog);
1393     BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog);
1394     BOUNDCHECK(ZSTD_c_minMatch,  (int)cParams.minMatch);
1395     BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength);
1396     BOUNDCHECK(ZSTD_c_strategy,  (int)cParams.strategy);
1397     return 0;
1398 }
1399 
1400 /** ZSTD_clampCParams() :
1401  *  make CParam values within valid range.
1402  *  @return : valid CParams */
1403 static ZSTD_compressionParameters
ZSTD_clampCParams(ZSTD_compressionParameters cParams)1404 ZSTD_clampCParams(ZSTD_compressionParameters cParams)
1405 {
1406 #   define CLAMP_TYPE(cParam, val, type)                                      \
1407         do {                                                                  \
1408             ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);         \
1409             if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound;      \
1410             else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
1411         } while (0)
1412 #   define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
1413     CLAMP(ZSTD_c_windowLog, cParams.windowLog);
1414     CLAMP(ZSTD_c_chainLog,  cParams.chainLog);
1415     CLAMP(ZSTD_c_hashLog,   cParams.hashLog);
1416     CLAMP(ZSTD_c_searchLog, cParams.searchLog);
1417     CLAMP(ZSTD_c_minMatch,  cParams.minMatch);
1418     CLAMP(ZSTD_c_targetLength,cParams.targetLength);
1419     CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
1420     return cParams;
1421 }
1422 
1423 /** ZSTD_cycleLog() :
1424  *  condition for correct operation : hashLog > 1 */
ZSTD_cycleLog(U32 hashLog,ZSTD_strategy strat)1425 U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
1426 {
1427     U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
1428     return hashLog - btScale;
1429 }
1430 
1431 /** ZSTD_dictAndWindowLog() :
1432  * Returns an adjusted window log that is large enough to fit the source and the dictionary.
1433  * The zstd format says that the entire dictionary is valid if one byte of the dictionary
1434  * is within the window. So the hashLog and chainLog should be large enough to reference both
1435  * the dictionary and the window. So we must use this adjusted dictAndWindowLog when downsizing
1436  * the hashLog and windowLog.
1437  * NOTE: srcSize must not be ZSTD_CONTENTSIZE_UNKNOWN.
1438  */
ZSTD_dictAndWindowLog(U32 windowLog,U64 srcSize,U64 dictSize)1439 static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
1440 {
1441     const U64 maxWindowSize = 1ULL << ZSTD_WINDOWLOG_MAX;
1442     /* No dictionary ==> No change */
1443     if (dictSize == 0) {
1444         return windowLog;
1445     }
1446     assert(windowLog <= ZSTD_WINDOWLOG_MAX);
1447     assert(srcSize != ZSTD_CONTENTSIZE_UNKNOWN); /* Handled in ZSTD_adjustCParams_internal() */
1448     {
1449         U64 const windowSize = 1ULL << windowLog;
1450         U64 const dictAndWindowSize = dictSize + windowSize;
1451         /* If the window size is already large enough to fit both the source and the dictionary
1452          * then just use the window size. Otherwise adjust so that it fits the dictionary and
1453          * the window.
1454          */
1455         if (windowSize >= dictSize + srcSize) {
1456             return windowLog; /* Window size large enough already */
1457         } else if (dictAndWindowSize >= maxWindowSize) {
1458             return ZSTD_WINDOWLOG_MAX; /* Larger than max window log */
1459         } else  {
1460             return ZSTD_highbit32((U32)dictAndWindowSize - 1) + 1;
1461         }
1462     }
1463 }
1464 
1465 /** ZSTD_adjustCParams_internal() :
1466  *  optimize `cPar` for a specified input (`srcSize` and `dictSize`).
1467  *  mostly downsize to reduce memory consumption and initialization latency.
1468  * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.
1469  * `mode` is the mode for parameter adjustment. See docs for `ZSTD_CParamMode_e`.
1470  *  note : `srcSize==0` means 0!
1471  *  condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
1472 static ZSTD_compressionParameters
ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,unsigned long long srcSize,size_t dictSize,ZSTD_CParamMode_e mode,ZSTD_ParamSwitch_e useRowMatchFinder)1473 ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
1474                             unsigned long long srcSize,
1475                             size_t dictSize,
1476                             ZSTD_CParamMode_e mode,
1477                             ZSTD_ParamSwitch_e useRowMatchFinder)
1478 {
1479     const U64 minSrcSize = 513; /* (1<<9) + 1 */
1480     const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
1481     assert(ZSTD_checkCParams(cPar)==0);
1482 
1483     /* Cascade the selected strategy down to the next-highest one built into
1484      * this binary. */
1485 #ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR
1486     if (cPar.strategy == ZSTD_btultra2) {
1487         cPar.strategy = ZSTD_btultra;
1488     }
1489     if (cPar.strategy == ZSTD_btultra) {
1490         cPar.strategy = ZSTD_btopt;
1491     }
1492 #endif
1493 #ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR
1494     if (cPar.strategy == ZSTD_btopt) {
1495         cPar.strategy = ZSTD_btlazy2;
1496     }
1497 #endif
1498 #ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR
1499     if (cPar.strategy == ZSTD_btlazy2) {
1500         cPar.strategy = ZSTD_lazy2;
1501     }
1502 #endif
1503 #ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR
1504     if (cPar.strategy == ZSTD_lazy2) {
1505         cPar.strategy = ZSTD_lazy;
1506     }
1507 #endif
1508 #ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR
1509     if (cPar.strategy == ZSTD_lazy) {
1510         cPar.strategy = ZSTD_greedy;
1511     }
1512 #endif
1513 #ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR
1514     if (cPar.strategy == ZSTD_greedy) {
1515         cPar.strategy = ZSTD_dfast;
1516     }
1517 #endif
1518 #ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
1519     if (cPar.strategy == ZSTD_dfast) {
1520         cPar.strategy = ZSTD_fast;
1521         cPar.targetLength = 0;
1522     }
1523 #endif
1524 
1525     switch (mode) {
1526     case ZSTD_cpm_unknown:
1527     case ZSTD_cpm_noAttachDict:
1528         /* If we don't know the source size, don't make any
1529          * assumptions about it. We will already have selected
1530          * smaller parameters if a dictionary is in use.
1531          */
1532         break;
1533     case ZSTD_cpm_createCDict:
1534         /* Assume a small source size when creating a dictionary
1535          * with an unknown source size.
1536          */
1537         if (dictSize && srcSize == ZSTD_CONTENTSIZE_UNKNOWN)
1538             srcSize = minSrcSize;
1539         break;
1540     case ZSTD_cpm_attachDict:
1541         /* Dictionary has its own dedicated parameters which have
1542          * already been selected. We are selecting parameters
1543          * for only the source.
1544          */
1545         dictSize = 0;
1546         break;
1547     default:
1548         assert(0);
1549         break;
1550     }
1551 
1552     /* resize windowLog if input is small enough, to use less memory */
1553     if ( (srcSize <= maxWindowResize)
1554       && (dictSize <= maxWindowResize) )  {
1555         U32 const tSize = (U32)(srcSize + dictSize);
1556         static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
1557         U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
1558                             ZSTD_highbit32(tSize-1) + 1;
1559         if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
1560     }
1561     if (srcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
1562         U32 const dictAndWindowLog = ZSTD_dictAndWindowLog(cPar.windowLog, (U64)srcSize, (U64)dictSize);
1563         U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
1564         if (cPar.hashLog > dictAndWindowLog+1) cPar.hashLog = dictAndWindowLog+1;
1565         if (cycleLog > dictAndWindowLog)
1566             cPar.chainLog -= (cycleLog - dictAndWindowLog);
1567     }
1568 
1569     if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
1570         cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN;  /* minimum wlog required for valid frame header */
1571 
1572     /* We can't use more than 32 bits of hash in total, so that means that we require:
1573      * (hashLog + 8) <= 32 && (chainLog + 8) <= 32
1574      */
1575     if (mode == ZSTD_cpm_createCDict && ZSTD_CDictIndicesAreTagged(&cPar)) {
1576         U32 const maxShortCacheHashLog = 32 - ZSTD_SHORT_CACHE_TAG_BITS;
1577         if (cPar.hashLog > maxShortCacheHashLog) {
1578             cPar.hashLog = maxShortCacheHashLog;
1579         }
1580         if (cPar.chainLog > maxShortCacheHashLog) {
1581             cPar.chainLog = maxShortCacheHashLog;
1582         }
1583     }
1584 
1585 
1586     /* At this point, we aren't 100% sure if we are using the row match finder.
1587      * Unless it is explicitly disabled, conservatively assume that it is enabled.
1588      * In this case it will only be disabled for small sources, so shrinking the
1589      * hash log a little bit shouldn't result in any ratio loss.
1590      */
1591     if (useRowMatchFinder == ZSTD_ps_auto)
1592         useRowMatchFinder = ZSTD_ps_enable;
1593 
1594     /* We can't hash more than 32-bits in total. So that means that we require:
1595      * (hashLog - rowLog + 8) <= 32
1596      */
1597     if (ZSTD_rowMatchFinderUsed(cPar.strategy, useRowMatchFinder)) {
1598         /* Switch to 32-entry rows if searchLog is 5 (or more) */
1599         U32 const rowLog = BOUNDED(4, cPar.searchLog, 6);
1600         U32 const maxRowHashLog = 32 - ZSTD_ROW_HASH_TAG_BITS;
1601         U32 const maxHashLog = maxRowHashLog + rowLog;
1602         assert(cPar.hashLog >= rowLog);
1603         if (cPar.hashLog > maxHashLog) {
1604             cPar.hashLog = maxHashLog;
1605         }
1606     }
1607 
1608     return cPar;
1609 }
1610 
1611 ZSTD_compressionParameters
ZSTD_adjustCParams(ZSTD_compressionParameters cPar,unsigned long long srcSize,size_t dictSize)1612 ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
1613                    unsigned long long srcSize,
1614                    size_t dictSize)
1615 {
1616     cPar = ZSTD_clampCParams(cPar);   /* resulting cPar is necessarily valid (all parameters within range) */
1617     if (srcSize == 0) srcSize = ZSTD_CONTENTSIZE_UNKNOWN;
1618     return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown, ZSTD_ps_auto);
1619 }
1620 
1621 static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
1622 static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
1623 
ZSTD_overrideCParams(ZSTD_compressionParameters * cParams,const ZSTD_compressionParameters * overrides)1624 static void ZSTD_overrideCParams(
1625               ZSTD_compressionParameters* cParams,
1626         const ZSTD_compressionParameters* overrides)
1627 {
1628     if (overrides->windowLog)    cParams->windowLog    = overrides->windowLog;
1629     if (overrides->hashLog)      cParams->hashLog      = overrides->hashLog;
1630     if (overrides->chainLog)     cParams->chainLog     = overrides->chainLog;
1631     if (overrides->searchLog)    cParams->searchLog    = overrides->searchLog;
1632     if (overrides->minMatch)     cParams->minMatch     = overrides->minMatch;
1633     if (overrides->targetLength) cParams->targetLength = overrides->targetLength;
1634     if (overrides->strategy)     cParams->strategy     = overrides->strategy;
1635 }
1636 
ZSTD_getCParamsFromCCtxParams(const ZSTD_CCtx_params * CCtxParams,U64 srcSizeHint,size_t dictSize,ZSTD_CParamMode_e mode)1637 ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
1638         const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
1639 {
1640     ZSTD_compressionParameters cParams;
1641     if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
1642         assert(CCtxParams->srcSizeHint>=0);
1643         srcSizeHint = (U64)CCtxParams->srcSizeHint;
1644     }
1645     cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode);
1646     if (CCtxParams->ldmParams.enableLdm == ZSTD_ps_enable) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
1647     ZSTD_overrideCParams(&cParams, &CCtxParams->cParams);
1648     assert(!ZSTD_checkCParams(cParams));
1649     /* srcSizeHint == 0 means 0 */
1650     return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize, mode, CCtxParams->useRowMatchFinder);
1651 }
1652 
1653 static size_t
ZSTD_sizeof_matchState(const ZSTD_compressionParameters * const cParams,const ZSTD_ParamSwitch_e useRowMatchFinder,const int enableDedicatedDictSearch,const U32 forCCtx)1654 ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
1655                        const ZSTD_ParamSwitch_e useRowMatchFinder,
1656                        const int enableDedicatedDictSearch,
1657                        const U32 forCCtx)
1658 {
1659     /* chain table size should be 0 for fast or row-hash strategies */
1660     size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder, enableDedicatedDictSearch && !forCCtx)
1661                                 ? ((size_t)1 << cParams->chainLog)
1662                                 : 0;
1663     size_t const hSize = ((size_t)1) << cParams->hashLog;
1664     U32    const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
1665     size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
1666     /* We don't use ZSTD_cwksp_alloc_size() here because the tables aren't
1667      * surrounded by redzones in ASAN. */
1668     size_t const tableSpace = chainSize * sizeof(U32)
1669                             + hSize * sizeof(U32)
1670                             + h3Size * sizeof(U32);
1671     size_t const optPotentialSpace =
1672         ZSTD_cwksp_aligned64_alloc_size((MaxML+1) * sizeof(U32))
1673       + ZSTD_cwksp_aligned64_alloc_size((MaxLL+1) * sizeof(U32))
1674       + ZSTD_cwksp_aligned64_alloc_size((MaxOff+1) * sizeof(U32))
1675       + ZSTD_cwksp_aligned64_alloc_size((1<<Litbits) * sizeof(U32))
1676       + ZSTD_cwksp_aligned64_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_match_t))
1677       + ZSTD_cwksp_aligned64_alloc_size(ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
1678     size_t const lazyAdditionalSpace = ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)
1679                                             ? ZSTD_cwksp_aligned64_alloc_size(hSize)
1680                                             : 0;
1681     size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
1682                                 ? optPotentialSpace
1683                                 : 0;
1684     size_t const slackSpace = ZSTD_cwksp_slack_space_required();
1685 
1686     /* tables are guaranteed to be sized in multiples of 64 bytes (or 16 uint32_t) */
1687     ZSTD_STATIC_ASSERT(ZSTD_HASHLOG_MIN >= 4 && ZSTD_WINDOWLOG_MIN >= 4 && ZSTD_CHAINLOG_MIN >= 4);
1688     assert(useRowMatchFinder != ZSTD_ps_auto);
1689 
1690     DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
1691                 (U32)chainSize, (U32)hSize, (U32)h3Size);
1692     return tableSpace + optSpace + slackSpace + lazyAdditionalSpace;
1693 }
1694 
1695 /* Helper function for calculating memory requirements.
1696  * Gives a tighter bound than ZSTD_sequenceBound() by taking minMatch into account. */
ZSTD_maxNbSeq(size_t blockSize,unsigned minMatch,int useSequenceProducer)1697 static size_t ZSTD_maxNbSeq(size_t blockSize, unsigned minMatch, int useSequenceProducer) {
1698     U32 const divider = (minMatch==3 || useSequenceProducer) ? 3 : 4;
1699     return blockSize / divider;
1700 }
1701 
ZSTD_estimateCCtxSize_usingCCtxParams_internal(const ZSTD_compressionParameters * cParams,const ldmParams_t * ldmParams,const int isStatic,const ZSTD_ParamSwitch_e useRowMatchFinder,const size_t buffInSize,const size_t buffOutSize,const U64 pledgedSrcSize,int useSequenceProducer,size_t maxBlockSize)1702 static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1703         const ZSTD_compressionParameters* cParams,
1704         const ldmParams_t* ldmParams,
1705         const int isStatic,
1706         const ZSTD_ParamSwitch_e useRowMatchFinder,
1707         const size_t buffInSize,
1708         const size_t buffOutSize,
1709         const U64 pledgedSrcSize,
1710         int useSequenceProducer,
1711         size_t maxBlockSize)
1712 {
1713     size_t const windowSize = (size_t) BOUNDED(1ULL, 1ULL << cParams->windowLog, pledgedSrcSize);
1714     size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize);
1715     size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer);
1716     size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize)
1717                             + ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(SeqDef))
1718                             + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE));
1719     size_t const tmpWorkSpace = ZSTD_cwksp_alloc_size(TMP_WORKSPACE_SIZE);
1720     size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t));
1721     size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1);
1722 
1723     size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams);
1724     size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize);
1725     size_t const ldmSeqSpace = ldmParams->enableLdm == ZSTD_ps_enable ?
1726         ZSTD_cwksp_aligned64_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0;
1727 
1728 
1729     size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize)
1730                              + ZSTD_cwksp_alloc_size(buffOutSize);
1731 
1732     size_t const cctxSpace = isStatic ? ZSTD_cwksp_alloc_size(sizeof(ZSTD_CCtx)) : 0;
1733 
1734     size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
1735     size_t const externalSeqSpace = useSequenceProducer
1736         ? ZSTD_cwksp_aligned64_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence))
1737         : 0;
1738 
1739     size_t const neededSpace =
1740         cctxSpace +
1741         tmpWorkSpace +
1742         blockStateSpace +
1743         ldmSpace +
1744         ldmSeqSpace +
1745         matchStateSize +
1746         tokenSpace +
1747         bufferSpace +
1748         externalSeqSpace;
1749 
1750     DEBUGLOG(5, "estimate workspace : %u", (U32)neededSpace);
1751     return neededSpace;
1752 }
1753 
ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params * params)1754 size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1755 {
1756     ZSTD_compressionParameters const cParams =
1757                 ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1758     ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
1759                                                                                &cParams);
1760 
1761     RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1762     /* estimateCCtxSize is for one-shot compression. So no buffers should
1763      * be needed. However, we still allocate two 0-sized buffers, which can
1764      * take space under ASAN. */
1765     return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1766         &cParams, &params->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1767 }
1768 
ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)1769 size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
1770 {
1771     ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
1772     if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
1773         /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
1774         size_t noRowCCtxSize;
1775         size_t rowCCtxSize;
1776         initialParams.useRowMatchFinder = ZSTD_ps_disable;
1777         noRowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1778         initialParams.useRowMatchFinder = ZSTD_ps_enable;
1779         rowCCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1780         return MAX(noRowCCtxSize, rowCCtxSize);
1781     } else {
1782         return ZSTD_estimateCCtxSize_usingCCtxParams(&initialParams);
1783     }
1784 }
1785 
ZSTD_estimateCCtxSize_internal(int compressionLevel)1786 static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
1787 {
1788     int tier = 0;
1789     size_t largestSize = 0;
1790     static const unsigned long long srcSizeTiers[4] = {16 KB, 128 KB, 256 KB, ZSTD_CONTENTSIZE_UNKNOWN};
1791     for (; tier < 4; ++tier) {
1792         /* Choose the set of cParams for a given level across all srcSizes that give the largest cctxSize */
1793         ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeTiers[tier], 0, ZSTD_cpm_noAttachDict);
1794         largestSize = MAX(ZSTD_estimateCCtxSize_usingCParams(cParams), largestSize);
1795     }
1796     return largestSize;
1797 }
1798 
ZSTD_estimateCCtxSize(int compressionLevel)1799 size_t ZSTD_estimateCCtxSize(int compressionLevel)
1800 {
1801     int level;
1802     size_t memBudget = 0;
1803     for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1804         /* Ensure monotonically increasing memory usage as compression level increases */
1805         size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
1806         if (newMB > memBudget) memBudget = newMB;
1807     }
1808     return memBudget;
1809 }
1810 
ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params * params)1811 size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
1812 {
1813     RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only.");
1814     {   ZSTD_compressionParameters const cParams =
1815                 ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1816         size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(params->maxBlockSize), (size_t)1 << cParams.windowLog);
1817         size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered)
1818                 ? ((size_t)1 << cParams.windowLog) + blockSize
1819                 : 0;
1820         size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)
1821                 ? ZSTD_compressBound(blockSize) + 1
1822                 : 0;
1823         ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, &params->cParams);
1824 
1825         return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
1826             &cParams, &params->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
1827             ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
1828     }
1829 }
1830 
ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)1831 size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
1832 {
1833     ZSTD_CCtx_params initialParams = ZSTD_makeCCtxParamsFromCParams(cParams);
1834     if (ZSTD_rowMatchFinderSupported(cParams.strategy)) {
1835         /* Pick bigger of not using and using row-based matchfinder for greedy and lazy strategies */
1836         size_t noRowCCtxSize;
1837         size_t rowCCtxSize;
1838         initialParams.useRowMatchFinder = ZSTD_ps_disable;
1839         noRowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1840         initialParams.useRowMatchFinder = ZSTD_ps_enable;
1841         rowCCtxSize = ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1842         return MAX(noRowCCtxSize, rowCCtxSize);
1843     } else {
1844         return ZSTD_estimateCStreamSize_usingCCtxParams(&initialParams);
1845     }
1846 }
1847 
ZSTD_estimateCStreamSize_internal(int compressionLevel)1848 static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
1849 {
1850     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1851     return ZSTD_estimateCStreamSize_usingCParams(cParams);
1852 }
1853 
ZSTD_estimateCStreamSize(int compressionLevel)1854 size_t ZSTD_estimateCStreamSize(int compressionLevel)
1855 {
1856     int level;
1857     size_t memBudget = 0;
1858     for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
1859         size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
1860         if (newMB > memBudget) memBudget = newMB;
1861     }
1862     return memBudget;
1863 }
1864 
1865 /* ZSTD_getFrameProgression():
1866  * tells how much data has been consumed (input) and produced (output) for current frame.
1867  * able to count progression inside worker threads (non-blocking mode).
1868  */
ZSTD_getFrameProgression(const ZSTD_CCtx * cctx)1869 ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
1870 {
1871 #ifdef ZSTD_MULTITHREAD
1872     if (cctx->appliedParams.nbWorkers > 0) {
1873         return ZSTDMT_getFrameProgression(cctx->mtctx);
1874     }
1875 #endif
1876     {   ZSTD_frameProgression fp;
1877         size_t const buffered = (cctx->inBuff == NULL) ? 0 :
1878                                 cctx->inBuffPos - cctx->inToCompress;
1879         if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
1880         assert(buffered <= ZSTD_BLOCKSIZE_MAX);
1881         fp.ingested = cctx->consumedSrcSize + buffered;
1882         fp.consumed = cctx->consumedSrcSize;
1883         fp.produced = cctx->producedCSize;
1884         fp.flushed  = cctx->producedCSize;   /* simplified; some data might still be left within streaming output buffer */
1885         fp.currentJobID = 0;
1886         fp.nbActiveWorkers = 0;
1887         return fp;
1888 }   }
1889 
1890 /*! ZSTD_toFlushNow()
1891  *  Only useful for multithreading scenarios currently (nbWorkers >= 1).
1892  */
ZSTD_toFlushNow(ZSTD_CCtx * cctx)1893 size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
1894 {
1895 #ifdef ZSTD_MULTITHREAD
1896     if (cctx->appliedParams.nbWorkers > 0) {
1897         return ZSTDMT_toFlushNow(cctx->mtctx);
1898     }
1899 #endif
1900     (void)cctx;
1901     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 */
1902 }
1903 
ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,ZSTD_compressionParameters cParams2)1904 static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
1905                                     ZSTD_compressionParameters cParams2)
1906 {
1907     (void)cParams1;
1908     (void)cParams2;
1909     assert(cParams1.windowLog    == cParams2.windowLog);
1910     assert(cParams1.chainLog     == cParams2.chainLog);
1911     assert(cParams1.hashLog      == cParams2.hashLog);
1912     assert(cParams1.searchLog    == cParams2.searchLog);
1913     assert(cParams1.minMatch     == cParams2.minMatch);
1914     assert(cParams1.targetLength == cParams2.targetLength);
1915     assert(cParams1.strategy     == cParams2.strategy);
1916 }
1917 
ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t * bs)1918 void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
1919 {
1920     int i;
1921     for (i = 0; i < ZSTD_REP_NUM; ++i)
1922         bs->rep[i] = repStartValue[i];
1923     bs->entropy.huf.repeatMode = HUF_repeat_none;
1924     bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
1925     bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
1926     bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
1927 }
1928 
1929 /*! ZSTD_invalidateMatchState()
1930  *  Invalidate all the matches in the match finder tables.
1931  *  Requires nextSrc and base to be set (can be NULL).
1932  */
ZSTD_invalidateMatchState(ZSTD_MatchState_t * ms)1933 static void ZSTD_invalidateMatchState(ZSTD_MatchState_t* ms)
1934 {
1935     ZSTD_window_clear(&ms->window);
1936 
1937     ms->nextToUpdate = ms->window.dictLimit;
1938     ms->loadedDictEnd = 0;
1939     ms->opt.litLengthSum = 0;  /* force reset of btopt stats */
1940     ms->dictMatchState = NULL;
1941 }
1942 
1943 /**
1944  * Controls, for this matchState reset, whether the tables need to be cleared /
1945  * prepared for the coming compression (ZSTDcrp_makeClean), or whether the
1946  * tables can be left unclean (ZSTDcrp_leaveDirty), because we know that a
1947  * subsequent operation will overwrite the table space anyways (e.g., copying
1948  * the matchState contents in from a CDict).
1949  */
1950 typedef enum {
1951     ZSTDcrp_makeClean,
1952     ZSTDcrp_leaveDirty
1953 } ZSTD_compResetPolicy_e;
1954 
1955 /**
1956  * Controls, for this matchState reset, whether indexing can continue where it
1957  * left off (ZSTDirp_continue), or whether it needs to be restarted from zero
1958  * (ZSTDirp_reset).
1959  */
1960 typedef enum {
1961     ZSTDirp_continue,
1962     ZSTDirp_reset
1963 } ZSTD_indexResetPolicy_e;
1964 
1965 typedef enum {
1966     ZSTD_resetTarget_CDict,
1967     ZSTD_resetTarget_CCtx
1968 } ZSTD_resetTarget_e;
1969 
1970 /* Mixes bits in a 64 bits in a value, based on XXH3_rrmxmx */
ZSTD_bitmix(U64 val,U64 len)1971 static U64 ZSTD_bitmix(U64 val, U64 len) {
1972     val ^= ZSTD_rotateRight_U64(val, 49) ^ ZSTD_rotateRight_U64(val, 24);
1973     val *= 0x9FB21C651E98DF25ULL;
1974     val ^= (val >> 35) + len ;
1975     val *= 0x9FB21C651E98DF25ULL;
1976     return val ^ (val >> 28);
1977 }
1978 
1979 /* Mixes in the hashSalt and hashSaltEntropy to create a new hashSalt */
ZSTD_advanceHashSalt(ZSTD_MatchState_t * ms)1980 static void ZSTD_advanceHashSalt(ZSTD_MatchState_t* ms) {
1981     ms->hashSalt = ZSTD_bitmix(ms->hashSalt, 8) ^ ZSTD_bitmix((U64) ms->hashSaltEntropy, 4);
1982 }
1983 
1984 static size_t
ZSTD_reset_matchState(ZSTD_MatchState_t * ms,ZSTD_cwksp * ws,const ZSTD_compressionParameters * cParams,const ZSTD_ParamSwitch_e useRowMatchFinder,const ZSTD_compResetPolicy_e crp,const ZSTD_indexResetPolicy_e forceResetIndex,const ZSTD_resetTarget_e forWho)1985 ZSTD_reset_matchState(ZSTD_MatchState_t* ms,
1986                       ZSTD_cwksp* ws,
1987                 const ZSTD_compressionParameters* cParams,
1988                 const ZSTD_ParamSwitch_e useRowMatchFinder,
1989                 const ZSTD_compResetPolicy_e crp,
1990                 const ZSTD_indexResetPolicy_e forceResetIndex,
1991                 const ZSTD_resetTarget_e forWho)
1992 {
1993     /* disable chain table allocation for fast or row-based strategies */
1994     size_t const chainSize = ZSTD_allocateChainTable(cParams->strategy, useRowMatchFinder,
1995                                                      ms->dedicatedDictSearch && (forWho == ZSTD_resetTarget_CDict))
1996                                 ? ((size_t)1 << cParams->chainLog)
1997                                 : 0;
1998     size_t const hSize = ((size_t)1) << cParams->hashLog;
1999     U32    const hashLog3 = ((forWho == ZSTD_resetTarget_CCtx) && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
2000     size_t const h3Size = hashLog3 ? ((size_t)1) << hashLog3 : 0;
2001 
2002     DEBUGLOG(4, "reset indices : %u", forceResetIndex == ZSTDirp_reset);
2003     assert(useRowMatchFinder != ZSTD_ps_auto);
2004     if (forceResetIndex == ZSTDirp_reset) {
2005         ZSTD_window_init(&ms->window);
2006         ZSTD_cwksp_mark_tables_dirty(ws);
2007     }
2008 
2009     ms->hashLog3 = hashLog3;
2010     ms->lazySkipping = 0;
2011 
2012     ZSTD_invalidateMatchState(ms);
2013 
2014     assert(!ZSTD_cwksp_reserve_failed(ws)); /* check that allocation hasn't already failed */
2015 
2016     ZSTD_cwksp_clear_tables(ws);
2017 
2018     DEBUGLOG(5, "reserving table space");
2019     /* table Space */
2020     ms->hashTable = (U32*)ZSTD_cwksp_reserve_table(ws, hSize * sizeof(U32));
2021     ms->chainTable = (U32*)ZSTD_cwksp_reserve_table(ws, chainSize * sizeof(U32));
2022     ms->hashTable3 = (U32*)ZSTD_cwksp_reserve_table(ws, h3Size * sizeof(U32));
2023     RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
2024                     "failed a workspace allocation in ZSTD_reset_matchState");
2025 
2026     DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_leaveDirty);
2027     if (crp!=ZSTDcrp_leaveDirty) {
2028         /* reset tables only */
2029         ZSTD_cwksp_clean_tables(ws);
2030     }
2031 
2032     if (ZSTD_rowMatchFinderUsed(cParams->strategy, useRowMatchFinder)) {
2033         /* Row match finder needs an additional table of hashes ("tags") */
2034         size_t const tagTableSize = hSize;
2035         /* We want to generate a new salt in case we reset a Cctx, but we always want to use
2036          * 0 when we reset a Cdict */
2037         if(forWho == ZSTD_resetTarget_CCtx) {
2038             ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned_init_once(ws, tagTableSize);
2039             ZSTD_advanceHashSalt(ms);
2040         } else {
2041             /* When we are not salting we want to always memset the memory */
2042             ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned64(ws, tagTableSize);
2043             ZSTD_memset(ms->tagTable, 0, tagTableSize);
2044             ms->hashSalt = 0;
2045         }
2046         {   /* Switch to 32-entry rows if searchLog is 5 (or more) */
2047             U32 const rowLog = BOUNDED(4, cParams->searchLog, 6);
2048             assert(cParams->hashLog >= rowLog);
2049             ms->rowHashLog = cParams->hashLog - rowLog;
2050         }
2051     }
2052 
2053     /* opt parser space */
2054     if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) {
2055         DEBUGLOG(4, "reserving optimal parser space");
2056         ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (1<<Litbits) * sizeof(unsigned));
2057         ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxLL+1) * sizeof(unsigned));
2058         ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxML+1) * sizeof(unsigned));
2059         ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxOff+1) * sizeof(unsigned));
2060         ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t));
2061         ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
2062     }
2063 
2064     ms->cParams = *cParams;
2065 
2066     RETURN_ERROR_IF(ZSTD_cwksp_reserve_failed(ws), memory_allocation,
2067                     "failed a workspace allocation in ZSTD_reset_matchState");
2068     return 0;
2069 }
2070 
2071 /* ZSTD_indexTooCloseToMax() :
2072  * minor optimization : prefer memset() rather than reduceIndex()
2073  * which is measurably slow in some circumstances (reported for Visual Studio).
2074  * Works when re-using a context for a lot of smallish inputs :
2075  * if all inputs are smaller than ZSTD_INDEXOVERFLOW_MARGIN,
2076  * memset() will be triggered before reduceIndex().
2077  */
2078 #define ZSTD_INDEXOVERFLOW_MARGIN (16 MB)
ZSTD_indexTooCloseToMax(ZSTD_window_t w)2079 static int ZSTD_indexTooCloseToMax(ZSTD_window_t w)
2080 {
2081     return (size_t)(w.nextSrc - w.base) > (ZSTD_CURRENT_MAX - ZSTD_INDEXOVERFLOW_MARGIN);
2082 }
2083 
2084 /** ZSTD_dictTooBig():
2085  * When dictionaries are larger than ZSTD_CHUNKSIZE_MAX they can't be loaded in
2086  * one go generically. So we ensure that in that case we reset the tables to zero,
2087  * so that we can load as much of the dictionary as possible.
2088  */
ZSTD_dictTooBig(size_t const loadedDictSize)2089 static int ZSTD_dictTooBig(size_t const loadedDictSize)
2090 {
2091     return loadedDictSize > ZSTD_CHUNKSIZE_MAX;
2092 }
2093 
2094 /*! ZSTD_resetCCtx_internal() :
2095  * @param loadedDictSize The size of the dictionary to be loaded
2096  * into the context, if any. If no dictionary is used, or the
2097  * dictionary is being attached / copied, then pass 0.
2098  * note : `params` are assumed fully validated at this stage.
2099  */
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)2100 static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
2101                                       ZSTD_CCtx_params const* params,
2102                                       U64 const pledgedSrcSize,
2103                                       size_t const loadedDictSize,
2104                                       ZSTD_compResetPolicy_e const crp,
2105                                       ZSTD_buffered_policy_e const zbuff)
2106 {
2107     ZSTD_cwksp* const ws = &zc->workspace;
2108     DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d useBlockSplitter=%d",
2109                 (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->postBlockSplitter);
2110     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
2111 
2112     zc->isFirstBlock = 1;
2113 
2114     /* Set applied params early so we can modify them for LDM,
2115      * and point params at the applied params.
2116      */
2117     zc->appliedParams = *params;
2118     params = &zc->appliedParams;
2119 
2120     assert(params->useRowMatchFinder != ZSTD_ps_auto);
2121     assert(params->postBlockSplitter != ZSTD_ps_auto);
2122     assert(params->ldmParams.enableLdm != ZSTD_ps_auto);
2123     assert(params->maxBlockSize != 0);
2124     if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
2125         /* Adjust long distance matching parameters */
2126         ZSTD_ldm_adjustParameters(&zc->appliedParams.ldmParams, &params->cParams);
2127         assert(params->ldmParams.hashLog >= params->ldmParams.bucketSizeLog);
2128         assert(params->ldmParams.hashRateLog < 32);
2129     }
2130 
2131     {   size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
2132         size_t const blockSize = MIN(params->maxBlockSize, windowSize);
2133         size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, ZSTD_hasExtSeqProd(params));
2134         size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
2135                 ? ZSTD_compressBound(blockSize) + 1
2136                 : 0;
2137         size_t const buffInSize = (zbuff == ZSTDb_buffered && params->inBufferMode == ZSTD_bm_buffered)
2138                 ? windowSize + blockSize
2139                 : 0;
2140         size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize);
2141 
2142         int const indexTooClose = ZSTD_indexTooCloseToMax(zc->blockState.matchState.window);
2143         int const dictTooBig = ZSTD_dictTooBig(loadedDictSize);
2144         ZSTD_indexResetPolicy_e needsIndexReset =
2145             (indexTooClose || dictTooBig || !zc->initialized) ? ZSTDirp_reset : ZSTDirp_continue;
2146 
2147         size_t const neededSpace =
2148             ZSTD_estimateCCtxSize_usingCCtxParams_internal(
2149                 &params->cParams, &params->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
2150                 buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
2151 
2152         FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
2153 
2154         if (!zc->staticSize) ZSTD_cwksp_bump_oversized_duration(ws, 0);
2155 
2156         {   /* Check if workspace is large enough, alloc a new one if needed */
2157             int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
2158             int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
2159             int resizeWorkspace = workspaceTooSmall || workspaceWasteful;
2160             DEBUGLOG(4, "Need %zu B workspace", neededSpace);
2161             DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
2162 
2163             if (resizeWorkspace) {
2164                 DEBUGLOG(4, "Resize workspaceSize from %zuKB to %zuKB",
2165                             ZSTD_cwksp_sizeof(ws) >> 10,
2166                             neededSpace >> 10);
2167 
2168                 RETURN_ERROR_IF(zc->staticSize, memory_allocation, "static cctx : no resize");
2169 
2170                 needsIndexReset = ZSTDirp_reset;
2171 
2172                 ZSTD_cwksp_free(ws, zc->customMem);
2173                 FORWARD_IF_ERROR(ZSTD_cwksp_create(ws, neededSpace, zc->customMem), "");
2174 
2175                 DEBUGLOG(5, "reserving object space");
2176                 /* Statically sized space.
2177                  * tmpWorkspace never moves,
2178                  * though prev/next block swap places */
2179                 assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t)));
2180                 zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
2181                 RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock");
2182                 zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t));
2183                 RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock");
2184                 zc->tmpWorkspace = ZSTD_cwksp_reserve_object(ws, TMP_WORKSPACE_SIZE);
2185                 RETURN_ERROR_IF(zc->tmpWorkspace == NULL, memory_allocation, "couldn't allocate tmpWorkspace");
2186                 zc->tmpWkspSize = TMP_WORKSPACE_SIZE;
2187         }   }
2188 
2189         ZSTD_cwksp_clear(ws);
2190 
2191         /* init params */
2192         zc->blockState.matchState.cParams = params->cParams;
2193         zc->blockState.matchState.prefetchCDictTables = params->prefetchCDictTables == ZSTD_ps_enable;
2194         zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
2195         zc->consumedSrcSize = 0;
2196         zc->producedCSize = 0;
2197         if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
2198             zc->appliedParams.fParams.contentSizeFlag = 0;
2199         DEBUGLOG(4, "pledged content size : %u ; flag : %u",
2200             (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
2201         zc->blockSizeMax = blockSize;
2202 
2203         XXH64_reset(&zc->xxhState, 0);
2204         zc->stage = ZSTDcs_init;
2205         zc->dictID = 0;
2206         zc->dictContentSize = 0;
2207 
2208         ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
2209 
2210         FORWARD_IF_ERROR(ZSTD_reset_matchState(
2211                 &zc->blockState.matchState,
2212                 ws,
2213                 &params->cParams,
2214                 params->useRowMatchFinder,
2215                 crp,
2216                 needsIndexReset,
2217                 ZSTD_resetTarget_CCtx), "");
2218 
2219         zc->seqStore.sequencesStart = (SeqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(SeqDef));
2220 
2221         /* ldm hash table */
2222         if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
2223             /* TODO: avoid memset? */
2224             size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog;
2225             zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned64(ws, ldmHSize * sizeof(ldmEntry_t));
2226             ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t));
2227             zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned64(ws, maxNbLdmSeq * sizeof(rawSeq));
2228             zc->maxNbLdmSequences = maxNbLdmSeq;
2229 
2230             ZSTD_window_init(&zc->ldmState.window);
2231             zc->ldmState.loadedDictEnd = 0;
2232         }
2233 
2234         /* reserve space for block-level external sequences */
2235         if (ZSTD_hasExtSeqProd(params)) {
2236             size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
2237             zc->extSeqBufCapacity = maxNbExternalSeq;
2238             zc->extSeqBuf =
2239                 (ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned64(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence));
2240         }
2241 
2242         /* buffers */
2243 
2244         /* ZSTD_wildcopy() is used to copy into the literals buffer,
2245          * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
2246          */
2247         zc->seqStore.litStart = ZSTD_cwksp_reserve_buffer(ws, blockSize + WILDCOPY_OVERLENGTH);
2248         zc->seqStore.maxNbLit = blockSize;
2249 
2250         zc->bufferedPolicy = zbuff;
2251         zc->inBuffSize = buffInSize;
2252         zc->inBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffInSize);
2253         zc->outBuffSize = buffOutSize;
2254         zc->outBuff = (char*)ZSTD_cwksp_reserve_buffer(ws, buffOutSize);
2255 
2256         /* ldm bucketOffsets table */
2257         if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
2258             /* TODO: avoid memset? */
2259             size_t const numBuckets =
2260                   ((size_t)1) << (params->ldmParams.hashLog -
2261                                   params->ldmParams.bucketSizeLog);
2262             zc->ldmState.bucketOffsets = ZSTD_cwksp_reserve_buffer(ws, numBuckets);
2263             ZSTD_memset(zc->ldmState.bucketOffsets, 0, numBuckets);
2264         }
2265 
2266         /* sequences storage */
2267         ZSTD_referenceExternalSequences(zc, NULL, 0);
2268         zc->seqStore.maxNbSeq = maxNbSeq;
2269         zc->seqStore.llCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
2270         zc->seqStore.mlCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
2271         zc->seqStore.ofCode = ZSTD_cwksp_reserve_buffer(ws, maxNbSeq * sizeof(BYTE));
2272 
2273         DEBUGLOG(3, "wksp: finished allocating, %zd bytes remain available", ZSTD_cwksp_available_space(ws));
2274         assert(ZSTD_cwksp_estimated_space_within_bounds(ws, neededSpace));
2275 
2276         zc->initialized = 1;
2277 
2278         return 0;
2279     }
2280 }
2281 
2282 /* ZSTD_invalidateRepCodes() :
2283  * ensures next compression will not use repcodes from previous block.
2284  * Note : only works with regular variant;
2285  *        do not use with extDict variant ! */
ZSTD_invalidateRepCodes(ZSTD_CCtx * cctx)2286 void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
2287     int i;
2288     for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
2289     assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
2290 }
2291 
2292 /* These are the approximate sizes for each strategy past which copying the
2293  * dictionary tables into the working context is faster than using them
2294  * in-place.
2295  */
2296 static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
2297     8 KB,  /* unused */
2298     8 KB,  /* ZSTD_fast */
2299     16 KB, /* ZSTD_dfast */
2300     32 KB, /* ZSTD_greedy */
2301     32 KB, /* ZSTD_lazy */
2302     32 KB, /* ZSTD_lazy2 */
2303     32 KB, /* ZSTD_btlazy2 */
2304     32 KB, /* ZSTD_btopt */
2305     8 KB,  /* ZSTD_btultra */
2306     8 KB   /* ZSTD_btultra2 */
2307 };
2308 
ZSTD_shouldAttachDict(const ZSTD_CDict * cdict,const ZSTD_CCtx_params * params,U64 pledgedSrcSize)2309 static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
2310                                  const ZSTD_CCtx_params* params,
2311                                  U64 pledgedSrcSize)
2312 {
2313     size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
2314     int const dedicatedDictSearch = cdict->matchState.dedicatedDictSearch;
2315     return dedicatedDictSearch
2316         || ( ( pledgedSrcSize <= cutoff
2317             || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
2318             || params->attachDictPref == ZSTD_dictForceAttach )
2319           && params->attachDictPref != ZSTD_dictForceCopy
2320           && !params->forceWindow ); /* dictMatchState isn't correctly
2321                                       * handled in _enforceMaxDist */
2322 }
2323 
2324 static size_t
ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict,ZSTD_CCtx_params params,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)2325 ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx,
2326                         const ZSTD_CDict* cdict,
2327                         ZSTD_CCtx_params params,
2328                         U64 pledgedSrcSize,
2329                         ZSTD_buffered_policy_e zbuff)
2330 {
2331     DEBUGLOG(4, "ZSTD_resetCCtx_byAttachingCDict() pledgedSrcSize=%llu",
2332                 (unsigned long long)pledgedSrcSize);
2333     {
2334         ZSTD_compressionParameters adjusted_cdict_cParams = cdict->matchState.cParams;
2335         unsigned const windowLog = params.cParams.windowLog;
2336         assert(windowLog != 0);
2337         /* Resize working context table params for input only, since the dict
2338          * has its own tables. */
2339         /* pledgedSrcSize == 0 means 0! */
2340 
2341         if (cdict->matchState.dedicatedDictSearch) {
2342             ZSTD_dedicatedDictSearch_revertCParams(&adjusted_cdict_cParams);
2343         }
2344 
2345         params.cParams = ZSTD_adjustCParams_internal(adjusted_cdict_cParams, pledgedSrcSize,
2346                                                      cdict->dictContentSize, ZSTD_cpm_attachDict,
2347                                                      params.useRowMatchFinder);
2348         params.cParams.windowLog = windowLog;
2349         params.useRowMatchFinder = cdict->useRowMatchFinder;    /* cdict overrides */
2350         FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
2351                                                  /* loadedDictSize */ 0,
2352                                                  ZSTDcrp_makeClean, zbuff), "");
2353         assert(cctx->appliedParams.cParams.strategy == adjusted_cdict_cParams.strategy);
2354     }
2355 
2356     {   const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
2357                                   - cdict->matchState.window.base);
2358         const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
2359         if (cdictLen == 0) {
2360             /* don't even attach dictionaries with no contents */
2361             DEBUGLOG(4, "skipping attaching empty dictionary");
2362         } else {
2363             DEBUGLOG(4, "attaching dictionary into context");
2364             cctx->blockState.matchState.dictMatchState = &cdict->matchState;
2365 
2366             /* prep working match state so dict matches never have negative indices
2367              * when they are translated to the working context's index space. */
2368             if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
2369                 cctx->blockState.matchState.window.nextSrc =
2370                     cctx->blockState.matchState.window.base + cdictEnd;
2371                 ZSTD_window_clear(&cctx->blockState.matchState.window);
2372             }
2373             /* loadedDictEnd is expressed within the referential of the active context */
2374             cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
2375     }   }
2376 
2377     cctx->dictID = cdict->dictID;
2378     cctx->dictContentSize = cdict->dictContentSize;
2379 
2380     /* copy block state */
2381     ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
2382 
2383     return 0;
2384 }
2385 
ZSTD_copyCDictTableIntoCCtx(U32 * dst,U32 const * src,size_t tableSize,ZSTD_compressionParameters const * cParams)2386 static void ZSTD_copyCDictTableIntoCCtx(U32* dst, U32 const* src, size_t tableSize,
2387                                         ZSTD_compressionParameters const* cParams) {
2388     if (ZSTD_CDictIndicesAreTagged(cParams)){
2389         /* Remove tags from the CDict table if they are present.
2390          * See docs on "short cache" in zstd_compress_internal.h for context. */
2391         size_t i;
2392         for (i = 0; i < tableSize; i++) {
2393             U32 const taggedIndex = src[i];
2394             U32 const index = taggedIndex >> ZSTD_SHORT_CACHE_TAG_BITS;
2395             dst[i] = index;
2396         }
2397     } else {
2398         ZSTD_memcpy(dst, src, tableSize * sizeof(U32));
2399     }
2400 }
2401 
ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict,ZSTD_CCtx_params params,U64 pledgedSrcSize,ZSTD_buffered_policy_e zbuff)2402 static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
2403                             const ZSTD_CDict* cdict,
2404                             ZSTD_CCtx_params params,
2405                             U64 pledgedSrcSize,
2406                             ZSTD_buffered_policy_e zbuff)
2407 {
2408     const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
2409 
2410     assert(!cdict->matchState.dedicatedDictSearch);
2411     DEBUGLOG(4, "ZSTD_resetCCtx_byCopyingCDict() pledgedSrcSize=%llu",
2412                 (unsigned long long)pledgedSrcSize);
2413 
2414     {   unsigned const windowLog = params.cParams.windowLog;
2415         assert(windowLog != 0);
2416         /* Copy only compression parameters related to tables. */
2417         params.cParams = *cdict_cParams;
2418         params.cParams.windowLog = windowLog;
2419         params.useRowMatchFinder = cdict->useRowMatchFinder;
2420         FORWARD_IF_ERROR(ZSTD_resetCCtx_internal(cctx, &params, pledgedSrcSize,
2421                                                  /* loadedDictSize */ 0,
2422                                                  ZSTDcrp_leaveDirty, zbuff), "");
2423         assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
2424         assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
2425         assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
2426     }
2427 
2428     ZSTD_cwksp_mark_tables_dirty(&cctx->workspace);
2429     assert(params.useRowMatchFinder != ZSTD_ps_auto);
2430 
2431     /* copy tables */
2432     {   size_t const chainSize = ZSTD_allocateChainTable(cdict_cParams->strategy, cdict->useRowMatchFinder, 0 /* DDS guaranteed disabled */)
2433                                                             ? ((size_t)1 << cdict_cParams->chainLog)
2434                                                             : 0;
2435         size_t const hSize =  (size_t)1 << cdict_cParams->hashLog;
2436 
2437         ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.hashTable,
2438                                 cdict->matchState.hashTable,
2439                                 hSize, cdict_cParams);
2440 
2441         /* Do not copy cdict's chainTable if cctx has parameters such that it would not use chainTable */
2442         if (ZSTD_allocateChainTable(cctx->appliedParams.cParams.strategy, cctx->appliedParams.useRowMatchFinder, 0 /* forDDSDict */)) {
2443             ZSTD_copyCDictTableIntoCCtx(cctx->blockState.matchState.chainTable,
2444                                     cdict->matchState.chainTable,
2445                                     chainSize, cdict_cParams);
2446         }
2447         /* copy tag table */
2448         if (ZSTD_rowMatchFinderUsed(cdict_cParams->strategy, cdict->useRowMatchFinder)) {
2449             size_t const tagTableSize = hSize;
2450             ZSTD_memcpy(cctx->blockState.matchState.tagTable,
2451                         cdict->matchState.tagTable,
2452                         tagTableSize);
2453             cctx->blockState.matchState.hashSalt = cdict->matchState.hashSalt;
2454         }
2455     }
2456 
2457     /* Zero the hashTable3, since the cdict never fills it */
2458     assert(cctx->blockState.matchState.hashLog3 <= 31);
2459     {   U32 const h3log = cctx->blockState.matchState.hashLog3;
2460         size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2461         assert(cdict->matchState.hashLog3 == 0);
2462         ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
2463     }
2464 
2465     ZSTD_cwksp_mark_tables_clean(&cctx->workspace);
2466 
2467     /* copy dictionary offsets */
2468     {   ZSTD_MatchState_t const* srcMatchState = &cdict->matchState;
2469         ZSTD_MatchState_t* dstMatchState = &cctx->blockState.matchState;
2470         dstMatchState->window       = srcMatchState->window;
2471         dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2472         dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2473     }
2474 
2475     cctx->dictID = cdict->dictID;
2476     cctx->dictContentSize = cdict->dictContentSize;
2477 
2478     /* copy block state */
2479     ZSTD_memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
2480 
2481     return 0;
2482 }
2483 
2484 /* We have a choice between copying the dictionary context into the working
2485  * context, or referencing the dictionary context from the working context
2486  * 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)2487 static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
2488                             const ZSTD_CDict* cdict,
2489                             const ZSTD_CCtx_params* params,
2490                             U64 pledgedSrcSize,
2491                             ZSTD_buffered_policy_e zbuff)
2492 {
2493 
2494     DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
2495                 (unsigned)pledgedSrcSize);
2496 
2497     if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
2498         return ZSTD_resetCCtx_byAttachingCDict(
2499             cctx, cdict, *params, pledgedSrcSize, zbuff);
2500     } else {
2501         return ZSTD_resetCCtx_byCopyingCDict(
2502             cctx, cdict, *params, pledgedSrcSize, zbuff);
2503     }
2504 }
2505 
2506 /*! ZSTD_copyCCtx_internal() :
2507  *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2508  *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2509  *  The "context", in this case, refers to the hash and chain tables,
2510  *  entropy tables, and dictionary references.
2511  * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
2512  * @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)2513 static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
2514                             const ZSTD_CCtx* srcCCtx,
2515                             ZSTD_frameParameters fParams,
2516                             U64 pledgedSrcSize,
2517                             ZSTD_buffered_policy_e zbuff)
2518 {
2519     RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong,
2520                     "Can't copy a ctx that's not in init stage.");
2521     DEBUGLOG(5, "ZSTD_copyCCtx_internal");
2522     ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
2523     {   ZSTD_CCtx_params params = dstCCtx->requestedParams;
2524         /* Copy only compression parameters related to tables. */
2525         params.cParams = srcCCtx->appliedParams.cParams;
2526         assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto);
2527         assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto);
2528         assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto);
2529         params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder;
2530         params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter;
2531         params.ldmParams = srcCCtx->appliedParams.ldmParams;
2532         params.fParams = fParams;
2533         params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize;
2534         ZSTD_resetCCtx_internal(dstCCtx, &params, pledgedSrcSize,
2535                                 /* loadedDictSize */ 0,
2536                                 ZSTDcrp_leaveDirty, zbuff);
2537         assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
2538         assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
2539         assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
2540         assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
2541         assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
2542     }
2543 
2544     ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace);
2545 
2546     /* copy tables */
2547     {   size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy,
2548                                                          srcCCtx->appliedParams.useRowMatchFinder,
2549                                                          0 /* forDDSDict */)
2550                                     ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog)
2551                                     : 0;
2552         size_t const hSize =  (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
2553         U32 const h3log = srcCCtx->blockState.matchState.hashLog3;
2554         size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0;
2555 
2556         ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable,
2557                srcCCtx->blockState.matchState.hashTable,
2558                hSize * sizeof(U32));
2559         ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable,
2560                srcCCtx->blockState.matchState.chainTable,
2561                chainSize * sizeof(U32));
2562         ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3,
2563                srcCCtx->blockState.matchState.hashTable3,
2564                h3Size * sizeof(U32));
2565     }
2566 
2567     ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace);
2568 
2569     /* copy dictionary offsets */
2570     {
2571         const ZSTD_MatchState_t* srcMatchState = &srcCCtx->blockState.matchState;
2572         ZSTD_MatchState_t* dstMatchState = &dstCCtx->blockState.matchState;
2573         dstMatchState->window       = srcMatchState->window;
2574         dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
2575         dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
2576     }
2577     dstCCtx->dictID = srcCCtx->dictID;
2578     dstCCtx->dictContentSize = srcCCtx->dictContentSize;
2579 
2580     /* copy block state */
2581     ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
2582 
2583     return 0;
2584 }
2585 
2586 /*! ZSTD_copyCCtx() :
2587  *  Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
2588  *  Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
2589  *  pledgedSrcSize==0 means "unknown".
2590 *   @return : 0, or an error code */
ZSTD_copyCCtx(ZSTD_CCtx * dstCCtx,const ZSTD_CCtx * srcCCtx,unsigned long long pledgedSrcSize)2591 size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
2592 {
2593     ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
2594     ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy;
2595     ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
2596     if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
2597     fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
2598 
2599     return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
2600                                 fParams, pledgedSrcSize,
2601                                 zbuff);
2602 }
2603 
2604 
2605 #define ZSTD_ROWSIZE 16
2606 /*! ZSTD_reduceTable() :
2607  *  reduce table indexes by `reducerValue`, or squash to zero.
2608  *  PreserveMark preserves "unsorted mark" for btlazy2 strategy.
2609  *  It must be set to a clear 0/1 value, to remove branch during inlining.
2610  *  Presume table size is a multiple of ZSTD_ROWSIZE
2611  *  to help auto-vectorization */
2612 FORCE_INLINE_TEMPLATE void
ZSTD_reduceTable_internal(U32 * const table,U32 const size,U32 const reducerValue,int const preserveMark)2613 ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
2614 {
2615     int const nbRows = (int)size / ZSTD_ROWSIZE;
2616     int cellNb = 0;
2617     int rowNb;
2618     /* Protect special index values < ZSTD_WINDOW_START_INDEX. */
2619     U32 const reducerThreshold = reducerValue + ZSTD_WINDOW_START_INDEX;
2620     assert((size & (ZSTD_ROWSIZE-1)) == 0);  /* multiple of ZSTD_ROWSIZE */
2621     assert(size < (1U<<31));   /* can be cast to int */
2622 
2623 #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
2624     /* To validate that the table reuse logic is sound, and that we don't
2625      * access table space that we haven't cleaned, we re-"poison" the table
2626      * space every time we mark it dirty.
2627      *
2628      * This function however is intended to operate on those dirty tables and
2629      * re-clean them. So when this function is used correctly, we can unpoison
2630      * the memory it operated on. This introduces a blind spot though, since
2631      * if we now try to operate on __actually__ poisoned memory, we will not
2632      * detect that. */
2633     __msan_unpoison(table, size * sizeof(U32));
2634 #endif
2635 
2636     for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
2637         int column;
2638         for (column=0; column<ZSTD_ROWSIZE; column++) {
2639             U32 newVal;
2640             if (preserveMark && table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) {
2641                 /* This write is pointless, but is required(?) for the compiler
2642                  * to auto-vectorize the loop. */
2643                 newVal = ZSTD_DUBT_UNSORTED_MARK;
2644             } else if (table[cellNb] < reducerThreshold) {
2645                 newVal = 0;
2646             } else {
2647                 newVal = table[cellNb] - reducerValue;
2648             }
2649             table[cellNb] = newVal;
2650             cellNb++;
2651     }   }
2652 }
2653 
ZSTD_reduceTable(U32 * const table,U32 const size,U32 const reducerValue)2654 static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
2655 {
2656     ZSTD_reduceTable_internal(table, size, reducerValue, 0);
2657 }
2658 
ZSTD_reduceTable_btlazy2(U32 * const table,U32 const size,U32 const reducerValue)2659 static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
2660 {
2661     ZSTD_reduceTable_internal(table, size, reducerValue, 1);
2662 }
2663 
2664 /*! ZSTD_reduceIndex() :
2665 *   rescale all indexes to avoid future overflow (indexes are U32) */
ZSTD_reduceIndex(ZSTD_MatchState_t * ms,ZSTD_CCtx_params const * params,const U32 reducerValue)2666 static void ZSTD_reduceIndex (ZSTD_MatchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue)
2667 {
2668     {   U32 const hSize = (U32)1 << params->cParams.hashLog;
2669         ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
2670     }
2671 
2672     if (ZSTD_allocateChainTable(params->cParams.strategy, params->useRowMatchFinder, (U32)ms->dedicatedDictSearch)) {
2673         U32 const chainSize = (U32)1 << params->cParams.chainLog;
2674         if (params->cParams.strategy == ZSTD_btlazy2)
2675             ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
2676         else
2677             ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
2678     }
2679 
2680     if (ms->hashLog3) {
2681         U32 const h3Size = (U32)1 << ms->hashLog3;
2682         ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
2683     }
2684 }
2685 
2686 
2687 /*-*******************************************************
2688 *  Block entropic compression
2689 *********************************************************/
2690 
2691 /* See doc/zstd_compression_format.md for detailed format description */
2692 
ZSTD_seqToCodes(const SeqStore_t * seqStorePtr)2693 int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr)
2694 {
2695     const SeqDef* const sequences = seqStorePtr->sequencesStart;
2696     BYTE* const llCodeTable = seqStorePtr->llCode;
2697     BYTE* const ofCodeTable = seqStorePtr->ofCode;
2698     BYTE* const mlCodeTable = seqStorePtr->mlCode;
2699     U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2700     U32 u;
2701     int longOffsets = 0;
2702     assert(nbSeq <= seqStorePtr->maxNbSeq);
2703     for (u=0; u<nbSeq; u++) {
2704         U32 const llv = sequences[u].litLength;
2705         U32 const ofCode = ZSTD_highbit32(sequences[u].offBase);
2706         U32 const mlv = sequences[u].mlBase;
2707         llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
2708         ofCodeTable[u] = (BYTE)ofCode;
2709         mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
2710         assert(!(MEM_64bits() && ofCode >= STREAM_ACCUMULATOR_MIN));
2711         if (MEM_32bits() && ofCode >= STREAM_ACCUMULATOR_MIN)
2712             longOffsets = 1;
2713     }
2714     if (seqStorePtr->longLengthType==ZSTD_llt_literalLength)
2715         llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
2716     if (seqStorePtr->longLengthType==ZSTD_llt_matchLength)
2717         mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
2718     return longOffsets;
2719 }
2720 
2721 /* ZSTD_useTargetCBlockSize():
2722  * Returns if target compressed block size param is being used.
2723  * If used, compression will do best effort to make a compressed block size to be around targetCBlockSize.
2724  * Returns 1 if true, 0 otherwise. */
ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params * cctxParams)2725 static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams)
2726 {
2727     DEBUGLOG(5, "ZSTD_useTargetCBlockSize (targetCBlockSize=%zu)", cctxParams->targetCBlockSize);
2728     return (cctxParams->targetCBlockSize != 0);
2729 }
2730 
2731 /* ZSTD_blockSplitterEnabled():
2732  * Returns if block splitting param is being used
2733  * If used, compression will do best effort to split a block in order to improve compression ratio.
2734  * At the time this function is called, the parameter must be finalized.
2735  * Returns 1 if true, 0 otherwise. */
ZSTD_blockSplitterEnabled(ZSTD_CCtx_params * cctxParams)2736 static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams)
2737 {
2738     DEBUGLOG(5, "ZSTD_blockSplitterEnabled (postBlockSplitter=%d)", cctxParams->postBlockSplitter);
2739     assert(cctxParams->postBlockSplitter != ZSTD_ps_auto);
2740     return (cctxParams->postBlockSplitter == ZSTD_ps_enable);
2741 }
2742 
2743 /* Type returned by ZSTD_buildSequencesStatistics containing finalized symbol encoding types
2744  * and size of the sequences statistics
2745  */
2746 typedef struct {
2747     U32 LLtype;
2748     U32 Offtype;
2749     U32 MLtype;
2750     size_t size;
2751     size_t lastCountSize; /* Accounts for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
2752     int longOffsets;
2753 } ZSTD_symbolEncodingTypeStats_t;
2754 
2755 /* ZSTD_buildSequencesStatistics():
2756  * Returns a ZSTD_symbolEncodingTypeStats_t, or a zstd error code in the `size` field.
2757  * Modifies `nextEntropy` to have the appropriate values as a side effect.
2758  * nbSeq must be greater than 0.
2759  *
2760  * entropyWkspSize must be of size at least ENTROPY_WORKSPACE_SIZE - (MaxSeq + 1)*sizeof(U32)
2761  */
2762 static ZSTD_symbolEncodingTypeStats_t
ZSTD_buildSequencesStatistics(const 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)2763 ZSTD_buildSequencesStatistics(
2764                 const SeqStore_t* seqStorePtr, size_t nbSeq,
2765                 const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy,
2766                       BYTE* dst, const BYTE* const dstEnd,
2767                       ZSTD_strategy strategy, unsigned* countWorkspace,
2768                       void* entropyWorkspace, size_t entropyWkspSize)
2769 {
2770     BYTE* const ostart = dst;
2771     const BYTE* const oend = dstEnd;
2772     BYTE* op = ostart;
2773     FSE_CTable* CTable_LitLength = nextEntropy->litlengthCTable;
2774     FSE_CTable* CTable_OffsetBits = nextEntropy->offcodeCTable;
2775     FSE_CTable* CTable_MatchLength = nextEntropy->matchlengthCTable;
2776     const BYTE* const ofCodeTable = seqStorePtr->ofCode;
2777     const BYTE* const llCodeTable = seqStorePtr->llCode;
2778     const BYTE* const mlCodeTable = seqStorePtr->mlCode;
2779     ZSTD_symbolEncodingTypeStats_t stats;
2780 
2781     stats.lastCountSize = 0;
2782     /* convert length/distances into codes */
2783     stats.longOffsets = ZSTD_seqToCodes(seqStorePtr);
2784     assert(op <= oend);
2785     assert(nbSeq != 0); /* ZSTD_selectEncodingType() divides by nbSeq */
2786     /* build CTable for Literal Lengths */
2787     {   unsigned max = MaxLL;
2788         size_t const mostFrequent = HIST_countFast_wksp(countWorkspace, &max, llCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2789         DEBUGLOG(5, "Building LL table");
2790         nextEntropy->litlength_repeatMode = prevEntropy->litlength_repeatMode;
2791         stats.LLtype = ZSTD_selectEncodingType(&nextEntropy->litlength_repeatMode,
2792                                         countWorkspace, max, mostFrequent, nbSeq,
2793                                         LLFSELog, prevEntropy->litlengthCTable,
2794                                         LL_defaultNorm, LL_defaultNormLog,
2795                                         ZSTD_defaultAllowed, strategy);
2796         assert(set_basic < set_compressed && set_rle < set_compressed);
2797         assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2798         {   size_t const countSize = ZSTD_buildCTable(
2799                 op, (size_t)(oend - op),
2800                 CTable_LitLength, LLFSELog, (SymbolEncodingType_e)stats.LLtype,
2801                 countWorkspace, max, llCodeTable, nbSeq,
2802                 LL_defaultNorm, LL_defaultNormLog, MaxLL,
2803                 prevEntropy->litlengthCTable,
2804                 sizeof(prevEntropy->litlengthCTable),
2805                 entropyWorkspace, entropyWkspSize);
2806             if (ZSTD_isError(countSize)) {
2807                 DEBUGLOG(3, "ZSTD_buildCTable for LitLens failed");
2808                 stats.size = countSize;
2809                 return stats;
2810             }
2811             if (stats.LLtype == set_compressed)
2812                 stats.lastCountSize = countSize;
2813             op += countSize;
2814             assert(op <= oend);
2815     }   }
2816     /* build CTable for Offsets */
2817     {   unsigned max = MaxOff;
2818         size_t const mostFrequent = HIST_countFast_wksp(
2819             countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);  /* can't fail */
2820         /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
2821         ZSTD_DefaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
2822         DEBUGLOG(5, "Building OF table");
2823         nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode;
2824         stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode,
2825                                         countWorkspace, max, mostFrequent, nbSeq,
2826                                         OffFSELog, prevEntropy->offcodeCTable,
2827                                         OF_defaultNorm, OF_defaultNormLog,
2828                                         defaultPolicy, strategy);
2829         assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2830         {   size_t const countSize = ZSTD_buildCTable(
2831                 op, (size_t)(oend - op),
2832                 CTable_OffsetBits, OffFSELog, (SymbolEncodingType_e)stats.Offtype,
2833                 countWorkspace, max, ofCodeTable, nbSeq,
2834                 OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
2835                 prevEntropy->offcodeCTable,
2836                 sizeof(prevEntropy->offcodeCTable),
2837                 entropyWorkspace, entropyWkspSize);
2838             if (ZSTD_isError(countSize)) {
2839                 DEBUGLOG(3, "ZSTD_buildCTable for Offsets failed");
2840                 stats.size = countSize;
2841                 return stats;
2842             }
2843             if (stats.Offtype == set_compressed)
2844                 stats.lastCountSize = countSize;
2845             op += countSize;
2846             assert(op <= oend);
2847     }   }
2848     /* build CTable for MatchLengths */
2849     {   unsigned max = MaxML;
2850         size_t const mostFrequent = HIST_countFast_wksp(
2851             countWorkspace, &max, mlCodeTable, nbSeq, entropyWorkspace, entropyWkspSize);   /* can't fail */
2852         DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
2853         nextEntropy->matchlength_repeatMode = prevEntropy->matchlength_repeatMode;
2854         stats.MLtype = ZSTD_selectEncodingType(&nextEntropy->matchlength_repeatMode,
2855                                         countWorkspace, max, mostFrequent, nbSeq,
2856                                         MLFSELog, prevEntropy->matchlengthCTable,
2857                                         ML_defaultNorm, ML_defaultNormLog,
2858                                         ZSTD_defaultAllowed, strategy);
2859         assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
2860         {   size_t const countSize = ZSTD_buildCTable(
2861                 op, (size_t)(oend - op),
2862                 CTable_MatchLength, MLFSELog, (SymbolEncodingType_e)stats.MLtype,
2863                 countWorkspace, max, mlCodeTable, nbSeq,
2864                 ML_defaultNorm, ML_defaultNormLog, MaxML,
2865                 prevEntropy->matchlengthCTable,
2866                 sizeof(prevEntropy->matchlengthCTable),
2867                 entropyWorkspace, entropyWkspSize);
2868             if (ZSTD_isError(countSize)) {
2869                 DEBUGLOG(3, "ZSTD_buildCTable for MatchLengths failed");
2870                 stats.size = countSize;
2871                 return stats;
2872             }
2873             if (stats.MLtype == set_compressed)
2874                 stats.lastCountSize = countSize;
2875             op += countSize;
2876             assert(op <= oend);
2877     }   }
2878     stats.size = (size_t)(op-ostart);
2879     return stats;
2880 }
2881 
2882 /* ZSTD_entropyCompressSeqStore_internal():
2883  * compresses both literals and sequences
2884  * Returns compressed size of block, or a zstd error.
2885  */
2886 #define SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO 20
2887 MEM_STATIC size_t
ZSTD_entropyCompressSeqStore_internal(void * dst,size_t dstCapacity,const void * literals,size_t litSize,const SeqStore_t * seqStorePtr,const ZSTD_entropyCTables_t * prevEntropy,ZSTD_entropyCTables_t * nextEntropy,const ZSTD_CCtx_params * cctxParams,void * entropyWorkspace,size_t entropyWkspSize,const int bmi2)2888 ZSTD_entropyCompressSeqStore_internal(
2889                               void* dst, size_t dstCapacity,
2890                         const void* literals, size_t litSize,
2891                         const SeqStore_t* seqStorePtr,
2892                         const ZSTD_entropyCTables_t* prevEntropy,
2893                               ZSTD_entropyCTables_t* nextEntropy,
2894                         const ZSTD_CCtx_params* cctxParams,
2895                               void* entropyWorkspace, size_t entropyWkspSize,
2896                         const int bmi2)
2897 {
2898     ZSTD_strategy const strategy = cctxParams->cParams.strategy;
2899     unsigned* count = (unsigned*)entropyWorkspace;
2900     FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
2901     FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
2902     FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
2903     const SeqDef* const sequences = seqStorePtr->sequencesStart;
2904     const size_t nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2905     const BYTE* const ofCodeTable = seqStorePtr->ofCode;
2906     const BYTE* const llCodeTable = seqStorePtr->llCode;
2907     const BYTE* const mlCodeTable = seqStorePtr->mlCode;
2908     BYTE* const ostart = (BYTE*)dst;
2909     BYTE* const oend = ostart + dstCapacity;
2910     BYTE* op = ostart;
2911     size_t lastCountSize;
2912     int longOffsets = 0;
2913 
2914     entropyWorkspace = count + (MaxSeq + 1);
2915     entropyWkspSize -= (MaxSeq + 1) * sizeof(*count);
2916 
2917     DEBUGLOG(5, "ZSTD_entropyCompressSeqStore_internal (nbSeq=%zu, dstCapacity=%zu)", nbSeq, dstCapacity);
2918     ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
2919     assert(entropyWkspSize >= HUF_WORKSPACE_SIZE);
2920 
2921     /* Compress literals */
2922     {   size_t const numSequences = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
2923         /* Base suspicion of uncompressibility on ratio of literals to sequences */
2924         int const suspectUncompressible = (numSequences == 0) || (litSize / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO);
2925 
2926         size_t const cSize = ZSTD_compressLiterals(
2927                                     op, dstCapacity,
2928                                     literals, litSize,
2929                                     entropyWorkspace, entropyWkspSize,
2930                                     &prevEntropy->huf, &nextEntropy->huf,
2931                                     cctxParams->cParams.strategy,
2932                                     ZSTD_literalsCompressionIsDisabled(cctxParams),
2933                                     suspectUncompressible, bmi2);
2934         FORWARD_IF_ERROR(cSize, "ZSTD_compressLiterals failed");
2935         assert(cSize <= dstCapacity);
2936         op += cSize;
2937     }
2938 
2939     /* Sequences Header */
2940     RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
2941                     dstSize_tooSmall, "Can't fit seq hdr in output buf!");
2942     if (nbSeq < 128) {
2943         *op++ = (BYTE)nbSeq;
2944     } else if (nbSeq < LONGNBSEQ) {
2945         op[0] = (BYTE)((nbSeq>>8) + 0x80);
2946         op[1] = (BYTE)nbSeq;
2947         op+=2;
2948     } else {
2949         op[0]=0xFF;
2950         MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ));
2951         op+=3;
2952     }
2953     assert(op <= oend);
2954     if (nbSeq==0) {
2955         /* Copy the old tables over as if we repeated them */
2956         ZSTD_memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
2957         return (size_t)(op - ostart);
2958     }
2959     {   BYTE* const seqHead = op++;
2960         /* build stats for sequences */
2961         const ZSTD_symbolEncodingTypeStats_t stats =
2962                 ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
2963                                              &prevEntropy->fse, &nextEntropy->fse,
2964                                               op, oend,
2965                                               strategy, count,
2966                                               entropyWorkspace, entropyWkspSize);
2967         FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
2968         *seqHead = (BYTE)((stats.LLtype<<6) + (stats.Offtype<<4) + (stats.MLtype<<2));
2969         lastCountSize = stats.lastCountSize;
2970         op += stats.size;
2971         longOffsets = stats.longOffsets;
2972     }
2973 
2974     {   size_t const bitstreamSize = ZSTD_encodeSequences(
2975                                         op, (size_t)(oend - op),
2976                                         CTable_MatchLength, mlCodeTable,
2977                                         CTable_OffsetBits, ofCodeTable,
2978                                         CTable_LitLength, llCodeTable,
2979                                         sequences, nbSeq,
2980                                         longOffsets, bmi2);
2981         FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
2982         op += bitstreamSize;
2983         assert(op <= oend);
2984         /* zstd versions <= 1.3.4 mistakenly report corruption when
2985          * FSE_readNCount() receives a buffer < 4 bytes.
2986          * Fixed by https://github.com/facebook/zstd/pull/1146.
2987          * This can happen when the last set_compressed table present is 2
2988          * bytes and the bitstream is only one byte.
2989          * In this exceedingly rare case, we will simply emit an uncompressed
2990          * block, since it isn't worth optimizing.
2991          */
2992         if (lastCountSize && (lastCountSize + bitstreamSize) < 4) {
2993             /* lastCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
2994             assert(lastCountSize + bitstreamSize == 3);
2995             DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
2996                         "emitting an uncompressed block.");
2997             return 0;
2998         }
2999     }
3000 
3001     DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
3002     return (size_t)(op - ostart);
3003 }
3004 
3005 static size_t
ZSTD_entropyCompressSeqStore_wExtLitBuffer(void * dst,size_t dstCapacity,const void * literals,size_t litSize,size_t blockSize,const SeqStore_t * seqStorePtr,const ZSTD_entropyCTables_t * prevEntropy,ZSTD_entropyCTables_t * nextEntropy,const ZSTD_CCtx_params * cctxParams,void * entropyWorkspace,size_t entropyWkspSize,int bmi2)3006 ZSTD_entropyCompressSeqStore_wExtLitBuffer(
3007                           void* dst, size_t dstCapacity,
3008                     const void* literals, size_t litSize,
3009                           size_t blockSize,
3010                     const SeqStore_t* seqStorePtr,
3011                     const ZSTD_entropyCTables_t* prevEntropy,
3012                           ZSTD_entropyCTables_t* nextEntropy,
3013                     const ZSTD_CCtx_params* cctxParams,
3014                           void* entropyWorkspace, size_t entropyWkspSize,
3015                           int bmi2)
3016 {
3017     size_t const cSize = ZSTD_entropyCompressSeqStore_internal(
3018                             dst, dstCapacity,
3019                             literals, litSize,
3020                             seqStorePtr, prevEntropy, nextEntropy, cctxParams,
3021                             entropyWorkspace, entropyWkspSize, bmi2);
3022     if (cSize == 0) return 0;
3023     /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
3024      * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
3025      */
3026     if ((cSize == ERROR(dstSize_tooSmall)) & (blockSize <= dstCapacity)) {
3027         DEBUGLOG(4, "not enough dstCapacity (%zu) for ZSTD_entropyCompressSeqStore_internal()=> do not compress block", dstCapacity);
3028         return 0;  /* block not compressed */
3029     }
3030     FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed");
3031 
3032     /* Check compressibility */
3033     {   size_t const maxCSize = blockSize - ZSTD_minGain(blockSize, cctxParams->cParams.strategy);
3034         if (cSize >= maxCSize) return 0;  /* block not compressed */
3035     }
3036     DEBUGLOG(5, "ZSTD_entropyCompressSeqStore() cSize: %zu", cSize);
3037     /* libzstd decoder before  > v1.5.4 is not compatible with compressed blocks of size ZSTD_BLOCKSIZE_MAX exactly.
3038      * This restriction is indirectly already fulfilled by respecting ZSTD_minGain() condition above.
3039      */
3040     assert(cSize < ZSTD_BLOCKSIZE_MAX);
3041     return cSize;
3042 }
3043 
3044 static size_t
ZSTD_entropyCompressSeqStore(const 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)3045 ZSTD_entropyCompressSeqStore(
3046                     const SeqStore_t* seqStorePtr,
3047                     const ZSTD_entropyCTables_t* prevEntropy,
3048                           ZSTD_entropyCTables_t* nextEntropy,
3049                     const ZSTD_CCtx_params* cctxParams,
3050                           void* dst, size_t dstCapacity,
3051                           size_t srcSize,
3052                           void* entropyWorkspace, size_t entropyWkspSize,
3053                           int bmi2)
3054 {
3055     return ZSTD_entropyCompressSeqStore_wExtLitBuffer(
3056                 dst, dstCapacity,
3057                 seqStorePtr->litStart, (size_t)(seqStorePtr->lit - seqStorePtr->litStart),
3058                 srcSize,
3059                 seqStorePtr,
3060                 prevEntropy, nextEntropy,
3061                 cctxParams,
3062                 entropyWorkspace, entropyWkspSize,
3063                 bmi2);
3064 }
3065 
3066 /* ZSTD_selectBlockCompressor() :
3067  * Not static, but internal use only (used by long distance matcher)
3068  * assumption : strat is a valid strategy */
ZSTD_selectBlockCompressor(ZSTD_strategy strat,ZSTD_ParamSwitch_e useRowMatchFinder,ZSTD_dictMode_e dictMode)3069 ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
3070 {
3071     static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
3072         { ZSTD_compressBlock_fast  /* default for 0 */,
3073           ZSTD_compressBlock_fast,
3074           ZSTD_COMPRESSBLOCK_DOUBLEFAST,
3075           ZSTD_COMPRESSBLOCK_GREEDY,
3076           ZSTD_COMPRESSBLOCK_LAZY,
3077           ZSTD_COMPRESSBLOCK_LAZY2,
3078           ZSTD_COMPRESSBLOCK_BTLAZY2,
3079           ZSTD_COMPRESSBLOCK_BTOPT,
3080           ZSTD_COMPRESSBLOCK_BTULTRA,
3081           ZSTD_COMPRESSBLOCK_BTULTRA2
3082         },
3083         { ZSTD_compressBlock_fast_extDict  /* default for 0 */,
3084           ZSTD_compressBlock_fast_extDict,
3085           ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT,
3086           ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT,
3087           ZSTD_COMPRESSBLOCK_LAZY_EXTDICT,
3088           ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT,
3089           ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT,
3090           ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT,
3091           ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT,
3092           ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT
3093         },
3094         { ZSTD_compressBlock_fast_dictMatchState  /* default for 0 */,
3095           ZSTD_compressBlock_fast_dictMatchState,
3096           ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE,
3097           ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE,
3098           ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE,
3099           ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE,
3100           ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE,
3101           ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE,
3102           ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE,
3103           ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE
3104         },
3105         { NULL  /* default for 0 */,
3106           NULL,
3107           NULL,
3108           ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH,
3109           ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH,
3110           ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH,
3111           NULL,
3112           NULL,
3113           NULL,
3114           NULL }
3115     };
3116     ZSTD_BlockCompressor_f selectedCompressor;
3117     ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
3118 
3119     assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
3120     DEBUGLOG(5, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder);
3121     if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) {
3122         static const ZSTD_BlockCompressor_f rowBasedBlockCompressors[4][3] = {
3123             {
3124                 ZSTD_COMPRESSBLOCK_GREEDY_ROW,
3125                 ZSTD_COMPRESSBLOCK_LAZY_ROW,
3126                 ZSTD_COMPRESSBLOCK_LAZY2_ROW
3127             },
3128             {
3129                 ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW,
3130                 ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW,
3131                 ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW
3132             },
3133             {
3134                 ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW,
3135                 ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW,
3136                 ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW
3137             },
3138             {
3139                 ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW,
3140                 ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW,
3141                 ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW
3142             }
3143         };
3144         DEBUGLOG(5, "Selecting a row-based matchfinder");
3145         assert(useRowMatchFinder != ZSTD_ps_auto);
3146         selectedCompressor = rowBasedBlockCompressors[(int)dictMode][(int)strat - (int)ZSTD_greedy];
3147     } else {
3148         selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
3149     }
3150     assert(selectedCompressor != NULL);
3151     return selectedCompressor;
3152 }
3153 
ZSTD_storeLastLiterals(SeqStore_t * seqStorePtr,const BYTE * anchor,size_t lastLLSize)3154 static void ZSTD_storeLastLiterals(SeqStore_t* seqStorePtr,
3155                                    const BYTE* anchor, size_t lastLLSize)
3156 {
3157     ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize);
3158     seqStorePtr->lit += lastLLSize;
3159 }
3160 
ZSTD_resetSeqStore(SeqStore_t * ssPtr)3161 void ZSTD_resetSeqStore(SeqStore_t* ssPtr)
3162 {
3163     ssPtr->lit = ssPtr->litStart;
3164     ssPtr->sequences = ssPtr->sequencesStart;
3165     ssPtr->longLengthType = ZSTD_llt_none;
3166 }
3167 
3168 /* ZSTD_postProcessSequenceProducerResult() :
3169  * Validates and post-processes sequences obtained through the external matchfinder API:
3170  *   - Checks whether nbExternalSeqs represents an error condition.
3171  *   - Appends a block delimiter to outSeqs if one is not already present.
3172  *     See zstd.h for context regarding block delimiters.
3173  * Returns the number of sequences after post-processing, or an error code. */
ZSTD_postProcessSequenceProducerResult(ZSTD_Sequence * outSeqs,size_t nbExternalSeqs,size_t outSeqsCapacity,size_t srcSize)3174 static size_t ZSTD_postProcessSequenceProducerResult(
3175     ZSTD_Sequence* outSeqs, size_t nbExternalSeqs, size_t outSeqsCapacity, size_t srcSize
3176 ) {
3177     RETURN_ERROR_IF(
3178         nbExternalSeqs > outSeqsCapacity,
3179         sequenceProducer_failed,
3180         "External sequence producer returned error code %lu",
3181         (unsigned long)nbExternalSeqs
3182     );
3183 
3184     RETURN_ERROR_IF(
3185         nbExternalSeqs == 0 && srcSize > 0,
3186         sequenceProducer_failed,
3187         "Got zero sequences from external sequence producer for a non-empty src buffer!"
3188     );
3189 
3190     if (srcSize == 0) {
3191         ZSTD_memset(&outSeqs[0], 0, sizeof(ZSTD_Sequence));
3192         return 1;
3193     }
3194 
3195     {
3196         ZSTD_Sequence const lastSeq = outSeqs[nbExternalSeqs - 1];
3197 
3198         /* We can return early if lastSeq is already a block delimiter. */
3199         if (lastSeq.offset == 0 && lastSeq.matchLength == 0) {
3200             return nbExternalSeqs;
3201         }
3202 
3203         /* This error condition is only possible if the external matchfinder
3204          * produced an invalid parse, by definition of ZSTD_sequenceBound(). */
3205         RETURN_ERROR_IF(
3206             nbExternalSeqs == outSeqsCapacity,
3207             sequenceProducer_failed,
3208             "nbExternalSeqs == outSeqsCapacity but lastSeq is not a block delimiter!"
3209         );
3210 
3211         /* lastSeq is not a block delimiter, so we need to append one. */
3212         ZSTD_memset(&outSeqs[nbExternalSeqs], 0, sizeof(ZSTD_Sequence));
3213         return nbExternalSeqs + 1;
3214     }
3215 }
3216 
3217 /* ZSTD_fastSequenceLengthSum() :
3218  * Returns sum(litLen) + sum(matchLen) + lastLits for *seqBuf*.
3219  * Similar to another function in zstd_compress.c (determine_blockSize),
3220  * except it doesn't check for a block delimiter to end summation.
3221  * Removing the early exit allows the compiler to auto-vectorize (https://godbolt.org/z/cY1cajz9P).
3222  * This function can be deleted and replaced by determine_blockSize after we resolve issue #3456. */
ZSTD_fastSequenceLengthSum(ZSTD_Sequence const * seqBuf,size_t seqBufSize)3223 static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seqBufSize) {
3224     size_t matchLenSum, litLenSum, i;
3225     matchLenSum = 0;
3226     litLenSum = 0;
3227     for (i = 0; i < seqBufSize; i++) {
3228         litLenSum += seqBuf[i].litLength;
3229         matchLenSum += seqBuf[i].matchLength;
3230     }
3231     return litLenSum + matchLenSum;
3232 }
3233 
3234 /**
3235  * Function to validate sequences produced by a block compressor.
3236  */
ZSTD_validateSeqStore(const SeqStore_t * seqStore,const ZSTD_compressionParameters * cParams)3237 static void ZSTD_validateSeqStore(const SeqStore_t* seqStore, const ZSTD_compressionParameters* cParams)
3238 {
3239 #if DEBUGLEVEL >= 1
3240     const SeqDef* seq = seqStore->sequencesStart;
3241     const SeqDef* const seqEnd = seqStore->sequences;
3242     size_t const matchLenLowerBound = cParams->minMatch == 3 ? 3 : 4;
3243     for (; seq < seqEnd; ++seq) {
3244         const ZSTD_SequenceLength seqLength = ZSTD_getSequenceLength(seqStore, seq);
3245         assert(seqLength.matchLength >= matchLenLowerBound);
3246         (void)seqLength;
3247         (void)matchLenLowerBound;
3248     }
3249 #else
3250     (void)seqStore;
3251     (void)cParams;
3252 #endif
3253 }
3254 
3255 static size_t
3256 ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
3257                                    ZSTD_SequencePosition* seqPos,
3258                              const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
3259                              const void* src, size_t blockSize,
3260                                    ZSTD_ParamSwitch_e externalRepSearch);
3261 
3262 typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e;
3263 
ZSTD_buildSeqStore(ZSTD_CCtx * zc,const void * src,size_t srcSize)3264 static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
3265 {
3266     ZSTD_MatchState_t* const ms = &zc->blockState.matchState;
3267     DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize);
3268     assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
3269     /* Assert that we have correctly flushed the ctx params into the ms's copy */
3270     ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
3271     /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
3272      * additional 1. We need to revisit and change this logic to be more consistent */
3273     if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
3274         if (zc->appliedParams.cParams.strategy >= ZSTD_btopt) {
3275             ZSTD_ldm_skipRawSeqStoreBytes(&zc->externSeqStore, srcSize);
3276         } else {
3277             ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
3278         }
3279         return ZSTDbss_noCompress; /* don't even attempt compression below a certain srcSize */
3280     }
3281     ZSTD_resetSeqStore(&(zc->seqStore));
3282     /* required for optimal parser to read stats from dictionary */
3283     ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy;
3284     /* tell the optimal parser how we expect to compress literals */
3285     ms->opt.literalCompressionMode = zc->appliedParams.literalCompressionMode;
3286     /* a gap between an attached dict and the current window is not safe,
3287      * they must remain adjacent,
3288      * and when that stops being the case, the dict must be unset */
3289     assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
3290 
3291     /* limited update after a very long match */
3292     {   const BYTE* const base = ms->window.base;
3293         const BYTE* const istart = (const BYTE*)src;
3294         const U32 curr = (U32)(istart-base);
3295         if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1));   /* ensure no overflow */
3296         if (curr > ms->nextToUpdate + 384)
3297             ms->nextToUpdate = curr - MIN(192, (U32)(curr - ms->nextToUpdate - 384));
3298     }
3299 
3300     /* select and store sequences */
3301     {   ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
3302         size_t lastLLSize;
3303         {   int i;
3304             for (i = 0; i < ZSTD_REP_NUM; ++i)
3305                 zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
3306         }
3307         if (zc->externSeqStore.pos < zc->externSeqStore.size) {
3308             assert(zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_disable);
3309 
3310             /* External matchfinder + LDM is technically possible, just not implemented yet.
3311              * We need to revisit soon and implement it. */
3312             RETURN_ERROR_IF(
3313                 ZSTD_hasExtSeqProd(&zc->appliedParams),
3314                 parameter_combination_unsupported,
3315                 "Long-distance matching with external sequence producer enabled is not currently supported."
3316             );
3317 
3318             /* Updates ldmSeqStore.pos */
3319             lastLLSize =
3320                 ZSTD_ldm_blockCompress(&zc->externSeqStore,
3321                                        ms, &zc->seqStore,
3322                                        zc->blockState.nextCBlock->rep,
3323                                        zc->appliedParams.useRowMatchFinder,
3324                                        src, srcSize);
3325             assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
3326         } else if (zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
3327             RawSeqStore_t ldmSeqStore = kNullRawSeqStore;
3328 
3329             /* External matchfinder + LDM is technically possible, just not implemented yet.
3330              * We need to revisit soon and implement it. */
3331             RETURN_ERROR_IF(
3332                 ZSTD_hasExtSeqProd(&zc->appliedParams),
3333                 parameter_combination_unsupported,
3334                 "Long-distance matching with external sequence producer enabled is not currently supported."
3335             );
3336 
3337             ldmSeqStore.seq = zc->ldmSequences;
3338             ldmSeqStore.capacity = zc->maxNbLdmSequences;
3339             /* Updates ldmSeqStore.size */
3340             FORWARD_IF_ERROR(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
3341                                                &zc->appliedParams.ldmParams,
3342                                                src, srcSize), "");
3343             /* Updates ldmSeqStore.pos */
3344             lastLLSize =
3345                 ZSTD_ldm_blockCompress(&ldmSeqStore,
3346                                        ms, &zc->seqStore,
3347                                        zc->blockState.nextCBlock->rep,
3348                                        zc->appliedParams.useRowMatchFinder,
3349                                        src, srcSize);
3350             assert(ldmSeqStore.pos == ldmSeqStore.size);
3351         } else if (ZSTD_hasExtSeqProd(&zc->appliedParams)) {
3352             assert(
3353                 zc->extSeqBufCapacity >= ZSTD_sequenceBound(srcSize)
3354             );
3355             assert(zc->appliedParams.extSeqProdFunc != NULL);
3356 
3357             {   U32 const windowSize = (U32)1 << zc->appliedParams.cParams.windowLog;
3358 
3359                 size_t const nbExternalSeqs = (zc->appliedParams.extSeqProdFunc)(
3360                     zc->appliedParams.extSeqProdState,
3361                     zc->extSeqBuf,
3362                     zc->extSeqBufCapacity,
3363                     src, srcSize,
3364                     NULL, 0,  /* dict and dictSize, currently not supported */
3365                     zc->appliedParams.compressionLevel,
3366                     windowSize
3367                 );
3368 
3369                 size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
3370                     zc->extSeqBuf,
3371                     nbExternalSeqs,
3372                     zc->extSeqBufCapacity,
3373                     srcSize
3374                 );
3375 
3376                 /* Return early if there is no error, since we don't need to worry about last literals */
3377                 if (!ZSTD_isError(nbPostProcessedSeqs)) {
3378                     ZSTD_SequencePosition seqPos = {0,0,0};
3379                     size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs);
3380                     RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!");
3381                     FORWARD_IF_ERROR(
3382                         ZSTD_transferSequences_wBlockDelim(
3383                             zc, &seqPos,
3384                             zc->extSeqBuf, nbPostProcessedSeqs,
3385                             src, srcSize,
3386                             zc->appliedParams.searchForExternalRepcodes
3387                         ),
3388                         "Failed to copy external sequences to seqStore!"
3389                     );
3390                     ms->ldmSeqStore = NULL;
3391                     DEBUGLOG(5, "Copied %lu sequences from external sequence producer to internal seqStore.", (unsigned long)nbExternalSeqs);
3392                     return ZSTDbss_compress;
3393                 }
3394 
3395                 /* Propagate the error if fallback is disabled */
3396                 if (!zc->appliedParams.enableMatchFinderFallback) {
3397                     return nbPostProcessedSeqs;
3398                 }
3399 
3400                 /* Fallback to software matchfinder */
3401                 {   ZSTD_BlockCompressor_f const blockCompressor =
3402                         ZSTD_selectBlockCompressor(
3403                             zc->appliedParams.cParams.strategy,
3404                             zc->appliedParams.useRowMatchFinder,
3405                             dictMode);
3406                     ms->ldmSeqStore = NULL;
3407                     DEBUGLOG(
3408                         5,
3409                         "External sequence producer returned error code %lu. Falling back to internal parser.",
3410                         (unsigned long)nbExternalSeqs
3411                     );
3412                     lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
3413             }   }
3414         } else {   /* not long range mode and no external matchfinder */
3415             ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor(
3416                     zc->appliedParams.cParams.strategy,
3417                     zc->appliedParams.useRowMatchFinder,
3418                     dictMode);
3419             ms->ldmSeqStore = NULL;
3420             lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
3421         }
3422         {   const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
3423             ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
3424     }   }
3425     ZSTD_validateSeqStore(&zc->seqStore, &zc->appliedParams.cParams);
3426     return ZSTDbss_compress;
3427 }
3428 
ZSTD_copyBlockSequences(SeqCollector * seqCollector,const SeqStore_t * seqStore,const U32 prevRepcodes[ZSTD_REP_NUM])3429 static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM])
3430 {
3431     const SeqDef* inSeqs = seqStore->sequencesStart;
3432     const size_t nbInSequences = (size_t)(seqStore->sequences - inSeqs);
3433     const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart);
3434 
3435     ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex;
3436     const size_t nbOutSequences = nbInSequences + 1;
3437     size_t nbOutLiterals = 0;
3438     Repcodes_t repcodes;
3439     size_t i;
3440 
3441     /* Bounds check that we have enough space for every input sequence
3442      * and the block delimiter
3443      */
3444     assert(seqCollector->seqIndex <= seqCollector->maxSequences);
3445     RETURN_ERROR_IF(
3446         nbOutSequences > (size_t)(seqCollector->maxSequences - seqCollector->seqIndex),
3447         dstSize_tooSmall,
3448         "Not enough space to copy sequences");
3449 
3450     ZSTD_memcpy(&repcodes, prevRepcodes, sizeof(repcodes));
3451     for (i = 0; i < nbInSequences; ++i) {
3452         U32 rawOffset;
3453         outSeqs[i].litLength = inSeqs[i].litLength;
3454         outSeqs[i].matchLength = inSeqs[i].mlBase + MINMATCH;
3455         outSeqs[i].rep = 0;
3456 
3457         /* Handle the possible single length >= 64K
3458          * There can only be one because we add MINMATCH to every match length,
3459          * and blocks are at most 128K.
3460          */
3461         if (i == seqStore->longLengthPos) {
3462             if (seqStore->longLengthType == ZSTD_llt_literalLength) {
3463                 outSeqs[i].litLength += 0x10000;
3464             } else if (seqStore->longLengthType == ZSTD_llt_matchLength) {
3465                 outSeqs[i].matchLength += 0x10000;
3466             }
3467         }
3468 
3469         /* Determine the raw offset given the offBase, which may be a repcode. */
3470         if (OFFBASE_IS_REPCODE(inSeqs[i].offBase)) {
3471             const U32 repcode = OFFBASE_TO_REPCODE(inSeqs[i].offBase);
3472             assert(repcode > 0);
3473             outSeqs[i].rep = repcode;
3474             if (outSeqs[i].litLength != 0) {
3475                 rawOffset = repcodes.rep[repcode - 1];
3476             } else {
3477                 if (repcode == 3) {
3478                     assert(repcodes.rep[0] > 1);
3479                     rawOffset = repcodes.rep[0] - 1;
3480                 } else {
3481                     rawOffset = repcodes.rep[repcode];
3482                 }
3483             }
3484         } else {
3485             rawOffset = OFFBASE_TO_OFFSET(inSeqs[i].offBase);
3486         }
3487         outSeqs[i].offset = rawOffset;
3488 
3489         /* Update repcode history for the sequence */
3490         ZSTD_updateRep(repcodes.rep,
3491                        inSeqs[i].offBase,
3492                        inSeqs[i].litLength == 0);
3493 
3494         nbOutLiterals += outSeqs[i].litLength;
3495     }
3496     /* Insert last literals (if any exist) in the block as a sequence with ml == off == 0.
3497      * If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker
3498      * for the block boundary, according to the API.
3499      */
3500     assert(nbInLiterals >= nbOutLiterals);
3501     {
3502         const size_t lastLLSize = nbInLiterals - nbOutLiterals;
3503         outSeqs[nbInSequences].litLength = (U32)lastLLSize;
3504         outSeqs[nbInSequences].matchLength = 0;
3505         outSeqs[nbInSequences].offset = 0;
3506         assert(nbOutSequences == nbInSequences + 1);
3507     }
3508     seqCollector->seqIndex += nbOutSequences;
3509     assert(seqCollector->seqIndex <= seqCollector->maxSequences);
3510 
3511     return 0;
3512 }
3513 
ZSTD_sequenceBound(size_t srcSize)3514 size_t ZSTD_sequenceBound(size_t srcSize) {
3515     const size_t maxNbSeq = (srcSize / ZSTD_MINMATCH_MIN) + 1;
3516     const size_t maxNbDelims = (srcSize / ZSTD_BLOCKSIZE_MAX_MIN) + 1;
3517     return maxNbSeq + maxNbDelims;
3518 }
3519 
ZSTD_generateSequences(ZSTD_CCtx * zc,ZSTD_Sequence * outSeqs,size_t outSeqsSize,const void * src,size_t srcSize)3520 size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
3521                               size_t outSeqsSize, const void* src, size_t srcSize)
3522 {
3523     const size_t dstCapacity = ZSTD_compressBound(srcSize);
3524     void* dst; /* Make C90 happy. */
3525     SeqCollector seqCollector;
3526     {
3527         int targetCBlockSize;
3528         FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_targetCBlockSize, &targetCBlockSize), "");
3529         RETURN_ERROR_IF(targetCBlockSize != 0, parameter_unsupported, "targetCBlockSize != 0");
3530     }
3531     {
3532         int nbWorkers;
3533         FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_nbWorkers, &nbWorkers), "");
3534         RETURN_ERROR_IF(nbWorkers != 0, parameter_unsupported, "nbWorkers != 0");
3535     }
3536 
3537     dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem);
3538     RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!");
3539 
3540     seqCollector.collectSequences = 1;
3541     seqCollector.seqStart = outSeqs;
3542     seqCollector.seqIndex = 0;
3543     seqCollector.maxSequences = outSeqsSize;
3544     zc->seqCollector = seqCollector;
3545 
3546     {
3547         const size_t ret = ZSTD_compress2(zc, dst, dstCapacity, src, srcSize);
3548         ZSTD_customFree(dst, ZSTD_defaultCMem);
3549         FORWARD_IF_ERROR(ret, "ZSTD_compress2 failed");
3550     }
3551     assert(zc->seqCollector.seqIndex <= ZSTD_sequenceBound(srcSize));
3552     return zc->seqCollector.seqIndex;
3553 }
3554 
ZSTD_mergeBlockDelimiters(ZSTD_Sequence * sequences,size_t seqsSize)3555 size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, size_t seqsSize) {
3556     size_t in = 0;
3557     size_t out = 0;
3558     for (; in < seqsSize; ++in) {
3559         if (sequences[in].offset == 0 && sequences[in].matchLength == 0) {
3560             if (in != seqsSize - 1) {
3561                 sequences[in+1].litLength += sequences[in].litLength;
3562             }
3563         } else {
3564             sequences[out] = sequences[in];
3565             ++out;
3566         }
3567     }
3568     return out;
3569 }
3570 
3571 /* 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)3572 static int ZSTD_isRLE(const BYTE* src, size_t length) {
3573     const BYTE* ip = src;
3574     const BYTE value = ip[0];
3575     const size_t valueST = (size_t)((U64)value * 0x0101010101010101ULL);
3576     const size_t unrollSize = sizeof(size_t) * 4;
3577     const size_t unrollMask = unrollSize - 1;
3578     const size_t prefixLength = length & unrollMask;
3579     size_t i;
3580     if (length == 1) return 1;
3581     /* Check if prefix is RLE first before using unrolled loop */
3582     if (prefixLength && ZSTD_count(ip+1, ip, ip+prefixLength) != prefixLength-1) {
3583         return 0;
3584     }
3585     for (i = prefixLength; i != length; i += unrollSize) {
3586         size_t u;
3587         for (u = 0; u < unrollSize; u += sizeof(size_t)) {
3588             if (MEM_readST(ip + i + u) != valueST) {
3589                 return 0;
3590     }   }   }
3591     return 1;
3592 }
3593 
3594 /* Returns true if the given block may be RLE.
3595  * This is just a heuristic based on the compressibility.
3596  * It may return both false positives and false negatives.
3597  */
ZSTD_maybeRLE(SeqStore_t const * seqStore)3598 static int ZSTD_maybeRLE(SeqStore_t const* seqStore)
3599 {
3600     size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
3601     size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart);
3602 
3603     return nbSeqs < 4 && nbLits < 10;
3604 }
3605 
3606 static void
ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t * const bs)3607 ZSTD_blockState_confirmRepcodesAndEntropyTables(ZSTD_blockState_t* const bs)
3608 {
3609     ZSTD_compressedBlockState_t* const tmp = bs->prevCBlock;
3610     bs->prevCBlock = bs->nextCBlock;
3611     bs->nextCBlock = tmp;
3612 }
3613 
3614 /* Writes the block header */
3615 static void
writeBlockHeader(void * op,size_t cSize,size_t blockSize,U32 lastBlock)3616 writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock)
3617 {
3618     U32 const cBlockHeader = cSize == 1 ?
3619                         lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
3620                         lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
3621     MEM_writeLE24(op, cBlockHeader);
3622     DEBUGLOG(5, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock);
3623 }
3624 
3625 /** ZSTD_buildBlockEntropyStats_literals() :
3626  *  Builds entropy for the literals.
3627  *  Stores literals block type (raw, rle, compressed, repeat) and
3628  *  huffman description table to hufMetadata.
3629  *  Requires ENTROPY_WORKSPACE_SIZE workspace
3630  * @return : size of huffman description table, or an error code
3631  */
3632 static size_t
ZSTD_buildBlockEntropyStats_literals(void * const src,size_t srcSize,const ZSTD_hufCTables_t * prevHuf,ZSTD_hufCTables_t * nextHuf,ZSTD_hufCTablesMetadata_t * hufMetadata,const int literalsCompressionIsDisabled,void * workspace,size_t wkspSize,int hufFlags)3633 ZSTD_buildBlockEntropyStats_literals(void* const src, size_t srcSize,
3634                                const ZSTD_hufCTables_t* prevHuf,
3635                                      ZSTD_hufCTables_t* nextHuf,
3636                                      ZSTD_hufCTablesMetadata_t* hufMetadata,
3637                                const int literalsCompressionIsDisabled,
3638                                      void* workspace, size_t wkspSize,
3639                                      int hufFlags)
3640 {
3641     BYTE* const wkspStart = (BYTE*)workspace;
3642     BYTE* const wkspEnd = wkspStart + wkspSize;
3643     BYTE* const countWkspStart = wkspStart;
3644     unsigned* const countWksp = (unsigned*)workspace;
3645     const size_t countWkspSize = (HUF_SYMBOLVALUE_MAX + 1) * sizeof(unsigned);
3646     BYTE* const nodeWksp = countWkspStart + countWkspSize;
3647     const size_t nodeWkspSize = (size_t)(wkspEnd - nodeWksp);
3648     unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
3649     unsigned huffLog = LitHufLog;
3650     HUF_repeat repeat = prevHuf->repeatMode;
3651     DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_literals (srcSize=%zu)", srcSize);
3652 
3653     /* Prepare nextEntropy assuming reusing the existing table */
3654     ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3655 
3656     if (literalsCompressionIsDisabled) {
3657         DEBUGLOG(5, "set_basic - disabled");
3658         hufMetadata->hType = set_basic;
3659         return 0;
3660     }
3661 
3662     /* small ? don't even attempt compression (speed opt) */
3663 #ifndef COMPRESS_LITERALS_SIZE_MIN
3664 # define COMPRESS_LITERALS_SIZE_MIN 63  /* heuristic */
3665 #endif
3666     {   size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
3667         if (srcSize <= minLitSize) {
3668             DEBUGLOG(5, "set_basic - too small");
3669             hufMetadata->hType = set_basic;
3670             return 0;
3671     }   }
3672 
3673     /* Scan input and build symbol stats */
3674     {   size_t const largest =
3675             HIST_count_wksp (countWksp, &maxSymbolValue,
3676                             (const BYTE*)src, srcSize,
3677                             workspace, wkspSize);
3678         FORWARD_IF_ERROR(largest, "HIST_count_wksp failed");
3679         if (largest == srcSize) {
3680             /* only one literal symbol */
3681             DEBUGLOG(5, "set_rle");
3682             hufMetadata->hType = set_rle;
3683             return 0;
3684         }
3685         if (largest <= (srcSize >> 7)+4) {
3686             /* heuristic: likely not compressible */
3687             DEBUGLOG(5, "set_basic - no gain");
3688             hufMetadata->hType = set_basic;
3689             return 0;
3690     }   }
3691 
3692     /* Validate the previous Huffman table */
3693     if (repeat == HUF_repeat_check
3694       && !HUF_validateCTable((HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue)) {
3695         repeat = HUF_repeat_none;
3696     }
3697 
3698     /* Build Huffman Tree */
3699     ZSTD_memset(nextHuf->CTable, 0, sizeof(nextHuf->CTable));
3700     huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, nodeWksp, nodeWkspSize, nextHuf->CTable, countWksp, hufFlags);
3701     assert(huffLog <= LitHufLog);
3702     {   size_t const maxBits = HUF_buildCTable_wksp((HUF_CElt*)nextHuf->CTable, countWksp,
3703                                                     maxSymbolValue, huffLog,
3704                                                     nodeWksp, nodeWkspSize);
3705         FORWARD_IF_ERROR(maxBits, "HUF_buildCTable_wksp");
3706         huffLog = (U32)maxBits;
3707     }
3708     {   /* Build and write the CTable */
3709         size_t const newCSize = HUF_estimateCompressedSize(
3710                 (HUF_CElt*)nextHuf->CTable, countWksp, maxSymbolValue);
3711         size_t const hSize = HUF_writeCTable_wksp(
3712                 hufMetadata->hufDesBuffer, sizeof(hufMetadata->hufDesBuffer),
3713                 (HUF_CElt*)nextHuf->CTable, maxSymbolValue, huffLog,
3714                 nodeWksp, nodeWkspSize);
3715         /* Check against repeating the previous CTable */
3716         if (repeat != HUF_repeat_none) {
3717             size_t const oldCSize = HUF_estimateCompressedSize(
3718                     (HUF_CElt const*)prevHuf->CTable, countWksp, maxSymbolValue);
3719             if (oldCSize < srcSize && (oldCSize <= hSize + newCSize || hSize + 12 >= srcSize)) {
3720                 DEBUGLOG(5, "set_repeat - smaller");
3721                 ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3722                 hufMetadata->hType = set_repeat;
3723                 return 0;
3724         }   }
3725         if (newCSize + hSize >= srcSize) {
3726             DEBUGLOG(5, "set_basic - no gains");
3727             ZSTD_memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
3728             hufMetadata->hType = set_basic;
3729             return 0;
3730         }
3731         DEBUGLOG(5, "set_compressed (hSize=%u)", (U32)hSize);
3732         hufMetadata->hType = set_compressed;
3733         nextHuf->repeatMode = HUF_repeat_check;
3734         return hSize;
3735     }
3736 }
3737 
3738 
3739 /* ZSTD_buildDummySequencesStatistics():
3740  * Returns a ZSTD_symbolEncodingTypeStats_t with all encoding types as set_basic,
3741  * and updates nextEntropy to the appropriate repeatMode.
3742  */
3743 static ZSTD_symbolEncodingTypeStats_t
ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t * nextEntropy)3744 ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t* nextEntropy)
3745 {
3746     ZSTD_symbolEncodingTypeStats_t stats = {set_basic, set_basic, set_basic, 0, 0, 0};
3747     nextEntropy->litlength_repeatMode = FSE_repeat_none;
3748     nextEntropy->offcode_repeatMode = FSE_repeat_none;
3749     nextEntropy->matchlength_repeatMode = FSE_repeat_none;
3750     return stats;
3751 }
3752 
3753 /** ZSTD_buildBlockEntropyStats_sequences() :
3754  *  Builds entropy for the sequences.
3755  *  Stores symbol compression modes and fse table to fseMetadata.
3756  *  Requires ENTROPY_WORKSPACE_SIZE wksp.
3757  * @return : size of fse tables or error code */
3758 static size_t
ZSTD_buildBlockEntropyStats_sequences(const 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)3759 ZSTD_buildBlockEntropyStats_sequences(
3760                 const SeqStore_t* seqStorePtr,
3761                 const ZSTD_fseCTables_t* prevEntropy,
3762                       ZSTD_fseCTables_t* nextEntropy,
3763                 const ZSTD_CCtx_params* cctxParams,
3764                       ZSTD_fseCTablesMetadata_t* fseMetadata,
3765                       void* workspace, size_t wkspSize)
3766 {
3767     ZSTD_strategy const strategy = cctxParams->cParams.strategy;
3768     size_t const nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
3769     BYTE* const ostart = fseMetadata->fseTablesBuffer;
3770     BYTE* const oend = ostart + sizeof(fseMetadata->fseTablesBuffer);
3771     BYTE* op = ostart;
3772     unsigned* countWorkspace = (unsigned*)workspace;
3773     unsigned* entropyWorkspace = countWorkspace + (MaxSeq + 1);
3774     size_t entropyWorkspaceSize = wkspSize - (MaxSeq + 1) * sizeof(*countWorkspace);
3775     ZSTD_symbolEncodingTypeStats_t stats;
3776 
3777     DEBUGLOG(5, "ZSTD_buildBlockEntropyStats_sequences (nbSeq=%zu)", nbSeq);
3778     stats = nbSeq != 0 ? ZSTD_buildSequencesStatistics(seqStorePtr, nbSeq,
3779                                           prevEntropy, nextEntropy, op, oend,
3780                                           strategy, countWorkspace,
3781                                           entropyWorkspace, entropyWorkspaceSize)
3782                        : ZSTD_buildDummySequencesStatistics(nextEntropy);
3783     FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!");
3784     fseMetadata->llType = (SymbolEncodingType_e) stats.LLtype;
3785     fseMetadata->ofType = (SymbolEncodingType_e) stats.Offtype;
3786     fseMetadata->mlType = (SymbolEncodingType_e) stats.MLtype;
3787     fseMetadata->lastCountSize = stats.lastCountSize;
3788     return stats.size;
3789 }
3790 
3791 
3792 /** ZSTD_buildBlockEntropyStats() :
3793  *  Builds entropy for the block.
3794  *  Requires workspace size ENTROPY_WORKSPACE_SIZE
3795  * @return : 0 on success, or an error code
3796  *  Note : also employed in superblock
3797  */
ZSTD_buildBlockEntropyStats(const 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)3798 size_t ZSTD_buildBlockEntropyStats(
3799             const SeqStore_t* seqStorePtr,
3800             const ZSTD_entropyCTables_t* prevEntropy,
3801                   ZSTD_entropyCTables_t* nextEntropy,
3802             const ZSTD_CCtx_params* cctxParams,
3803                   ZSTD_entropyCTablesMetadata_t* entropyMetadata,
3804                   void* workspace, size_t wkspSize)
3805 {
3806     size_t const litSize = (size_t)(seqStorePtr->lit - seqStorePtr->litStart);
3807     int const huf_useOptDepth = (cctxParams->cParams.strategy >= HUF_OPTIMAL_DEPTH_THRESHOLD);
3808     int const hufFlags = huf_useOptDepth ? HUF_flags_optimalDepth : 0;
3809 
3810     entropyMetadata->hufMetadata.hufDesSize =
3811         ZSTD_buildBlockEntropyStats_literals(seqStorePtr->litStart, litSize,
3812                                             &prevEntropy->huf, &nextEntropy->huf,
3813                                             &entropyMetadata->hufMetadata,
3814                                             ZSTD_literalsCompressionIsDisabled(cctxParams),
3815                                             workspace, wkspSize, hufFlags);
3816 
3817     FORWARD_IF_ERROR(entropyMetadata->hufMetadata.hufDesSize, "ZSTD_buildBlockEntropyStats_literals failed");
3818     entropyMetadata->fseMetadata.fseTablesSize =
3819         ZSTD_buildBlockEntropyStats_sequences(seqStorePtr,
3820                                               &prevEntropy->fse, &nextEntropy->fse,
3821                                               cctxParams,
3822                                               &entropyMetadata->fseMetadata,
3823                                               workspace, wkspSize);
3824     FORWARD_IF_ERROR(entropyMetadata->fseMetadata.fseTablesSize, "ZSTD_buildBlockEntropyStats_sequences failed");
3825     return 0;
3826 }
3827 
3828 /* Returns the size estimate for the literals section (header + content) of a block */
3829 static size_t
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)3830 ZSTD_estimateBlockSize_literal(const BYTE* literals, size_t litSize,
3831                                const ZSTD_hufCTables_t* huf,
3832                                const ZSTD_hufCTablesMetadata_t* hufMetadata,
3833                                void* workspace, size_t wkspSize,
3834                                int writeEntropy)
3835 {
3836     unsigned* const countWksp = (unsigned*)workspace;
3837     unsigned maxSymbolValue = HUF_SYMBOLVALUE_MAX;
3838     size_t literalSectionHeaderSize = 3 + (litSize >= 1 KB) + (litSize >= 16 KB);
3839     U32 singleStream = litSize < 256;
3840 
3841     if (hufMetadata->hType == set_basic) return litSize;
3842     else if (hufMetadata->hType == set_rle) return 1;
3843     else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
3844         size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
3845         if (ZSTD_isError(largest)) return litSize;
3846         {   size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
3847             if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
3848             if (!singleStream) cLitSizeEstimate += 6; /* multi-stream huffman uses 6-byte jump table */
3849             return cLitSizeEstimate + literalSectionHeaderSize;
3850     }   }
3851     assert(0); /* impossible */
3852     return 0;
3853 }
3854 
3855 /* Returns the size estimate for the FSE-compressed symbols (of, ml, ll) of a block */
3856 static size_t
ZSTD_estimateBlockSize_symbolType(SymbolEncodingType_e type,const BYTE * codeTable,size_t nbSeq,unsigned maxCode,const FSE_CTable * fseCTable,const U8 * additionalBits,short const * defaultNorm,U32 defaultNormLog,U32 defaultMax,void * workspace,size_t wkspSize)3857 ZSTD_estimateBlockSize_symbolType(SymbolEncodingType_e type,
3858                     const BYTE* codeTable, size_t nbSeq, unsigned maxCode,
3859                     const FSE_CTable* fseCTable,
3860                     const U8* additionalBits,
3861                     short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
3862                     void* workspace, size_t wkspSize)
3863 {
3864     unsigned* const countWksp = (unsigned*)workspace;
3865     const BYTE* ctp = codeTable;
3866     const BYTE* const ctStart = ctp;
3867     const BYTE* const ctEnd = ctStart + nbSeq;
3868     size_t cSymbolTypeSizeEstimateInBits = 0;
3869     unsigned max = maxCode;
3870 
3871     HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize);  /* can't fail */
3872     if (type == set_basic) {
3873         /* We selected this encoding type, so it must be valid. */
3874         assert(max <= defaultMax);
3875         (void)defaultMax;
3876         cSymbolTypeSizeEstimateInBits = ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max);
3877     } else if (type == set_rle) {
3878         cSymbolTypeSizeEstimateInBits = 0;
3879     } else if (type == set_compressed || type == set_repeat) {
3880         cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
3881     }
3882     if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) {
3883         return nbSeq * 10;
3884     }
3885     while (ctp < ctEnd) {
3886         if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
3887         else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
3888         ctp++;
3889     }
3890     return cSymbolTypeSizeEstimateInBits >> 3;
3891 }
3892 
3893 /* Returns the size estimate for the sequences section (header + content) of a block */
3894 static size_t
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)3895 ZSTD_estimateBlockSize_sequences(const BYTE* ofCodeTable,
3896                                  const BYTE* llCodeTable,
3897                                  const BYTE* mlCodeTable,
3898                                  size_t nbSeq,
3899                                  const ZSTD_fseCTables_t* fseTables,
3900                                  const ZSTD_fseCTablesMetadata_t* fseMetadata,
3901                                  void* workspace, size_t wkspSize,
3902                                  int writeEntropy)
3903 {
3904     size_t sequencesSectionHeaderSize = 1 /* seqHead */ + 1 /* min seqSize size */ + (nbSeq >= 128) + (nbSeq >= LONGNBSEQ);
3905     size_t cSeqSizeEstimate = 0;
3906     cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, nbSeq, MaxOff,
3907                                     fseTables->offcodeCTable, NULL,
3908                                     OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
3909                                     workspace, wkspSize);
3910     cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->llType, llCodeTable, nbSeq, MaxLL,
3911                                     fseTables->litlengthCTable, LL_bits,
3912                                     LL_defaultNorm, LL_defaultNormLog, MaxLL,
3913                                     workspace, wkspSize);
3914     cSeqSizeEstimate += ZSTD_estimateBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, nbSeq, MaxML,
3915                                     fseTables->matchlengthCTable, ML_bits,
3916                                     ML_defaultNorm, ML_defaultNormLog, MaxML,
3917                                     workspace, wkspSize);
3918     if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
3919     return cSeqSizeEstimate + sequencesSectionHeaderSize;
3920 }
3921 
3922 /* Returns the size estimate for a given stream of literals, of, ll, ml */
3923 static size_t
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)3924 ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize,
3925                        const BYTE* ofCodeTable,
3926                        const BYTE* llCodeTable,
3927                        const BYTE* mlCodeTable,
3928                        size_t nbSeq,
3929                        const ZSTD_entropyCTables_t* entropy,
3930                        const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
3931                        void* workspace, size_t wkspSize,
3932                        int writeLitEntropy, int writeSeqEntropy)
3933 {
3934     size_t const literalsSize = ZSTD_estimateBlockSize_literal(literals, litSize,
3935                                     &entropy->huf, &entropyMetadata->hufMetadata,
3936                                     workspace, wkspSize, writeLitEntropy);
3937     size_t const seqSize = ZSTD_estimateBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
3938                                     nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
3939                                     workspace, wkspSize, writeSeqEntropy);
3940     return seqSize + literalsSize + ZSTD_blockHeaderSize;
3941 }
3942 
3943 /* Builds entropy statistics and uses them for blocksize estimation.
3944  *
3945  * @return: estimated compressed size of the seqStore, or a zstd error.
3946  */
3947 static size_t
ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(SeqStore_t * seqStore,ZSTD_CCtx * zc)3948 ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(SeqStore_t* seqStore, ZSTD_CCtx* zc)
3949 {
3950     ZSTD_entropyCTablesMetadata_t* const entropyMetadata = &zc->blockSplitCtx.entropyMetadata;
3951     DEBUGLOG(6, "ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()");
3952     FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(seqStore,
3953                     &zc->blockState.prevCBlock->entropy,
3954                     &zc->blockState.nextCBlock->entropy,
3955                     &zc->appliedParams,
3956                     entropyMetadata,
3957                     zc->tmpWorkspace, zc->tmpWkspSize), "");
3958     return ZSTD_estimateBlockSize(
3959                     seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart),
3960                     seqStore->ofCode, seqStore->llCode, seqStore->mlCode,
3961                     (size_t)(seqStore->sequences - seqStore->sequencesStart),
3962                     &zc->blockState.nextCBlock->entropy,
3963                     entropyMetadata,
3964                     zc->tmpWorkspace, zc->tmpWkspSize,
3965                     (int)(entropyMetadata->hufMetadata.hType == set_compressed), 1);
3966 }
3967 
3968 /* Returns literals bytes represented in a seqStore */
ZSTD_countSeqStoreLiteralsBytes(const SeqStore_t * const seqStore)3969 static size_t ZSTD_countSeqStoreLiteralsBytes(const SeqStore_t* const seqStore)
3970 {
3971     size_t literalsBytes = 0;
3972     size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
3973     size_t i;
3974     for (i = 0; i < nbSeqs; ++i) {
3975         SeqDef const seq = seqStore->sequencesStart[i];
3976         literalsBytes += seq.litLength;
3977         if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_literalLength) {
3978             literalsBytes += 0x10000;
3979     }   }
3980     return literalsBytes;
3981 }
3982 
3983 /* Returns match bytes represented in a seqStore */
ZSTD_countSeqStoreMatchBytes(const SeqStore_t * const seqStore)3984 static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore)
3985 {
3986     size_t matchBytes = 0;
3987     size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart);
3988     size_t i;
3989     for (i = 0; i < nbSeqs; ++i) {
3990         SeqDef seq = seqStore->sequencesStart[i];
3991         matchBytes += seq.mlBase + MINMATCH;
3992         if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_matchLength) {
3993             matchBytes += 0x10000;
3994     }   }
3995     return matchBytes;
3996 }
3997 
3998 /* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx).
3999  * Stores the result in resultSeqStore.
4000  */
ZSTD_deriveSeqStoreChunk(SeqStore_t * resultSeqStore,const SeqStore_t * originalSeqStore,size_t startIdx,size_t endIdx)4001 static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore,
4002                                const SeqStore_t* originalSeqStore,
4003                                      size_t startIdx, size_t endIdx)
4004 {
4005     *resultSeqStore = *originalSeqStore;
4006     if (startIdx > 0) {
4007         resultSeqStore->sequences = originalSeqStore->sequencesStart + startIdx;
4008         resultSeqStore->litStart += ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
4009     }
4010 
4011     /* Move longLengthPos into the correct position if necessary */
4012     if (originalSeqStore->longLengthType != ZSTD_llt_none) {
4013         if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) {
4014             resultSeqStore->longLengthType = ZSTD_llt_none;
4015         } else {
4016             resultSeqStore->longLengthPos -= (U32)startIdx;
4017         }
4018     }
4019     resultSeqStore->sequencesStart = originalSeqStore->sequencesStart + startIdx;
4020     resultSeqStore->sequences = originalSeqStore->sequencesStart + endIdx;
4021     if (endIdx == (size_t)(originalSeqStore->sequences - originalSeqStore->sequencesStart)) {
4022         /* This accounts for possible last literals if the derived chunk reaches the end of the block */
4023         assert(resultSeqStore->lit == originalSeqStore->lit);
4024     } else {
4025         size_t const literalsBytes = ZSTD_countSeqStoreLiteralsBytes(resultSeqStore);
4026         resultSeqStore->lit = resultSeqStore->litStart + literalsBytes;
4027     }
4028     resultSeqStore->llCode += startIdx;
4029     resultSeqStore->mlCode += startIdx;
4030     resultSeqStore->ofCode += startIdx;
4031 }
4032 
4033 /**
4034  * Returns the raw offset represented by the combination of offBase, ll0, and repcode history.
4035  * offBase must represent a repcode in the numeric representation of ZSTD_storeSeq().
4036  */
4037 static U32
ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM],const U32 offBase,const U32 ll0)4038 ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offBase, const U32 ll0)
4039 {
4040     U32 const adjustedRepCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;  /* [ 0 - 3 ] */
4041     assert(OFFBASE_IS_REPCODE(offBase));
4042     if (adjustedRepCode == ZSTD_REP_NUM) {
4043         assert(ll0);
4044         /* litlength == 0 and offCode == 2 implies selection of first repcode - 1
4045          * This is only valid if it results in a valid offset value, aka > 0.
4046          * Note : it may happen that `rep[0]==1` in exceptional circumstances.
4047          * In which case this function will return 0, which is an invalid offset.
4048          * It's not an issue though, since this value will be
4049          * compared and discarded within ZSTD_seqStore_resolveOffCodes().
4050          */
4051         return rep[0] - 1;
4052     }
4053     return rep[adjustedRepCode];
4054 }
4055 
4056 /**
4057  * ZSTD_seqStore_resolveOffCodes() reconciles any possible divergences in offset history that may arise
4058  * due to emission of RLE/raw blocks that disturb the offset history,
4059  * and replaces any repcodes within the seqStore that may be invalid.
4060  *
4061  * dRepcodes are updated as would be on the decompression side.
4062  * cRepcodes are updated exactly in accordance with the seqStore.
4063  *
4064  * Note : this function assumes seq->offBase respects the following numbering scheme :
4065  *        0 : invalid
4066  *        1-3 : repcode 1-3
4067  *        4+ : real_offset+3
4068  */
4069 static void
ZSTD_seqStore_resolveOffCodes(Repcodes_t * const dRepcodes,Repcodes_t * const cRepcodes,const SeqStore_t * const seqStore,U32 const nbSeq)4070 ZSTD_seqStore_resolveOffCodes(Repcodes_t* const dRepcodes, Repcodes_t* const cRepcodes,
4071                         const SeqStore_t* const seqStore, U32 const nbSeq)
4072 {
4073     U32 idx = 0;
4074     U32 const longLitLenIdx = seqStore->longLengthType == ZSTD_llt_literalLength ? seqStore->longLengthPos : nbSeq;
4075     for (; idx < nbSeq; ++idx) {
4076         SeqDef* const seq = seqStore->sequencesStart + idx;
4077         U32 const ll0 = (seq->litLength == 0) && (idx != longLitLenIdx);
4078         U32 const offBase = seq->offBase;
4079         assert(offBase > 0);
4080         if (OFFBASE_IS_REPCODE(offBase)) {
4081             U32 const dRawOffset = ZSTD_resolveRepcodeToRawOffset(dRepcodes->rep, offBase, ll0);
4082             U32 const cRawOffset = ZSTD_resolveRepcodeToRawOffset(cRepcodes->rep, offBase, ll0);
4083             /* Adjust simulated decompression repcode history if we come across a mismatch. Replace
4084              * the repcode with the offset it actually references, determined by the compression
4085              * repcode history.
4086              */
4087             if (dRawOffset != cRawOffset) {
4088                 seq->offBase = OFFSET_TO_OFFBASE(cRawOffset);
4089             }
4090         }
4091         /* Compression repcode history is always updated with values directly from the unmodified seqStore.
4092          * Decompression repcode history may use modified seq->offset value taken from compression repcode history.
4093          */
4094         ZSTD_updateRep(dRepcodes->rep, seq->offBase, ll0);
4095         ZSTD_updateRep(cRepcodes->rep, offBase, ll0);
4096     }
4097 }
4098 
4099 /* ZSTD_compressSeqStore_singleBlock():
4100  * Compresses a seqStore into a block with a block header, into the buffer dst.
4101  *
4102  * Returns the total size of that block (including header) or a ZSTD error code.
4103  */
4104 static size_t
ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx * zc,const 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)4105 ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc,
4106                             const SeqStore_t* const seqStore,
4107                                   Repcodes_t* const dRep, Repcodes_t* const cRep,
4108                                   void* dst, size_t dstCapacity,
4109                             const void* src, size_t srcSize,
4110                                   U32 lastBlock, U32 isPartition)
4111 {
4112     const U32 rleMaxLength = 25;
4113     BYTE* op = (BYTE*)dst;
4114     const BYTE* ip = (const BYTE*)src;
4115     size_t cSize;
4116     size_t cSeqsSize;
4117 
4118     /* In case of an RLE or raw block, the simulated decompression repcode history must be reset */
4119     Repcodes_t const dRepOriginal = *dRep;
4120     DEBUGLOG(5, "ZSTD_compressSeqStore_singleBlock");
4121     if (isPartition)
4122         ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart));
4123 
4124     RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "Block header doesn't fit");
4125     cSeqsSize = ZSTD_entropyCompressSeqStore(seqStore,
4126                 &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
4127                 &zc->appliedParams,
4128                 op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize,
4129                 srcSize,
4130                 zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
4131                 zc->bmi2);
4132     FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!");
4133 
4134     if (!zc->isFirstBlock &&
4135         cSeqsSize < rleMaxLength &&
4136         ZSTD_isRLE((BYTE const*)src, srcSize)) {
4137         /* We don't want to emit our first block as a RLE even if it qualifies because
4138         * doing so will cause the decoder (cli only) to throw a "should consume all input error."
4139         * This is only an issue for zstd <= v1.4.3
4140         */
4141         cSeqsSize = 1;
4142     }
4143 
4144     /* Sequence collection not supported when block splitting */
4145     if (zc->seqCollector.collectSequences) {
4146         FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, seqStore, dRepOriginal.rep), "copyBlockSequences failed");
4147         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4148         return 0;
4149     }
4150 
4151     if (cSeqsSize == 0) {
4152         cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock);
4153         FORWARD_IF_ERROR(cSize, "Nocompress block failed");
4154         DEBUGLOG(5, "Writing out nocompress block, size: %zu", cSize);
4155         *dRep = dRepOriginal; /* reset simulated decompression repcode history */
4156     } else if (cSeqsSize == 1) {
4157         cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock);
4158         FORWARD_IF_ERROR(cSize, "RLE compress block failed");
4159         DEBUGLOG(5, "Writing out RLE block, size: %zu", cSize);
4160         *dRep = dRepOriginal; /* reset simulated decompression repcode history */
4161     } else {
4162         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4163         writeBlockHeader(op, cSeqsSize, srcSize, lastBlock);
4164         cSize = ZSTD_blockHeaderSize + cSeqsSize;
4165         DEBUGLOG(5, "Writing out compressed block, size: %zu", cSize);
4166     }
4167 
4168     if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4169         zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4170 
4171     return cSize;
4172 }
4173 
4174 /* Struct to keep track of where we are in our recursive calls. */
4175 typedef struct {
4176     U32* splitLocations;    /* Array of split indices */
4177     size_t idx;             /* The current index within splitLocations being worked on */
4178 } seqStoreSplits;
4179 
4180 #define MIN_SEQUENCES_BLOCK_SPLITTING 300
4181 
4182 /* Helper function to perform the recursive search for block splits.
4183  * Estimates the cost of seqStore prior to split, and estimates the cost of splitting the sequences in half.
4184  * If advantageous to split, then we recurse down the two sub-blocks.
4185  * If not, or if an error occurred in estimation, then we do not recurse.
4186  *
4187  * Note: The recursion depth is capped by a heuristic minimum number of sequences,
4188  * defined by MIN_SEQUENCES_BLOCK_SPLITTING.
4189  * In theory, this means the absolute largest recursion depth is 10 == log2(maxNbSeqInBlock/MIN_SEQUENCES_BLOCK_SPLITTING).
4190  * In practice, recursion depth usually doesn't go beyond 4.
4191  *
4192  * Furthermore, the number of splits is capped by ZSTD_MAX_NB_BLOCK_SPLITS.
4193  * At ZSTD_MAX_NB_BLOCK_SPLITS == 196 with the current existing blockSize
4194  * maximum of 128 KB, this value is actually impossible to reach.
4195  */
4196 static void
ZSTD_deriveBlockSplitsHelper(seqStoreSplits * splits,size_t startIdx,size_t endIdx,ZSTD_CCtx * zc,const SeqStore_t * origSeqStore)4197 ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx,
4198                              ZSTD_CCtx* zc, const SeqStore_t* origSeqStore)
4199 {
4200     SeqStore_t* const fullSeqStoreChunk = &zc->blockSplitCtx.fullSeqStoreChunk;
4201     SeqStore_t* const firstHalfSeqStore = &zc->blockSplitCtx.firstHalfSeqStore;
4202     SeqStore_t* const secondHalfSeqStore = &zc->blockSplitCtx.secondHalfSeqStore;
4203     size_t estimatedOriginalSize;
4204     size_t estimatedFirstHalfSize;
4205     size_t estimatedSecondHalfSize;
4206     size_t midIdx = (startIdx + endIdx)/2;
4207 
4208     DEBUGLOG(5, "ZSTD_deriveBlockSplitsHelper: startIdx=%zu endIdx=%zu", startIdx, endIdx);
4209     assert(endIdx >= startIdx);
4210     if (endIdx - startIdx < MIN_SEQUENCES_BLOCK_SPLITTING || splits->idx >= ZSTD_MAX_NB_BLOCK_SPLITS) {
4211         DEBUGLOG(6, "ZSTD_deriveBlockSplitsHelper: Too few sequences (%zu)", endIdx - startIdx);
4212         return;
4213     }
4214     ZSTD_deriveSeqStoreChunk(fullSeqStoreChunk, origSeqStore, startIdx, endIdx);
4215     ZSTD_deriveSeqStoreChunk(firstHalfSeqStore, origSeqStore, startIdx, midIdx);
4216     ZSTD_deriveSeqStoreChunk(secondHalfSeqStore, origSeqStore, midIdx, endIdx);
4217     estimatedOriginalSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(fullSeqStoreChunk, zc);
4218     estimatedFirstHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(firstHalfSeqStore, zc);
4219     estimatedSecondHalfSize = ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(secondHalfSeqStore, zc);
4220     DEBUGLOG(5, "Estimated original block size: %zu -- First half split: %zu -- Second half split: %zu",
4221              estimatedOriginalSize, estimatedFirstHalfSize, estimatedSecondHalfSize);
4222     if (ZSTD_isError(estimatedOriginalSize) || ZSTD_isError(estimatedFirstHalfSize) || ZSTD_isError(estimatedSecondHalfSize)) {
4223         return;
4224     }
4225     if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) {
4226         DEBUGLOG(5, "split decided at seqNb:%zu", midIdx);
4227         ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore);
4228         splits->splitLocations[splits->idx] = (U32)midIdx;
4229         splits->idx++;
4230         ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore);
4231     }
4232 }
4233 
4234 /* Base recursive function.
4235  * Populates a table with intra-block partition indices that can improve compression ratio.
4236  *
4237  * @return: number of splits made (which equals the size of the partition table - 1).
4238  */
ZSTD_deriveBlockSplits(ZSTD_CCtx * zc,U32 partitions[],U32 nbSeq)4239 static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq)
4240 {
4241     seqStoreSplits splits;
4242     splits.splitLocations = partitions;
4243     splits.idx = 0;
4244     if (nbSeq <= 4) {
4245         DEBUGLOG(5, "ZSTD_deriveBlockSplits: Too few sequences to split (%u <= 4)", nbSeq);
4246         /* Refuse to try and split anything with less than 4 sequences */
4247         return 0;
4248     }
4249     ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore);
4250     splits.splitLocations[splits.idx] = nbSeq;
4251     DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1);
4252     return splits.idx;
4253 }
4254 
4255 /* ZSTD_compressBlock_splitBlock():
4256  * Attempts to split a given block into multiple blocks to improve compression ratio.
4257  *
4258  * Returns combined size of all blocks (which includes headers), or a ZSTD error code.
4259  */
4260 static size_t
ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t blockSize,U32 lastBlock,U32 nbSeq)4261 ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc,
4262                                     void* dst, size_t dstCapacity,
4263                               const void* src, size_t blockSize,
4264                                     U32 lastBlock, U32 nbSeq)
4265 {
4266     size_t cSize = 0;
4267     const BYTE* ip = (const BYTE*)src;
4268     BYTE* op = (BYTE*)dst;
4269     size_t i = 0;
4270     size_t srcBytesTotal = 0;
4271     U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */
4272     SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore;
4273     SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore;
4274     size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq);
4275 
4276     /* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history
4277      * may become invalid. In order to reconcile potentially invalid repcodes, we keep track of two
4278      * separate repcode histories that simulate repcode history on compression and decompression side,
4279      * and use the histories to determine whether we must replace a particular repcode with its raw offset.
4280      *
4281      * 1) cRep gets updated for each partition, regardless of whether the block was emitted as uncompressed
4282      *    or RLE. This allows us to retrieve the offset value that an invalid repcode references within
4283      *    a nocompress/RLE block.
4284      * 2) dRep gets updated only for compressed partitions, and when a repcode gets replaced, will use
4285      *    the replacement offset value rather than the original repcode to update the repcode history.
4286      *    dRep also will be the final repcode history sent to the next block.
4287      *
4288      * See ZSTD_seqStore_resolveOffCodes() for more details.
4289      */
4290     Repcodes_t dRep;
4291     Repcodes_t cRep;
4292     ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));
4293     ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t));
4294     ZSTD_memset(nextSeqStore, 0, sizeof(SeqStore_t));
4295 
4296     DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
4297                 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
4298                 (unsigned)zc->blockState.matchState.nextToUpdate);
4299 
4300     if (numSplits == 0) {
4301         size_t cSizeSingleBlock =
4302             ZSTD_compressSeqStore_singleBlock(zc, &zc->seqStore,
4303                                             &dRep, &cRep,
4304                                             op, dstCapacity,
4305                                             ip, blockSize,
4306                                             lastBlock, 0 /* isPartition */);
4307         FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!");
4308         DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits");
4309         assert(zc->blockSizeMax <= ZSTD_BLOCKSIZE_MAX);
4310         assert(cSizeSingleBlock <= zc->blockSizeMax + ZSTD_blockHeaderSize);
4311         return cSizeSingleBlock;
4312     }
4313 
4314     ZSTD_deriveSeqStoreChunk(currSeqStore, &zc->seqStore, 0, partitions[0]);
4315     for (i = 0; i <= numSplits; ++i) {
4316         size_t cSizeChunk;
4317         U32 const lastPartition = (i == numSplits);
4318         U32 lastBlockEntireSrc = 0;
4319 
4320         size_t srcBytes = ZSTD_countSeqStoreLiteralsBytes(currSeqStore) + ZSTD_countSeqStoreMatchBytes(currSeqStore);
4321         srcBytesTotal += srcBytes;
4322         if (lastPartition) {
4323             /* This is the final partition, need to account for possible last literals */
4324             srcBytes += blockSize - srcBytesTotal;
4325             lastBlockEntireSrc = lastBlock;
4326         } else {
4327             ZSTD_deriveSeqStoreChunk(nextSeqStore, &zc->seqStore, partitions[i], partitions[i+1]);
4328         }
4329 
4330         cSizeChunk = ZSTD_compressSeqStore_singleBlock(zc, currSeqStore,
4331                                                       &dRep, &cRep,
4332                                                        op, dstCapacity,
4333                                                        ip, srcBytes,
4334                                                        lastBlockEntireSrc, 1 /* isPartition */);
4335         DEBUGLOG(5, "Estimated size: %zu vs %zu : actual size",
4336                     ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(currSeqStore, zc), cSizeChunk);
4337         FORWARD_IF_ERROR(cSizeChunk, "Compressing chunk failed!");
4338 
4339         ip += srcBytes;
4340         op += cSizeChunk;
4341         dstCapacity -= cSizeChunk;
4342         cSize += cSizeChunk;
4343         *currSeqStore = *nextSeqStore;
4344         assert(cSizeChunk <= zc->blockSizeMax + ZSTD_blockHeaderSize);
4345     }
4346     /* cRep and dRep may have diverged during the compression.
4347      * If so, we use the dRep repcodes for the next block.
4348      */
4349     ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(Repcodes_t));
4350     return cSize;
4351 }
4352 
4353 static size_t
ZSTD_compressBlock_splitBlock(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastBlock)4354 ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc,
4355                               void* dst, size_t dstCapacity,
4356                               const void* src, size_t srcSize, U32 lastBlock)
4357 {
4358     U32 nbSeq;
4359     size_t cSize;
4360     DEBUGLOG(5, "ZSTD_compressBlock_splitBlock");
4361     assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable);
4362 
4363     {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
4364         FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
4365         if (bss == ZSTDbss_noCompress) {
4366             if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4367                 zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4368             RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
4369             cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
4370             FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
4371             DEBUGLOG(5, "ZSTD_compressBlock_splitBlock: Nocompress block");
4372             return cSize;
4373         }
4374         nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart);
4375     }
4376 
4377     cSize = ZSTD_compressBlock_splitBlock_internal(zc, dst, dstCapacity, src, srcSize, lastBlock, nbSeq);
4378     FORWARD_IF_ERROR(cSize, "Splitting blocks failed!");
4379     return cSize;
4380 }
4381 
4382 static size_t
ZSTD_compressBlock_internal(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 frame)4383 ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
4384                             void* dst, size_t dstCapacity,
4385                             const void* src, size_t srcSize, U32 frame)
4386 {
4387     /* This is an estimated upper bound for the length of an rle block.
4388      * This isn't the actual upper bound.
4389      * Finding the real threshold needs further investigation.
4390      */
4391     const U32 rleMaxLength = 25;
4392     size_t cSize;
4393     const BYTE* ip = (const BYTE*)src;
4394     BYTE* op = (BYTE*)dst;
4395     DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
4396                 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit,
4397                 (unsigned)zc->blockState.matchState.nextToUpdate);
4398 
4399     {   const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
4400         FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
4401         if (bss == ZSTDbss_noCompress) {
4402             RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block");
4403             cSize = 0;
4404             goto out;
4405         }
4406     }
4407 
4408     if (zc->seqCollector.collectSequences) {
4409         FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, ZSTD_getSeqStore(zc), zc->blockState.prevCBlock->rep), "copyBlockSequences failed");
4410         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4411         return 0;
4412     }
4413 
4414     /* encode sequences and literals */
4415     cSize = ZSTD_entropyCompressSeqStore(&zc->seqStore,
4416             &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
4417             &zc->appliedParams,
4418             dst, dstCapacity,
4419             srcSize,
4420             zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */,
4421             zc->bmi2);
4422 
4423     if (frame &&
4424         /* We don't want to emit our first block as a RLE even if it qualifies because
4425          * doing so will cause the decoder (cli only) to throw a "should consume all input error."
4426          * This is only an issue for zstd <= v1.4.3
4427          */
4428         !zc->isFirstBlock &&
4429         cSize < rleMaxLength &&
4430         ZSTD_isRLE(ip, srcSize))
4431     {
4432         cSize = 1;
4433         op[0] = ip[0];
4434     }
4435 
4436 out:
4437     if (!ZSTD_isError(cSize) && cSize > 1) {
4438         ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4439     }
4440     /* We check that dictionaries have offset codes available for the first
4441      * block. After the first block, the offcode table might not have large
4442      * enough codes to represent the offsets in the data.
4443      */
4444     if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4445         zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4446 
4447     return cSize;
4448 }
4449 
ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const size_t bss,U32 lastBlock)4450 static size_t ZSTD_compressBlock_targetCBlockSize_body(ZSTD_CCtx* zc,
4451                                void* dst, size_t dstCapacity,
4452                                const void* src, size_t srcSize,
4453                                const size_t bss, U32 lastBlock)
4454 {
4455     DEBUGLOG(6, "Attempting ZSTD_compressSuperBlock()");
4456     if (bss == ZSTDbss_compress) {
4457         if (/* We don't want to emit our first block as a RLE even if it qualifies because
4458             * doing so will cause the decoder (cli only) to throw a "should consume all input error."
4459             * This is only an issue for zstd <= v1.4.3
4460             */
4461             !zc->isFirstBlock &&
4462             ZSTD_maybeRLE(&zc->seqStore) &&
4463             ZSTD_isRLE((BYTE const*)src, srcSize))
4464         {
4465             return ZSTD_rleCompressBlock(dst, dstCapacity, *(BYTE const*)src, srcSize, lastBlock);
4466         }
4467         /* Attempt superblock compression.
4468          *
4469          * Note that compressed size of ZSTD_compressSuperBlock() is not bound by the
4470          * standard ZSTD_compressBound(). This is a problem, because even if we have
4471          * space now, taking an extra byte now could cause us to run out of space later
4472          * and violate ZSTD_compressBound().
4473          *
4474          * Define blockBound(blockSize) = blockSize + ZSTD_blockHeaderSize.
4475          *
4476          * In order to respect ZSTD_compressBound() we must attempt to emit a raw
4477          * uncompressed block in these cases:
4478          *   * cSize == 0: Return code for an uncompressed block.
4479          *   * cSize == dstSize_tooSmall: We may have expanded beyond blockBound(srcSize).
4480          *     ZSTD_noCompressBlock() will return dstSize_tooSmall if we are really out of
4481          *     output space.
4482          *   * cSize >= blockBound(srcSize): We have expanded the block too much so
4483          *     emit an uncompressed block.
4484          */
4485         {   size_t const cSize =
4486                 ZSTD_compressSuperBlock(zc, dst, dstCapacity, src, srcSize, lastBlock);
4487             if (cSize != ERROR(dstSize_tooSmall)) {
4488                 size_t const maxCSize =
4489                     srcSize - ZSTD_minGain(srcSize, zc->appliedParams.cParams.strategy);
4490                 FORWARD_IF_ERROR(cSize, "ZSTD_compressSuperBlock failed");
4491                 if (cSize != 0 && cSize < maxCSize + ZSTD_blockHeaderSize) {
4492                     ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState);
4493                     return cSize;
4494                 }
4495             }
4496         }
4497     } /* if (bss == ZSTDbss_compress)*/
4498 
4499     DEBUGLOG(6, "Resorting to ZSTD_noCompressBlock()");
4500     /* Superblock compression failed, attempt to emit a single no compress block.
4501      * The decoder will be able to stream this block since it is uncompressed.
4502      */
4503     return ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock);
4504 }
4505 
ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastBlock)4506 static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc,
4507                                void* dst, size_t dstCapacity,
4508                                const void* src, size_t srcSize,
4509                                U32 lastBlock)
4510 {
4511     size_t cSize = 0;
4512     const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize);
4513     DEBUGLOG(5, "ZSTD_compressBlock_targetCBlockSize (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u, srcSize=%zu)",
4514                 (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, (unsigned)zc->blockState.matchState.nextToUpdate, srcSize);
4515     FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed");
4516 
4517     cSize = ZSTD_compressBlock_targetCBlockSize_body(zc, dst, dstCapacity, src, srcSize, bss, lastBlock);
4518     FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize_body failed");
4519 
4520     if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
4521         zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
4522 
4523     return cSize;
4524 }
4525 
ZSTD_overflowCorrectIfNeeded(ZSTD_MatchState_t * ms,ZSTD_cwksp * ws,ZSTD_CCtx_params const * params,void const * ip,void const * iend)4526 static void ZSTD_overflowCorrectIfNeeded(ZSTD_MatchState_t* ms,
4527                                          ZSTD_cwksp* ws,
4528                                          ZSTD_CCtx_params const* params,
4529                                          void const* ip,
4530                                          void const* iend)
4531 {
4532     U32 const cycleLog = ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy);
4533     U32 const maxDist = (U32)1 << params->cParams.windowLog;
4534     if (ZSTD_window_needOverflowCorrection(ms->window, cycleLog, maxDist, ms->loadedDictEnd, ip, iend)) {
4535         U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
4536         ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
4537         ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
4538         ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
4539         ZSTD_cwksp_mark_tables_dirty(ws);
4540         ZSTD_reduceIndex(ms, params, correction);
4541         ZSTD_cwksp_mark_tables_clean(ws);
4542         if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
4543         else ms->nextToUpdate -= correction;
4544         /* invalidate dictionaries on overflow correction */
4545         ms->loadedDictEnd = 0;
4546         ms->dictMatchState = NULL;
4547     }
4548 }
4549 
4550 #include "zstd_preSplit.h"
4551 
ZSTD_optimalBlockSize(ZSTD_CCtx * cctx,const void * src,size_t srcSize,size_t blockSizeMax,int splitLevel,ZSTD_strategy strat,S64 savings)4552 static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, int splitLevel, ZSTD_strategy strat, S64 savings)
4553 {
4554     /* split level based on compression strategy, from `fast` to `btultra2` */
4555     static const int splitLevels[] = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4 };
4556     /* note: conservatively only split full blocks (128 KB) currently.
4557      * While it's possible to go lower, let's keep it simple for a first implementation.
4558      * Besides, benefits of splitting are reduced when blocks are already small.
4559      */
4560     if (srcSize < 128 KB || blockSizeMax < 128 KB)
4561         return MIN(srcSize, blockSizeMax);
4562     /* do not split incompressible data though:
4563      * require verified savings to allow pre-splitting.
4564      * Note: as a consequence, the first full block is not split.
4565      */
4566     if (savings < 3) {
4567         DEBUGLOG(6, "don't attempt splitting: savings (%i) too low", (int)savings);
4568         return 128 KB;
4569     }
4570     /* apply @splitLevel, or use default value (which depends on @strat).
4571      * note that splitting heuristic is still conditioned by @savings >= 3,
4572      * so the first block will not reach this code path */
4573     if (splitLevel == 1) return 128 KB;
4574     if (splitLevel == 0) {
4575         assert(ZSTD_fast <= strat && strat <= ZSTD_btultra2);
4576         splitLevel = splitLevels[strat];
4577     } else {
4578         assert(2 <= splitLevel && splitLevel <= 6);
4579         splitLevel -= 2;
4580     }
4581     return ZSTD_splitBlock(src, blockSizeMax, splitLevel, cctx->tmpWorkspace, cctx->tmpWkspSize);
4582 }
4583 
4584 /*! ZSTD_compress_frameChunk() :
4585 *   Compress a chunk of data into one or multiple blocks.
4586 *   All blocks will be terminated, all input will be consumed.
4587 *   Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
4588 *   Frame is supposed already started (header already produced)
4589 *  @return : compressed size, or an error code
4590 */
ZSTD_compress_frameChunk(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 lastFrameChunk)4591 static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx,
4592                                      void* dst, size_t dstCapacity,
4593                                const void* src, size_t srcSize,
4594                                      U32 lastFrameChunk)
4595 {
4596     size_t blockSizeMax = cctx->blockSizeMax;
4597     size_t remaining = srcSize;
4598     const BYTE* ip = (const BYTE*)src;
4599     BYTE* const ostart = (BYTE*)dst;
4600     BYTE* op = ostart;
4601     U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
4602     S64 savings = (S64)cctx->consumedSrcSize - (S64)cctx->producedCSize;
4603 
4604     assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX);
4605 
4606     DEBUGLOG(5, "ZSTD_compress_frameChunk (srcSize=%u, blockSizeMax=%u)", (unsigned)srcSize, (unsigned)blockSizeMax);
4607     if (cctx->appliedParams.fParams.checksumFlag && srcSize)
4608         XXH64_update(&cctx->xxhState, src, srcSize);
4609 
4610     while (remaining) {
4611         ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
4612         size_t const blockSize = ZSTD_optimalBlockSize(cctx,
4613                                 ip, remaining,
4614                                 blockSizeMax,
4615                                 cctx->appliedParams.preBlockSplitter_level,
4616                                 cctx->appliedParams.cParams.strategy,
4617                                 savings);
4618         U32 const lastBlock = lastFrameChunk & (blockSize == remaining);
4619         assert(blockSize <= remaining);
4620 
4621         /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
4622          * additional 1. We need to revisit and change this logic to be more consistent */
4623         RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE + 1,
4624                         dstSize_tooSmall,
4625                         "not enough space to store compressed block");
4626 
4627         ZSTD_overflowCorrectIfNeeded(
4628             ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize);
4629         ZSTD_checkDictValidity(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
4630         ZSTD_window_enforceMaxDist(&ms->window, ip, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
4631 
4632         /* Ensure hash/chain table insertion resumes no sooner than lowlimit */
4633         if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
4634 
4635         {   size_t cSize;
4636             if (ZSTD_useTargetCBlockSize(&cctx->appliedParams)) {
4637                 cSize = ZSTD_compressBlock_targetCBlockSize(cctx, op, dstCapacity, ip, blockSize, lastBlock);
4638                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_targetCBlockSize failed");
4639                 assert(cSize > 0);
4640                 assert(cSize <= blockSize + ZSTD_blockHeaderSize);
4641             } else if (ZSTD_blockSplitterEnabled(&cctx->appliedParams)) {
4642                 cSize = ZSTD_compressBlock_splitBlock(cctx, op, dstCapacity, ip, blockSize, lastBlock);
4643                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_splitBlock failed");
4644                 assert(cSize > 0 || cctx->seqCollector.collectSequences == 1);
4645             } else {
4646                 cSize = ZSTD_compressBlock_internal(cctx,
4647                                         op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
4648                                         ip, blockSize, 1 /* frame */);
4649                 FORWARD_IF_ERROR(cSize, "ZSTD_compressBlock_internal failed");
4650 
4651                 if (cSize == 0) {  /* block is not compressible */
4652                     cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
4653                     FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
4654                 } else {
4655                     U32 const cBlockHeader = cSize == 1 ?
4656                         lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) :
4657                         lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
4658                     MEM_writeLE24(op, cBlockHeader);
4659                     cSize += ZSTD_blockHeaderSize;
4660                 }
4661             }  /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/
4662 
4663             /* @savings is employed to ensure that splitting doesn't worsen expansion of incompressible data.
4664              * Without splitting, the maximum expansion is 3 bytes per full block.
4665              * An adversarial input could attempt to fudge the split detector,
4666              * and make it split incompressible data, resulting in more block headers.
4667              * Note that, since ZSTD_COMPRESSBOUND() assumes a worst case scenario of 1KB per block,
4668              * and the splitter never creates blocks that small (current lower limit is 8 KB),
4669              * there is already no risk to expand beyond ZSTD_COMPRESSBOUND() limit.
4670              * But if the goal is to not expand by more than 3-bytes per 128 KB full block,
4671              * then yes, it becomes possible to make the block splitter oversplit incompressible data.
4672              * Using @savings, we enforce an even more conservative condition,
4673              * requiring the presence of enough savings (at least 3 bytes) to authorize splitting,
4674              * otherwise only full blocks are used.
4675              * But being conservative is fine,
4676              * since splitting barely compressible blocks is not fruitful anyway */
4677             savings += (S64)blockSize - (S64)cSize;
4678 
4679             ip += blockSize;
4680             assert(remaining >= blockSize);
4681             remaining -= blockSize;
4682             op += cSize;
4683             assert(dstCapacity >= cSize);
4684             dstCapacity -= cSize;
4685             cctx->isFirstBlock = 0;
4686             DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
4687                         (unsigned)cSize);
4688     }   }
4689 
4690     if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
4691     return (size_t)(op-ostart);
4692 }
4693 
4694 
ZSTD_writeFrameHeader(void * dst,size_t dstCapacity,const ZSTD_CCtx_params * params,U64 pledgedSrcSize,U32 dictID)4695 static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
4696                                     const ZSTD_CCtx_params* params,
4697                                     U64 pledgedSrcSize, U32 dictID)
4698 {
4699     BYTE* const op = (BYTE*)dst;
4700     U32   const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536);   /* 0-3 */
4701     U32   const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength;   /* 0-3 */
4702     U32   const checksumFlag = params->fParams.checksumFlag>0;
4703     U32   const windowSize = (U32)1 << params->cParams.windowLog;
4704     U32   const singleSegment = params->fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
4705     BYTE  const windowLogByte = (BYTE)((params->cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
4706     U32   const fcsCode = params->fParams.contentSizeFlag ?
4707                      (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0;  /* 0-3 */
4708     BYTE  const frameHeaderDescriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
4709     size_t pos=0;
4710 
4711     assert(!(params->fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
4712     RETURN_ERROR_IF(dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX, dstSize_tooSmall,
4713                     "dst buf is too small to fit worst-case frame header size.");
4714     DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
4715                 !params->fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
4716     if (params->format == ZSTD_f_zstd1) {
4717         MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
4718         pos = 4;
4719     }
4720     op[pos++] = frameHeaderDescriptionByte;
4721     if (!singleSegment) op[pos++] = windowLogByte;
4722     switch(dictIDSizeCode)
4723     {
4724         default:
4725             assert(0); /* impossible */
4726             ZSTD_FALLTHROUGH;
4727         case 0 : break;
4728         case 1 : op[pos] = (BYTE)(dictID); pos++; break;
4729         case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
4730         case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
4731     }
4732     switch(fcsCode)
4733     {
4734         default:
4735             assert(0); /* impossible */
4736             ZSTD_FALLTHROUGH;
4737         case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
4738         case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
4739         case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
4740         case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
4741     }
4742     return pos;
4743 }
4744 
4745 /* ZSTD_writeSkippableFrame_advanced() :
4746  * Writes out a skippable frame with the specified magic number variant (16 are supported),
4747  * from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15, and the desired source data.
4748  *
4749  * Returns the total number of bytes written, or a ZSTD error code.
4750  */
ZSTD_writeSkippableFrame(void * dst,size_t dstCapacity,const void * src,size_t srcSize,unsigned magicVariant)4751 size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
4752                                 const void* src, size_t srcSize, unsigned magicVariant) {
4753     BYTE* op = (BYTE*)dst;
4754     RETURN_ERROR_IF(dstCapacity < srcSize + ZSTD_SKIPPABLEHEADERSIZE /* Skippable frame overhead */,
4755                     dstSize_tooSmall, "Not enough room for skippable frame");
4756     RETURN_ERROR_IF(srcSize > (unsigned)0xFFFFFFFF, srcSize_wrong, "Src size too large for skippable frame");
4757     RETURN_ERROR_IF(magicVariant > 15, parameter_outOfBound, "Skippable frame magic number variant not supported");
4758 
4759     MEM_writeLE32(op, (U32)(ZSTD_MAGIC_SKIPPABLE_START + magicVariant));
4760     MEM_writeLE32(op+4, (U32)srcSize);
4761     ZSTD_memcpy(op+8, src, srcSize);
4762     return srcSize + ZSTD_SKIPPABLEHEADERSIZE;
4763 }
4764 
4765 /* ZSTD_writeLastEmptyBlock() :
4766  * output an empty Block with end-of-frame mark to complete a frame
4767  * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
4768  *           or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
4769  */
ZSTD_writeLastEmptyBlock(void * dst,size_t dstCapacity)4770 size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
4771 {
4772     RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall,
4773                     "dst buf is too small to write frame trailer empty block.");
4774     {   U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1);  /* 0 size */
4775         MEM_writeLE24(dst, cBlockHeader24);
4776         return ZSTD_blockHeaderSize;
4777     }
4778 }
4779 
ZSTD_referenceExternalSequences(ZSTD_CCtx * cctx,rawSeq * seq,size_t nbSeq)4780 void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
4781 {
4782     assert(cctx->stage == ZSTDcs_init);
4783     assert(nbSeq == 0 || cctx->appliedParams.ldmParams.enableLdm != ZSTD_ps_enable);
4784     cctx->externSeqStore.seq = seq;
4785     cctx->externSeqStore.size = nbSeq;
4786     cctx->externSeqStore.capacity = nbSeq;
4787     cctx->externSeqStore.pos = 0;
4788     cctx->externSeqStore.posInSequence = 0;
4789 }
4790 
4791 
ZSTD_compressContinue_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,U32 frame,U32 lastFrameChunk)4792 static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
4793                               void* dst, size_t dstCapacity,
4794                         const void* src, size_t srcSize,
4795                                U32 frame, U32 lastFrameChunk)
4796 {
4797     ZSTD_MatchState_t* const ms = &cctx->blockState.matchState;
4798     size_t fhSize = 0;
4799 
4800     DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
4801                 cctx->stage, (unsigned)srcSize);
4802     RETURN_ERROR_IF(cctx->stage==ZSTDcs_created, stage_wrong,
4803                     "missing init (ZSTD_compressBegin)");
4804 
4805     if (frame && (cctx->stage==ZSTDcs_init)) {
4806         fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams,
4807                                        cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
4808         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
4809         assert(fhSize <= dstCapacity);
4810         dstCapacity -= fhSize;
4811         dst = (char*)dst + fhSize;
4812         cctx->stage = ZSTDcs_ongoing;
4813     }
4814 
4815     if (!srcSize) return fhSize;  /* do not generate an empty block if no input */
4816 
4817     if (!ZSTD_window_update(&ms->window, src, srcSize, ms->forceNonContiguous)) {
4818         ms->forceNonContiguous = 0;
4819         ms->nextToUpdate = ms->window.dictLimit;
4820     }
4821     if (cctx->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) {
4822         ZSTD_window_update(&cctx->ldmState.window, src, srcSize, /* forceNonContiguous */ 0);
4823     }
4824 
4825     if (!frame) {
4826         /* overflow check and correction for block mode */
4827         ZSTD_overflowCorrectIfNeeded(
4828             ms, &cctx->workspace, &cctx->appliedParams,
4829             src, (BYTE const*)src + srcSize);
4830     }
4831 
4832     DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSizeMax);
4833     {   size_t const cSize = frame ?
4834                              ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
4835                              ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */);
4836         FORWARD_IF_ERROR(cSize, "%s", frame ? "ZSTD_compress_frameChunk failed" : "ZSTD_compressBlock_internal failed");
4837         cctx->consumedSrcSize += srcSize;
4838         cctx->producedCSize += (cSize + fhSize);
4839         assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
4840         if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
4841             ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
4842             RETURN_ERROR_IF(
4843                 cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne,
4844                 srcSize_wrong,
4845                 "error : pledgedSrcSize = %u, while realSrcSize >= %u",
4846                 (unsigned)cctx->pledgedSrcSizePlusOne-1,
4847                 (unsigned)cctx->consumedSrcSize);
4848         }
4849         return cSize + fhSize;
4850     }
4851 }
4852 
ZSTD_compressContinue_public(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4853 size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
4854                                         void* dst, size_t dstCapacity,
4855                                   const void* src, size_t srcSize)
4856 {
4857     DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
4858     return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
4859 }
4860 
4861 /* NOTE: Must just wrap ZSTD_compressContinue_public() */
ZSTD_compressContinue(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4862 size_t ZSTD_compressContinue(ZSTD_CCtx* cctx,
4863                              void* dst, size_t dstCapacity,
4864                        const void* src, size_t srcSize)
4865 {
4866     return ZSTD_compressContinue_public(cctx, dst, dstCapacity, src, srcSize);
4867 }
4868 
ZSTD_getBlockSize_deprecated(const ZSTD_CCtx * cctx)4869 static size_t ZSTD_getBlockSize_deprecated(const ZSTD_CCtx* cctx)
4870 {
4871     ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
4872     assert(!ZSTD_checkCParams(cParams));
4873     return MIN(cctx->appliedParams.maxBlockSize, (size_t)1 << cParams.windowLog);
4874 }
4875 
4876 /* NOTE: Must just wrap ZSTD_getBlockSize_deprecated() */
ZSTD_getBlockSize(const ZSTD_CCtx * cctx)4877 size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
4878 {
4879     return ZSTD_getBlockSize_deprecated(cctx);
4880 }
4881 
4882 /* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
ZSTD_compressBlock_deprecated(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4883 size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
4884 {
4885     DEBUGLOG(5, "ZSTD_compressBlock: srcSize = %u", (unsigned)srcSize);
4886     { size_t const blockSizeMax = ZSTD_getBlockSize_deprecated(cctx);
4887       RETURN_ERROR_IF(srcSize > blockSizeMax, srcSize_wrong, "input is larger than a block"); }
4888 
4889     return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
4890 }
4891 
4892 /* NOTE: Must just wrap ZSTD_compressBlock_deprecated() */
ZSTD_compressBlock(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)4893 size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
4894 {
4895     return ZSTD_compressBlock_deprecated(cctx, dst, dstCapacity, src, srcSize);
4896 }
4897 
4898 /*! ZSTD_loadDictionaryContent() :
4899  *  @return : 0, or an error code
4900  */
4901 static size_t
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,ZSTD_tableFillPurpose_e tfp)4902 ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms,
4903                         ldmState_t* ls,
4904                         ZSTD_cwksp* ws,
4905                         ZSTD_CCtx_params const* params,
4906                         const void* src, size_t srcSize,
4907                         ZSTD_dictTableLoadMethod_e dtlm,
4908                         ZSTD_tableFillPurpose_e tfp)
4909 {
4910     const BYTE* ip = (const BYTE*) src;
4911     const BYTE* const iend = ip + srcSize;
4912     int const loadLdmDict = params->ldmParams.enableLdm == ZSTD_ps_enable && ls != NULL;
4913 
4914     /* Assert that the ms params match the params we're being given */
4915     ZSTD_assertEqualCParams(params->cParams, ms->cParams);
4916 
4917     {   /* Ensure large dictionaries can't cause index overflow */
4918 
4919         /* Allow the dictionary to set indices up to exactly ZSTD_CURRENT_MAX.
4920          * Dictionaries right at the edge will immediately trigger overflow
4921          * correction, but I don't want to insert extra constraints here.
4922          */
4923         U32 maxDictSize = ZSTD_CURRENT_MAX - ZSTD_WINDOW_START_INDEX;
4924 
4925         int const CDictTaggedIndices = ZSTD_CDictIndicesAreTagged(&params->cParams);
4926         if (CDictTaggedIndices && tfp == ZSTD_tfp_forCDict) {
4927             /* Some dictionary matchfinders in zstd use "short cache",
4928              * which treats the lower ZSTD_SHORT_CACHE_TAG_BITS of each
4929              * CDict hashtable entry as a tag rather than as part of an index.
4930              * When short cache is used, we need to truncate the dictionary
4931              * so that its indices don't overlap with the tag. */
4932             U32 const shortCacheMaxDictSize = (1u << (32 - ZSTD_SHORT_CACHE_TAG_BITS)) - ZSTD_WINDOW_START_INDEX;
4933             maxDictSize = MIN(maxDictSize, shortCacheMaxDictSize);
4934             assert(!loadLdmDict);
4935         }
4936 
4937         /* If the dictionary is too large, only load the suffix of the dictionary. */
4938         if (srcSize > maxDictSize) {
4939             ip = iend - maxDictSize;
4940             src = ip;
4941             srcSize = maxDictSize;
4942         }
4943     }
4944 
4945     if (srcSize > ZSTD_CHUNKSIZE_MAX) {
4946         /* We must have cleared our windows when our source is this large. */
4947         assert(ZSTD_window_isEmpty(ms->window));
4948         if (loadLdmDict) assert(ZSTD_window_isEmpty(ls->window));
4949     }
4950     ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0);
4951 
4952     DEBUGLOG(4, "ZSTD_loadDictionaryContent: useRowMatchFinder=%d", (int)params->useRowMatchFinder);
4953 
4954     if (loadLdmDict) { /* Load the entire dict into LDM matchfinders. */
4955         DEBUGLOG(4, "ZSTD_loadDictionaryContent: Trigger loadLdmDict");
4956         ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0);
4957         ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base);
4958         ZSTD_ldm_fillHashTable(ls, ip, iend, &params->ldmParams);
4959         DEBUGLOG(4, "ZSTD_loadDictionaryContent: ZSTD_ldm_fillHashTable completes");
4960     }
4961 
4962     /* If the dict is larger than we can reasonably index in our tables, only load the suffix. */
4963     {   U32 maxDictSize = 1U << MIN(MAX(params->cParams.hashLog + 3, params->cParams.chainLog + 1), 31);
4964         if (srcSize > maxDictSize) {
4965             ip = iend - maxDictSize;
4966             src = ip;
4967             srcSize = maxDictSize;
4968         }
4969     }
4970 
4971     ms->nextToUpdate = (U32)(ip - ms->window.base);
4972     ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
4973     ms->forceNonContiguous = params->deterministicRefPrefix;
4974 
4975     if (srcSize <= HASH_READ_SIZE) return 0;
4976 
4977     ZSTD_overflowCorrectIfNeeded(ms, ws, params, ip, iend);
4978 
4979     switch(params->cParams.strategy)
4980     {
4981     case ZSTD_fast:
4982         ZSTD_fillHashTable(ms, iend, dtlm, tfp);
4983         break;
4984     case ZSTD_dfast:
4985 #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
4986         ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp);
4987 #else
4988         assert(0); /* shouldn't be called: cparams should've been adjusted. */
4989 #endif
4990         break;
4991 
4992     case ZSTD_greedy:
4993     case ZSTD_lazy:
4994     case ZSTD_lazy2:
4995 #if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \
4996  || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \
4997  || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR)
4998         assert(srcSize >= HASH_READ_SIZE);
4999         if (ms->dedicatedDictSearch) {
5000             assert(ms->chainTable != NULL);
5001             ZSTD_dedicatedDictSearch_lazy_loadDictionary(ms, iend-HASH_READ_SIZE);
5002         } else {
5003             assert(params->useRowMatchFinder != ZSTD_ps_auto);
5004             if (params->useRowMatchFinder == ZSTD_ps_enable) {
5005                 size_t const tagTableSize = ((size_t)1 << params->cParams.hashLog);
5006                 ZSTD_memset(ms->tagTable, 0, tagTableSize);
5007                 ZSTD_row_update(ms, iend-HASH_READ_SIZE);
5008                 DEBUGLOG(4, "Using row-based hash table for lazy dict");
5009             } else {
5010                 ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
5011                 DEBUGLOG(4, "Using chain-based hash table for lazy dict");
5012             }
5013         }
5014 #else
5015         assert(0); /* shouldn't be called: cparams should've been adjusted. */
5016 #endif
5017         break;
5018 
5019     case ZSTD_btlazy2:   /* we want the dictionary table fully sorted */
5020     case ZSTD_btopt:
5021     case ZSTD_btultra:
5022     case ZSTD_btultra2:
5023 #if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
5024  || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
5025  || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
5026         assert(srcSize >= HASH_READ_SIZE);
5027         DEBUGLOG(4, "Fill %u bytes into the Binary Tree", (unsigned)srcSize);
5028         ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
5029 #else
5030         assert(0); /* shouldn't be called: cparams should've been adjusted. */
5031 #endif
5032         break;
5033 
5034     default:
5035         assert(0);  /* not possible : not a valid strategy id */
5036     }
5037 
5038     ms->nextToUpdate = (U32)(iend - ms->window.base);
5039     return 0;
5040 }
5041 
5042 
5043 /* Dictionaries that assign zero probability to symbols that show up causes problems
5044  * when FSE encoding. Mark dictionaries with zero probability symbols as FSE_repeat_check
5045  * and only dictionaries with 100% valid symbols can be assumed valid.
5046  */
ZSTD_dictNCountRepeat(short * normalizedCounter,unsigned dictMaxSymbolValue,unsigned maxSymbolValue)5047 static FSE_repeat ZSTD_dictNCountRepeat(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue)
5048 {
5049     U32 s;
5050     if (dictMaxSymbolValue < maxSymbolValue) {
5051         return FSE_repeat_check;
5052     }
5053     for (s = 0; s <= maxSymbolValue; ++s) {
5054         if (normalizedCounter[s] == 0) {
5055             return FSE_repeat_check;
5056         }
5057     }
5058     return FSE_repeat_valid;
5059 }
5060 
ZSTD_loadCEntropy(ZSTD_compressedBlockState_t * bs,void * workspace,const void * const dict,size_t dictSize)5061 size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
5062                          const void* const dict, size_t dictSize)
5063 {
5064     short offcodeNCount[MaxOff+1];
5065     unsigned offcodeMaxValue = MaxOff;
5066     const BYTE* dictPtr = (const BYTE*)dict;    /* skip magic num and dict ID */
5067     const BYTE* const dictEnd = dictPtr + dictSize;
5068     dictPtr += 8;
5069     bs->entropy.huf.repeatMode = HUF_repeat_check;
5070 
5071     {   unsigned maxSymbolValue = 255;
5072         unsigned hasZeroWeights = 1;
5073         size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr,
5074             (size_t)(dictEnd-dictPtr), &hasZeroWeights);
5075 
5076         /* We only set the loaded table as valid if it contains all non-zero
5077          * weights. Otherwise, we set it to check */
5078         if (!hasZeroWeights && maxSymbolValue == 255)
5079             bs->entropy.huf.repeatMode = HUF_repeat_valid;
5080 
5081         RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, "");
5082         dictPtr += hufHeaderSize;
5083     }
5084 
5085     {   unsigned offcodeLog;
5086         size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr));
5087         RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
5088         RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
5089         /* fill all offset symbols to avoid garbage at end of table */
5090         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5091                 bs->entropy.fse.offcodeCTable,
5092                 offcodeNCount, MaxOff, offcodeLog,
5093                 workspace, HUF_WORKSPACE_SIZE)),
5094             dictionary_corrupted, "");
5095         /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
5096         dictPtr += offcodeHeaderSize;
5097     }
5098 
5099     {   short matchlengthNCount[MaxML+1];
5100         unsigned matchlengthMaxValue = MaxML, matchlengthLog;
5101         size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
5102         RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
5103         RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
5104         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5105                 bs->entropy.fse.matchlengthCTable,
5106                 matchlengthNCount, matchlengthMaxValue, matchlengthLog,
5107                 workspace, HUF_WORKSPACE_SIZE)),
5108             dictionary_corrupted, "");
5109         bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML);
5110         dictPtr += matchlengthHeaderSize;
5111     }
5112 
5113     {   short litlengthNCount[MaxLL+1];
5114         unsigned litlengthMaxValue = MaxLL, litlengthLog;
5115         size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
5116         RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
5117         RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
5118         RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp(
5119                 bs->entropy.fse.litlengthCTable,
5120                 litlengthNCount, litlengthMaxValue, litlengthLog,
5121                 workspace, HUF_WORKSPACE_SIZE)),
5122             dictionary_corrupted, "");
5123         bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL);
5124         dictPtr += litlengthHeaderSize;
5125     }
5126 
5127     RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
5128     bs->rep[0] = MEM_readLE32(dictPtr+0);
5129     bs->rep[1] = MEM_readLE32(dictPtr+4);
5130     bs->rep[2] = MEM_readLE32(dictPtr+8);
5131     dictPtr += 12;
5132 
5133     {   size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
5134         U32 offcodeMax = MaxOff;
5135         if (dictContentSize <= ((U32)-1) - 128 KB) {
5136             U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
5137             offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
5138         }
5139         /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */
5140         bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff));
5141 
5142         /* All repCodes must be <= dictContentSize and != 0 */
5143         {   U32 u;
5144             for (u=0; u<3; u++) {
5145                 RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, "");
5146                 RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, "");
5147     }   }   }
5148 
5149     return (size_t)(dictPtr - (const BYTE*)dict);
5150 }
5151 
5152 /* Dictionary format :
5153  * See :
5154  * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format
5155  */
5156 /*! ZSTD_loadZstdDictionary() :
5157  * @return : dictID, or an error code
5158  *  assumptions : magic number supposed already checked
5159  *                dictSize supposed >= 8
5160  */
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,ZSTD_tableFillPurpose_e tfp,void * workspace)5161 static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
5162                                       ZSTD_MatchState_t* ms,
5163                                       ZSTD_cwksp* ws,
5164                                       ZSTD_CCtx_params const* params,
5165                                       const void* dict, size_t dictSize,
5166                                       ZSTD_dictTableLoadMethod_e dtlm,
5167                                       ZSTD_tableFillPurpose_e tfp,
5168                                       void* workspace)
5169 {
5170     const BYTE* dictPtr = (const BYTE*)dict;
5171     const BYTE* const dictEnd = dictPtr + dictSize;
5172     size_t dictID;
5173     size_t eSize;
5174     ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
5175     assert(dictSize >= 8);
5176     assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
5177 
5178     dictID = params->fParams.noDictIDFlag ? 0 :  MEM_readLE32(dictPtr + 4 /* skip magic number */ );
5179     eSize = ZSTD_loadCEntropy(bs, workspace, dict, dictSize);
5180     FORWARD_IF_ERROR(eSize, "ZSTD_loadCEntropy failed");
5181     dictPtr += eSize;
5182 
5183     {
5184         size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
5185         FORWARD_IF_ERROR(ZSTD_loadDictionaryContent(
5186             ms, NULL, ws, params, dictPtr, dictContentSize, dtlm, tfp), "");
5187     }
5188     return dictID;
5189 }
5190 
5191 /** ZSTD_compress_insertDictionary() :
5192 *   @return : dictID, or an error code */
5193 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,ZSTD_tableFillPurpose_e tfp,void * workspace)5194 ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
5195                                ZSTD_MatchState_t* ms,
5196                                ldmState_t* ls,
5197                                ZSTD_cwksp* ws,
5198                          const ZSTD_CCtx_params* params,
5199                          const void* dict, size_t dictSize,
5200                                ZSTD_dictContentType_e dictContentType,
5201                                ZSTD_dictTableLoadMethod_e dtlm,
5202                                ZSTD_tableFillPurpose_e tfp,
5203                                void* workspace)
5204 {
5205     DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
5206     if ((dict==NULL) || (dictSize<8)) {
5207         RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
5208         return 0;
5209     }
5210 
5211     ZSTD_reset_compressedBlockState(bs);
5212 
5213     /* dict restricted modes */
5214     if (dictContentType == ZSTD_dct_rawContent)
5215         return ZSTD_loadDictionaryContent(ms, ls, ws, params, dict, dictSize, dtlm, tfp);
5216 
5217     if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
5218         if (dictContentType == ZSTD_dct_auto) {
5219             DEBUGLOG(4, "raw content dictionary detected");
5220             return ZSTD_loadDictionaryContent(
5221                 ms, ls, ws, params, dict, dictSize, dtlm, tfp);
5222         }
5223         RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, "");
5224         assert(0);   /* impossible */
5225     }
5226 
5227     /* dict as full zstd dictionary */
5228     return ZSTD_loadZstdDictionary(
5229         bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace);
5230 }
5231 
5232 #define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB)
5233 #define ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER (6ULL)
5234 
5235 /*! ZSTD_compressBegin_internal() :
5236  * Assumption : either @dict OR @cdict (or none) is non-NULL, never both
5237  * @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)5238 static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
5239                                     const void* dict, size_t dictSize,
5240                                     ZSTD_dictContentType_e dictContentType,
5241                                     ZSTD_dictTableLoadMethod_e dtlm,
5242                                     const ZSTD_CDict* cdict,
5243                                     const ZSTD_CCtx_params* params, U64 pledgedSrcSize,
5244                                     ZSTD_buffered_policy_e zbuff)
5245 {
5246     size_t const dictContentSize = cdict ? cdict->dictContentSize : dictSize;
5247 #if ZSTD_TRACE
5248     cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
5249 #endif
5250     DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params->cParams.windowLog);
5251     /* params are supposed to be fully validated at this point */
5252     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
5253     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
5254     if ( (cdict)
5255       && (cdict->dictContentSize > 0)
5256       && ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
5257         || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
5258         || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
5259         || cdict->compressionLevel == 0)
5260       && (params->attachDictPref != ZSTD_dictForceLoad) ) {
5261         return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
5262     }
5263 
5264     FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
5265                                      dictContentSize,
5266                                      ZSTDcrp_makeClean, zbuff) , "");
5267     {   size_t const dictID = cdict ?
5268                 ZSTD_compress_insertDictionary(
5269                         cctx->blockState.prevCBlock, &cctx->blockState.matchState,
5270                         &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent,
5271                         cdict->dictContentSize, cdict->dictContentType, dtlm,
5272                         ZSTD_tfp_forCCtx, cctx->tmpWorkspace)
5273               : ZSTD_compress_insertDictionary(
5274                         cctx->blockState.prevCBlock, &cctx->blockState.matchState,
5275                         &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize,
5276                         dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace);
5277         FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
5278         assert(dictID <= UINT_MAX);
5279         cctx->dictID = (U32)dictID;
5280         cctx->dictContentSize = dictContentSize;
5281     }
5282     return 0;
5283 }
5284 
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)5285 size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
5286                                     const void* dict, size_t dictSize,
5287                                     ZSTD_dictContentType_e dictContentType,
5288                                     ZSTD_dictTableLoadMethod_e dtlm,
5289                                     const ZSTD_CDict* cdict,
5290                                     const ZSTD_CCtx_params* params,
5291                                     unsigned long long pledgedSrcSize)
5292 {
5293     DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params->cParams.windowLog);
5294     /* compression parameters verification and optimization */
5295     FORWARD_IF_ERROR( ZSTD_checkCParams(params->cParams) , "");
5296     return ZSTD_compressBegin_internal(cctx,
5297                                        dict, dictSize, dictContentType, dtlm,
5298                                        cdict,
5299                                        params, pledgedSrcSize,
5300                                        ZSTDb_not_buffered);
5301 }
5302 
5303 /*! ZSTD_compressBegin_advanced() :
5304 *   @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)5305 size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
5306                              const void* dict, size_t dictSize,
5307                                    ZSTD_parameters params, unsigned long long pledgedSrcSize)
5308 {
5309     ZSTD_CCtx_params cctxParams;
5310     ZSTD_CCtxParams_init_internal(&cctxParams, &params, ZSTD_NO_CLEVEL);
5311     return ZSTD_compressBegin_advanced_internal(cctx,
5312                                             dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
5313                                             NULL /*cdict*/,
5314                                             &cctxParams, pledgedSrcSize);
5315 }
5316 
5317 static size_t
ZSTD_compressBegin_usingDict_deprecated(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,int compressionLevel)5318 ZSTD_compressBegin_usingDict_deprecated(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
5319 {
5320     ZSTD_CCtx_params cctxParams;
5321     {   ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_noAttachDict);
5322         ZSTD_CCtxParams_init_internal(&cctxParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel);
5323     }
5324     DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
5325     return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
5326                                        &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
5327 }
5328 
5329 size_t
ZSTD_compressBegin_usingDict(ZSTD_CCtx * cctx,const void * dict,size_t dictSize,int compressionLevel)5330 ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
5331 {
5332     return ZSTD_compressBegin_usingDict_deprecated(cctx, dict, dictSize, compressionLevel);
5333 }
5334 
ZSTD_compressBegin(ZSTD_CCtx * cctx,int compressionLevel)5335 size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
5336 {
5337     return ZSTD_compressBegin_usingDict_deprecated(cctx, NULL, 0, compressionLevel);
5338 }
5339 
5340 
5341 /*! ZSTD_writeEpilogue() :
5342 *   Ends a frame.
5343 *   @return : nb of bytes written into dst (or an error code) */
ZSTD_writeEpilogue(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity)5344 static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
5345 {
5346     BYTE* const ostart = (BYTE*)dst;
5347     BYTE* op = ostart;
5348 
5349     DEBUGLOG(4, "ZSTD_writeEpilogue");
5350     RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
5351 
5352     /* special case : empty frame */
5353     if (cctx->stage == ZSTDcs_init) {
5354         size_t fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
5355         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
5356         dstCapacity -= fhSize;
5357         op += fhSize;
5358         cctx->stage = ZSTDcs_ongoing;
5359     }
5360 
5361     if (cctx->stage != ZSTDcs_ending) {
5362         /* write one last empty block, make it the "last" block */
5363         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
5364         ZSTD_STATIC_ASSERT(ZSTD_BLOCKHEADERSIZE == 3);
5365         RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "no room for epilogue");
5366         MEM_writeLE24(op, cBlockHeader24);
5367         op += ZSTD_blockHeaderSize;
5368         dstCapacity -= ZSTD_blockHeaderSize;
5369     }
5370 
5371     if (cctx->appliedParams.fParams.checksumFlag) {
5372         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
5373         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
5374         DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
5375         MEM_writeLE32(op, checksum);
5376         op += 4;
5377     }
5378 
5379     cctx->stage = ZSTDcs_created;  /* return to "created but no init" status */
5380     return (size_t)(op-ostart);
5381 }
5382 
ZSTD_CCtx_trace(ZSTD_CCtx * cctx,size_t extraCSize)5383 void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize)
5384 {
5385 #if ZSTD_TRACE
5386     if (cctx->traceCtx && ZSTD_trace_compress_end != NULL) {
5387         int const streaming = cctx->inBuffSize > 0 || cctx->outBuffSize > 0 || cctx->appliedParams.nbWorkers > 0;
5388         ZSTD_Trace trace;
5389         ZSTD_memset(&trace, 0, sizeof(trace));
5390         trace.version = ZSTD_VERSION_NUMBER;
5391         trace.streaming = streaming;
5392         trace.dictionaryID = cctx->dictID;
5393         trace.dictionarySize = cctx->dictContentSize;
5394         trace.uncompressedSize = cctx->consumedSrcSize;
5395         trace.compressedSize = cctx->producedCSize + extraCSize;
5396         trace.params = &cctx->appliedParams;
5397         trace.cctx = cctx;
5398         ZSTD_trace_compress_end(cctx->traceCtx, &trace);
5399     }
5400     cctx->traceCtx = 0;
5401 #else
5402     (void)cctx;
5403     (void)extraCSize;
5404 #endif
5405 }
5406 
ZSTD_compressEnd_public(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)5407 size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
5408                                void* dst, size_t dstCapacity,
5409                          const void* src, size_t srcSize)
5410 {
5411     size_t endResult;
5412     size_t const cSize = ZSTD_compressContinue_internal(cctx,
5413                                 dst, dstCapacity, src, srcSize,
5414                                 1 /* frame mode */, 1 /* last chunk */);
5415     FORWARD_IF_ERROR(cSize, "ZSTD_compressContinue_internal failed");
5416     endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
5417     FORWARD_IF_ERROR(endResult, "ZSTD_writeEpilogue failed");
5418     assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
5419     if (cctx->pledgedSrcSizePlusOne != 0) {  /* control src size */
5420         ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
5421         DEBUGLOG(4, "end of frame : controlling src size");
5422         RETURN_ERROR_IF(
5423             cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1,
5424             srcSize_wrong,
5425              "error : pledgedSrcSize = %u, while realSrcSize = %u",
5426             (unsigned)cctx->pledgedSrcSizePlusOne-1,
5427             (unsigned)cctx->consumedSrcSize);
5428     }
5429     ZSTD_CCtx_trace(cctx, endResult);
5430     return cSize + endResult;
5431 }
5432 
5433 /* NOTE: Must just wrap ZSTD_compressEnd_public() */
ZSTD_compressEnd(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)5434 size_t ZSTD_compressEnd(ZSTD_CCtx* cctx,
5435                         void* dst, size_t dstCapacity,
5436                   const void* src, size_t srcSize)
5437 {
5438     return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
5439 }
5440 
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)5441 size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
5442                                void* dst, size_t dstCapacity,
5443                          const void* src, size_t srcSize,
5444                          const void* dict,size_t dictSize,
5445                                ZSTD_parameters params)
5446 {
5447     DEBUGLOG(4, "ZSTD_compress_advanced");
5448     FORWARD_IF_ERROR(ZSTD_checkCParams(params.cParams), "");
5449     ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, ZSTD_NO_CLEVEL);
5450     return ZSTD_compress_advanced_internal(cctx,
5451                                            dst, dstCapacity,
5452                                            src, srcSize,
5453                                            dict, dictSize,
5454                                            &cctx->simpleApiParams);
5455 }
5456 
5457 /* 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)5458 size_t ZSTD_compress_advanced_internal(
5459         ZSTD_CCtx* cctx,
5460         void* dst, size_t dstCapacity,
5461         const void* src, size_t srcSize,
5462         const void* dict,size_t dictSize,
5463         const ZSTD_CCtx_params* params)
5464 {
5465     DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
5466     FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
5467                          dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
5468                          params, srcSize, ZSTDb_not_buffered) , "");
5469     return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
5470 }
5471 
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)5472 size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
5473                                void* dst, size_t dstCapacity,
5474                          const void* src, size_t srcSize,
5475                          const void* dict, size_t dictSize,
5476                                int compressionLevel)
5477 {
5478     {
5479         ZSTD_parameters const params = ZSTD_getParams_internal(compressionLevel, srcSize, dict ? dictSize : 0, ZSTD_cpm_noAttachDict);
5480         assert(params.fParams.contentSizeFlag == 1);
5481         ZSTD_CCtxParams_init_internal(&cctx->simpleApiParams, &params, (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT: compressionLevel);
5482     }
5483     DEBUGLOG(4, "ZSTD_compress_usingDict (srcSize=%u)", (unsigned)srcSize);
5484     return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, &cctx->simpleApiParams);
5485 }
5486 
ZSTD_compressCCtx(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,int compressionLevel)5487 size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
5488                          void* dst, size_t dstCapacity,
5489                    const void* src, size_t srcSize,
5490                          int compressionLevel)
5491 {
5492     DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
5493     assert(cctx != NULL);
5494     return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
5495 }
5496 
ZSTD_compress(void * dst,size_t dstCapacity,const void * src,size_t srcSize,int compressionLevel)5497 size_t ZSTD_compress(void* dst, size_t dstCapacity,
5498                const void* src, size_t srcSize,
5499                      int compressionLevel)
5500 {
5501     size_t result;
5502 #if ZSTD_COMPRESS_HEAPMODE
5503     ZSTD_CCtx* cctx = ZSTD_createCCtx();
5504     RETURN_ERROR_IF(!cctx, memory_allocation, "ZSTD_createCCtx failed");
5505     result = ZSTD_compressCCtx(cctx, dst, dstCapacity, src, srcSize, compressionLevel);
5506     ZSTD_freeCCtx(cctx);
5507 #else
5508     ZSTD_CCtx ctxBody;
5509     ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
5510     result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
5511     ZSTD_freeCCtxContent(&ctxBody);   /* can't free ctxBody itself, as it's on stack; free only heap content */
5512 #endif
5513     return result;
5514 }
5515 
5516 
5517 /* =====  Dictionary API  ===== */
5518 
5519 /*! ZSTD_estimateCDictSize_advanced() :
5520  *  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)5521 size_t ZSTD_estimateCDictSize_advanced(
5522         size_t dictSize, ZSTD_compressionParameters cParams,
5523         ZSTD_dictLoadMethod_e dictLoadMethod)
5524 {
5525     DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
5526     return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5527          + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5528          /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small
5529           * in case we are using DDS with row-hash. */
5530          + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams),
5531                                   /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0)
5532          + (dictLoadMethod == ZSTD_dlm_byRef ? 0
5533             : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *))));
5534 }
5535 
ZSTD_estimateCDictSize(size_t dictSize,int compressionLevel)5536 size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
5537 {
5538     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5539     return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
5540 }
5541 
ZSTD_sizeof_CDict(const ZSTD_CDict * cdict)5542 size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
5543 {
5544     if (cdict==NULL) return 0;   /* support sizeof on NULL */
5545     DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
5546     /* cdict may be in the workspace */
5547     return (cdict->workspace.workspace == cdict ? 0 : sizeof(*cdict))
5548         + ZSTD_cwksp_sizeof(&cdict->workspace);
5549 }
5550 
ZSTD_initCDict_internal(ZSTD_CDict * cdict,const void * dictBuffer,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_CCtx_params params)5551 static size_t ZSTD_initCDict_internal(
5552                     ZSTD_CDict* cdict,
5553               const void* dictBuffer, size_t dictSize,
5554                     ZSTD_dictLoadMethod_e dictLoadMethod,
5555                     ZSTD_dictContentType_e dictContentType,
5556                     ZSTD_CCtx_params params)
5557 {
5558     DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
5559     assert(!ZSTD_checkCParams(params.cParams));
5560     cdict->matchState.cParams = params.cParams;
5561     cdict->matchState.dedicatedDictSearch = params.enableDedicatedDictSearch;
5562     if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
5563         cdict->dictContent = dictBuffer;
5564     } else {
5565          void *internalBuffer = ZSTD_cwksp_reserve_object(&cdict->workspace, ZSTD_cwksp_align(dictSize, sizeof(void*)));
5566         RETURN_ERROR_IF(!internalBuffer, memory_allocation, "NULL pointer!");
5567         cdict->dictContent = internalBuffer;
5568         ZSTD_memcpy(internalBuffer, dictBuffer, dictSize);
5569     }
5570     cdict->dictContentSize = dictSize;
5571     cdict->dictContentType = dictContentType;
5572 
5573     cdict->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cdict->workspace, HUF_WORKSPACE_SIZE);
5574 
5575 
5576     /* Reset the state to no dictionary */
5577     ZSTD_reset_compressedBlockState(&cdict->cBlockState);
5578     FORWARD_IF_ERROR(ZSTD_reset_matchState(
5579         &cdict->matchState,
5580         &cdict->workspace,
5581         &params.cParams,
5582         params.useRowMatchFinder,
5583         ZSTDcrp_makeClean,
5584         ZSTDirp_reset,
5585         ZSTD_resetTarget_CDict), "");
5586     /* (Maybe) load the dictionary
5587      * Skips loading the dictionary if it is < 8 bytes.
5588      */
5589     {   params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
5590         params.fParams.contentSizeFlag = 1;
5591         {   size_t const dictID = ZSTD_compress_insertDictionary(
5592                     &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace,
5593                     &params, cdict->dictContent, cdict->dictContentSize,
5594                     dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace);
5595             FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed");
5596             assert(dictID <= (size_t)(U32)-1);
5597             cdict->dictID = (U32)dictID;
5598         }
5599     }
5600 
5601     return 0;
5602 }
5603 
5604 static ZSTD_CDict*
ZSTD_createCDict_advanced_internal(size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_compressionParameters cParams,ZSTD_ParamSwitch_e useRowMatchFinder,int enableDedicatedDictSearch,ZSTD_customMem customMem)5605 ZSTD_createCDict_advanced_internal(size_t dictSize,
5606                                 ZSTD_dictLoadMethod_e dictLoadMethod,
5607                                 ZSTD_compressionParameters cParams,
5608                                 ZSTD_ParamSwitch_e useRowMatchFinder,
5609                                 int enableDedicatedDictSearch,
5610                                 ZSTD_customMem customMem)
5611 {
5612     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
5613     DEBUGLOG(3, "ZSTD_createCDict_advanced_internal (dictSize=%u)", (unsigned)dictSize);
5614 
5615     {   size_t const workspaceSize =
5616             ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) +
5617             ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) +
5618             ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) +
5619             (dictLoadMethod == ZSTD_dlm_byRef ? 0
5620              : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))));
5621         void* const workspace = ZSTD_customMalloc(workspaceSize, customMem);
5622         ZSTD_cwksp ws;
5623         ZSTD_CDict* cdict;
5624 
5625         if (!workspace) {
5626             ZSTD_customFree(workspace, customMem);
5627             return NULL;
5628         }
5629 
5630         ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_dynamic_alloc);
5631 
5632         cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
5633         assert(cdict != NULL);
5634         ZSTD_cwksp_move(&cdict->workspace, &ws);
5635         cdict->customMem = customMem;
5636         cdict->compressionLevel = ZSTD_NO_CLEVEL; /* signals advanced API usage */
5637         cdict->useRowMatchFinder = useRowMatchFinder;
5638         return cdict;
5639     }
5640 }
5641 
ZSTD_createCDict_advanced(const void * dictBuffer,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_compressionParameters cParams,ZSTD_customMem customMem)5642 ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
5643                                       ZSTD_dictLoadMethod_e dictLoadMethod,
5644                                       ZSTD_dictContentType_e dictContentType,
5645                                       ZSTD_compressionParameters cParams,
5646                                       ZSTD_customMem customMem)
5647 {
5648     ZSTD_CCtx_params cctxParams;
5649     ZSTD_memset(&cctxParams, 0, sizeof(cctxParams));
5650     DEBUGLOG(3, "ZSTD_createCDict_advanced, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
5651     ZSTD_CCtxParams_init(&cctxParams, 0);
5652     cctxParams.cParams = cParams;
5653     cctxParams.customMem = customMem;
5654     return ZSTD_createCDict_advanced2(
5655         dictBuffer, dictSize,
5656         dictLoadMethod, dictContentType,
5657         &cctxParams, customMem);
5658 }
5659 
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)5660 ZSTD_CDict* ZSTD_createCDict_advanced2(
5661         const void* dict, size_t dictSize,
5662         ZSTD_dictLoadMethod_e dictLoadMethod,
5663         ZSTD_dictContentType_e dictContentType,
5664         const ZSTD_CCtx_params* originalCctxParams,
5665         ZSTD_customMem customMem)
5666 {
5667     ZSTD_CCtx_params cctxParams = *originalCctxParams;
5668     ZSTD_compressionParameters cParams;
5669     ZSTD_CDict* cdict;
5670 
5671     DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType);
5672     if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
5673 
5674     if (cctxParams.enableDedicatedDictSearch) {
5675         cParams = ZSTD_dedicatedDictSearch_getCParams(
5676             cctxParams.compressionLevel, dictSize);
5677         ZSTD_overrideCParams(&cParams, &cctxParams.cParams);
5678     } else {
5679         cParams = ZSTD_getCParamsFromCCtxParams(
5680             &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5681     }
5682 
5683     if (!ZSTD_dedicatedDictSearch_isSupported(&cParams)) {
5684         /* Fall back to non-DDSS params */
5685         cctxParams.enableDedicatedDictSearch = 0;
5686         cParams = ZSTD_getCParamsFromCCtxParams(
5687             &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5688     }
5689 
5690     DEBUGLOG(3, "ZSTD_createCDict_advanced2: DedicatedDictSearch=%u", cctxParams.enableDedicatedDictSearch);
5691     cctxParams.cParams = cParams;
5692     cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams);
5693 
5694     cdict = ZSTD_createCDict_advanced_internal(dictSize,
5695                         dictLoadMethod, cctxParams.cParams,
5696                         cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
5697                         customMem);
5698 
5699     if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict,
5700                                     dict, dictSize,
5701                                     dictLoadMethod, dictContentType,
5702                                     cctxParams) )) {
5703         ZSTD_freeCDict(cdict);
5704         return NULL;
5705     }
5706 
5707     return cdict;
5708 }
5709 
ZSTD_createCDict(const void * dict,size_t dictSize,int compressionLevel)5710 ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
5711 {
5712     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5713     ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
5714                                                   ZSTD_dlm_byCopy, ZSTD_dct_auto,
5715                                                   cParams, ZSTD_defaultCMem);
5716     if (cdict)
5717         cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
5718     return cdict;
5719 }
5720 
ZSTD_createCDict_byReference(const void * dict,size_t dictSize,int compressionLevel)5721 ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
5722 {
5723     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict);
5724     ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dict, dictSize,
5725                                      ZSTD_dlm_byRef, ZSTD_dct_auto,
5726                                      cParams, ZSTD_defaultCMem);
5727     if (cdict)
5728         cdict->compressionLevel = (compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : compressionLevel;
5729     return cdict;
5730 }
5731 
ZSTD_freeCDict(ZSTD_CDict * cdict)5732 size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
5733 {
5734     if (cdict==NULL) return 0;   /* support free on NULL */
5735     {   ZSTD_customMem const cMem = cdict->customMem;
5736         int cdictInWorkspace = ZSTD_cwksp_owns_buffer(&cdict->workspace, cdict);
5737         ZSTD_cwksp_free(&cdict->workspace, cMem);
5738         if (!cdictInWorkspace) {
5739             ZSTD_customFree(cdict, cMem);
5740         }
5741         return 0;
5742     }
5743 }
5744 
5745 /*! ZSTD_initStaticCDict_advanced() :
5746  *  Generate a digested dictionary in provided memory area.
5747  *  workspace: The memory area to emplace the dictionary into.
5748  *             Provided pointer must 8-bytes aligned.
5749  *             It must outlive dictionary usage.
5750  *  workspaceSize: Use ZSTD_estimateCDictSize()
5751  *                 to determine how large workspace must be.
5752  *  cParams : use ZSTD_getCParams() to transform a compression level
5753  *            into its relevant cParams.
5754  * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
5755  *  Note : there is no corresponding "free" function.
5756  *         Since workspace was allocated externally, it must be freed externally.
5757  */
ZSTD_initStaticCDict(void * workspace,size_t workspaceSize,const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType,ZSTD_compressionParameters cParams)5758 const ZSTD_CDict* ZSTD_initStaticCDict(
5759                                  void* workspace, size_t workspaceSize,
5760                            const void* dict, size_t dictSize,
5761                                  ZSTD_dictLoadMethod_e dictLoadMethod,
5762                                  ZSTD_dictContentType_e dictContentType,
5763                                  ZSTD_compressionParameters cParams)
5764 {
5765     ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams);
5766     /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */
5767     size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0);
5768     size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict))
5769                             + (dictLoadMethod == ZSTD_dlm_byRef ? 0
5770                                : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*))))
5771                             + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE)
5772                             + matchStateSize;
5773     ZSTD_CDict* cdict;
5774     ZSTD_CCtx_params params;
5775 
5776     DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize);
5777     if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
5778 
5779     {
5780         ZSTD_cwksp ws;
5781         ZSTD_cwksp_init(&ws, workspace, workspaceSize, ZSTD_cwksp_static_alloc);
5782         cdict = (ZSTD_CDict*)ZSTD_cwksp_reserve_object(&ws, sizeof(ZSTD_CDict));
5783         if (cdict == NULL) return NULL;
5784         ZSTD_cwksp_move(&cdict->workspace, &ws);
5785     }
5786 
5787     if (workspaceSize < neededSize) return NULL;
5788 
5789     ZSTD_CCtxParams_init(&params, 0);
5790     params.cParams = cParams;
5791     params.useRowMatchFinder = useRowMatchFinder;
5792     cdict->useRowMatchFinder = useRowMatchFinder;
5793     cdict->compressionLevel = ZSTD_NO_CLEVEL;
5794 
5795     if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
5796                                               dict, dictSize,
5797                                               dictLoadMethod, dictContentType,
5798                                               params) ))
5799         return NULL;
5800 
5801     return cdict;
5802 }
5803 
ZSTD_getCParamsFromCDict(const ZSTD_CDict * cdict)5804 ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
5805 {
5806     assert(cdict != NULL);
5807     return cdict->matchState.cParams;
5808 }
5809 
5810 /*! ZSTD_getDictID_fromCDict() :
5811  *  Provides the dictID of the dictionary loaded into `cdict`.
5812  *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
5813  *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
ZSTD_getDictID_fromCDict(const ZSTD_CDict * cdict)5814 unsigned ZSTD_getDictID_fromCDict(const ZSTD_CDict* cdict)
5815 {
5816     if (cdict==NULL) return 0;
5817     return cdict->dictID;
5818 }
5819 
5820 /* ZSTD_compressBegin_usingCDict_internal() :
5821  * Implementation of various ZSTD_compressBegin_usingCDict* functions.
5822  */
ZSTD_compressBegin_usingCDict_internal(ZSTD_CCtx * const cctx,const ZSTD_CDict * const cdict,ZSTD_frameParameters const fParams,unsigned long long const pledgedSrcSize)5823 static size_t ZSTD_compressBegin_usingCDict_internal(
5824     ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5825     ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5826 {
5827     ZSTD_CCtx_params cctxParams;
5828     DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_internal");
5829     RETURN_ERROR_IF(cdict==NULL, dictionary_wrong, "NULL pointer!");
5830     /* Initialize the cctxParams from the cdict */
5831     {
5832         ZSTD_parameters params;
5833         params.fParams = fParams;
5834         params.cParams = ( pledgedSrcSize < ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF
5835                         || pledgedSrcSize < cdict->dictContentSize * ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
5836                         || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
5837                         || cdict->compressionLevel == 0 ) ?
5838                 ZSTD_getCParamsFromCDict(cdict)
5839               : ZSTD_getCParams(cdict->compressionLevel,
5840                                 pledgedSrcSize,
5841                                 cdict->dictContentSize);
5842         ZSTD_CCtxParams_init_internal(&cctxParams, &params, cdict->compressionLevel);
5843     }
5844     /* Increase window log to fit the entire dictionary and source if the
5845      * source size is known. Limit the increase to 19, which is the
5846      * window log for compression level 1 with the largest source size.
5847      */
5848     if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
5849         U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
5850         U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
5851         cctxParams.cParams.windowLog = MAX(cctxParams.cParams.windowLog, limitedSrcLog);
5852     }
5853     return ZSTD_compressBegin_internal(cctx,
5854                                         NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
5855                                         cdict,
5856                                         &cctxParams, pledgedSrcSize,
5857                                         ZSTDb_not_buffered);
5858 }
5859 
5860 
5861 /* ZSTD_compressBegin_usingCDict_advanced() :
5862  * This function is DEPRECATED.
5863  * 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)5864 size_t ZSTD_compressBegin_usingCDict_advanced(
5865     ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
5866     ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
5867 {
5868     return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, pledgedSrcSize);
5869 }
5870 
5871 /* ZSTD_compressBegin_usingCDict() :
5872  * cdict must be != NULL */
ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict)5873 size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
5874 {
5875     ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5876     return ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
5877 }
5878 
ZSTD_compressBegin_usingCDict(ZSTD_CCtx * cctx,const ZSTD_CDict * cdict)5879 size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
5880 {
5881     return ZSTD_compressBegin_usingCDict_deprecated(cctx, cdict);
5882 }
5883 
5884 /*! ZSTD_compress_usingCDict_internal():
5885  * Implementation of various ZSTD_compress_usingCDict* functions.
5886  */
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)5887 static size_t ZSTD_compress_usingCDict_internal(ZSTD_CCtx* cctx,
5888                                 void* dst, size_t dstCapacity,
5889                                 const void* src, size_t srcSize,
5890                                 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5891 {
5892     FORWARD_IF_ERROR(ZSTD_compressBegin_usingCDict_internal(cctx, cdict, fParams, srcSize), ""); /* will check if cdict != NULL */
5893     return ZSTD_compressEnd_public(cctx, dst, dstCapacity, src, srcSize);
5894 }
5895 
5896 /*! ZSTD_compress_usingCDict_advanced():
5897  * This function is DEPRECATED.
5898  */
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)5899 size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
5900                                 void* dst, size_t dstCapacity,
5901                                 const void* src, size_t srcSize,
5902                                 const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
5903 {
5904     return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5905 }
5906 
5907 /*! ZSTD_compress_usingCDict() :
5908  *  Compression using a digested Dictionary.
5909  *  Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
5910  *  Note that compression parameters are decided at CDict creation time
5911  *  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)5912 size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
5913                                 void* dst, size_t dstCapacity,
5914                                 const void* src, size_t srcSize,
5915                                 const ZSTD_CDict* cdict)
5916 {
5917     ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
5918     return ZSTD_compress_usingCDict_internal(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
5919 }
5920 
5921 
5922 
5923 /* ******************************************************************
5924 *  Streaming
5925 ********************************************************************/
5926 
ZSTD_createCStream(void)5927 ZSTD_CStream* ZSTD_createCStream(void)
5928 {
5929     DEBUGLOG(3, "ZSTD_createCStream");
5930     return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
5931 }
5932 
ZSTD_initStaticCStream(void * workspace,size_t workspaceSize)5933 ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
5934 {
5935     return ZSTD_initStaticCCtx(workspace, workspaceSize);
5936 }
5937 
ZSTD_createCStream_advanced(ZSTD_customMem customMem)5938 ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
5939 {   /* CStream and CCtx are now same object */
5940     return ZSTD_createCCtx_advanced(customMem);
5941 }
5942 
ZSTD_freeCStream(ZSTD_CStream * zcs)5943 size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
5944 {
5945     return ZSTD_freeCCtx(zcs);   /* same object */
5946 }
5947 
5948 
5949 
5950 /*======   Initialization   ======*/
5951 
ZSTD_CStreamInSize(void)5952 size_t ZSTD_CStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX; }
5953 
ZSTD_CStreamOutSize(void)5954 size_t ZSTD_CStreamOutSize(void)
5955 {
5956     return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
5957 }
5958 
ZSTD_getCParamMode(ZSTD_CDict const * cdict,ZSTD_CCtx_params const * params,U64 pledgedSrcSize)5959 static ZSTD_CParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
5960 {
5961     if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))
5962         return ZSTD_cpm_attachDict;
5963     else
5964         return ZSTD_cpm_noAttachDict;
5965 }
5966 
5967 /* ZSTD_resetCStream():
5968  * pledgedSrcSize == 0 means "unknown" */
ZSTD_resetCStream(ZSTD_CStream * zcs,unsigned long long pss)5969 size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pss)
5970 {
5971     /* temporary : 0 interpreted as "unknown" during transition period.
5972      * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
5973      * 0 will be interpreted as "empty" in the future.
5974      */
5975     U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
5976     DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
5977     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5978     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5979     return 0;
5980 }
5981 
5982 /*! ZSTD_initCStream_internal() :
5983  *  Note : for lib/compress only. Used by zstdmt_compress.c.
5984  *  Assumption 1 : params are valid
5985  *  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)5986 size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
5987                     const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
5988                     const ZSTD_CCtx_params* params,
5989                     unsigned long long pledgedSrcSize)
5990 {
5991     DEBUGLOG(4, "ZSTD_initCStream_internal");
5992     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
5993     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
5994     assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams)));
5995     zcs->requestedParams = *params;
5996     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
5997     if (dict) {
5998         FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
5999     } else {
6000         /* Dictionary is cleared if !cdict */
6001         FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
6002     }
6003     return 0;
6004 }
6005 
6006 /* ZSTD_initCStream_usingCDict_advanced() :
6007  * 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)6008 size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
6009                                             const ZSTD_CDict* cdict,
6010                                             ZSTD_frameParameters fParams,
6011                                             unsigned long long pledgedSrcSize)
6012 {
6013     DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
6014     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6015     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6016     zcs->requestedParams.fParams = fParams;
6017     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
6018     return 0;
6019 }
6020 
6021 /* note : cdict must outlive compression session */
ZSTD_initCStream_usingCDict(ZSTD_CStream * zcs,const ZSTD_CDict * cdict)6022 size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
6023 {
6024     DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
6025     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6026     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, cdict) , "");
6027     return 0;
6028 }
6029 
6030 
6031 /* ZSTD_initCStream_advanced() :
6032  * pledgedSrcSize must be exact.
6033  * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
6034  * 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)6035 size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
6036                                  const void* dict, size_t dictSize,
6037                                  ZSTD_parameters params, unsigned long long pss)
6038 {
6039     /* for compatibility with older programs relying on this behavior.
6040      * Users should now specify ZSTD_CONTENTSIZE_UNKNOWN.
6041      * This line will be removed in the future.
6042      */
6043     U64 const pledgedSrcSize = (pss==0 && params.fParams.contentSizeFlag==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
6044     DEBUGLOG(4, "ZSTD_initCStream_advanced");
6045     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6046     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6047     FORWARD_IF_ERROR( ZSTD_checkCParams(params.cParams) , "");
6048     ZSTD_CCtxParams_setZstdParams(&zcs->requestedParams, &params);
6049     FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
6050     return 0;
6051 }
6052 
ZSTD_initCStream_usingDict(ZSTD_CStream * zcs,const void * dict,size_t dictSize,int compressionLevel)6053 size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
6054 {
6055     DEBUGLOG(4, "ZSTD_initCStream_usingDict");
6056     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6057     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
6058     FORWARD_IF_ERROR( ZSTD_CCtx_loadDictionary(zcs, dict, dictSize) , "");
6059     return 0;
6060 }
6061 
ZSTD_initCStream_srcSize(ZSTD_CStream * zcs,int compressionLevel,unsigned long long pss)6062 size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
6063 {
6064     /* temporary : 0 interpreted as "unknown" during transition period.
6065      * Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN.
6066      * 0 will be interpreted as "empty" in the future.
6067      */
6068     U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss;
6069     DEBUGLOG(4, "ZSTD_initCStream_srcSize");
6070     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6071     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
6072     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
6073     FORWARD_IF_ERROR( ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize) , "");
6074     return 0;
6075 }
6076 
ZSTD_initCStream(ZSTD_CStream * zcs,int compressionLevel)6077 size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
6078 {
6079     DEBUGLOG(4, "ZSTD_initCStream");
6080     FORWARD_IF_ERROR( ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only) , "");
6081     FORWARD_IF_ERROR( ZSTD_CCtx_refCDict(zcs, NULL) , "");
6082     FORWARD_IF_ERROR( ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel) , "");
6083     return 0;
6084 }
6085 
6086 /*======   Compression   ======*/
6087 
ZSTD_nextInputSizeHint(const ZSTD_CCtx * cctx)6088 static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
6089 {
6090     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
6091         return cctx->blockSizeMax - cctx->stableIn_notConsumed;
6092     }
6093     assert(cctx->appliedParams.inBufferMode == ZSTD_bm_buffered);
6094     {   size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
6095         if (hintInSize==0) hintInSize = cctx->blockSizeMax;
6096         return hintInSize;
6097     }
6098 }
6099 
6100 /** ZSTD_compressStream_generic():
6101  *  internal function for all *compressStream*() variants
6102  * @return : hint size for next input to complete ongoing block */
ZSTD_compressStream_generic(ZSTD_CStream * zcs,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective const flushMode)6103 static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
6104                                           ZSTD_outBuffer* output,
6105                                           ZSTD_inBuffer* input,
6106                                           ZSTD_EndDirective const flushMode)
6107 {
6108     const char* const istart = (assert(input != NULL), (const char*)input->src);
6109     const char* const iend = (istart != NULL) ? istart + input->size : istart;
6110     const char* ip = (istart != NULL) ? istart + input->pos : istart;
6111     char* const ostart = (assert(output != NULL), (char*)output->dst);
6112     char* const oend = (ostart != NULL) ? ostart + output->size : ostart;
6113     char* op = (ostart != NULL) ? ostart + output->pos : ostart;
6114     U32 someMoreWork = 1;
6115 
6116     /* check expectations */
6117     DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%i, srcSize = %zu", (int)flushMode, input->size - input->pos);
6118     assert(zcs != NULL);
6119     if (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) {
6120         assert(input->pos >= zcs->stableIn_notConsumed);
6121         input->pos -= zcs->stableIn_notConsumed;
6122         if (ip) ip -= zcs->stableIn_notConsumed;
6123         zcs->stableIn_notConsumed = 0;
6124     }
6125     if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
6126         assert(zcs->inBuff != NULL);
6127         assert(zcs->inBuffSize > 0);
6128     }
6129     if (zcs->appliedParams.outBufferMode == ZSTD_bm_buffered) {
6130         assert(zcs->outBuff !=  NULL);
6131         assert(zcs->outBuffSize > 0);
6132     }
6133     if (input->src == NULL) assert(input->size == 0);
6134     assert(input->pos <= input->size);
6135     if (output->dst == NULL) assert(output->size == 0);
6136     assert(output->pos <= output->size);
6137     assert((U32)flushMode <= (U32)ZSTD_e_end);
6138 
6139     while (someMoreWork) {
6140         switch(zcs->streamStage)
6141         {
6142         case zcss_init:
6143             RETURN_ERROR(init_missing, "call ZSTD_initCStream() first!");
6144 
6145         case zcss_load:
6146             if ( (flushMode == ZSTD_e_end)
6147               && ( (size_t)(oend-op) >= ZSTD_compressBound((size_t)(iend-ip))     /* Enough output space */
6148                 || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)  /* OR we are allowed to return dstSizeTooSmall */
6149               && (zcs->inBuffPos == 0) ) {
6150                 /* shortcut to compression pass directly into output buffer */
6151                 size_t const cSize = ZSTD_compressEnd_public(zcs,
6152                                                 op, (size_t)(oend-op),
6153                                                 ip, (size_t)(iend-ip));
6154                 DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
6155                 FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed");
6156                 ip = iend;
6157                 op += cSize;
6158                 zcs->frameEnded = 1;
6159                 ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
6160                 someMoreWork = 0; break;
6161             }
6162             /* complete loading into inBuffer in buffered mode */
6163             if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) {
6164                 size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
6165                 size_t const loaded = ZSTD_limitCopy(
6166                                         zcs->inBuff + zcs->inBuffPos, toLoad,
6167                                         ip, (size_t)(iend-ip));
6168                 zcs->inBuffPos += loaded;
6169                 if (ip) ip += loaded;
6170                 if ( (flushMode == ZSTD_e_continue)
6171                   && (zcs->inBuffPos < zcs->inBuffTarget) ) {
6172                     /* not enough input to fill full block : stop here */
6173                     someMoreWork = 0; break;
6174                 }
6175                 if ( (flushMode == ZSTD_e_flush)
6176                   && (zcs->inBuffPos == zcs->inToCompress) ) {
6177                     /* empty */
6178                     someMoreWork = 0; break;
6179                 }
6180             } else {
6181                 assert(zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
6182                 if ( (flushMode == ZSTD_e_continue)
6183                   && ( (size_t)(iend - ip) < zcs->blockSizeMax) ) {
6184                     /* can't compress a full block : stop here */
6185                     zcs->stableIn_notConsumed = (size_t)(iend - ip);
6186                     ip = iend;  /* pretend to have consumed input */
6187                     someMoreWork = 0; break;
6188                 }
6189                 if ( (flushMode == ZSTD_e_flush)
6190                   && (ip == iend) ) {
6191                     /* empty */
6192                     someMoreWork = 0; break;
6193                 }
6194             }
6195             /* compress current block (note : this stage cannot be stopped in the middle) */
6196             DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
6197             {   int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered);
6198                 void* cDst;
6199                 size_t cSize;
6200                 size_t oSize = (size_t)(oend-op);
6201                 size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress
6202                                                    : MIN((size_t)(iend - ip), zcs->blockSizeMax);
6203                 if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable)
6204                     cDst = op;   /* compress into output buffer, to skip flush stage */
6205                 else
6206                     cDst = zcs->outBuff, oSize = zcs->outBuffSize;
6207                 if (inputBuffered) {
6208                     unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
6209                     cSize = lastBlock ?
6210                             ZSTD_compressEnd_public(zcs, cDst, oSize,
6211                                         zcs->inBuff + zcs->inToCompress, iSize) :
6212                             ZSTD_compressContinue_public(zcs, cDst, oSize,
6213                                         zcs->inBuff + zcs->inToCompress, iSize);
6214                     FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
6215                     zcs->frameEnded = lastBlock;
6216                     /* prepare next block */
6217                     zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSizeMax;
6218                     if (zcs->inBuffTarget > zcs->inBuffSize)
6219                         zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSizeMax;
6220                     DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
6221                             (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
6222                     if (!lastBlock)
6223                         assert(zcs->inBuffTarget <= zcs->inBuffSize);
6224                     zcs->inToCompress = zcs->inBuffPos;
6225                 } else { /* !inputBuffered, hence ZSTD_bm_stable */
6226                     unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip + iSize == iend);
6227                     cSize = lastBlock ?
6228                             ZSTD_compressEnd_public(zcs, cDst, oSize, ip, iSize) :
6229                             ZSTD_compressContinue_public(zcs, cDst, oSize, ip, iSize);
6230                     /* Consume the input prior to error checking to mirror buffered mode. */
6231                     if (ip) ip += iSize;
6232                     FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed");
6233                     zcs->frameEnded = lastBlock;
6234                     if (lastBlock) assert(ip == iend);
6235                 }
6236                 if (cDst == op) {  /* no need to flush */
6237                     op += cSize;
6238                     if (zcs->frameEnded) {
6239                         DEBUGLOG(5, "Frame completed directly in outBuffer");
6240                         someMoreWork = 0;
6241                         ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
6242                     }
6243                     break;
6244                 }
6245                 zcs->outBuffContentSize = cSize;
6246                 zcs->outBuffFlushedSize = 0;
6247                 zcs->streamStage = zcss_flush; /* pass-through to flush stage */
6248             }
6249 	    ZSTD_FALLTHROUGH;
6250         case zcss_flush:
6251             DEBUGLOG(5, "flush stage");
6252             assert(zcs->appliedParams.outBufferMode == ZSTD_bm_buffered);
6253             {   size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
6254                 size_t const flushed = ZSTD_limitCopy(op, (size_t)(oend-op),
6255                             zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
6256                 DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
6257                             (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
6258                 if (flushed)
6259                     op += flushed;
6260                 zcs->outBuffFlushedSize += flushed;
6261                 if (toFlush!=flushed) {
6262                     /* flush not fully completed, presumably because dst is too small */
6263                     assert(op==oend);
6264                     someMoreWork = 0;
6265                     break;
6266                 }
6267                 zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
6268                 if (zcs->frameEnded) {
6269                     DEBUGLOG(5, "Frame completed on flush");
6270                     someMoreWork = 0;
6271                     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
6272                     break;
6273                 }
6274                 zcs->streamStage = zcss_load;
6275                 break;
6276             }
6277 
6278         default: /* impossible */
6279             assert(0);
6280         }
6281     }
6282 
6283     input->pos = (size_t)(ip - istart);
6284     output->pos = (size_t)(op - ostart);
6285     if (zcs->frameEnded) return 0;
6286     return ZSTD_nextInputSizeHint(zcs);
6287 }
6288 
ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx * cctx)6289 static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
6290 {
6291 #ifdef ZSTD_MULTITHREAD
6292     if (cctx->appliedParams.nbWorkers >= 1) {
6293         assert(cctx->mtctx != NULL);
6294         return ZSTDMT_nextInputSizeHint(cctx->mtctx);
6295     }
6296 #endif
6297     return ZSTD_nextInputSizeHint(cctx);
6298 
6299 }
6300 
ZSTD_compressStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output,ZSTD_inBuffer * input)6301 size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
6302 {
6303     FORWARD_IF_ERROR( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) , "");
6304     return ZSTD_nextInputSizeHint_MTorST(zcs);
6305 }
6306 
6307 /* After a compression call set the expected input/output buffer.
6308  * This is validated at the start of the next compression call.
6309  */
6310 static void
ZSTD_setBufferExpectations(ZSTD_CCtx * cctx,const ZSTD_outBuffer * output,const ZSTD_inBuffer * input)6311 ZSTD_setBufferExpectations(ZSTD_CCtx* cctx, const ZSTD_outBuffer* output, const ZSTD_inBuffer* input)
6312 {
6313     DEBUGLOG(5, "ZSTD_setBufferExpectations (for advanced stable in/out modes)");
6314     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
6315         cctx->expectedInBuffer = *input;
6316     }
6317     if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
6318         cctx->expectedOutBufferSize = output->size - output->pos;
6319     }
6320 }
6321 
6322 /* Validate that the input/output buffers match the expectations set by
6323  * ZSTD_setBufferExpectations.
6324  */
ZSTD_checkBufferStability(ZSTD_CCtx const * cctx,ZSTD_outBuffer const * output,ZSTD_inBuffer const * input,ZSTD_EndDirective endOp)6325 static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
6326                                         ZSTD_outBuffer const* output,
6327                                         ZSTD_inBuffer const* input,
6328                                         ZSTD_EndDirective endOp)
6329 {
6330     if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) {
6331         ZSTD_inBuffer const expect = cctx->expectedInBuffer;
6332         if (expect.src != input->src || expect.pos != input->pos)
6333             RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableInBuffer enabled but input differs!");
6334     }
6335     (void)endOp;
6336     if (cctx->appliedParams.outBufferMode == ZSTD_bm_stable) {
6337         size_t const outBufferSize = output->size - output->pos;
6338         if (cctx->expectedOutBufferSize != outBufferSize)
6339             RETURN_ERROR(stabilityCondition_notRespected, "ZSTD_c_stableOutBuffer enabled but output size differs!");
6340     }
6341     return 0;
6342 }
6343 
6344 /*
6345  * If @endOp == ZSTD_e_end, @inSize becomes pledgedSrcSize.
6346  * Otherwise, it's ignored.
6347  * @return: 0 on success, or a ZSTD_error code otherwise.
6348  */
ZSTD_CCtx_init_compressStream2(ZSTD_CCtx * cctx,ZSTD_EndDirective endOp,size_t inSize)6349 static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
6350                                              ZSTD_EndDirective endOp,
6351                                              size_t inSize)
6352 {
6353     ZSTD_CCtx_params params = cctx->requestedParams;
6354     ZSTD_prefixDict const prefixDict = cctx->prefixDict;
6355     FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */
6356     ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict));   /* single usage */
6357     assert(prefixDict.dict==NULL || cctx->cdict==NULL);    /* only one can be set */
6358     if (cctx->cdict && !cctx->localDict.cdict) {
6359         /* Let the cdict's compression level take priority over the requested params.
6360          * But do not take the cdict's compression level if the "cdict" is actually a localDict
6361          * generated from ZSTD_initLocalDict().
6362          */
6363         params.compressionLevel = cctx->cdict->compressionLevel;
6364     }
6365     DEBUGLOG(4, "ZSTD_CCtx_init_compressStream2 : transparent init stage");
6366     if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1;  /* auto-determine pledgedSrcSize */
6367 
6368     {   size_t const dictSize = prefixDict.dict
6369                 ? prefixDict.dictSize
6370                 : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
6371         ZSTD_CParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, &params, cctx->pledgedSrcSizePlusOne - 1);
6372         params.cParams = ZSTD_getCParamsFromCCtxParams(
6373                 &params, cctx->pledgedSrcSizePlusOne-1,
6374                 dictSize, mode);
6375     }
6376 
6377     params.postBlockSplitter = ZSTD_resolveBlockSplitterMode(params.postBlockSplitter, &params.cParams);
6378     params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, &params.cParams);
6379     params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, &params.cParams);
6380     params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences);
6381     params.maxBlockSize = ZSTD_resolveMaxBlockSize(params.maxBlockSize);
6382     params.searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(params.searchForExternalRepcodes, params.compressionLevel);
6383 
6384 #ifdef ZSTD_MULTITHREAD
6385     /* If external matchfinder is enabled, make sure to fail before checking job size (for consistency) */
6386     RETURN_ERROR_IF(
6387         ZSTD_hasExtSeqProd(&params) && params.nbWorkers >= 1,
6388         parameter_combination_unsupported,
6389         "External sequence producer isn't supported with nbWorkers >= 1"
6390     );
6391 
6392     if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
6393         params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
6394     }
6395     if (params.nbWorkers > 0) {
6396 # if ZSTD_TRACE
6397         cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0;
6398 # endif
6399         /* mt context creation */
6400         if (cctx->mtctx == NULL) {
6401             DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
6402                         params.nbWorkers);
6403             cctx->mtctx = ZSTDMT_createCCtx_advanced((U32)params.nbWorkers, cctx->customMem, cctx->pool);
6404             RETURN_ERROR_IF(cctx->mtctx == NULL, memory_allocation, "NULL pointer!");
6405         }
6406         /* mt compression */
6407         DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
6408         FORWARD_IF_ERROR( ZSTDMT_initCStream_internal(
6409                     cctx->mtctx,
6410                     prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
6411                     cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , "");
6412         cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0;
6413         cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize;
6414         cctx->consumedSrcSize = 0;
6415         cctx->producedCSize = 0;
6416         cctx->streamStage = zcss_load;
6417         cctx->appliedParams = params;
6418     } else
6419 #endif  /* ZSTD_MULTITHREAD */
6420     {   U64 const pledgedSrcSize = cctx->pledgedSrcSizePlusOne - 1;
6421         assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
6422         FORWARD_IF_ERROR( ZSTD_compressBegin_internal(cctx,
6423                 prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, ZSTD_dtlm_fast,
6424                 cctx->cdict,
6425                 &params, pledgedSrcSize,
6426                 ZSTDb_buffered) , "");
6427         assert(cctx->appliedParams.nbWorkers == 0);
6428         cctx->inToCompress = 0;
6429         cctx->inBuffPos = 0;
6430         if (cctx->appliedParams.inBufferMode == ZSTD_bm_buffered) {
6431             /* for small input: avoid automatic flush on reaching end of block, since
6432             * it would require to add a 3-bytes null block to end frame
6433             */
6434             cctx->inBuffTarget = cctx->blockSizeMax + (cctx->blockSizeMax == pledgedSrcSize);
6435         } else {
6436             cctx->inBuffTarget = 0;
6437         }
6438         cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
6439         cctx->streamStage = zcss_load;
6440         cctx->frameEnded = 0;
6441     }
6442     return 0;
6443 }
6444 
6445 /* @return provides a minimum amount of data remaining to be flushed from internal buffers
6446  */
ZSTD_compressStream2(ZSTD_CCtx * cctx,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective endOp)6447 size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
6448                              ZSTD_outBuffer* output,
6449                              ZSTD_inBuffer* input,
6450                              ZSTD_EndDirective endOp)
6451 {
6452     DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
6453     /* check conditions */
6454     RETURN_ERROR_IF(output->pos > output->size, dstSize_tooSmall, "invalid output buffer");
6455     RETURN_ERROR_IF(input->pos  > input->size, srcSize_wrong, "invalid input buffer");
6456     RETURN_ERROR_IF((U32)endOp > (U32)ZSTD_e_end, parameter_outOfBound, "invalid endDirective");
6457     assert(cctx != NULL);
6458 
6459     /* transparent initialization stage */
6460     if (cctx->streamStage == zcss_init) {
6461         size_t const inputSize = input->size - input->pos;  /* no obligation to start from pos==0 */
6462         size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed;
6463         if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */
6464           && (endOp == ZSTD_e_continue)                             /* no flush requested, more input to come */
6465           && (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) {              /* not even reached one block yet */
6466             if (cctx->stableIn_notConsumed) {  /* not the first time */
6467                 /* check stable source guarantees */
6468                 RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer");
6469                 RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos");
6470             }
6471             /* pretend input was consumed, to give a sense forward progress */
6472             input->pos = input->size;
6473             /* save stable inBuffer, for later control, and flush/end */
6474             cctx->expectedInBuffer = *input;
6475             /* but actually input wasn't consumed, so keep track of position from where compression shall resume */
6476             cctx->stableIn_notConsumed += inputSize;
6477             /* don't initialize yet, wait for the first block of flush() order, for better parameters adaptation */
6478             return ZSTD_FRAMEHEADERSIZE_MIN(cctx->requestedParams.format);  /* at least some header to produce */
6479         }
6480         FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, endOp, totalInputSize), "compressStream2 initialization failed");
6481         ZSTD_setBufferExpectations(cctx, output, input);   /* Set initial buffer expectations now that we've initialized */
6482     }
6483     /* end of transparent initialization stage */
6484 
6485     FORWARD_IF_ERROR(ZSTD_checkBufferStability(cctx, output, input, endOp), "invalid buffers");
6486     /* compression stage */
6487 #ifdef ZSTD_MULTITHREAD
6488     if (cctx->appliedParams.nbWorkers > 0) {
6489         size_t flushMin;
6490         if (cctx->cParamsChanged) {
6491             ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
6492             cctx->cParamsChanged = 0;
6493         }
6494         if (cctx->stableIn_notConsumed) {
6495             assert(cctx->appliedParams.inBufferMode == ZSTD_bm_stable);
6496             /* some early data was skipped - make it available for consumption */
6497             assert(input->pos >= cctx->stableIn_notConsumed);
6498             input->pos -= cctx->stableIn_notConsumed;
6499             cctx->stableIn_notConsumed = 0;
6500         }
6501         for (;;) {
6502             size_t const ipos = input->pos;
6503             size_t const opos = output->pos;
6504             flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
6505             cctx->consumedSrcSize += (U64)(input->pos - ipos);
6506             cctx->producedCSize += (U64)(output->pos - opos);
6507             if ( ZSTD_isError(flushMin)
6508               || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
6509                 if (flushMin == 0)
6510                     ZSTD_CCtx_trace(cctx, 0);
6511                 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
6512             }
6513             FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed");
6514 
6515             if (endOp == ZSTD_e_continue) {
6516                 /* We only require some progress with ZSTD_e_continue, not maximal progress.
6517                  * We're done if we've consumed or produced any bytes, or either buffer is
6518                  * full.
6519                  */
6520                 if (input->pos != ipos || output->pos != opos || input->pos == input->size || output->pos == output->size)
6521                     break;
6522             } else {
6523                 assert(endOp == ZSTD_e_flush || endOp == ZSTD_e_end);
6524                 /* We require maximal progress. We're done when the flush is complete or the
6525                  * output buffer is full.
6526                  */
6527                 if (flushMin == 0 || output->pos == output->size)
6528                     break;
6529             }
6530         }
6531         DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
6532         /* Either we don't require maximum forward progress, we've finished the
6533          * flush, or we are out of output space.
6534          */
6535         assert(endOp == ZSTD_e_continue || flushMin == 0 || output->pos == output->size);
6536         ZSTD_setBufferExpectations(cctx, output, input);
6537         return flushMin;
6538     }
6539 #endif /* ZSTD_MULTITHREAD */
6540     FORWARD_IF_ERROR( ZSTD_compressStream_generic(cctx, output, input, endOp) , "");
6541     DEBUGLOG(5, "completed ZSTD_compressStream2");
6542     ZSTD_setBufferExpectations(cctx, output, input);
6543     return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
6544 }
6545 
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)6546 size_t ZSTD_compressStream2_simpleArgs (
6547                             ZSTD_CCtx* cctx,
6548                             void* dst, size_t dstCapacity, size_t* dstPos,
6549                       const void* src, size_t srcSize, size_t* srcPos,
6550                             ZSTD_EndDirective endOp)
6551 {
6552     ZSTD_outBuffer output;
6553     ZSTD_inBuffer  input;
6554     output.dst = dst;
6555     output.size = dstCapacity;
6556     output.pos = *dstPos;
6557     input.src = src;
6558     input.size = srcSize;
6559     input.pos = *srcPos;
6560     /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
6561     {   size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
6562         *dstPos = output.pos;
6563         *srcPos = input.pos;
6564         return cErr;
6565     }
6566 }
6567 
ZSTD_compress2(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)6568 size_t ZSTD_compress2(ZSTD_CCtx* cctx,
6569                       void* dst, size_t dstCapacity,
6570                       const void* src, size_t srcSize)
6571 {
6572     ZSTD_bufferMode_e const originalInBufferMode = cctx->requestedParams.inBufferMode;
6573     ZSTD_bufferMode_e const originalOutBufferMode = cctx->requestedParams.outBufferMode;
6574     DEBUGLOG(4, "ZSTD_compress2 (srcSize=%u)", (unsigned)srcSize);
6575     ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
6576     /* Enable stable input/output buffers. */
6577     cctx->requestedParams.inBufferMode = ZSTD_bm_stable;
6578     cctx->requestedParams.outBufferMode = ZSTD_bm_stable;
6579     {   size_t oPos = 0;
6580         size_t iPos = 0;
6581         size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
6582                                         dst, dstCapacity, &oPos,
6583                                         src, srcSize, &iPos,
6584                                         ZSTD_e_end);
6585         /* Reset to the original values. */
6586         cctx->requestedParams.inBufferMode = originalInBufferMode;
6587         cctx->requestedParams.outBufferMode = originalOutBufferMode;
6588 
6589         FORWARD_IF_ERROR(result, "ZSTD_compressStream2_simpleArgs failed");
6590         if (result != 0) {  /* compression not completed, due to lack of output space */
6591             assert(oPos == dstCapacity);
6592             RETURN_ERROR(dstSize_tooSmall, "");
6593         }
6594         assert(iPos == srcSize);   /* all input is expected consumed */
6595         return oPos;
6596     }
6597 }
6598 
6599 /* ZSTD_validateSequence() :
6600  * @offBase : must use the format required by ZSTD_storeSeq()
6601  * @returns a ZSTD error code if sequence is not valid
6602  */
6603 static size_t
ZSTD_validateSequence(U32 offBase,U32 matchLength,U32 minMatch,size_t posInSrc,U32 windowLog,size_t dictSize,int useSequenceProducer)6604 ZSTD_validateSequence(U32 offBase, U32 matchLength, U32 minMatch,
6605                       size_t posInSrc, U32 windowLog, size_t dictSize, int useSequenceProducer)
6606 {
6607     U32 const windowSize = 1u << windowLog;
6608     /* posInSrc represents the amount of data the decoder would decode up to this point.
6609      * As long as the amount of data decoded is less than or equal to window size, offsets may be
6610      * larger than the total length of output decoded in order to reference the dict, even larger than
6611      * window size. After output surpasses windowSize, we're limited to windowSize offsets again.
6612      */
6613     size_t const offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize;
6614     size_t const matchLenLowerBound = (minMatch == 3 || useSequenceProducer) ? 3 : 4;
6615     RETURN_ERROR_IF(offBase > OFFSET_TO_OFFBASE(offsetBound), externalSequences_invalid, "Offset too large!");
6616     /* Validate maxNbSeq is large enough for the given matchLength and minMatch */
6617     RETURN_ERROR_IF(matchLength < matchLenLowerBound, externalSequences_invalid, "Matchlength too small for the minMatch");
6618     return 0;
6619 }
6620 
6621 /* Returns an offset code, given a sequence's raw offset, the ongoing repcode array, and whether litLength == 0 */
ZSTD_finalizeOffBase(U32 rawOffset,const U32 rep[ZSTD_REP_NUM],U32 ll0)6622 static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 ll0)
6623 {
6624     U32 offBase = OFFSET_TO_OFFBASE(rawOffset);
6625 
6626     if (!ll0 && rawOffset == rep[0]) {
6627         offBase = REPCODE1_TO_OFFBASE;
6628     } else if (rawOffset == rep[1]) {
6629         offBase = REPCODE_TO_OFFBASE(2 - ll0);
6630     } else if (rawOffset == rep[2]) {
6631         offBase = REPCODE_TO_OFFBASE(3 - ll0);
6632     } else if (ll0 && rawOffset == rep[0] - 1) {
6633         offBase = REPCODE3_TO_OFFBASE;
6634     }
6635     return offBase;
6636 }
6637 
6638 /* This function scans through an array of ZSTD_Sequence,
6639  * storing the sequences it reads, until it reaches a block delimiter.
6640  * Note that the block delimiter includes the last literals of the block.
6641  * @blockSize must be == sum(sequence_lengths).
6642  * @returns @blockSize on success, and a ZSTD_error otherwise.
6643  */
6644 static size_t
ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx * cctx,ZSTD_SequencePosition * seqPos,const ZSTD_Sequence * const inSeqs,size_t inSeqsSize,const void * src,size_t blockSize,ZSTD_ParamSwitch_e externalRepSearch)6645 ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
6646                                    ZSTD_SequencePosition* seqPos,
6647                              const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
6648                              const void* src, size_t blockSize,
6649                                    ZSTD_ParamSwitch_e externalRepSearch)
6650 {
6651     U32 idx = seqPos->idx;
6652     U32 const startIdx = idx;
6653     BYTE const* ip = (BYTE const*)(src);
6654     const BYTE* const iend = ip + blockSize;
6655     Repcodes_t updatedRepcodes;
6656     U32 dictSize;
6657 
6658     DEBUGLOG(5, "ZSTD_transferSequences_wBlockDelim (blockSize = %zu)", blockSize);
6659 
6660     if (cctx->cdict) {
6661         dictSize = (U32)cctx->cdict->dictContentSize;
6662     } else if (cctx->prefixDict.dict) {
6663         dictSize = (U32)cctx->prefixDict.dictSize;
6664     } else {
6665         dictSize = 0;
6666     }
6667     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
6668     for (; idx < inSeqsSize && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) {
6669         U32 const litLength = inSeqs[idx].litLength;
6670         U32 const matchLength = inSeqs[idx].matchLength;
6671         U32 offBase;
6672 
6673         if (externalRepSearch == ZSTD_ps_disable) {
6674             offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset);
6675         } else {
6676             U32 const ll0 = (litLength == 0);
6677             offBase = ZSTD_finalizeOffBase(inSeqs[idx].offset, updatedRepcodes.rep, ll0);
6678             ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
6679         }
6680 
6681         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
6682         if (cctx->appliedParams.validateSequences) {
6683             seqPos->posInSrc += litLength + matchLength;
6684             FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch,
6685                                                 seqPos->posInSrc,
6686                                                 cctx->appliedParams.cParams.windowLog, dictSize,
6687                                                 ZSTD_hasExtSeqProd(&cctx->appliedParams)),
6688                                                 "Sequence validation failed");
6689         }
6690         RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
6691                         "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
6692         ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);
6693         ip += matchLength + litLength;
6694     }
6695     RETURN_ERROR_IF(idx == inSeqsSize, externalSequences_invalid, "Block delimiter not found.");
6696 
6697     /* If we skipped repcode search while parsing, we need to update repcodes now */
6698     assert(externalRepSearch != ZSTD_ps_auto);
6699     assert(idx >= startIdx);
6700     if (externalRepSearch == ZSTD_ps_disable && idx != startIdx) {
6701         U32* const rep = updatedRepcodes.rep;
6702         U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */
6703 
6704         if (lastSeqIdx >= startIdx + 2) {
6705             rep[2] = inSeqs[lastSeqIdx - 2].offset;
6706             rep[1] = inSeqs[lastSeqIdx - 1].offset;
6707             rep[0] = inSeqs[lastSeqIdx].offset;
6708         } else if (lastSeqIdx == startIdx + 1) {
6709             rep[2] = rep[0];
6710             rep[1] = inSeqs[lastSeqIdx - 1].offset;
6711             rep[0] = inSeqs[lastSeqIdx].offset;
6712         } else {
6713             assert(lastSeqIdx == startIdx);
6714             rep[2] = rep[1];
6715             rep[1] = rep[0];
6716             rep[0] = inSeqs[lastSeqIdx].offset;
6717         }
6718     }
6719 
6720     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
6721 
6722     if (inSeqs[idx].litLength) {
6723         DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength);
6724         ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength);
6725         ip += inSeqs[idx].litLength;
6726         seqPos->posInSrc += inSeqs[idx].litLength;
6727     }
6728     RETURN_ERROR_IF(ip != iend, externalSequences_invalid, "Blocksize doesn't agree with block delimiter!");
6729     seqPos->idx = idx+1;
6730     return blockSize;
6731 }
6732 
6733 /*
6734  * This function attempts to scan through @blockSize bytes in @src
6735  * represented by the sequences in @inSeqs,
6736  * storing any (partial) sequences.
6737  *
6738  * Occasionally, we may want to reduce the actual number of bytes consumed from @src
6739  * to avoid splitting a match, notably if it would produce a match smaller than MINMATCH.
6740  *
6741  * @returns the number of bytes consumed from @src, necessarily <= @blockSize.
6742  * Otherwise, it may return a ZSTD error if something went wrong.
6743  */
6744 static size_t
ZSTD_transferSequences_noDelim(ZSTD_CCtx * cctx,ZSTD_SequencePosition * seqPos,const ZSTD_Sequence * const inSeqs,size_t inSeqsSize,const void * src,size_t blockSize,ZSTD_ParamSwitch_e externalRepSearch)6745 ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
6746                                ZSTD_SequencePosition* seqPos,
6747                          const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
6748                          const void* src, size_t blockSize,
6749                                ZSTD_ParamSwitch_e externalRepSearch)
6750 {
6751     U32 idx = seqPos->idx;
6752     U32 startPosInSequence = seqPos->posInSequence;
6753     U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
6754     size_t dictSize;
6755     const BYTE* const istart = (const BYTE*)(src);
6756     const BYTE* ip = istart;
6757     const BYTE* iend = istart + blockSize;  /* May be adjusted if we decide to process fewer than blockSize bytes */
6758     Repcodes_t updatedRepcodes;
6759     U32 bytesAdjustment = 0;
6760     U32 finalMatchSplit = 0;
6761 
6762     /* TODO(embg) support fast parsing mode in noBlockDelim mode */
6763     (void)externalRepSearch;
6764 
6765     if (cctx->cdict) {
6766         dictSize = cctx->cdict->dictContentSize;
6767     } else if (cctx->prefixDict.dict) {
6768         dictSize = cctx->prefixDict.dictSize;
6769     } else {
6770         dictSize = 0;
6771     }
6772     DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize);
6773     DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
6774     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
6775     while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) {
6776         const ZSTD_Sequence currSeq = inSeqs[idx];
6777         U32 litLength = currSeq.litLength;
6778         U32 matchLength = currSeq.matchLength;
6779         U32 const rawOffset = currSeq.offset;
6780         U32 offBase;
6781 
6782         /* Modify the sequence depending on where endPosInSequence lies */
6783         if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) {
6784             if (startPosInSequence >= litLength) {
6785                 startPosInSequence -= litLength;
6786                 litLength = 0;
6787                 matchLength -= startPosInSequence;
6788             } else {
6789                 litLength -= startPosInSequence;
6790             }
6791             /* Move to the next sequence */
6792             endPosInSequence -= currSeq.litLength + currSeq.matchLength;
6793             startPosInSequence = 0;
6794         } else {
6795             /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence
6796                does not reach the end of the match. So, we have to split the sequence */
6797             DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u",
6798                      currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence);
6799             if (endPosInSequence > litLength) {
6800                 U32 firstHalfMatchLength;
6801                 litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence;
6802                 firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength;
6803                 if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) {
6804                     /* Only ever split the match if it is larger than the block size */
6805                     U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence;
6806                     if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) {
6807                         /* Move the endPosInSequence backward so that it creates match of minMatch length */
6808                         endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
6809                         bytesAdjustment = cctx->appliedParams.cParams.minMatch - secondHalfMatchLength;
6810                         firstHalfMatchLength -= bytesAdjustment;
6811                     }
6812                     matchLength = firstHalfMatchLength;
6813                     /* Flag that we split the last match - after storing the sequence, exit the loop,
6814                        but keep the value of endPosInSequence */
6815                     finalMatchSplit = 1;
6816                 } else {
6817                     /* Move the position in sequence backwards so that we don't split match, and break to store
6818                      * the last literals. We use the original currSeq.litLength as a marker for where endPosInSequence
6819                      * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so
6820                      * would cause the first half of the match to be too small
6821                      */
6822                     bytesAdjustment = endPosInSequence - currSeq.litLength;
6823                     endPosInSequence = currSeq.litLength;
6824                     break;
6825                 }
6826             } else {
6827                 /* This sequence ends inside the literals, break to store the last literals */
6828                 break;
6829             }
6830         }
6831         /* Check if this offset can be represented with a repcode */
6832         {   U32 const ll0 = (litLength == 0);
6833             offBase = ZSTD_finalizeOffBase(rawOffset, updatedRepcodes.rep, ll0);
6834             ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
6835         }
6836 
6837         if (cctx->appliedParams.validateSequences) {
6838             seqPos->posInSrc += litLength + matchLength;
6839             FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,
6840                                                    cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),
6841                                                    "Sequence validation failed");
6842         }
6843         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
6844         RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
6845                         "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
6846         ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength);
6847         ip += matchLength + litLength;
6848         if (!finalMatchSplit)
6849             idx++; /* Next Sequence */
6850     }
6851     DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength);
6852     assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength);
6853     seqPos->idx = idx;
6854     seqPos->posInSequence = endPosInSequence;
6855     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
6856 
6857     iend -= bytesAdjustment;
6858     if (ip != iend) {
6859         /* Store any last literals */
6860         U32 const lastLLSize = (U32)(iend - ip);
6861         assert(ip <= iend);
6862         DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);
6863         ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);
6864         seqPos->posInSrc += lastLLSize;
6865     }
6866 
6867     return (size_t)(iend-istart);
6868 }
6869 
6870 /* @seqPos represents a position within @inSeqs,
6871  * it is read and updated by this function,
6872  * once the goal to produce a block of size @blockSize is reached.
6873  * @return: nb of bytes consumed from @src, necessarily <= @blockSize.
6874  */
6875 typedef size_t (*ZSTD_SequenceCopier_f)(ZSTD_CCtx* cctx,
6876                                         ZSTD_SequencePosition* seqPos,
6877                                   const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
6878                                   const void* src, size_t blockSize,
6879                                         ZSTD_ParamSwitch_e externalRepSearch);
6880 
ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode)6881 static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode)
6882 {
6883     assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode));
6884     if (mode == ZSTD_sf_explicitBlockDelimiters) {
6885         return ZSTD_transferSequences_wBlockDelim;
6886     }
6887     assert(mode == ZSTD_sf_noBlockDelimiters);
6888     return ZSTD_transferSequences_noDelim;
6889 }
6890 
6891 /* Discover the size of next block by searching for the delimiter.
6892  * Note that a block delimiter **must** exist in this mode,
6893  * otherwise it's an input error.
6894  * The block size retrieved will be later compared to ensure it remains within bounds */
6895 static size_t
blockSize_explicitDelimiter(const ZSTD_Sequence * inSeqs,size_t inSeqsSize,ZSTD_SequencePosition seqPos)6896 blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos)
6897 {
6898     int end = 0;
6899     size_t blockSize = 0;
6900     size_t spos = seqPos.idx;
6901     DEBUGLOG(6, "blockSize_explicitDelimiter : seq %zu / %zu", spos, inSeqsSize);
6902     assert(spos <= inSeqsSize);
6903     while (spos < inSeqsSize) {
6904         end = (inSeqs[spos].offset == 0);
6905         blockSize += inSeqs[spos].litLength + inSeqs[spos].matchLength;
6906         if (end) {
6907             if (inSeqs[spos].matchLength != 0)
6908                 RETURN_ERROR(externalSequences_invalid, "delimiter format error : both matchlength and offset must be == 0");
6909             break;
6910         }
6911         spos++;
6912     }
6913     if (!end)
6914         RETURN_ERROR(externalSequences_invalid, "Reached end of sequences without finding a block delimiter");
6915     return blockSize;
6916 }
6917 
determine_blockSize(ZSTD_SequenceFormat_e mode,size_t blockSize,size_t remaining,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,ZSTD_SequencePosition seqPos)6918 static size_t determine_blockSize(ZSTD_SequenceFormat_e mode,
6919                            size_t blockSize, size_t remaining,
6920                      const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
6921                            ZSTD_SequencePosition seqPos)
6922 {
6923     DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining);
6924     if (mode == ZSTD_sf_noBlockDelimiters) {
6925         /* Note: more a "target" block size */
6926         return MIN(remaining, blockSize);
6927     }
6928     assert(mode == ZSTD_sf_explicitBlockDelimiters);
6929     {   size_t const explicitBlockSize = blockSize_explicitDelimiter(inSeqs, inSeqsSize, seqPos);
6930         FORWARD_IF_ERROR(explicitBlockSize, "Error while determining block size with explicit delimiters");
6931         if (explicitBlockSize > blockSize)
6932             RETURN_ERROR(externalSequences_invalid, "sequences incorrectly define a too large block");
6933         if (explicitBlockSize > remaining)
6934             RETURN_ERROR(externalSequences_invalid, "sequences define a frame longer than source");
6935         return explicitBlockSize;
6936     }
6937 }
6938 
6939 /* Compress all provided sequences, block-by-block.
6940  *
6941  * Returns the cumulative size of all compressed blocks (including their headers),
6942  * otherwise a ZSTD error.
6943  */
6944 static size_t
ZSTD_compressSequences_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * src,size_t srcSize)6945 ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
6946                                 void* dst, size_t dstCapacity,
6947                           const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
6948                           const void* src, size_t srcSize)
6949 {
6950     size_t cSize = 0;
6951     size_t remaining = srcSize;
6952     ZSTD_SequencePosition seqPos = {0, 0, 0};
6953 
6954     const BYTE* ip = (BYTE const*)src;
6955     BYTE* op = (BYTE*)dst;
6956     ZSTD_SequenceCopier_f const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
6957 
6958     DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize);
6959     /* Special case: empty frame */
6960     if (remaining == 0) {
6961         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
6962         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header");
6963         MEM_writeLE32(op, cBlockHeader24);
6964         op += ZSTD_blockHeaderSize;
6965         dstCapacity -= ZSTD_blockHeaderSize;
6966         cSize += ZSTD_blockHeaderSize;
6967     }
6968 
6969     while (remaining) {
6970         size_t compressedSeqsSize;
6971         size_t cBlockSize;
6972         size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters,
6973                                         cctx->blockSizeMax, remaining,
6974                                         inSeqs, inSeqsSize, seqPos);
6975         U32 const lastBlock = (blockSize == remaining);
6976         FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size");
6977         assert(blockSize <= remaining);
6978         ZSTD_resetSeqStore(&cctx->seqStore);
6979 
6980         blockSize = sequenceCopier(cctx,
6981                                    &seqPos, inSeqs, inSeqsSize,
6982                                    ip, blockSize,
6983                                    cctx->appliedParams.searchForExternalRepcodes);
6984         FORWARD_IF_ERROR(blockSize, "Bad sequence copy");
6985 
6986         /* If blocks are too small, emit as a nocompress block */
6987         /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
6988          * additional 1. We need to revisit and change this logic to be more consistent */
6989         if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) {
6990             cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
6991             FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed");
6992             DEBUGLOG(5, "Block too small (%zu): data remains uncompressed: cSize=%zu", blockSize, cBlockSize);
6993             cSize += cBlockSize;
6994             ip += blockSize;
6995             op += cBlockSize;
6996             remaining -= blockSize;
6997             dstCapacity -= cBlockSize;
6998             continue;
6999         }
7000 
7001         RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
7002         compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore,
7003                                 &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
7004                                 &cctx->appliedParams,
7005                                 op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
7006                                 blockSize,
7007                                 cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
7008                                 cctx->bmi2);
7009         FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
7010         DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
7011 
7012         if (!cctx->isFirstBlock &&
7013             ZSTD_maybeRLE(&cctx->seqStore) &&
7014             ZSTD_isRLE(ip, blockSize)) {
7015             /* Note: don't emit the first block as RLE even if it qualifies because
7016              * doing so will cause the decoder (cli <= v1.4.3 only) to throw an (invalid) error
7017              * "should consume all input error."
7018              */
7019             compressedSeqsSize = 1;
7020         }
7021 
7022         if (compressedSeqsSize == 0) {
7023             /* ZSTD_noCompressBlock writes the block header as well */
7024             cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
7025             FORWARD_IF_ERROR(cBlockSize, "ZSTD_noCompressBlock failed");
7026             DEBUGLOG(5, "Writing out nocompress block, size: %zu", cBlockSize);
7027         } else if (compressedSeqsSize == 1) {
7028             cBlockSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, blockSize, lastBlock);
7029             FORWARD_IF_ERROR(cBlockSize, "ZSTD_rleCompressBlock failed");
7030             DEBUGLOG(5, "Writing out RLE block, size: %zu", cBlockSize);
7031         } else {
7032             U32 cBlockHeader;
7033             /* Error checking and repcodes update */
7034             ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
7035             if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
7036                 cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
7037 
7038             /* Write block header into beginning of block*/
7039             cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
7040             MEM_writeLE24(op, cBlockHeader);
7041             cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
7042             DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
7043         }
7044 
7045         cSize += cBlockSize;
7046 
7047         if (lastBlock) {
7048             break;
7049         } else {
7050             ip += blockSize;
7051             op += cBlockSize;
7052             remaining -= blockSize;
7053             dstCapacity -= cBlockSize;
7054             cctx->isFirstBlock = 0;
7055         }
7056         DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);
7057     }
7058 
7059     DEBUGLOG(4, "cSize final total: %zu", cSize);
7060     return cSize;
7061 }
7062 
ZSTD_compressSequences(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * src,size_t srcSize)7063 size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
7064                               void* dst, size_t dstCapacity,
7065                               const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
7066                               const void* src, size_t srcSize)
7067 {
7068     BYTE* op = (BYTE*)dst;
7069     size_t cSize = 0;
7070 
7071     /* Transparent initialization stage, same as compressStream2() */
7072     DEBUGLOG(4, "ZSTD_compressSequences (nbSeqs=%zu,dstCapacity=%zu)", inSeqsSize, dstCapacity);
7073     assert(cctx != NULL);
7074     FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
7075 
7076     /* Begin writing output, starting with frame header */
7077     {   size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
7078                     &cctx->appliedParams, srcSize, cctx->dictID);
7079         op += frameHeaderSize;
7080         assert(frameHeaderSize <= dstCapacity);
7081         dstCapacity -= frameHeaderSize;
7082         cSize += frameHeaderSize;
7083     }
7084     if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
7085         XXH64_update(&cctx->xxhState, src, srcSize);
7086     }
7087 
7088     /* Now generate compressed blocks */
7089     {   size_t const cBlocksSize = ZSTD_compressSequences_internal(cctx,
7090                                                            op, dstCapacity,
7091                                                            inSeqs, inSeqsSize,
7092                                                            src, srcSize);
7093         FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
7094         cSize += cBlocksSize;
7095         assert(cBlocksSize <= dstCapacity);
7096         dstCapacity -= cBlocksSize;
7097     }
7098 
7099     /* Complete with frame checksum, if needed */
7100     if (cctx->appliedParams.fParams.checksumFlag) {
7101         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
7102         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");
7103         DEBUGLOG(4, "Write checksum : %08X", (unsigned)checksum);
7104         MEM_writeLE32((char*)dst + cSize, checksum);
7105         cSize += 4;
7106     }
7107 
7108     DEBUGLOG(4, "Final compressed size: %zu", cSize);
7109     return cSize;
7110 }
7111 
7112 
7113 #if defined(__AVX2__)
7114 
7115 #include <immintrin.h>  /* AVX2 intrinsics */
7116 
7117 /*
7118  * Convert 2 sequences per iteration, using AVX2 intrinsics:
7119  *   - offset -> offBase = offset + 2
7120  *   - litLength -> (U16) litLength
7121  *   - matchLength -> (U16)(matchLength - 3)
7122  *   - rep is ignored
7123  * Store only 8 bytes per SeqDef (offBase[4], litLength[2], mlBase[2]).
7124  *
7125  * At the end, instead of extracting two __m128i,
7126  * we use _mm256_permute4x64_epi64(..., 0xE8) to move lane2 into lane1,
7127  * then store the lower 16 bytes in one go.
7128  *
7129  * @returns 0 on succes, with no long length detected
7130  * @returns > 0 if there is one long length (> 65535),
7131  * indicating the position, and type.
7132  */
convertSequences_noRepcodes(SeqDef * dstSeqs,const ZSTD_Sequence * inSeqs,size_t nbSequences)7133 static size_t convertSequences_noRepcodes(
7134     SeqDef* dstSeqs,
7135     const ZSTD_Sequence* inSeqs,
7136     size_t nbSequences)
7137 {
7138     /*
7139      * addition:
7140      *   For each 128-bit half: (offset+2, litLength+0, matchLength-3, rep+0)
7141      */
7142     const __m256i addition = _mm256_setr_epi32(
7143         ZSTD_REP_NUM, 0, -MINMATCH, 0,    /* for sequence i */
7144         ZSTD_REP_NUM, 0, -MINMATCH, 0     /* for sequence i+1 */
7145     );
7146 
7147     /* limit: check if there is a long length */
7148     const __m256i limit = _mm256_set1_epi32(65535);
7149 
7150     /*
7151      * shuffle mask for byte-level rearrangement in each 128-bit half:
7152      *
7153      * Input layout (after addition) per 128-bit half:
7154      *   [ offset+2 (4 bytes) | litLength (4 bytes) | matchLength (4 bytes) | rep (4 bytes) ]
7155      * We only need:
7156      *   offBase (4 bytes) = offset+2
7157      *   litLength (2 bytes) = low 2 bytes of litLength
7158      *   mlBase (2 bytes) = low 2 bytes of (matchLength)
7159      * => Bytes [0..3, 4..5, 8..9], zero the rest.
7160      */
7161     const __m256i mask = _mm256_setr_epi8(
7162         /* For the lower 128 bits => sequence i */
7163          0, 1, 2, 3,       /* offset+2 */
7164          4, 5,             /* litLength (16 bits) */
7165          8, 9,             /* matchLength (16 bits) */
7166          (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,
7167          (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,
7168 
7169         /* For the upper 128 bits => sequence i+1 */
7170         16,17,18,19,       /* offset+2 */
7171         20,21,             /* litLength */
7172         24,25,             /* matchLength */
7173         (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80,
7174         (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80
7175     );
7176 
7177     /*
7178      * Next, we'll use _mm256_permute4x64_epi64(vshf, 0xE8).
7179      * Explanation of 0xE8 = 11101000b => [lane0, lane2, lane2, lane3].
7180      * So the lower 128 bits become [lane0, lane2] => combining seq0 and seq1.
7181      */
7182 #define PERM_LANE_0X_E8 0xE8  /* [0,2,2,3] in lane indices */
7183 
7184     size_t longLen = 0, i = 0;
7185 
7186     /* AVX permutation depends on the specific definition of target structures */
7187     ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7188     ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0);
7189     ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4);
7190     ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7191     ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8);
7192     ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0);
7193     ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4);
7194     ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6);
7195 
7196     /* Process 2 sequences per loop iteration */
7197     for (; i + 1 < nbSequences; i += 2) {
7198         /* Load 2 ZSTD_Sequence (32 bytes) */
7199         __m256i vin  = _mm256_loadu_si256((const __m256i*)(const void*)&inSeqs[i]);
7200 
7201         /* Add {2, 0, -3, 0} in each 128-bit half */
7202         __m256i vadd = _mm256_add_epi32(vin, addition);
7203 
7204         /* Check for long length */
7205         __m256i ll_cmp  = _mm256_cmpgt_epi32(vadd, limit);  /* 0xFFFFFFFF for element > 65535 */
7206         int ll_res  = _mm256_movemask_epi8(ll_cmp);
7207 
7208         /* Shuffle bytes so each half gives us the 8 bytes we need */
7209         __m256i vshf = _mm256_shuffle_epi8(vadd, mask);
7210         /*
7211          * Now:
7212          *   Lane0 = seq0's 8 bytes
7213          *   Lane1 = 0
7214          *   Lane2 = seq1's 8 bytes
7215          *   Lane3 = 0
7216          */
7217 
7218         /* Permute 64-bit lanes => move Lane2 down into Lane1. */
7219         __m256i vperm = _mm256_permute4x64_epi64(vshf, PERM_LANE_0X_E8);
7220         /*
7221          * Now the lower 16 bytes (Lane0+Lane1) = [seq0, seq1].
7222          * The upper 16 bytes are [Lane2, Lane3] = [seq1, 0], but we won't use them.
7223          */
7224 
7225         /* Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */
7226         _mm_storeu_si128((__m128i *)(void*)&dstSeqs[i], _mm256_castsi256_si128(vperm));
7227         /*
7228          * This writes out 16 bytes total:
7229          *   - offset 0..7  => seq0 (offBase, litLength, mlBase)
7230          *   - offset 8..15 => seq1 (offBase, litLength, mlBase)
7231          */
7232 
7233         /* check (unlikely) long lengths > 65535
7234          * indices for lengths correspond to bits [4..7], [8..11], [20..23], [24..27]
7235          * => combined mask = 0x0FF00FF0
7236          */
7237         if (UNLIKELY((ll_res & 0x0FF00FF0) != 0)) {
7238             /* long length detected: let's figure out which one*/
7239             if (inSeqs[i].matchLength > 65535+MINMATCH) {
7240                 assert(longLen == 0);
7241                 longLen = i + 1;
7242             }
7243             if (inSeqs[i].litLength > 65535) {
7244                 assert(longLen == 0);
7245                 longLen = i + nbSequences + 1;
7246             }
7247             if (inSeqs[i+1].matchLength > 65535+MINMATCH) {
7248                 assert(longLen == 0);
7249                 longLen = i + 1 + 1;
7250             }
7251             if (inSeqs[i+1].litLength > 65535) {
7252                 assert(longLen == 0);
7253                 longLen = i + 1 + nbSequences + 1;
7254             }
7255         }
7256     }
7257 
7258     /* Handle leftover if @nbSequences is odd */
7259     if (i < nbSequences) {
7260         /* process last sequence */
7261         assert(i == nbSequences - 1);
7262         dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset);
7263         dstSeqs[i].litLength = (U16)inSeqs[i].litLength;
7264         dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH);
7265         /* check (unlikely) long lengths > 65535 */
7266         if (UNLIKELY(inSeqs[i].matchLength > 65535+MINMATCH)) {
7267             assert(longLen == 0);
7268             longLen = i + 1;
7269         }
7270         if (UNLIKELY(inSeqs[i].litLength > 65535)) {
7271             assert(longLen == 0);
7272             longLen = i + nbSequences + 1;
7273         }
7274     }
7275 
7276     return longLen;
7277 }
7278 
7279 /* the vector implementation could also be ported to SSSE3,
7280  * but since this implementation is targeting modern systems (>= Sapphire Rapid),
7281  * it's not useful to develop and maintain code for older pre-AVX2 platforms */
7282 
7283 #else /* no AVX2 */
7284 
convertSequences_noRepcodes(SeqDef * dstSeqs,const ZSTD_Sequence * inSeqs,size_t nbSequences)7285 static size_t convertSequences_noRepcodes(
7286     SeqDef* dstSeqs,
7287     const ZSTD_Sequence* inSeqs,
7288     size_t nbSequences)
7289 {
7290     size_t longLen = 0;
7291     size_t n;
7292     for (n=0; n<nbSequences; n++) {
7293         dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset);
7294         dstSeqs[n].litLength = (U16)inSeqs[n].litLength;
7295         dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH);
7296         /* check for long length > 65535 */
7297         if (UNLIKELY(inSeqs[n].matchLength > 65535+MINMATCH)) {
7298             assert(longLen == 0);
7299             longLen = n + 1;
7300         }
7301         if (UNLIKELY(inSeqs[n].litLength > 65535)) {
7302             assert(longLen == 0);
7303             longLen = n + nbSequences + 1;
7304         }
7305     }
7306     return longLen;
7307 }
7308 
7309 #endif
7310 
7311 /*
7312  * Precondition: Sequences must end on an explicit Block Delimiter
7313  * @return: 0 on success, or an error code.
7314  * Note: Sequence validation functionality has been disabled (removed).
7315  * This is helpful to generate a lean main pipeline, improving performance.
7316  * It may be re-inserted later.
7317  */
ZSTD_convertBlockSequences(ZSTD_CCtx * cctx,const ZSTD_Sequence * const inSeqs,size_t nbSequences,int repcodeResolution)7318 size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,
7319                 const ZSTD_Sequence* const inSeqs, size_t nbSequences,
7320                 int repcodeResolution)
7321 {
7322     Repcodes_t updatedRepcodes;
7323     size_t seqNb = 0;
7324 
7325     DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences);
7326 
7327     RETURN_ERROR_IF(nbSequences >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
7328                     "Not enough memory allocated. Try adjusting ZSTD_c_minMatch.");
7329 
7330     ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t));
7331 
7332     /* check end condition */
7333     assert(nbSequences >= 1);
7334     assert(inSeqs[nbSequences-1].matchLength == 0);
7335     assert(inSeqs[nbSequences-1].offset == 0);
7336 
7337     /* Convert Sequences from public format to internal format */
7338     if (!repcodeResolution) {
7339         size_t const longl = convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences-1);
7340         cctx->seqStore.sequences = cctx->seqStore.sequencesStart + nbSequences-1;
7341         if (longl) {
7342             DEBUGLOG(5, "long length");
7343             assert(cctx->seqStore.longLengthType == ZSTD_llt_none);
7344             if (longl <= nbSequences-1) {
7345                 DEBUGLOG(5, "long match length detected at pos %zu", longl-1);
7346                 cctx->seqStore.longLengthType = ZSTD_llt_matchLength;
7347                 cctx->seqStore.longLengthPos = (U32)(longl-1);
7348             } else {
7349                 DEBUGLOG(5, "long literals length detected at pos %zu", longl-nbSequences);
7350                 assert(longl <= 2* (nbSequences-1));
7351                 cctx->seqStore.longLengthType = ZSTD_llt_literalLength;
7352                 cctx->seqStore.longLengthPos = (U32)(longl-(nbSequences-1)-1);
7353             }
7354         }
7355     } else {
7356         for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) {
7357             U32 const litLength = inSeqs[seqNb].litLength;
7358             U32 const matchLength = inSeqs[seqNb].matchLength;
7359             U32 const ll0 = (litLength == 0);
7360             U32 const offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0);
7361 
7362             DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
7363             ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength);
7364             ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0);
7365         }
7366     }
7367 
7368     /* If we skipped repcode search while parsing, we need to update repcodes now */
7369     if (!repcodeResolution && nbSequences > 1) {
7370         U32* const rep = updatedRepcodes.rep;
7371 
7372         if (nbSequences >= 4) {
7373             U32 lastSeqIdx = (U32)nbSequences - 2; /* index of last full sequence */
7374             rep[2] = inSeqs[lastSeqIdx - 2].offset;
7375             rep[1] = inSeqs[lastSeqIdx - 1].offset;
7376             rep[0] = inSeqs[lastSeqIdx].offset;
7377         } else if (nbSequences == 3) {
7378             rep[2] = rep[0];
7379             rep[1] = inSeqs[0].offset;
7380             rep[0] = inSeqs[1].offset;
7381         } else {
7382             assert(nbSequences == 2);
7383             rep[2] = rep[1];
7384             rep[1] = rep[0];
7385             rep[0] = inSeqs[0].offset;
7386         }
7387     }
7388 
7389     ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t));
7390 
7391     return 0;
7392 }
7393 
7394 #if defined(ZSTD_ARCH_X86_AVX2)
7395 
ZSTD_get1BlockSummary(const ZSTD_Sequence * seqs,size_t nbSeqs)7396 BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7397 {
7398     size_t i;
7399     __m256i const zeroVec = _mm256_setzero_si256();
7400     __m256i sumVec = zeroVec;  /* accumulates match+lit in 32-bit lanes */
7401     ZSTD_ALIGNED(32) U32 tmp[8];      /* temporary buffer for reduction */
7402     size_t mSum = 0, lSum = 0;
7403     ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16);
7404 
7405     /* Process 2 structs (32 bytes) at a time */
7406     for (i = 0; i + 2 <= nbSeqs; i += 2) {
7407         /* Load two consecutive ZSTD_Sequence (8×4 = 32 bytes) */
7408         __m256i data     = _mm256_loadu_si256((const __m256i*)(const void*)&seqs[i]);
7409         /* check end of block signal */
7410         __m256i cmp      = _mm256_cmpeq_epi32(data, zeroVec);
7411         int cmp_res      = _mm256_movemask_epi8(cmp);
7412         /* indices for match lengths correspond to bits [8..11], [24..27]
7413          * => combined mask = 0x0F000F00 */
7414         ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8);
7415         if (cmp_res & 0x0F000F00) break;
7416         /* Accumulate in sumVec */
7417         sumVec           = _mm256_add_epi32(sumVec, data);
7418     }
7419 
7420     /* Horizontal reduction */
7421     _mm256_store_si256((__m256i*)tmp, sumVec);
7422     lSum = tmp[1] + tmp[5];
7423     mSum = tmp[2] + tmp[6];
7424 
7425     /* Handle the leftover */
7426     for (; i < nbSeqs; i++) {
7427         lSum += seqs[i].litLength;
7428         mSum += seqs[i].matchLength;
7429         if (seqs[i].matchLength == 0) break; /* end of block */
7430     }
7431 
7432     if (i==nbSeqs) {
7433         /* reaching end of sequences: end of block signal was not present */
7434         BlockSummary bs;
7435         bs.nbSequences = ERROR(externalSequences_invalid);
7436         return bs;
7437     }
7438     {   BlockSummary bs;
7439         bs.nbSequences = i+1;
7440         bs.blockSize = lSum + mSum;
7441         bs.litSize = lSum;
7442         return bs;
7443     }
7444 }
7445 
7446 #else
7447 
ZSTD_get1BlockSummary(const ZSTD_Sequence * seqs,size_t nbSeqs)7448 BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs)
7449 {
7450     size_t totalMatchSize = 0;
7451     size_t litSize = 0;
7452     size_t n;
7453     assert(seqs);
7454     for (n=0; n<nbSeqs; n++) {
7455         totalMatchSize += seqs[n].matchLength;
7456         litSize += seqs[n].litLength;
7457         if (seqs[n].matchLength == 0) {
7458             assert(seqs[n].offset == 0);
7459             break;
7460         }
7461     }
7462     if (n==nbSeqs) {
7463         BlockSummary bs;
7464         bs.nbSequences = ERROR(externalSequences_invalid);
7465         return bs;
7466     }
7467     {   BlockSummary bs;
7468         bs.nbSequences = n+1;
7469         bs.blockSize = litSize + totalMatchSize;
7470         bs.litSize = litSize;
7471         return bs;
7472     }
7473 }
7474 #endif
7475 
7476 
7477 static size_t
ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t nbSequences,const void * literals,size_t litSize,size_t srcSize)7478 ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx,
7479                                 void* dst, size_t dstCapacity,
7480                           const ZSTD_Sequence* inSeqs, size_t nbSequences,
7481                           const void* literals, size_t litSize, size_t srcSize)
7482 {
7483     size_t remaining = srcSize;
7484     size_t cSize = 0;
7485     BYTE* op = (BYTE*)dst;
7486     int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable);
7487     assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto);
7488 
7489     DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize);
7490     RETURN_ERROR_IF(nbSequences == 0, externalSequences_invalid, "Requires at least 1 end-of-block");
7491 
7492     /* Special case: empty frame */
7493     if ((nbSequences == 1) && (inSeqs[0].litLength == 0)) {
7494         U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1);
7495         RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "No room for empty frame block header");
7496         MEM_writeLE24(op, cBlockHeader24);
7497         op += ZSTD_blockHeaderSize;
7498         dstCapacity -= ZSTD_blockHeaderSize;
7499         cSize += ZSTD_blockHeaderSize;
7500     }
7501 
7502     while (nbSequences) {
7503         size_t compressedSeqsSize, cBlockSize, conversionStatus;
7504         BlockSummary const block = ZSTD_get1BlockSummary(inSeqs, nbSequences);
7505         U32 const lastBlock = (block.nbSequences == nbSequences);
7506         FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block");
7507         assert(block.nbSequences <= nbSequences);
7508         RETURN_ERROR_IF(block.litSize > litSize, externalSequences_invalid, "discrepancy: Sequences require more literals than present in buffer");
7509         ZSTD_resetSeqStore(&cctx->seqStore);
7510 
7511         conversionStatus = ZSTD_convertBlockSequences(cctx,
7512                             inSeqs, block.nbSequences,
7513                             repcodeResolution);
7514         FORWARD_IF_ERROR(conversionStatus, "Bad sequence conversion");
7515         inSeqs += block.nbSequences;
7516         nbSequences -= block.nbSequences;
7517         remaining -= block.blockSize;
7518 
7519         /* Note: when blockSize is very small, other variant send it uncompressed.
7520          * Here, we still send the sequences, because we don't have the original source to send it uncompressed.
7521          * One could imagine in theory reproducing the source from the sequences,
7522          * but that's complex and costly memory intensive, and goes against the objectives of this variant. */
7523 
7524         RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block");
7525 
7526         compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal(
7527                                 op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize,
7528                                 literals, block.litSize,
7529                                 &cctx->seqStore,
7530                                 &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy,
7531                                 &cctx->appliedParams,
7532                                 cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */,
7533                                 cctx->bmi2);
7534         FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed");
7535         /* note: the spec forbids for any compressed block to be larger than maximum block size */
7536         if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0;
7537         DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize);
7538         litSize -= block.litSize;
7539         literals = (const char*)literals + block.litSize;
7540 
7541         /* Note: difficult to check source for RLE block when only Literals are provided,
7542          * but it could be considered from analyzing the sequence directly */
7543 
7544         if (compressedSeqsSize == 0) {
7545             /* Sending uncompressed blocks is out of reach, because the source is not provided.
7546              * In theory, one could use the sequences to regenerate the source, like a decompressor,
7547              * but it's complex, and memory hungry, killing the purpose of this variant.
7548              * Current outcome: generate an error code.
7549              */
7550             RETURN_ERROR(cannotProduce_uncompressedBlock, "ZSTD_compressSequencesAndLiterals cannot generate an uncompressed block");
7551         } else {
7552             U32 cBlockHeader;
7553             assert(compressedSeqsSize > 1); /* no RLE */
7554             /* Error checking and repcodes update */
7555             ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState);
7556             if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
7557                 cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
7558 
7559             /* Write block header into beginning of block*/
7560             cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3);
7561             MEM_writeLE24(op, cBlockHeader);
7562             cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize;
7563             DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize);
7564         }
7565 
7566         cSize += cBlockSize;
7567         op += cBlockSize;
7568         dstCapacity -= cBlockSize;
7569         cctx->isFirstBlock = 0;
7570         DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity);
7571 
7572         if (lastBlock) {
7573             assert(nbSequences == 0);
7574             break;
7575         }
7576     }
7577 
7578     RETURN_ERROR_IF(litSize != 0, externalSequences_invalid, "literals must be entirely and exactly consumed");
7579     RETURN_ERROR_IF(remaining != 0, externalSequences_invalid, "Sequences must represent a total of exactly srcSize=%zu", srcSize);
7580     DEBUGLOG(4, "cSize final total: %zu", cSize);
7581     return cSize;
7582 }
7583 
7584 size_t
ZSTD_compressSequencesAndLiterals(ZSTD_CCtx * cctx,void * dst,size_t dstCapacity,const ZSTD_Sequence * inSeqs,size_t inSeqsSize,const void * literals,size_t litSize,size_t litCapacity,size_t decompressedSize)7585 ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
7586                     void* dst, size_t dstCapacity,
7587                     const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
7588                     const void* literals, size_t litSize, size_t litCapacity,
7589                     size_t decompressedSize)
7590 {
7591     BYTE* op = (BYTE*)dst;
7592     size_t cSize = 0;
7593 
7594     /* Transparent initialization stage, same as compressStream2() */
7595     DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity);
7596     assert(cctx != NULL);
7597     if (litCapacity < litSize) {
7598         RETURN_ERROR(workSpace_tooSmall, "literals buffer is not large enough: must be at least 8 bytes larger than litSize (risk of read out-of-bound)");
7599     }
7600     FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize), "CCtx initialization failed");
7601 
7602     if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) {
7603         RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters");
7604     }
7605     if (cctx->appliedParams.validateSequences) {
7606         RETURN_ERROR(parameter_unsupported, "This mode is not compatible with Sequence validation");
7607     }
7608     if (cctx->appliedParams.fParams.checksumFlag) {
7609         RETURN_ERROR(frameParameter_unsupported, "this mode is not compatible with frame checksum");
7610     }
7611 
7612     /* Begin writing output, starting with frame header */
7613     {   size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
7614                     &cctx->appliedParams, decompressedSize, cctx->dictID);
7615         op += frameHeaderSize;
7616         assert(frameHeaderSize <= dstCapacity);
7617         dstCapacity -= frameHeaderSize;
7618         cSize += frameHeaderSize;
7619     }
7620 
7621     /* Now generate compressed blocks */
7622     {   size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx,
7623                                             op, dstCapacity,
7624                                             inSeqs, inSeqsSize,
7625                                             literals, litSize, decompressedSize);
7626         FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
7627         cSize += cBlocksSize;
7628         assert(cBlocksSize <= dstCapacity);
7629         dstCapacity -= cBlocksSize;
7630     }
7631 
7632     DEBUGLOG(4, "Final compressed size: %zu", cSize);
7633     return cSize;
7634 }
7635 
7636 /*======   Finalize   ======*/
7637 
inBuffer_forEndFlush(const ZSTD_CStream * zcs)7638 static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs)
7639 {
7640     const ZSTD_inBuffer nullInput = { NULL, 0, 0 };
7641     const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable);
7642     return stableInput ? zcs->expectedInBuffer : nullInput;
7643 }
7644 
7645 /*! ZSTD_flushStream() :
7646  * @return : amount of data remaining to flush */
ZSTD_flushStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output)7647 size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
7648 {
7649     ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);
7650     input.size = input.pos; /* do not ingest more input during flush */
7651     return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
7652 }
7653 
ZSTD_endStream(ZSTD_CStream * zcs,ZSTD_outBuffer * output)7654 size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
7655 {
7656     ZSTD_inBuffer input = inBuffer_forEndFlush(zcs);
7657     size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
7658     FORWARD_IF_ERROR(remainingToFlush , "ZSTD_compressStream2(,,ZSTD_e_end) failed");
7659     if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush;   /* minimal estimation */
7660     /* single thread mode : attempt to calculate remaining to flush more precisely */
7661     {   size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
7662         size_t const checksumSize = (size_t)(zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4);
7663         size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
7664         DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
7665         return toFlush;
7666     }
7667 }
7668 
7669 
7670 /*-=====  Pre-defined compression levels  =====-*/
7671 #include "clevels.h"
7672 
ZSTD_maxCLevel(void)7673 int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
ZSTD_minCLevel(void)7674 int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
ZSTD_defaultCLevel(void)7675 int ZSTD_defaultCLevel(void) { return ZSTD_CLEVEL_DEFAULT; }
7676 
ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel,size_t const dictSize)7677 static ZSTD_compressionParameters ZSTD_dedicatedDictSearch_getCParams(int const compressionLevel, size_t const dictSize)
7678 {
7679     ZSTD_compressionParameters cParams = ZSTD_getCParams_internal(compressionLevel, 0, dictSize, ZSTD_cpm_createCDict);
7680     switch (cParams.strategy) {
7681         case ZSTD_fast:
7682         case ZSTD_dfast:
7683             break;
7684         case ZSTD_greedy:
7685         case ZSTD_lazy:
7686         case ZSTD_lazy2:
7687             cParams.hashLog += ZSTD_LAZY_DDSS_BUCKET_LOG;
7688             break;
7689         case ZSTD_btlazy2:
7690         case ZSTD_btopt:
7691         case ZSTD_btultra:
7692         case ZSTD_btultra2:
7693             break;
7694     }
7695     return cParams;
7696 }
7697 
ZSTD_dedicatedDictSearch_isSupported(ZSTD_compressionParameters const * cParams)7698 static int ZSTD_dedicatedDictSearch_isSupported(
7699         ZSTD_compressionParameters const* cParams)
7700 {
7701     return (cParams->strategy >= ZSTD_greedy)
7702         && (cParams->strategy <= ZSTD_lazy2)
7703         && (cParams->hashLog > cParams->chainLog)
7704         && (cParams->chainLog <= 24);
7705 }
7706 
7707 /**
7708  * Reverses the adjustment applied to cparams when enabling dedicated dict
7709  * search. This is used to recover the params set to be used in the working
7710  * context. (Otherwise, those tables would also grow.)
7711  */
ZSTD_dedicatedDictSearch_revertCParams(ZSTD_compressionParameters * cParams)7712 static void ZSTD_dedicatedDictSearch_revertCParams(
7713         ZSTD_compressionParameters* cParams) {
7714     switch (cParams->strategy) {
7715         case ZSTD_fast:
7716         case ZSTD_dfast:
7717             break;
7718         case ZSTD_greedy:
7719         case ZSTD_lazy:
7720         case ZSTD_lazy2:
7721             cParams->hashLog -= ZSTD_LAZY_DDSS_BUCKET_LOG;
7722             if (cParams->hashLog < ZSTD_HASHLOG_MIN) {
7723                 cParams->hashLog = ZSTD_HASHLOG_MIN;
7724             }
7725             break;
7726         case ZSTD_btlazy2:
7727         case ZSTD_btopt:
7728         case ZSTD_btultra:
7729         case ZSTD_btultra2:
7730             break;
7731     }
7732 }
7733 
ZSTD_getCParamRowSize(U64 srcSizeHint,size_t dictSize,ZSTD_CParamMode_e mode)7734 static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
7735 {
7736     switch (mode) {
7737     case ZSTD_cpm_unknown:
7738     case ZSTD_cpm_noAttachDict:
7739     case ZSTD_cpm_createCDict:
7740         break;
7741     case ZSTD_cpm_attachDict:
7742         dictSize = 0;
7743         break;
7744     default:
7745         assert(0);
7746         break;
7747     }
7748     {   int const unknown = srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN;
7749         size_t const addedSize = unknown && dictSize > 0 ? 500 : 0;
7750         return unknown && dictSize == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : srcSizeHint+dictSize+addedSize;
7751     }
7752 }
7753 
7754 /*! ZSTD_getCParams_internal() :
7755  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
7756  *  Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
7757  *        Use dictSize == 0 for unknown or unused.
7758  *  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)7759 static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
7760 {
7761     U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
7762     U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
7763     int row;
7764     DEBUGLOG(5, "ZSTD_getCParams_internal (cLevel=%i)", compressionLevel);
7765 
7766     /* row */
7767     if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT;   /* 0 == default */
7768     else if (compressionLevel < 0) row = 0;   /* entry 0 is baseline for fast mode */
7769     else if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
7770     else row = compressionLevel;
7771 
7772     {   ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
7773         DEBUGLOG(5, "ZSTD_getCParams_internal selected tableID: %u row: %u strat: %u", tableID, row, (U32)cp.strategy);
7774         /* acceleration factor */
7775         if (compressionLevel < 0) {
7776             int const clampedCompressionLevel = MAX(ZSTD_minCLevel(), compressionLevel);
7777             cp.targetLength = (unsigned)(-clampedCompressionLevel);
7778         }
7779         /* refine parameters based on srcSize & dictSize */
7780         return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize, mode, ZSTD_ps_auto);
7781     }
7782 }
7783 
7784 /*! ZSTD_getCParams() :
7785  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
7786  *  Size values are optional, provide 0 if not known or unused */
ZSTD_getCParams(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize)7787 ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
7788 {
7789     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
7790     return ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
7791 }
7792 
7793 /*! ZSTD_getParams() :
7794  *  same idea as ZSTD_getCParams()
7795  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
7796  *  Fields of `ZSTD_frameParameters` are set to default values */
7797 static ZSTD_parameters
ZSTD_getParams_internal(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize,ZSTD_CParamMode_e mode)7798 ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
7799 {
7800     ZSTD_parameters params;
7801     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
7802     DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
7803     ZSTD_memset(&params, 0, sizeof(params));
7804     params.cParams = cParams;
7805     params.fParams.contentSizeFlag = 1;
7806     return params;
7807 }
7808 
7809 /*! ZSTD_getParams() :
7810  *  same idea as ZSTD_getCParams()
7811  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
7812  *  Fields of `ZSTD_frameParameters` are set to default values */
ZSTD_getParams(int compressionLevel,unsigned long long srcSizeHint,size_t dictSize)7813 ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
7814 {
7815     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
7816     return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
7817 }
7818 
ZSTD_registerSequenceProducer(ZSTD_CCtx * zc,void * extSeqProdState,ZSTD_sequenceProducer_F extSeqProdFunc)7819 void ZSTD_registerSequenceProducer(
7820     ZSTD_CCtx* zc,
7821     void* extSeqProdState,
7822     ZSTD_sequenceProducer_F extSeqProdFunc)
7823 {
7824     assert(zc != NULL);
7825     ZSTD_CCtxParams_registerSequenceProducer(
7826         &zc->requestedParams, extSeqProdState, extSeqProdFunc
7827     );
7828 }
7829 
ZSTD_CCtxParams_registerSequenceProducer(ZSTD_CCtx_params * params,void * extSeqProdState,ZSTD_sequenceProducer_F extSeqProdFunc)7830 void ZSTD_CCtxParams_registerSequenceProducer(
7831   ZSTD_CCtx_params* params,
7832   void* extSeqProdState,
7833   ZSTD_sequenceProducer_F extSeqProdFunc)
7834 {
7835     assert(params != NULL);
7836     if (extSeqProdFunc != NULL) {
7837         params->extSeqProdFunc = extSeqProdFunc;
7838         params->extSeqProdState = extSeqProdState;
7839     } else {
7840         params->extSeqProdFunc = NULL;
7841         params->extSeqProdState = NULL;
7842     }
7843 }
7844