Coverage Report

Created: 2025-03-15 06:58

/src/zstd/lib/decompress/zstd_decompress_block.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
/* zstd_decompress_block :
12
 * this module takes care of decompressing _compressed_ block */
13
14
/*-*******************************************************
15
*  Dependencies
16
*********************************************************/
17
#include "../common/zstd_deps.h"   /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
18
#include "../common/compiler.h"    /* prefetch */
19
#include "../common/mem.h"         /* low level memory routines */
20
#include <stddef.h>
21
#define FSE_STATIC_LINKING_ONLY
22
#include "../common/fse.h"
23
#include "../common/huf.h"
24
#include "../common/zstd_internal.h"
25
#include "zstd_decompress_internal.h"   /* ZSTD_DCtx */
26
#include "zstd_decompress_block.h"
27
#include "../common/bits.h"  /* ZSTD_highbit32 */
28
29
/*_*******************************************************
30
*  Macros
31
**********************************************************/
32
33
/* These two optional macros force the use one way or another of the two
34
 * ZSTD_decompressSequences implementations. You can't force in both directions
35
 * at the same time.
36
 */
37
#if defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
38
    defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
39
#error "Cannot force the use of the short and the long ZSTD_decompressSequences variants!"
40
#endif
41
42
43
/*_*******************************************************
44
*  Memory operations
45
**********************************************************/
46
3.16M
static void ZSTD_copy4(void* dst, const void* src) { ZSTD_memcpy(dst, src, 4); }
47
48
49
/*-*************************************************************
50
 *   Block decoding
51
 ***************************************************************/
52
53
static size_t ZSTD_blockSizeMax(ZSTD_DCtx const* dctx)
54
79.3k
{
55
79.3k
    size_t const blockSizeMax = dctx->isFrameDecompression ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX;
56
79.3k
    assert(blockSizeMax <= ZSTD_BLOCKSIZE_MAX);
57
79.3k
    return blockSizeMax;
58
79.3k
}
59
60
/*! ZSTD_getcBlockSize() :
61
 *  Provides the size of compressed block from block header `src` */
62
size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
63
                          blockProperties_t* bpPtr)
64
2.00M
{
65
2.00M
    RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, "");
66
67
2.00M
    {   U32 const cBlockHeader = MEM_readLE24(src);
68
2.00M
        U32 const cSize = cBlockHeader >> 3;
69
2.00M
        bpPtr->lastBlock = cBlockHeader & 1;
70
2.00M
        bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
71
2.00M
        bpPtr->origSize = cSize;   /* only useful for RLE */
72
2.00M
        if (bpPtr->blockType == bt_rle) return 1;
73
1.99M
        RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, "");
74
1.99M
        return cSize;
75
1.99M
    }
76
1.99M
}
77
78
/* Allocate buffer for literals, either overlapping current dst, or split between dst and litExtraBuffer, or stored entirely within litExtraBuffer */
79
static void ZSTD_allocateLiteralsBuffer(ZSTD_DCtx* dctx, void* const dst, const size_t dstCapacity, const size_t litSize,
80
    const streaming_operation streaming, const size_t expectedWriteSize, const unsigned splitImmediately)
81
18.0k
{
82
18.0k
    size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);
83
18.0k
    assert(litSize <= blockSizeMax);
84
18.0k
    assert(dctx->isFrameDecompression || streaming == not_streaming);
85
18.0k
    assert(expectedWriteSize <= blockSizeMax);
86
18.0k
    if (streaming == not_streaming && dstCapacity > blockSizeMax + WILDCOPY_OVERLENGTH + litSize + WILDCOPY_OVERLENGTH) {
87
        /* If we aren't streaming, we can just put the literals after the output
88
         * of the current block. We don't need to worry about overwriting the
89
         * extDict of our window, because it doesn't exist.
90
         * So if we have space after the end of the block, just put it there.
91
         */
92
542
        dctx->litBuffer = (BYTE*)dst + blockSizeMax + WILDCOPY_OVERLENGTH;
93
542
        dctx->litBufferEnd = dctx->litBuffer + litSize;
94
542
        dctx->litBufferLocation = ZSTD_in_dst;
95
17.5k
    } else if (litSize <= ZSTD_LITBUFFEREXTRASIZE) {
96
        /* Literals fit entirely within the extra buffer, put them there to avoid
97
         * having to split the literals.
98
         */
99
14.7k
        dctx->litBuffer = dctx->litExtraBuffer;
100
14.7k
        dctx->litBufferEnd = dctx->litBuffer + litSize;
101
14.7k
        dctx->litBufferLocation = ZSTD_not_in_dst;
102
14.7k
    } else {
103
2.77k
        assert(blockSizeMax > ZSTD_LITBUFFEREXTRASIZE);
104
        /* Literals must be split between the output block and the extra lit
105
         * buffer. We fill the extra lit buffer with the tail of the literals,
106
         * and put the rest of the literals at the end of the block, with
107
         * WILDCOPY_OVERLENGTH of buffer room to allow for overreads.
108
         * This MUST not write more than our maxBlockSize beyond dst, because in
109
         * streaming mode, that could overwrite part of our extDict window.
110
         */
111
2.77k
        if (splitImmediately) {
112
            /* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */
113
2.76k
            dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;
114
2.76k
            dctx->litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE;
115
2.76k
        } else {
116
            /* initially this will be stored entirely in dst during huffman decoding, it will partially be shifted to litExtraBuffer after */
117
9
            dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize;
118
9
            dctx->litBufferEnd = (BYTE*)dst + expectedWriteSize;
119
9
        }
120
2.77k
        dctx->litBufferLocation = ZSTD_split;
121
2.77k
        assert(dctx->litBufferEnd <= (BYTE*)dst + expectedWriteSize);
122
2.77k
    }
123
18.0k
}
124
125
/*! ZSTD_decodeLiteralsBlock() :
126
 * Where it is possible to do so without being stomped by the output during decompression, the literals block will be stored
127
 * in the dstBuffer.  If there is room to do so, it will be stored in full in the excess dst space after where the current
128
 * block will be output.  Otherwise it will be stored at the end of the current dst blockspace, with a small portion being
129
 * stored in dctx->litExtraBuffer to help keep it "ahead" of the current output write.
130
 *
131
 * @return : nb of bytes read from src (< srcSize )
132
 *  note : symbol not declared but exposed for fullbench */
133
static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
134
                          const void* src, size_t srcSize,   /* note : srcSize < BLOCKSIZE */
135
                          void* dst, size_t dstCapacity, const streaming_operation streaming)
136
18.7k
{
137
18.7k
    DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");
138
18.7k
    RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");
139
140
18.6k
    {   const BYTE* const istart = (const BYTE*) src;
141
18.6k
        SymbolEncodingType_e const litEncType = (SymbolEncodingType_e)(istart[0] & 3);
142
18.6k
        size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);
143
144
18.6k
        switch(litEncType)
145
18.6k
        {
146
287
        case set_repeat:
147
287
            DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");
148
287
            RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");
149
235
            ZSTD_FALLTHROUGH;
150
151
11.6k
        case set_compressed:
152
11.6k
            RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need up to 5 for case 3");
153
11.6k
            {   size_t lhSize, litSize, litCSize;
154
11.6k
                U32 singleStream=0;
155
11.6k
                U32 const lhlCode = (istart[0] >> 2) & 3;
156
11.6k
                U32 const lhc = MEM_readLE32(istart);
157
11.6k
                size_t hufSuccess;
158
11.6k
                size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
159
11.6k
                int const flags = 0
160
11.6k
                    | (ZSTD_DCtx_get_bmi2(dctx) ? HUF_flags_bmi2 : 0)
161
11.6k
                    | (dctx->disableHufAsm ? HUF_flags_disableAsm : 0);
162
11.6k
                switch(lhlCode)
163
11.6k
                {
164
11.3k
                case 0: case 1: default:   /* note : default is impossible, since lhlCode into [0..3] */
165
                    /* 2 - 2 - 10 - 10 */
166
11.3k
                    singleStream = !lhlCode;
167
11.3k
                    lhSize = 3;
168
11.3k
                    litSize  = (lhc >> 4) & 0x3FF;
169
11.3k
                    litCSize = (lhc >> 14) & 0x3FF;
170
11.3k
                    break;
171
79
                case 2:
172
                    /* 2 - 2 - 14 - 14 */
173
79
                    lhSize = 4;
174
79
                    litSize  = (lhc >> 4) & 0x3FFF;
175
79
                    litCSize = lhc >> 18;
176
79
                    break;
177
179
                case 3:
178
                    /* 2 - 2 - 18 - 18 */
179
179
                    lhSize = 5;
180
179
                    litSize  = (lhc >> 4) & 0x3FFFF;
181
179
                    litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);
182
179
                    break;
183
11.6k
                }
184
11.6k
                RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
185
11.6k
                RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
186
11.5k
                if (!singleStream)
187
11.0k
                    RETURN_ERROR_IF(litSize < MIN_LITERALS_FOR_4_STREAMS, literals_headerWrong,
188
11.5k
                        "Not enough literals (%zu) for the 4-streams mode (min %u)",
189
11.5k
                        litSize, MIN_LITERALS_FOR_4_STREAMS);
190
11.4k
                RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");
191
11.3k
                RETURN_ERROR_IF(expectedWriteSize < litSize , dstSize_tooSmall, "");
192
11.3k
                ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 0);
193
194
                /* prefetch huffman table if cold */
195
11.3k
                if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
196
0
                    PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
197
0
                }
198
199
11.3k
                if (litEncType==set_repeat) {
200
148
                    if (singleStream) {
201
124
                        hufSuccess = HUF_decompress1X_usingDTable(
202
124
                            dctx->litBuffer, litSize, istart+lhSize, litCSize,
203
124
                            dctx->HUFptr, flags);
204
124
                    } else {
205
24
                        assert(litSize >= MIN_LITERALS_FOR_4_STREAMS);
206
24
                        hufSuccess = HUF_decompress4X_usingDTable(
207
24
                            dctx->litBuffer, litSize, istart+lhSize, litCSize,
208
24
                            dctx->HUFptr, flags);
209
24
                    }
210
11.1k
                } else {
211
11.1k
                    if (singleStream) {
212
#if defined(HUF_FORCE_DECOMPRESS_X2)
213
                        hufSuccess = HUF_decompress1X_DCtx_wksp(
214
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
215
                            istart+lhSize, litCSize, dctx->workspace,
216
                            sizeof(dctx->workspace), flags);
217
#else
218
316
                        hufSuccess = HUF_decompress1X1_DCtx_wksp(
219
316
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
220
316
                            istart+lhSize, litCSize, dctx->workspace,
221
316
                            sizeof(dctx->workspace), flags);
222
316
#endif
223
10.8k
                    } else {
224
10.8k
                        hufSuccess = HUF_decompress4X_hufOnly_wksp(
225
10.8k
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
226
10.8k
                            istart+lhSize, litCSize, dctx->workspace,
227
10.8k
                            sizeof(dctx->workspace), flags);
228
10.8k
                    }
229
11.1k
                }
230
11.3k
                if (dctx->litBufferLocation == ZSTD_split)
231
9
                {
232
9
                    assert(litSize > ZSTD_LITBUFFEREXTRASIZE);
233
9
                    ZSTD_memcpy(dctx->litExtraBuffer, dctx->litBufferEnd - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);
234
9
                    ZSTD_memmove(dctx->litBuffer + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH, dctx->litBuffer, litSize - ZSTD_LITBUFFEREXTRASIZE);
235
9
                    dctx->litBuffer += ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;
236
9
                    dctx->litBufferEnd -= WILDCOPY_OVERLENGTH;
237
9
                    assert(dctx->litBufferEnd <= (BYTE*)dst + blockSizeMax);
238
9
                }
239
240
11.3k
                RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");
241
242
6.56k
                dctx->litPtr = dctx->litBuffer;
243
6.56k
                dctx->litSize = litSize;
244
6.56k
                dctx->litEntropy = 1;
245
6.56k
                if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
246
6.56k
                return litCSize + lhSize;
247
11.3k
            }
248
249
2.18k
        case set_basic:
250
2.18k
            {   size_t litSize, lhSize;
251
2.18k
                U32 const lhlCode = ((istart[0]) >> 2) & 3;
252
2.18k
                size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
253
2.18k
                switch(lhlCode)
254
2.18k
                {
255
1.60k
                case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
256
1.60k
                    lhSize = 1;
257
1.60k
                    litSize = istart[0] >> 3;
258
1.60k
                    break;
259
377
                case 1:
260
377
                    lhSize = 2;
261
377
                    litSize = MEM_readLE16(istart) >> 4;
262
377
                    break;
263
203
                case 3:
264
203
                    lhSize = 3;
265
203
                    RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize = 3");
266
152
                    litSize = MEM_readLE24(istart) >> 4;
267
152
                    break;
268
2.18k
                }
269
270
2.13k
                RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
271
2.13k
                RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
272
2.09k
                RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");
273
2.08k
                ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);
274
2.08k
                if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) {  /* risk reading beyond src buffer with wildcopy */
275
1.89k
                    RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");
276
1.82k
                    if (dctx->litBufferLocation == ZSTD_split)
277
0
                    {
278
0
                        ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize - ZSTD_LITBUFFEREXTRASIZE);
279
0
                        ZSTD_memcpy(dctx->litExtraBuffer, istart + lhSize + litSize - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);
280
0
                    }
281
1.82k
                    else
282
1.82k
                    {
283
1.82k
                        ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize);
284
1.82k
                    }
285
1.82k
                    dctx->litPtr = dctx->litBuffer;
286
1.82k
                    dctx->litSize = litSize;
287
1.82k
                    return lhSize+litSize;
288
1.89k
                }
289
                /* direct reference into compressed stream */
290
194
                dctx->litPtr = istart+lhSize;
291
194
                dctx->litSize = litSize;
292
194
                dctx->litBufferEnd = dctx->litPtr + litSize;
293
194
                dctx->litBufferLocation = ZSTD_not_in_dst;
294
194
                return lhSize+litSize;
295
2.08k
            }
296
297
4.77k
        case set_rle:
298
4.77k
            {   U32 const lhlCode = ((istart[0]) >> 2) & 3;
299
4.77k
                size_t litSize, lhSize;
300
4.77k
                size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
301
4.77k
                switch(lhlCode)
302
4.77k
                {
303
283
                case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
304
283
                    lhSize = 1;
305
283
                    litSize = istart[0] >> 3;
306
283
                    break;
307
731
                case 1:
308
731
                    lhSize = 2;
309
731
                    RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 3");
310
729
                    litSize = MEM_readLE16(istart) >> 4;
311
729
                    break;
312
3.76k
                case 3:
313
3.76k
                    lhSize = 3;
314
3.76k
                    RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 4");
315
3.75k
                    litSize = MEM_readLE24(istart) >> 4;
316
3.75k
                    break;
317
4.77k
                }
318
4.77k
                RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
319
4.77k
                RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
320
4.70k
                RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");
321
4.66k
                ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);
322
4.66k
                if (dctx->litBufferLocation == ZSTD_split)
323
2.75k
                {
324
2.75k
                    ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize - ZSTD_LITBUFFEREXTRASIZE);
325
2.75k
                    ZSTD_memset(dctx->litExtraBuffer, istart[lhSize], ZSTD_LITBUFFEREXTRASIZE);
326
2.75k
                }
327
1.91k
                else
328
1.91k
                {
329
1.91k
                    ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize);
330
1.91k
                }
331
4.66k
                dctx->litPtr = dctx->litBuffer;
332
4.66k
                dctx->litSize = litSize;
333
4.66k
                return lhSize+1;
334
4.70k
            }
335
0
        default:
336
0
            RETURN_ERROR(corruption_detected, "impossible");
337
18.6k
        }
338
18.6k
    }
339
18.6k
}
340
341
/* Hidden declaration for fullbench */
342
size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx,
343
                          const void* src, size_t srcSize,
344
                          void* dst, size_t dstCapacity);
345
size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx,
346
                          const void* src, size_t srcSize,
347
                          void* dst, size_t dstCapacity)
348
0
{
349
0
    dctx->isFrameDecompression = 0;
350
0
    return ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, not_streaming);
351
0
}
352
353
/* Default FSE distribution tables.
354
 * These are pre-calculated FSE decoding tables using default distributions as defined in specification :
355
 * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#default-distributions
356
 * They were generated programmatically with following method :
357
 * - start from default distributions, present in /lib/common/zstd_internal.h
358
 * - generate tables normally, using ZSTD_buildFSETable()
359
 * - printout the content of tables
360
 * - prettify output, report below, test with fuzzer to ensure it's correct */
361
362
/* Default FSE distribution table for Literal Lengths */
363
static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
364
     {  1,  1,  1, LL_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
365
     /* nextState, nbAddBits, nbBits, baseVal */
366
     {  0,  0,  4,    0},  { 16,  0,  4,    0},
367
     { 32,  0,  5,    1},  {  0,  0,  5,    3},
368
     {  0,  0,  5,    4},  {  0,  0,  5,    6},
369
     {  0,  0,  5,    7},  {  0,  0,  5,    9},
370
     {  0,  0,  5,   10},  {  0,  0,  5,   12},
371
     {  0,  0,  6,   14},  {  0,  1,  5,   16},
372
     {  0,  1,  5,   20},  {  0,  1,  5,   22},
373
     {  0,  2,  5,   28},  {  0,  3,  5,   32},
374
     {  0,  4,  5,   48},  { 32,  6,  5,   64},
375
     {  0,  7,  5,  128},  {  0,  8,  6,  256},
376
     {  0, 10,  6, 1024},  {  0, 12,  6, 4096},
377
     { 32,  0,  4,    0},  {  0,  0,  4,    1},
378
     {  0,  0,  5,    2},  { 32,  0,  5,    4},
379
     {  0,  0,  5,    5},  { 32,  0,  5,    7},
380
     {  0,  0,  5,    8},  { 32,  0,  5,   10},
381
     {  0,  0,  5,   11},  {  0,  0,  6,   13},
382
     { 32,  1,  5,   16},  {  0,  1,  5,   18},
383
     { 32,  1,  5,   22},  {  0,  2,  5,   24},
384
     { 32,  3,  5,   32},  {  0,  3,  5,   40},
385
     {  0,  6,  4,   64},  { 16,  6,  4,   64},
386
     { 32,  7,  5,  128},  {  0,  9,  6,  512},
387
     {  0, 11,  6, 2048},  { 48,  0,  4,    0},
388
     { 16,  0,  4,    1},  { 32,  0,  5,    2},
389
     { 32,  0,  5,    3},  { 32,  0,  5,    5},
390
     { 32,  0,  5,    6},  { 32,  0,  5,    8},
391
     { 32,  0,  5,    9},  { 32,  0,  5,   11},
392
     { 32,  0,  5,   12},  {  0,  0,  6,   15},
393
     { 32,  1,  5,   18},  { 32,  1,  5,   20},
394
     { 32,  2,  5,   24},  { 32,  2,  5,   28},
395
     { 32,  3,  5,   40},  { 32,  4,  5,   48},
396
     {  0, 16,  6,65536},  {  0, 15,  6,32768},
397
     {  0, 14,  6,16384},  {  0, 13,  6, 8192},
398
};   /* LL_defaultDTable */
399
400
/* Default FSE distribution table for Offset Codes */
401
static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
402
    {  1,  1,  1, OF_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
403
    /* nextState, nbAddBits, nbBits, baseVal */
404
    {  0,  0,  5,    0},     {  0,  6,  4,   61},
405
    {  0,  9,  5,  509},     {  0, 15,  5,32765},
406
    {  0, 21,  5,2097149},   {  0,  3,  5,    5},
407
    {  0,  7,  4,  125},     {  0, 12,  5, 4093},
408
    {  0, 18,  5,262141},    {  0, 23,  5,8388605},
409
    {  0,  5,  5,   29},     {  0,  8,  4,  253},
410
    {  0, 14,  5,16381},     {  0, 20,  5,1048573},
411
    {  0,  2,  5,    1},     { 16,  7,  4,  125},
412
    {  0, 11,  5, 2045},     {  0, 17,  5,131069},
413
    {  0, 22,  5,4194301},   {  0,  4,  5,   13},
414
    { 16,  8,  4,  253},     {  0, 13,  5, 8189},
415
    {  0, 19,  5,524285},    {  0,  1,  5,    1},
416
    { 16,  6,  4,   61},     {  0, 10,  5, 1021},
417
    {  0, 16,  5,65533},     {  0, 28,  5,268435453},
418
    {  0, 27,  5,134217725}, {  0, 26,  5,67108861},
419
    {  0, 25,  5,33554429},  {  0, 24,  5,16777213},
420
};   /* OF_defaultDTable */
421
422
423
/* Default FSE distribution table for Match Lengths */
424
static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
425
    {  1,  1,  1, ML_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
426
    /* nextState, nbAddBits, nbBits, baseVal */
427
    {  0,  0,  6,    3},  {  0,  0,  4,    4},
428
    { 32,  0,  5,    5},  {  0,  0,  5,    6},
429
    {  0,  0,  5,    8},  {  0,  0,  5,    9},
430
    {  0,  0,  5,   11},  {  0,  0,  6,   13},
431
    {  0,  0,  6,   16},  {  0,  0,  6,   19},
432
    {  0,  0,  6,   22},  {  0,  0,  6,   25},
433
    {  0,  0,  6,   28},  {  0,  0,  6,   31},
434
    {  0,  0,  6,   34},  {  0,  1,  6,   37},
435
    {  0,  1,  6,   41},  {  0,  2,  6,   47},
436
    {  0,  3,  6,   59},  {  0,  4,  6,   83},
437
    {  0,  7,  6,  131},  {  0,  9,  6,  515},
438
    { 16,  0,  4,    4},  {  0,  0,  4,    5},
439
    { 32,  0,  5,    6},  {  0,  0,  5,    7},
440
    { 32,  0,  5,    9},  {  0,  0,  5,   10},
441
    {  0,  0,  6,   12},  {  0,  0,  6,   15},
442
    {  0,  0,  6,   18},  {  0,  0,  6,   21},
443
    {  0,  0,  6,   24},  {  0,  0,  6,   27},
444
    {  0,  0,  6,   30},  {  0,  0,  6,   33},
445
    {  0,  1,  6,   35},  {  0,  1,  6,   39},
446
    {  0,  2,  6,   43},  {  0,  3,  6,   51},
447
    {  0,  4,  6,   67},  {  0,  5,  6,   99},
448
    {  0,  8,  6,  259},  { 32,  0,  4,    4},
449
    { 48,  0,  4,    4},  { 16,  0,  4,    5},
450
    { 32,  0,  5,    7},  { 32,  0,  5,    8},
451
    { 32,  0,  5,   10},  { 32,  0,  5,   11},
452
    {  0,  0,  6,   14},  {  0,  0,  6,   17},
453
    {  0,  0,  6,   20},  {  0,  0,  6,   23},
454
    {  0,  0,  6,   26},  {  0,  0,  6,   29},
455
    {  0,  0,  6,   32},  {  0, 16,  6,65539},
456
    {  0, 15,  6,32771},  {  0, 14,  6,16387},
457
    {  0, 13,  6, 8195},  {  0, 12,  6, 4099},
458
    {  0, 11,  6, 2051},  {  0, 10,  6, 1027},
459
};   /* ML_defaultDTable */
460
461
462
static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U8 nbAddBits)
463
1.74k
{
464
1.74k
    void* ptr = dt;
465
1.74k
    ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
466
1.74k
    ZSTD_seqSymbol* const cell = dt + 1;
467
468
1.74k
    DTableH->tableLog = 0;
469
1.74k
    DTableH->fastMode = 0;
470
471
1.74k
    cell->nbBits = 0;
472
1.74k
    cell->nextState = 0;
473
1.74k
    assert(nbAddBits < 255);
474
1.74k
    cell->nbAdditionalBits = nbAddBits;
475
1.74k
    cell->baseValue = baseValue;
476
1.74k
}
477
478
479
/* ZSTD_buildFSETable() :
480
 * generate FSE decoding table for one symbol (ll, ml or off)
481
 * cannot fail if input is valid =>
482
 * all inputs are presumed validated at this stage */
483
FORCE_INLINE_TEMPLATE
484
void ZSTD_buildFSETable_body(ZSTD_seqSymbol* dt,
485
            const short* normalizedCounter, unsigned maxSymbolValue,
486
            const U32* baseValue, const U8* nbAdditionalBits,
487
            unsigned tableLog, void* wksp, size_t wkspSize)
488
3.20k
{
489
3.20k
    ZSTD_seqSymbol* const tableDecode = dt+1;
490
3.20k
    U32 const maxSV1 = maxSymbolValue + 1;
491
3.20k
    U32 const tableSize = 1 << tableLog;
492
493
3.20k
    U16* symbolNext = (U16*)wksp;
494
3.20k
    BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1);
495
3.20k
    U32 highThreshold = tableSize - 1;
496
497
498
    /* Sanity Checks */
499
3.20k
    assert(maxSymbolValue <= MaxSeq);
500
3.20k
    assert(tableLog <= MaxFSELog);
501
3.20k
    assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE);
502
3.20k
    (void)wkspSize;
503
    /* Init, lay down lowprob symbols */
504
3.20k
    {   ZSTD_seqSymbol_header DTableH;
505
3.20k
        DTableH.tableLog = tableLog;
506
3.20k
        DTableH.fastMode = 1;
507
3.20k
        {   S16 const largeLimit= (S16)(1 << (tableLog-1));
508
3.20k
            U32 s;
509
36.6k
            for (s=0; s<maxSV1; s++) {
510
33.4k
                if (normalizedCounter[s]==-1) {
511
11.0k
                    tableDecode[highThreshold--].baseValue = s;
512
11.0k
                    symbolNext[s] = 1;
513
22.4k
                } else {
514
22.4k
                    if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
515
22.4k
                    assert(normalizedCounter[s]>=0);
516
22.4k
                    symbolNext[s] = (U16)normalizedCounter[s];
517
22.4k
        }   }   }
518
3.20k
        ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
519
3.20k
    }
520
521
    /* Spread symbols */
522
3.20k
    assert(tableSize <= 512);
523
    /* Specialized symbol spreading for the case when there are
524
     * no low probability (-1 count) symbols. When compressing
525
     * small blocks we avoid low probability symbols to hit this
526
     * case, since header decoding speed matters more.
527
     */
528
3.20k
    if (highThreshold == tableSize - 1) {
529
400
        size_t const tableMask = tableSize-1;
530
400
        size_t const step = FSE_TABLESTEP(tableSize);
531
        /* First lay down the symbols in order.
532
         * We use a uint64_t to lay down 8 bytes at a time. This reduces branch
533
         * misses since small blocks generally have small table logs, so nearly
534
         * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
535
         * our buffer to handle the over-write.
536
         */
537
400
        {
538
400
            U64 const add = 0x0101010101010101ull;
539
400
            size_t pos = 0;
540
400
            U64 sv = 0;
541
400
            U32 s;
542
3.85k
            for (s=0; s<maxSV1; ++s, sv += add) {
543
3.45k
                int i;
544
3.45k
                int const n = normalizedCounter[s];
545
3.45k
                MEM_write64(spread + pos, sv);
546
7.59k
                for (i = 8; i < n; i += 8) {
547
4.14k
                    MEM_write64(spread + pos + i, sv);
548
4.14k
                }
549
3.45k
                assert(n>=0);
550
3.45k
                pos += (size_t)n;
551
3.45k
            }
552
400
        }
553
        /* Now we spread those positions across the table.
554
         * The benefit of doing it in two stages is that we avoid the
555
         * variable size inner loop, which caused lots of branch misses.
556
         * Now we can run through all the positions without any branch misses.
557
         * We unroll the loop twice, since that is what empirically worked best.
558
         */
559
400
        {
560
400
            size_t position = 0;
561
400
            size_t s;
562
400
            size_t const unroll = 2;
563
400
            assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
564
19.9k
            for (s = 0; s < (size_t)tableSize; s += unroll) {
565
19.5k
                size_t u;
566
58.6k
                for (u = 0; u < unroll; ++u) {
567
39.1k
                    size_t const uPosition = (position + (u * step)) & tableMask;
568
39.1k
                    tableDecode[uPosition].baseValue = spread[s + u];
569
39.1k
                }
570
19.5k
                position = (position + (unroll * step)) & tableMask;
571
19.5k
            }
572
400
            assert(position == 0);
573
400
        }
574
2.80k
    } else {
575
2.80k
        U32 const tableMask = tableSize-1;
576
2.80k
        U32 const step = FSE_TABLESTEP(tableSize);
577
2.80k
        U32 s, position = 0;
578
32.8k
        for (s=0; s<maxSV1; s++) {
579
30.0k
            int i;
580
30.0k
            int const n = normalizedCounter[s];
581
154k
            for (i=0; i<n; i++) {
582
124k
                tableDecode[position].baseValue = s;
583
124k
                position = (position + step) & tableMask;
584
135k
                while (UNLIKELY(position > highThreshold)) position = (position + step) & tableMask;   /* lowprob area */
585
124k
        }   }
586
2.80k
        assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
587
2.80k
    }
588
589
    /* Build Decoding table */
590
3.20k
    {
591
3.20k
        U32 u;
592
178k
        for (u=0; u<tableSize; u++) {
593
174k
            U32 const symbol = tableDecode[u].baseValue;
594
174k
            U32 const nextState = symbolNext[symbol]++;
595
174k
            tableDecode[u].nbBits = (BYTE) (tableLog - ZSTD_highbit32(nextState) );
596
174k
            tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
597
174k
            assert(nbAdditionalBits[symbol] < 255);
598
174k
            tableDecode[u].nbAdditionalBits = nbAdditionalBits[symbol];
599
174k
            tableDecode[u].baseValue = baseValue[symbol];
600
174k
        }
601
3.20k
    }
602
3.20k
}
603
604
/* Avoids the FORCE_INLINE of the _body() function. */
605
static void ZSTD_buildFSETable_body_default(ZSTD_seqSymbol* dt,
606
            const short* normalizedCounter, unsigned maxSymbolValue,
607
            const U32* baseValue, const U8* nbAdditionalBits,
608
            unsigned tableLog, void* wksp, size_t wkspSize)
609
0
{
610
0
    ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
611
0
            baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
612
0
}
613
614
#if DYNAMIC_BMI2
615
BMI2_TARGET_ATTRIBUTE static void ZSTD_buildFSETable_body_bmi2(ZSTD_seqSymbol* dt,
616
            const short* normalizedCounter, unsigned maxSymbolValue,
617
            const U32* baseValue, const U8* nbAdditionalBits,
618
            unsigned tableLog, void* wksp, size_t wkspSize)
619
3.20k
{
620
3.20k
    ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
621
3.20k
            baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
622
3.20k
}
623
#endif
624
625
void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
626
            const short* normalizedCounter, unsigned maxSymbolValue,
627
            const U32* baseValue, const U8* nbAdditionalBits,
628
            unsigned tableLog, void* wksp, size_t wkspSize, int bmi2)
629
3.20k
{
630
3.20k
#if DYNAMIC_BMI2
631
3.20k
    if (bmi2) {
632
3.20k
        ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue,
633
3.20k
                baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
634
3.20k
        return;
635
3.20k
    }
636
0
#endif
637
0
    (void)bmi2;
638
0
    ZSTD_buildFSETable_body_default(dt, normalizedCounter, maxSymbolValue,
639
0
            baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
640
0
}
641
642
643
/*! ZSTD_buildSeqTable() :
644
 * @return : nb bytes read from src,
645
 *           or an error code if it fails */
646
static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
647
                                 SymbolEncodingType_e type, unsigned max, U32 maxLog,
648
                                 const void* src, size_t srcSize,
649
                                 const U32* baseValue, const U8* nbAdditionalBits,
650
                                 const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
651
                                 int ddictIsCold, int nbSeq, U32* wksp, size_t wkspSize,
652
                                 int bmi2)
653
12.4k
{
654
12.4k
    switch(type)
655
12.4k
    {
656
1.83k
    case set_rle :
657
1.83k
        RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
658
1.80k
        RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
659
1.74k
        {   U32 const symbol = *(const BYTE*)src;
660
1.74k
            U32 const baseline = baseValue[symbol];
661
1.74k
            U8 const nbBits = nbAdditionalBits[symbol];
662
1.74k
            ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
663
1.74k
        }
664
1.74k
        *DTablePtr = DTableSpace;
665
1.74k
        return 1;
666
6.96k
    case set_basic :
667
6.96k
        *DTablePtr = defaultTable;
668
6.96k
        return 0;
669
91
    case set_repeat:
670
91
        RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
671
        /* prefetch FSE table if used */
672
6
        if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
673
0
            const void* const pStart = *DTablePtr;
674
0
            size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
675
0
            PREFETCH_AREA(pStart, pSize);
676
0
        }
677
6
        return 0;
678
3.54k
    case set_compressed :
679
3.54k
        {   unsigned tableLog;
680
3.54k
            S16 norm[MaxSeq+1];
681
3.54k
            size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
682
3.54k
            RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
683
3.26k
            RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
684
3.20k
            ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2);
685
3.20k
            *DTablePtr = DTableSpace;
686
3.20k
            return headerSize;
687
3.26k
        }
688
0
    default :
689
0
        assert(0);
690
0
        RETURN_ERROR(GENERIC, "impossible");
691
12.4k
    }
692
12.4k
}
693
694
size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
695
                             const void* src, size_t srcSize)
696
13.2k
{
697
13.2k
    const BYTE* const istart = (const BYTE*)src;
698
13.2k
    const BYTE* const iend = istart + srcSize;
699
13.2k
    const BYTE* ip = istart;
700
13.2k
    int nbSeq;
701
13.2k
    DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
702
703
    /* check */
704
13.2k
    RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");
705
706
    /* SeqHead */
707
13.1k
    nbSeq = *ip++;
708
13.1k
    if (nbSeq > 0x7F) {
709
3.42k
        if (nbSeq == 0xFF) {
710
151
            RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
711
86
            nbSeq = MEM_readLE16(ip) + LONGNBSEQ;
712
86
            ip+=2;
713
3.27k
        } else {
714
3.27k
            RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
715
3.15k
            nbSeq = ((nbSeq-0x80)<<8) + *ip++;
716
3.15k
        }
717
3.42k
    }
718
12.9k
    *nbSeqPtr = nbSeq;
719
720
12.9k
    if (nbSeq == 0) {
721
        /* No sequence : section ends immediately */
722
8.31k
        RETURN_ERROR_IF(ip != iend, corruption_detected,
723
8.31k
            "extraneous data present in the Sequences section");
724
8.20k
        return (size_t)(ip - istart);
725
8.31k
    }
726
727
    /* FSE table descriptors */
728
4.65k
    RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
729
4.52k
    RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */
730
4.30k
    {   SymbolEncodingType_e const LLtype = (SymbolEncodingType_e)(*ip >> 6);
731
4.30k
        SymbolEncodingType_e const OFtype = (SymbolEncodingType_e)((*ip >> 4) & 3);
732
4.30k
        SymbolEncodingType_e const MLtype = (SymbolEncodingType_e)((*ip >> 2) & 3);
733
4.30k
        ip++;
734
735
        /* Build DTables */
736
4.30k
        assert(ip <= iend);
737
4.30k
        {   size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
738
4.30k
                                                      LLtype, MaxLL, LLFSELog,
739
4.30k
                                                      ip, (size_t)(iend-ip),
740
4.30k
                                                      LL_base, LL_bits,
741
4.30k
                                                      LL_defaultDTable, dctx->fseEntropy,
742
4.30k
                                                      dctx->ddictIsCold, nbSeq,
743
4.30k
                                                      dctx->workspace, sizeof(dctx->workspace),
744
4.30k
                                                      ZSTD_DCtx_get_bmi2(dctx));
745
4.30k
            RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
746
4.26k
            ip += llhSize;
747
4.26k
        }
748
749
4.26k
        assert(ip <= iend);
750
4.26k
        {   size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
751
4.26k
                                                      OFtype, MaxOff, OffFSELog,
752
4.26k
                                                      ip, (size_t)(iend-ip),
753
4.26k
                                                      OF_base, OF_bits,
754
4.26k
                                                      OF_defaultDTable, dctx->fseEntropy,
755
4.26k
                                                      dctx->ddictIsCold, nbSeq,
756
4.26k
                                                      dctx->workspace, sizeof(dctx->workspace),
757
4.26k
                                                      ZSTD_DCtx_get_bmi2(dctx));
758
4.26k
            RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
759
3.86k
            ip += ofhSize;
760
3.86k
        }
761
762
3.86k
        assert(ip <= iend);
763
3.86k
        {   size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
764
3.86k
                                                      MLtype, MaxML, MLFSELog,
765
3.86k
                                                      ip, (size_t)(iend-ip),
766
3.86k
                                                      ML_base, ML_bits,
767
3.86k
                                                      ML_defaultDTable, dctx->fseEntropy,
768
3.86k
                                                      dctx->ddictIsCold, nbSeq,
769
3.86k
                                                      dctx->workspace, sizeof(dctx->workspace),
770
3.86k
                                                      ZSTD_DCtx_get_bmi2(dctx));
771
3.86k
            RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");
772
3.78k
            ip += mlhSize;
773
3.78k
        }
774
3.78k
    }
775
776
0
    return (size_t)(ip-istart);
777
3.86k
}
778
779
780
typedef struct {
781
    size_t litLength;
782
    size_t matchLength;
783
    size_t offset;
784
} seq_t;
785
786
typedef struct {
787
    size_t state;
788
    const ZSTD_seqSymbol* table;
789
} ZSTD_fseState;
790
791
typedef struct {
792
    BIT_DStream_t DStream;
793
    ZSTD_fseState stateLL;
794
    ZSTD_fseState stateOffb;
795
    ZSTD_fseState stateML;
796
    size_t prevOffset[ZSTD_REP_NUM];
797
} seqState_t;
798
799
/*! ZSTD_overlapCopy8() :
800
 *  Copies 8 bytes from ip to op and updates op and ip where ip <= op.
801
 *  If the offset is < 8 then the offset is spread to at least 8 bytes.
802
 *
803
 *  Precondition: *ip <= *op
804
 *  Postcondition: *op - *op >= 8
805
 */
806
HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset)
807
3.95M
{
808
3.95M
    assert(*ip <= *op);
809
3.95M
    if (offset < 8) {
810
        /* close range match, overlap */
811
3.16M
        static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 };   /* added */
812
3.16M
        static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 };   /* subtracted */
813
3.16M
        int const sub2 = dec64table[offset];
814
3.16M
        (*op)[0] = (*ip)[0];
815
3.16M
        (*op)[1] = (*ip)[1];
816
3.16M
        (*op)[2] = (*ip)[2];
817
3.16M
        (*op)[3] = (*ip)[3];
818
3.16M
        *ip += dec32table[offset];
819
3.16M
        ZSTD_copy4(*op+4, *ip);
820
3.16M
        *ip -= sub2;
821
3.16M
    } else {
822
784k
        ZSTD_copy8(*op, *ip);
823
784k
    }
824
3.95M
    *ip += 8;
825
3.95M
    *op += 8;
826
3.95M
    assert(*op - *ip >= 8);
827
3.95M
}
828
829
/*! ZSTD_safecopy() :
830
 *  Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer
831
 *  and write up to 16 bytes past oend_w (op >= oend_w is allowed).
832
 *  This function is only called in the uncommon case where the sequence is near the end of the block. It
833
 *  should be fast for a single long sequence, but can be slow for several short sequences.
834
 *
835
 *  @param ovtype controls the overlap detection
836
 *         - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
837
 *         - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
838
 *           The src buffer must be before the dst buffer.
839
 */
840
static void
841
ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, size_t length, ZSTD_overlap_e ovtype)
842
844k
{
843
844k
    ptrdiff_t const diff = op - ip;
844
844k
    BYTE* const oend = op + length;
845
846
844k
    assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
847
844k
           (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
848
849
844k
    if (length < 8) {
850
        /* Handle short lengths. */
851
1.52M
        while (op < oend) *op++ = *ip++;
852
341k
        return;
853
341k
    }
854
503k
    if (ovtype == ZSTD_overlap_src_before_dst) {
855
        /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
856
503k
        assert(length >= 8);
857
503k
        assert(diff > 0);
858
503k
        ZSTD_overlapCopy8(&op, &ip, (size_t)diff);
859
503k
        length -= 8;
860
503k
        assert(op - ip >= 8);
861
503k
        assert(op <= oend);
862
503k
    }
863
864
503k
    if (oend <= oend_w) {
865
        /* No risk of overwrite. */
866
155
        ZSTD_wildcopy(op, ip, length, ovtype);
867
155
        return;
868
155
    }
869
503k
    if (op <= oend_w) {
870
        /* Wildcopy until we get close to the end. */
871
1.42k
        assert(oend > oend_w);
872
1.42k
        ZSTD_wildcopy(op, ip, (size_t)(oend_w - op), ovtype);
873
1.42k
        ip += oend_w - op;
874
1.42k
        op += oend_w - op;
875
1.42k
    }
876
    /* Handle the leftovers. */
877
3.92G
    while (op < oend) *op++ = *ip++;
878
503k
}
879
880
/* ZSTD_safecopyDstBeforeSrc():
881
 * This version allows overlap with dst before src, or handles the non-overlap case with dst after src
882
 * Kept separate from more common ZSTD_safecopy case to avoid performance impact to the safecopy common case */
883
static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, size_t length)
884
844k
{
885
844k
    ptrdiff_t const diff = op - ip;
886
844k
    BYTE* const oend = op + length;
887
888
844k
    if (length < 8 || diff > -8) {
889
        /* Handle short lengths, close overlaps, and dst not before src. */
890
10.8M
        while (op < oend) *op++ = *ip++;
891
843k
        return;
892
843k
    }
893
894
1.48k
    if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) {
895
855
        ZSTD_wildcopy(op, ip, (size_t)(oend - WILDCOPY_OVERLENGTH - op), ZSTD_no_overlap);
896
855
        ip += oend - WILDCOPY_OVERLENGTH - op;
897
855
        op += oend - WILDCOPY_OVERLENGTH - op;
898
855
    }
899
900
    /* Handle the leftovers. */
901
84.6k
    while (op < oend) *op++ = *ip++;
902
1.48k
}
903
904
/* ZSTD_execSequenceEnd():
905
 * This version handles cases that are near the end of the output buffer. It requires
906
 * more careful checks to make sure there is no overflow. By separating out these hard
907
 * and unlikely cases, we can speed up the common cases.
908
 *
909
 * NOTE: This function needs to be fast for a single long sequence, but doesn't need
910
 * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
911
 */
912
FORCE_NOINLINE
913
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
914
size_t ZSTD_execSequenceEnd(BYTE* op,
915
    BYTE* const oend, seq_t sequence,
916
    const BYTE** litPtr, const BYTE* const litLimit,
917
    const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
918
2.38k
{
919
2.38k
    BYTE* const oLitEnd = op + sequence.litLength;
920
2.38k
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
921
2.38k
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
922
2.38k
    const BYTE* match = oLitEnd - sequence.offset;
923
2.38k
    BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
924
925
    /* bounds checks : careful of address space overflow in 32-bit mode */
926
2.38k
    RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
927
1.56k
    RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
928
772
    assert(op < op + sequenceLength);
929
772
    assert(oLitEnd < op + sequenceLength);
930
931
    /* copy literals */
932
772
    ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
933
772
    op = oLitEnd;
934
772
    *litPtr = iLitEnd;
935
936
    /* copy Match */
937
772
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
938
        /* offset beyond prefix */
939
54
        RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
940
2
        match = dictEnd - (prefixStart - match);
941
2
        if (match + sequence.matchLength <= dictEnd) {
942
0
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
943
0
            return sequenceLength;
944
0
        }
945
        /* span extDict & currentPrefixSegment */
946
2
        {   size_t const length1 = (size_t)(dictEnd - match);
947
2
            ZSTD_memmove(oLitEnd, match, length1);
948
2
            op = oLitEnd + length1;
949
2
            sequence.matchLength -= length1;
950
2
            match = prefixStart;
951
2
        }
952
2
    }
953
720
    ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
954
720
    return sequenceLength;
955
772
}
956
957
/* ZSTD_execSequenceEndSplitLitBuffer():
958
 * This version is intended to be used during instances where the litBuffer is still split.  It is kept separate to avoid performance impact for the good case.
959
 */
960
FORCE_NOINLINE
961
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
962
size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op,
963
    BYTE* const oend, const BYTE* const oend_w, seq_t sequence,
964
    const BYTE** litPtr, const BYTE* const litLimit,
965
    const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
966
843k
{
967
843k
    BYTE* const oLitEnd = op + sequence.litLength;
968
843k
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
969
843k
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
970
843k
    const BYTE* match = oLitEnd - sequence.offset;
971
972
973
    /* bounds checks : careful of address space overflow in 32-bit mode */
974
843k
    RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
975
843k
    RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
976
843k
    assert(op < op + sequenceLength);
977
843k
    assert(oLitEnd < op + sequenceLength);
978
979
    /* copy literals */
980
843k
    RETURN_ERROR_IF(op > *litPtr && op < *litPtr + sequence.litLength, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer");
981
843k
    ZSTD_safecopyDstBeforeSrc(op, *litPtr, sequence.litLength);
982
843k
    op = oLitEnd;
983
843k
    *litPtr = iLitEnd;
984
985
    /* copy Match */
986
843k
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
987
        /* offset beyond prefix */
988
108
        RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
989
0
        match = dictEnd - (prefixStart - match);
990
0
        if (match + sequence.matchLength <= dictEnd) {
991
0
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
992
0
            return sequenceLength;
993
0
        }
994
        /* span extDict & currentPrefixSegment */
995
0
        {   size_t const length1 = (size_t)(dictEnd - match);
996
0
            ZSTD_memmove(oLitEnd, match, length1);
997
0
            op = oLitEnd + length1;
998
0
            sequence.matchLength -= length1;
999
0
            match = prefixStart;
1000
0
        }
1001
0
    }
1002
843k
    ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
1003
843k
    return sequenceLength;
1004
843k
}
1005
1006
HINT_INLINE
1007
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1008
size_t ZSTD_execSequence(BYTE* op,
1009
    BYTE* const oend, seq_t sequence,
1010
    const BYTE** litPtr, const BYTE* const litLimit,
1011
    const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
1012
3.44M
{
1013
3.44M
    BYTE* const oLitEnd = op + sequence.litLength;
1014
3.44M
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
1015
3.44M
    BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
1016
3.44M
    BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;   /* risk : address space underflow on oend=NULL */
1017
3.44M
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
1018
3.44M
    const BYTE* match = oLitEnd - sequence.offset;
1019
1020
3.44M
    assert(op != NULL /* Precondition */);
1021
3.44M
    assert(oend_w < oend /* No underflow */);
1022
1023
#if defined(__aarch64__)
1024
    /* prefetch sequence starting from match that will be used for copy later */
1025
    PREFETCH_L1(match);
1026
#endif
1027
    /* Handle edge cases in a slow path:
1028
     *   - Read beyond end of literals
1029
     *   - Match end is within WILDCOPY_OVERLIMIT of oend
1030
     *   - 32-bit mode and the match length overflows
1031
     */
1032
3.44M
    if (UNLIKELY(
1033
3.44M
        iLitEnd > litLimit ||
1034
3.44M
        oMatchEnd > oend_w ||
1035
3.44M
        (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
1036
2.38k
        return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
1037
1038
    /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
1039
3.43M
    assert(op <= oLitEnd /* No overflow */);
1040
3.43M
    assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
1041
3.43M
    assert(oMatchEnd <= oend /* No underflow */);
1042
3.43M
    assert(iLitEnd <= litLimit /* Literal length is in bounds */);
1043
3.43M
    assert(oLitEnd <= oend_w /* Can wildcopy literals */);
1044
3.43M
    assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
1045
1046
    /* Copy Literals:
1047
     * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
1048
     * We likely don't need the full 32-byte wildcopy.
1049
     */
1050
3.43M
    assert(WILDCOPY_OVERLENGTH >= 16);
1051
3.43M
    ZSTD_copy16(op, (*litPtr));
1052
3.43M
    if (UNLIKELY(sequence.litLength > 16)) {
1053
501k
        ZSTD_wildcopy(op + 16, (*litPtr) + 16, sequence.litLength - 16, ZSTD_no_overlap);
1054
501k
    }
1055
3.43M
    op = oLitEnd;
1056
3.43M
    *litPtr = iLitEnd;   /* update for next sequence */
1057
1058
    /* Copy Match */
1059
3.43M
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
1060
        /* offset beyond prefix -> go into extDict */
1061
613
        RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
1062
125
        match = dictEnd + (match - prefixStart);
1063
125
        if (match + sequence.matchLength <= dictEnd) {
1064
113
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
1065
113
            return sequenceLength;
1066
113
        }
1067
        /* span extDict & currentPrefixSegment */
1068
12
        {   size_t const length1 = (size_t)(dictEnd - match);
1069
12
            ZSTD_memmove(oLitEnd, match, length1);
1070
12
            op = oLitEnd + length1;
1071
12
            sequence.matchLength -= length1;
1072
12
            match = prefixStart;
1073
12
        }
1074
12
    }
1075
    /* Match within prefix of 1 or more bytes */
1076
3.43M
    assert(op <= oMatchEnd);
1077
3.43M
    assert(oMatchEnd <= oend_w);
1078
3.43M
    assert(match >= prefixStart);
1079
3.43M
    assert(sequence.matchLength >= 1);
1080
1081
    /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
1082
     * without overlap checking.
1083
     */
1084
3.43M
    if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
1085
        /* We bet on a full wildcopy for matches, since we expect matches to be
1086
         * longer than literals (in general). In silesia, ~10% of matches are longer
1087
         * than 16 bytes.
1088
         */
1089
1.14M
        ZSTD_wildcopy(op, match, sequence.matchLength, ZSTD_no_overlap);
1090
1.14M
        return sequenceLength;
1091
1.14M
    }
1092
2.29M
    assert(sequence.offset < WILDCOPY_VECLEN);
1093
1094
    /* Copy 8 bytes and spread the offset to be >= 8. */
1095
2.29M
    ZSTD_overlapCopy8(&op, &match, sequence.offset);
1096
1097
    /* If the match length is > 8 bytes, then continue with the wildcopy. */
1098
2.29M
    if (sequence.matchLength > 8) {
1099
830k
        assert(op < oMatchEnd);
1100
830k
        ZSTD_wildcopy(op, match, sequence.matchLength - 8, ZSTD_overlap_src_before_dst);
1101
830k
    }
1102
2.29M
    return sequenceLength;
1103
3.43M
}
1104
1105
HINT_INLINE
1106
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1107
size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op,
1108
    BYTE* const oend, const BYTE* const oend_w, seq_t sequence,
1109
    const BYTE** litPtr, const BYTE* const litLimit,
1110
    const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
1111
2.69M
{
1112
2.69M
    BYTE* const oLitEnd = op + sequence.litLength;
1113
2.69M
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
1114
2.69M
    BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
1115
2.69M
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
1116
2.69M
    const BYTE* match = oLitEnd - sequence.offset;
1117
1118
2.69M
    assert(op != NULL /* Precondition */);
1119
2.69M
    assert(oend_w < oend /* No underflow */);
1120
    /* Handle edge cases in a slow path:
1121
     *   - Read beyond end of literals
1122
     *   - Match end is within WILDCOPY_OVERLIMIT of oend
1123
     *   - 32-bit mode and the match length overflows
1124
     */
1125
2.69M
    if (UNLIKELY(
1126
2.69M
            iLitEnd > litLimit ||
1127
2.69M
            oMatchEnd > oend_w ||
1128
2.69M
            (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
1129
843k
        return ZSTD_execSequenceEndSplitLitBuffer(op, oend, oend_w, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
1130
1131
    /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
1132
1.85M
    assert(op <= oLitEnd /* No overflow */);
1133
1.85M
    assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
1134
1.85M
    assert(oMatchEnd <= oend /* No underflow */);
1135
1.85M
    assert(iLitEnd <= litLimit /* Literal length is in bounds */);
1136
1.85M
    assert(oLitEnd <= oend_w /* Can wildcopy literals */);
1137
1.85M
    assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
1138
1139
    /* Copy Literals:
1140
     * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
1141
     * We likely don't need the full 32-byte wildcopy.
1142
     */
1143
1.85M
    assert(WILDCOPY_OVERLENGTH >= 16);
1144
1.85M
    ZSTD_copy16(op, (*litPtr));
1145
1.85M
    if (UNLIKELY(sequence.litLength > 16)) {
1146
58.6k
        ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
1147
58.6k
    }
1148
1.85M
    op = oLitEnd;
1149
1.85M
    *litPtr = iLitEnd;   /* update for next sequence */
1150
1151
    /* Copy Match */
1152
1.85M
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
1153
        /* offset beyond prefix -> go into extDict */
1154
164
        RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
1155
0
        match = dictEnd + (match - prefixStart);
1156
0
        if (match + sequence.matchLength <= dictEnd) {
1157
0
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
1158
0
            return sequenceLength;
1159
0
        }
1160
        /* span extDict & currentPrefixSegment */
1161
0
        {   size_t const length1 = (size_t)(dictEnd - match);
1162
0
            ZSTD_memmove(oLitEnd, match, length1);
1163
0
            op = oLitEnd + length1;
1164
0
            sequence.matchLength -= length1;
1165
0
            match = prefixStart;
1166
0
    }   }
1167
    /* Match within prefix of 1 or more bytes */
1168
1.85M
    assert(op <= oMatchEnd);
1169
1.85M
    assert(oMatchEnd <= oend_w);
1170
1.85M
    assert(match >= prefixStart);
1171
1.85M
    assert(sequence.matchLength >= 1);
1172
1173
    /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
1174
     * without overlap checking.
1175
     */
1176
1.85M
    if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
1177
        /* We bet on a full wildcopy for matches, since we expect matches to be
1178
         * longer than literals (in general). In silesia, ~10% of matches are longer
1179
         * than 16 bytes.
1180
         */
1181
703k
        ZSTD_wildcopy(op, match, sequence.matchLength, ZSTD_no_overlap);
1182
703k
        return sequenceLength;
1183
703k
    }
1184
1.15M
    assert(sequence.offset < WILDCOPY_VECLEN);
1185
1186
    /* Copy 8 bytes and spread the offset to be >= 8. */
1187
1.15M
    ZSTD_overlapCopy8(&op, &match, sequence.offset);
1188
1189
    /* If the match length is > 8 bytes, then continue with the wildcopy. */
1190
1.15M
    if (sequence.matchLength > 8) {
1191
168k
        assert(op < oMatchEnd);
1192
168k
        ZSTD_wildcopy(op, match, sequence.matchLength-8, ZSTD_overlap_src_before_dst);
1193
168k
    }
1194
1.15M
    return sequenceLength;
1195
1.85M
}
1196
1197
1198
static void
1199
ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
1200
9.83k
{
1201
9.83k
    const void* ptr = dt;
1202
9.83k
    const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
1203
9.83k
    DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
1204
9.83k
    DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
1205
9.83k
                (U32)DStatePtr->state, DTableH->tableLog);
1206
9.83k
    BIT_reloadDStream(bitD);
1207
9.83k
    DStatePtr->table = dt + 1;
1208
9.83k
}
1209
1210
FORCE_INLINE_TEMPLATE void
1211
ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, U16 nextState, U32 nbBits)
1212
18.4M
{
1213
18.4M
    size_t const lowBits = BIT_readBits(bitD, nbBits);
1214
18.4M
    DStatePtr->state = nextState + lowBits;
1215
18.4M
}
1216
1217
/* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
1218
 * offset bits. But we can only read at most STREAM_ACCUMULATOR_MIN_32
1219
 * bits before reloading. This value is the maximum number of bytes we read
1220
 * after reloading when we are decoding long offsets.
1221
 */
1222
#define LONG_OFFSETS_MAX_EXTRA_BITS_32                       \
1223
0
    (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32       \
1224
0
        ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32  \
1225
0
        : 0)
1226
1227
typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
1228
1229
/**
1230
 * ZSTD_decodeSequence():
1231
 * @p longOffsets : tells the decoder to reload more bit while decoding large offsets
1232
 *                  only used in 32-bit mode
1233
 * @return : Sequence (litL + matchL + offset)
1234
 */
1235
FORCE_INLINE_TEMPLATE seq_t
1236
ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq)
1237
6.13M
{
1238
6.13M
    seq_t seq;
1239
    /*
1240
     * ZSTD_seqSymbol is a 64 bits wide structure.
1241
     * It can be loaded in one operation
1242
     * and its fields extracted by simply shifting or bit-extracting on aarch64.
1243
     * GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh
1244
     * operations that cause performance drop. This can be avoided by using this
1245
     * ZSTD_memcpy hack.
1246
     */
1247
#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__))
1248
    ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS;
1249
    ZSTD_seqSymbol* const llDInfo = &llDInfoS;
1250
    ZSTD_seqSymbol* const mlDInfo = &mlDInfoS;
1251
    ZSTD_seqSymbol* const ofDInfo = &ofDInfoS;
1252
    ZSTD_memcpy(llDInfo, seqState->stateLL.table + seqState->stateLL.state, sizeof(ZSTD_seqSymbol));
1253
    ZSTD_memcpy(mlDInfo, seqState->stateML.table + seqState->stateML.state, sizeof(ZSTD_seqSymbol));
1254
    ZSTD_memcpy(ofDInfo, seqState->stateOffb.table + seqState->stateOffb.state, sizeof(ZSTD_seqSymbol));
1255
#else
1256
6.13M
    const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state;
1257
6.13M
    const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state;
1258
6.13M
    const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state;
1259
6.13M
#endif
1260
6.13M
    seq.matchLength = mlDInfo->baseValue;
1261
6.13M
    seq.litLength = llDInfo->baseValue;
1262
6.13M
    {   U32 const ofBase = ofDInfo->baseValue;
1263
6.13M
        BYTE const llBits = llDInfo->nbAdditionalBits;
1264
6.13M
        BYTE const mlBits = mlDInfo->nbAdditionalBits;
1265
6.13M
        BYTE const ofBits = ofDInfo->nbAdditionalBits;
1266
6.13M
        BYTE const totalBits = llBits+mlBits+ofBits;
1267
1268
6.13M
        U16 const llNext = llDInfo->nextState;
1269
6.13M
        U16 const mlNext = mlDInfo->nextState;
1270
6.13M
        U16 const ofNext = ofDInfo->nextState;
1271
6.13M
        U32 const llnbBits = llDInfo->nbBits;
1272
6.13M
        U32 const mlnbBits = mlDInfo->nbBits;
1273
6.13M
        U32 const ofnbBits = ofDInfo->nbBits;
1274
1275
6.13M
        assert(llBits <= MaxLLBits);
1276
6.13M
        assert(mlBits <= MaxMLBits);
1277
6.13M
        assert(ofBits <= MaxOff);
1278
        /*
1279
         * As gcc has better branch and block analyzers, sometimes it is only
1280
         * valuable to mark likeliness for clang, it gives around 3-4% of
1281
         * performance.
1282
         */
1283
1284
        /* sequence */
1285
6.13M
        {   size_t offset;
1286
6.13M
            if (ofBits > 1) {
1287
2.21M
                ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
1288
2.21M
                ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
1289
2.21M
                ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32);
1290
2.21M
                ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits);
1291
2.21M
                if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
1292
                    /* Always read extra bits, this keeps the logic simple,
1293
                     * avoids branches, and avoids accidentally reading 0 bits.
1294
                     */
1295
0
                    U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32;
1296
0
                    offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
1297
0
                    BIT_reloadDStream(&seqState->DStream);
1298
0
                    offset += BIT_readBitsFast(&seqState->DStream, extraBits);
1299
2.21M
                } else {
1300
2.21M
                    offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/);   /* <=  (ZSTD_WINDOWLOG_MAX-1) bits */
1301
2.21M
                    if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
1302
2.21M
                }
1303
2.21M
                seqState->prevOffset[2] = seqState->prevOffset[1];
1304
2.21M
                seqState->prevOffset[1] = seqState->prevOffset[0];
1305
2.21M
                seqState->prevOffset[0] = offset;
1306
3.92M
            } else {
1307
3.92M
                U32 const ll0 = (llDInfo->baseValue == 0);
1308
3.92M
                if (LIKELY((ofBits == 0))) {
1309
2.13M
                    offset = seqState->prevOffset[ll0];
1310
2.13M
                    seqState->prevOffset[1] = seqState->prevOffset[!ll0];
1311
2.13M
                    seqState->prevOffset[0] = offset;
1312
2.13M
                } else {
1313
1.79M
                    offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
1314
1.79M
                    {   size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
1315
1.79M
                        temp -= !temp; /* 0 is not valid: input corrupted => force offset to -1 => corruption detected at execSequence */
1316
1.79M
                        if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
1317
1.79M
                        seqState->prevOffset[1] = seqState->prevOffset[0];
1318
1.79M
                        seqState->prevOffset[0] = offset = temp;
1319
1.79M
            }   }   }
1320
6.13M
            seq.offset = offset;
1321
6.13M
        }
1322
1323
6.13M
        if (mlBits > 0)
1324
784k
            seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
1325
1326
6.13M
        if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
1327
0
            BIT_reloadDStream(&seqState->DStream);
1328
6.13M
        if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
1329
8.25k
            BIT_reloadDStream(&seqState->DStream);
1330
        /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
1331
6.13M
        ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
1332
1333
6.13M
        if (llBits > 0)
1334
708k
            seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
1335
1336
6.13M
        if (MEM_32bits())
1337
0
            BIT_reloadDStream(&seqState->DStream);
1338
1339
6.13M
        DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
1340
6.13M
                    (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1341
1342
6.13M
        if (!isLastSeq) {
1343
            /* don't update FSE state for last Sequence */
1344
6.13M
            ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits);    /* <=  9 bits */
1345
6.13M
            ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits);    /* <=  9 bits */
1346
6.13M
            if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);    /* <= 18 bits */
1347
6.13M
            ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits);  /* <=  8 bits */
1348
6.13M
            BIT_reloadDStream(&seqState->DStream);
1349
6.13M
        }
1350
6.13M
    }
1351
1352
6.13M
    return seq;
1353
6.13M
}
1354
1355
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1356
#if DEBUGLEVEL >= 1
1357
static int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
1358
{
1359
    size_t const windowSize = dctx->fParams.windowSize;
1360
    /* No dictionary used. */
1361
    if (dctx->dictContentEndForFuzzing == NULL) return 0;
1362
    /* Dictionary is our prefix. */
1363
    if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
1364
    /* Dictionary is not our ext-dict. */
1365
    if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
1366
    /* Dictionary is not within our window size. */
1367
    if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
1368
    /* Dictionary is active. */
1369
    return 1;
1370
}
1371
#endif
1372
1373
static void ZSTD_assertValidSequence(
1374
        ZSTD_DCtx const* dctx,
1375
        BYTE const* op, BYTE const* oend,
1376
        seq_t const seq,
1377
        BYTE const* prefixStart, BYTE const* virtualStart)
1378
{
1379
#if DEBUGLEVEL >= 1
1380
    if (dctx->isFrameDecompression) {
1381
        size_t const windowSize = dctx->fParams.windowSize;
1382
        size_t const sequenceSize = seq.litLength + seq.matchLength;
1383
        BYTE const* const oLitEnd = op + seq.litLength;
1384
        DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
1385
                (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1386
        assert(op <= oend);
1387
        assert((size_t)(oend - op) >= sequenceSize);
1388
        assert(sequenceSize <= ZSTD_blockSizeMax(dctx));
1389
        if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
1390
            size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
1391
            /* Offset must be within the dictionary. */
1392
            assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
1393
            assert(seq.offset <= windowSize + dictSize);
1394
        } else {
1395
            /* Offset must be within our window. */
1396
            assert(seq.offset <= windowSize);
1397
        }
1398
    }
1399
#else
1400
    (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
1401
#endif
1402
}
1403
#endif
1404
1405
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1406
1407
1408
FORCE_INLINE_TEMPLATE size_t
1409
DONT_VECTORIZE
1410
ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
1411
                               void* dst, size_t maxDstSize,
1412
                         const void* seqStart, size_t seqSize, int nbSeq,
1413
                         const ZSTD_longOffset_e isLongOffset)
1414
2.49k
{
1415
2.49k
    BYTE* const ostart = (BYTE*)dst;
1416
2.49k
    BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize);
1417
2.49k
    BYTE* op = ostart;
1418
2.49k
    const BYTE* litPtr = dctx->litPtr;
1419
2.49k
    const BYTE* litBufferEnd = dctx->litBufferEnd;
1420
2.49k
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1421
2.49k
    const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
1422
2.49k
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1423
2.49k
    DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq);
1424
1425
    /* Literals are split between internal buffer & output buffer */
1426
2.49k
    if (nbSeq) {
1427
2.46k
        seqState_t seqState;
1428
2.46k
        dctx->fseEntropy = 1;
1429
9.86k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1430
2.46k
        RETURN_ERROR_IF(
1431
2.46k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1432
2.46k
            corruption_detected, "");
1433
2.31k
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1434
2.31k
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1435
2.31k
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1436
2.31k
        assert(dst != NULL);
1437
1438
2.31k
        ZSTD_STATIC_ASSERT(
1439
2.31k
                BIT_DStream_unfinished < BIT_DStream_completed &&
1440
2.31k
                BIT_DStream_endOfBuffer < BIT_DStream_completed &&
1441
2.31k
                BIT_DStream_completed < BIT_DStream_overflow);
1442
1443
        /* decompress without overrunning litPtr begins */
1444
2.31k
        {   seq_t sequence = {0,0,0};  /* some static analyzer believe that @sequence is not initialized (it necessarily is, since for(;;) loop as at least one iteration) */
1445
            /* Align the decompression loop to 32 + 16 bytes.
1446
                *
1447
                * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
1448
                * speed swings based on the alignment of the decompression loop. This
1449
                * performance swing is caused by parts of the decompression loop falling
1450
                * out of the DSB. The entire decompression loop should fit in the DSB,
1451
                * when it can't we get much worse performance. You can measure if you've
1452
                * hit the good case or the bad case with this perf command for some
1453
                * compressed file test.zst:
1454
                *
1455
                *   perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
1456
                *             -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
1457
                *
1458
                * If you see most cycles served out of the MITE you've hit the bad case.
1459
                * If you see most cycles served out of the DSB you've hit the good case.
1460
                * If it is pretty even then you may be in an okay case.
1461
                *
1462
                * This issue has been reproduced on the following CPUs:
1463
                *   - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
1464
                *               Use Instruments->Counters to get DSB/MITE cycles.
1465
                *               I never got performance swings, but I was able to
1466
                *               go from the good case of mostly DSB to half of the
1467
                *               cycles served from MITE.
1468
                *   - Coffeelake: Intel i9-9900k
1469
                *   - Coffeelake: Intel i7-9700k
1470
                *
1471
                * I haven't been able to reproduce the instability or DSB misses on any
1472
                * of the following CPUS:
1473
                *   - Haswell
1474
                *   - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
1475
                *   - Skylake
1476
                *
1477
                * Alignment is done for each of the three major decompression loops:
1478
                *   - ZSTD_decompressSequences_bodySplitLitBuffer - presplit section of the literal buffer
1479
                *   - ZSTD_decompressSequences_bodySplitLitBuffer - postsplit section of the literal buffer
1480
                *   - ZSTD_decompressSequences_body
1481
                * Alignment choices are made to minimize large swings on bad cases and influence on performance
1482
                * from changes external to this code, rather than to overoptimize on the current commit.
1483
                *
1484
                * If you are seeing performance stability this script can help test.
1485
                * It tests on 4 commits in zstd where I saw performance change.
1486
                *
1487
                *   https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
1488
                */
1489
2.31k
#if defined(__GNUC__) && defined(__x86_64__)
1490
2.31k
            __asm__(".p2align 6");
1491
#  if __GNUC__ >= 7
1492
      /* good for gcc-7, gcc-9, and gcc-11 */
1493
            __asm__("nop");
1494
            __asm__(".p2align 5");
1495
            __asm__("nop");
1496
            __asm__(".p2align 4");
1497
#    if __GNUC__ == 8 || __GNUC__ == 10
1498
      /* good for gcc-8 and gcc-10 */
1499
            __asm__("nop");
1500
            __asm__(".p2align 3");
1501
#    endif
1502
#  endif
1503
2.31k
#endif
1504
1505
            /* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */
1506
2.70M
            for ( ; nbSeq; nbSeq--) {
1507
2.69M
                sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
1508
2.69M
                if (litPtr + sequence.litLength > dctx->litBufferEnd) break;
1509
2.69M
                {   size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
1510
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1511
                    assert(!ZSTD_isError(oneSeqSize));
1512
                    ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1513
#endif
1514
2.69M
                    if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1515
574
                        return oneSeqSize;
1516
2.69M
                    DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1517
2.69M
                    op += oneSeqSize;
1518
2.69M
            }   }
1519
1.73k
            DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)");
1520
1521
            /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */
1522
1.73k
            if (nbSeq > 0) {
1523
1.56k
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1524
1.56k
                assert(dctx->litBufferEnd >= litPtr);
1525
1.56k
                DEBUGLOG(6, "There are %i sequences left, and %zu/%zu literals left in buffer", nbSeq, leftoverLit, sequence.litLength);
1526
1.56k
                if (leftoverLit) {
1527
1.49k
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1528
1.45k
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1529
1.45k
                    sequence.litLength -= leftoverLit;
1530
1.45k
                    op += leftoverLit;
1531
1.45k
                }
1532
1.52k
                litPtr = dctx->litExtraBuffer;
1533
1.52k
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1534
1.52k
                dctx->litBufferLocation = ZSTD_not_in_dst;
1535
1.52k
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
1536
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1537
                    assert(!ZSTD_isError(oneSeqSize));
1538
                    ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1539
#endif
1540
1.52k
                    if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1541
179
                        return oneSeqSize;
1542
1.34k
                    DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1543
1.34k
                    op += oneSeqSize;
1544
1.34k
                }
1545
0
                nbSeq--;
1546
1.34k
            }
1547
1.73k
        }
1548
1549
1.51k
        if (nbSeq > 0) {
1550
            /* there is remaining lit from extra buffer */
1551
1552
1.32k
#if defined(__GNUC__) && defined(__x86_64__)
1553
1.32k
            __asm__(".p2align 6");
1554
1.32k
            __asm__("nop");
1555
1.32k
#  if __GNUC__ != 7
1556
            /* worse for gcc-7 better for gcc-8, gcc-9, and gcc-10 and clang */
1557
1.32k
            __asm__(".p2align 4");
1558
1.32k
            __asm__("nop");
1559
1.32k
            __asm__(".p2align 3");
1560
#  elif __GNUC__ >= 11
1561
            __asm__(".p2align 3");
1562
#  else
1563
            __asm__(".p2align 5");
1564
            __asm__("nop");
1565
            __asm__(".p2align 3");
1566
#  endif
1567
1.32k
#endif
1568
1569
2.56M
            for ( ; nbSeq ; nbSeq--) {
1570
2.56M
                seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
1571
2.56M
                size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
1572
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1573
                assert(!ZSTD_isError(oneSeqSize));
1574
                ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1575
#endif
1576
2.56M
                if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1577
1.10k
                    return oneSeqSize;
1578
2.56M
                DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1579
2.56M
                op += oneSeqSize;
1580
2.56M
            }
1581
1.32k
        }
1582
1583
        /* check if reached exact end */
1584
409
        DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq);
1585
409
        RETURN_ERROR_IF(nbSeq, corruption_detected, "");
1586
409
        DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed);
1587
409
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1588
        /* save reps for next block */
1589
64
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1590
16
    }
1591
1592
    /* last literal segment */
1593
44
    if (dctx->litBufferLocation == ZSTD_split) {
1594
        /* split hasn't been reached yet, first get dst then copy litExtraBuffer */
1595
40
        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1596
40
        DEBUGLOG(6, "copy last literals from segment : %u", (U32)lastLLSize);
1597
40
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
1598
37
        if (op != NULL) {
1599
37
            ZSTD_memmove(op, litPtr, lastLLSize);
1600
37
            op += lastLLSize;
1601
37
        }
1602
37
        litPtr = dctx->litExtraBuffer;
1603
37
        litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1604
37
        dctx->litBufferLocation = ZSTD_not_in_dst;
1605
37
    }
1606
    /* copy last literals from internal buffer */
1607
41
    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1608
41
        DEBUGLOG(6, "copy last literals from internal buffer : %u", (U32)lastLLSize);
1609
41
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1610
38
        if (op != NULL) {
1611
38
            ZSTD_memcpy(op, litPtr, lastLLSize);
1612
38
            op += lastLLSize;
1613
38
    }   }
1614
1615
38
    DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));
1616
38
    return (size_t)(op - ostart);
1617
41
}
1618
1619
FORCE_INLINE_TEMPLATE size_t
1620
DONT_VECTORIZE
1621
ZSTD_decompressSequences_body(ZSTD_DCtx* dctx,
1622
    void* dst, size_t maxDstSize,
1623
    const void* seqStart, size_t seqSize, int nbSeq,
1624
    const ZSTD_longOffset_e isLongOffset)
1625
9.49k
{
1626
9.49k
    BYTE* const ostart = (BYTE*)dst;
1627
9.49k
    BYTE* const oend = (dctx->litBufferLocation == ZSTD_not_in_dst) ?
1628
9.05k
                        (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize) :
1629
9.49k
                        dctx->litBuffer;
1630
9.49k
    BYTE* op = ostart;
1631
9.49k
    const BYTE* litPtr = dctx->litPtr;
1632
9.49k
    const BYTE* const litEnd = litPtr + dctx->litSize;
1633
9.49k
    const BYTE* const prefixStart = (const BYTE*)(dctx->prefixStart);
1634
9.49k
    const BYTE* const vBase = (const BYTE*)(dctx->virtualStart);
1635
9.49k
    const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd);
1636
9.49k
    DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq);
1637
1638
    /* Regen sequences */
1639
9.49k
    if (nbSeq) {
1640
1.32k
        seqState_t seqState;
1641
1.32k
        dctx->fseEntropy = 1;
1642
5.28k
        { U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1643
1.32k
        RETURN_ERROR_IF(
1644
1.32k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1645
1.32k
            corruption_detected, "");
1646
968
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1647
968
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1648
968
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1649
968
        assert(dst != NULL);
1650
1651
968
#if defined(__GNUC__) && defined(__x86_64__)
1652
968
            __asm__(".p2align 6");
1653
968
            __asm__("nop");
1654
#  if __GNUC__ >= 7
1655
            __asm__(".p2align 5");
1656
            __asm__("nop");
1657
            __asm__(".p2align 3");
1658
#  else
1659
968
            __asm__(".p2align 4");
1660
968
            __asm__("nop");
1661
968
            __asm__(".p2align 3");
1662
968
#  endif
1663
968
#endif
1664
1665
873k
        for ( ; nbSeq ; nbSeq--) {
1666
873k
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
1667
873k
            size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
1668
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1669
            assert(!ZSTD_isError(oneSeqSize));
1670
            ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1671
#endif
1672
873k
            if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1673
872
                return oneSeqSize;
1674
872k
            DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1675
872k
            op += oneSeqSize;
1676
872k
        }
1677
1678
        /* check if reached exact end */
1679
96
        assert(nbSeq == 0);
1680
96
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1681
        /* save reps for next block */
1682
88
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1683
22
    }
1684
1685
    /* last literal segment */
1686
8.19k
    {   size_t const lastLLSize = (size_t)(litEnd - litPtr);
1687
8.19k
        DEBUGLOG(6, "copy last literals : %u", (U32)lastLLSize);
1688
8.19k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1689
8.19k
        if (op != NULL) {
1690
8.19k
            ZSTD_memcpy(op, litPtr, lastLLSize);
1691
8.19k
            op += lastLLSize;
1692
8.19k
    }   }
1693
1694
8.19k
    DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));
1695
8.19k
    return (size_t)(op - ostart);
1696
8.19k
}
1697
1698
static size_t
1699
ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
1700
                                 void* dst, size_t maxDstSize,
1701
                           const void* seqStart, size_t seqSize, int nbSeq,
1702
                           const ZSTD_longOffset_e isLongOffset)
1703
0
{
1704
0
    return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1705
0
}
1706
1707
static size_t
1708
ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx,
1709
                                               void* dst, size_t maxDstSize,
1710
                                         const void* seqStart, size_t seqSize, int nbSeq,
1711
                                         const ZSTD_longOffset_e isLongOffset)
1712
0
{
1713
0
    return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1714
0
}
1715
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1716
1717
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1718
1719
FORCE_INLINE_TEMPLATE
1720
1721
size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
1722
                   const BYTE* const prefixStart, const BYTE* const dictEnd)
1723
0
{
1724
0
    prefetchPos += sequence.litLength;
1725
0
    {   const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;
1726
        /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.
1727
         * No consequence though : memory address is only used for prefetching, not for dereferencing */
1728
0
        const BYTE* const match = (const BYTE*)ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset);
1729
0
        PREFETCH_L1(match); PREFETCH_L1(ZSTD_wrappedPtrAdd(match, CACHELINE_SIZE));   /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
1730
0
    }
1731
0
    return prefetchPos + sequence.matchLength;
1732
0
}
1733
1734
/* This decoding function employs prefetching
1735
 * to reduce latency impact of cache misses.
1736
 * It's generally employed when block contains a significant portion of long-distance matches
1737
 * or when coupled with a "cold" dictionary */
1738
FORCE_INLINE_TEMPLATE size_t
1739
ZSTD_decompressSequencesLong_body(
1740
                               ZSTD_DCtx* dctx,
1741
                               void* dst, size_t maxDstSize,
1742
                         const void* seqStart, size_t seqSize, int nbSeq,
1743
                         const ZSTD_longOffset_e isLongOffset)
1744
0
{
1745
0
    BYTE* const ostart = (BYTE*)dst;
1746
0
    BYTE* const oend = (dctx->litBufferLocation == ZSTD_in_dst) ?
1747
0
                        dctx->litBuffer :
1748
0
                        (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize);
1749
0
    BYTE* op = ostart;
1750
0
    const BYTE* litPtr = dctx->litPtr;
1751
0
    const BYTE* litBufferEnd = dctx->litBufferEnd;
1752
0
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1753
0
    const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
1754
0
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1755
1756
    /* Regen sequences */
1757
0
    if (nbSeq) {
1758
0
#define STORED_SEQS 8
1759
0
#define STORED_SEQS_MASK (STORED_SEQS-1)
1760
0
#define ADVANCED_SEQS STORED_SEQS
1761
0
        seq_t sequences[STORED_SEQS];
1762
0
        int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
1763
0
        seqState_t seqState;
1764
0
        int seqNb;
1765
0
        size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
1766
1767
0
        dctx->fseEntropy = 1;
1768
0
        { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1769
0
        assert(dst != NULL);
1770
0
        RETURN_ERROR_IF(
1771
0
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1772
0
            corruption_detected, "");
1773
0
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1774
0
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1775
0
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1776
1777
        /* prepare in advance */
1778
0
        for (seqNb=0; seqNb<seqAdvance; seqNb++) {
1779
0
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1780
0
            prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1781
0
            sequences[seqNb] = sequence;
1782
0
        }
1783
1784
        /* decompress without stomping litBuffer */
1785
0
        for (; seqNb < nbSeq; seqNb++) {
1786
0
            seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1787
1788
0
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) {
1789
                /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */
1790
0
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1791
0
                assert(dctx->litBufferEnd >= litPtr);
1792
0
                if (leftoverLit) {
1793
0
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1794
0
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1795
0
                    sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;
1796
0
                    op += leftoverLit;
1797
0
                }
1798
0
                litPtr = dctx->litExtraBuffer;
1799
0
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1800
0
                dctx->litBufferLocation = ZSTD_not_in_dst;
1801
0
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1802
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1803
                    assert(!ZSTD_isError(oneSeqSize));
1804
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1805
#endif
1806
0
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1807
1808
0
                    prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1809
0
                    sequences[seqNb & STORED_SEQS_MASK] = sequence;
1810
0
                    op += oneSeqSize;
1811
0
            }   }
1812
0
            else
1813
0
            {
1814
                /* lit buffer is either wholly contained in first or second split, or not split at all*/
1815
0
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1816
0
                    ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength - WILDCOPY_OVERLENGTH, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
1817
0
                    ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1818
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1819
                assert(!ZSTD_isError(oneSeqSize));
1820
                ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1821
#endif
1822
0
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1823
1824
0
                prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1825
0
                sequences[seqNb & STORED_SEQS_MASK] = sequence;
1826
0
                op += oneSeqSize;
1827
0
            }
1828
0
        }
1829
0
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1830
1831
        /* finish queue */
1832
0
        seqNb -= seqAdvance;
1833
0
        for ( ; seqNb<nbSeq ; seqNb++) {
1834
0
            seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);
1835
0
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) {
1836
0
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1837
0
                assert(dctx->litBufferEnd >= litPtr);
1838
0
                if (leftoverLit) {
1839
0
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1840
0
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1841
0
                    sequence->litLength -= leftoverLit;
1842
0
                    op += leftoverLit;
1843
0
                }
1844
0
                litPtr = dctx->litExtraBuffer;
1845
0
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1846
0
                dctx->litBufferLocation = ZSTD_not_in_dst;
1847
0
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1848
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1849
                    assert(!ZSTD_isError(oneSeqSize));
1850
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1851
#endif
1852
0
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1853
0
                    op += oneSeqSize;
1854
0
                }
1855
0
            }
1856
0
            else
1857
0
            {
1858
0
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1859
0
                    ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
1860
0
                    ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1861
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1862
                assert(!ZSTD_isError(oneSeqSize));
1863
                ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1864
#endif
1865
0
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1866
0
                op += oneSeqSize;
1867
0
            }
1868
0
        }
1869
1870
        /* save reps for next block */
1871
0
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1872
0
    }
1873
1874
    /* last literal segment */
1875
0
    if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */
1876
0
        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1877
0
        assert(litBufferEnd >= litPtr);
1878
0
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
1879
0
        if (op != NULL) {
1880
0
            ZSTD_memmove(op, litPtr, lastLLSize);
1881
0
            op += lastLLSize;
1882
0
        }
1883
0
        litPtr = dctx->litExtraBuffer;
1884
0
        litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1885
0
    }
1886
0
    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1887
0
        assert(litBufferEnd >= litPtr);
1888
0
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1889
0
        if (op != NULL) {
1890
0
            ZSTD_memmove(op, litPtr, lastLLSize);
1891
0
            op += lastLLSize;
1892
0
        }
1893
0
    }
1894
1895
0
    return (size_t)(op - ostart);
1896
0
}
1897
1898
static size_t
1899
ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
1900
                                 void* dst, size_t maxDstSize,
1901
                           const void* seqStart, size_t seqSize, int nbSeq,
1902
                           const ZSTD_longOffset_e isLongOffset)
1903
0
{
1904
0
    return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1905
0
}
1906
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
1907
1908
1909
1910
#if DYNAMIC_BMI2
1911
1912
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1913
static BMI2_TARGET_ATTRIBUTE size_t
1914
DONT_VECTORIZE
1915
ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
1916
                                 void* dst, size_t maxDstSize,
1917
                           const void* seqStart, size_t seqSize, int nbSeq,
1918
                           const ZSTD_longOffset_e isLongOffset)
1919
9.49k
{
1920
9.49k
    return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1921
9.49k
}
1922
static BMI2_TARGET_ATTRIBUTE size_t
1923
DONT_VECTORIZE
1924
ZSTD_decompressSequencesSplitLitBuffer_bmi2(ZSTD_DCtx* dctx,
1925
                                 void* dst, size_t maxDstSize,
1926
                           const void* seqStart, size_t seqSize, int nbSeq,
1927
                           const ZSTD_longOffset_e isLongOffset)
1928
2.49k
{
1929
2.49k
    return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1930
2.49k
}
1931
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1932
1933
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1934
static BMI2_TARGET_ATTRIBUTE size_t
1935
ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
1936
                                 void* dst, size_t maxDstSize,
1937
                           const void* seqStart, size_t seqSize, int nbSeq,
1938
                           const ZSTD_longOffset_e isLongOffset)
1939
0
{
1940
0
    return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1941
0
}
1942
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
1943
1944
#endif /* DYNAMIC_BMI2 */
1945
1946
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1947
static size_t
1948
ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
1949
                   const void* seqStart, size_t seqSize, int nbSeq,
1950
                   const ZSTD_longOffset_e isLongOffset)
1951
9.49k
{
1952
9.49k
    DEBUGLOG(5, "ZSTD_decompressSequences");
1953
9.49k
#if DYNAMIC_BMI2
1954
9.49k
    if (ZSTD_DCtx_get_bmi2(dctx)) {
1955
9.49k
        return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1956
9.49k
    }
1957
0
#endif
1958
0
    return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1959
9.49k
}
1960
static size_t
1961
ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
1962
                                 const void* seqStart, size_t seqSize, int nbSeq,
1963
                                 const ZSTD_longOffset_e isLongOffset)
1964
2.49k
{
1965
2.49k
    DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer");
1966
2.49k
#if DYNAMIC_BMI2
1967
2.49k
    if (ZSTD_DCtx_get_bmi2(dctx)) {
1968
2.49k
        return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1969
2.49k
    }
1970
0
#endif
1971
0
    return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1972
2.49k
}
1973
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1974
1975
1976
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1977
/* ZSTD_decompressSequencesLong() :
1978
 * decompression function triggered when a minimum share of offsets is considered "long",
1979
 * aka out of cache.
1980
 * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
1981
 * This function will try to mitigate main memory latency through the use of prefetching */
1982
static size_t
1983
ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
1984
                             void* dst, size_t maxDstSize,
1985
                             const void* seqStart, size_t seqSize, int nbSeq,
1986
                             const ZSTD_longOffset_e isLongOffset)
1987
0
{
1988
0
    DEBUGLOG(5, "ZSTD_decompressSequencesLong");
1989
0
#if DYNAMIC_BMI2
1990
0
    if (ZSTD_DCtx_get_bmi2(dctx)) {
1991
0
        return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1992
0
    }
1993
0
#endif
1994
0
  return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1995
0
}
1996
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
1997
1998
1999
/**
2000
 * @returns The total size of the history referenceable by zstd, including
2001
 * both the prefix and the extDict. At @p op any offset larger than this
2002
 * is invalid.
2003
 */
2004
static size_t ZSTD_totalHistorySize(void* curPtr, const void* virtualStart)
2005
13.2k
{
2006
13.2k
    return (size_t)((char*)curPtr - (const char*)virtualStart);
2007
13.2k
}
2008
2009
typedef struct {
2010
    unsigned longOffsetShare;
2011
    unsigned maxNbAdditionalBits;
2012
} ZSTD_OffsetInfo;
2013
2014
/* ZSTD_getOffsetInfo() :
2015
 * condition : offTable must be valid
2016
 * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
2017
 *           compared to maximum possible of (1<<OffFSELog),
2018
 *           as well as the maximum number additional bits required.
2019
 */
2020
static ZSTD_OffsetInfo
2021
ZSTD_getOffsetInfo(const ZSTD_seqSymbol* offTable, int nbSeq)
2022
0
{
2023
0
    ZSTD_OffsetInfo info = {0, 0};
2024
    /* If nbSeq == 0, then the offTable is uninitialized, but we have
2025
     * no sequences, so both values should be 0.
2026
     */
2027
0
    if (nbSeq != 0) {
2028
0
        const void* ptr = offTable;
2029
0
        U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
2030
0
        const ZSTD_seqSymbol* table = offTable + 1;
2031
0
        U32 const max = 1 << tableLog;
2032
0
        U32 u;
2033
0
        DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
2034
2035
0
        assert(max <= (1 << OffFSELog));  /* max not too large */
2036
0
        for (u=0; u<max; u++) {
2037
0
            info.maxNbAdditionalBits = MAX(info.maxNbAdditionalBits, table[u].nbAdditionalBits);
2038
0
            if (table[u].nbAdditionalBits > 22) info.longOffsetShare += 1;
2039
0
        }
2040
2041
0
        assert(tableLog <= OffFSELog);
2042
0
        info.longOffsetShare <<= (OffFSELog - tableLog);  /* scale to OffFSELog */
2043
0
    }
2044
2045
0
    return info;
2046
0
}
2047
2048
/**
2049
 * @returns The maximum offset we can decode in one read of our bitstream, without
2050
 * reloading more bits in the middle of the offset bits read. Any offsets larger
2051
 * than this must use the long offset decoder.
2052
 */
2053
static size_t ZSTD_maxShortOffset(void)
2054
0
{
2055
0
    if (MEM_64bits()) {
2056
        /* We can decode any offset without reloading bits.
2057
         * This might change if the max window size grows.
2058
         */
2059
0
        ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
2060
0
        return (size_t)-1;
2061
0
    } else {
2062
        /* The maximum offBase is (1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1.
2063
         * This offBase would require STREAM_ACCUMULATOR_MIN extra bits.
2064
         * Then we have to subtract ZSTD_REP_NUM to get the maximum possible offset.
2065
         */
2066
0
        size_t const maxOffbase = ((size_t)1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1;
2067
0
        size_t const maxOffset = maxOffbase - ZSTD_REP_NUM;
2068
0
        assert(ZSTD_highbit32((U32)maxOffbase) == STREAM_ACCUMULATOR_MIN);
2069
0
        return maxOffset;
2070
0
    }
2071
0
}
2072
2073
size_t
2074
ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
2075
                              void* dst, size_t dstCapacity,
2076
                        const void* src, size_t srcSize, const streaming_operation streaming)
2077
18.7k
{   /* blockType == blockCompressed */
2078
18.7k
    const BYTE* ip = (const BYTE*)src;
2079
18.7k
    DEBUGLOG(5, "ZSTD_decompressBlock_internal (cSize : %u)", (unsigned)srcSize);
2080
2081
    /* Note : the wording of the specification
2082
     * allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx).
2083
     * This generally does not happen, as it makes little sense,
2084
     * since an uncompressed block would feature same size and have no decompression cost.
2085
     * Also, note that decoder from reference libzstd before < v1.5.4
2086
     * would consider this edge case as an error.
2087
     * As a consequence, avoid generating compressed blocks of size ZSTD_blockSizeMax(dctx)
2088
     * for broader compatibility with the deployed ecosystem of zstd decoders */
2089
18.7k
    RETURN_ERROR_IF(srcSize > ZSTD_blockSizeMax(dctx), srcSize_wrong, "");
2090
2091
    /* Decode literals section */
2092
18.7k
    {   size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming);
2093
18.7k
        DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : cSize=%u, nbLiterals=%zu", (U32)litCSize, dctx->litSize);
2094
18.7k
        if (ZSTD_isError(litCSize)) return litCSize;
2095
13.2k
        ip += litCSize;
2096
13.2k
        srcSize -= litCSize;
2097
13.2k
    }
2098
2099
    /* Build Decoding Tables */
2100
0
    {
2101
        /* Compute the maximum block size, which must also work when !frame and fParams are unset.
2102
         * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t.
2103
         */
2104
13.2k
        size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx));
2105
13.2k
        size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd(dst, (ptrdiff_t)blockSizeMax), (BYTE const*)dctx->virtualStart);
2106
        /* isLongOffset must be true if there are long offsets.
2107
         * Offsets are long if they are larger than ZSTD_maxShortOffset().
2108
         * We don't expect that to be the case in 64-bit mode.
2109
         *
2110
         * We check here to see if our history is large enough to allow long offsets.
2111
         * If it isn't, then we can't possible have (valid) long offsets. If the offset
2112
         * is invalid, then it is okay to read it incorrectly.
2113
         *
2114
         * If isLongOffsets is true, then we will later check our decoding table to see
2115
         * if it is even possible to generate long offsets.
2116
         */
2117
13.2k
        ZSTD_longOffset_e isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (totalHistorySize > ZSTD_maxShortOffset()));
2118
        /* These macros control at build-time which decompressor implementation
2119
         * we use. If neither is defined, we do some inspection and dispatch at
2120
         * runtime.
2121
         */
2122
13.2k
#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
2123
13.2k
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
2124
13.2k
        int usePrefetchDecoder = dctx->ddictIsCold;
2125
#else
2126
        /* Set to 1 to avoid computing offset info if we don't need to.
2127
         * Otherwise this value is ignored.
2128
         */
2129
        int usePrefetchDecoder = 1;
2130
#endif
2131
13.2k
        int nbSeq;
2132
13.2k
        size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
2133
13.2k
        if (ZSTD_isError(seqHSize)) return seqHSize;
2134
11.9k
        ip += seqHSize;
2135
11.9k
        srcSize -= seqHSize;
2136
2137
11.9k
        RETURN_ERROR_IF((dst == NULL || dstCapacity == 0) && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
2138
11.9k
        RETURN_ERROR_IF(MEM_64bits() && sizeof(size_t) == sizeof(void*) && (size_t)(-1) - (size_t)dst < (size_t)(1 << 20), dstSize_tooSmall,
2139
11.9k
                "invalid dst");
2140
2141
        /* If we could potentially have long offsets, or we might want to use the prefetch decoder,
2142
         * compute information about the share of long offsets, and the maximum nbAdditionalBits.
2143
         * NOTE: could probably use a larger nbSeq limit
2144
         */
2145
11.9k
        if (isLongOffset || (!usePrefetchDecoder && (totalHistorySize > (1u << 24)) && (nbSeq > 8))) {
2146
0
            ZSTD_OffsetInfo const info = ZSTD_getOffsetInfo(dctx->OFTptr, nbSeq);
2147
0
            if (isLongOffset && info.maxNbAdditionalBits <= STREAM_ACCUMULATOR_MIN) {
2148
                /* If isLongOffset, but the maximum number of additional bits that we see in our table is small
2149
                 * enough, then we know it is impossible to have too long an offset in this block, so we can
2150
                 * use the regular offset decoder.
2151
                 */
2152
0
                isLongOffset = ZSTD_lo_isRegularOffset;
2153
0
            }
2154
0
            if (!usePrefetchDecoder) {
2155
0
                U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
2156
0
                usePrefetchDecoder = (info.longOffsetShare >= minShare);
2157
0
            }
2158
0
        }
2159
2160
11.9k
        dctx->ddictIsCold = 0;
2161
2162
11.9k
#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
2163
11.9k
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
2164
11.9k
        if (usePrefetchDecoder) {
2165
#else
2166
        (void)usePrefetchDecoder;
2167
        {
2168
#endif
2169
0
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
2170
0
            return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
2171
0
#endif
2172
0
        }
2173
2174
11.9k
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
2175
        /* else */
2176
11.9k
        if (dctx->litBufferLocation == ZSTD_split)
2177
2.49k
            return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
2178
9.49k
        else
2179
9.49k
            return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
2180
11.9k
#endif
2181
11.9k
    }
2182
11.9k
}
2183
2184
2185
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
2186
void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
2187
2.02M
{
2188
2.02M
    if (dst != dctx->previousDstEnd && dstSize > 0) {   /* not contiguous */
2189
12.9k
        dctx->dictEnd = dctx->previousDstEnd;
2190
12.9k
        dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
2191
12.9k
        dctx->prefixStart = dst;
2192
12.9k
        dctx->previousDstEnd = dst;
2193
12.9k
    }
2194
2.02M
}
2195
2196
2197
size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx,
2198
                                       void* dst, size_t dstCapacity,
2199
                                 const void* src, size_t srcSize)
2200
0
{
2201
0
    size_t dSize;
2202
0
    dctx->isFrameDecompression = 0;
2203
0
    ZSTD_checkContinuity(dctx, dst, dstCapacity);
2204
0
    dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, not_streaming);
2205
0
    FORWARD_IF_ERROR(dSize, "");
2206
0
    dctx->previousDstEnd = (char*)dst + dSize;
2207
0
    return dSize;
2208
0
}
2209
2210
2211
/* NOTE: Must just wrap ZSTD_decompressBlock_deprecated() */
2212
size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
2213
                            void* dst, size_t dstCapacity,
2214
                      const void* src, size_t srcSize)
2215
0
{
2216
0
    return ZSTD_decompressBlock_deprecated(dctx, dst, dstCapacity, src, srcSize);
2217
0
}