Coverage Report

Created: 2024-06-18 06:08

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