Coverage Report

Created: 2026-10-17 06:31

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