Coverage Report

Created: 2026-10-22 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/tdengine/contrib/TSZ/zstd/decompress/zstd_decompress.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
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 <string.h>      /* memcpy, memmove, memset */
59
#include "cpu.h"         /* bmi2 */
60
#include "mem.h"         /* low level memory routines */
61
#define FSE_STATIC_LINKING_ONLY
62
#include "fse.h"
63
#define HUF_STATIC_LINKING_ONLY
64
#include "huf.h"
65
#include "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
70
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
71
#  include "zstd_legacy.h"
72
#endif
73
74
75
/*-*************************************************************
76
*   Context management
77
***************************************************************/
78
size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)
79
0
{
80
0
    if (dctx==NULL) return 0;   /* support sizeof NULL */
81
0
    return sizeof(*dctx)
82
0
           + ZSTD_sizeof_DDict(dctx->ddictLocal)
83
0
           + dctx->inBuffSize + dctx->outBuffSize;
84
0
}
85
86
0
size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }
87
88
89
static size_t ZSTD_startingInputLength(ZSTD_format_e format)
90
0
{
91
0
    size_t const startingInputLength = (format==ZSTD_f_zstd1_magicless) ?
92
0
                    ZSTD_FRAMEHEADERSIZE_PREFIX - ZSTD_FRAMEIDSIZE :
93
0
                    ZSTD_FRAMEHEADERSIZE_PREFIX;
94
0
    ZSTD_STATIC_ASSERT(ZSTD_FRAMEHEADERSIZE_PREFIX >= ZSTD_FRAMEIDSIZE);
95
    /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */
96
0
    assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );
97
0
    return startingInputLength;
98
0
}
99
100
static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)
101
0
{
102
0
    dctx->format = ZSTD_f_zstd1;  /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */
103
0
    dctx->staticSize  = 0;
104
0
    dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
105
0
    dctx->ddict       = NULL;
106
0
    dctx->ddictLocal  = NULL;
107
0
    dctx->dictEnd     = NULL;
108
0
    dctx->ddictIsCold = 0;
109
0
    dctx->inBuff      = NULL;
110
0
    dctx->inBuffSize  = 0;
111
0
    dctx->outBuffSize = 0;
112
0
    dctx->streamStage = zdss_init;
113
0
    dctx->legacyContext = NULL;
114
0
    dctx->previousLegacyVersion = 0;
115
0
    dctx->noForwardProgress = 0;
116
0
    dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
117
0
}
118
119
ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)
120
0
{
121
0
    ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace;
122
123
0
    if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
124
0
    if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL;  /* minimum size */
125
126
0
    ZSTD_initDCtx_internal(dctx);
127
0
    dctx->staticSize = workspaceSize;
128
0
    dctx->inBuff = (char*)(dctx+1);
129
0
    return dctx;
130
0
}
131
132
ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
133
0
{
134
0
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
135
136
0
    {   ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem);
137
0
        if (!dctx) return NULL;
138
0
        dctx->customMem = customMem;
139
0
        ZSTD_initDCtx_internal(dctx);
140
0
        return dctx;
141
0
    }
142
0
}
143
144
ZSTD_DCtx* ZSTD_createDCtx(void)
145
0
{
146
0
    DEBUGLOG(3, "ZSTD_createDCtx");
147
0
    return ZSTD_createDCtx_advanced(ZSTD_defaultCMem);
148
0
}
149
150
size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
151
0
{
152
0
    if (dctx==NULL) return 0;   /* support free on NULL */
153
0
    if (dctx->staticSize) return ERROR(memory_allocation);   /* not compatible with static DCtx */
154
0
    {   ZSTD_customMem const cMem = dctx->customMem;
155
0
        ZSTD_freeDDict(dctx->ddictLocal);
156
0
        dctx->ddictLocal = NULL;
157
0
        ZSTD_free(dctx->inBuff, cMem);
158
0
        dctx->inBuff = NULL;
159
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
160
        if (dctx->legacyContext)
161
            ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
162
#endif
163
0
        ZSTD_free(dctx, cMem);
164
0
        return 0;
165
0
    }
166
0
}
167
168
/* no longer useful */
169
void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)
170
0
{
171
0
    size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);
172
0
    memcpy(dstDCtx, srcDCtx, toCopy);  /* no need to copy workspace */
173
0
}
174
175
176
/*-*************************************************************
177
 *   Frame header decoding
178
 ***************************************************************/
179
180
/*! ZSTD_isFrame() :
181
 *  Tells if the content of `buffer` starts with a valid Frame Identifier.
182
 *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
183
 *  Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
184
 *  Note 3 : Skippable Frame Identifiers are considered valid. */
185
unsigned ZSTD_isFrame(const void* buffer, size_t size)
186
0
{
187
0
    if (size < ZSTD_FRAMEIDSIZE) return 0;
188
0
    {   U32 const magic = MEM_readLE32(buffer);
189
0
        if (magic == ZSTD_MAGICNUMBER) return 1;
190
0
        if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
191
0
    }
192
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
193
    if (ZSTD_isLegacy(buffer, size)) return 1;
194
#endif
195
0
    return 0;
196
0
}
197
198
/** ZSTD_frameHeaderSize_internal() :
199
 *  srcSize must be large enough to reach header size fields.
200
 *  note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.
201
 * @return : size of the Frame Header
202
 *           or an error code, which can be tested with ZSTD_isError() */
203
static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format)
204
0
{
205
0
    size_t const minInputSize = ZSTD_startingInputLength(format);
206
0
    if (srcSize < minInputSize) return ERROR(srcSize_wrong);
207
208
0
    {   BYTE const fhd = ((const BYTE*)src)[minInputSize-1];
209
0
        U32 const dictID= fhd & 3;
210
0
        U32 const singleSegment = (fhd >> 5) & 1;
211
0
        U32 const fcsId = fhd >> 6;
212
0
        return minInputSize + !singleSegment
213
0
             + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]
214
0
             + (singleSegment && !fcsId);
215
0
    }
216
0
}
217
218
/** ZSTD_frameHeaderSize() :
219
 *  srcSize must be >= ZSTD_frameHeaderSize_prefix.
220
 * @return : size of the Frame Header,
221
 *           or an error code (if srcSize is too small) */
222
size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)
223
0
{
224
0
    return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1);
225
0
}
226
227
228
/** ZSTD_getFrameHeader_advanced() :
229
 *  decode Frame Header, or require larger `srcSize`.
230
 *  note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless
231
 * @return : 0, `zfhPtr` is correctly filled,
232
 *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
233
 *           or an error code, which can be tested using ZSTD_isError() */
234
size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format)
235
0
{
236
0
    const BYTE* ip = (const BYTE*)src;
237
0
    size_t const minInputSize = ZSTD_startingInputLength(format);
238
239
0
    memset(zfhPtr, 0, sizeof(*zfhPtr));   /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */
240
0
    if (srcSize < minInputSize) return minInputSize;
241
0
    if (src==NULL) return ERROR(GENERIC);   /* invalid parameter */
242
243
0
    if ( (format != ZSTD_f_zstd1_magicless)
244
0
      && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) {
245
0
        if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
246
            /* skippable frame */
247
0
            if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
248
0
                return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */
249
0
            memset(zfhPtr, 0, sizeof(*zfhPtr));
250
0
            zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE);
251
0
            zfhPtr->frameType = ZSTD_skippableFrame;
252
0
            return 0;
253
0
        }
254
0
        return ERROR(prefix_unknown);
255
0
    }
256
257
    /* ensure there is enough `srcSize` to fully read/decode frame header */
258
0
    {   size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format);
259
0
        if (srcSize < fhsize) return fhsize;
260
0
        zfhPtr->headerSize = (U32)fhsize;
261
0
    }
262
263
0
    {   BYTE const fhdByte = ip[minInputSize-1];
264
0
        size_t pos = minInputSize;
265
0
        U32 const dictIDSizeCode = fhdByte&3;
266
0
        U32 const checksumFlag = (fhdByte>>2)&1;
267
0
        U32 const singleSegment = (fhdByte>>5)&1;
268
0
        U32 const fcsID = fhdByte>>6;
269
0
        U64 windowSize = 0;
270
0
        U32 dictID = 0;
271
0
        U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;
272
0
        if ((fhdByte & 0x08) != 0)
273
0
            return ERROR(frameParameter_unsupported); /* reserved bits, must be zero */
274
275
0
        if (!singleSegment) {
276
0
            BYTE const wlByte = ip[pos++];
277
0
            U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
278
0
            if (windowLog > ZSTD_WINDOWLOG_MAX)
279
0
                return ERROR(frameParameter_windowTooLarge);
280
0
            windowSize = (1ULL << windowLog);
281
0
            windowSize += (windowSize >> 3) * (wlByte&7);
282
0
        }
283
0
        switch(dictIDSizeCode)
284
0
        {
285
0
            default: assert(0);  /* impossible */
286
0
            case 0 : break;
287
0
            case 1 : dictID = ip[pos]; pos++; break;
288
0
            case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
289
0
            case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
290
0
        }
291
0
        switch(fcsID)
292
0
        {
293
0
            default: assert(0);  /* impossible */
294
0
            case 0 : if (singleSegment) frameContentSize = ip[pos]; break;
295
0
            case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
296
0
            case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
297
0
            case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
298
0
        }
299
0
        if (singleSegment) windowSize = frameContentSize;
300
301
0
        zfhPtr->frameType = ZSTD_frame;
302
0
        zfhPtr->frameContentSize = frameContentSize;
303
0
        zfhPtr->windowSize = windowSize;
304
0
        zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
305
0
        zfhPtr->dictID = dictID;
306
0
        zfhPtr->checksumFlag = checksumFlag;
307
0
    }
308
0
    return 0;
309
0
}
310
311
/** ZSTD_getFrameHeader() :
312
 *  decode Frame Header, or require larger `srcSize`.
313
 *  note : this function does not consume input, it only reads it.
314
 * @return : 0, `zfhPtr` is correctly filled,
315
 *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
316
 *           or an error code, which can be tested using ZSTD_isError() */
317
size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)
318
0
{
319
0
    return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1);
320
0
}
321
322
323
/** ZSTD_getFrameContentSize() :
324
 *  compatible with legacy mode
325
 * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
326
 *         - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
327
 *         - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
328
unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
329
0
{
330
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
331
    if (ZSTD_isLegacy(src, srcSize)) {
332
        unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
333
        return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
334
    }
335
#endif
336
0
    {   ZSTD_frameHeader zfh;
337
0
        if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
338
0
            return ZSTD_CONTENTSIZE_ERROR;
339
0
        if (zfh.frameType == ZSTD_skippableFrame) {
340
0
            return 0;
341
0
        } else {
342
0
            return zfh.frameContentSize;
343
0
    }   }
344
0
}
345
346
static size_t readSkippableFrameSize(void const* src, size_t srcSize)
347
0
{
348
0
    size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;
349
0
    U32 sizeU32;
350
351
0
    if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
352
0
        return ERROR(srcSize_wrong);
353
354
0
    sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);
355
0
    if ((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32)
356
0
        return ERROR(frameParameter_unsupported);
357
358
0
    return skippableHeaderSize + sizeU32;
359
0
}
360
361
/** ZSTD_findDecompressedSize() :
362
 *  compatible with legacy mode
363
 *  `srcSize` must be the exact length of some number of ZSTD compressed and/or
364
 *      skippable frames
365
 *  @return : decompressed size of the frames contained */
366
unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)
367
0
{
368
0
    unsigned long long totalDstSize = 0;
369
370
0
    while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) {
371
0
        U32 const magicNumber = MEM_readLE32(src);
372
373
0
        if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
374
0
            size_t const skippableSize = readSkippableFrameSize(src, srcSize);
375
0
            if (ZSTD_isError(skippableSize))
376
0
                return skippableSize;
377
0
            if (srcSize < skippableSize) {
378
0
                return ZSTD_CONTENTSIZE_ERROR;
379
0
            }
380
381
0
            src = (const BYTE *)src + skippableSize;
382
0
            srcSize -= skippableSize;
383
0
            continue;
384
0
        }
385
386
0
        {   unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
387
0
            if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret;
388
389
            /* check for overflow */
390
0
            if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR;
391
0
            totalDstSize += ret;
392
0
        }
393
0
        {   size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
394
0
            if (ZSTD_isError(frameSrcSize)) {
395
0
                return ZSTD_CONTENTSIZE_ERROR;
396
0
            }
397
398
0
            src = (const BYTE *)src + frameSrcSize;
399
0
            srcSize -= frameSrcSize;
400
0
        }
401
0
    }  /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
402
403
0
    if (srcSize) return ZSTD_CONTENTSIZE_ERROR;
404
405
0
    return totalDstSize;
406
0
}
407
408
/** ZSTD_getDecompressedSize() :
409
 *  compatible with legacy mode
410
 * @return : decompressed size if known, 0 otherwise
411
             note : 0 can mean any of the following :
412
                   - frame content is empty
413
                   - decompressed size field is not present in frame header
414
                   - frame header unknown / not supported
415
                   - frame header not complete (`srcSize` too small) */
416
unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)
417
0
{
418
0
    unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
419
0
    ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN);
420
0
    return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret;
421
0
}
422
423
424
/** ZSTD_decodeFrameHeader() :
425
 * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
426
 * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
427
static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)
428
0
{
429
0
    size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);
430
0
    if (ZSTD_isError(result)) return result;    /* invalid header */
431
0
    if (result>0) return ERROR(srcSize_wrong);  /* headerSize too small */
432
0
    if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID))
433
0
        return ERROR(dictionary_wrong);
434
0
    if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);
435
0
    return 0;
436
0
}
437
438
439
/** ZSTD_findFrameCompressedSize() :
440
 *  compatible with legacy mode
441
 *  `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
442
 *  `srcSize` must be at least as large as the frame contained
443
 *  @return : the compressed size of the frame starting at `src` */
444
size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
445
0
{
446
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
447
    if (ZSTD_isLegacy(src, srcSize))
448
        return ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
449
#endif
450
0
    if ( (srcSize >= ZSTD_SKIPPABLEHEADERSIZE)
451
0
      && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START ) {
452
0
        return readSkippableFrameSize(src, srcSize);
453
0
    } else {
454
0
        const BYTE* ip = (const BYTE*)src;
455
0
        const BYTE* const ipstart = ip;
456
0
        size_t remainingSize = srcSize;
457
0
        ZSTD_frameHeader zfh;
458
459
        /* Extract Frame Header */
460
0
        {   size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize);
461
0
            if (ZSTD_isError(ret)) return ret;
462
0
            if (ret > 0) return ERROR(srcSize_wrong);
463
0
        }
464
465
0
        ip += zfh.headerSize;
466
0
        remainingSize -= zfh.headerSize;
467
468
        /* Loop on each block */
469
0
        while (1) {
470
0
            blockProperties_t blockProperties;
471
0
            size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
472
0
            if (ZSTD_isError(cBlockSize)) return cBlockSize;
473
474
0
            if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
475
0
                return ERROR(srcSize_wrong);
476
477
0
            ip += ZSTD_blockHeaderSize + cBlockSize;
478
0
            remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
479
480
0
            if (blockProperties.lastBlock) break;
481
0
        }
482
483
0
        if (zfh.checksumFlag) {   /* Final frame content checksum */
484
0
            if (remainingSize < 4) return ERROR(srcSize_wrong);
485
0
            ip += 4;
486
0
        }
487
488
0
        return ip - ipstart;
489
0
    }
490
0
}
491
492
493
494
/*-*************************************************************
495
 *   Frame decoding
496
 ***************************************************************/
497
498
499
void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
500
0
{
501
0
    if (dst != dctx->previousDstEnd) {   /* not contiguous */
502
0
        dctx->dictEnd = dctx->previousDstEnd;
503
0
        dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
504
0
        dctx->prefixStart = dst;
505
0
        dctx->previousDstEnd = dst;
506
0
    }
507
0
}
508
509
/** ZSTD_insertBlock() :
510
    insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
511
size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)
512
0
{
513
0
    ZSTD_checkContinuity(dctx, blockStart);
514
0
    dctx->previousDstEnd = (const char*)blockStart + blockSize;
515
0
    return blockSize;
516
0
}
517
518
519
static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
520
                          const void* src, size_t srcSize)
521
0
{
522
0
    DEBUGLOG(5, "ZSTD_copyRawBlock");
523
0
    if (dst == NULL) {
524
0
        if (srcSize == 0) return 0;
525
0
        return ERROR(dstBuffer_null);
526
0
    }
527
0
    if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall);
528
0
    memcpy(dst, src, srcSize);
529
0
    return srcSize;
530
0
}
531
532
static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,
533
                               BYTE b,
534
                               size_t regenSize)
535
0
{
536
0
    if (dst == NULL) {
537
0
        if (regenSize == 0) return 0;
538
0
        return ERROR(dstBuffer_null);
539
0
    }
540
0
    if (regenSize > dstCapacity) return ERROR(dstSize_tooSmall);
541
0
    memset(dst, b, regenSize);
542
0
    return regenSize;
543
0
}
544
545
546
/*! ZSTD_decompressFrame() :
547
 * @dctx must be properly initialized
548
 *  will update *srcPtr and *srcSizePtr,
549
 *  to make *srcPtr progress by one frame. */
550
static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
551
                                   void* dst, size_t dstCapacity,
552
                             const void** srcPtr, size_t *srcSizePtr)
553
0
{
554
0
    const BYTE* ip = (const BYTE*)(*srcPtr);
555
0
    BYTE* const ostart = (BYTE* const)dst;
556
0
    BYTE* const oend = ostart + dstCapacity;
557
0
    BYTE* op = ostart;
558
0
    size_t remainingSrcSize = *srcSizePtr;
559
560
0
    DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);
561
562
    /* check */
563
0
    if (remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN+ZSTD_blockHeaderSize)
564
0
        return ERROR(srcSize_wrong);
565
566
    /* Frame Header */
567
0
    {   size_t const frameHeaderSize = ZSTD_frameHeaderSize(ip, ZSTD_FRAMEHEADERSIZE_PREFIX);
568
0
        if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
569
0
        if (remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize)
570
0
            return ERROR(srcSize_wrong);
571
0
        CHECK_F( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) );
572
0
        ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;
573
0
    }
574
575
    /* Loop on each block */
576
0
    while (1) {
577
0
        size_t decodedSize;
578
0
        blockProperties_t blockProperties;
579
0
        size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);
580
0
        if (ZSTD_isError(cBlockSize)) return cBlockSize;
581
582
0
        ip += ZSTD_blockHeaderSize;
583
0
        remainingSrcSize -= ZSTD_blockHeaderSize;
584
0
        if (cBlockSize > remainingSrcSize) return ERROR(srcSize_wrong);
585
586
0
        switch(blockProperties.blockType)
587
0
        {
588
0
        case bt_compressed:
589
0
            decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1);
590
0
            break;
591
0
        case bt_raw :
592
0
            decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);
593
0
            break;
594
0
        case bt_rle :
595
0
            decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize);
596
0
            break;
597
0
        case bt_reserved :
598
0
        default:
599
0
            return ERROR(corruption_detected);
600
0
        }
601
602
0
        if (ZSTD_isError(decodedSize)) return decodedSize;
603
0
        if (dctx->fParams.checksumFlag)
604
0
            XXH64_update(&dctx->xxhState, op, decodedSize);
605
0
        op += decodedSize;
606
0
        ip += cBlockSize;
607
0
        remainingSrcSize -= cBlockSize;
608
0
        if (blockProperties.lastBlock) break;
609
0
    }
610
611
0
    if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
612
0
        if ((U64)(op-ostart) != dctx->fParams.frameContentSize) {
613
0
            return ERROR(corruption_detected);
614
0
    }   }
615
0
    if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
616
0
        U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
617
0
        U32 checkRead;
618
0
        if (remainingSrcSize<4) return ERROR(checksum_wrong);
619
0
        checkRead = MEM_readLE32(ip);
620
0
        if (checkRead != checkCalc) return ERROR(checksum_wrong);
621
0
        ip += 4;
622
0
        remainingSrcSize -= 4;
623
0
    }
624
625
    /* Allow caller to get size read */
626
0
    *srcPtr = ip;
627
0
    *srcSizePtr = remainingSrcSize;
628
0
    return op-ostart;
629
0
}
630
631
static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
632
                                        void* dst, size_t dstCapacity,
633
                                  const void* src, size_t srcSize,
634
                                  const void* dict, size_t dictSize,
635
                                  const ZSTD_DDict* ddict)
636
0
{
637
0
    void* const dststart = dst;
638
0
    int moreThan1Frame = 0;
639
640
0
    DEBUGLOG(5, "ZSTD_decompressMultiFrame");
641
0
    assert(dict==NULL || ddict==NULL);  /* either dict or ddict set, not both */
642
643
0
    if (ddict) {
644
0
        dict = ZSTD_DDict_dictContent(ddict);
645
0
        dictSize = ZSTD_DDict_dictSize(ddict);
646
0
    }
647
648
0
    while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) {
649
650
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
651
        if (ZSTD_isLegacy(src, srcSize)) {
652
            size_t decodedSize;
653
            size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
654
            if (ZSTD_isError(frameSize)) return frameSize;
655
            /* legacy support is not compatible with static dctx */
656
            if (dctx->staticSize) return ERROR(memory_allocation);
657
658
            decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
659
            if (ZSTD_isError(decodedSize)) return decodedSize;
660
661
            assert(decodedSize <=- dstCapacity);
662
            dst = (BYTE*)dst + decodedSize;
663
            dstCapacity -= decodedSize;
664
665
            src = (const BYTE*)src + frameSize;
666
            srcSize -= frameSize;
667
668
            continue;
669
        }
670
#endif
671
672
0
        {   U32 const magicNumber = MEM_readLE32(src);
673
0
            DEBUGLOG(4, "reading magic number %08X (expecting %08X)",
674
0
                        (unsigned)magicNumber, ZSTD_MAGICNUMBER);
675
0
            if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
676
0
                size_t const skippableSize = readSkippableFrameSize(src, srcSize);
677
0
                if (ZSTD_isError(skippableSize))
678
0
                    return skippableSize;
679
0
                if (srcSize < skippableSize) return ERROR(srcSize_wrong);
680
681
0
                src = (const BYTE *)src + skippableSize;
682
0
                srcSize -= skippableSize;
683
0
                continue;
684
0
        }   }
685
686
0
        if (ddict) {
687
            /* we were called from ZSTD_decompress_usingDDict */
688
0
            CHECK_F(ZSTD_decompressBegin_usingDDict(dctx, ddict));
689
0
        } else {
690
            /* this will initialize correctly with no dict if dict == NULL, so
691
             * use this in all cases but ddict */
692
0
            CHECK_F(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize));
693
0
        }
694
0
        ZSTD_checkContinuity(dctx, dst);
695
696
0
        {   const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
697
0
                                                    &src, &srcSize);
698
0
            if ( (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)
699
0
              && (moreThan1Frame==1) ) {
700
                /* at least one frame successfully completed,
701
                 * but following bytes are garbage :
702
                 * it's more likely to be a srcSize error,
703
                 * specifying more bytes than compressed size of frame(s).
704
                 * This error message replaces ERROR(prefix_unknown),
705
                 * which would be confusing, as the first header is actually correct.
706
                 * Note that one could be unlucky, it might be a corruption error instead,
707
                 * happening right at the place where we expect zstd magic bytes.
708
                 * But this is _much_ less likely than a srcSize field error. */
709
0
                return ERROR(srcSize_wrong);
710
0
            }
711
0
            if (ZSTD_isError(res)) return res;
712
0
            assert(res <= dstCapacity);
713
0
            dst = (BYTE*)dst + res;
714
0
            dstCapacity -= res;
715
0
        }
716
0
        moreThan1Frame = 1;
717
0
    }  /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
718
719
0
    if (srcSize) return ERROR(srcSize_wrong); /* input not entirely consumed */
720
721
0
    return (BYTE*)dst - (BYTE*)dststart;
722
0
}
723
724
size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
725
                                 void* dst, size_t dstCapacity,
726
                           const void* src, size_t srcSize,
727
                           const void* dict, size_t dictSize)
728
0
{
729
0
    return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
730
0
}
731
732
733
size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
734
0
{
735
0
    return ZSTD_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
736
0
}
737
738
739
size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
740
0
{
741
0
#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
742
0
    size_t regenSize;
743
0
    ZSTD_DCtx* const dctx = ZSTD_createDCtx();
744
0
    if (dctx==NULL) return ERROR(memory_allocation);
745
0
    regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
746
0
    ZSTD_freeDCtx(dctx);
747
0
    return regenSize;
748
#else   /* stack mode */
749
    ZSTD_DCtx dctx;
750
    ZSTD_initDCtx_internal(&dctx);
751
    return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
752
#endif
753
0
}
754
755
756
/*-**************************************
757
*   Advanced Streaming Decompression API
758
*   Bufferless and synchronous
759
****************************************/
760
0
size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }
761
762
0
ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {
763
0
    switch(dctx->stage)
764
0
    {
765
0
    default:   /* should not happen */
766
0
        assert(0);
767
0
    case ZSTDds_getFrameHeaderSize:
768
0
    case ZSTDds_decodeFrameHeader:
769
0
        return ZSTDnit_frameHeader;
770
0
    case ZSTDds_decodeBlockHeader:
771
0
        return ZSTDnit_blockHeader;
772
0
    case ZSTDds_decompressBlock:
773
0
        return ZSTDnit_block;
774
0
    case ZSTDds_decompressLastBlock:
775
0
        return ZSTDnit_lastBlock;
776
0
    case ZSTDds_checkChecksum:
777
0
        return ZSTDnit_checksum;
778
0
    case ZSTDds_decodeSkippableHeader:
779
0
    case ZSTDds_skipFrame:
780
0
        return ZSTDnit_skippableFrame;
781
0
    }
782
0
}
783
784
0
static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }
785
786
/** ZSTD_decompressContinue() :
787
 *  srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())
788
 *  @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
789
 *            or an error code, which can be tested using ZSTD_isError() */
790
size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
791
0
{
792
0
    DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize);
793
    /* Sanity check */
794
0
    if (srcSize != dctx->expected)
795
0
        return ERROR(srcSize_wrong);  /* not allowed */
796
0
    if (dstCapacity) ZSTD_checkContinuity(dctx, dst);
797
798
0
    switch (dctx->stage)
799
0
    {
800
0
    case ZSTDds_getFrameHeaderSize :
801
0
        assert(src != NULL);
802
0
        if (dctx->format == ZSTD_f_zstd1) {  /* allows header */
803
0
            assert(srcSize >= ZSTD_FRAMEIDSIZE);  /* to read skippable magic number */
804
0
            if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {        /* skippable frame */
805
0
                memcpy(dctx->headerBuffer, src, srcSize);
806
0
                dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize;  /* remaining to load to get full skippable frame header */
807
0
                dctx->stage = ZSTDds_decodeSkippableHeader;
808
0
                return 0;
809
0
        }   }
810
0
        dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);
811
0
        if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
812
0
        memcpy(dctx->headerBuffer, src, srcSize);
813
0
        dctx->expected = dctx->headerSize - srcSize;
814
0
        dctx->stage = ZSTDds_decodeFrameHeader;
815
0
        return 0;
816
817
0
    case ZSTDds_decodeFrameHeader:
818
0
        assert(src != NULL);
819
0
        memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);
820
0
        CHECK_F(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize));
821
0
        dctx->expected = ZSTD_blockHeaderSize;
822
0
        dctx->stage = ZSTDds_decodeBlockHeader;
823
0
        return 0;
824
825
0
    case ZSTDds_decodeBlockHeader:
826
0
        {   blockProperties_t bp;
827
0
            size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
828
0
            if (ZSTD_isError(cBlockSize)) return cBlockSize;
829
0
            dctx->expected = cBlockSize;
830
0
            dctx->bType = bp.blockType;
831
0
            dctx->rleSize = bp.origSize;
832
0
            if (cBlockSize) {
833
0
                dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
834
0
                return 0;
835
0
            }
836
            /* empty block */
837
0
            if (bp.lastBlock) {
838
0
                if (dctx->fParams.checksumFlag) {
839
0
                    dctx->expected = 4;
840
0
                    dctx->stage = ZSTDds_checkChecksum;
841
0
                } else {
842
0
                    dctx->expected = 0; /* end of frame */
843
0
                    dctx->stage = ZSTDds_getFrameHeaderSize;
844
0
                }
845
0
            } else {
846
0
                dctx->expected = ZSTD_blockHeaderSize;  /* jump to next header */
847
0
                dctx->stage = ZSTDds_decodeBlockHeader;
848
0
            }
849
0
            return 0;
850
0
        }
851
852
0
    case ZSTDds_decompressLastBlock:
853
0
    case ZSTDds_decompressBlock:
854
0
        DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");
855
0
        {   size_t rSize;
856
0
            switch(dctx->bType)
857
0
            {
858
0
            case bt_compressed:
859
0
                DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");
860
0
                rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1);
861
0
                break;
862
0
            case bt_raw :
863
0
                rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
864
0
                break;
865
0
            case bt_rle :
866
0
                rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);
867
0
                break;
868
0
            case bt_reserved :   /* should never happen */
869
0
            default:
870
0
                return ERROR(corruption_detected);
871
0
            }
872
0
            if (ZSTD_isError(rSize)) return rSize;
873
0
            DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);
874
0
            dctx->decodedSize += rSize;
875
0
            if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
876
877
0
            if (dctx->stage == ZSTDds_decompressLastBlock) {   /* end of frame */
878
0
                DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);
879
0
                if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
880
0
                    if (dctx->decodedSize != dctx->fParams.frameContentSize) {
881
0
                        return ERROR(corruption_detected);
882
0
                }   }
883
0
                if (dctx->fParams.checksumFlag) {  /* another round for frame checksum */
884
0
                    dctx->expected = 4;
885
0
                    dctx->stage = ZSTDds_checkChecksum;
886
0
                } else {
887
0
                    dctx->expected = 0;   /* ends here */
888
0
                    dctx->stage = ZSTDds_getFrameHeaderSize;
889
0
                }
890
0
            } else {
891
0
                dctx->stage = ZSTDds_decodeBlockHeader;
892
0
                dctx->expected = ZSTD_blockHeaderSize;
893
0
                dctx->previousDstEnd = (char*)dst + rSize;
894
0
            }
895
0
            return rSize;
896
0
        }
897
898
0
    case ZSTDds_checkChecksum:
899
0
        assert(srcSize == 4);  /* guaranteed by dctx->expected */
900
0
        {   U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
901
0
            U32 const check32 = MEM_readLE32(src);
902
0
            DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);
903
0
            if (check32 != h32) return ERROR(checksum_wrong);
904
0
            dctx->expected = 0;
905
0
            dctx->stage = ZSTDds_getFrameHeaderSize;
906
0
            return 0;
907
0
        }
908
909
0
    case ZSTDds_decodeSkippableHeader:
910
0
        assert(src != NULL);
911
0
        assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);
912
0
        memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize);   /* complete skippable header */
913
0
        dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE);   /* note : dctx->expected can grow seriously large, beyond local buffer size */
914
0
        dctx->stage = ZSTDds_skipFrame;
915
0
        return 0;
916
917
0
    case ZSTDds_skipFrame:
918
0
        dctx->expected = 0;
919
0
        dctx->stage = ZSTDds_getFrameHeaderSize;
920
0
        return 0;
921
922
0
    default:
923
0
        assert(0);   /* impossible */
924
0
        return ERROR(GENERIC);   /* some compiler require default to do something */
925
0
    }
926
0
}
927
928
929
static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
930
0
{
931
0
    dctx->dictEnd = dctx->previousDstEnd;
932
0
    dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
933
0
    dctx->prefixStart = dict;
934
0
    dctx->previousDstEnd = (const char*)dict + dictSize;
935
0
    return 0;
936
0
}
937
938
/*! ZSTD_loadDEntropy() :
939
 *  dict : must point at beginning of a valid zstd dictionary.
940
 * @return : size of entropy tables read */
941
size_t
942
ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
943
                  const void* const dict, size_t const dictSize)
944
0
{
945
0
    const BYTE* dictPtr = (const BYTE*)dict;
946
0
    const BYTE* const dictEnd = dictPtr + dictSize;
947
948
0
    if (dictSize <= 8) return ERROR(dictionary_corrupted);
949
0
    assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY);   /* dict must be valid */
950
0
    dictPtr += 8;   /* skip header = magic + dictID */
951
952
0
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));
953
0
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));
954
0
    ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);
955
0
    {   void* const workspace = &entropy->LLTable;   /* use fse tables as temporary workspace; implies fse tables are grouped together */
956
0
        size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);
957
#ifdef HUF_FORCE_DECOMPRESS_X1
958
        /* in minimal huffman, we always use X1 variants */
959
        size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,
960
                                                dictPtr, dictEnd - dictPtr,
961
                                                workspace, workspaceSize);
962
#else
963
0
        size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,
964
0
                                                dictPtr, dictEnd - dictPtr,
965
0
                                                workspace, workspaceSize);
966
0
#endif
967
0
        if (HUF_isError(hSize)) return ERROR(dictionary_corrupted);
968
0
        dictPtr += hSize;
969
0
    }
970
971
0
    {   short offcodeNCount[MaxOff+1];
972
0
        unsigned offcodeMaxValue = MaxOff, offcodeLog;
973
0
        size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
974
0
        if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
975
0
        if (offcodeMaxValue > MaxOff) return ERROR(dictionary_corrupted);
976
0
        if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
977
0
        ZSTD_buildFSETable( entropy->OFTable,
978
0
                            offcodeNCount, offcodeMaxValue,
979
0
                            OF_base, OF_bits,
980
0
                            offcodeLog);
981
0
        dictPtr += offcodeHeaderSize;
982
0
    }
983
984
0
    {   short matchlengthNCount[MaxML+1];
985
0
        unsigned matchlengthMaxValue = MaxML, matchlengthLog;
986
0
        size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
987
0
        if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
988
0
        if (matchlengthMaxValue > MaxML) return ERROR(dictionary_corrupted);
989
0
        if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
990
0
        ZSTD_buildFSETable( entropy->MLTable,
991
0
                            matchlengthNCount, matchlengthMaxValue,
992
0
                            ML_base, ML_bits,
993
0
                            matchlengthLog);
994
0
        dictPtr += matchlengthHeaderSize;
995
0
    }
996
997
0
    {   short litlengthNCount[MaxLL+1];
998
0
        unsigned litlengthMaxValue = MaxLL, litlengthLog;
999
0
        size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
1000
0
        if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
1001
0
        if (litlengthMaxValue > MaxLL) return ERROR(dictionary_corrupted);
1002
0
        if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
1003
0
        ZSTD_buildFSETable( entropy->LLTable,
1004
0
                            litlengthNCount, litlengthMaxValue,
1005
0
                            LL_base, LL_bits,
1006
0
                            litlengthLog);
1007
0
        dictPtr += litlengthHeaderSize;
1008
0
    }
1009
1010
0
    if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
1011
0
    {   int i;
1012
0
        size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
1013
0
        for (i=0; i<3; i++) {
1014
0
            U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
1015
0
            if (rep==0 || rep >= dictContentSize) return ERROR(dictionary_corrupted);
1016
0
            entropy->rep[i] = rep;
1017
0
    }   }
1018
1019
0
    return dictPtr - (const BYTE*)dict;
1020
0
}
1021
1022
static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1023
0
{
1024
0
    if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
1025
0
    {   U32 const magic = MEM_readLE32(dict);
1026
0
        if (magic != ZSTD_MAGIC_DICTIONARY) {
1027
0
            return ZSTD_refDictContent(dctx, dict, dictSize);   /* pure content mode */
1028
0
    }   }
1029
0
    dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
1030
1031
    /* load entropy tables */
1032
0
    {   size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);
1033
0
        if (ZSTD_isError(eSize)) return ERROR(dictionary_corrupted);
1034
0
        dict = (const char*)dict + eSize;
1035
0
        dictSize -= eSize;
1036
0
    }
1037
0
    dctx->litEntropy = dctx->fseEntropy = 1;
1038
1039
    /* reference dictionary content */
1040
0
    return ZSTD_refDictContent(dctx, dict, dictSize);
1041
0
}
1042
1043
size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
1044
0
{
1045
0
    assert(dctx != NULL);
1046
0
    dctx->expected = ZSTD_startingInputLength(dctx->format);  /* dctx->format must be properly set */
1047
0
    dctx->stage = ZSTDds_getFrameHeaderSize;
1048
0
    dctx->decodedSize = 0;
1049
0
    dctx->previousDstEnd = NULL;
1050
0
    dctx->prefixStart = NULL;
1051
0
    dctx->virtualStart = NULL;
1052
0
    dctx->dictEnd = NULL;
1053
0
    dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001);  /* cover both little and big endian */
1054
0
    dctx->litEntropy = dctx->fseEntropy = 0;
1055
0
    dctx->dictID = 0;
1056
0
    ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
1057
0
    memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue));  /* initial repcodes */
1058
0
    dctx->LLTptr = dctx->entropy.LLTable;
1059
0
    dctx->MLTptr = dctx->entropy.MLTable;
1060
0
    dctx->OFTptr = dctx->entropy.OFTable;
1061
0
    dctx->HUFptr = dctx->entropy.hufTable;
1062
0
    return 0;
1063
0
}
1064
1065
size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1066
0
{
1067
0
    CHECK_F( ZSTD_decompressBegin(dctx) );
1068
0
    if (dict && dictSize)
1069
0
        CHECK_E(ZSTD_decompress_insertDictionary(dctx, dict, dictSize), dictionary_corrupted);
1070
0
    return 0;
1071
0
}
1072
1073
1074
/* ======   ZSTD_DDict   ====== */
1075
1076
size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
1077
0
{
1078
0
    DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict");
1079
0
    assert(dctx != NULL);
1080
0
    if (ddict) {
1081
0
        const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict);
1082
0
        size_t const dictSize = ZSTD_DDict_dictSize(ddict);
1083
0
        const void* const dictEnd = dictStart + dictSize;
1084
0
        dctx->ddictIsCold = (dctx->dictEnd != dictEnd);
1085
0
        DEBUGLOG(4, "DDict is %s",
1086
0
                    dctx->ddictIsCold ? "~cold~" : "hot!");
1087
0
    }
1088
0
    CHECK_F( ZSTD_decompressBegin(dctx) );
1089
0
    if (ddict) {   /* NULL ddict is equivalent to no dictionary */
1090
0
        ZSTD_copyDDictParameters(dctx, ddict);
1091
0
    }
1092
0
    return 0;
1093
0
}
1094
1095
/*! ZSTD_getDictID_fromDict() :
1096
 *  Provides the dictID stored within dictionary.
1097
 *  if @return == 0, the dictionary is not conformant with Zstandard specification.
1098
 *  It can still be loaded, but as a content-only dictionary. */
1099
unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)
1100
0
{
1101
0
    if (dictSize < 8) return 0;
1102
0
    if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;
1103
0
    return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
1104
0
}
1105
1106
/*! ZSTD_getDictID_fromFrame() :
1107
 *  Provides the dictID required to decompresse frame stored within `src`.
1108
 *  If @return == 0, the dictID could not be decoded.
1109
 *  This could for one of the following reasons :
1110
 *  - The frame does not require a dictionary (most common case).
1111
 *  - The frame was built with dictID intentionally removed.
1112
 *    Needed dictionary is a hidden information.
1113
 *    Note : this use case also happens when using a non-conformant dictionary.
1114
 *  - `srcSize` is too small, and as a result, frame header could not be decoded.
1115
 *    Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.
1116
 *  - This is not a Zstandard frame.
1117
 *  When identifying the exact failure cause, it's possible to use
1118
 *  ZSTD_getFrameHeader(), which will provide a more precise error code. */
1119
unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)
1120
0
{
1121
0
    ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 };
1122
0
    size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);
1123
0
    if (ZSTD_isError(hError)) return 0;
1124
0
    return zfp.dictID;
1125
0
}
1126
1127
1128
/*! ZSTD_decompress_usingDDict() :
1129
*   Decompression using a pre-digested Dictionary
1130
*   Use dictionary without significant overhead. */
1131
size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
1132
                                  void* dst, size_t dstCapacity,
1133
                            const void* src, size_t srcSize,
1134
                            const ZSTD_DDict* ddict)
1135
0
{
1136
    /* pass content and size in case legacy frames are encountered */
1137
0
    return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,
1138
0
                                     NULL, 0,
1139
0
                                     ddict);
1140
0
}
1141
1142
1143
/*=====================================
1144
*   Streaming decompression
1145
*====================================*/
1146
1147
ZSTD_DStream* ZSTD_createDStream(void)
1148
0
{
1149
0
    DEBUGLOG(3, "ZSTD_createDStream");
1150
0
    return ZSTD_createDStream_advanced(ZSTD_defaultCMem);
1151
0
}
1152
1153
ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)
1154
0
{
1155
0
    return ZSTD_initStaticDCtx(workspace, workspaceSize);
1156
0
}
1157
1158
ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)
1159
0
{
1160
0
    return ZSTD_createDCtx_advanced(customMem);
1161
0
}
1162
1163
size_t ZSTD_freeDStream(ZSTD_DStream* zds)
1164
0
{
1165
0
    return ZSTD_freeDCtx(zds);
1166
0
}
1167
1168
1169
/* ***  Initialization  *** */
1170
1171
0
size_t ZSTD_DStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }
1172
0
size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }
1173
1174
size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx,
1175
                                   const void* dict, size_t dictSize,
1176
                                         ZSTD_dictLoadMethod_e dictLoadMethod,
1177
                                         ZSTD_dictContentType_e dictContentType)
1178
0
{
1179
0
    if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1180
0
    ZSTD_freeDDict(dctx->ddictLocal);
1181
0
    if (dict && dictSize >= 8) {
1182
0
        dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem);
1183
0
        if (dctx->ddictLocal == NULL) return ERROR(memory_allocation);
1184
0
    } else {
1185
0
        dctx->ddictLocal = NULL;
1186
0
    }
1187
0
    dctx->ddict = dctx->ddictLocal;
1188
0
    return 0;
1189
0
}
1190
1191
size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1192
0
{
1193
0
    return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
1194
0
}
1195
1196
size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1197
0
{
1198
0
    return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1199
0
}
1200
1201
size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
1202
0
{
1203
0
    return ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType);
1204
0
}
1205
1206
size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize)
1207
0
{
1208
0
    return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent);
1209
0
}
1210
1211
1212
/* ZSTD_initDStream_usingDict() :
1213
 * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX.
1214
 * this function cannot fail */
1215
size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)
1216
0
{
1217
0
    DEBUGLOG(4, "ZSTD_initDStream_usingDict");
1218
0
    zds->streamStage = zdss_init;
1219
0
    zds->noForwardProgress = 0;
1220
0
    CHECK_F( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) );
1221
0
    return ZSTD_FRAMEHEADERSIZE_PREFIX;
1222
0
}
1223
1224
/* note : this variant can't fail */
1225
size_t ZSTD_initDStream(ZSTD_DStream* zds)
1226
0
{
1227
0
    DEBUGLOG(4, "ZSTD_initDStream");
1228
0
    return ZSTD_initDStream_usingDict(zds, NULL, 0);
1229
0
}
1230
1231
/* ZSTD_initDStream_usingDDict() :
1232
 * ddict will just be referenced, and must outlive decompression session
1233
 * this function cannot fail */
1234
size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict)
1235
0
{
1236
0
    size_t const initResult = ZSTD_initDStream(dctx);
1237
0
    dctx->ddict = ddict;
1238
0
    return initResult;
1239
0
}
1240
1241
/* ZSTD_resetDStream() :
1242
 * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX.
1243
 * this function cannot fail */
1244
size_t ZSTD_resetDStream(ZSTD_DStream* dctx)
1245
0
{
1246
0
    DEBUGLOG(4, "ZSTD_resetDStream");
1247
0
    dctx->streamStage = zdss_loadHeader;
1248
0
    dctx->lhSize = dctx->inPos = dctx->outStart = dctx->outEnd = 0;
1249
0
    dctx->legacyVersion = 0;
1250
0
    dctx->hostageByte = 0;
1251
0
    return ZSTD_FRAMEHEADERSIZE_PREFIX;
1252
0
}
1253
1254
1255
size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
1256
0
{
1257
0
    if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1258
0
    dctx->ddict = ddict;
1259
0
    return 0;
1260
0
}
1261
1262
/* ZSTD_DCtx_setMaxWindowSize() :
1263
 * note : no direct equivalence in ZSTD_DCtx_setParameter,
1264
 * since this version sets windowSize, and the other sets windowLog */
1265
size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize)
1266
0
{
1267
0
    ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
1268
0
    size_t const min = (size_t)1 << bounds.lowerBound;
1269
0
    size_t const max = (size_t)1 << bounds.upperBound;
1270
0
    if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1271
0
    if (maxWindowSize < min) return ERROR(parameter_outOfBound);
1272
0
    if (maxWindowSize > max) return ERROR(parameter_outOfBound);
1273
0
    dctx->maxWindowSize = maxWindowSize;
1274
0
    return 0;
1275
0
}
1276
1277
size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format)
1278
0
{
1279
0
    return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format);
1280
0
}
1281
1282
ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
1283
0
{
1284
0
    ZSTD_bounds bounds = { 0, 0, 0 };
1285
0
    switch(dParam) {
1286
0
        case ZSTD_d_windowLogMax:
1287
0
            bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
1288
0
            bounds.upperBound = ZSTD_WINDOWLOG_MAX;
1289
0
            return bounds;
1290
0
        case ZSTD_d_format:
1291
0
            bounds.lowerBound = (int)ZSTD_f_zstd1;
1292
0
            bounds.upperBound = (int)ZSTD_f_zstd1_magicless;
1293
0
            ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
1294
0
            return bounds;
1295
0
        default:;
1296
0
    }
1297
0
    bounds.error = ERROR(parameter_unsupported);
1298
0
    return bounds;
1299
0
}
1300
1301
/* ZSTD_dParam_withinBounds:
1302
 * @return 1 if value is within dParam bounds,
1303
 * 0 otherwise */
1304
static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value)
1305
0
{
1306
0
    ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam);
1307
0
    if (ZSTD_isError(bounds.error)) return 0;
1308
0
    if (value < bounds.lowerBound) return 0;
1309
0
    if (value > bounds.upperBound) return 0;
1310
0
    return 1;
1311
0
}
1312
1313
0
#define CHECK_DBOUNDS(p,v) {                \
1314
0
    if (!ZSTD_dParam_withinBounds(p, v))    \
1315
0
        return ERROR(parameter_outOfBound); \
1316
0
}
1317
1318
size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)
1319
0
{
1320
0
    if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1321
0
    switch(dParam) {
1322
0
        case ZSTD_d_windowLogMax:
1323
0
            CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);
1324
0
            dctx->maxWindowSize = ((size_t)1) << value;
1325
0
            return 0;
1326
0
        case ZSTD_d_format:
1327
0
            CHECK_DBOUNDS(ZSTD_d_format, value);
1328
0
            dctx->format = (ZSTD_format_e)value;
1329
0
            return 0;
1330
0
        default:;
1331
0
    }
1332
0
    return ERROR(parameter_unsupported);
1333
0
}
1334
1335
size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)
1336
0
{
1337
0
    if ( (reset == ZSTD_reset_session_only)
1338
0
      || (reset == ZSTD_reset_session_and_parameters) ) {
1339
0
        (void)ZSTD_initDStream(dctx);
1340
0
    }
1341
0
    if ( (reset == ZSTD_reset_parameters)
1342
0
      || (reset == ZSTD_reset_session_and_parameters) ) {
1343
0
        if (dctx->streamStage != zdss_init)
1344
0
            return ERROR(stage_wrong);
1345
0
        dctx->format = ZSTD_f_zstd1;
1346
0
        dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
1347
0
    }
1348
0
    return 0;
1349
0
}
1350
1351
1352
size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx)
1353
0
{
1354
0
    return ZSTD_sizeof_DCtx(dctx);
1355
0
}
1356
1357
size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)
1358
0
{
1359
0
    size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
1360
0
    unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2);
1361
0
    unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);
1362
0
    size_t const minRBSize = (size_t) neededSize;
1363
0
    if ((unsigned long long)minRBSize != neededSize) return ERROR(frameParameter_windowTooLarge);
1364
0
    return minRBSize;
1365
0
}
1366
1367
size_t ZSTD_estimateDStreamSize(size_t windowSize)
1368
0
{
1369
0
    size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
1370
0
    size_t const inBuffSize = blockSize;  /* no block can be larger */
1371
0
    size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);
1372
0
    return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;
1373
0
}
1374
1375
size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)
1376
0
{
1377
0
    U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX;   /* note : should be user-selectable, but requires an additional parameter (or a dctx) */
1378
0
    ZSTD_frameHeader zfh;
1379
0
    size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);
1380
0
    if (ZSTD_isError(err)) return err;
1381
0
    if (err>0) return ERROR(srcSize_wrong);
1382
0
    if (zfh.windowSize > windowSizeMax)
1383
0
        return ERROR(frameParameter_windowTooLarge);
1384
0
    return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);
1385
0
}
1386
1387
1388
/* *****   Decompression   ***** */
1389
1390
MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
1391
0
{
1392
0
    size_t const length = MIN(dstCapacity, srcSize);
1393
0
    memcpy(dst, src, length);
1394
0
    return length;
1395
0
}
1396
1397
1398
size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
1399
0
{
1400
0
    const char* const istart = (const char*)(input->src) + input->pos;
1401
0
    const char* const iend = (const char*)(input->src) + input->size;
1402
0
    const char* ip = istart;
1403
0
    char* const ostart = (char*)(output->dst) + output->pos;
1404
0
    char* const oend = (char*)(output->dst) + output->size;
1405
0
    char* op = ostart;
1406
0
    U32 someMoreWork = 1;
1407
1408
0
    DEBUGLOG(5, "ZSTD_decompressStream");
1409
0
    if (input->pos > input->size) {  /* forbidden */
1410
0
        DEBUGLOG(5, "in: pos: %u   vs size: %u",
1411
0
                    (U32)input->pos, (U32)input->size);
1412
0
        return ERROR(srcSize_wrong);
1413
0
    }
1414
0
    if (output->pos > output->size) {  /* forbidden */
1415
0
        DEBUGLOG(5, "out: pos: %u   vs size: %u",
1416
0
                    (U32)output->pos, (U32)output->size);
1417
0
        return ERROR(dstSize_tooSmall);
1418
0
    }
1419
0
    DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));
1420
1421
0
    while (someMoreWork) {
1422
0
        switch(zds->streamStage)
1423
0
        {
1424
0
        case zdss_init :
1425
0
            DEBUGLOG(5, "stage zdss_init => transparent reset ");
1426
0
            ZSTD_resetDStream(zds);   /* transparent reset on starting decoding a new frame */
1427
            /* fall-through */
1428
1429
0
        case zdss_loadHeader :
1430
0
            DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip));
1431
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
1432
            if (zds->legacyVersion) {
1433
                /* legacy support is incompatible with static dctx */
1434
                if (zds->staticSize) return ERROR(memory_allocation);
1435
                {   size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);
1436
                    if (hint==0) zds->streamStage = zdss_init;
1437
                    return hint;
1438
            }   }
1439
#endif
1440
0
            {   size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format);
1441
0
                DEBUGLOG(5, "header size : %u", (U32)hSize);
1442
0
                if (ZSTD_isError(hSize)) {
1443
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
1444
                    U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);
1445
                    if (legacyVersion) {
1446
                        const void* const dict = zds->ddict ? ZSTD_DDict_dictContent(zds->ddict) : NULL;
1447
                        size_t const dictSize = zds->ddict ? ZSTD_DDict_dictSize(zds->ddict) : 0;
1448
                        DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion);
1449
                        /* legacy support is incompatible with static dctx */
1450
                        if (zds->staticSize) return ERROR(memory_allocation);
1451
                        CHECK_F(ZSTD_initLegacyStream(&zds->legacyContext,
1452
                                    zds->previousLegacyVersion, legacyVersion,
1453
                                    dict, dictSize));
1454
                        zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;
1455
                        {   size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);
1456
                            if (hint==0) zds->streamStage = zdss_init;   /* or stay in stage zdss_loadHeader */
1457
                            return hint;
1458
                    }   }
1459
#endif
1460
0
                    return hSize;   /* error */
1461
0
                }
1462
0
                if (hSize != 0) {   /* need more input */
1463
0
                    size_t const toLoad = hSize - zds->lhSize;   /* if hSize!=0, hSize > zds->lhSize */
1464
0
                    size_t const remainingInput = (size_t)(iend-ip);
1465
0
                    assert(iend >= ip);
1466
0
                    if (toLoad > remainingInput) {   /* not enough input to load full header */
1467
0
                        if (remainingInput > 0) {
1468
0
                            memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput);
1469
0
                            zds->lhSize += remainingInput;
1470
0
                        }
1471
0
                        input->pos = input->size;
1472
0
                        return (MAX(ZSTD_FRAMEHEADERSIZE_MIN, hSize) - zds->lhSize) + ZSTD_blockHeaderSize;   /* remaining header bytes + next block header */
1473
0
                    }
1474
0
                    assert(ip != NULL);
1475
0
                    memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;
1476
0
                    break;
1477
0
            }   }
1478
1479
            /* check for single-pass mode opportunity */
1480
0
            if (zds->fParams.frameContentSize && zds->fParams.windowSize /* skippable frame if == 0 */
1481
0
                && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {
1482
0
                size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart);
1483
0
                if (cSize <= (size_t)(iend-istart)) {
1484
                    /* shortcut : using single-pass mode */
1485
0
                    size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, zds->ddict);
1486
0
                    if (ZSTD_isError(decompressedSize)) return decompressedSize;
1487
0
                    DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()")
1488
0
                    ip = istart + cSize;
1489
0
                    op += decompressedSize;
1490
0
                    zds->expected = 0;
1491
0
                    zds->streamStage = zdss_init;
1492
0
                    someMoreWork = 0;
1493
0
                    break;
1494
0
            }   }
1495
1496
            /* Consume header (see ZSTDds_decodeFrameHeader) */
1497
0
            DEBUGLOG(4, "Consume header");
1498
0
            CHECK_F(ZSTD_decompressBegin_usingDDict(zds, zds->ddict));
1499
1500
0
            if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {  /* skippable frame */
1501
0
                zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE);
1502
0
                zds->stage = ZSTDds_skipFrame;
1503
0
            } else {
1504
0
                CHECK_F(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize));
1505
0
                zds->expected = ZSTD_blockHeaderSize;
1506
0
                zds->stage = ZSTDds_decodeBlockHeader;
1507
0
            }
1508
1509
            /* control buffer memory usage */
1510
0
            DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)",
1511
0
                        (U32)(zds->fParams.windowSize >>10),
1512
0
                        (U32)(zds->maxWindowSize >> 10) );
1513
0
            zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
1514
0
            if (zds->fParams.windowSize > zds->maxWindowSize) return ERROR(frameParameter_windowTooLarge);
1515
1516
            /* Adapt buffer sizes to frame header instructions */
1517
0
            {   size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);
1518
0
                size_t const neededOutBuffSize = ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize);
1519
0
                if ((zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize)) {
1520
0
                    size_t const bufferSize = neededInBuffSize + neededOutBuffSize;
1521
0
                    DEBUGLOG(4, "inBuff  : from %u to %u",
1522
0
                                (U32)zds->inBuffSize, (U32)neededInBuffSize);
1523
0
                    DEBUGLOG(4, "outBuff : from %u to %u",
1524
0
                                (U32)zds->outBuffSize, (U32)neededOutBuffSize);
1525
0
                    if (zds->staticSize) {  /* static DCtx */
1526
0
                        DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);
1527
0
                        assert(zds->staticSize >= sizeof(ZSTD_DCtx));  /* controlled at init */
1528
0
                        if (bufferSize > zds->staticSize - sizeof(ZSTD_DCtx))
1529
0
                            return ERROR(memory_allocation);
1530
0
                    } else {
1531
0
                        ZSTD_free(zds->inBuff, zds->customMem);
1532
0
                        zds->inBuffSize = 0;
1533
0
                        zds->outBuffSize = 0;
1534
0
                        zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem);
1535
0
                        if (zds->inBuff == NULL) return ERROR(memory_allocation);
1536
0
                    }
1537
0
                    zds->inBuffSize = neededInBuffSize;
1538
0
                    zds->outBuff = zds->inBuff + zds->inBuffSize;
1539
0
                    zds->outBuffSize = neededOutBuffSize;
1540
0
            }   }
1541
0
            zds->streamStage = zdss_read;
1542
            /* fall-through */
1543
1544
0
        case zdss_read:
1545
0
            DEBUGLOG(5, "stage zdss_read");
1546
0
            {   size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
1547
0
                DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);
1548
0
                if (neededInSize==0) {  /* end of frame */
1549
0
                    zds->streamStage = zdss_init;
1550
0
                    someMoreWork = 0;
1551
0
                    break;
1552
0
                }
1553
0
                if ((size_t)(iend-ip) >= neededInSize) {  /* decode directly from src */
1554
0
                    int const isSkipFrame = ZSTD_isSkipFrame(zds);
1555
0
                    size_t const decodedSize = ZSTD_decompressContinue(zds,
1556
0
                        zds->outBuff + zds->outStart, (isSkipFrame ? 0 : zds->outBuffSize - zds->outStart),
1557
0
                        ip, neededInSize);
1558
0
                    if (ZSTD_isError(decodedSize)) return decodedSize;
1559
0
                    ip += neededInSize;
1560
0
                    if (!decodedSize && !isSkipFrame) break;   /* this was just a header */
1561
0
                    zds->outEnd = zds->outStart + decodedSize;
1562
0
                    zds->streamStage = zdss_flush;
1563
0
                    break;
1564
0
            }   }
1565
0
            if (ip==iend) { someMoreWork = 0; break; }   /* no more input */
1566
0
            zds->streamStage = zdss_load;
1567
            /* fall-through */
1568
1569
0
        case zdss_load:
1570
0
            {   size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
1571
0
                size_t const toLoad = neededInSize - zds->inPos;
1572
0
                int const isSkipFrame = ZSTD_isSkipFrame(zds);
1573
0
                size_t loadedSize;
1574
0
                if (isSkipFrame) {
1575
0
                    loadedSize = MIN(toLoad, (size_t)(iend-ip));
1576
0
                } else {
1577
0
                    if (toLoad > zds->inBuffSize - zds->inPos) return ERROR(corruption_detected);   /* should never happen */
1578
0
                    loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip);
1579
0
                }
1580
0
                ip += loadedSize;
1581
0
                zds->inPos += loadedSize;
1582
0
                if (loadedSize < toLoad) { someMoreWork = 0; break; }   /* not enough input, wait for more */
1583
1584
                /* decode loaded input */
1585
0
                {   size_t const decodedSize = ZSTD_decompressContinue(zds,
1586
0
                        zds->outBuff + zds->outStart, zds->outBuffSize - zds->outStart,
1587
0
                        zds->inBuff, neededInSize);
1588
0
                    if (ZSTD_isError(decodedSize)) return decodedSize;
1589
0
                    zds->inPos = 0;   /* input is consumed */
1590
0
                    if (!decodedSize && !isSkipFrame) { zds->streamStage = zdss_read; break; }   /* this was just a header */
1591
0
                    zds->outEnd = zds->outStart +  decodedSize;
1592
0
            }   }
1593
0
            zds->streamStage = zdss_flush;
1594
            /* fall-through */
1595
1596
0
        case zdss_flush:
1597
0
            {   size_t const toFlushSize = zds->outEnd - zds->outStart;
1598
0
                size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize);
1599
0
                op += flushedSize;
1600
0
                zds->outStart += flushedSize;
1601
0
                if (flushedSize == toFlushSize) {  /* flush completed */
1602
0
                    zds->streamStage = zdss_read;
1603
0
                    if ( (zds->outBuffSize < zds->fParams.frameContentSize)
1604
0
                      && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {
1605
0
                        DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",
1606
0
                                (int)(zds->outBuffSize - zds->outStart),
1607
0
                                (U32)zds->fParams.blockSizeMax);
1608
0
                        zds->outStart = zds->outEnd = 0;
1609
0
                    }
1610
0
                    break;
1611
0
            }   }
1612
            /* cannot complete flush */
1613
0
            someMoreWork = 0;
1614
0
            break;
1615
1616
0
        default:
1617
0
            assert(0);    /* impossible */
1618
0
            return ERROR(GENERIC);   /* some compiler require default to do something */
1619
0
    }   }
1620
1621
    /* result */
1622
0
    input->pos = (size_t)(ip - (const char*)(input->src));
1623
0
    output->pos = (size_t)(op - (char*)(output->dst));
1624
0
    if ((ip==istart) && (op==ostart)) {  /* no forward progress */
1625
0
        zds->noForwardProgress ++;
1626
0
        if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) {
1627
0
            if (op==oend) return ERROR(dstSize_tooSmall);
1628
0
            if (ip==iend) return ERROR(srcSize_wrong);
1629
0
            assert(0);
1630
0
        }
1631
0
    } else {
1632
0
        zds->noForwardProgress = 0;
1633
0
    }
1634
0
    {   size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
1635
0
        if (!nextSrcSizeHint) {   /* frame fully decoded */
1636
0
            if (zds->outEnd == zds->outStart) {  /* output fully flushed */
1637
0
                if (zds->hostageByte) {
1638
0
                    if (input->pos >= input->size) {
1639
                        /* can't release hostage (not present) */
1640
0
                        zds->streamStage = zdss_read;
1641
0
                        return 1;
1642
0
                    }
1643
0
                    input->pos++;  /* release hostage */
1644
0
                }   /* zds->hostageByte */
1645
0
                return 0;
1646
0
            }  /* zds->outEnd == zds->outStart */
1647
0
            if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
1648
0
                input->pos--;   /* note : pos > 0, otherwise, impossible to finish reading last block */
1649
0
                zds->hostageByte=1;
1650
0
            }
1651
0
            return 1;
1652
0
        }  /* nextSrcSizeHint==0 */
1653
0
        nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block);   /* preload header of next block */
1654
0
        assert(zds->inPos <= nextSrcSizeHint);
1655
0
        nextSrcSizeHint -= zds->inPos;   /* part already loaded*/
1656
0
        return nextSrcSizeHint;
1657
0
    }
1658
0
}
1659
1660
size_t ZSTD_decompressStream_simpleArgs (
1661
                            ZSTD_DCtx* dctx,
1662
                            void* dst, size_t dstCapacity, size_t* dstPos,
1663
                      const void* src, size_t srcSize, size_t* srcPos)
1664
0
{
1665
0
    ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
1666
0
    ZSTD_inBuffer  input  = { src, srcSize, *srcPos };
1667
    /* ZSTD_compress_generic() will check validity of dstPos and srcPos */
1668
0
    size_t const cErr = ZSTD_decompressStream(dctx, &output, &input);
1669
0
    *dstPos = output.pos;
1670
0
    *srcPos = input.pos;
1671
0
    return cErr;
1672
0
}