Coverage Report

Created: 2025-07-23 06:08

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