Coverage Report

Created: 2026-10-28 07:09

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