Coverage Report

Created: 2026-10-28 07:09

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