xref: /aosp_15_r20/external/zstd/lib/decompress/zstd_decompress.c (revision 01826a4963a0d8a59bc3812d29bdf0fb76416722)
1*01826a49SYabin Cui /*
2*01826a49SYabin Cui  * Copyright (c) Meta Platforms, Inc. and affiliates.
3*01826a49SYabin Cui  * All rights reserved.
4*01826a49SYabin Cui  *
5*01826a49SYabin Cui  * This source code is licensed under both the BSD-style license (found in the
6*01826a49SYabin Cui  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*01826a49SYabin Cui  * in the COPYING file in the root directory of this source tree).
8*01826a49SYabin Cui  * You may select, at your option, one of the above-listed licenses.
9*01826a49SYabin Cui  */
10*01826a49SYabin Cui 
11*01826a49SYabin Cui 
12*01826a49SYabin Cui /* ***************************************************************
13*01826a49SYabin Cui *  Tuning parameters
14*01826a49SYabin Cui *****************************************************************/
15*01826a49SYabin Cui /*!
16*01826a49SYabin Cui  * HEAPMODE :
17*01826a49SYabin Cui  * Select how default decompression function ZSTD_decompress() allocates its context,
18*01826a49SYabin Cui  * on stack (0), or into heap (1, default; requires malloc()).
19*01826a49SYabin Cui  * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.
20*01826a49SYabin Cui  */
21*01826a49SYabin Cui #ifndef ZSTD_HEAPMODE
22*01826a49SYabin Cui #  define ZSTD_HEAPMODE 1
23*01826a49SYabin Cui #endif
24*01826a49SYabin Cui 
25*01826a49SYabin Cui /*!
26*01826a49SYabin Cui *  LEGACY_SUPPORT :
27*01826a49SYabin Cui *  if set to 1+, ZSTD_decompress() can decode older formats (v0.1+)
28*01826a49SYabin Cui */
29*01826a49SYabin Cui #ifndef ZSTD_LEGACY_SUPPORT
30*01826a49SYabin Cui #  define ZSTD_LEGACY_SUPPORT 0
31*01826a49SYabin Cui #endif
32*01826a49SYabin Cui 
33*01826a49SYabin Cui /*!
34*01826a49SYabin Cui  *  MAXWINDOWSIZE_DEFAULT :
35*01826a49SYabin Cui  *  maximum window size accepted by DStream __by default__.
36*01826a49SYabin Cui  *  Frames requiring more memory will be rejected.
37*01826a49SYabin Cui  *  It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize().
38*01826a49SYabin Cui  */
39*01826a49SYabin Cui #ifndef ZSTD_MAXWINDOWSIZE_DEFAULT
40*01826a49SYabin Cui #  define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1)
41*01826a49SYabin Cui #endif
42*01826a49SYabin Cui 
43*01826a49SYabin Cui /*!
44*01826a49SYabin Cui  *  NO_FORWARD_PROGRESS_MAX :
45*01826a49SYabin Cui  *  maximum allowed nb of calls to ZSTD_decompressStream()
46*01826a49SYabin Cui  *  without any forward progress
47*01826a49SYabin Cui  *  (defined as: no byte read from input, and no byte flushed to output)
48*01826a49SYabin Cui  *  before triggering an error.
49*01826a49SYabin Cui  */
50*01826a49SYabin Cui #ifndef ZSTD_NO_FORWARD_PROGRESS_MAX
51*01826a49SYabin Cui #  define ZSTD_NO_FORWARD_PROGRESS_MAX 16
52*01826a49SYabin Cui #endif
53*01826a49SYabin Cui 
54*01826a49SYabin Cui 
55*01826a49SYabin Cui /*-*******************************************************
56*01826a49SYabin Cui *  Dependencies
57*01826a49SYabin Cui *********************************************************/
58*01826a49SYabin Cui #include "../common/zstd_deps.h"   /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
59*01826a49SYabin Cui #include "../common/allocations.h"  /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
60*01826a49SYabin Cui #include "../common/error_private.h"
61*01826a49SYabin Cui #include "../common/zstd_internal.h"  /* blockProperties_t */
62*01826a49SYabin Cui #include "../common/mem.h"         /* low level memory routines */
63*01826a49SYabin Cui #include "../common/bits.h"  /* ZSTD_highbit32 */
64*01826a49SYabin Cui #define FSE_STATIC_LINKING_ONLY
65*01826a49SYabin Cui #include "../common/fse.h"
66*01826a49SYabin Cui #include "../common/huf.h"
67*01826a49SYabin Cui #include "../common/xxhash.h" /* XXH64_reset, XXH64_update, XXH64_digest, XXH64 */
68*01826a49SYabin Cui #include "zstd_decompress_internal.h"   /* ZSTD_DCtx */
69*01826a49SYabin Cui #include "zstd_ddict.h"  /* ZSTD_DDictDictContent */
70*01826a49SYabin Cui #include "zstd_decompress_block.h"   /* ZSTD_decompressBlock_internal */
71*01826a49SYabin Cui 
72*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
73*01826a49SYabin Cui #  include "../legacy/zstd_legacy.h"
74*01826a49SYabin Cui #endif
75*01826a49SYabin Cui 
76*01826a49SYabin Cui 
77*01826a49SYabin Cui 
78*01826a49SYabin Cui /*************************************
79*01826a49SYabin Cui  * Multiple DDicts Hashset internals *
80*01826a49SYabin Cui  *************************************/
81*01826a49SYabin Cui 
82*01826a49SYabin Cui #define DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT 4
83*01826a49SYabin Cui #define DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT 3  /* These two constants represent SIZE_MULT/COUNT_MULT load factor without using a float.
84*01826a49SYabin Cui                                                     * Currently, that means a 0.75 load factor.
85*01826a49SYabin Cui                                                     * So, if count * COUNT_MULT / size * SIZE_MULT != 0, then we've exceeded
86*01826a49SYabin Cui                                                     * the load factor of the ddict hash set.
87*01826a49SYabin Cui                                                     */
88*01826a49SYabin Cui 
89*01826a49SYabin Cui #define DDICT_HASHSET_TABLE_BASE_SIZE 64
90*01826a49SYabin Cui #define DDICT_HASHSET_RESIZE_FACTOR 2
91*01826a49SYabin Cui 
92*01826a49SYabin Cui /* Hash function to determine starting position of dict insertion within the table
93*01826a49SYabin Cui  * Returns an index between [0, hashSet->ddictPtrTableSize]
94*01826a49SYabin Cui  */
ZSTD_DDictHashSet_getIndex(const ZSTD_DDictHashSet * hashSet,U32 dictID)95*01826a49SYabin Cui static size_t ZSTD_DDictHashSet_getIndex(const ZSTD_DDictHashSet* hashSet, U32 dictID) {
96*01826a49SYabin Cui     const U64 hash = XXH64(&dictID, sizeof(U32), 0);
97*01826a49SYabin Cui     /* DDict ptr table size is a multiple of 2, use size - 1 as mask to get index within [0, hashSet->ddictPtrTableSize) */
98*01826a49SYabin Cui     return hash & (hashSet->ddictPtrTableSize - 1);
99*01826a49SYabin Cui }
100*01826a49SYabin Cui 
101*01826a49SYabin Cui /* Adds DDict to a hashset without resizing it.
102*01826a49SYabin Cui  * If inserting a DDict with a dictID that already exists in the set, replaces the one in the set.
103*01826a49SYabin Cui  * Returns 0 if successful, or a zstd error code if something went wrong.
104*01826a49SYabin Cui  */
ZSTD_DDictHashSet_emplaceDDict(ZSTD_DDictHashSet * hashSet,const ZSTD_DDict * ddict)105*01826a49SYabin Cui static size_t ZSTD_DDictHashSet_emplaceDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict) {
106*01826a49SYabin Cui     const U32 dictID = ZSTD_getDictID_fromDDict(ddict);
107*01826a49SYabin Cui     size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID);
108*01826a49SYabin Cui     const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1;
109*01826a49SYabin Cui     RETURN_ERROR_IF(hashSet->ddictPtrCount == hashSet->ddictPtrTableSize, GENERIC, "Hash set is full!");
110*01826a49SYabin Cui     DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx);
111*01826a49SYabin Cui     while (hashSet->ddictPtrTable[idx] != NULL) {
112*01826a49SYabin Cui         /* Replace existing ddict if inserting ddict with same dictID */
113*01826a49SYabin Cui         if (ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]) == dictID) {
114*01826a49SYabin Cui             DEBUGLOG(4, "DictID already exists, replacing rather than adding");
115*01826a49SYabin Cui             hashSet->ddictPtrTable[idx] = ddict;
116*01826a49SYabin Cui             return 0;
117*01826a49SYabin Cui         }
118*01826a49SYabin Cui         idx &= idxRangeMask;
119*01826a49SYabin Cui         idx++;
120*01826a49SYabin Cui     }
121*01826a49SYabin Cui     DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx);
122*01826a49SYabin Cui     hashSet->ddictPtrTable[idx] = ddict;
123*01826a49SYabin Cui     hashSet->ddictPtrCount++;
124*01826a49SYabin Cui     return 0;
125*01826a49SYabin Cui }
126*01826a49SYabin Cui 
127*01826a49SYabin Cui /* Expands hash table by factor of DDICT_HASHSET_RESIZE_FACTOR and
128*01826a49SYabin Cui  * rehashes all values, allocates new table, frees old table.
129*01826a49SYabin Cui  * Returns 0 on success, otherwise a zstd error code.
130*01826a49SYabin Cui  */
ZSTD_DDictHashSet_expand(ZSTD_DDictHashSet * hashSet,ZSTD_customMem customMem)131*01826a49SYabin Cui static size_t ZSTD_DDictHashSet_expand(ZSTD_DDictHashSet* hashSet, ZSTD_customMem customMem) {
132*01826a49SYabin Cui     size_t newTableSize = hashSet->ddictPtrTableSize * DDICT_HASHSET_RESIZE_FACTOR;
133*01826a49SYabin Cui     const ZSTD_DDict** newTable = (const ZSTD_DDict**)ZSTD_customCalloc(sizeof(ZSTD_DDict*) * newTableSize, customMem);
134*01826a49SYabin Cui     const ZSTD_DDict** oldTable = hashSet->ddictPtrTable;
135*01826a49SYabin Cui     size_t oldTableSize = hashSet->ddictPtrTableSize;
136*01826a49SYabin Cui     size_t i;
137*01826a49SYabin Cui 
138*01826a49SYabin Cui     DEBUGLOG(4, "Expanding DDict hash table! Old size: %zu new size: %zu", oldTableSize, newTableSize);
139*01826a49SYabin Cui     RETURN_ERROR_IF(!newTable, memory_allocation, "Expanded hashset allocation failed!");
140*01826a49SYabin Cui     hashSet->ddictPtrTable = newTable;
141*01826a49SYabin Cui     hashSet->ddictPtrTableSize = newTableSize;
142*01826a49SYabin Cui     hashSet->ddictPtrCount = 0;
143*01826a49SYabin Cui     for (i = 0; i < oldTableSize; ++i) {
144*01826a49SYabin Cui         if (oldTable[i] != NULL) {
145*01826a49SYabin Cui             FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, oldTable[i]), "");
146*01826a49SYabin Cui         }
147*01826a49SYabin Cui     }
148*01826a49SYabin Cui     ZSTD_customFree((void*)oldTable, customMem);
149*01826a49SYabin Cui     DEBUGLOG(4, "Finished re-hash");
150*01826a49SYabin Cui     return 0;
151*01826a49SYabin Cui }
152*01826a49SYabin Cui 
153*01826a49SYabin Cui /* Fetches a DDict with the given dictID
154*01826a49SYabin Cui  * Returns the ZSTD_DDict* with the requested dictID. If it doesn't exist, then returns NULL.
155*01826a49SYabin Cui  */
ZSTD_DDictHashSet_getDDict(ZSTD_DDictHashSet * hashSet,U32 dictID)156*01826a49SYabin Cui static const ZSTD_DDict* ZSTD_DDictHashSet_getDDict(ZSTD_DDictHashSet* hashSet, U32 dictID) {
157*01826a49SYabin Cui     size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID);
158*01826a49SYabin Cui     const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1;
159*01826a49SYabin Cui     DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx);
160*01826a49SYabin Cui     for (;;) {
161*01826a49SYabin Cui         size_t currDictID = ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]);
162*01826a49SYabin Cui         if (currDictID == dictID || currDictID == 0) {
163*01826a49SYabin Cui             /* currDictID == 0 implies a NULL ddict entry */
164*01826a49SYabin Cui             break;
165*01826a49SYabin Cui         } else {
166*01826a49SYabin Cui             idx &= idxRangeMask;    /* Goes to start of table when we reach the end */
167*01826a49SYabin Cui             idx++;
168*01826a49SYabin Cui         }
169*01826a49SYabin Cui     }
170*01826a49SYabin Cui     DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx);
171*01826a49SYabin Cui     return hashSet->ddictPtrTable[idx];
172*01826a49SYabin Cui }
173*01826a49SYabin Cui 
174*01826a49SYabin Cui /* Allocates space for and returns a ddict hash set
175*01826a49SYabin Cui  * The hash set's ZSTD_DDict* table has all values automatically set to NULL to begin with.
176*01826a49SYabin Cui  * Returns NULL if allocation failed.
177*01826a49SYabin Cui  */
ZSTD_createDDictHashSet(ZSTD_customMem customMem)178*01826a49SYabin Cui static ZSTD_DDictHashSet* ZSTD_createDDictHashSet(ZSTD_customMem customMem) {
179*01826a49SYabin Cui     ZSTD_DDictHashSet* ret = (ZSTD_DDictHashSet*)ZSTD_customMalloc(sizeof(ZSTD_DDictHashSet), customMem);
180*01826a49SYabin Cui     DEBUGLOG(4, "Allocating new hash set");
181*01826a49SYabin Cui     if (!ret)
182*01826a49SYabin Cui         return NULL;
183*01826a49SYabin Cui     ret->ddictPtrTable = (const ZSTD_DDict**)ZSTD_customCalloc(DDICT_HASHSET_TABLE_BASE_SIZE * sizeof(ZSTD_DDict*), customMem);
184*01826a49SYabin Cui     if (!ret->ddictPtrTable) {
185*01826a49SYabin Cui         ZSTD_customFree(ret, customMem);
186*01826a49SYabin Cui         return NULL;
187*01826a49SYabin Cui     }
188*01826a49SYabin Cui     ret->ddictPtrTableSize = DDICT_HASHSET_TABLE_BASE_SIZE;
189*01826a49SYabin Cui     ret->ddictPtrCount = 0;
190*01826a49SYabin Cui     return ret;
191*01826a49SYabin Cui }
192*01826a49SYabin Cui 
193*01826a49SYabin Cui /* Frees the table of ZSTD_DDict* within a hashset, then frees the hashset itself.
194*01826a49SYabin Cui  * Note: The ZSTD_DDict* within the table are NOT freed.
195*01826a49SYabin Cui  */
ZSTD_freeDDictHashSet(ZSTD_DDictHashSet * hashSet,ZSTD_customMem customMem)196*01826a49SYabin Cui static void ZSTD_freeDDictHashSet(ZSTD_DDictHashSet* hashSet, ZSTD_customMem customMem) {
197*01826a49SYabin Cui     DEBUGLOG(4, "Freeing ddict hash set");
198*01826a49SYabin Cui     if (hashSet && hashSet->ddictPtrTable) {
199*01826a49SYabin Cui         ZSTD_customFree((void*)hashSet->ddictPtrTable, customMem);
200*01826a49SYabin Cui     }
201*01826a49SYabin Cui     if (hashSet) {
202*01826a49SYabin Cui         ZSTD_customFree(hashSet, customMem);
203*01826a49SYabin Cui     }
204*01826a49SYabin Cui }
205*01826a49SYabin Cui 
206*01826a49SYabin Cui /* Public function: Adds a DDict into the ZSTD_DDictHashSet, possibly triggering a resize of the hash set.
207*01826a49SYabin Cui  * Returns 0 on success, or a ZSTD error.
208*01826a49SYabin Cui  */
ZSTD_DDictHashSet_addDDict(ZSTD_DDictHashSet * hashSet,const ZSTD_DDict * ddict,ZSTD_customMem customMem)209*01826a49SYabin Cui static size_t ZSTD_DDictHashSet_addDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict, ZSTD_customMem customMem) {
210*01826a49SYabin Cui     DEBUGLOG(4, "Adding dict ID: %u to hashset with - Count: %zu Tablesize: %zu", ZSTD_getDictID_fromDDict(ddict), hashSet->ddictPtrCount, hashSet->ddictPtrTableSize);
211*01826a49SYabin Cui     if (hashSet->ddictPtrCount * DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT / hashSet->ddictPtrTableSize * DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT != 0) {
212*01826a49SYabin Cui         FORWARD_IF_ERROR(ZSTD_DDictHashSet_expand(hashSet, customMem), "");
213*01826a49SYabin Cui     }
214*01826a49SYabin Cui     FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, ddict), "");
215*01826a49SYabin Cui     return 0;
216*01826a49SYabin Cui }
217*01826a49SYabin Cui 
218*01826a49SYabin Cui /*-*************************************************************
219*01826a49SYabin Cui *   Context management
220*01826a49SYabin Cui ***************************************************************/
ZSTD_sizeof_DCtx(const ZSTD_DCtx * dctx)221*01826a49SYabin Cui size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)
222*01826a49SYabin Cui {
223*01826a49SYabin Cui     if (dctx==NULL) return 0;   /* support sizeof NULL */
224*01826a49SYabin Cui     return sizeof(*dctx)
225*01826a49SYabin Cui            + ZSTD_sizeof_DDict(dctx->ddictLocal)
226*01826a49SYabin Cui            + dctx->inBuffSize + dctx->outBuffSize;
227*01826a49SYabin Cui }
228*01826a49SYabin Cui 
ZSTD_estimateDCtxSize(void)229*01826a49SYabin Cui size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }
230*01826a49SYabin Cui 
231*01826a49SYabin Cui 
ZSTD_startingInputLength(ZSTD_format_e format)232*01826a49SYabin Cui static size_t ZSTD_startingInputLength(ZSTD_format_e format)
233*01826a49SYabin Cui {
234*01826a49SYabin Cui     size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format);
235*01826a49SYabin Cui     /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */
236*01826a49SYabin Cui     assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );
237*01826a49SYabin Cui     return startingInputLength;
238*01826a49SYabin Cui }
239*01826a49SYabin Cui 
ZSTD_DCtx_resetParameters(ZSTD_DCtx * dctx)240*01826a49SYabin Cui static void ZSTD_DCtx_resetParameters(ZSTD_DCtx* dctx)
241*01826a49SYabin Cui {
242*01826a49SYabin Cui     assert(dctx->streamStage == zdss_init);
243*01826a49SYabin Cui     dctx->format = ZSTD_f_zstd1;
244*01826a49SYabin Cui     dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
245*01826a49SYabin Cui     dctx->outBufferMode = ZSTD_bm_buffered;
246*01826a49SYabin Cui     dctx->forceIgnoreChecksum = ZSTD_d_validateChecksum;
247*01826a49SYabin Cui     dctx->refMultipleDDicts = ZSTD_rmd_refSingleDDict;
248*01826a49SYabin Cui     dctx->disableHufAsm = 0;
249*01826a49SYabin Cui     dctx->maxBlockSizeParam = 0;
250*01826a49SYabin Cui }
251*01826a49SYabin Cui 
ZSTD_initDCtx_internal(ZSTD_DCtx * dctx)252*01826a49SYabin Cui static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)
253*01826a49SYabin Cui {
254*01826a49SYabin Cui     dctx->staticSize  = 0;
255*01826a49SYabin Cui     dctx->ddict       = NULL;
256*01826a49SYabin Cui     dctx->ddictLocal  = NULL;
257*01826a49SYabin Cui     dctx->dictEnd     = NULL;
258*01826a49SYabin Cui     dctx->ddictIsCold = 0;
259*01826a49SYabin Cui     dctx->dictUses = ZSTD_dont_use;
260*01826a49SYabin Cui     dctx->inBuff      = NULL;
261*01826a49SYabin Cui     dctx->inBuffSize  = 0;
262*01826a49SYabin Cui     dctx->outBuffSize = 0;
263*01826a49SYabin Cui     dctx->streamStage = zdss_init;
264*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
265*01826a49SYabin Cui     dctx->legacyContext = NULL;
266*01826a49SYabin Cui     dctx->previousLegacyVersion = 0;
267*01826a49SYabin Cui #endif
268*01826a49SYabin Cui     dctx->noForwardProgress = 0;
269*01826a49SYabin Cui     dctx->oversizedDuration = 0;
270*01826a49SYabin Cui     dctx->isFrameDecompression = 1;
271*01826a49SYabin Cui #if DYNAMIC_BMI2
272*01826a49SYabin Cui     dctx->bmi2 = ZSTD_cpuSupportsBmi2();
273*01826a49SYabin Cui #endif
274*01826a49SYabin Cui     dctx->ddictSet = NULL;
275*01826a49SYabin Cui     ZSTD_DCtx_resetParameters(dctx);
276*01826a49SYabin Cui #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
277*01826a49SYabin Cui     dctx->dictContentEndForFuzzing = NULL;
278*01826a49SYabin Cui #endif
279*01826a49SYabin Cui }
280*01826a49SYabin Cui 
ZSTD_initStaticDCtx(void * workspace,size_t workspaceSize)281*01826a49SYabin Cui ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)
282*01826a49SYabin Cui {
283*01826a49SYabin Cui     ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace;
284*01826a49SYabin Cui 
285*01826a49SYabin Cui     if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
286*01826a49SYabin Cui     if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL;  /* minimum size */
287*01826a49SYabin Cui 
288*01826a49SYabin Cui     ZSTD_initDCtx_internal(dctx);
289*01826a49SYabin Cui     dctx->staticSize = workspaceSize;
290*01826a49SYabin Cui     dctx->inBuff = (char*)(dctx+1);
291*01826a49SYabin Cui     return dctx;
292*01826a49SYabin Cui }
293*01826a49SYabin Cui 
ZSTD_createDCtx_internal(ZSTD_customMem customMem)294*01826a49SYabin Cui static ZSTD_DCtx* ZSTD_createDCtx_internal(ZSTD_customMem customMem) {
295*01826a49SYabin Cui     if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL;
296*01826a49SYabin Cui 
297*01826a49SYabin Cui     {   ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_customMalloc(sizeof(*dctx), customMem);
298*01826a49SYabin Cui         if (!dctx) return NULL;
299*01826a49SYabin Cui         dctx->customMem = customMem;
300*01826a49SYabin Cui         ZSTD_initDCtx_internal(dctx);
301*01826a49SYabin Cui         return dctx;
302*01826a49SYabin Cui     }
303*01826a49SYabin Cui }
304*01826a49SYabin Cui 
ZSTD_createDCtx_advanced(ZSTD_customMem customMem)305*01826a49SYabin Cui ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
306*01826a49SYabin Cui {
307*01826a49SYabin Cui     return ZSTD_createDCtx_internal(customMem);
308*01826a49SYabin Cui }
309*01826a49SYabin Cui 
ZSTD_createDCtx(void)310*01826a49SYabin Cui ZSTD_DCtx* ZSTD_createDCtx(void)
311*01826a49SYabin Cui {
312*01826a49SYabin Cui     DEBUGLOG(3, "ZSTD_createDCtx");
313*01826a49SYabin Cui     return ZSTD_createDCtx_internal(ZSTD_defaultCMem);
314*01826a49SYabin Cui }
315*01826a49SYabin Cui 
ZSTD_clearDict(ZSTD_DCtx * dctx)316*01826a49SYabin Cui static void ZSTD_clearDict(ZSTD_DCtx* dctx)
317*01826a49SYabin Cui {
318*01826a49SYabin Cui     ZSTD_freeDDict(dctx->ddictLocal);
319*01826a49SYabin Cui     dctx->ddictLocal = NULL;
320*01826a49SYabin Cui     dctx->ddict = NULL;
321*01826a49SYabin Cui     dctx->dictUses = ZSTD_dont_use;
322*01826a49SYabin Cui }
323*01826a49SYabin Cui 
ZSTD_freeDCtx(ZSTD_DCtx * dctx)324*01826a49SYabin Cui size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
325*01826a49SYabin Cui {
326*01826a49SYabin Cui     if (dctx==NULL) return 0;   /* support free on NULL */
327*01826a49SYabin Cui     RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx");
328*01826a49SYabin Cui     {   ZSTD_customMem const cMem = dctx->customMem;
329*01826a49SYabin Cui         ZSTD_clearDict(dctx);
330*01826a49SYabin Cui         ZSTD_customFree(dctx->inBuff, cMem);
331*01826a49SYabin Cui         dctx->inBuff = NULL;
332*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
333*01826a49SYabin Cui         if (dctx->legacyContext)
334*01826a49SYabin Cui             ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
335*01826a49SYabin Cui #endif
336*01826a49SYabin Cui         if (dctx->ddictSet) {
337*01826a49SYabin Cui             ZSTD_freeDDictHashSet(dctx->ddictSet, cMem);
338*01826a49SYabin Cui             dctx->ddictSet = NULL;
339*01826a49SYabin Cui         }
340*01826a49SYabin Cui         ZSTD_customFree(dctx, cMem);
341*01826a49SYabin Cui         return 0;
342*01826a49SYabin Cui     }
343*01826a49SYabin Cui }
344*01826a49SYabin Cui 
345*01826a49SYabin Cui /* no longer useful */
ZSTD_copyDCtx(ZSTD_DCtx * dstDCtx,const ZSTD_DCtx * srcDCtx)346*01826a49SYabin Cui void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)
347*01826a49SYabin Cui {
348*01826a49SYabin Cui     size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);
349*01826a49SYabin Cui     ZSTD_memcpy(dstDCtx, srcDCtx, toCopy);  /* no need to copy workspace */
350*01826a49SYabin Cui }
351*01826a49SYabin Cui 
352*01826a49SYabin Cui /* Given a dctx with a digested frame params, re-selects the correct ZSTD_DDict based on
353*01826a49SYabin Cui  * the requested dict ID from the frame. If there exists a reference to the correct ZSTD_DDict, then
354*01826a49SYabin Cui  * accordingly sets the ddict to be used to decompress the frame.
355*01826a49SYabin Cui  *
356*01826a49SYabin Cui  * If no DDict is found, then no action is taken, and the ZSTD_DCtx::ddict remains as-is.
357*01826a49SYabin Cui  *
358*01826a49SYabin Cui  * ZSTD_d_refMultipleDDicts must be enabled for this function to be called.
359*01826a49SYabin Cui  */
ZSTD_DCtx_selectFrameDDict(ZSTD_DCtx * dctx)360*01826a49SYabin Cui static void ZSTD_DCtx_selectFrameDDict(ZSTD_DCtx* dctx) {
361*01826a49SYabin Cui     assert(dctx->refMultipleDDicts && dctx->ddictSet);
362*01826a49SYabin Cui     DEBUGLOG(4, "Adjusting DDict based on requested dict ID from frame");
363*01826a49SYabin Cui     if (dctx->ddict) {
364*01826a49SYabin Cui         const ZSTD_DDict* frameDDict = ZSTD_DDictHashSet_getDDict(dctx->ddictSet, dctx->fParams.dictID);
365*01826a49SYabin Cui         if (frameDDict) {
366*01826a49SYabin Cui             DEBUGLOG(4, "DDict found!");
367*01826a49SYabin Cui             ZSTD_clearDict(dctx);
368*01826a49SYabin Cui             dctx->dictID = dctx->fParams.dictID;
369*01826a49SYabin Cui             dctx->ddict = frameDDict;
370*01826a49SYabin Cui             dctx->dictUses = ZSTD_use_indefinitely;
371*01826a49SYabin Cui         }
372*01826a49SYabin Cui     }
373*01826a49SYabin Cui }
374*01826a49SYabin Cui 
375*01826a49SYabin Cui 
376*01826a49SYabin Cui /*-*************************************************************
377*01826a49SYabin Cui  *   Frame header decoding
378*01826a49SYabin Cui  ***************************************************************/
379*01826a49SYabin Cui 
380*01826a49SYabin Cui /*! ZSTD_isFrame() :
381*01826a49SYabin Cui  *  Tells if the content of `buffer` starts with a valid Frame Identifier.
382*01826a49SYabin Cui  *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
383*01826a49SYabin Cui  *  Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
384*01826a49SYabin Cui  *  Note 3 : Skippable Frame Identifiers are considered valid. */
ZSTD_isFrame(const void * buffer,size_t size)385*01826a49SYabin Cui unsigned ZSTD_isFrame(const void* buffer, size_t size)
386*01826a49SYabin Cui {
387*01826a49SYabin Cui     if (size < ZSTD_FRAMEIDSIZE) return 0;
388*01826a49SYabin Cui     {   U32 const magic = MEM_readLE32(buffer);
389*01826a49SYabin Cui         if (magic == ZSTD_MAGICNUMBER) return 1;
390*01826a49SYabin Cui         if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
391*01826a49SYabin Cui     }
392*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
393*01826a49SYabin Cui     if (ZSTD_isLegacy(buffer, size)) return 1;
394*01826a49SYabin Cui #endif
395*01826a49SYabin Cui     return 0;
396*01826a49SYabin Cui }
397*01826a49SYabin Cui 
398*01826a49SYabin Cui /*! ZSTD_isSkippableFrame() :
399*01826a49SYabin Cui  *  Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame.
400*01826a49SYabin Cui  *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
401*01826a49SYabin Cui  */
ZSTD_isSkippableFrame(const void * buffer,size_t size)402*01826a49SYabin Cui unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size)
403*01826a49SYabin Cui {
404*01826a49SYabin Cui     if (size < ZSTD_FRAMEIDSIZE) return 0;
405*01826a49SYabin Cui     {   U32 const magic = MEM_readLE32(buffer);
406*01826a49SYabin Cui         if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
407*01826a49SYabin Cui     }
408*01826a49SYabin Cui     return 0;
409*01826a49SYabin Cui }
410*01826a49SYabin Cui 
411*01826a49SYabin Cui /** ZSTD_frameHeaderSize_internal() :
412*01826a49SYabin Cui  *  srcSize must be large enough to reach header size fields.
413*01826a49SYabin Cui  *  note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.
414*01826a49SYabin Cui  * @return : size of the Frame Header
415*01826a49SYabin Cui  *           or an error code, which can be tested with ZSTD_isError() */
ZSTD_frameHeaderSize_internal(const void * src,size_t srcSize,ZSTD_format_e format)416*01826a49SYabin Cui static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format)
417*01826a49SYabin Cui {
418*01826a49SYabin Cui     size_t const minInputSize = ZSTD_startingInputLength(format);
419*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, "");
420*01826a49SYabin Cui 
421*01826a49SYabin Cui     {   BYTE const fhd = ((const BYTE*)src)[minInputSize-1];
422*01826a49SYabin Cui         U32 const dictID= fhd & 3;
423*01826a49SYabin Cui         U32 const singleSegment = (fhd >> 5) & 1;
424*01826a49SYabin Cui         U32 const fcsId = fhd >> 6;
425*01826a49SYabin Cui         return minInputSize + !singleSegment
426*01826a49SYabin Cui              + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]
427*01826a49SYabin Cui              + (singleSegment && !fcsId);
428*01826a49SYabin Cui     }
429*01826a49SYabin Cui }
430*01826a49SYabin Cui 
431*01826a49SYabin Cui /** ZSTD_frameHeaderSize() :
432*01826a49SYabin Cui  *  srcSize must be >= ZSTD_frameHeaderSize_prefix.
433*01826a49SYabin Cui  * @return : size of the Frame Header,
434*01826a49SYabin Cui  *           or an error code (if srcSize is too small) */
ZSTD_frameHeaderSize(const void * src,size_t srcSize)435*01826a49SYabin Cui size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)
436*01826a49SYabin Cui {
437*01826a49SYabin Cui     return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1);
438*01826a49SYabin Cui }
439*01826a49SYabin Cui 
440*01826a49SYabin Cui 
441*01826a49SYabin Cui /** ZSTD_getFrameHeader_advanced() :
442*01826a49SYabin Cui  *  decode Frame Header, or require larger `srcSize`.
443*01826a49SYabin Cui  *  note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless
444*01826a49SYabin Cui  * @return : 0, `zfhPtr` is correctly filled,
445*01826a49SYabin Cui  *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
446*01826a49SYabin Cui **           or an error code, which can be tested using ZSTD_isError() */
ZSTD_getFrameHeader_advanced(ZSTD_frameHeader * zfhPtr,const void * src,size_t srcSize,ZSTD_format_e format)447*01826a49SYabin Cui size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format)
448*01826a49SYabin Cui {
449*01826a49SYabin Cui     const BYTE* ip = (const BYTE*)src;
450*01826a49SYabin Cui     size_t const minInputSize = ZSTD_startingInputLength(format);
451*01826a49SYabin Cui 
452*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_getFrameHeader_advanced: minInputSize = %zu, srcSize = %zu", minInputSize, srcSize);
453*01826a49SYabin Cui 
454*01826a49SYabin Cui     if (srcSize > 0) {
455*01826a49SYabin Cui         /* note : technically could be considered an assert(), since it's an invalid entry */
456*01826a49SYabin Cui         RETURN_ERROR_IF(src==NULL, GENERIC, "invalid parameter : src==NULL, but srcSize>0");
457*01826a49SYabin Cui     }
458*01826a49SYabin Cui     if (srcSize < minInputSize) {
459*01826a49SYabin Cui         if (srcSize > 0 && format != ZSTD_f_zstd1_magicless) {
460*01826a49SYabin Cui             /* when receiving less than @minInputSize bytes,
461*01826a49SYabin Cui              * control these bytes at least correspond to a supported magic number
462*01826a49SYabin Cui              * in order to error out early if they don't.
463*01826a49SYabin Cui             **/
464*01826a49SYabin Cui             size_t const toCopy = MIN(4, srcSize);
465*01826a49SYabin Cui             unsigned char hbuf[4]; MEM_writeLE32(hbuf, ZSTD_MAGICNUMBER);
466*01826a49SYabin Cui             assert(src != NULL);
467*01826a49SYabin Cui             ZSTD_memcpy(hbuf, src, toCopy);
468*01826a49SYabin Cui             if ( MEM_readLE32(hbuf) != ZSTD_MAGICNUMBER ) {
469*01826a49SYabin Cui                 /* not a zstd frame : let's check if it's a skippable frame */
470*01826a49SYabin Cui                 MEM_writeLE32(hbuf, ZSTD_MAGIC_SKIPPABLE_START);
471*01826a49SYabin Cui                 ZSTD_memcpy(hbuf, src, toCopy);
472*01826a49SYabin Cui                 if ((MEM_readLE32(hbuf) & ZSTD_MAGIC_SKIPPABLE_MASK) != ZSTD_MAGIC_SKIPPABLE_START) {
473*01826a49SYabin Cui                     RETURN_ERROR(prefix_unknown,
474*01826a49SYabin Cui                                 "first bytes don't correspond to any supported magic number");
475*01826a49SYabin Cui         }   }   }
476*01826a49SYabin Cui         return minInputSize;
477*01826a49SYabin Cui     }
478*01826a49SYabin Cui 
479*01826a49SYabin Cui     ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr));   /* not strictly necessary, but static analyzers may not understand that zfhPtr will be read only if return value is zero, since they are 2 different signals */
480*01826a49SYabin Cui     if ( (format != ZSTD_f_zstd1_magicless)
481*01826a49SYabin Cui       && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) {
482*01826a49SYabin Cui         if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
483*01826a49SYabin Cui             /* skippable frame */
484*01826a49SYabin Cui             if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
485*01826a49SYabin Cui                 return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */
486*01826a49SYabin Cui             ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr));
487*01826a49SYabin Cui             zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE);
488*01826a49SYabin Cui             zfhPtr->frameType = ZSTD_skippableFrame;
489*01826a49SYabin Cui             return 0;
490*01826a49SYabin Cui         }
491*01826a49SYabin Cui         RETURN_ERROR(prefix_unknown, "");
492*01826a49SYabin Cui     }
493*01826a49SYabin Cui 
494*01826a49SYabin Cui     /* ensure there is enough `srcSize` to fully read/decode frame header */
495*01826a49SYabin Cui     {   size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format);
496*01826a49SYabin Cui         if (srcSize < fhsize) return fhsize;
497*01826a49SYabin Cui         zfhPtr->headerSize = (U32)fhsize;
498*01826a49SYabin Cui     }
499*01826a49SYabin Cui 
500*01826a49SYabin Cui     {   BYTE const fhdByte = ip[minInputSize-1];
501*01826a49SYabin Cui         size_t pos = minInputSize;
502*01826a49SYabin Cui         U32 const dictIDSizeCode = fhdByte&3;
503*01826a49SYabin Cui         U32 const checksumFlag = (fhdByte>>2)&1;
504*01826a49SYabin Cui         U32 const singleSegment = (fhdByte>>5)&1;
505*01826a49SYabin Cui         U32 const fcsID = fhdByte>>6;
506*01826a49SYabin Cui         U64 windowSize = 0;
507*01826a49SYabin Cui         U32 dictID = 0;
508*01826a49SYabin Cui         U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;
509*01826a49SYabin Cui         RETURN_ERROR_IF((fhdByte & 0x08) != 0, frameParameter_unsupported,
510*01826a49SYabin Cui                         "reserved bits, must be zero");
511*01826a49SYabin Cui 
512*01826a49SYabin Cui         if (!singleSegment) {
513*01826a49SYabin Cui             BYTE const wlByte = ip[pos++];
514*01826a49SYabin Cui             U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
515*01826a49SYabin Cui             RETURN_ERROR_IF(windowLog > ZSTD_WINDOWLOG_MAX, frameParameter_windowTooLarge, "");
516*01826a49SYabin Cui             windowSize = (1ULL << windowLog);
517*01826a49SYabin Cui             windowSize += (windowSize >> 3) * (wlByte&7);
518*01826a49SYabin Cui         }
519*01826a49SYabin Cui         switch(dictIDSizeCode)
520*01826a49SYabin Cui         {
521*01826a49SYabin Cui             default:
522*01826a49SYabin Cui                 assert(0);  /* impossible */
523*01826a49SYabin Cui                 ZSTD_FALLTHROUGH;
524*01826a49SYabin Cui             case 0 : break;
525*01826a49SYabin Cui             case 1 : dictID = ip[pos]; pos++; break;
526*01826a49SYabin Cui             case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
527*01826a49SYabin Cui             case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
528*01826a49SYabin Cui         }
529*01826a49SYabin Cui         switch(fcsID)
530*01826a49SYabin Cui         {
531*01826a49SYabin Cui             default:
532*01826a49SYabin Cui                 assert(0);  /* impossible */
533*01826a49SYabin Cui                 ZSTD_FALLTHROUGH;
534*01826a49SYabin Cui             case 0 : if (singleSegment) frameContentSize = ip[pos]; break;
535*01826a49SYabin Cui             case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
536*01826a49SYabin Cui             case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
537*01826a49SYabin Cui             case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
538*01826a49SYabin Cui         }
539*01826a49SYabin Cui         if (singleSegment) windowSize = frameContentSize;
540*01826a49SYabin Cui 
541*01826a49SYabin Cui         zfhPtr->frameType = ZSTD_frame;
542*01826a49SYabin Cui         zfhPtr->frameContentSize = frameContentSize;
543*01826a49SYabin Cui         zfhPtr->windowSize = windowSize;
544*01826a49SYabin Cui         zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
545*01826a49SYabin Cui         zfhPtr->dictID = dictID;
546*01826a49SYabin Cui         zfhPtr->checksumFlag = checksumFlag;
547*01826a49SYabin Cui     }
548*01826a49SYabin Cui     return 0;
549*01826a49SYabin Cui }
550*01826a49SYabin Cui 
551*01826a49SYabin Cui /** ZSTD_getFrameHeader() :
552*01826a49SYabin Cui  *  decode Frame Header, or require larger `srcSize`.
553*01826a49SYabin Cui  *  note : this function does not consume input, it only reads it.
554*01826a49SYabin Cui  * @return : 0, `zfhPtr` is correctly filled,
555*01826a49SYabin Cui  *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
556*01826a49SYabin Cui  *           or an error code, which can be tested using ZSTD_isError() */
ZSTD_getFrameHeader(ZSTD_frameHeader * zfhPtr,const void * src,size_t srcSize)557*01826a49SYabin Cui size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)
558*01826a49SYabin Cui {
559*01826a49SYabin Cui     return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1);
560*01826a49SYabin Cui }
561*01826a49SYabin Cui 
562*01826a49SYabin Cui /** ZSTD_getFrameContentSize() :
563*01826a49SYabin Cui  *  compatible with legacy mode
564*01826a49SYabin Cui  * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
565*01826a49SYabin Cui  *         - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
566*01826a49SYabin Cui  *         - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
ZSTD_getFrameContentSize(const void * src,size_t srcSize)567*01826a49SYabin Cui unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
568*01826a49SYabin Cui {
569*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
570*01826a49SYabin Cui     if (ZSTD_isLegacy(src, srcSize)) {
571*01826a49SYabin Cui         unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
572*01826a49SYabin Cui         return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
573*01826a49SYabin Cui     }
574*01826a49SYabin Cui #endif
575*01826a49SYabin Cui     {   ZSTD_frameHeader zfh;
576*01826a49SYabin Cui         if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
577*01826a49SYabin Cui             return ZSTD_CONTENTSIZE_ERROR;
578*01826a49SYabin Cui         if (zfh.frameType == ZSTD_skippableFrame) {
579*01826a49SYabin Cui             return 0;
580*01826a49SYabin Cui         } else {
581*01826a49SYabin Cui             return zfh.frameContentSize;
582*01826a49SYabin Cui     }   }
583*01826a49SYabin Cui }
584*01826a49SYabin Cui 
readSkippableFrameSize(void const * src,size_t srcSize)585*01826a49SYabin Cui static size_t readSkippableFrameSize(void const* src, size_t srcSize)
586*01826a49SYabin Cui {
587*01826a49SYabin Cui     size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;
588*01826a49SYabin Cui     U32 sizeU32;
589*01826a49SYabin Cui 
590*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, "");
591*01826a49SYabin Cui 
592*01826a49SYabin Cui     sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);
593*01826a49SYabin Cui     RETURN_ERROR_IF((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32,
594*01826a49SYabin Cui                     frameParameter_unsupported, "");
595*01826a49SYabin Cui     {   size_t const skippableSize = skippableHeaderSize + sizeU32;
596*01826a49SYabin Cui         RETURN_ERROR_IF(skippableSize > srcSize, srcSize_wrong, "");
597*01826a49SYabin Cui         return skippableSize;
598*01826a49SYabin Cui     }
599*01826a49SYabin Cui }
600*01826a49SYabin Cui 
601*01826a49SYabin Cui /*! ZSTD_readSkippableFrame() :
602*01826a49SYabin Cui  * Retrieves content of a skippable frame, and writes it to dst buffer.
603*01826a49SYabin Cui  *
604*01826a49SYabin Cui  * The parameter magicVariant will receive the magicVariant that was supplied when the frame was written,
605*01826a49SYabin Cui  * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START.  This can be NULL if the caller is not interested
606*01826a49SYabin Cui  * in the magicVariant.
607*01826a49SYabin Cui  *
608*01826a49SYabin Cui  * Returns an error if destination buffer is not large enough, or if this is not a valid skippable frame.
609*01826a49SYabin Cui  *
610*01826a49SYabin Cui  * @return : number of bytes written or a ZSTD error.
611*01826a49SYabin Cui  */
ZSTD_readSkippableFrame(void * dst,size_t dstCapacity,unsigned * magicVariant,const void * src,size_t srcSize)612*01826a49SYabin Cui size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity,
613*01826a49SYabin Cui                                unsigned* magicVariant,  /* optional, can be NULL */
614*01826a49SYabin Cui                          const void* src, size_t srcSize)
615*01826a49SYabin Cui {
616*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, "");
617*01826a49SYabin Cui 
618*01826a49SYabin Cui     {   U32 const magicNumber = MEM_readLE32(src);
619*01826a49SYabin Cui         size_t skippableFrameSize = readSkippableFrameSize(src, srcSize);
620*01826a49SYabin Cui         size_t skippableContentSize = skippableFrameSize - ZSTD_SKIPPABLEHEADERSIZE;
621*01826a49SYabin Cui 
622*01826a49SYabin Cui         /* check input validity */
623*01826a49SYabin Cui         RETURN_ERROR_IF(!ZSTD_isSkippableFrame(src, srcSize), frameParameter_unsupported, "");
624*01826a49SYabin Cui         RETURN_ERROR_IF(skippableFrameSize < ZSTD_SKIPPABLEHEADERSIZE || skippableFrameSize > srcSize, srcSize_wrong, "");
625*01826a49SYabin Cui         RETURN_ERROR_IF(skippableContentSize > dstCapacity, dstSize_tooSmall, "");
626*01826a49SYabin Cui 
627*01826a49SYabin Cui         /* deliver payload */
628*01826a49SYabin Cui         if (skippableContentSize > 0  && dst != NULL)
629*01826a49SYabin Cui             ZSTD_memcpy(dst, (const BYTE *)src + ZSTD_SKIPPABLEHEADERSIZE, skippableContentSize);
630*01826a49SYabin Cui         if (magicVariant != NULL)
631*01826a49SYabin Cui             *magicVariant = magicNumber - ZSTD_MAGIC_SKIPPABLE_START;
632*01826a49SYabin Cui         return skippableContentSize;
633*01826a49SYabin Cui     }
634*01826a49SYabin Cui }
635*01826a49SYabin Cui 
636*01826a49SYabin Cui /** ZSTD_findDecompressedSize() :
637*01826a49SYabin Cui  *  `srcSize` must be the exact length of some number of ZSTD compressed and/or
638*01826a49SYabin Cui  *      skippable frames
639*01826a49SYabin Cui  *  note: compatible with legacy mode
640*01826a49SYabin Cui  * @return : decompressed size of the frames contained */
ZSTD_findDecompressedSize(const void * src,size_t srcSize)641*01826a49SYabin Cui unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)
642*01826a49SYabin Cui {
643*01826a49SYabin Cui     unsigned long long totalDstSize = 0;
644*01826a49SYabin Cui 
645*01826a49SYabin Cui     while (srcSize >= ZSTD_startingInputLength(ZSTD_f_zstd1)) {
646*01826a49SYabin Cui         U32 const magicNumber = MEM_readLE32(src);
647*01826a49SYabin Cui 
648*01826a49SYabin Cui         if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
649*01826a49SYabin Cui             size_t const skippableSize = readSkippableFrameSize(src, srcSize);
650*01826a49SYabin Cui             if (ZSTD_isError(skippableSize)) return ZSTD_CONTENTSIZE_ERROR;
651*01826a49SYabin Cui             assert(skippableSize <= srcSize);
652*01826a49SYabin Cui 
653*01826a49SYabin Cui             src = (const BYTE *)src + skippableSize;
654*01826a49SYabin Cui             srcSize -= skippableSize;
655*01826a49SYabin Cui             continue;
656*01826a49SYabin Cui         }
657*01826a49SYabin Cui 
658*01826a49SYabin Cui         {   unsigned long long const fcs = ZSTD_getFrameContentSize(src, srcSize);
659*01826a49SYabin Cui             if (fcs >= ZSTD_CONTENTSIZE_ERROR) return fcs;
660*01826a49SYabin Cui 
661*01826a49SYabin Cui             if (totalDstSize + fcs < totalDstSize)
662*01826a49SYabin Cui                 return ZSTD_CONTENTSIZE_ERROR; /* check for overflow */
663*01826a49SYabin Cui             totalDstSize += fcs;
664*01826a49SYabin Cui         }
665*01826a49SYabin Cui         /* skip to next frame */
666*01826a49SYabin Cui         {   size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
667*01826a49SYabin Cui             if (ZSTD_isError(frameSrcSize)) return ZSTD_CONTENTSIZE_ERROR;
668*01826a49SYabin Cui             assert(frameSrcSize <= srcSize);
669*01826a49SYabin Cui 
670*01826a49SYabin Cui             src = (const BYTE *)src + frameSrcSize;
671*01826a49SYabin Cui             srcSize -= frameSrcSize;
672*01826a49SYabin Cui         }
673*01826a49SYabin Cui     }  /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
674*01826a49SYabin Cui 
675*01826a49SYabin Cui     if (srcSize) return ZSTD_CONTENTSIZE_ERROR;
676*01826a49SYabin Cui 
677*01826a49SYabin Cui     return totalDstSize;
678*01826a49SYabin Cui }
679*01826a49SYabin Cui 
680*01826a49SYabin Cui /** ZSTD_getDecompressedSize() :
681*01826a49SYabin Cui  *  compatible with legacy mode
682*01826a49SYabin Cui  * @return : decompressed size if known, 0 otherwise
683*01826a49SYabin Cui              note : 0 can mean any of the following :
684*01826a49SYabin Cui                    - frame content is empty
685*01826a49SYabin Cui                    - decompressed size field is not present in frame header
686*01826a49SYabin Cui                    - frame header unknown / not supported
687*01826a49SYabin Cui                    - frame header not complete (`srcSize` too small) */
ZSTD_getDecompressedSize(const void * src,size_t srcSize)688*01826a49SYabin Cui unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)
689*01826a49SYabin Cui {
690*01826a49SYabin Cui     unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
691*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN);
692*01826a49SYabin Cui     return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret;
693*01826a49SYabin Cui }
694*01826a49SYabin Cui 
695*01826a49SYabin Cui 
696*01826a49SYabin Cui /** ZSTD_decodeFrameHeader() :
697*01826a49SYabin Cui  * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
698*01826a49SYabin Cui  * If multiple DDict references are enabled, also will choose the correct DDict to use.
699*01826a49SYabin Cui  * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
ZSTD_decodeFrameHeader(ZSTD_DCtx * dctx,const void * src,size_t headerSize)700*01826a49SYabin Cui static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)
701*01826a49SYabin Cui {
702*01826a49SYabin Cui     size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);
703*01826a49SYabin Cui     if (ZSTD_isError(result)) return result;    /* invalid header */
704*01826a49SYabin Cui     RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small");
705*01826a49SYabin Cui 
706*01826a49SYabin Cui     /* Reference DDict requested by frame if dctx references multiple ddicts */
707*01826a49SYabin Cui     if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts && dctx->ddictSet) {
708*01826a49SYabin Cui         ZSTD_DCtx_selectFrameDDict(dctx);
709*01826a49SYabin Cui     }
710*01826a49SYabin Cui 
711*01826a49SYabin Cui #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
712*01826a49SYabin Cui     /* Skip the dictID check in fuzzing mode, because it makes the search
713*01826a49SYabin Cui      * harder.
714*01826a49SYabin Cui      */
715*01826a49SYabin Cui     RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID),
716*01826a49SYabin Cui                     dictionary_wrong, "");
717*01826a49SYabin Cui #endif
718*01826a49SYabin Cui     dctx->validateChecksum = (dctx->fParams.checksumFlag && !dctx->forceIgnoreChecksum) ? 1 : 0;
719*01826a49SYabin Cui     if (dctx->validateChecksum) XXH64_reset(&dctx->xxhState, 0);
720*01826a49SYabin Cui     dctx->processedCSize += headerSize;
721*01826a49SYabin Cui     return 0;
722*01826a49SYabin Cui }
723*01826a49SYabin Cui 
ZSTD_errorFrameSizeInfo(size_t ret)724*01826a49SYabin Cui static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret)
725*01826a49SYabin Cui {
726*01826a49SYabin Cui     ZSTD_frameSizeInfo frameSizeInfo;
727*01826a49SYabin Cui     frameSizeInfo.compressedSize = ret;
728*01826a49SYabin Cui     frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
729*01826a49SYabin Cui     return frameSizeInfo;
730*01826a49SYabin Cui }
731*01826a49SYabin Cui 
ZSTD_findFrameSizeInfo(const void * src,size_t srcSize,ZSTD_format_e format)732*01826a49SYabin Cui static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize, ZSTD_format_e format)
733*01826a49SYabin Cui {
734*01826a49SYabin Cui     ZSTD_frameSizeInfo frameSizeInfo;
735*01826a49SYabin Cui     ZSTD_memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo));
736*01826a49SYabin Cui 
737*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
738*01826a49SYabin Cui     if (format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize))
739*01826a49SYabin Cui         return ZSTD_findFrameSizeInfoLegacy(src, srcSize);
740*01826a49SYabin Cui #endif
741*01826a49SYabin Cui 
742*01826a49SYabin Cui     if (format == ZSTD_f_zstd1 && (srcSize >= ZSTD_SKIPPABLEHEADERSIZE)
743*01826a49SYabin Cui         && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
744*01826a49SYabin Cui         frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize);
745*01826a49SYabin Cui         assert(ZSTD_isError(frameSizeInfo.compressedSize) ||
746*01826a49SYabin Cui                frameSizeInfo.compressedSize <= srcSize);
747*01826a49SYabin Cui         return frameSizeInfo;
748*01826a49SYabin Cui     } else {
749*01826a49SYabin Cui         const BYTE* ip = (const BYTE*)src;
750*01826a49SYabin Cui         const BYTE* const ipstart = ip;
751*01826a49SYabin Cui         size_t remainingSize = srcSize;
752*01826a49SYabin Cui         size_t nbBlocks = 0;
753*01826a49SYabin Cui         ZSTD_frameHeader zfh;
754*01826a49SYabin Cui 
755*01826a49SYabin Cui         /* Extract Frame Header */
756*01826a49SYabin Cui         {   size_t const ret = ZSTD_getFrameHeader_advanced(&zfh, src, srcSize, format);
757*01826a49SYabin Cui             if (ZSTD_isError(ret))
758*01826a49SYabin Cui                 return ZSTD_errorFrameSizeInfo(ret);
759*01826a49SYabin Cui             if (ret > 0)
760*01826a49SYabin Cui                 return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
761*01826a49SYabin Cui         }
762*01826a49SYabin Cui 
763*01826a49SYabin Cui         ip += zfh.headerSize;
764*01826a49SYabin Cui         remainingSize -= zfh.headerSize;
765*01826a49SYabin Cui 
766*01826a49SYabin Cui         /* Iterate over each block */
767*01826a49SYabin Cui         while (1) {
768*01826a49SYabin Cui             blockProperties_t blockProperties;
769*01826a49SYabin Cui             size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
770*01826a49SYabin Cui             if (ZSTD_isError(cBlockSize))
771*01826a49SYabin Cui                 return ZSTD_errorFrameSizeInfo(cBlockSize);
772*01826a49SYabin Cui 
773*01826a49SYabin Cui             if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
774*01826a49SYabin Cui                 return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
775*01826a49SYabin Cui 
776*01826a49SYabin Cui             ip += ZSTD_blockHeaderSize + cBlockSize;
777*01826a49SYabin Cui             remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
778*01826a49SYabin Cui             nbBlocks++;
779*01826a49SYabin Cui 
780*01826a49SYabin Cui             if (blockProperties.lastBlock) break;
781*01826a49SYabin Cui         }
782*01826a49SYabin Cui 
783*01826a49SYabin Cui         /* Final frame content checksum */
784*01826a49SYabin Cui         if (zfh.checksumFlag) {
785*01826a49SYabin Cui             if (remainingSize < 4)
786*01826a49SYabin Cui                 return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
787*01826a49SYabin Cui             ip += 4;
788*01826a49SYabin Cui         }
789*01826a49SYabin Cui 
790*01826a49SYabin Cui         frameSizeInfo.nbBlocks = nbBlocks;
791*01826a49SYabin Cui         frameSizeInfo.compressedSize = (size_t)(ip - ipstart);
792*01826a49SYabin Cui         frameSizeInfo.decompressedBound = (zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN)
793*01826a49SYabin Cui                                         ? zfh.frameContentSize
794*01826a49SYabin Cui                                         : (unsigned long long)nbBlocks * zfh.blockSizeMax;
795*01826a49SYabin Cui         return frameSizeInfo;
796*01826a49SYabin Cui     }
797*01826a49SYabin Cui }
798*01826a49SYabin Cui 
ZSTD_findFrameCompressedSize_advanced(const void * src,size_t srcSize,ZSTD_format_e format)799*01826a49SYabin Cui static size_t ZSTD_findFrameCompressedSize_advanced(const void *src, size_t srcSize, ZSTD_format_e format) {
800*01826a49SYabin Cui     ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, format);
801*01826a49SYabin Cui     return frameSizeInfo.compressedSize;
802*01826a49SYabin Cui }
803*01826a49SYabin Cui 
804*01826a49SYabin Cui /** ZSTD_findFrameCompressedSize() :
805*01826a49SYabin Cui  * See docs in zstd.h
806*01826a49SYabin Cui  * Note: compatible with legacy mode */
ZSTD_findFrameCompressedSize(const void * src,size_t srcSize)807*01826a49SYabin Cui size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
808*01826a49SYabin Cui {
809*01826a49SYabin Cui     return ZSTD_findFrameCompressedSize_advanced(src, srcSize, ZSTD_f_zstd1);
810*01826a49SYabin Cui }
811*01826a49SYabin Cui 
812*01826a49SYabin Cui /** ZSTD_decompressBound() :
813*01826a49SYabin Cui  *  compatible with legacy mode
814*01826a49SYabin Cui  *  `src` must point to the start of a ZSTD frame or a skippeable frame
815*01826a49SYabin Cui  *  `srcSize` must be at least as large as the frame contained
816*01826a49SYabin Cui  *  @return : the maximum decompressed size of the compressed source
817*01826a49SYabin Cui  */
ZSTD_decompressBound(const void * src,size_t srcSize)818*01826a49SYabin Cui unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize)
819*01826a49SYabin Cui {
820*01826a49SYabin Cui     unsigned long long bound = 0;
821*01826a49SYabin Cui     /* Iterate over each frame */
822*01826a49SYabin Cui     while (srcSize > 0) {
823*01826a49SYabin Cui         ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1);
824*01826a49SYabin Cui         size_t const compressedSize = frameSizeInfo.compressedSize;
825*01826a49SYabin Cui         unsigned long long const decompressedBound = frameSizeInfo.decompressedBound;
826*01826a49SYabin Cui         if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR)
827*01826a49SYabin Cui             return ZSTD_CONTENTSIZE_ERROR;
828*01826a49SYabin Cui         assert(srcSize >= compressedSize);
829*01826a49SYabin Cui         src = (const BYTE*)src + compressedSize;
830*01826a49SYabin Cui         srcSize -= compressedSize;
831*01826a49SYabin Cui         bound += decompressedBound;
832*01826a49SYabin Cui     }
833*01826a49SYabin Cui     return bound;
834*01826a49SYabin Cui }
835*01826a49SYabin Cui 
ZSTD_decompressionMargin(void const * src,size_t srcSize)836*01826a49SYabin Cui size_t ZSTD_decompressionMargin(void const* src, size_t srcSize)
837*01826a49SYabin Cui {
838*01826a49SYabin Cui     size_t margin = 0;
839*01826a49SYabin Cui     unsigned maxBlockSize = 0;
840*01826a49SYabin Cui 
841*01826a49SYabin Cui     /* Iterate over each frame */
842*01826a49SYabin Cui     while (srcSize > 0) {
843*01826a49SYabin Cui         ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1);
844*01826a49SYabin Cui         size_t const compressedSize = frameSizeInfo.compressedSize;
845*01826a49SYabin Cui         unsigned long long const decompressedBound = frameSizeInfo.decompressedBound;
846*01826a49SYabin Cui         ZSTD_frameHeader zfh;
847*01826a49SYabin Cui 
848*01826a49SYabin Cui         FORWARD_IF_ERROR(ZSTD_getFrameHeader(&zfh, src, srcSize), "");
849*01826a49SYabin Cui         if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR)
850*01826a49SYabin Cui             return ERROR(corruption_detected);
851*01826a49SYabin Cui 
852*01826a49SYabin Cui         if (zfh.frameType == ZSTD_frame) {
853*01826a49SYabin Cui             /* Add the frame header to our margin */
854*01826a49SYabin Cui             margin += zfh.headerSize;
855*01826a49SYabin Cui             /* Add the checksum to our margin */
856*01826a49SYabin Cui             margin += zfh.checksumFlag ? 4 : 0;
857*01826a49SYabin Cui             /* Add 3 bytes per block */
858*01826a49SYabin Cui             margin += 3 * frameSizeInfo.nbBlocks;
859*01826a49SYabin Cui 
860*01826a49SYabin Cui             /* Compute the max block size */
861*01826a49SYabin Cui             maxBlockSize = MAX(maxBlockSize, zfh.blockSizeMax);
862*01826a49SYabin Cui         } else {
863*01826a49SYabin Cui             assert(zfh.frameType == ZSTD_skippableFrame);
864*01826a49SYabin Cui             /* Add the entire skippable frame size to our margin. */
865*01826a49SYabin Cui             margin += compressedSize;
866*01826a49SYabin Cui         }
867*01826a49SYabin Cui 
868*01826a49SYabin Cui         assert(srcSize >= compressedSize);
869*01826a49SYabin Cui         src = (const BYTE*)src + compressedSize;
870*01826a49SYabin Cui         srcSize -= compressedSize;
871*01826a49SYabin Cui     }
872*01826a49SYabin Cui 
873*01826a49SYabin Cui     /* Add the max block size back to the margin. */
874*01826a49SYabin Cui     margin += maxBlockSize;
875*01826a49SYabin Cui 
876*01826a49SYabin Cui     return margin;
877*01826a49SYabin Cui }
878*01826a49SYabin Cui 
879*01826a49SYabin Cui /*-*************************************************************
880*01826a49SYabin Cui  *   Frame decoding
881*01826a49SYabin Cui  ***************************************************************/
882*01826a49SYabin Cui 
883*01826a49SYabin Cui /** ZSTD_insertBlock() :
884*01826a49SYabin Cui  *  insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
ZSTD_insertBlock(ZSTD_DCtx * dctx,const void * blockStart,size_t blockSize)885*01826a49SYabin Cui size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)
886*01826a49SYabin Cui {
887*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize);
888*01826a49SYabin Cui     ZSTD_checkContinuity(dctx, blockStart, blockSize);
889*01826a49SYabin Cui     dctx->previousDstEnd = (const char*)blockStart + blockSize;
890*01826a49SYabin Cui     return blockSize;
891*01826a49SYabin Cui }
892*01826a49SYabin Cui 
893*01826a49SYabin Cui 
ZSTD_copyRawBlock(void * dst,size_t dstCapacity,const void * src,size_t srcSize)894*01826a49SYabin Cui static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
895*01826a49SYabin Cui                           const void* src, size_t srcSize)
896*01826a49SYabin Cui {
897*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_copyRawBlock");
898*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, "");
899*01826a49SYabin Cui     if (dst == NULL) {
900*01826a49SYabin Cui         if (srcSize == 0) return 0;
901*01826a49SYabin Cui         RETURN_ERROR(dstBuffer_null, "");
902*01826a49SYabin Cui     }
903*01826a49SYabin Cui     ZSTD_memmove(dst, src, srcSize);
904*01826a49SYabin Cui     return srcSize;
905*01826a49SYabin Cui }
906*01826a49SYabin Cui 
ZSTD_setRleBlock(void * dst,size_t dstCapacity,BYTE b,size_t regenSize)907*01826a49SYabin Cui static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,
908*01826a49SYabin Cui                                BYTE b,
909*01826a49SYabin Cui                                size_t regenSize)
910*01826a49SYabin Cui {
911*01826a49SYabin Cui     RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, "");
912*01826a49SYabin Cui     if (dst == NULL) {
913*01826a49SYabin Cui         if (regenSize == 0) return 0;
914*01826a49SYabin Cui         RETURN_ERROR(dstBuffer_null, "");
915*01826a49SYabin Cui     }
916*01826a49SYabin Cui     ZSTD_memset(dst, b, regenSize);
917*01826a49SYabin Cui     return regenSize;
918*01826a49SYabin Cui }
919*01826a49SYabin Cui 
ZSTD_DCtx_trace_end(ZSTD_DCtx const * dctx,U64 uncompressedSize,U64 compressedSize,unsigned streaming)920*01826a49SYabin Cui static void ZSTD_DCtx_trace_end(ZSTD_DCtx const* dctx, U64 uncompressedSize, U64 compressedSize, unsigned streaming)
921*01826a49SYabin Cui {
922*01826a49SYabin Cui #if ZSTD_TRACE
923*01826a49SYabin Cui     if (dctx->traceCtx && ZSTD_trace_decompress_end != NULL) {
924*01826a49SYabin Cui         ZSTD_Trace trace;
925*01826a49SYabin Cui         ZSTD_memset(&trace, 0, sizeof(trace));
926*01826a49SYabin Cui         trace.version = ZSTD_VERSION_NUMBER;
927*01826a49SYabin Cui         trace.streaming = streaming;
928*01826a49SYabin Cui         if (dctx->ddict) {
929*01826a49SYabin Cui             trace.dictionaryID = ZSTD_getDictID_fromDDict(dctx->ddict);
930*01826a49SYabin Cui             trace.dictionarySize = ZSTD_DDict_dictSize(dctx->ddict);
931*01826a49SYabin Cui             trace.dictionaryIsCold = dctx->ddictIsCold;
932*01826a49SYabin Cui         }
933*01826a49SYabin Cui         trace.uncompressedSize = (size_t)uncompressedSize;
934*01826a49SYabin Cui         trace.compressedSize = (size_t)compressedSize;
935*01826a49SYabin Cui         trace.dctx = dctx;
936*01826a49SYabin Cui         ZSTD_trace_decompress_end(dctx->traceCtx, &trace);
937*01826a49SYabin Cui     }
938*01826a49SYabin Cui #else
939*01826a49SYabin Cui     (void)dctx;
940*01826a49SYabin Cui     (void)uncompressedSize;
941*01826a49SYabin Cui     (void)compressedSize;
942*01826a49SYabin Cui     (void)streaming;
943*01826a49SYabin Cui #endif
944*01826a49SYabin Cui }
945*01826a49SYabin Cui 
946*01826a49SYabin Cui 
947*01826a49SYabin Cui /*! ZSTD_decompressFrame() :
948*01826a49SYabin Cui  * @dctx must be properly initialized
949*01826a49SYabin Cui  *  will update *srcPtr and *srcSizePtr,
950*01826a49SYabin Cui  *  to make *srcPtr progress by one frame. */
ZSTD_decompressFrame(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void ** srcPtr,size_t * srcSizePtr)951*01826a49SYabin Cui static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
952*01826a49SYabin Cui                                    void* dst, size_t dstCapacity,
953*01826a49SYabin Cui                              const void** srcPtr, size_t *srcSizePtr)
954*01826a49SYabin Cui {
955*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*)(*srcPtr);
956*01826a49SYabin Cui     const BYTE* ip = istart;
957*01826a49SYabin Cui     BYTE* const ostart = (BYTE*)dst;
958*01826a49SYabin Cui     BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart;
959*01826a49SYabin Cui     BYTE* op = ostart;
960*01826a49SYabin Cui     size_t remainingSrcSize = *srcSizePtr;
961*01826a49SYabin Cui 
962*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);
963*01826a49SYabin Cui 
964*01826a49SYabin Cui     /* check */
965*01826a49SYabin Cui     RETURN_ERROR_IF(
966*01826a49SYabin Cui         remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize,
967*01826a49SYabin Cui         srcSize_wrong, "");
968*01826a49SYabin Cui 
969*01826a49SYabin Cui     /* Frame Header */
970*01826a49SYabin Cui     {   size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal(
971*01826a49SYabin Cui                 ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format);
972*01826a49SYabin Cui         if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
973*01826a49SYabin Cui         RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize,
974*01826a49SYabin Cui                         srcSize_wrong, "");
975*01826a49SYabin Cui         FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , "");
976*01826a49SYabin Cui         ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;
977*01826a49SYabin Cui     }
978*01826a49SYabin Cui 
979*01826a49SYabin Cui     /* Shrink the blockSizeMax if enabled */
980*01826a49SYabin Cui     if (dctx->maxBlockSizeParam != 0)
981*01826a49SYabin Cui         dctx->fParams.blockSizeMax = MIN(dctx->fParams.blockSizeMax, (unsigned)dctx->maxBlockSizeParam);
982*01826a49SYabin Cui 
983*01826a49SYabin Cui     /* Loop on each block */
984*01826a49SYabin Cui     while (1) {
985*01826a49SYabin Cui         BYTE* oBlockEnd = oend;
986*01826a49SYabin Cui         size_t decodedSize;
987*01826a49SYabin Cui         blockProperties_t blockProperties;
988*01826a49SYabin Cui         size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);
989*01826a49SYabin Cui         if (ZSTD_isError(cBlockSize)) return cBlockSize;
990*01826a49SYabin Cui 
991*01826a49SYabin Cui         ip += ZSTD_blockHeaderSize;
992*01826a49SYabin Cui         remainingSrcSize -= ZSTD_blockHeaderSize;
993*01826a49SYabin Cui         RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, "");
994*01826a49SYabin Cui 
995*01826a49SYabin Cui         if (ip >= op && ip < oBlockEnd) {
996*01826a49SYabin Cui             /* We are decompressing in-place. Limit the output pointer so that we
997*01826a49SYabin Cui              * don't overwrite the block that we are currently reading. This will
998*01826a49SYabin Cui              * fail decompression if the input & output pointers aren't spaced
999*01826a49SYabin Cui              * far enough apart.
1000*01826a49SYabin Cui              *
1001*01826a49SYabin Cui              * This is important to set, even when the pointers are far enough
1002*01826a49SYabin Cui              * apart, because ZSTD_decompressBlock_internal() can decide to store
1003*01826a49SYabin Cui              * literals in the output buffer, after the block it is decompressing.
1004*01826a49SYabin Cui              * Since we don't want anything to overwrite our input, we have to tell
1005*01826a49SYabin Cui              * ZSTD_decompressBlock_internal to never write past ip.
1006*01826a49SYabin Cui              *
1007*01826a49SYabin Cui              * See ZSTD_allocateLiteralsBuffer() for reference.
1008*01826a49SYabin Cui              */
1009*01826a49SYabin Cui             oBlockEnd = op + (ip - op);
1010*01826a49SYabin Cui         }
1011*01826a49SYabin Cui 
1012*01826a49SYabin Cui         switch(blockProperties.blockType)
1013*01826a49SYabin Cui         {
1014*01826a49SYabin Cui         case bt_compressed:
1015*01826a49SYabin Cui             assert(dctx->isFrameDecompression == 1);
1016*01826a49SYabin Cui             decodedSize = ZSTD_decompressBlock_internal(dctx, op, (size_t)(oBlockEnd-op), ip, cBlockSize, not_streaming);
1017*01826a49SYabin Cui             break;
1018*01826a49SYabin Cui         case bt_raw :
1019*01826a49SYabin Cui             /* Use oend instead of oBlockEnd because this function is safe to overlap. It uses memmove. */
1020*01826a49SYabin Cui             decodedSize = ZSTD_copyRawBlock(op, (size_t)(oend-op), ip, cBlockSize);
1021*01826a49SYabin Cui             break;
1022*01826a49SYabin Cui         case bt_rle :
1023*01826a49SYabin Cui             decodedSize = ZSTD_setRleBlock(op, (size_t)(oBlockEnd-op), *ip, blockProperties.origSize);
1024*01826a49SYabin Cui             break;
1025*01826a49SYabin Cui         case bt_reserved :
1026*01826a49SYabin Cui         default:
1027*01826a49SYabin Cui             RETURN_ERROR(corruption_detected, "invalid block type");
1028*01826a49SYabin Cui         }
1029*01826a49SYabin Cui         FORWARD_IF_ERROR(decodedSize, "Block decompression failure");
1030*01826a49SYabin Cui         DEBUGLOG(5, "Decompressed block of dSize = %u", (unsigned)decodedSize);
1031*01826a49SYabin Cui         if (dctx->validateChecksum) {
1032*01826a49SYabin Cui             XXH64_update(&dctx->xxhState, op, decodedSize);
1033*01826a49SYabin Cui         }
1034*01826a49SYabin Cui         if (decodedSize) /* support dst = NULL,0 */ {
1035*01826a49SYabin Cui             op += decodedSize;
1036*01826a49SYabin Cui         }
1037*01826a49SYabin Cui         assert(ip != NULL);
1038*01826a49SYabin Cui         ip += cBlockSize;
1039*01826a49SYabin Cui         remainingSrcSize -= cBlockSize;
1040*01826a49SYabin Cui         if (blockProperties.lastBlock) break;
1041*01826a49SYabin Cui     }
1042*01826a49SYabin Cui 
1043*01826a49SYabin Cui     if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
1044*01826a49SYabin Cui         RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize,
1045*01826a49SYabin Cui                         corruption_detected, "");
1046*01826a49SYabin Cui     }
1047*01826a49SYabin Cui     if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
1048*01826a49SYabin Cui         RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, "");
1049*01826a49SYabin Cui         if (!dctx->forceIgnoreChecksum) {
1050*01826a49SYabin Cui             U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
1051*01826a49SYabin Cui             U32 checkRead;
1052*01826a49SYabin Cui             checkRead = MEM_readLE32(ip);
1053*01826a49SYabin Cui             RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, "");
1054*01826a49SYabin Cui         }
1055*01826a49SYabin Cui         ip += 4;
1056*01826a49SYabin Cui         remainingSrcSize -= 4;
1057*01826a49SYabin Cui     }
1058*01826a49SYabin Cui     ZSTD_DCtx_trace_end(dctx, (U64)(op-ostart), (U64)(ip-istart), /* streaming */ 0);
1059*01826a49SYabin Cui     /* Allow caller to get size read */
1060*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_decompressFrame: decompressed frame of size %zi, consuming %zi bytes of input", op-ostart, ip - (const BYTE*)*srcPtr);
1061*01826a49SYabin Cui     *srcPtr = ip;
1062*01826a49SYabin Cui     *srcSizePtr = remainingSrcSize;
1063*01826a49SYabin Cui     return (size_t)(op-ostart);
1064*01826a49SYabin Cui }
1065*01826a49SYabin Cui 
1066*01826a49SYabin Cui static
1067*01826a49SYabin Cui ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
ZSTD_decompressMultiFrame(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize,const ZSTD_DDict * ddict)1068*01826a49SYabin Cui size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
1069*01826a49SYabin Cui                                         void* dst, size_t dstCapacity,
1070*01826a49SYabin Cui                                   const void* src, size_t srcSize,
1071*01826a49SYabin Cui                                   const void* dict, size_t dictSize,
1072*01826a49SYabin Cui                                   const ZSTD_DDict* ddict)
1073*01826a49SYabin Cui {
1074*01826a49SYabin Cui     void* const dststart = dst;
1075*01826a49SYabin Cui     int moreThan1Frame = 0;
1076*01826a49SYabin Cui 
1077*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_decompressMultiFrame");
1078*01826a49SYabin Cui     assert(dict==NULL || ddict==NULL);  /* either dict or ddict set, not both */
1079*01826a49SYabin Cui 
1080*01826a49SYabin Cui     if (ddict) {
1081*01826a49SYabin Cui         dict = ZSTD_DDict_dictContent(ddict);
1082*01826a49SYabin Cui         dictSize = ZSTD_DDict_dictSize(ddict);
1083*01826a49SYabin Cui     }
1084*01826a49SYabin Cui 
1085*01826a49SYabin Cui     while (srcSize >= ZSTD_startingInputLength(dctx->format)) {
1086*01826a49SYabin Cui 
1087*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
1088*01826a49SYabin Cui         if (dctx->format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) {
1089*01826a49SYabin Cui             size_t decodedSize;
1090*01826a49SYabin Cui             size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
1091*01826a49SYabin Cui             if (ZSTD_isError(frameSize)) return frameSize;
1092*01826a49SYabin Cui             RETURN_ERROR_IF(dctx->staticSize, memory_allocation,
1093*01826a49SYabin Cui                 "legacy support is not compatible with static dctx");
1094*01826a49SYabin Cui 
1095*01826a49SYabin Cui             decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
1096*01826a49SYabin Cui             if (ZSTD_isError(decodedSize)) return decodedSize;
1097*01826a49SYabin Cui 
1098*01826a49SYabin Cui             {
1099*01826a49SYabin Cui                 unsigned long long const expectedSize = ZSTD_getFrameContentSize(src, srcSize);
1100*01826a49SYabin Cui                 RETURN_ERROR_IF(expectedSize == ZSTD_CONTENTSIZE_ERROR, corruption_detected, "Corrupted frame header!");
1101*01826a49SYabin Cui                 if (expectedSize != ZSTD_CONTENTSIZE_UNKNOWN) {
1102*01826a49SYabin Cui                     RETURN_ERROR_IF(expectedSize != decodedSize, corruption_detected,
1103*01826a49SYabin Cui                         "Frame header size does not match decoded size!");
1104*01826a49SYabin Cui                 }
1105*01826a49SYabin Cui             }
1106*01826a49SYabin Cui 
1107*01826a49SYabin Cui             assert(decodedSize <= dstCapacity);
1108*01826a49SYabin Cui             dst = (BYTE*)dst + decodedSize;
1109*01826a49SYabin Cui             dstCapacity -= decodedSize;
1110*01826a49SYabin Cui 
1111*01826a49SYabin Cui             src = (const BYTE*)src + frameSize;
1112*01826a49SYabin Cui             srcSize -= frameSize;
1113*01826a49SYabin Cui 
1114*01826a49SYabin Cui             continue;
1115*01826a49SYabin Cui         }
1116*01826a49SYabin Cui #endif
1117*01826a49SYabin Cui 
1118*01826a49SYabin Cui         if (dctx->format == ZSTD_f_zstd1 && srcSize >= 4) {
1119*01826a49SYabin Cui             U32 const magicNumber = MEM_readLE32(src);
1120*01826a49SYabin Cui             DEBUGLOG(5, "reading magic number %08X", (unsigned)magicNumber);
1121*01826a49SYabin Cui             if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
1122*01826a49SYabin Cui                 /* skippable frame detected : skip it */
1123*01826a49SYabin Cui                 size_t const skippableSize = readSkippableFrameSize(src, srcSize);
1124*01826a49SYabin Cui                 FORWARD_IF_ERROR(skippableSize, "invalid skippable frame");
1125*01826a49SYabin Cui                 assert(skippableSize <= srcSize);
1126*01826a49SYabin Cui 
1127*01826a49SYabin Cui                 src = (const BYTE *)src + skippableSize;
1128*01826a49SYabin Cui                 srcSize -= skippableSize;
1129*01826a49SYabin Cui                 continue; /* check next frame */
1130*01826a49SYabin Cui         }   }
1131*01826a49SYabin Cui 
1132*01826a49SYabin Cui         if (ddict) {
1133*01826a49SYabin Cui             /* we were called from ZSTD_decompress_usingDDict */
1134*01826a49SYabin Cui             FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), "");
1135*01826a49SYabin Cui         } else {
1136*01826a49SYabin Cui             /* this will initialize correctly with no dict if dict == NULL, so
1137*01826a49SYabin Cui              * use this in all cases but ddict */
1138*01826a49SYabin Cui             FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), "");
1139*01826a49SYabin Cui         }
1140*01826a49SYabin Cui         ZSTD_checkContinuity(dctx, dst, dstCapacity);
1141*01826a49SYabin Cui 
1142*01826a49SYabin Cui         {   const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
1143*01826a49SYabin Cui                                                     &src, &srcSize);
1144*01826a49SYabin Cui             RETURN_ERROR_IF(
1145*01826a49SYabin Cui                 (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)
1146*01826a49SYabin Cui              && (moreThan1Frame==1),
1147*01826a49SYabin Cui                 srcSize_wrong,
1148*01826a49SYabin Cui                 "At least one frame successfully completed, "
1149*01826a49SYabin Cui                 "but following bytes are garbage: "
1150*01826a49SYabin Cui                 "it's more likely to be a srcSize error, "
1151*01826a49SYabin Cui                 "specifying more input bytes than size of frame(s). "
1152*01826a49SYabin Cui                 "Note: one could be unlucky, it might be a corruption error instead, "
1153*01826a49SYabin Cui                 "happening right at the place where we expect zstd magic bytes. "
1154*01826a49SYabin Cui                 "But this is _much_ less likely than a srcSize field error.");
1155*01826a49SYabin Cui             if (ZSTD_isError(res)) return res;
1156*01826a49SYabin Cui             assert(res <= dstCapacity);
1157*01826a49SYabin Cui             if (res != 0)
1158*01826a49SYabin Cui                 dst = (BYTE*)dst + res;
1159*01826a49SYabin Cui             dstCapacity -= res;
1160*01826a49SYabin Cui         }
1161*01826a49SYabin Cui         moreThan1Frame = 1;
1162*01826a49SYabin Cui     }  /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
1163*01826a49SYabin Cui 
1164*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize, srcSize_wrong, "input not entirely consumed");
1165*01826a49SYabin Cui 
1166*01826a49SYabin Cui     return (size_t)((BYTE*)dst - (BYTE*)dststart);
1167*01826a49SYabin Cui }
1168*01826a49SYabin Cui 
ZSTD_decompress_usingDict(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize)1169*01826a49SYabin Cui size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
1170*01826a49SYabin Cui                                  void* dst, size_t dstCapacity,
1171*01826a49SYabin Cui                            const void* src, size_t srcSize,
1172*01826a49SYabin Cui                            const void* dict, size_t dictSize)
1173*01826a49SYabin Cui {
1174*01826a49SYabin Cui     return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
1175*01826a49SYabin Cui }
1176*01826a49SYabin Cui 
1177*01826a49SYabin Cui 
ZSTD_getDDict(ZSTD_DCtx * dctx)1178*01826a49SYabin Cui static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx)
1179*01826a49SYabin Cui {
1180*01826a49SYabin Cui     switch (dctx->dictUses) {
1181*01826a49SYabin Cui     default:
1182*01826a49SYabin Cui         assert(0 /* Impossible */);
1183*01826a49SYabin Cui         ZSTD_FALLTHROUGH;
1184*01826a49SYabin Cui     case ZSTD_dont_use:
1185*01826a49SYabin Cui         ZSTD_clearDict(dctx);
1186*01826a49SYabin Cui         return NULL;
1187*01826a49SYabin Cui     case ZSTD_use_indefinitely:
1188*01826a49SYabin Cui         return dctx->ddict;
1189*01826a49SYabin Cui     case ZSTD_use_once:
1190*01826a49SYabin Cui         dctx->dictUses = ZSTD_dont_use;
1191*01826a49SYabin Cui         return dctx->ddict;
1192*01826a49SYabin Cui     }
1193*01826a49SYabin Cui }
1194*01826a49SYabin Cui 
ZSTD_decompressDCtx(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)1195*01826a49SYabin Cui size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
1196*01826a49SYabin Cui {
1197*01826a49SYabin Cui     return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx));
1198*01826a49SYabin Cui }
1199*01826a49SYabin Cui 
1200*01826a49SYabin Cui 
ZSTD_decompress(void * dst,size_t dstCapacity,const void * src,size_t srcSize)1201*01826a49SYabin Cui size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
1202*01826a49SYabin Cui {
1203*01826a49SYabin Cui #if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
1204*01826a49SYabin Cui     size_t regenSize;
1205*01826a49SYabin Cui     ZSTD_DCtx* const dctx =  ZSTD_createDCtx_internal(ZSTD_defaultCMem);
1206*01826a49SYabin Cui     RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!");
1207*01826a49SYabin Cui     regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
1208*01826a49SYabin Cui     ZSTD_freeDCtx(dctx);
1209*01826a49SYabin Cui     return regenSize;
1210*01826a49SYabin Cui #else   /* stack mode */
1211*01826a49SYabin Cui     ZSTD_DCtx dctx;
1212*01826a49SYabin Cui     ZSTD_initDCtx_internal(&dctx);
1213*01826a49SYabin Cui     return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
1214*01826a49SYabin Cui #endif
1215*01826a49SYabin Cui }
1216*01826a49SYabin Cui 
1217*01826a49SYabin Cui 
1218*01826a49SYabin Cui /*-**************************************
1219*01826a49SYabin Cui *   Advanced Streaming Decompression API
1220*01826a49SYabin Cui *   Bufferless and synchronous
1221*01826a49SYabin Cui ****************************************/
ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx * dctx)1222*01826a49SYabin Cui size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }
1223*01826a49SYabin Cui 
1224*01826a49SYabin Cui /**
1225*01826a49SYabin Cui  * Similar to ZSTD_nextSrcSizeToDecompress(), but when a block input can be streamed, we
1226*01826a49SYabin Cui  * allow taking a partial block as the input. Currently only raw uncompressed blocks can
1227*01826a49SYabin Cui  * be streamed.
1228*01826a49SYabin Cui  *
1229*01826a49SYabin Cui  * For blocks that can be streamed, this allows us to reduce the latency until we produce
1230*01826a49SYabin Cui  * output, and avoid copying the input.
1231*01826a49SYabin Cui  *
1232*01826a49SYabin Cui  * @param inputSize - The total amount of input that the caller currently has.
1233*01826a49SYabin Cui  */
ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx * dctx,size_t inputSize)1234*01826a49SYabin Cui static size_t ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx* dctx, size_t inputSize) {
1235*01826a49SYabin Cui     if (!(dctx->stage == ZSTDds_decompressBlock || dctx->stage == ZSTDds_decompressLastBlock))
1236*01826a49SYabin Cui         return dctx->expected;
1237*01826a49SYabin Cui     if (dctx->bType != bt_raw)
1238*01826a49SYabin Cui         return dctx->expected;
1239*01826a49SYabin Cui     return BOUNDED(1, inputSize, dctx->expected);
1240*01826a49SYabin Cui }
1241*01826a49SYabin Cui 
ZSTD_nextInputType(ZSTD_DCtx * dctx)1242*01826a49SYabin Cui ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {
1243*01826a49SYabin Cui     switch(dctx->stage)
1244*01826a49SYabin Cui     {
1245*01826a49SYabin Cui     default:   /* should not happen */
1246*01826a49SYabin Cui         assert(0);
1247*01826a49SYabin Cui         ZSTD_FALLTHROUGH;
1248*01826a49SYabin Cui     case ZSTDds_getFrameHeaderSize:
1249*01826a49SYabin Cui         ZSTD_FALLTHROUGH;
1250*01826a49SYabin Cui     case ZSTDds_decodeFrameHeader:
1251*01826a49SYabin Cui         return ZSTDnit_frameHeader;
1252*01826a49SYabin Cui     case ZSTDds_decodeBlockHeader:
1253*01826a49SYabin Cui         return ZSTDnit_blockHeader;
1254*01826a49SYabin Cui     case ZSTDds_decompressBlock:
1255*01826a49SYabin Cui         return ZSTDnit_block;
1256*01826a49SYabin Cui     case ZSTDds_decompressLastBlock:
1257*01826a49SYabin Cui         return ZSTDnit_lastBlock;
1258*01826a49SYabin Cui     case ZSTDds_checkChecksum:
1259*01826a49SYabin Cui         return ZSTDnit_checksum;
1260*01826a49SYabin Cui     case ZSTDds_decodeSkippableHeader:
1261*01826a49SYabin Cui         ZSTD_FALLTHROUGH;
1262*01826a49SYabin Cui     case ZSTDds_skipFrame:
1263*01826a49SYabin Cui         return ZSTDnit_skippableFrame;
1264*01826a49SYabin Cui     }
1265*01826a49SYabin Cui }
1266*01826a49SYabin Cui 
ZSTD_isSkipFrame(ZSTD_DCtx * dctx)1267*01826a49SYabin Cui static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }
1268*01826a49SYabin Cui 
1269*01826a49SYabin Cui /** ZSTD_decompressContinue() :
1270*01826a49SYabin Cui  *  srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())
1271*01826a49SYabin Cui  *  @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
1272*01826a49SYabin Cui  *            or an error code, which can be tested using ZSTD_isError() */
ZSTD_decompressContinue(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)1273*01826a49SYabin Cui size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
1274*01826a49SYabin Cui {
1275*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize);
1276*01826a49SYabin Cui     /* Sanity check */
1277*01826a49SYabin Cui     RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed");
1278*01826a49SYabin Cui     ZSTD_checkContinuity(dctx, dst, dstCapacity);
1279*01826a49SYabin Cui 
1280*01826a49SYabin Cui     dctx->processedCSize += srcSize;
1281*01826a49SYabin Cui 
1282*01826a49SYabin Cui     switch (dctx->stage)
1283*01826a49SYabin Cui     {
1284*01826a49SYabin Cui     case ZSTDds_getFrameHeaderSize :
1285*01826a49SYabin Cui         assert(src != NULL);
1286*01826a49SYabin Cui         if (dctx->format == ZSTD_f_zstd1) {  /* allows header */
1287*01826a49SYabin Cui             assert(srcSize >= ZSTD_FRAMEIDSIZE);  /* to read skippable magic number */
1288*01826a49SYabin Cui             if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {        /* skippable frame */
1289*01826a49SYabin Cui                 ZSTD_memcpy(dctx->headerBuffer, src, srcSize);
1290*01826a49SYabin Cui                 dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize;  /* remaining to load to get full skippable frame header */
1291*01826a49SYabin Cui                 dctx->stage = ZSTDds_decodeSkippableHeader;
1292*01826a49SYabin Cui                 return 0;
1293*01826a49SYabin Cui         }   }
1294*01826a49SYabin Cui         dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);
1295*01826a49SYabin Cui         if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
1296*01826a49SYabin Cui         ZSTD_memcpy(dctx->headerBuffer, src, srcSize);
1297*01826a49SYabin Cui         dctx->expected = dctx->headerSize - srcSize;
1298*01826a49SYabin Cui         dctx->stage = ZSTDds_decodeFrameHeader;
1299*01826a49SYabin Cui         return 0;
1300*01826a49SYabin Cui 
1301*01826a49SYabin Cui     case ZSTDds_decodeFrameHeader:
1302*01826a49SYabin Cui         assert(src != NULL);
1303*01826a49SYabin Cui         ZSTD_memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);
1304*01826a49SYabin Cui         FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), "");
1305*01826a49SYabin Cui         dctx->expected = ZSTD_blockHeaderSize;
1306*01826a49SYabin Cui         dctx->stage = ZSTDds_decodeBlockHeader;
1307*01826a49SYabin Cui         return 0;
1308*01826a49SYabin Cui 
1309*01826a49SYabin Cui     case ZSTDds_decodeBlockHeader:
1310*01826a49SYabin Cui         {   blockProperties_t bp;
1311*01826a49SYabin Cui             size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
1312*01826a49SYabin Cui             if (ZSTD_isError(cBlockSize)) return cBlockSize;
1313*01826a49SYabin Cui             RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum");
1314*01826a49SYabin Cui             dctx->expected = cBlockSize;
1315*01826a49SYabin Cui             dctx->bType = bp.blockType;
1316*01826a49SYabin Cui             dctx->rleSize = bp.origSize;
1317*01826a49SYabin Cui             if (cBlockSize) {
1318*01826a49SYabin Cui                 dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
1319*01826a49SYabin Cui                 return 0;
1320*01826a49SYabin Cui             }
1321*01826a49SYabin Cui             /* empty block */
1322*01826a49SYabin Cui             if (bp.lastBlock) {
1323*01826a49SYabin Cui                 if (dctx->fParams.checksumFlag) {
1324*01826a49SYabin Cui                     dctx->expected = 4;
1325*01826a49SYabin Cui                     dctx->stage = ZSTDds_checkChecksum;
1326*01826a49SYabin Cui                 } else {
1327*01826a49SYabin Cui                     dctx->expected = 0; /* end of frame */
1328*01826a49SYabin Cui                     dctx->stage = ZSTDds_getFrameHeaderSize;
1329*01826a49SYabin Cui                 }
1330*01826a49SYabin Cui             } else {
1331*01826a49SYabin Cui                 dctx->expected = ZSTD_blockHeaderSize;  /* jump to next header */
1332*01826a49SYabin Cui                 dctx->stage = ZSTDds_decodeBlockHeader;
1333*01826a49SYabin Cui             }
1334*01826a49SYabin Cui             return 0;
1335*01826a49SYabin Cui         }
1336*01826a49SYabin Cui 
1337*01826a49SYabin Cui     case ZSTDds_decompressLastBlock:
1338*01826a49SYabin Cui     case ZSTDds_decompressBlock:
1339*01826a49SYabin Cui         DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");
1340*01826a49SYabin Cui         {   size_t rSize;
1341*01826a49SYabin Cui             switch(dctx->bType)
1342*01826a49SYabin Cui             {
1343*01826a49SYabin Cui             case bt_compressed:
1344*01826a49SYabin Cui                 DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");
1345*01826a49SYabin Cui                 assert(dctx->isFrameDecompression == 1);
1346*01826a49SYabin Cui                 rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, is_streaming);
1347*01826a49SYabin Cui                 dctx->expected = 0;  /* Streaming not supported */
1348*01826a49SYabin Cui                 break;
1349*01826a49SYabin Cui             case bt_raw :
1350*01826a49SYabin Cui                 assert(srcSize <= dctx->expected);
1351*01826a49SYabin Cui                 rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
1352*01826a49SYabin Cui                 FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed");
1353*01826a49SYabin Cui                 assert(rSize == srcSize);
1354*01826a49SYabin Cui                 dctx->expected -= rSize;
1355*01826a49SYabin Cui                 break;
1356*01826a49SYabin Cui             case bt_rle :
1357*01826a49SYabin Cui                 rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);
1358*01826a49SYabin Cui                 dctx->expected = 0;  /* Streaming not supported */
1359*01826a49SYabin Cui                 break;
1360*01826a49SYabin Cui             case bt_reserved :   /* should never happen */
1361*01826a49SYabin Cui             default:
1362*01826a49SYabin Cui                 RETURN_ERROR(corruption_detected, "invalid block type");
1363*01826a49SYabin Cui             }
1364*01826a49SYabin Cui             FORWARD_IF_ERROR(rSize, "");
1365*01826a49SYabin Cui             RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum");
1366*01826a49SYabin Cui             DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);
1367*01826a49SYabin Cui             dctx->decodedSize += rSize;
1368*01826a49SYabin Cui             if (dctx->validateChecksum) XXH64_update(&dctx->xxhState, dst, rSize);
1369*01826a49SYabin Cui             dctx->previousDstEnd = (char*)dst + rSize;
1370*01826a49SYabin Cui 
1371*01826a49SYabin Cui             /* Stay on the same stage until we are finished streaming the block. */
1372*01826a49SYabin Cui             if (dctx->expected > 0) {
1373*01826a49SYabin Cui                 return rSize;
1374*01826a49SYabin Cui             }
1375*01826a49SYabin Cui 
1376*01826a49SYabin Cui             if (dctx->stage == ZSTDds_decompressLastBlock) {   /* end of frame */
1377*01826a49SYabin Cui                 DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);
1378*01826a49SYabin Cui                 RETURN_ERROR_IF(
1379*01826a49SYabin Cui                     dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
1380*01826a49SYabin Cui                  && dctx->decodedSize != dctx->fParams.frameContentSize,
1381*01826a49SYabin Cui                     corruption_detected, "");
1382*01826a49SYabin Cui                 if (dctx->fParams.checksumFlag) {  /* another round for frame checksum */
1383*01826a49SYabin Cui                     dctx->expected = 4;
1384*01826a49SYabin Cui                     dctx->stage = ZSTDds_checkChecksum;
1385*01826a49SYabin Cui                 } else {
1386*01826a49SYabin Cui                     ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1);
1387*01826a49SYabin Cui                     dctx->expected = 0;   /* ends here */
1388*01826a49SYabin Cui                     dctx->stage = ZSTDds_getFrameHeaderSize;
1389*01826a49SYabin Cui                 }
1390*01826a49SYabin Cui             } else {
1391*01826a49SYabin Cui                 dctx->stage = ZSTDds_decodeBlockHeader;
1392*01826a49SYabin Cui                 dctx->expected = ZSTD_blockHeaderSize;
1393*01826a49SYabin Cui             }
1394*01826a49SYabin Cui             return rSize;
1395*01826a49SYabin Cui         }
1396*01826a49SYabin Cui 
1397*01826a49SYabin Cui     case ZSTDds_checkChecksum:
1398*01826a49SYabin Cui         assert(srcSize == 4);  /* guaranteed by dctx->expected */
1399*01826a49SYabin Cui         {
1400*01826a49SYabin Cui             if (dctx->validateChecksum) {
1401*01826a49SYabin Cui                 U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
1402*01826a49SYabin Cui                 U32 const check32 = MEM_readLE32(src);
1403*01826a49SYabin Cui                 DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);
1404*01826a49SYabin Cui                 RETURN_ERROR_IF(check32 != h32, checksum_wrong, "");
1405*01826a49SYabin Cui             }
1406*01826a49SYabin Cui             ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1);
1407*01826a49SYabin Cui             dctx->expected = 0;
1408*01826a49SYabin Cui             dctx->stage = ZSTDds_getFrameHeaderSize;
1409*01826a49SYabin Cui             return 0;
1410*01826a49SYabin Cui         }
1411*01826a49SYabin Cui 
1412*01826a49SYabin Cui     case ZSTDds_decodeSkippableHeader:
1413*01826a49SYabin Cui         assert(src != NULL);
1414*01826a49SYabin Cui         assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);
1415*01826a49SYabin Cui         assert(dctx->format != ZSTD_f_zstd1_magicless);
1416*01826a49SYabin Cui         ZSTD_memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize);   /* complete skippable header */
1417*01826a49SYabin Cui         dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE);   /* note : dctx->expected can grow seriously large, beyond local buffer size */
1418*01826a49SYabin Cui         dctx->stage = ZSTDds_skipFrame;
1419*01826a49SYabin Cui         return 0;
1420*01826a49SYabin Cui 
1421*01826a49SYabin Cui     case ZSTDds_skipFrame:
1422*01826a49SYabin Cui         dctx->expected = 0;
1423*01826a49SYabin Cui         dctx->stage = ZSTDds_getFrameHeaderSize;
1424*01826a49SYabin Cui         return 0;
1425*01826a49SYabin Cui 
1426*01826a49SYabin Cui     default:
1427*01826a49SYabin Cui         assert(0);   /* impossible */
1428*01826a49SYabin Cui         RETURN_ERROR(GENERIC, "impossible to reach");   /* some compilers require default to do something */
1429*01826a49SYabin Cui     }
1430*01826a49SYabin Cui }
1431*01826a49SYabin Cui 
1432*01826a49SYabin Cui 
ZSTD_refDictContent(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1433*01826a49SYabin Cui static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1434*01826a49SYabin Cui {
1435*01826a49SYabin Cui     dctx->dictEnd = dctx->previousDstEnd;
1436*01826a49SYabin Cui     dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
1437*01826a49SYabin Cui     dctx->prefixStart = dict;
1438*01826a49SYabin Cui     dctx->previousDstEnd = (const char*)dict + dictSize;
1439*01826a49SYabin Cui #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1440*01826a49SYabin Cui     dctx->dictContentBeginForFuzzing = dctx->prefixStart;
1441*01826a49SYabin Cui     dctx->dictContentEndForFuzzing = dctx->previousDstEnd;
1442*01826a49SYabin Cui #endif
1443*01826a49SYabin Cui     return 0;
1444*01826a49SYabin Cui }
1445*01826a49SYabin Cui 
1446*01826a49SYabin Cui /*! ZSTD_loadDEntropy() :
1447*01826a49SYabin Cui  *  dict : must point at beginning of a valid zstd dictionary.
1448*01826a49SYabin Cui  * @return : size of entropy tables read */
1449*01826a49SYabin Cui size_t
ZSTD_loadDEntropy(ZSTD_entropyDTables_t * entropy,const void * const dict,size_t const dictSize)1450*01826a49SYabin Cui ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
1451*01826a49SYabin Cui                   const void* const dict, size_t const dictSize)
1452*01826a49SYabin Cui {
1453*01826a49SYabin Cui     const BYTE* dictPtr = (const BYTE*)dict;
1454*01826a49SYabin Cui     const BYTE* const dictEnd = dictPtr + dictSize;
1455*01826a49SYabin Cui 
1456*01826a49SYabin Cui     RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small");
1457*01826a49SYabin Cui     assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY);   /* dict must be valid */
1458*01826a49SYabin Cui     dictPtr += 8;   /* skip header = magic + dictID */
1459*01826a49SYabin Cui 
1460*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));
1461*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));
1462*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);
1463*01826a49SYabin Cui     {   void* const workspace = &entropy->LLTable;   /* use fse tables as temporary workspace; implies fse tables are grouped together */
1464*01826a49SYabin Cui         size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);
1465*01826a49SYabin Cui #ifdef HUF_FORCE_DECOMPRESS_X1
1466*01826a49SYabin Cui         /* in minimal huffman, we always use X1 variants */
1467*01826a49SYabin Cui         size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,
1468*01826a49SYabin Cui                                                 dictPtr, dictEnd - dictPtr,
1469*01826a49SYabin Cui                                                 workspace, workspaceSize, /* flags */ 0);
1470*01826a49SYabin Cui #else
1471*01826a49SYabin Cui         size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,
1472*01826a49SYabin Cui                                                 dictPtr, (size_t)(dictEnd - dictPtr),
1473*01826a49SYabin Cui                                                 workspace, workspaceSize, /* flags */ 0);
1474*01826a49SYabin Cui #endif
1475*01826a49SYabin Cui         RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, "");
1476*01826a49SYabin Cui         dictPtr += hSize;
1477*01826a49SYabin Cui     }
1478*01826a49SYabin Cui 
1479*01826a49SYabin Cui     {   short offcodeNCount[MaxOff+1];
1480*01826a49SYabin Cui         unsigned offcodeMaxValue = MaxOff, offcodeLog;
1481*01826a49SYabin Cui         size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr));
1482*01826a49SYabin Cui         RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
1483*01826a49SYabin Cui         RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, "");
1484*01826a49SYabin Cui         RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
1485*01826a49SYabin Cui         ZSTD_buildFSETable( entropy->OFTable,
1486*01826a49SYabin Cui                             offcodeNCount, offcodeMaxValue,
1487*01826a49SYabin Cui                             OF_base, OF_bits,
1488*01826a49SYabin Cui                             offcodeLog,
1489*01826a49SYabin Cui                             entropy->workspace, sizeof(entropy->workspace),
1490*01826a49SYabin Cui                             /* bmi2 */0);
1491*01826a49SYabin Cui         dictPtr += offcodeHeaderSize;
1492*01826a49SYabin Cui     }
1493*01826a49SYabin Cui 
1494*01826a49SYabin Cui     {   short matchlengthNCount[MaxML+1];
1495*01826a49SYabin Cui         unsigned matchlengthMaxValue = MaxML, matchlengthLog;
1496*01826a49SYabin Cui         size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
1497*01826a49SYabin Cui         RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
1498*01826a49SYabin Cui         RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, "");
1499*01826a49SYabin Cui         RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
1500*01826a49SYabin Cui         ZSTD_buildFSETable( entropy->MLTable,
1501*01826a49SYabin Cui                             matchlengthNCount, matchlengthMaxValue,
1502*01826a49SYabin Cui                             ML_base, ML_bits,
1503*01826a49SYabin Cui                             matchlengthLog,
1504*01826a49SYabin Cui                             entropy->workspace, sizeof(entropy->workspace),
1505*01826a49SYabin Cui                             /* bmi2 */ 0);
1506*01826a49SYabin Cui         dictPtr += matchlengthHeaderSize;
1507*01826a49SYabin Cui     }
1508*01826a49SYabin Cui 
1509*01826a49SYabin Cui     {   short litlengthNCount[MaxLL+1];
1510*01826a49SYabin Cui         unsigned litlengthMaxValue = MaxLL, litlengthLog;
1511*01826a49SYabin Cui         size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr));
1512*01826a49SYabin Cui         RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
1513*01826a49SYabin Cui         RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, "");
1514*01826a49SYabin Cui         RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
1515*01826a49SYabin Cui         ZSTD_buildFSETable( entropy->LLTable,
1516*01826a49SYabin Cui                             litlengthNCount, litlengthMaxValue,
1517*01826a49SYabin Cui                             LL_base, LL_bits,
1518*01826a49SYabin Cui                             litlengthLog,
1519*01826a49SYabin Cui                             entropy->workspace, sizeof(entropy->workspace),
1520*01826a49SYabin Cui                             /* bmi2 */ 0);
1521*01826a49SYabin Cui         dictPtr += litlengthHeaderSize;
1522*01826a49SYabin Cui     }
1523*01826a49SYabin Cui 
1524*01826a49SYabin Cui     RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
1525*01826a49SYabin Cui     {   int i;
1526*01826a49SYabin Cui         size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
1527*01826a49SYabin Cui         for (i=0; i<3; i++) {
1528*01826a49SYabin Cui             U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
1529*01826a49SYabin Cui             RETURN_ERROR_IF(rep==0 || rep > dictContentSize,
1530*01826a49SYabin Cui                             dictionary_corrupted, "");
1531*01826a49SYabin Cui             entropy->rep[i] = rep;
1532*01826a49SYabin Cui     }   }
1533*01826a49SYabin Cui 
1534*01826a49SYabin Cui     return (size_t)(dictPtr - (const BYTE*)dict);
1535*01826a49SYabin Cui }
1536*01826a49SYabin Cui 
ZSTD_decompress_insertDictionary(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1537*01826a49SYabin Cui static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1538*01826a49SYabin Cui {
1539*01826a49SYabin Cui     if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
1540*01826a49SYabin Cui     {   U32 const magic = MEM_readLE32(dict);
1541*01826a49SYabin Cui         if (magic != ZSTD_MAGIC_DICTIONARY) {
1542*01826a49SYabin Cui             return ZSTD_refDictContent(dctx, dict, dictSize);   /* pure content mode */
1543*01826a49SYabin Cui     }   }
1544*01826a49SYabin Cui     dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
1545*01826a49SYabin Cui 
1546*01826a49SYabin Cui     /* load entropy tables */
1547*01826a49SYabin Cui     {   size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);
1548*01826a49SYabin Cui         RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, "");
1549*01826a49SYabin Cui         dict = (const char*)dict + eSize;
1550*01826a49SYabin Cui         dictSize -= eSize;
1551*01826a49SYabin Cui     }
1552*01826a49SYabin Cui     dctx->litEntropy = dctx->fseEntropy = 1;
1553*01826a49SYabin Cui 
1554*01826a49SYabin Cui     /* reference dictionary content */
1555*01826a49SYabin Cui     return ZSTD_refDictContent(dctx, dict, dictSize);
1556*01826a49SYabin Cui }
1557*01826a49SYabin Cui 
ZSTD_decompressBegin(ZSTD_DCtx * dctx)1558*01826a49SYabin Cui size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
1559*01826a49SYabin Cui {
1560*01826a49SYabin Cui     assert(dctx != NULL);
1561*01826a49SYabin Cui #if ZSTD_TRACE
1562*01826a49SYabin Cui     dctx->traceCtx = (ZSTD_trace_decompress_begin != NULL) ? ZSTD_trace_decompress_begin(dctx) : 0;
1563*01826a49SYabin Cui #endif
1564*01826a49SYabin Cui     dctx->expected = ZSTD_startingInputLength(dctx->format);  /* dctx->format must be properly set */
1565*01826a49SYabin Cui     dctx->stage = ZSTDds_getFrameHeaderSize;
1566*01826a49SYabin Cui     dctx->processedCSize = 0;
1567*01826a49SYabin Cui     dctx->decodedSize = 0;
1568*01826a49SYabin Cui     dctx->previousDstEnd = NULL;
1569*01826a49SYabin Cui     dctx->prefixStart = NULL;
1570*01826a49SYabin Cui     dctx->virtualStart = NULL;
1571*01826a49SYabin Cui     dctx->dictEnd = NULL;
1572*01826a49SYabin Cui     dctx->entropy.hufTable[0] = (HUF_DTable)((ZSTD_HUFFDTABLE_CAPACITY_LOG)*0x1000001);  /* cover both little and big endian */
1573*01826a49SYabin Cui     dctx->litEntropy = dctx->fseEntropy = 0;
1574*01826a49SYabin Cui     dctx->dictID = 0;
1575*01826a49SYabin Cui     dctx->bType = bt_reserved;
1576*01826a49SYabin Cui     dctx->isFrameDecompression = 1;
1577*01826a49SYabin Cui     ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
1578*01826a49SYabin Cui     ZSTD_memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue));  /* initial repcodes */
1579*01826a49SYabin Cui     dctx->LLTptr = dctx->entropy.LLTable;
1580*01826a49SYabin Cui     dctx->MLTptr = dctx->entropy.MLTable;
1581*01826a49SYabin Cui     dctx->OFTptr = dctx->entropy.OFTable;
1582*01826a49SYabin Cui     dctx->HUFptr = dctx->entropy.hufTable;
1583*01826a49SYabin Cui     return 0;
1584*01826a49SYabin Cui }
1585*01826a49SYabin Cui 
ZSTD_decompressBegin_usingDict(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1586*01826a49SYabin Cui size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1587*01826a49SYabin Cui {
1588*01826a49SYabin Cui     FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , "");
1589*01826a49SYabin Cui     if (dict && dictSize)
1590*01826a49SYabin Cui         RETURN_ERROR_IF(
1591*01826a49SYabin Cui             ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)),
1592*01826a49SYabin Cui             dictionary_corrupted, "");
1593*01826a49SYabin Cui     return 0;
1594*01826a49SYabin Cui }
1595*01826a49SYabin Cui 
1596*01826a49SYabin Cui 
1597*01826a49SYabin Cui /* ======   ZSTD_DDict   ====== */
1598*01826a49SYabin Cui 
ZSTD_decompressBegin_usingDDict(ZSTD_DCtx * dctx,const ZSTD_DDict * ddict)1599*01826a49SYabin Cui size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
1600*01826a49SYabin Cui {
1601*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict");
1602*01826a49SYabin Cui     assert(dctx != NULL);
1603*01826a49SYabin Cui     if (ddict) {
1604*01826a49SYabin Cui         const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict);
1605*01826a49SYabin Cui         size_t const dictSize = ZSTD_DDict_dictSize(ddict);
1606*01826a49SYabin Cui         const void* const dictEnd = dictStart + dictSize;
1607*01826a49SYabin Cui         dctx->ddictIsCold = (dctx->dictEnd != dictEnd);
1608*01826a49SYabin Cui         DEBUGLOG(4, "DDict is %s",
1609*01826a49SYabin Cui                     dctx->ddictIsCold ? "~cold~" : "hot!");
1610*01826a49SYabin Cui     }
1611*01826a49SYabin Cui     FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , "");
1612*01826a49SYabin Cui     if (ddict) {   /* NULL ddict is equivalent to no dictionary */
1613*01826a49SYabin Cui         ZSTD_copyDDictParameters(dctx, ddict);
1614*01826a49SYabin Cui     }
1615*01826a49SYabin Cui     return 0;
1616*01826a49SYabin Cui }
1617*01826a49SYabin Cui 
1618*01826a49SYabin Cui /*! ZSTD_getDictID_fromDict() :
1619*01826a49SYabin Cui  *  Provides the dictID stored within dictionary.
1620*01826a49SYabin Cui  *  if @return == 0, the dictionary is not conformant with Zstandard specification.
1621*01826a49SYabin Cui  *  It can still be loaded, but as a content-only dictionary. */
ZSTD_getDictID_fromDict(const void * dict,size_t dictSize)1622*01826a49SYabin Cui unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)
1623*01826a49SYabin Cui {
1624*01826a49SYabin Cui     if (dictSize < 8) return 0;
1625*01826a49SYabin Cui     if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;
1626*01826a49SYabin Cui     return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
1627*01826a49SYabin Cui }
1628*01826a49SYabin Cui 
1629*01826a49SYabin Cui /*! ZSTD_getDictID_fromFrame() :
1630*01826a49SYabin Cui  *  Provides the dictID required to decompress frame stored within `src`.
1631*01826a49SYabin Cui  *  If @return == 0, the dictID could not be decoded.
1632*01826a49SYabin Cui  *  This could for one of the following reasons :
1633*01826a49SYabin Cui  *  - The frame does not require a dictionary (most common case).
1634*01826a49SYabin Cui  *  - The frame was built with dictID intentionally removed.
1635*01826a49SYabin Cui  *    Needed dictionary is a hidden piece of information.
1636*01826a49SYabin Cui  *    Note : this use case also happens when using a non-conformant dictionary.
1637*01826a49SYabin Cui  *  - `srcSize` is too small, and as a result, frame header could not be decoded.
1638*01826a49SYabin Cui  *    Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.
1639*01826a49SYabin Cui  *  - This is not a Zstandard frame.
1640*01826a49SYabin Cui  *  When identifying the exact failure cause, it's possible to use
1641*01826a49SYabin Cui  *  ZSTD_getFrameHeader(), which will provide a more precise error code. */
ZSTD_getDictID_fromFrame(const void * src,size_t srcSize)1642*01826a49SYabin Cui unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)
1643*01826a49SYabin Cui {
1644*01826a49SYabin Cui     ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0, 0, 0 };
1645*01826a49SYabin Cui     size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);
1646*01826a49SYabin Cui     if (ZSTD_isError(hError)) return 0;
1647*01826a49SYabin Cui     return zfp.dictID;
1648*01826a49SYabin Cui }
1649*01826a49SYabin Cui 
1650*01826a49SYabin Cui 
1651*01826a49SYabin Cui /*! ZSTD_decompress_usingDDict() :
1652*01826a49SYabin Cui *   Decompression using a pre-digested Dictionary
1653*01826a49SYabin Cui *   Use dictionary without significant overhead. */
ZSTD_decompress_usingDDict(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const ZSTD_DDict * ddict)1654*01826a49SYabin Cui size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
1655*01826a49SYabin Cui                                   void* dst, size_t dstCapacity,
1656*01826a49SYabin Cui                             const void* src, size_t srcSize,
1657*01826a49SYabin Cui                             const ZSTD_DDict* ddict)
1658*01826a49SYabin Cui {
1659*01826a49SYabin Cui     /* pass content and size in case legacy frames are encountered */
1660*01826a49SYabin Cui     return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,
1661*01826a49SYabin Cui                                      NULL, 0,
1662*01826a49SYabin Cui                                      ddict);
1663*01826a49SYabin Cui }
1664*01826a49SYabin Cui 
1665*01826a49SYabin Cui 
1666*01826a49SYabin Cui /*=====================================
1667*01826a49SYabin Cui *   Streaming decompression
1668*01826a49SYabin Cui *====================================*/
1669*01826a49SYabin Cui 
ZSTD_createDStream(void)1670*01826a49SYabin Cui ZSTD_DStream* ZSTD_createDStream(void)
1671*01826a49SYabin Cui {
1672*01826a49SYabin Cui     DEBUGLOG(3, "ZSTD_createDStream");
1673*01826a49SYabin Cui     return ZSTD_createDCtx_internal(ZSTD_defaultCMem);
1674*01826a49SYabin Cui }
1675*01826a49SYabin Cui 
ZSTD_initStaticDStream(void * workspace,size_t workspaceSize)1676*01826a49SYabin Cui ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)
1677*01826a49SYabin Cui {
1678*01826a49SYabin Cui     return ZSTD_initStaticDCtx(workspace, workspaceSize);
1679*01826a49SYabin Cui }
1680*01826a49SYabin Cui 
ZSTD_createDStream_advanced(ZSTD_customMem customMem)1681*01826a49SYabin Cui ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)
1682*01826a49SYabin Cui {
1683*01826a49SYabin Cui     return ZSTD_createDCtx_internal(customMem);
1684*01826a49SYabin Cui }
1685*01826a49SYabin Cui 
ZSTD_freeDStream(ZSTD_DStream * zds)1686*01826a49SYabin Cui size_t ZSTD_freeDStream(ZSTD_DStream* zds)
1687*01826a49SYabin Cui {
1688*01826a49SYabin Cui     return ZSTD_freeDCtx(zds);
1689*01826a49SYabin Cui }
1690*01826a49SYabin Cui 
1691*01826a49SYabin Cui 
1692*01826a49SYabin Cui /* ***  Initialization  *** */
1693*01826a49SYabin Cui 
ZSTD_DStreamInSize(void)1694*01826a49SYabin Cui size_t ZSTD_DStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }
ZSTD_DStreamOutSize(void)1695*01826a49SYabin Cui size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }
1696*01826a49SYabin Cui 
ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx * dctx,const void * dict,size_t dictSize,ZSTD_dictLoadMethod_e dictLoadMethod,ZSTD_dictContentType_e dictContentType)1697*01826a49SYabin Cui size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx,
1698*01826a49SYabin Cui                                    const void* dict, size_t dictSize,
1699*01826a49SYabin Cui                                          ZSTD_dictLoadMethod_e dictLoadMethod,
1700*01826a49SYabin Cui                                          ZSTD_dictContentType_e dictContentType)
1701*01826a49SYabin Cui {
1702*01826a49SYabin Cui     RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
1703*01826a49SYabin Cui     ZSTD_clearDict(dctx);
1704*01826a49SYabin Cui     if (dict && dictSize != 0) {
1705*01826a49SYabin Cui         dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem);
1706*01826a49SYabin Cui         RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!");
1707*01826a49SYabin Cui         dctx->ddict = dctx->ddictLocal;
1708*01826a49SYabin Cui         dctx->dictUses = ZSTD_use_indefinitely;
1709*01826a49SYabin Cui     }
1710*01826a49SYabin Cui     return 0;
1711*01826a49SYabin Cui }
1712*01826a49SYabin Cui 
ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1713*01826a49SYabin Cui size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1714*01826a49SYabin Cui {
1715*01826a49SYabin Cui     return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
1716*01826a49SYabin Cui }
1717*01826a49SYabin Cui 
ZSTD_DCtx_loadDictionary(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1718*01826a49SYabin Cui size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1719*01826a49SYabin Cui {
1720*01826a49SYabin Cui     return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1721*01826a49SYabin Cui }
1722*01826a49SYabin Cui 
ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx * dctx,const void * prefix,size_t prefixSize,ZSTD_dictContentType_e dictContentType)1723*01826a49SYabin Cui size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
1724*01826a49SYabin Cui {
1725*01826a49SYabin Cui     FORWARD_IF_ERROR(ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType), "");
1726*01826a49SYabin Cui     dctx->dictUses = ZSTD_use_once;
1727*01826a49SYabin Cui     return 0;
1728*01826a49SYabin Cui }
1729*01826a49SYabin Cui 
ZSTD_DCtx_refPrefix(ZSTD_DCtx * dctx,const void * prefix,size_t prefixSize)1730*01826a49SYabin Cui size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize)
1731*01826a49SYabin Cui {
1732*01826a49SYabin Cui     return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent);
1733*01826a49SYabin Cui }
1734*01826a49SYabin Cui 
1735*01826a49SYabin Cui 
1736*01826a49SYabin Cui /* ZSTD_initDStream_usingDict() :
1737*01826a49SYabin Cui  * return : expected size, aka ZSTD_startingInputLength().
1738*01826a49SYabin Cui  * this function cannot fail */
ZSTD_initDStream_usingDict(ZSTD_DStream * zds,const void * dict,size_t dictSize)1739*01826a49SYabin Cui size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)
1740*01826a49SYabin Cui {
1741*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_initDStream_usingDict");
1742*01826a49SYabin Cui     FORWARD_IF_ERROR( ZSTD_DCtx_reset(zds, ZSTD_reset_session_only) , "");
1743*01826a49SYabin Cui     FORWARD_IF_ERROR( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) , "");
1744*01826a49SYabin Cui     return ZSTD_startingInputLength(zds->format);
1745*01826a49SYabin Cui }
1746*01826a49SYabin Cui 
1747*01826a49SYabin Cui /* note : this variant can't fail */
ZSTD_initDStream(ZSTD_DStream * zds)1748*01826a49SYabin Cui size_t ZSTD_initDStream(ZSTD_DStream* zds)
1749*01826a49SYabin Cui {
1750*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_initDStream");
1751*01826a49SYabin Cui     FORWARD_IF_ERROR(ZSTD_DCtx_reset(zds, ZSTD_reset_session_only), "");
1752*01826a49SYabin Cui     FORWARD_IF_ERROR(ZSTD_DCtx_refDDict(zds, NULL), "");
1753*01826a49SYabin Cui     return ZSTD_startingInputLength(zds->format);
1754*01826a49SYabin Cui }
1755*01826a49SYabin Cui 
1756*01826a49SYabin Cui /* ZSTD_initDStream_usingDDict() :
1757*01826a49SYabin Cui  * ddict will just be referenced, and must outlive decompression session
1758*01826a49SYabin Cui  * this function cannot fail */
ZSTD_initDStream_usingDDict(ZSTD_DStream * dctx,const ZSTD_DDict * ddict)1759*01826a49SYabin Cui size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict)
1760*01826a49SYabin Cui {
1761*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_initDStream_usingDDict");
1762*01826a49SYabin Cui     FORWARD_IF_ERROR( ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) , "");
1763*01826a49SYabin Cui     FORWARD_IF_ERROR( ZSTD_DCtx_refDDict(dctx, ddict) , "");
1764*01826a49SYabin Cui     return ZSTD_startingInputLength(dctx->format);
1765*01826a49SYabin Cui }
1766*01826a49SYabin Cui 
1767*01826a49SYabin Cui /* ZSTD_resetDStream() :
1768*01826a49SYabin Cui  * return : expected size, aka ZSTD_startingInputLength().
1769*01826a49SYabin Cui  * this function cannot fail */
ZSTD_resetDStream(ZSTD_DStream * dctx)1770*01826a49SYabin Cui size_t ZSTD_resetDStream(ZSTD_DStream* dctx)
1771*01826a49SYabin Cui {
1772*01826a49SYabin Cui     DEBUGLOG(4, "ZSTD_resetDStream");
1773*01826a49SYabin Cui     FORWARD_IF_ERROR(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only), "");
1774*01826a49SYabin Cui     return ZSTD_startingInputLength(dctx->format);
1775*01826a49SYabin Cui }
1776*01826a49SYabin Cui 
1777*01826a49SYabin Cui 
ZSTD_DCtx_refDDict(ZSTD_DCtx * dctx,const ZSTD_DDict * ddict)1778*01826a49SYabin Cui size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
1779*01826a49SYabin Cui {
1780*01826a49SYabin Cui     RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
1781*01826a49SYabin Cui     ZSTD_clearDict(dctx);
1782*01826a49SYabin Cui     if (ddict) {
1783*01826a49SYabin Cui         dctx->ddict = ddict;
1784*01826a49SYabin Cui         dctx->dictUses = ZSTD_use_indefinitely;
1785*01826a49SYabin Cui         if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts) {
1786*01826a49SYabin Cui             if (dctx->ddictSet == NULL) {
1787*01826a49SYabin Cui                 dctx->ddictSet = ZSTD_createDDictHashSet(dctx->customMem);
1788*01826a49SYabin Cui                 if (!dctx->ddictSet) {
1789*01826a49SYabin Cui                     RETURN_ERROR(memory_allocation, "Failed to allocate memory for hash set!");
1790*01826a49SYabin Cui                 }
1791*01826a49SYabin Cui             }
1792*01826a49SYabin Cui             assert(!dctx->staticSize);  /* Impossible: ddictSet cannot have been allocated if static dctx */
1793*01826a49SYabin Cui             FORWARD_IF_ERROR(ZSTD_DDictHashSet_addDDict(dctx->ddictSet, ddict, dctx->customMem), "");
1794*01826a49SYabin Cui         }
1795*01826a49SYabin Cui     }
1796*01826a49SYabin Cui     return 0;
1797*01826a49SYabin Cui }
1798*01826a49SYabin Cui 
1799*01826a49SYabin Cui /* ZSTD_DCtx_setMaxWindowSize() :
1800*01826a49SYabin Cui  * note : no direct equivalence in ZSTD_DCtx_setParameter,
1801*01826a49SYabin Cui  * since this version sets windowSize, and the other sets windowLog */
ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx * dctx,size_t maxWindowSize)1802*01826a49SYabin Cui size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize)
1803*01826a49SYabin Cui {
1804*01826a49SYabin Cui     ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
1805*01826a49SYabin Cui     size_t const min = (size_t)1 << bounds.lowerBound;
1806*01826a49SYabin Cui     size_t const max = (size_t)1 << bounds.upperBound;
1807*01826a49SYabin Cui     RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
1808*01826a49SYabin Cui     RETURN_ERROR_IF(maxWindowSize < min, parameter_outOfBound, "");
1809*01826a49SYabin Cui     RETURN_ERROR_IF(maxWindowSize > max, parameter_outOfBound, "");
1810*01826a49SYabin Cui     dctx->maxWindowSize = maxWindowSize;
1811*01826a49SYabin Cui     return 0;
1812*01826a49SYabin Cui }
1813*01826a49SYabin Cui 
ZSTD_DCtx_setFormat(ZSTD_DCtx * dctx,ZSTD_format_e format)1814*01826a49SYabin Cui size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format)
1815*01826a49SYabin Cui {
1816*01826a49SYabin Cui     return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, (int)format);
1817*01826a49SYabin Cui }
1818*01826a49SYabin Cui 
ZSTD_dParam_getBounds(ZSTD_dParameter dParam)1819*01826a49SYabin Cui ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
1820*01826a49SYabin Cui {
1821*01826a49SYabin Cui     ZSTD_bounds bounds = { 0, 0, 0 };
1822*01826a49SYabin Cui     switch(dParam) {
1823*01826a49SYabin Cui         case ZSTD_d_windowLogMax:
1824*01826a49SYabin Cui             bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
1825*01826a49SYabin Cui             bounds.upperBound = ZSTD_WINDOWLOG_MAX;
1826*01826a49SYabin Cui             return bounds;
1827*01826a49SYabin Cui         case ZSTD_d_format:
1828*01826a49SYabin Cui             bounds.lowerBound = (int)ZSTD_f_zstd1;
1829*01826a49SYabin Cui             bounds.upperBound = (int)ZSTD_f_zstd1_magicless;
1830*01826a49SYabin Cui             ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
1831*01826a49SYabin Cui             return bounds;
1832*01826a49SYabin Cui         case ZSTD_d_stableOutBuffer:
1833*01826a49SYabin Cui             bounds.lowerBound = (int)ZSTD_bm_buffered;
1834*01826a49SYabin Cui             bounds.upperBound = (int)ZSTD_bm_stable;
1835*01826a49SYabin Cui             return bounds;
1836*01826a49SYabin Cui         case ZSTD_d_forceIgnoreChecksum:
1837*01826a49SYabin Cui             bounds.lowerBound = (int)ZSTD_d_validateChecksum;
1838*01826a49SYabin Cui             bounds.upperBound = (int)ZSTD_d_ignoreChecksum;
1839*01826a49SYabin Cui             return bounds;
1840*01826a49SYabin Cui         case ZSTD_d_refMultipleDDicts:
1841*01826a49SYabin Cui             bounds.lowerBound = (int)ZSTD_rmd_refSingleDDict;
1842*01826a49SYabin Cui             bounds.upperBound = (int)ZSTD_rmd_refMultipleDDicts;
1843*01826a49SYabin Cui             return bounds;
1844*01826a49SYabin Cui         case ZSTD_d_disableHuffmanAssembly:
1845*01826a49SYabin Cui             bounds.lowerBound = 0;
1846*01826a49SYabin Cui             bounds.upperBound = 1;
1847*01826a49SYabin Cui             return bounds;
1848*01826a49SYabin Cui         case ZSTD_d_maxBlockSize:
1849*01826a49SYabin Cui             bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
1850*01826a49SYabin Cui             bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
1851*01826a49SYabin Cui             return bounds;
1852*01826a49SYabin Cui 
1853*01826a49SYabin Cui         default:;
1854*01826a49SYabin Cui     }
1855*01826a49SYabin Cui     bounds.error = ERROR(parameter_unsupported);
1856*01826a49SYabin Cui     return bounds;
1857*01826a49SYabin Cui }
1858*01826a49SYabin Cui 
1859*01826a49SYabin Cui /* ZSTD_dParam_withinBounds:
1860*01826a49SYabin Cui  * @return 1 if value is within dParam bounds,
1861*01826a49SYabin Cui  * 0 otherwise */
ZSTD_dParam_withinBounds(ZSTD_dParameter dParam,int value)1862*01826a49SYabin Cui static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value)
1863*01826a49SYabin Cui {
1864*01826a49SYabin Cui     ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam);
1865*01826a49SYabin Cui     if (ZSTD_isError(bounds.error)) return 0;
1866*01826a49SYabin Cui     if (value < bounds.lowerBound) return 0;
1867*01826a49SYabin Cui     if (value > bounds.upperBound) return 0;
1868*01826a49SYabin Cui     return 1;
1869*01826a49SYabin Cui }
1870*01826a49SYabin Cui 
1871*01826a49SYabin Cui #define CHECK_DBOUNDS(p,v) {                \
1872*01826a49SYabin Cui     RETURN_ERROR_IF(!ZSTD_dParam_withinBounds(p, v), parameter_outOfBound, ""); \
1873*01826a49SYabin Cui }
1874*01826a49SYabin Cui 
ZSTD_DCtx_getParameter(ZSTD_DCtx * dctx,ZSTD_dParameter param,int * value)1875*01826a49SYabin Cui size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value)
1876*01826a49SYabin Cui {
1877*01826a49SYabin Cui     switch (param) {
1878*01826a49SYabin Cui         case ZSTD_d_windowLogMax:
1879*01826a49SYabin Cui             *value = (int)ZSTD_highbit32((U32)dctx->maxWindowSize);
1880*01826a49SYabin Cui             return 0;
1881*01826a49SYabin Cui         case ZSTD_d_format:
1882*01826a49SYabin Cui             *value = (int)dctx->format;
1883*01826a49SYabin Cui             return 0;
1884*01826a49SYabin Cui         case ZSTD_d_stableOutBuffer:
1885*01826a49SYabin Cui             *value = (int)dctx->outBufferMode;
1886*01826a49SYabin Cui             return 0;
1887*01826a49SYabin Cui         case ZSTD_d_forceIgnoreChecksum:
1888*01826a49SYabin Cui             *value = (int)dctx->forceIgnoreChecksum;
1889*01826a49SYabin Cui             return 0;
1890*01826a49SYabin Cui         case ZSTD_d_refMultipleDDicts:
1891*01826a49SYabin Cui             *value = (int)dctx->refMultipleDDicts;
1892*01826a49SYabin Cui             return 0;
1893*01826a49SYabin Cui         case ZSTD_d_disableHuffmanAssembly:
1894*01826a49SYabin Cui             *value = (int)dctx->disableHufAsm;
1895*01826a49SYabin Cui             return 0;
1896*01826a49SYabin Cui         case ZSTD_d_maxBlockSize:
1897*01826a49SYabin Cui             *value = dctx->maxBlockSizeParam;
1898*01826a49SYabin Cui             return 0;
1899*01826a49SYabin Cui         default:;
1900*01826a49SYabin Cui     }
1901*01826a49SYabin Cui     RETURN_ERROR(parameter_unsupported, "");
1902*01826a49SYabin Cui }
1903*01826a49SYabin Cui 
ZSTD_DCtx_setParameter(ZSTD_DCtx * dctx,ZSTD_dParameter dParam,int value)1904*01826a49SYabin Cui size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)
1905*01826a49SYabin Cui {
1906*01826a49SYabin Cui     RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
1907*01826a49SYabin Cui     switch(dParam) {
1908*01826a49SYabin Cui         case ZSTD_d_windowLogMax:
1909*01826a49SYabin Cui             if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT;
1910*01826a49SYabin Cui             CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);
1911*01826a49SYabin Cui             dctx->maxWindowSize = ((size_t)1) << value;
1912*01826a49SYabin Cui             return 0;
1913*01826a49SYabin Cui         case ZSTD_d_format:
1914*01826a49SYabin Cui             CHECK_DBOUNDS(ZSTD_d_format, value);
1915*01826a49SYabin Cui             dctx->format = (ZSTD_format_e)value;
1916*01826a49SYabin Cui             return 0;
1917*01826a49SYabin Cui         case ZSTD_d_stableOutBuffer:
1918*01826a49SYabin Cui             CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value);
1919*01826a49SYabin Cui             dctx->outBufferMode = (ZSTD_bufferMode_e)value;
1920*01826a49SYabin Cui             return 0;
1921*01826a49SYabin Cui         case ZSTD_d_forceIgnoreChecksum:
1922*01826a49SYabin Cui             CHECK_DBOUNDS(ZSTD_d_forceIgnoreChecksum, value);
1923*01826a49SYabin Cui             dctx->forceIgnoreChecksum = (ZSTD_forceIgnoreChecksum_e)value;
1924*01826a49SYabin Cui             return 0;
1925*01826a49SYabin Cui         case ZSTD_d_refMultipleDDicts:
1926*01826a49SYabin Cui             CHECK_DBOUNDS(ZSTD_d_refMultipleDDicts, value);
1927*01826a49SYabin Cui             if (dctx->staticSize != 0) {
1928*01826a49SYabin Cui                 RETURN_ERROR(parameter_unsupported, "Static dctx does not support multiple DDicts!");
1929*01826a49SYabin Cui             }
1930*01826a49SYabin Cui             dctx->refMultipleDDicts = (ZSTD_refMultipleDDicts_e)value;
1931*01826a49SYabin Cui             return 0;
1932*01826a49SYabin Cui         case ZSTD_d_disableHuffmanAssembly:
1933*01826a49SYabin Cui             CHECK_DBOUNDS(ZSTD_d_disableHuffmanAssembly, value);
1934*01826a49SYabin Cui             dctx->disableHufAsm = value != 0;
1935*01826a49SYabin Cui             return 0;
1936*01826a49SYabin Cui         case ZSTD_d_maxBlockSize:
1937*01826a49SYabin Cui             if (value != 0) CHECK_DBOUNDS(ZSTD_d_maxBlockSize, value);
1938*01826a49SYabin Cui             dctx->maxBlockSizeParam = value;
1939*01826a49SYabin Cui             return 0;
1940*01826a49SYabin Cui         default:;
1941*01826a49SYabin Cui     }
1942*01826a49SYabin Cui     RETURN_ERROR(parameter_unsupported, "");
1943*01826a49SYabin Cui }
1944*01826a49SYabin Cui 
ZSTD_DCtx_reset(ZSTD_DCtx * dctx,ZSTD_ResetDirective reset)1945*01826a49SYabin Cui size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)
1946*01826a49SYabin Cui {
1947*01826a49SYabin Cui     if ( (reset == ZSTD_reset_session_only)
1948*01826a49SYabin Cui       || (reset == ZSTD_reset_session_and_parameters) ) {
1949*01826a49SYabin Cui         dctx->streamStage = zdss_init;
1950*01826a49SYabin Cui         dctx->noForwardProgress = 0;
1951*01826a49SYabin Cui         dctx->isFrameDecompression = 1;
1952*01826a49SYabin Cui     }
1953*01826a49SYabin Cui     if ( (reset == ZSTD_reset_parameters)
1954*01826a49SYabin Cui       || (reset == ZSTD_reset_session_and_parameters) ) {
1955*01826a49SYabin Cui         RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
1956*01826a49SYabin Cui         ZSTD_clearDict(dctx);
1957*01826a49SYabin Cui         ZSTD_DCtx_resetParameters(dctx);
1958*01826a49SYabin Cui     }
1959*01826a49SYabin Cui     return 0;
1960*01826a49SYabin Cui }
1961*01826a49SYabin Cui 
1962*01826a49SYabin Cui 
ZSTD_sizeof_DStream(const ZSTD_DStream * dctx)1963*01826a49SYabin Cui size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx)
1964*01826a49SYabin Cui {
1965*01826a49SYabin Cui     return ZSTD_sizeof_DCtx(dctx);
1966*01826a49SYabin Cui }
1967*01826a49SYabin Cui 
ZSTD_decodingBufferSize_internal(unsigned long long windowSize,unsigned long long frameContentSize,size_t blockSizeMax)1968*01826a49SYabin Cui static size_t ZSTD_decodingBufferSize_internal(unsigned long long windowSize, unsigned long long frameContentSize, size_t blockSizeMax)
1969*01826a49SYabin Cui {
1970*01826a49SYabin Cui     size_t const blockSize = MIN((size_t)MIN(windowSize, ZSTD_BLOCKSIZE_MAX), blockSizeMax);
1971*01826a49SYabin Cui     /* We need blockSize + WILDCOPY_OVERLENGTH worth of buffer so that if a block
1972*01826a49SYabin Cui      * ends at windowSize + WILDCOPY_OVERLENGTH + 1 bytes, we can start writing
1973*01826a49SYabin Cui      * the block at the beginning of the output buffer, and maintain a full window.
1974*01826a49SYabin Cui      *
1975*01826a49SYabin Cui      * We need another blockSize worth of buffer so that we can store split
1976*01826a49SYabin Cui      * literals at the end of the block without overwriting the extDict window.
1977*01826a49SYabin Cui      */
1978*01826a49SYabin Cui     unsigned long long const neededRBSize = windowSize + (blockSize * 2) + (WILDCOPY_OVERLENGTH * 2);
1979*01826a49SYabin Cui     unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);
1980*01826a49SYabin Cui     size_t const minRBSize = (size_t) neededSize;
1981*01826a49SYabin Cui     RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize,
1982*01826a49SYabin Cui                     frameParameter_windowTooLarge, "");
1983*01826a49SYabin Cui     return minRBSize;
1984*01826a49SYabin Cui }
1985*01826a49SYabin Cui 
ZSTD_decodingBufferSize_min(unsigned long long windowSize,unsigned long long frameContentSize)1986*01826a49SYabin Cui size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)
1987*01826a49SYabin Cui {
1988*01826a49SYabin Cui     return ZSTD_decodingBufferSize_internal(windowSize, frameContentSize, ZSTD_BLOCKSIZE_MAX);
1989*01826a49SYabin Cui }
1990*01826a49SYabin Cui 
ZSTD_estimateDStreamSize(size_t windowSize)1991*01826a49SYabin Cui size_t ZSTD_estimateDStreamSize(size_t windowSize)
1992*01826a49SYabin Cui {
1993*01826a49SYabin Cui     size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
1994*01826a49SYabin Cui     size_t const inBuffSize = blockSize;  /* no block can be larger */
1995*01826a49SYabin Cui     size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);
1996*01826a49SYabin Cui     return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;
1997*01826a49SYabin Cui }
1998*01826a49SYabin Cui 
ZSTD_estimateDStreamSize_fromFrame(const void * src,size_t srcSize)1999*01826a49SYabin Cui size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)
2000*01826a49SYabin Cui {
2001*01826a49SYabin Cui     U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX;   /* note : should be user-selectable, but requires an additional parameter (or a dctx) */
2002*01826a49SYabin Cui     ZSTD_frameHeader zfh;
2003*01826a49SYabin Cui     size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);
2004*01826a49SYabin Cui     if (ZSTD_isError(err)) return err;
2005*01826a49SYabin Cui     RETURN_ERROR_IF(err>0, srcSize_wrong, "");
2006*01826a49SYabin Cui     RETURN_ERROR_IF(zfh.windowSize > windowSizeMax,
2007*01826a49SYabin Cui                     frameParameter_windowTooLarge, "");
2008*01826a49SYabin Cui     return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);
2009*01826a49SYabin Cui }
2010*01826a49SYabin Cui 
2011*01826a49SYabin Cui 
2012*01826a49SYabin Cui /* *****   Decompression   ***** */
2013*01826a49SYabin Cui 
ZSTD_DCtx_isOverflow(ZSTD_DStream * zds,size_t const neededInBuffSize,size_t const neededOutBuffSize)2014*01826a49SYabin Cui static int ZSTD_DCtx_isOverflow(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)
2015*01826a49SYabin Cui {
2016*01826a49SYabin Cui     return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR;
2017*01826a49SYabin Cui }
2018*01826a49SYabin Cui 
ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream * zds,size_t const neededInBuffSize,size_t const neededOutBuffSize)2019*01826a49SYabin Cui static void ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)
2020*01826a49SYabin Cui {
2021*01826a49SYabin Cui     if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize))
2022*01826a49SYabin Cui         zds->oversizedDuration++;
2023*01826a49SYabin Cui     else
2024*01826a49SYabin Cui         zds->oversizedDuration = 0;
2025*01826a49SYabin Cui }
2026*01826a49SYabin Cui 
ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream * zds)2027*01826a49SYabin Cui static int ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream* zds)
2028*01826a49SYabin Cui {
2029*01826a49SYabin Cui     return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION;
2030*01826a49SYabin Cui }
2031*01826a49SYabin Cui 
2032*01826a49SYabin Cui /* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */
ZSTD_checkOutBuffer(ZSTD_DStream const * zds,ZSTD_outBuffer const * output)2033*01826a49SYabin Cui static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output)
2034*01826a49SYabin Cui {
2035*01826a49SYabin Cui     ZSTD_outBuffer const expect = zds->expectedOutBuffer;
2036*01826a49SYabin Cui     /* No requirement when ZSTD_obm_stable is not enabled. */
2037*01826a49SYabin Cui     if (zds->outBufferMode != ZSTD_bm_stable)
2038*01826a49SYabin Cui         return 0;
2039*01826a49SYabin Cui     /* Any buffer is allowed in zdss_init, this must be the same for every other call until
2040*01826a49SYabin Cui      * the context is reset.
2041*01826a49SYabin Cui      */
2042*01826a49SYabin Cui     if (zds->streamStage == zdss_init)
2043*01826a49SYabin Cui         return 0;
2044*01826a49SYabin Cui     /* The buffer must match our expectation exactly. */
2045*01826a49SYabin Cui     if (expect.dst == output->dst && expect.pos == output->pos && expect.size == output->size)
2046*01826a49SYabin Cui         return 0;
2047*01826a49SYabin Cui     RETURN_ERROR(dstBuffer_wrong, "ZSTD_d_stableOutBuffer enabled but output differs!");
2048*01826a49SYabin Cui }
2049*01826a49SYabin Cui 
2050*01826a49SYabin Cui /* Calls ZSTD_decompressContinue() with the right parameters for ZSTD_decompressStream()
2051*01826a49SYabin Cui  * and updates the stage and the output buffer state. This call is extracted so it can be
2052*01826a49SYabin Cui  * used both when reading directly from the ZSTD_inBuffer, and in buffered input mode.
2053*01826a49SYabin Cui  * NOTE: You must break after calling this function since the streamStage is modified.
2054*01826a49SYabin Cui  */
ZSTD_decompressContinueStream(ZSTD_DStream * zds,char ** op,char * oend,void const * src,size_t srcSize)2055*01826a49SYabin Cui static size_t ZSTD_decompressContinueStream(
2056*01826a49SYabin Cui             ZSTD_DStream* zds, char** op, char* oend,
2057*01826a49SYabin Cui             void const* src, size_t srcSize) {
2058*01826a49SYabin Cui     int const isSkipFrame = ZSTD_isSkipFrame(zds);
2059*01826a49SYabin Cui     if (zds->outBufferMode == ZSTD_bm_buffered) {
2060*01826a49SYabin Cui         size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart;
2061*01826a49SYabin Cui         size_t const decodedSize = ZSTD_decompressContinue(zds,
2062*01826a49SYabin Cui                 zds->outBuff + zds->outStart, dstSize, src, srcSize);
2063*01826a49SYabin Cui         FORWARD_IF_ERROR(decodedSize, "");
2064*01826a49SYabin Cui         if (!decodedSize && !isSkipFrame) {
2065*01826a49SYabin Cui             zds->streamStage = zdss_read;
2066*01826a49SYabin Cui         } else {
2067*01826a49SYabin Cui             zds->outEnd = zds->outStart + decodedSize;
2068*01826a49SYabin Cui             zds->streamStage = zdss_flush;
2069*01826a49SYabin Cui         }
2070*01826a49SYabin Cui     } else {
2071*01826a49SYabin Cui         /* Write directly into the output buffer */
2072*01826a49SYabin Cui         size_t const dstSize = isSkipFrame ? 0 : (size_t)(oend - *op);
2073*01826a49SYabin Cui         size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize);
2074*01826a49SYabin Cui         FORWARD_IF_ERROR(decodedSize, "");
2075*01826a49SYabin Cui         *op += decodedSize;
2076*01826a49SYabin Cui         /* Flushing is not needed. */
2077*01826a49SYabin Cui         zds->streamStage = zdss_read;
2078*01826a49SYabin Cui         assert(*op <= oend);
2079*01826a49SYabin Cui         assert(zds->outBufferMode == ZSTD_bm_stable);
2080*01826a49SYabin Cui     }
2081*01826a49SYabin Cui     return 0;
2082*01826a49SYabin Cui }
2083*01826a49SYabin Cui 
ZSTD_decompressStream(ZSTD_DStream * zds,ZSTD_outBuffer * output,ZSTD_inBuffer * input)2084*01826a49SYabin Cui size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
2085*01826a49SYabin Cui {
2086*01826a49SYabin Cui     const char* const src = (const char*)input->src;
2087*01826a49SYabin Cui     const char* const istart = input->pos != 0 ? src + input->pos : src;
2088*01826a49SYabin Cui     const char* const iend = input->size != 0 ? src + input->size : src;
2089*01826a49SYabin Cui     const char* ip = istart;
2090*01826a49SYabin Cui     char* const dst = (char*)output->dst;
2091*01826a49SYabin Cui     char* const ostart = output->pos != 0 ? dst + output->pos : dst;
2092*01826a49SYabin Cui     char* const oend = output->size != 0 ? dst + output->size : dst;
2093*01826a49SYabin Cui     char* op = ostart;
2094*01826a49SYabin Cui     U32 someMoreWork = 1;
2095*01826a49SYabin Cui 
2096*01826a49SYabin Cui     DEBUGLOG(5, "ZSTD_decompressStream");
2097*01826a49SYabin Cui     RETURN_ERROR_IF(
2098*01826a49SYabin Cui         input->pos > input->size,
2099*01826a49SYabin Cui         srcSize_wrong,
2100*01826a49SYabin Cui         "forbidden. in: pos: %u   vs size: %u",
2101*01826a49SYabin Cui         (U32)input->pos, (U32)input->size);
2102*01826a49SYabin Cui     RETURN_ERROR_IF(
2103*01826a49SYabin Cui         output->pos > output->size,
2104*01826a49SYabin Cui         dstSize_tooSmall,
2105*01826a49SYabin Cui         "forbidden. out: pos: %u   vs size: %u",
2106*01826a49SYabin Cui         (U32)output->pos, (U32)output->size);
2107*01826a49SYabin Cui     DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));
2108*01826a49SYabin Cui     FORWARD_IF_ERROR(ZSTD_checkOutBuffer(zds, output), "");
2109*01826a49SYabin Cui 
2110*01826a49SYabin Cui     while (someMoreWork) {
2111*01826a49SYabin Cui         switch(zds->streamStage)
2112*01826a49SYabin Cui         {
2113*01826a49SYabin Cui         case zdss_init :
2114*01826a49SYabin Cui             DEBUGLOG(5, "stage zdss_init => transparent reset ");
2115*01826a49SYabin Cui             zds->streamStage = zdss_loadHeader;
2116*01826a49SYabin Cui             zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;
2117*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
2118*01826a49SYabin Cui             zds->legacyVersion = 0;
2119*01826a49SYabin Cui #endif
2120*01826a49SYabin Cui             zds->hostageByte = 0;
2121*01826a49SYabin Cui             zds->expectedOutBuffer = *output;
2122*01826a49SYabin Cui             ZSTD_FALLTHROUGH;
2123*01826a49SYabin Cui 
2124*01826a49SYabin Cui         case zdss_loadHeader :
2125*01826a49SYabin Cui             DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip));
2126*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
2127*01826a49SYabin Cui             if (zds->legacyVersion) {
2128*01826a49SYabin Cui                 RETURN_ERROR_IF(zds->staticSize, memory_allocation,
2129*01826a49SYabin Cui                     "legacy support is incompatible with static dctx");
2130*01826a49SYabin Cui                 {   size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);
2131*01826a49SYabin Cui                     if (hint==0) zds->streamStage = zdss_init;
2132*01826a49SYabin Cui                     return hint;
2133*01826a49SYabin Cui             }   }
2134*01826a49SYabin Cui #endif
2135*01826a49SYabin Cui             {   size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format);
2136*01826a49SYabin Cui                 if (zds->refMultipleDDicts && zds->ddictSet) {
2137*01826a49SYabin Cui                     ZSTD_DCtx_selectFrameDDict(zds);
2138*01826a49SYabin Cui                 }
2139*01826a49SYabin Cui                 if (ZSTD_isError(hSize)) {
2140*01826a49SYabin Cui #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
2141*01826a49SYabin Cui                     U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);
2142*01826a49SYabin Cui                     if (legacyVersion) {
2143*01826a49SYabin Cui                         ZSTD_DDict const* const ddict = ZSTD_getDDict(zds);
2144*01826a49SYabin Cui                         const void* const dict = ddict ? ZSTD_DDict_dictContent(ddict) : NULL;
2145*01826a49SYabin Cui                         size_t const dictSize = ddict ? ZSTD_DDict_dictSize(ddict) : 0;
2146*01826a49SYabin Cui                         DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion);
2147*01826a49SYabin Cui                         RETURN_ERROR_IF(zds->staticSize, memory_allocation,
2148*01826a49SYabin Cui                             "legacy support is incompatible with static dctx");
2149*01826a49SYabin Cui                         FORWARD_IF_ERROR(ZSTD_initLegacyStream(&zds->legacyContext,
2150*01826a49SYabin Cui                                     zds->previousLegacyVersion, legacyVersion,
2151*01826a49SYabin Cui                                     dict, dictSize), "");
2152*01826a49SYabin Cui                         zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;
2153*01826a49SYabin Cui                         {   size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);
2154*01826a49SYabin Cui                             if (hint==0) zds->streamStage = zdss_init;   /* or stay in stage zdss_loadHeader */
2155*01826a49SYabin Cui                             return hint;
2156*01826a49SYabin Cui                     }   }
2157*01826a49SYabin Cui #endif
2158*01826a49SYabin Cui                     return hSize;   /* error */
2159*01826a49SYabin Cui                 }
2160*01826a49SYabin Cui                 if (hSize != 0) {   /* need more input */
2161*01826a49SYabin Cui                     size_t const toLoad = hSize - zds->lhSize;   /* if hSize!=0, hSize > zds->lhSize */
2162*01826a49SYabin Cui                     size_t const remainingInput = (size_t)(iend-ip);
2163*01826a49SYabin Cui                     assert(iend >= ip);
2164*01826a49SYabin Cui                     if (toLoad > remainingInput) {   /* not enough input to load full header */
2165*01826a49SYabin Cui                         if (remainingInput > 0) {
2166*01826a49SYabin Cui                             ZSTD_memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput);
2167*01826a49SYabin Cui                             zds->lhSize += remainingInput;
2168*01826a49SYabin Cui                         }
2169*01826a49SYabin Cui                         input->pos = input->size;
2170*01826a49SYabin Cui                         /* check first few bytes */
2171*01826a49SYabin Cui                         FORWARD_IF_ERROR(
2172*01826a49SYabin Cui                             ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format),
2173*01826a49SYabin Cui                             "First few bytes detected incorrect" );
2174*01826a49SYabin Cui                         /* return hint input size */
2175*01826a49SYabin Cui                         return (MAX((size_t)ZSTD_FRAMEHEADERSIZE_MIN(zds->format), hSize) - zds->lhSize) + ZSTD_blockHeaderSize;   /* remaining header bytes + next block header */
2176*01826a49SYabin Cui                     }
2177*01826a49SYabin Cui                     assert(ip != NULL);
2178*01826a49SYabin Cui                     ZSTD_memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;
2179*01826a49SYabin Cui                     break;
2180*01826a49SYabin Cui             }   }
2181*01826a49SYabin Cui 
2182*01826a49SYabin Cui             /* check for single-pass mode opportunity */
2183*01826a49SYabin Cui             if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
2184*01826a49SYabin Cui                 && zds->fParams.frameType != ZSTD_skippableFrame
2185*01826a49SYabin Cui                 && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {
2186*01826a49SYabin Cui                 size_t const cSize = ZSTD_findFrameCompressedSize_advanced(istart, (size_t)(iend-istart), zds->format);
2187*01826a49SYabin Cui                 if (cSize <= (size_t)(iend-istart)) {
2188*01826a49SYabin Cui                     /* shortcut : using single-pass mode */
2189*01826a49SYabin Cui                     size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, (size_t)(oend-op), istart, cSize, ZSTD_getDDict(zds));
2190*01826a49SYabin Cui                     if (ZSTD_isError(decompressedSize)) return decompressedSize;
2191*01826a49SYabin Cui                     DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()");
2192*01826a49SYabin Cui                     assert(istart != NULL);
2193*01826a49SYabin Cui                     ip = istart + cSize;
2194*01826a49SYabin Cui                     op = op ? op + decompressedSize : op; /* can occur if frameContentSize = 0 (empty frame) */
2195*01826a49SYabin Cui                     zds->expected = 0;
2196*01826a49SYabin Cui                     zds->streamStage = zdss_init;
2197*01826a49SYabin Cui                     someMoreWork = 0;
2198*01826a49SYabin Cui                     break;
2199*01826a49SYabin Cui             }   }
2200*01826a49SYabin Cui 
2201*01826a49SYabin Cui             /* Check output buffer is large enough for ZSTD_odm_stable. */
2202*01826a49SYabin Cui             if (zds->outBufferMode == ZSTD_bm_stable
2203*01826a49SYabin Cui                 && zds->fParams.frameType != ZSTD_skippableFrame
2204*01826a49SYabin Cui                 && zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
2205*01826a49SYabin Cui                 && (U64)(size_t)(oend-op) < zds->fParams.frameContentSize) {
2206*01826a49SYabin Cui                 RETURN_ERROR(dstSize_tooSmall, "ZSTD_obm_stable passed but ZSTD_outBuffer is too small");
2207*01826a49SYabin Cui             }
2208*01826a49SYabin Cui 
2209*01826a49SYabin Cui             /* Consume header (see ZSTDds_decodeFrameHeader) */
2210*01826a49SYabin Cui             DEBUGLOG(4, "Consume header");
2211*01826a49SYabin Cui             FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), "");
2212*01826a49SYabin Cui 
2213*01826a49SYabin Cui             if (zds->format == ZSTD_f_zstd1
2214*01826a49SYabin Cui                 && (MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {  /* skippable frame */
2215*01826a49SYabin Cui                 zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE);
2216*01826a49SYabin Cui                 zds->stage = ZSTDds_skipFrame;
2217*01826a49SYabin Cui             } else {
2218*01826a49SYabin Cui                 FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), "");
2219*01826a49SYabin Cui                 zds->expected = ZSTD_blockHeaderSize;
2220*01826a49SYabin Cui                 zds->stage = ZSTDds_decodeBlockHeader;
2221*01826a49SYabin Cui             }
2222*01826a49SYabin Cui 
2223*01826a49SYabin Cui             /* control buffer memory usage */
2224*01826a49SYabin Cui             DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)",
2225*01826a49SYabin Cui                         (U32)(zds->fParams.windowSize >>10),
2226*01826a49SYabin Cui                         (U32)(zds->maxWindowSize >> 10) );
2227*01826a49SYabin Cui             zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
2228*01826a49SYabin Cui             RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize,
2229*01826a49SYabin Cui                             frameParameter_windowTooLarge, "");
2230*01826a49SYabin Cui             if (zds->maxBlockSizeParam != 0)
2231*01826a49SYabin Cui                 zds->fParams.blockSizeMax = MIN(zds->fParams.blockSizeMax, (unsigned)zds->maxBlockSizeParam);
2232*01826a49SYabin Cui 
2233*01826a49SYabin Cui             /* Adapt buffer sizes to frame header instructions */
2234*01826a49SYabin Cui             {   size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);
2235*01826a49SYabin Cui                 size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_bm_buffered
2236*01826a49SYabin Cui                         ? ZSTD_decodingBufferSize_internal(zds->fParams.windowSize, zds->fParams.frameContentSize, zds->fParams.blockSizeMax)
2237*01826a49SYabin Cui                         : 0;
2238*01826a49SYabin Cui 
2239*01826a49SYabin Cui                 ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize);
2240*01826a49SYabin Cui 
2241*01826a49SYabin Cui                 {   int const tooSmall = (zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize);
2242*01826a49SYabin Cui                     int const tooLarge = ZSTD_DCtx_isOversizedTooLong(zds);
2243*01826a49SYabin Cui 
2244*01826a49SYabin Cui                     if (tooSmall || tooLarge) {
2245*01826a49SYabin Cui                         size_t const bufferSize = neededInBuffSize + neededOutBuffSize;
2246*01826a49SYabin Cui                         DEBUGLOG(4, "inBuff  : from %u to %u",
2247*01826a49SYabin Cui                                     (U32)zds->inBuffSize, (U32)neededInBuffSize);
2248*01826a49SYabin Cui                         DEBUGLOG(4, "outBuff : from %u to %u",
2249*01826a49SYabin Cui                                     (U32)zds->outBuffSize, (U32)neededOutBuffSize);
2250*01826a49SYabin Cui                         if (zds->staticSize) {  /* static DCtx */
2251*01826a49SYabin Cui                             DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);
2252*01826a49SYabin Cui                             assert(zds->staticSize >= sizeof(ZSTD_DCtx));  /* controlled at init */
2253*01826a49SYabin Cui                             RETURN_ERROR_IF(
2254*01826a49SYabin Cui                                 bufferSize > zds->staticSize - sizeof(ZSTD_DCtx),
2255*01826a49SYabin Cui                                 memory_allocation, "");
2256*01826a49SYabin Cui                         } else {
2257*01826a49SYabin Cui                             ZSTD_customFree(zds->inBuff, zds->customMem);
2258*01826a49SYabin Cui                             zds->inBuffSize = 0;
2259*01826a49SYabin Cui                             zds->outBuffSize = 0;
2260*01826a49SYabin Cui                             zds->inBuff = (char*)ZSTD_customMalloc(bufferSize, zds->customMem);
2261*01826a49SYabin Cui                             RETURN_ERROR_IF(zds->inBuff == NULL, memory_allocation, "");
2262*01826a49SYabin Cui                         }
2263*01826a49SYabin Cui                         zds->inBuffSize = neededInBuffSize;
2264*01826a49SYabin Cui                         zds->outBuff = zds->inBuff + zds->inBuffSize;
2265*01826a49SYabin Cui                         zds->outBuffSize = neededOutBuffSize;
2266*01826a49SYabin Cui             }   }   }
2267*01826a49SYabin Cui             zds->streamStage = zdss_read;
2268*01826a49SYabin Cui             ZSTD_FALLTHROUGH;
2269*01826a49SYabin Cui 
2270*01826a49SYabin Cui         case zdss_read:
2271*01826a49SYabin Cui             DEBUGLOG(5, "stage zdss_read");
2272*01826a49SYabin Cui             {   size_t const neededInSize = ZSTD_nextSrcSizeToDecompressWithInputSize(zds, (size_t)(iend - ip));
2273*01826a49SYabin Cui                 DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);
2274*01826a49SYabin Cui                 if (neededInSize==0) {  /* end of frame */
2275*01826a49SYabin Cui                     zds->streamStage = zdss_init;
2276*01826a49SYabin Cui                     someMoreWork = 0;
2277*01826a49SYabin Cui                     break;
2278*01826a49SYabin Cui                 }
2279*01826a49SYabin Cui                 if ((size_t)(iend-ip) >= neededInSize) {  /* decode directly from src */
2280*01826a49SYabin Cui                     FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, ip, neededInSize), "");
2281*01826a49SYabin Cui                     assert(ip != NULL);
2282*01826a49SYabin Cui                     ip += neededInSize;
2283*01826a49SYabin Cui                     /* Function modifies the stage so we must break */
2284*01826a49SYabin Cui                     break;
2285*01826a49SYabin Cui             }   }
2286*01826a49SYabin Cui             if (ip==iend) { someMoreWork = 0; break; }   /* no more input */
2287*01826a49SYabin Cui             zds->streamStage = zdss_load;
2288*01826a49SYabin Cui             ZSTD_FALLTHROUGH;
2289*01826a49SYabin Cui 
2290*01826a49SYabin Cui         case zdss_load:
2291*01826a49SYabin Cui             {   size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
2292*01826a49SYabin Cui                 size_t const toLoad = neededInSize - zds->inPos;
2293*01826a49SYabin Cui                 int const isSkipFrame = ZSTD_isSkipFrame(zds);
2294*01826a49SYabin Cui                 size_t loadedSize;
2295*01826a49SYabin Cui                 /* At this point we shouldn't be decompressing a block that we can stream. */
2296*01826a49SYabin Cui                 assert(neededInSize == ZSTD_nextSrcSizeToDecompressWithInputSize(zds, (size_t)(iend - ip)));
2297*01826a49SYabin Cui                 if (isSkipFrame) {
2298*01826a49SYabin Cui                     loadedSize = MIN(toLoad, (size_t)(iend-ip));
2299*01826a49SYabin Cui                 } else {
2300*01826a49SYabin Cui                     RETURN_ERROR_IF(toLoad > zds->inBuffSize - zds->inPos,
2301*01826a49SYabin Cui                                     corruption_detected,
2302*01826a49SYabin Cui                                     "should never happen");
2303*01826a49SYabin Cui                     loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, (size_t)(iend-ip));
2304*01826a49SYabin Cui                 }
2305*01826a49SYabin Cui                 if (loadedSize != 0) {
2306*01826a49SYabin Cui                     /* ip may be NULL */
2307*01826a49SYabin Cui                     ip += loadedSize;
2308*01826a49SYabin Cui                     zds->inPos += loadedSize;
2309*01826a49SYabin Cui                 }
2310*01826a49SYabin Cui                 if (loadedSize < toLoad) { someMoreWork = 0; break; }   /* not enough input, wait for more */
2311*01826a49SYabin Cui 
2312*01826a49SYabin Cui                 /* decode loaded input */
2313*01826a49SYabin Cui                 zds->inPos = 0;   /* input is consumed */
2314*01826a49SYabin Cui                 FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, zds->inBuff, neededInSize), "");
2315*01826a49SYabin Cui                 /* Function modifies the stage so we must break */
2316*01826a49SYabin Cui                 break;
2317*01826a49SYabin Cui             }
2318*01826a49SYabin Cui         case zdss_flush:
2319*01826a49SYabin Cui             {
2320*01826a49SYabin Cui                 size_t const toFlushSize = zds->outEnd - zds->outStart;
2321*01826a49SYabin Cui                 size_t const flushedSize = ZSTD_limitCopy(op, (size_t)(oend-op), zds->outBuff + zds->outStart, toFlushSize);
2322*01826a49SYabin Cui 
2323*01826a49SYabin Cui                 op = op ? op + flushedSize : op;
2324*01826a49SYabin Cui 
2325*01826a49SYabin Cui                 zds->outStart += flushedSize;
2326*01826a49SYabin Cui                 if (flushedSize == toFlushSize) {  /* flush completed */
2327*01826a49SYabin Cui                     zds->streamStage = zdss_read;
2328*01826a49SYabin Cui                     if ( (zds->outBuffSize < zds->fParams.frameContentSize)
2329*01826a49SYabin Cui                         && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {
2330*01826a49SYabin Cui                         DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",
2331*01826a49SYabin Cui                                 (int)(zds->outBuffSize - zds->outStart),
2332*01826a49SYabin Cui                                 (U32)zds->fParams.blockSizeMax);
2333*01826a49SYabin Cui                         zds->outStart = zds->outEnd = 0;
2334*01826a49SYabin Cui                     }
2335*01826a49SYabin Cui                     break;
2336*01826a49SYabin Cui             }   }
2337*01826a49SYabin Cui             /* cannot complete flush */
2338*01826a49SYabin Cui             someMoreWork = 0;
2339*01826a49SYabin Cui             break;
2340*01826a49SYabin Cui 
2341*01826a49SYabin Cui         default:
2342*01826a49SYabin Cui             assert(0);    /* impossible */
2343*01826a49SYabin Cui             RETURN_ERROR(GENERIC, "impossible to reach");   /* some compilers require default to do something */
2344*01826a49SYabin Cui     }   }
2345*01826a49SYabin Cui 
2346*01826a49SYabin Cui     /* result */
2347*01826a49SYabin Cui     input->pos = (size_t)(ip - (const char*)(input->src));
2348*01826a49SYabin Cui     output->pos = (size_t)(op - (char*)(output->dst));
2349*01826a49SYabin Cui 
2350*01826a49SYabin Cui     /* Update the expected output buffer for ZSTD_obm_stable. */
2351*01826a49SYabin Cui     zds->expectedOutBuffer = *output;
2352*01826a49SYabin Cui 
2353*01826a49SYabin Cui     if ((ip==istart) && (op==ostart)) {  /* no forward progress */
2354*01826a49SYabin Cui         zds->noForwardProgress ++;
2355*01826a49SYabin Cui         if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) {
2356*01826a49SYabin Cui             RETURN_ERROR_IF(op==oend, noForwardProgress_destFull, "");
2357*01826a49SYabin Cui             RETURN_ERROR_IF(ip==iend, noForwardProgress_inputEmpty, "");
2358*01826a49SYabin Cui             assert(0);
2359*01826a49SYabin Cui         }
2360*01826a49SYabin Cui     } else {
2361*01826a49SYabin Cui         zds->noForwardProgress = 0;
2362*01826a49SYabin Cui     }
2363*01826a49SYabin Cui     {   size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
2364*01826a49SYabin Cui         if (!nextSrcSizeHint) {   /* frame fully decoded */
2365*01826a49SYabin Cui             if (zds->outEnd == zds->outStart) {  /* output fully flushed */
2366*01826a49SYabin Cui                 if (zds->hostageByte) {
2367*01826a49SYabin Cui                     if (input->pos >= input->size) {
2368*01826a49SYabin Cui                         /* can't release hostage (not present) */
2369*01826a49SYabin Cui                         zds->streamStage = zdss_read;
2370*01826a49SYabin Cui                         return 1;
2371*01826a49SYabin Cui                     }
2372*01826a49SYabin Cui                     input->pos++;  /* release hostage */
2373*01826a49SYabin Cui                 }   /* zds->hostageByte */
2374*01826a49SYabin Cui                 return 0;
2375*01826a49SYabin Cui             }  /* zds->outEnd == zds->outStart */
2376*01826a49SYabin Cui             if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
2377*01826a49SYabin Cui                 input->pos--;   /* note : pos > 0, otherwise, impossible to finish reading last block */
2378*01826a49SYabin Cui                 zds->hostageByte=1;
2379*01826a49SYabin Cui             }
2380*01826a49SYabin Cui             return 1;
2381*01826a49SYabin Cui         }  /* nextSrcSizeHint==0 */
2382*01826a49SYabin Cui         nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block);   /* preload header of next block */
2383*01826a49SYabin Cui         assert(zds->inPos <= nextSrcSizeHint);
2384*01826a49SYabin Cui         nextSrcSizeHint -= zds->inPos;   /* part already loaded*/
2385*01826a49SYabin Cui         return nextSrcSizeHint;
2386*01826a49SYabin Cui     }
2387*01826a49SYabin Cui }
2388*01826a49SYabin Cui 
ZSTD_decompressStream_simpleArgs(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,size_t * dstPos,const void * src,size_t srcSize,size_t * srcPos)2389*01826a49SYabin Cui size_t ZSTD_decompressStream_simpleArgs (
2390*01826a49SYabin Cui                             ZSTD_DCtx* dctx,
2391*01826a49SYabin Cui                             void* dst, size_t dstCapacity, size_t* dstPos,
2392*01826a49SYabin Cui                       const void* src, size_t srcSize, size_t* srcPos)
2393*01826a49SYabin Cui {
2394*01826a49SYabin Cui     ZSTD_outBuffer output;
2395*01826a49SYabin Cui     ZSTD_inBuffer  input;
2396*01826a49SYabin Cui     output.dst = dst;
2397*01826a49SYabin Cui     output.size = dstCapacity;
2398*01826a49SYabin Cui     output.pos = *dstPos;
2399*01826a49SYabin Cui     input.src = src;
2400*01826a49SYabin Cui     input.size = srcSize;
2401*01826a49SYabin Cui     input.pos = *srcPos;
2402*01826a49SYabin Cui     {   size_t const cErr = ZSTD_decompressStream(dctx, &output, &input);
2403*01826a49SYabin Cui         *dstPos = output.pos;
2404*01826a49SYabin Cui         *srcPos = input.pos;
2405*01826a49SYabin Cui         return cErr;
2406*01826a49SYabin Cui     }
2407*01826a49SYabin Cui }
2408