Coverage Report

Created: 2025-07-11 06:35

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