Coverage Report

Created: 2026-02-26 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/decompress/zstd_decompress_block.c
Line
Count
Source
1
/*
2
 * Copyright (c) Meta Platforms, Inc. and affiliates.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under both the BSD-style license (found in the
6
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
 * in the COPYING file in the root directory of this source tree).
8
 * You may select, at your option, one of the above-listed licenses.
9
 */
10
11
/* zstd_decompress_block :
12
 * this module takes care of decompressing _compressed_ block */
13
14
/*-*******************************************************
15
*  Dependencies
16
*********************************************************/
17
#include "../common/zstd_deps.h"   /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
18
#include "../common/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
52.9M
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
270M
{
55
270M
    size_t const blockSizeMax = dctx->isFrameDecompression ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX;
56
270M
    assert(blockSizeMax <= ZSTD_BLOCKSIZE_MAX);
57
270M
    return blockSizeMax;
58
270M
}
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
109M
{
65
109M
    RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, "");
66
67
109M
    {   U32 const cBlockHeader = MEM_readLE24(src);
68
109M
        U32 const cSize = cBlockHeader >> 3;
69
109M
        bpPtr->lastBlock = cBlockHeader & 1;
70
109M
        bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
71
109M
        bpPtr->origSize = cSize;   /* only useful for RLE */
72
109M
        if (bpPtr->blockType == bt_rle) return 1;
73
108M
        RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, "");
74
108M
        return cSize;
75
108M
    }
76
108M
}
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
4.46M
{
82
4.46M
    size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);
83
4.46M
    assert(litSize <= blockSizeMax);
84
4.46M
    assert(dctx->isFrameDecompression || streaming == not_streaming);
85
4.46M
    assert(expectedWriteSize <= blockSizeMax);
86
4.46M
    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
3.59M
        dctx->litBuffer = (BYTE*)dst + blockSizeMax + WILDCOPY_OVERLENGTH;
93
3.59M
        dctx->litBufferEnd = dctx->litBuffer + litSize;
94
3.59M
        dctx->litBufferLocation = ZSTD_in_dst;
95
3.59M
    } 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
828k
        dctx->litBuffer = dctx->litExtraBuffer;
100
828k
        dctx->litBufferEnd = dctx->litBuffer + litSize;
101
828k
        dctx->litBufferLocation = ZSTD_not_in_dst;
102
828k
    } else {
103
37.7k
        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
37.7k
        if (splitImmediately) {
112
            /* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */
113
30.5k
            dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;
114
30.5k
            dctx->litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE;
115
30.5k
        } else {
116
            /* initially this will be stored entirely in dst during huffman decoding, it will partially be shifted to litExtraBuffer after */
117
7.23k
            dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize;
118
7.23k
            dctx->litBufferEnd = (BYTE*)dst + expectedWriteSize;
119
7.23k
        }
120
37.7k
        dctx->litBufferLocation = ZSTD_split;
121
37.7k
        assert(dctx->litBufferEnd <= (BYTE*)dst + expectedWriteSize);
122
37.7k
    }
123
4.46M
}
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
4.47M
{
137
4.47M
    DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");
138
4.47M
    RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");
139
140
4.47M
    {   const BYTE* const istart = (const BYTE*) src;
141
4.47M
        SymbolEncodingType_e const litEncType = (SymbolEncodingType_e)(istart[0] & 3);
142
4.47M
        size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);
143
144
4.47M
        switch(litEncType)
145
4.47M
        {
146
560k
        case set_repeat:
147
560k
            DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");
148
560k
            RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");
149
560k
            ZSTD_FALLTHROUGH;
150
151
2.03M
        case set_compressed:
152
2.03M
            RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need up to 5 for case 3");
153
2.03M
            {   size_t lhSize, litSize, litCSize;
154
2.03M
                U32 singleStream=0;
155
2.03M
                U32 const lhlCode = (istart[0] >> 2) & 3;
156
2.03M
                U32 const lhc = MEM_readLE32(istart);
157
2.03M
                size_t hufSuccess;
158
2.03M
                size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
159
2.03M
                int const flags = 0
160
2.03M
                    | (ZSTD_DCtx_get_bmi2(dctx) ? HUF_flags_bmi2 : 0)
161
2.03M
                    | (dctx->disableHufAsm ? HUF_flags_disableAsm : 0);
162
2.03M
                switch(lhlCode)
163
2.03M
                {
164
1.43M
                case 0: case 1: default:   /* note : default is impossible, since lhlCode into [0..3] */
165
                    /* 2 - 2 - 10 - 10 */
166
1.43M
                    singleStream = !lhlCode;
167
1.43M
                    lhSize = 3;
168
1.43M
                    litSize  = (lhc >> 4) & 0x3FF;
169
1.43M
                    litCSize = (lhc >> 14) & 0x3FF;
170
1.43M
                    break;
171
567k
                case 2:
172
                    /* 2 - 2 - 14 - 14 */
173
567k
                    lhSize = 4;
174
567k
                    litSize  = (lhc >> 4) & 0x3FFF;
175
567k
                    litCSize = lhc >> 18;
176
567k
                    break;
177
34.5k
                case 3:
178
                    /* 2 - 2 - 18 - 18 */
179
34.5k
                    lhSize = 5;
180
34.5k
                    litSize  = (lhc >> 4) & 0x3FFFF;
181
34.5k
                    litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);
182
34.5k
                    break;
183
2.03M
                }
184
2.03M
                RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
185
2.03M
                RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
186
2.03M
                if (!singleStream)
187
1.08M
                    RETURN_ERROR_IF(litSize < MIN_LITERALS_FOR_4_STREAMS, literals_headerWrong,
188
2.03M
                        "Not enough literals (%zu) for the 4-streams mode (min %u)",
189
2.03M
                        litSize, MIN_LITERALS_FOR_4_STREAMS);
190
2.03M
                RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");
191
2.03M
                RETURN_ERROR_IF(expectedWriteSize < litSize , dstSize_tooSmall, "");
192
2.03M
                ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 0);
193
194
                /* prefetch huffman table if cold */
195
2.03M
                if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
196
11.8k
                    PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
197
11.8k
                }
198
199
2.03M
                if (litEncType==set_repeat) {
200
560k
                    if (singleStream) {
201
200k
                        hufSuccess = HUF_decompress1X_usingDTable(
202
200k
                            dctx->litBuffer, litSize, istart+lhSize, litCSize,
203
200k
                            dctx->HUFptr, flags);
204
359k
                    } else {
205
359k
                        assert(litSize >= MIN_LITERALS_FOR_4_STREAMS);
206
359k
                        hufSuccess = HUF_decompress4X_usingDTable(
207
359k
                            dctx->litBuffer, litSize, istart+lhSize, litCSize,
208
359k
                            dctx->HUFptr, flags);
209
359k
                    }
210
1.47M
                } else {
211
1.47M
                    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
748k
                        hufSuccess = HUF_decompress1X1_DCtx_wksp(
219
748k
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
220
748k
                            istart+lhSize, litCSize, dctx->workspace,
221
748k
                            sizeof(dctx->workspace), flags);
222
748k
#endif
223
748k
                    } else {
224
723k
                        hufSuccess = HUF_decompress4X_hufOnly_wksp(
225
723k
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
226
723k
                            istart+lhSize, litCSize, dctx->workspace,
227
723k
                            sizeof(dctx->workspace), flags);
228
723k
                    }
229
1.47M
                }
230
2.03M
                if (dctx->litBufferLocation == ZSTD_split)
231
7.23k
                {
232
7.23k
                    assert(litSize > ZSTD_LITBUFFEREXTRASIZE);
233
7.23k
                    ZSTD_memcpy(dctx->litExtraBuffer, dctx->litBufferEnd - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);
234
7.23k
                    ZSTD_memmove(dctx->litBuffer + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH, dctx->litBuffer, litSize - ZSTD_LITBUFFEREXTRASIZE);
235
7.23k
                    dctx->litBuffer += ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;
236
7.23k
                    dctx->litBufferEnd -= WILDCOPY_OVERLENGTH;
237
7.23k
                    assert(dctx->litBufferEnd <= (BYTE*)dst + blockSizeMax);
238
7.23k
                }
239
240
2.03M
                RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");
241
242
2.02M
                dctx->litPtr = dctx->litBuffer;
243
2.02M
                dctx->litSize = litSize;
244
2.02M
                dctx->litEntropy = 1;
245
2.02M
                if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
246
2.02M
                return litCSize + lhSize;
247
2.03M
            }
248
249
2.37M
        case set_basic:
250
2.37M
            {   size_t litSize, lhSize;
251
2.37M
                U32 const lhlCode = ((istart[0]) >> 2) & 3;
252
2.37M
                size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
253
2.37M
                switch(lhlCode)
254
2.37M
                {
255
1.46M
                case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
256
1.46M
                    lhSize = 1;
257
1.46M
                    litSize = istart[0] >> 3;
258
1.46M
                    break;
259
883k
                case 1:
260
883k
                    lhSize = 2;
261
883k
                    litSize = MEM_readLE16(istart) >> 4;
262
883k
                    break;
263
24.4k
                case 3:
264
24.4k
                    lhSize = 3;
265
24.4k
                    RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize = 3");
266
24.4k
                    litSize = MEM_readLE24(istart) >> 4;
267
24.4k
                    break;
268
2.37M
                }
269
270
2.37M
                RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
271
2.37M
                RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
272
2.37M
                RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");
273
2.37M
                ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);
274
2.37M
                if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) {  /* risk reading beyond src buffer with wildcopy */
275
1.41M
                    RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");
276
1.41M
                    if (dctx->litBufferLocation == ZSTD_split)
277
748
                    {
278
748
                        ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize - ZSTD_LITBUFFEREXTRASIZE);
279
748
                        ZSTD_memcpy(dctx->litExtraBuffer, istart + lhSize + litSize - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);
280
748
                    }
281
1.41M
                    else
282
1.41M
                    {
283
1.41M
                        ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize);
284
1.41M
                    }
285
1.41M
                    dctx->litPtr = dctx->litBuffer;
286
1.41M
                    dctx->litSize = litSize;
287
1.41M
                    return lhSize+litSize;
288
1.41M
                }
289
                /* direct reference into compressed stream */
290
956k
                dctx->litPtr = istart+lhSize;
291
956k
                dctx->litSize = litSize;
292
956k
                dctx->litBufferEnd = dctx->litPtr + litSize;
293
956k
                dctx->litBufferLocation = ZSTD_not_in_dst;
294
956k
                return lhSize+litSize;
295
2.37M
            }
296
297
63.6k
        case set_rle:
298
63.6k
            {   U32 const lhlCode = ((istart[0]) >> 2) & 3;
299
63.6k
                size_t litSize, lhSize;
300
63.6k
                size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);
301
63.6k
                switch(lhlCode)
302
63.6k
                {
303
17.7k
                case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
304
17.7k
                    lhSize = 1;
305
17.7k
                    litSize = istart[0] >> 3;
306
17.7k
                    break;
307
11.9k
                case 1:
308
11.9k
                    lhSize = 2;
309
11.9k
                    RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 3");
310
11.8k
                    litSize = MEM_readLE16(istart) >> 4;
311
11.8k
                    break;
312
33.9k
                case 3:
313
33.9k
                    lhSize = 3;
314
33.9k
                    RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 4");
315
33.9k
                    litSize = MEM_readLE24(istart) >> 4;
316
33.9k
                    break;
317
63.6k
                }
318
63.5k
                RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");
319
61.0k
                RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");
320
60.9k
                RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");
321
60.6k
                ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);
322
60.6k
                if (dctx->litBufferLocation == ZSTD_split)
323
29.0k
                {
324
29.0k
                    ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize - ZSTD_LITBUFFEREXTRASIZE);
325
29.0k
                    ZSTD_memset(dctx->litExtraBuffer, istart[lhSize], ZSTD_LITBUFFEREXTRASIZE);
326
29.0k
                }
327
31.6k
                else
328
31.6k
                {
329
31.6k
                    ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize);
330
31.6k
                }
331
60.6k
                dctx->litPtr = dctx->litBuffer;
332
60.6k
                dctx->litSize = litSize;
333
60.6k
                return lhSize+1;
334
60.9k
            }
335
0
        default:
336
0
            RETURN_ERROR(corruption_detected, "impossible");
337
4.47M
        }
338
4.47M
    }
339
4.47M
}
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
371k
{
464
371k
    void* ptr = dt;
465
371k
    ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
466
371k
    ZSTD_seqSymbol* const cell = dt + 1;
467
468
371k
    DTableH->tableLog = 0;
469
371k
    DTableH->fastMode = 0;
470
471
371k
    cell->nbBits = 0;
472
371k
    cell->nextState = 0;
473
371k
    assert(nbAddBits < 255);
474
371k
    cell->nbAdditionalBits = nbAddBits;
475
371k
    cell->baseValue = baseValue;
476
371k
}
477
478
479
/* ZSTD_buildFSETable() :
480
 * generate FSE decoding table for one symbol (ll, ml or off)
481
 * cannot fail if input is valid =>
482
 * all inputs are presumed validated at this stage */
483
FORCE_INLINE_TEMPLATE
484
void ZSTD_buildFSETable_body(ZSTD_seqSymbol* dt,
485
            const short* normalizedCounter, unsigned maxSymbolValue,
486
            const U32* baseValue, const U8* nbAdditionalBits,
487
            unsigned tableLog, void* wksp, size_t wkspSize)
488
3.18M
{
489
3.18M
    ZSTD_seqSymbol* const tableDecode = dt+1;
490
3.18M
    U32 const maxSV1 = maxSymbolValue + 1;
491
3.18M
    U32 const tableSize = 1 << tableLog;
492
493
3.18M
    U16* symbolNext = (U16*)wksp;
494
3.18M
    BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1);
495
3.18M
    U32 highThreshold = tableSize - 1;
496
497
498
    /* Sanity Checks */
499
3.18M
    assert(maxSymbolValue <= MaxSeq);
500
3.18M
    assert(tableLog <= MaxFSELog);
501
3.18M
    assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE);
502
3.18M
    (void)wkspSize;
503
    /* Init, lay down lowprob symbols */
504
3.18M
    {   ZSTD_seqSymbol_header DTableH;
505
3.18M
        DTableH.tableLog = tableLog;
506
3.18M
        DTableH.fastMode = 1;
507
3.18M
        {   S16 const largeLimit= (S16)(1 << (tableLog-1));
508
3.18M
            U32 s;
509
64.9M
            for (s=0; s<maxSV1; s++) {
510
61.7M
                if (normalizedCounter[s]==-1) {
511
638k
                    tableDecode[highThreshold--].baseValue = s;
512
638k
                    symbolNext[s] = 1;
513
61.0M
                } else {
514
61.0M
                    if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
515
61.0M
                    assert(normalizedCounter[s]>=0);
516
61.0M
                    symbolNext[s] = (U16)normalizedCounter[s];
517
61.0M
        }   }   }
518
3.18M
        ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
519
3.18M
    }
520
521
    /* Spread symbols */
522
3.18M
    assert(tableSize <= 512);
523
    /* Specialized symbol spreading for the case when there are
524
     * no low probability (-1 count) symbols. When compressing
525
     * small blocks we avoid low probability symbols to hit this
526
     * case, since header decoding speed matters more.
527
     */
528
3.18M
    if (highThreshold == tableSize - 1) {
529
3.11M
        size_t const tableMask = tableSize-1;
530
3.11M
        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
3.11M
        {
538
3.11M
            U64 const add = 0x0101010101010101ull;
539
3.11M
            size_t pos = 0;
540
3.11M
            U64 sv = 0;
541
3.11M
            U32 s;
542
63.0M
            for (s=0; s<maxSV1; ++s, sv += add) {
543
59.9M
                int i;
544
59.9M
                int const n = normalizedCounter[s];
545
59.9M
                MEM_write64(spread + pos, sv);
546
77.5M
                for (i = 8; i < n; i += 8) {
547
17.5M
                    MEM_write64(spread + pos + i, sv);
548
17.5M
                }
549
59.9M
                assert(n>=0);
550
59.9M
                pos += (size_t)n;
551
59.9M
            }
552
3.11M
        }
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
3.11M
        {
560
3.11M
            size_t position = 0;
561
3.11M
            size_t s;
562
3.11M
            size_t const unroll = 2;
563
3.11M
            assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
564
126M
            for (s = 0; s < (size_t)tableSize; s += unroll) {
565
123M
                size_t u;
566
369M
                for (u = 0; u < unroll; ++u) {
567
246M
                    size_t const uPosition = (position + (u * step)) & tableMask;
568
246M
                    tableDecode[uPosition].baseValue = spread[s + u];
569
246M
                }
570
123M
                position = (position + (unroll * step)) & tableMask;
571
123M
            }
572
3.11M
            assert(position == 0);
573
3.11M
        }
574
3.11M
    } else {
575
70.6k
        U32 const tableMask = tableSize-1;
576
70.6k
        U32 const step = FSE_TABLESTEP(tableSize);
577
70.6k
        U32 s, position = 0;
578
1.83M
        for (s=0; s<maxSV1; s++) {
579
1.76M
            int i;
580
1.76M
            int const n = normalizedCounter[s];
581
23.5M
            for (i=0; i<n; i++) {
582
21.7M
                tableDecode[position].baseValue = s;
583
21.7M
                position = (position + step) & tableMask;
584
22.3M
                while (UNLIKELY(position > highThreshold)) position = (position + step) & tableMask;   /* lowprob area */
585
21.7M
        }   }
586
70.6k
        assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
587
70.6k
    }
588
589
    /* Build Decoding table */
590
3.18M
    {
591
3.18M
        U32 u;
592
271M
        for (u=0; u<tableSize; u++) {
593
268M
            U32 const symbol = tableDecode[u].baseValue;
594
268M
            U32 const nextState = symbolNext[symbol]++;
595
268M
            tableDecode[u].nbBits = (BYTE) (tableLog - ZSTD_highbit32(nextState) );
596
268M
            tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
597
268M
            assert(nbAdditionalBits[symbol] < 255);
598
268M
            tableDecode[u].nbAdditionalBits = nbAdditionalBits[symbol];
599
268M
            tableDecode[u].baseValue = baseValue[symbol];
600
268M
        }
601
3.18M
    }
602
3.18M
}
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
195k
{
610
195k
    ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
611
195k
            baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
612
195k
}
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.98M
{
620
2.98M
    ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
621
2.98M
            baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
622
2.98M
}
623
#endif
624
625
void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
626
            const short* normalizedCounter, unsigned maxSymbolValue,
627
            const U32* baseValue, const U8* nbAdditionalBits,
628
            unsigned tableLog, void* wksp, size_t wkspSize, int bmi2)
629
3.18M
{
630
3.18M
#if DYNAMIC_BMI2
631
3.18M
    if (bmi2) {
632
2.98M
        ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue,
633
2.98M
                baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
634
2.98M
        return;
635
2.98M
    }
636
195k
#endif
637
195k
    (void)bmi2;
638
195k
    ZSTD_buildFSETable_body_default(dt, normalizedCounter, maxSymbolValue,
639
195k
            baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
640
195k
}
641
642
643
/*! ZSTD_buildSeqTable() :
644
 * @return : nb bytes read from src,
645
 *           or an error code if it fails */
646
static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
647
                                 SymbolEncodingType_e type, unsigned max, U32 maxLog,
648
                                 const void* src, size_t srcSize,
649
                                 const U32* baseValue, const U8* nbAdditionalBits,
650
                                 const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
651
                                 int ddictIsCold, int nbSeq, U32* wksp, size_t wkspSize,
652
                                 int bmi2)
653
12.0M
{
654
12.0M
    switch(type)
655
12.0M
    {
656
371k
    case set_rle :
657
371k
        RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
658
371k
        RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
659
371k
        {   U32 const symbol = *(const BYTE*)src;
660
371k
            U32 const baseline = baseValue[symbol];
661
371k
            U8 const nbBits = nbAdditionalBits[symbol];
662
371k
            ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
663
371k
        }
664
371k
        *DTablePtr = DTableSpace;
665
371k
        return 1;
666
6.63M
    case set_basic :
667
6.63M
        *DTablePtr = defaultTable;
668
6.63M
        return 0;
669
2.09M
    case set_repeat:
670
2.09M
        RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
671
        /* prefetch FSE table if used */
672
2.09M
        if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
673
30.8k
            const void* const pStart = *DTablePtr;
674
30.8k
            size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
675
30.8k
            PREFETCH_AREA(pStart, pSize);
676
30.8k
        }
677
2.09M
        return 0;
678
2.98M
    case set_compressed :
679
2.98M
        {   unsigned tableLog;
680
2.98M
            S16 norm[MaxSeq+1];
681
2.98M
            size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
682
2.98M
            RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
683
2.98M
            RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
684
2.98M
            ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2);
685
2.98M
            *DTablePtr = DTableSpace;
686
2.98M
            return headerSize;
687
2.98M
        }
688
0
    default :
689
0
        assert(0);
690
12.0M
        RETURN_ERROR(GENERIC, "impossible");
691
12.0M
    }
692
12.0M
}
693
694
size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
695
                             const void* src, size_t srcSize)
696
4.45M
{
697
4.45M
    const BYTE* const istart = (const BYTE*)src;
698
4.45M
    const BYTE* const iend = istart + srcSize;
699
4.45M
    const BYTE* ip = istart;
700
4.45M
    int nbSeq;
701
4.45M
    DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
702
703
    /* check */
704
4.45M
    RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");
705
706
    /* SeqHead */
707
4.45M
    nbSeq = *ip++;
708
4.45M
    if (nbSeq > 0x7F) {
709
427k
        if (nbSeq == 0xFF) {
710
1.02k
            RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
711
910
            nbSeq = MEM_readLE16(ip) + LONGNBSEQ;
712
910
            ip+=2;
713
426k
        } else {
714
426k
            RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
715
426k
            nbSeq = ((nbSeq-0x80)<<8) + *ip++;
716
426k
        }
717
427k
    }
718
4.45M
    *nbSeqPtr = nbSeq;
719
720
4.45M
    if (nbSeq == 0) {
721
        /* No sequence : section ends immediately */
722
422k
        RETURN_ERROR_IF(ip != iend, corruption_detected,
723
422k
            "extraneous data present in the Sequences section");
724
422k
        return (size_t)(ip - istart);
725
422k
    }
726
727
    /* FSE table descriptors */
728
4.03M
    RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
729
4.03M
    RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */
730
4.03M
    {   SymbolEncodingType_e const LLtype = (SymbolEncodingType_e)(*ip >> 6);
731
4.03M
        SymbolEncodingType_e const OFtype = (SymbolEncodingType_e)((*ip >> 4) & 3);
732
4.03M
        SymbolEncodingType_e const MLtype = (SymbolEncodingType_e)((*ip >> 2) & 3);
733
4.03M
        ip++;
734
735
        /* Build DTables */
736
4.03M
        assert(ip <= iend);
737
4.03M
        {   size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
738
4.03M
                                                      LLtype, MaxLL, LLFSELog,
739
4.03M
                                                      ip, (size_t)(iend-ip),
740
4.03M
                                                      LL_base, LL_bits,
741
4.03M
                                                      LL_defaultDTable, dctx->fseEntropy,
742
4.03M
                                                      dctx->ddictIsCold, nbSeq,
743
4.03M
                                                      dctx->workspace, sizeof(dctx->workspace),
744
4.03M
                                                      ZSTD_DCtx_get_bmi2(dctx));
745
4.03M
            RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
746
4.03M
            ip += llhSize;
747
4.03M
        }
748
749
4.03M
        assert(ip <= iend);
750
4.03M
        {   size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
751
4.03M
                                                      OFtype, MaxOff, OffFSELog,
752
4.03M
                                                      ip, (size_t)(iend-ip),
753
4.03M
                                                      OF_base, OF_bits,
754
4.03M
                                                      OF_defaultDTable, dctx->fseEntropy,
755
4.03M
                                                      dctx->ddictIsCold, nbSeq,
756
4.03M
                                                      dctx->workspace, sizeof(dctx->workspace),
757
4.03M
                                                      ZSTD_DCtx_get_bmi2(dctx));
758
4.03M
            RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
759
4.02M
            ip += ofhSize;
760
4.02M
        }
761
762
4.02M
        assert(ip <= iend);
763
4.02M
        {   size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
764
4.02M
                                                      MLtype, MaxML, MLFSELog,
765
4.02M
                                                      ip, (size_t)(iend-ip),
766
4.02M
                                                      ML_base, ML_bits,
767
4.02M
                                                      ML_defaultDTable, dctx->fseEntropy,
768
4.02M
                                                      dctx->ddictIsCold, nbSeq,
769
4.02M
                                                      dctx->workspace, sizeof(dctx->workspace),
770
4.02M
                                                      ZSTD_DCtx_get_bmi2(dctx));
771
4.02M
            RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");
772
4.02M
            ip += mlhSize;
773
4.02M
        }
774
4.02M
    }
775
776
0
    return (size_t)(ip-istart);
777
4.02M
}
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
73.9M
{
808
73.9M
    assert(*ip <= *op);
809
73.9M
    if (offset < 8) {
810
        /* close range match, overlap */
811
52.9M
        static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 };   /* added */
812
52.9M
        static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 };   /* subtracted */
813
52.9M
        int const sub2 = dec64table[offset];
814
52.9M
        (*op)[0] = (*ip)[0];
815
52.9M
        (*op)[1] = (*ip)[1];
816
52.9M
        (*op)[2] = (*ip)[2];
817
52.9M
        (*op)[3] = (*ip)[3];
818
52.9M
        *ip += dec32table[offset];
819
52.9M
        ZSTD_copy4(*op+4, *ip);
820
52.9M
        *ip -= sub2;
821
52.9M
    } else {
822
21.0M
        ZSTD_copy8(*op, *ip);
823
21.0M
    }
824
73.9M
    *ip += 8;
825
73.9M
    *op += 8;
826
73.9M
    assert(*op - *ip >= 8);
827
73.9M
}
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
2.73M
{
843
2.73M
    ptrdiff_t const diff = op - ip;
844
2.73M
    BYTE* const oend = op + length;
845
846
2.73M
    assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
847
2.73M
           (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
848
849
2.73M
    if (length < 8) {
850
        /* Handle short lengths. */
851
5.10M
        while (op < oend) *op++ = *ip++;
852
1.25M
        return;
853
1.25M
    }
854
1.48M
    if (ovtype == ZSTD_overlap_src_before_dst) {
855
        /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
856
1.43M
        assert(length >= 8);
857
1.43M
        assert(diff > 0);
858
1.43M
        ZSTD_overlapCopy8(&op, &ip, (size_t)diff);
859
1.43M
        length -= 8;
860
1.43M
        assert(op - ip >= 8);
861
1.43M
        assert(op <= oend);
862
1.43M
    }
863
864
1.48M
    if (oend <= oend_w) {
865
        /* No risk of overwrite. */
866
16.0k
        ZSTD_wildcopy(op, ip, length, ovtype);
867
16.0k
        return;
868
16.0k
    }
869
1.46M
    if (op <= oend_w) {
870
        /* Wildcopy until we get close to the end. */
871
57.4k
        assert(oend > oend_w);
872
57.4k
        ZSTD_wildcopy(op, ip, (size_t)(oend_w - op), ovtype);
873
57.4k
        ip += oend_w - op;
874
57.4k
        op += oend_w - op;
875
57.4k
    }
876
    /* Handle the leftovers. */
877
5.96G
    while (op < oend) *op++ = *ip++;
878
1.46M
}
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
2.32M
{
885
2.32M
    ptrdiff_t const diff = op - ip;
886
2.32M
    BYTE* const oend = op + length;
887
888
2.32M
    if (length < 8 || diff > -8) {
889
        /* Handle short lengths, close overlaps, and dst not before src. */
890
16.1M
        while (op < oend) *op++ = *ip++;
891
2.29M
        return;
892
2.29M
    }
893
894
24.7k
    if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) {
895
20.4k
        ZSTD_wildcopy(op, ip, (size_t)(oend - WILDCOPY_OVERLENGTH - op), ZSTD_no_overlap);
896
20.4k
        ip += oend - WILDCOPY_OVERLENGTH - op;
897
20.4k
        op += oend - WILDCOPY_OVERLENGTH - op;
898
20.4k
    }
899
900
    /* Handle the leftovers. */
901
1.16M
    while (op < oend) *op++ = *ip++;
902
24.7k
}
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
296k
{
919
296k
    BYTE* const oLitEnd = op + sequence.litLength;
920
296k
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
921
296k
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
922
296k
    const BYTE* match = oLitEnd - sequence.offset;
923
296k
    BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
924
925
    /* bounds checks : careful of address space overflow in 32-bit mode */
926
296k
    RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
927
291k
    RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
928
291k
    assert(op < op + sequenceLength);
929
289k
    assert(oLitEnd < op + sequenceLength);
930
931
    /* copy literals */
932
289k
    ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
933
289k
    op = oLitEnd;
934
289k
    *litPtr = iLitEnd;
935
936
    /* copy Match */
937
289k
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
938
        /* offset beyond prefix */
939
29.4k
        RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
940
28.7k
        match = dictEnd - (prefixStart - match);
941
28.7k
        if (match + sequence.matchLength <= dictEnd) {
942
26.7k
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
943
26.7k
            return sequenceLength;
944
26.7k
        }
945
        /* span extDict & currentPrefixSegment */
946
2.03k
        {   size_t const length1 = (size_t)(dictEnd - match);
947
2.03k
            ZSTD_memmove(oLitEnd, match, length1);
948
2.03k
            op = oLitEnd + length1;
949
2.03k
            sequence.matchLength -= length1;
950
2.03k
            match = prefixStart;
951
2.03k
        }
952
2.03k
    }
953
262k
    ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
954
262k
    return sequenceLength;
955
289k
}
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
2.29M
{
967
2.29M
    BYTE* const oLitEnd = op + sequence.litLength;
968
2.29M
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
969
2.29M
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
970
2.29M
    const BYTE* match = oLitEnd - sequence.offset;
971
972
973
    /* bounds checks : careful of address space overflow in 32-bit mode */
974
2.29M
    RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
975
2.29M
    RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
976
2.29M
    assert(op < op + sequenceLength);
977
2.29M
    assert(oLitEnd < op + sequenceLength);
978
979
    /* copy literals */
980
2.29M
    RETURN_ERROR_IF(op > *litPtr && op < *litPtr + sequence.litLength, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer");
981
2.29M
    ZSTD_safecopyDstBeforeSrc(op, *litPtr, sequence.litLength);
982
2.29M
    op = oLitEnd;
983
2.29M
    *litPtr = iLitEnd;
984
985
    /* copy Match */
986
2.29M
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
987
        /* offset beyond prefix */
988
106k
        RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
989
106k
        match = dictEnd - (prefixStart - match);
990
106k
        if (match + sequence.matchLength <= dictEnd) {
991
106k
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
992
106k
            return sequenceLength;
993
106k
        }
994
        /* span extDict & currentPrefixSegment */
995
96
        {   size_t const length1 = (size_t)(dictEnd - match);
996
96
            ZSTD_memmove(oLitEnd, match, length1);
997
96
            op = oLitEnd + length1;
998
96
            sequence.matchLength -= length1;
999
96
            match = prefixStart;
1000
96
        }
1001
96
    }
1002
2.18M
    ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
1003
2.18M
    return sequenceLength;
1004
2.29M
}
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
266M
{
1013
266M
    BYTE* const oLitEnd = op + sequence.litLength;
1014
266M
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
1015
266M
    BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
1016
266M
    BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;   /* risk : address space underflow on oend=NULL */
1017
266M
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
1018
266M
    const BYTE* match = oLitEnd - sequence.offset;
1019
1020
266M
    assert(op != NULL /* Precondition */);
1021
266M
    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
266M
    if (UNLIKELY(
1033
266M
        iLitEnd > litLimit ||
1034
266M
        oMatchEnd > oend_w ||
1035
266M
        (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
1036
296k
        return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
1037
1038
    /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
1039
266M
    assert(op <= oLitEnd /* No overflow */);
1040
266M
    assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
1041
266M
    assert(oMatchEnd <= oend /* No underflow */);
1042
266M
    assert(iLitEnd <= litLimit /* Literal length is in bounds */);
1043
266M
    assert(oLitEnd <= oend_w /* Can wildcopy literals */);
1044
266M
    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
266M
    assert(WILDCOPY_OVERLENGTH >= 16);
1051
266M
    ZSTD_copy16(op, (*litPtr));
1052
266M
    if (UNLIKELY(sequence.litLength > 16)) {
1053
16.0M
        ZSTD_wildcopy(op + 16, (*litPtr) + 16, sequence.litLength - 16, ZSTD_no_overlap);
1054
16.0M
    }
1055
266M
    op = oLitEnd;
1056
266M
    *litPtr = iLitEnd;   /* update for next sequence */
1057
1058
    /* Copy Match */
1059
266M
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
1060
        /* offset beyond prefix -> go into extDict */
1061
3.56M
        RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
1062
3.56M
        match = dictEnd + (match - prefixStart);
1063
3.56M
        if (match + sequence.matchLength <= dictEnd) {
1064
3.50M
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
1065
3.50M
            return sequenceLength;
1066
3.50M
        }
1067
        /* span extDict & currentPrefixSegment */
1068
51.1k
        {   size_t const length1 = (size_t)(dictEnd - match);
1069
51.1k
            ZSTD_memmove(oLitEnd, match, length1);
1070
51.1k
            op = oLitEnd + length1;
1071
51.1k
            sequence.matchLength -= length1;
1072
51.1k
            match = prefixStart;
1073
51.1k
        }
1074
51.1k
    }
1075
    /* Match within prefix of 1 or more bytes */
1076
266M
    assert(op <= oMatchEnd);
1077
262M
    assert(oMatchEnd <= oend_w);
1078
262M
    assert(match >= prefixStart);
1079
262M
    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
262M
    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
191M
        ZSTD_wildcopy(op, match, sequence.matchLength, ZSTD_no_overlap);
1090
191M
        return sequenceLength;
1091
191M
    }
1092
262M
    assert(sequence.offset < WILDCOPY_VECLEN);
1093
1094
    /* Copy 8 bytes and spread the offset to be >= 8. */
1095
70.9M
    ZSTD_overlapCopy8(&op, &match, sequence.offset);
1096
1097
    /* If the match length is > 8 bytes, then continue with the wildcopy. */
1098
70.9M
    if (sequence.matchLength > 8) {
1099
18.8M
        assert(op < oMatchEnd);
1100
18.8M
        ZSTD_wildcopy(op, match, sequence.matchLength - 8, ZSTD_overlap_src_before_dst);
1101
18.8M
    }
1102
70.9M
    return sequenceLength;
1103
70.9M
}
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
5.64M
{
1112
5.64M
    BYTE* const oLitEnd = op + sequence.litLength;
1113
5.64M
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
1114
5.64M
    BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
1115
5.64M
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
1116
5.64M
    const BYTE* match = oLitEnd - sequence.offset;
1117
1118
5.64M
    assert(op != NULL /* Precondition */);
1119
5.64M
    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
5.64M
    if (UNLIKELY(
1126
5.64M
            iLitEnd > litLimit ||
1127
5.64M
            oMatchEnd > oend_w ||
1128
5.64M
            (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
1129
2.29M
        return ZSTD_execSequenceEndSplitLitBuffer(op, oend, oend_w, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
1130
1131
    /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
1132
5.64M
    assert(op <= oLitEnd /* No overflow */);
1133
3.35M
    assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
1134
3.35M
    assert(oMatchEnd <= oend /* No underflow */);
1135
3.35M
    assert(iLitEnd <= litLimit /* Literal length is in bounds */);
1136
3.35M
    assert(oLitEnd <= oend_w /* Can wildcopy literals */);
1137
3.35M
    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
3.35M
    assert(WILDCOPY_OVERLENGTH >= 16);
1144
3.35M
    ZSTD_copy16(op, (*litPtr));
1145
3.35M
    if (UNLIKELY(sequence.litLength > 16)) {
1146
330k
        ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
1147
330k
    }
1148
3.35M
    op = oLitEnd;
1149
3.35M
    *litPtr = iLitEnd;   /* update for next sequence */
1150
1151
    /* Copy Match */
1152
3.35M
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
1153
        /* offset beyond prefix -> go into extDict */
1154
193k
        RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
1155
192k
        match = dictEnd + (match - prefixStart);
1156
192k
        if (match + sequence.matchLength <= dictEnd) {
1157
191k
            ZSTD_memmove(oLitEnd, match, sequence.matchLength);
1158
191k
            return sequenceLength;
1159
191k
        }
1160
        /* span extDict & currentPrefixSegment */
1161
1.37k
        {   size_t const length1 = (size_t)(dictEnd - match);
1162
1.37k
            ZSTD_memmove(oLitEnd, match, length1);
1163
1.37k
            op = oLitEnd + length1;
1164
1.37k
            sequence.matchLength -= length1;
1165
1.37k
            match = prefixStart;
1166
1.37k
    }   }
1167
    /* Match within prefix of 1 or more bytes */
1168
3.35M
    assert(op <= oMatchEnd);
1169
3.16M
    assert(oMatchEnd <= oend_w);
1170
3.16M
    assert(match >= prefixStart);
1171
3.16M
    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
3.16M
    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
1.59M
        ZSTD_wildcopy(op, match, sequence.matchLength, ZSTD_no_overlap);
1182
1.59M
        return sequenceLength;
1183
1.59M
    }
1184
3.16M
    assert(sequence.offset < WILDCOPY_VECLEN);
1185
1186
    /* Copy 8 bytes and spread the offset to be >= 8. */
1187
1.57M
    ZSTD_overlapCopy8(&op, &match, sequence.offset);
1188
1189
    /* If the match length is > 8 bytes, then continue with the wildcopy. */
1190
1.57M
    if (sequence.matchLength > 8) {
1191
511k
        assert(op < oMatchEnd);
1192
511k
        ZSTD_wildcopy(op, match, sequence.matchLength-8, ZSTD_overlap_src_before_dst);
1193
511k
    }
1194
1.57M
    return sequenceLength;
1195
1.57M
}
1196
1197
1198
static void
1199
ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
1200
12.0M
{
1201
12.0M
    const void* ptr = dt;
1202
12.0M
    const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
1203
12.0M
    DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
1204
12.0M
    DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
1205
12.0M
                (U32)DStatePtr->state, DTableH->tableLog);
1206
12.0M
    BIT_reloadDStream(bitD);
1207
12.0M
    DStatePtr->table = dt + 1;
1208
12.0M
}
1209
1210
FORCE_INLINE_TEMPLATE void
1211
ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, U16 nextState, U32 nbBits)
1212
804M
{
1213
804M
    size_t const lowBits = BIT_readBits(bitD, nbBits);
1214
804M
    DStatePtr->state = nextState + lowBits;
1215
804M
}
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
272M
{
1238
272M
    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
    (void)longOffsets;
1265
    seq.matchLength = mlDInfo->baseValue;
1266
    seq.litLength = llDInfo->baseValue;
1267
    {   U32 const ofBase = ofDInfo->baseValue;
1268
        BYTE const llBits = llDInfo->nbAdditionalBits;
1269
        BYTE const mlBits = mlDInfo->nbAdditionalBits;
1270
        BYTE const ofBits = ofDInfo->nbAdditionalBits;
1271
        BYTE const totalBits = llBits+mlBits+ofBits;
1272
1273
        U16 const llNext = llDInfo->nextState;
1274
        U16 const mlNext = mlDInfo->nextState;
1275
        U16 const ofNext = ofDInfo->nextState;
1276
        U32 const llnbBits = llDInfo->nbBits;
1277
        U32 const mlnbBits = mlDInfo->nbBits;
1278
        U32 const ofnbBits = ofDInfo->nbBits;
1279
1280
        assert(llBits <= MaxLLBits);
1281
        assert(mlBits <= MaxMLBits);
1282
        assert(ofBits <= MaxOff);
1283
        /* As GCC has better branch and block analyzers, sometimes it is only
1284
         * valuable to mark likeliness for Clang.
1285
         */
1286
1287
        /* sequence */
1288
        {   size_t offset;
1289
            if (ofBits > 1) {
1290
                ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
1291
                ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
1292
                ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32);
1293
                ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits);
1294
                offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/);   /* <=  (ZSTD_WINDOWLOG_MAX-1) bits */
1295
                prevOffset2 = prevOffset1;
1296
                prevOffset1 = prevOffset0;
1297
                prevOffset0 = offset;
1298
            } else {
1299
                U32 const ll0 = (llDInfo->baseValue == 0);
1300
                if (LIKELY((ofBits == 0))) {
1301
                    if (ll0) {
1302
                        offset = prevOffset1;
1303
                        prevOffset1 = prevOffset0;
1304
                        prevOffset0 = offset;
1305
                    } else {
1306
                        offset = prevOffset0;
1307
                    }
1308
                } else {
1309
                    offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
1310
                    {   size_t temp = (offset == 1)   ? prevOffset1
1311
                                      : (offset == 3) ? prevOffset0 - 1
1312
                                      : (offset >= 2) ? prevOffset2
1313
                                      : prevOffset0;
1314
                        /* 0 is not valid: input corrupted => force offset to -1 =>
1315
                         * corruption detected at execSequence.
1316
                         */
1317
                        temp -= !temp;
1318
                        prevOffset2 = (offset == 1) ? prevOffset2 : prevOffset1;
1319
                        prevOffset1 = prevOffset0;
1320
                        prevOffset0 = offset = temp;
1321
            }   }   }
1322
            seq.offset = offset;
1323
        }
1324
1325
        if (mlBits > 0)
1326
            seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
1327
1328
        if (UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
1329
            BIT_reloadDStream(&seqState->DStream);
1330
1331
        /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
1332
        ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
1333
1334
        if (llBits > 0)
1335
            seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
1336
1337
        DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
1338
                    (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1339
1340
        if (!isLastSeq) {
1341
            /* Don't update FSE state for last sequence. */
1342
            ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits);    /* <=  9 bits */
1343
            ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits);    /* <=  9 bits */
1344
            ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits);  /* <=  8 bits */
1345
            BIT_reloadDStream(&seqState->DStream);
1346
        }
1347
    }
1348
    seqState->prevOffset[0] = prevOffset0;
1349
    seqState->prevOffset[1] = prevOffset1;
1350
    seqState->prevOffset[2] = prevOffset2;
1351
#else   /* !defined(__aarch64__) */
1352
272M
    const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state;
1353
272M
    const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state;
1354
272M
    const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state;
1355
272M
    seq.matchLength = mlDInfo->baseValue;
1356
272M
    seq.litLength = llDInfo->baseValue;
1357
272M
    {   U32 const ofBase = ofDInfo->baseValue;
1358
272M
        BYTE const llBits = llDInfo->nbAdditionalBits;
1359
272M
        BYTE const mlBits = mlDInfo->nbAdditionalBits;
1360
272M
        BYTE const ofBits = ofDInfo->nbAdditionalBits;
1361
272M
        BYTE const totalBits = llBits+mlBits+ofBits;
1362
1363
272M
        U16 const llNext = llDInfo->nextState;
1364
272M
        U16 const mlNext = mlDInfo->nextState;
1365
272M
        U16 const ofNext = ofDInfo->nextState;
1366
272M
        U32 const llnbBits = llDInfo->nbBits;
1367
272M
        U32 const mlnbBits = mlDInfo->nbBits;
1368
272M
        U32 const ofnbBits = ofDInfo->nbBits;
1369
1370
272M
        assert(llBits <= MaxLLBits);
1371
272M
        assert(mlBits <= MaxMLBits);
1372
272M
        assert(ofBits <= MaxOff);
1373
        /* As GCC has better branch and block analyzers, sometimes it is only
1374
         * valuable to mark likeliness for Clang.
1375
         */
1376
1377
        /* sequence */
1378
272M
        {   size_t offset;
1379
272M
            if (ofBits > 1) {
1380
169M
                ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
1381
169M
                ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
1382
169M
                ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32);
1383
169M
                ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits);
1384
169M
                if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
1385
                    /* Always read extra bits, this keeps the logic simple,
1386
                     * avoids branches, and avoids accidentally reading 0 bits.
1387
                     */
1388
0
                    U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32;
1389
0
                    offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
1390
0
                    BIT_reloadDStream(&seqState->DStream);
1391
0
                    offset += BIT_readBitsFast(&seqState->DStream, extraBits);
1392
169M
                } else {
1393
169M
                    offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/);   /* <=  (ZSTD_WINDOWLOG_MAX-1) bits */
1394
169M
                    if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
1395
169M
                }
1396
169M
                seqState->prevOffset[2] = seqState->prevOffset[1];
1397
169M
                seqState->prevOffset[1] = seqState->prevOffset[0];
1398
169M
                seqState->prevOffset[0] = offset;
1399
169M
            } else {
1400
103M
                U32 const ll0 = (llDInfo->baseValue == 0);
1401
103M
                if (LIKELY((ofBits == 0))) {
1402
95.1M
                    offset = seqState->prevOffset[ll0];
1403
95.1M
                    seqState->prevOffset[1] = seqState->prevOffset[!ll0];
1404
95.1M
                    seqState->prevOffset[0] = offset;
1405
95.1M
                } else {
1406
8.16M
                    offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
1407
8.16M
                    {   size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
1408
8.16M
                        temp -= !temp; /* 0 is not valid: input corrupted => force offset to -1 => corruption detected at execSequence */
1409
8.16M
                        if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
1410
8.16M
                        seqState->prevOffset[1] = seqState->prevOffset[0];
1411
8.16M
                        seqState->prevOffset[0] = offset = temp;
1412
8.16M
            }   }   }
1413
272M
            seq.offset = offset;
1414
272M
        }
1415
1416
272M
        if (mlBits > 0)
1417
16.8M
            seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
1418
1419
272M
        if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
1420
0
            BIT_reloadDStream(&seqState->DStream);
1421
272M
        if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
1422
198k
            BIT_reloadDStream(&seqState->DStream);
1423
        /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
1424
272M
        ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
1425
1426
272M
        if (llBits > 0)
1427
17.9M
            seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
1428
1429
272M
        if (MEM_32bits())
1430
0
            BIT_reloadDStream(&seqState->DStream);
1431
1432
272M
        DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
1433
272M
                    (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1434
1435
272M
        if (!isLastSeq) {
1436
            /* Don't update FSE state for last sequence. */
1437
268M
            ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits);    /* <=  9 bits */
1438
268M
            ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits);    /* <=  9 bits */
1439
268M
            if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);    /* <= 18 bits */
1440
268M
            ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits);  /* <=  8 bits */
1441
268M
            BIT_reloadDStream(&seqState->DStream);
1442
268M
        }
1443
272M
    }
1444
272M
#endif  /* defined(__aarch64__) */
1445
1446
272M
    return seq;
1447
272M
}
1448
1449
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1450
#if DEBUGLEVEL >= 1
1451
static int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
1452
248M
{
1453
248M
    size_t const windowSize = dctx->fParams.windowSize;
1454
    /* No dictionary used. */
1455
248M
    if (dctx->dictContentEndForFuzzing == NULL) return 0;
1456
    /* Dictionary is our prefix. */
1457
83.9M
    if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
1458
    /* Dictionary is not our ext-dict. */
1459
83.9M
    if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
1460
    /* Dictionary is not within our window size. */
1461
83.9M
    if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
1462
    /* Dictionary is active. */
1463
36.1M
    return 1;
1464
83.9M
}
1465
#endif
1466
1467
static void ZSTD_assertValidSequence(
1468
        ZSTD_DCtx const* dctx,
1469
        BYTE const* op, BYTE const* oend,
1470
        seq_t const seq,
1471
        BYTE const* prefixStart, BYTE const* virtualStart)
1472
250M
{
1473
250M
#if DEBUGLEVEL >= 1
1474
250M
    if (dctx->isFrameDecompression) {
1475
248M
        size_t const windowSize = dctx->fParams.windowSize;
1476
248M
        size_t const sequenceSize = seq.litLength + seq.matchLength;
1477
248M
        BYTE const* const oLitEnd = op + seq.litLength;
1478
248M
        DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
1479
248M
                (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1480
248M
        assert(op <= oend);
1481
248M
        assert((size_t)(oend - op) >= sequenceSize);
1482
248M
        assert(sequenceSize <= ZSTD_blockSizeMax(dctx));
1483
248M
        if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
1484
36.1M
            size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
1485
            /* Offset must be within the dictionary. */
1486
36.1M
            assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
1487
36.1M
            assert(seq.offset <= windowSize + dictSize);
1488
212M
        } else {
1489
            /* Offset must be within our window. */
1490
212M
            assert(seq.offset <= windowSize);
1491
212M
        }
1492
248M
    }
1493
#else
1494
    (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
1495
#endif
1496
250M
}
1497
#endif
1498
1499
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1500
1501
1502
FORCE_INLINE_TEMPLATE size_t
1503
DONT_VECTORIZE
1504
ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
1505
                               void* dst, size_t maxDstSize,
1506
                         const void* seqStart, size_t seqSize, int nbSeq,
1507
                         const ZSTD_longOffset_e isLongOffset)
1508
12.2k
{
1509
12.2k
    BYTE* const ostart = (BYTE*)dst;
1510
12.2k
    BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize);
1511
12.2k
    BYTE* op = ostart;
1512
12.2k
    const BYTE* litPtr = dctx->litPtr;
1513
12.2k
    const BYTE* litBufferEnd = dctx->litBufferEnd;
1514
12.2k
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1515
12.2k
    const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
1516
12.2k
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1517
12.2k
    DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq);
1518
1519
    /* Literals are split between internal buffer & output buffer */
1520
12.2k
    if (nbSeq) {
1521
12.0k
        seqState_t seqState;
1522
12.0k
        dctx->fseEntropy = 1;
1523
48.0k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1524
12.0k
        RETURN_ERROR_IF(
1525
12.0k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1526
12.0k
            corruption_detected, "");
1527
11.9k
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1528
11.9k
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1529
11.9k
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1530
11.9k
        assert(dst != NULL);
1531
1532
11.9k
        ZSTD_STATIC_ASSERT(
1533
11.9k
                BIT_DStream_unfinished < BIT_DStream_completed &&
1534
11.9k
                BIT_DStream_endOfBuffer < BIT_DStream_completed &&
1535
11.9k
                BIT_DStream_completed < BIT_DStream_overflow);
1536
1537
        /* decompress without overrunning litPtr begins */
1538
11.9k
        {   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) */
1539
            /* Align the decompression loop to 32 + 16 bytes.
1540
                *
1541
                * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
1542
                * speed swings based on the alignment of the decompression loop. This
1543
                * performance swing is caused by parts of the decompression loop falling
1544
                * out of the DSB. The entire decompression loop should fit in the DSB,
1545
                * when it can't we get much worse performance. You can measure if you've
1546
                * hit the good case or the bad case with this perf command for some
1547
                * compressed file test.zst:
1548
                *
1549
                *   perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
1550
                *             -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
1551
                *
1552
                * If you see most cycles served out of the MITE you've hit the bad case.
1553
                * If you see most cycles served out of the DSB you've hit the good case.
1554
                * If it is pretty even then you may be in an okay case.
1555
                *
1556
                * This issue has been reproduced on the following CPUs:
1557
                *   - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
1558
                *               Use Instruments->Counters to get DSB/MITE cycles.
1559
                *               I never got performance swings, but I was able to
1560
                *               go from the good case of mostly DSB to half of the
1561
                *               cycles served from MITE.
1562
                *   - Coffeelake: Intel i9-9900k
1563
                *   - Coffeelake: Intel i7-9700k
1564
                *
1565
                * I haven't been able to reproduce the instability or DSB misses on any
1566
                * of the following CPUS:
1567
                *   - Haswell
1568
                *   - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
1569
                *   - Skylake
1570
                *
1571
                * Alignment is done for each of the three major decompression loops:
1572
                *   - ZSTD_decompressSequences_bodySplitLitBuffer - presplit section of the literal buffer
1573
                *   - ZSTD_decompressSequences_bodySplitLitBuffer - postsplit section of the literal buffer
1574
                *   - ZSTD_decompressSequences_body
1575
                * Alignment choices are made to minimize large swings on bad cases and influence on performance
1576
                * from changes external to this code, rather than to overoptimize on the current commit.
1577
                *
1578
                * If you are seeing performance stability this script can help test.
1579
                * It tests on 4 commits in zstd where I saw performance change.
1580
                *
1581
                *   https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
1582
                */
1583
11.9k
#if defined(__GNUC__) && defined(__x86_64__)
1584
11.9k
            __asm__(".p2align 6");
1585
#  if __GNUC__ >= 7
1586
      /* good for gcc-7, gcc-9, and gcc-11 */
1587
            __asm__("nop");
1588
            __asm__(".p2align 5");
1589
            __asm__("nop");
1590
            __asm__(".p2align 4");
1591
#    if __GNUC__ == 8 || __GNUC__ == 10
1592
      /* good for gcc-8 and gcc-10 */
1593
            __asm__("nop");
1594
            __asm__(".p2align 3");
1595
#    endif
1596
#  endif
1597
11.9k
#endif
1598
1599
            /* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */
1600
4.44M
            for ( ; nbSeq; nbSeq--) {
1601
4.44M
                sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
1602
4.44M
                if (litPtr + sequence.litLength > dctx->litBufferEnd) break;
1603
4.43M
                {   size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
1604
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1605
                    assert(!ZSTD_isError(oneSeqSize));
1606
                    ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1607
#endif
1608
4.43M
                    if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1609
1.19k
                        return oneSeqSize;
1610
4.43M
                    DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1611
4.43M
                    op += oneSeqSize;
1612
4.43M
            }   }
1613
10.7k
            DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)");
1614
1615
            /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */
1616
10.7k
            if (nbSeq > 0) {
1617
9.04k
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1618
9.04k
                assert(dctx->litBufferEnd >= litPtr);
1619
9.04k
                DEBUGLOG(6, "There are %i sequences left, and %zu/%zu literals left in buffer", nbSeq, leftoverLit, sequence.litLength);
1620
9.04k
                if (leftoverLit) {
1621
7.52k
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1622
7.50k
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1623
7.50k
                    sequence.litLength -= leftoverLit;
1624
7.50k
                    op += leftoverLit;
1625
7.50k
                }
1626
9.02k
                litPtr = dctx->litExtraBuffer;
1627
9.02k
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1628
9.02k
                dctx->litBufferLocation = ZSTD_not_in_dst;
1629
9.02k
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
1630
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1631
                    assert(!ZSTD_isError(oneSeqSize));
1632
                    ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1633
#endif
1634
9.02k
                    if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1635
417
                        return oneSeqSize;
1636
8.60k
                    DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1637
8.60k
                    op += oneSeqSize;
1638
8.60k
                }
1639
0
                nbSeq--;
1640
8.60k
            }
1641
10.7k
        }
1642
1643
10.2k
        if (nbSeq > 0) {
1644
            /* there is remaining lit from extra buffer */
1645
1646
5.90k
#if defined(__GNUC__) && defined(__x86_64__)
1647
5.90k
            __asm__(".p2align 6");
1648
5.90k
            __asm__("nop");
1649
5.90k
#  if __GNUC__ != 7
1650
            /* worse for gcc-7 better for gcc-8, gcc-9, and gcc-10 and clang */
1651
5.90k
            __asm__(".p2align 4");
1652
5.90k
            __asm__("nop");
1653
5.90k
            __asm__(".p2align 3");
1654
#  elif __GNUC__ >= 11
1655
            __asm__(".p2align 3");
1656
#  else
1657
            __asm__(".p2align 5");
1658
            __asm__("nop");
1659
            __asm__(".p2align 3");
1660
#  endif
1661
5.90k
#endif
1662
1663
4.95M
            for ( ; nbSeq ; nbSeq--) {
1664
4.94M
                seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
1665
4.94M
                size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
1666
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1667
                assert(!ZSTD_isError(oneSeqSize));
1668
                ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1669
#endif
1670
4.94M
                if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1671
2.31k
                    return oneSeqSize;
1672
4.94M
                DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1673
4.94M
                op += oneSeqSize;
1674
4.94M
            }
1675
5.90k
        }
1676
1677
        /* check if reached exact end */
1678
7.95k
        DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq);
1679
7.95k
        RETURN_ERROR_IF(nbSeq, corruption_detected, "");
1680
7.95k
        DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed);
1681
7.95k
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1682
        /* save reps for next block */
1683
29.0k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1684
7.25k
    }
1685
1686
    /* last literal segment */
1687
7.49k
    if (dctx->litBufferLocation == ZSTD_split) {
1688
        /* split hasn't been reached yet, first get dst then copy litExtraBuffer */
1689
1.68k
        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1690
1.68k
        DEBUGLOG(6, "copy last literals from segment : %u", (U32)lastLLSize);
1691
1.68k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
1692
1.61k
        if (op != NULL) {
1693
1.61k
            ZSTD_memmove(op, litPtr, lastLLSize);
1694
1.61k
            op += lastLLSize;
1695
1.61k
        }
1696
1.61k
        litPtr = dctx->litExtraBuffer;
1697
1.61k
        litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1698
1.61k
        dctx->litBufferLocation = ZSTD_not_in_dst;
1699
1.61k
    }
1700
    /* copy last literals from internal buffer */
1701
7.41k
    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1702
7.41k
        DEBUGLOG(6, "copy last literals from internal buffer : %u", (U32)lastLLSize);
1703
7.41k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1704
6.78k
        if (op != NULL) {
1705
6.78k
            ZSTD_memcpy(op, litPtr, lastLLSize);
1706
6.78k
            op += lastLLSize;
1707
6.78k
    }   }
1708
1709
6.78k
    DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));
1710
6.78k
    return (size_t)(op - ostart);
1711
7.41k
}
1712
1713
FORCE_INLINE_TEMPLATE size_t
1714
DONT_VECTORIZE
1715
ZSTD_decompressSequences_body(ZSTD_DCtx* dctx,
1716
    void* dst, size_t maxDstSize,
1717
    const void* seqStart, size_t seqSize, int nbSeq,
1718
    const ZSTD_longOffset_e isLongOffset)
1719
85.2k
{
1720
85.2k
    BYTE* const ostart = (BYTE*)dst;
1721
85.2k
    BYTE* const oend = (dctx->litBufferLocation == ZSTD_not_in_dst) ?
1722
53.1k
                        (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize) :
1723
85.2k
                        dctx->litBuffer;
1724
85.2k
    BYTE* op = ostart;
1725
85.2k
    const BYTE* litPtr = dctx->litPtr;
1726
85.2k
    const BYTE* const litEnd = litPtr + dctx->litSize;
1727
85.2k
    const BYTE* const prefixStart = (const BYTE*)(dctx->prefixStart);
1728
85.2k
    const BYTE* const vBase = (const BYTE*)(dctx->virtualStart);
1729
85.2k
    const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd);
1730
85.2k
    DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq);
1731
1732
    /* Regen sequences */
1733
85.2k
    if (nbSeq) {
1734
35.3k
        seqState_t seqState;
1735
35.3k
        dctx->fseEntropy = 1;
1736
141k
        { U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1737
35.3k
        RETURN_ERROR_IF(
1738
35.3k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1739
35.3k
            corruption_detected, "");
1740
34.9k
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1741
34.9k
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1742
34.9k
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1743
34.9k
        assert(dst != NULL);
1744
1745
34.9k
#if defined(__GNUC__) && defined(__x86_64__)
1746
34.9k
            __asm__(".p2align 6");
1747
34.9k
            __asm__("nop");
1748
#  if __GNUC__ >= 7
1749
            __asm__(".p2align 5");
1750
            __asm__("nop");
1751
            __asm__(".p2align 3");
1752
#  else
1753
34.9k
            __asm__(".p2align 4");
1754
34.9k
            __asm__("nop");
1755
34.9k
            __asm__(".p2align 3");
1756
34.9k
#  endif
1757
34.9k
#endif
1758
1759
10.6M
        for ( ; nbSeq ; nbSeq--) {
1760
10.6M
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);
1761
10.6M
            size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
1762
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1763
            assert(!ZSTD_isError(oneSeqSize));
1764
            ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1765
#endif
1766
10.6M
            if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1767
5.85k
                return oneSeqSize;
1768
10.6M
            DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1769
10.6M
            op += oneSeqSize;
1770
10.6M
        }
1771
1772
        /* check if reached exact end */
1773
34.9k
        assert(nbSeq == 0);
1774
29.1k
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1775
        /* save reps for next block */
1776
114k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1777
28.7k
    }
1778
1779
    /* last literal segment */
1780
78.5k
    {   size_t const lastLLSize = (size_t)(litEnd - litPtr);
1781
78.5k
        DEBUGLOG(6, "copy last literals : %u", (U32)lastLLSize);
1782
78.5k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1783
77.4k
        if (op != NULL) {
1784
67.3k
            ZSTD_memcpy(op, litPtr, lastLLSize);
1785
67.3k
            op += lastLLSize;
1786
67.3k
    }   }
1787
1788
77.4k
    DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));
1789
77.4k
    return (size_t)(op - ostart);
1790
78.5k
}
1791
1792
static size_t
1793
ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
1794
                                 void* dst, size_t maxDstSize,
1795
                           const void* seqStart, size_t seqSize, int nbSeq,
1796
                           const ZSTD_longOffset_e isLongOffset)
1797
0
{
1798
0
    return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1799
0
}
1800
1801
static size_t
1802
ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx,
1803
                                               void* dst, size_t maxDstSize,
1804
                                         const void* seqStart, size_t seqSize, int nbSeq,
1805
                                         const ZSTD_longOffset_e isLongOffset)
1806
0
{
1807
0
    return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1808
0
}
1809
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1810
1811
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1812
1813
FORCE_INLINE_TEMPLATE
1814
1815
size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
1816
                   const BYTE* const prefixStart, const BYTE* const dictEnd)
1817
16.9M
{
1818
16.9M
    prefetchPos += sequence.litLength;
1819
16.9M
    {   const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;
1820
        /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.
1821
         * No consequence though : memory address is only used for prefetching, not for dereferencing */
1822
16.9M
        const BYTE* const match = (const BYTE*)ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset);
1823
16.9M
        PREFETCH_L1(match); PREFETCH_L1(ZSTD_wrappedPtrAdd(match, CACHELINE_SIZE));   /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
1824
16.9M
    }
1825
16.9M
    return prefetchPos + sequence.matchLength;
1826
16.9M
}
1827
1828
/* This decoding function employs prefetching
1829
 * to reduce latency impact of cache misses.
1830
 * It's generally employed when block contains a significant portion of long-distance matches
1831
 * or when coupled with a "cold" dictionary */
1832
FORCE_INLINE_TEMPLATE size_t
1833
ZSTD_decompressSequencesLong_body(
1834
                               ZSTD_DCtx* dctx,
1835
                               void* dst, size_t maxDstSize,
1836
                         const void* seqStart, size_t seqSize, int nbSeq,
1837
                         const ZSTD_longOffset_e isLongOffset)
1838
130k
{
1839
130k
    BYTE* const ostart = (BYTE*)dst;
1840
130k
    BYTE* const oend = (dctx->litBufferLocation == ZSTD_in_dst) ?
1841
39.1k
                        dctx->litBuffer :
1842
130k
                        (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize);
1843
130k
    BYTE* op = ostart;
1844
130k
    const BYTE* litPtr = dctx->litPtr;
1845
130k
    const BYTE* litBufferEnd = dctx->litBufferEnd;
1846
130k
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1847
130k
    const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
1848
130k
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1849
1850
    /* Regen sequences */
1851
130k
    if (nbSeq) {
1852
82.6M
#define STORED_SEQS 8
1853
50.0M
#define STORED_SEQS_MASK (STORED_SEQS-1)
1854
32.5M
#define ADVANCED_SEQS STORED_SEQS
1855
127k
        seq_t sequences[STORED_SEQS];
1856
127k
        int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
1857
127k
        seqState_t seqState;
1858
127k
        int seqNb;
1859
127k
        size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
1860
1861
127k
        dctx->fseEntropy = 1;
1862
509k
        { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1863
127k
        assert(dst != NULL);
1864
127k
        RETURN_ERROR_IF(
1865
127k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1866
127k
            corruption_detected, "");
1867
127k
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1868
127k
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1869
127k
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1870
1871
        /* prepare in advance */
1872
897k
        for (seqNb=0; seqNb<seqAdvance; seqNb++) {
1873
769k
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1874
769k
            prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1875
769k
            sequences[seqNb] = sequence;
1876
769k
        }
1877
1878
        /* decompress without stomping litBuffer */
1879
16.2M
        for (; seqNb < nbSeq; seqNb++) {
1880
16.1M
            seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1881
1882
16.1M
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) {
1883
                /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */
1884
6.18k
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1885
6.18k
                assert(dctx->litBufferEnd >= litPtr);
1886
6.18k
                if (leftoverLit) {
1887
6.12k
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1888
6.11k
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1889
6.11k
                    sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;
1890
6.11k
                    op += leftoverLit;
1891
6.11k
                }
1892
6.17k
                litPtr = dctx->litExtraBuffer;
1893
6.17k
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1894
6.17k
                dctx->litBufferLocation = ZSTD_not_in_dst;
1895
6.17k
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1896
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1897
                    assert(!ZSTD_isError(oneSeqSize));
1898
852
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1899
#endif
1900
6.17k
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1901
1902
6.10k
                    prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1903
6.10k
                    sequences[seqNb & STORED_SEQS_MASK] = sequence;
1904
6.10k
                    op += oneSeqSize;
1905
6.10k
            }   }
1906
16.1M
            else
1907
16.1M
            {
1908
                /* lit buffer is either wholly contained in first or second split, or not split at all*/
1909
16.1M
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1910
741k
                    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) :
1911
16.1M
                    ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1912
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1913
                assert(!ZSTD_isError(oneSeqSize));
1914
14.8M
                ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1915
#endif
1916
16.1M
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1917
1918
16.1M
                prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1919
16.1M
                sequences[seqNb & STORED_SEQS_MASK] = sequence;
1920
16.1M
                op += oneSeqSize;
1921
16.1M
            }
1922
16.1M
        }
1923
126k
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1924
1925
        /* finish queue */
1926
125k
        seqNb -= seqAdvance;
1927
883k
        for ( ; seqNb<nbSeq ; seqNb++) {
1928
758k
            seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);
1929
758k
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) {
1930
12.2k
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1931
12.2k
                assert(dctx->litBufferEnd >= litPtr);
1932
12.2k
                if (leftoverLit) {
1933
11.8k
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1934
11.8k
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1935
11.8k
                    sequence->litLength -= leftoverLit;
1936
11.8k
                    op += leftoverLit;
1937
11.8k
                }
1938
12.2k
                litPtr = dctx->litExtraBuffer;
1939
12.2k
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1940
12.2k
                dctx->litBufferLocation = ZSTD_not_in_dst;
1941
12.2k
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1942
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1943
                    assert(!ZSTD_isError(oneSeqSize));
1944
887
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1945
#endif
1946
12.2k
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1947
12.2k
                    op += oneSeqSize;
1948
12.2k
                }
1949
12.2k
            }
1950
745k
            else
1951
745k
            {
1952
745k
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1953
31.1k
                    ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
1954
745k
                    ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1955
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1956
                assert(!ZSTD_isError(oneSeqSize));
1957
619k
                ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1958
#endif
1959
745k
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1960
745k
                op += oneSeqSize;
1961
745k
            }
1962
758k
        }
1963
1964
        /* save reps for next block */
1965
502k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1966
125k
    }
1967
1968
    /* last literal segment */
1969
128k
    if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */
1970
992
        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1971
992
        assert(litBufferEnd >= litPtr);
1972
992
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
1973
977
        if (op != NULL) {
1974
977
            ZSTD_memmove(op, litPtr, lastLLSize);
1975
977
            op += lastLLSize;
1976
977
        }
1977
977
        litPtr = dctx->litExtraBuffer;
1978
977
        litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1979
977
    }
1980
128k
    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1981
128k
        assert(litBufferEnd >= litPtr);
1982
128k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1983
128k
        if (op != NULL) {
1984
127k
            ZSTD_memmove(op, litPtr, lastLLSize);
1985
127k
            op += lastLLSize;
1986
127k
        }
1987
128k
    }
1988
1989
0
    return (size_t)(op - ostart);
1990
128k
}
zstd_decompress_block.c:ZSTD_decompressSequencesLong_body
Line
Count
Source
1838
19.4k
{
1839
19.4k
    BYTE* const ostart = (BYTE*)dst;
1840
19.4k
    BYTE* const oend = (dctx->litBufferLocation == ZSTD_in_dst) ?
1841
325
                        dctx->litBuffer :
1842
19.4k
                        (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize);
1843
19.4k
    BYTE* op = ostart;
1844
19.4k
    const BYTE* litPtr = dctx->litPtr;
1845
19.4k
    const BYTE* litBufferEnd = dctx->litBufferEnd;
1846
19.4k
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1847
19.4k
    const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
1848
19.4k
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1849
1850
    /* Regen sequences */
1851
19.4k
    if (nbSeq) {
1852
18.8k
#define STORED_SEQS 8
1853
18.8k
#define STORED_SEQS_MASK (STORED_SEQS-1)
1854
18.8k
#define ADVANCED_SEQS STORED_SEQS
1855
18.8k
        seq_t sequences[STORED_SEQS];
1856
18.8k
        int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
1857
18.8k
        seqState_t seqState;
1858
18.8k
        int seqNb;
1859
18.8k
        size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
1860
1861
18.8k
        dctx->fseEntropy = 1;
1862
75.3k
        { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1863
18.8k
        assert(dst != NULL);
1864
18.8k
        RETURN_ERROR_IF(
1865
18.8k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1866
18.8k
            corruption_detected, "");
1867
18.8k
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1868
18.8k
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1869
18.8k
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1870
1871
        /* prepare in advance */
1872
168k
        for (seqNb=0; seqNb<seqAdvance; seqNb++) {
1873
149k
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1874
149k
            prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1875
149k
            sequences[seqNb] = sequence;
1876
149k
        }
1877
1878
        /* decompress without stomping litBuffer */
1879
1.33M
        for (; seqNb < nbSeq; seqNb++) {
1880
1.31M
            seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1881
1882
1.31M
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) {
1883
                /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */
1884
5.33k
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1885
5.33k
                assert(dctx->litBufferEnd >= litPtr);
1886
5.33k
                if (leftoverLit) {
1887
5.28k
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1888
5.28k
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1889
5.28k
                    sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;
1890
5.28k
                    op += leftoverLit;
1891
5.28k
                }
1892
5.32k
                litPtr = dctx->litExtraBuffer;
1893
5.32k
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1894
5.32k
                dctx->litBufferLocation = ZSTD_not_in_dst;
1895
5.32k
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1896
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1897
                    assert(!ZSTD_isError(oneSeqSize));
1898
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1899
#endif
1900
5.32k
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1901
1902
5.24k
                    prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1903
5.24k
                    sequences[seqNb & STORED_SEQS_MASK] = sequence;
1904
5.24k
                    op += oneSeqSize;
1905
5.24k
            }   }
1906
1.31M
            else
1907
1.31M
            {
1908
                /* lit buffer is either wholly contained in first or second split, or not split at all*/
1909
1.31M
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1910
629k
                    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) :
1911
1.31M
                    ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1912
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1913
                assert(!ZSTD_isError(oneSeqSize));
1914
                ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1915
#endif
1916
1.31M
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1917
1918
1.30M
                prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1919
1.30M
                sequences[seqNb & STORED_SEQS_MASK] = sequence;
1920
1.30M
                op += oneSeqSize;
1921
1.30M
            }
1922
1.31M
        }
1923
17.5k
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1924
1925
        /* finish queue */
1926
17.4k
        seqNb -= seqAdvance;
1927
154k
        for ( ; seqNb<nbSeq ; seqNb++) {
1928
137k
            seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);
1929
137k
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) {
1930
11.3k
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1931
11.3k
                assert(dctx->litBufferEnd >= litPtr);
1932
11.3k
                if (leftoverLit) {
1933
11.0k
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1934
11.0k
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1935
11.0k
                    sequence->litLength -= leftoverLit;
1936
11.0k
                    op += leftoverLit;
1937
11.0k
                }
1938
11.3k
                litPtr = dctx->litExtraBuffer;
1939
11.3k
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1940
11.3k
                dctx->litBufferLocation = ZSTD_not_in_dst;
1941
11.3k
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1942
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1943
                    assert(!ZSTD_isError(oneSeqSize));
1944
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1945
#endif
1946
11.3k
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1947
11.3k
                    op += oneSeqSize;
1948
11.3k
                }
1949
11.3k
            }
1950
126k
            else
1951
126k
            {
1952
126k
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1953
28.7k
                    ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
1954
126k
                    ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1955
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1956
                assert(!ZSTD_isError(oneSeqSize));
1957
                ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1958
#endif
1959
126k
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1960
125k
                op += oneSeqSize;
1961
125k
            }
1962
137k
        }
1963
1964
        /* save reps for next block */
1965
68.6k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1966
17.1k
    }
1967
1968
    /* last literal segment */
1969
17.8k
    if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */
1970
714
        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1971
714
        assert(litBufferEnd >= litPtr);
1972
714
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
1973
699
        if (op != NULL) {
1974
699
            ZSTD_memmove(op, litPtr, lastLLSize);
1975
699
            op += lastLLSize;
1976
699
        }
1977
699
        litPtr = dctx->litExtraBuffer;
1978
699
        litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1979
699
    }
1980
17.7k
    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1981
17.7k
        assert(litBufferEnd >= litPtr);
1982
17.7k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1983
17.6k
        if (op != NULL) {
1984
17.4k
            ZSTD_memmove(op, litPtr, lastLLSize);
1985
17.4k
            op += lastLLSize;
1986
17.4k
        }
1987
17.6k
    }
1988
1989
0
    return (size_t)(op - ostart);
1990
17.7k
}
zstd_decompress_block.c:ZSTD_decompressSequencesLong_body
Line
Count
Source
1838
110k
{
1839
110k
    BYTE* const ostart = (BYTE*)dst;
1840
110k
    BYTE* const oend = (dctx->litBufferLocation == ZSTD_in_dst) ?
1841
38.8k
                        dctx->litBuffer :
1842
110k
                        (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize);
1843
110k
    BYTE* op = ostart;
1844
110k
    const BYTE* litPtr = dctx->litPtr;
1845
110k
    const BYTE* litBufferEnd = dctx->litBufferEnd;
1846
110k
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1847
110k
    const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
1848
110k
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1849
1850
    /* Regen sequences */
1851
110k
    if (nbSeq) {
1852
108k
#define STORED_SEQS 8
1853
108k
#define STORED_SEQS_MASK (STORED_SEQS-1)
1854
108k
#define ADVANCED_SEQS STORED_SEQS
1855
108k
        seq_t sequences[STORED_SEQS];
1856
108k
        int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
1857
108k
        seqState_t seqState;
1858
108k
        int seqNb;
1859
108k
        size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
1860
1861
108k
        dctx->fseEntropy = 1;
1862
434k
        { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1863
108k
        assert(dst != NULL);
1864
108k
        RETURN_ERROR_IF(
1865
108k
            ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)),
1866
108k
            corruption_detected, "");
1867
108k
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1868
108k
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1869
108k
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1870
1871
        /* prepare in advance */
1872
729k
        for (seqNb=0; seqNb<seqAdvance; seqNb++) {
1873
620k
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1874
620k
            prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1875
620k
            sequences[seqNb] = sequence;
1876
620k
        }
1877
1878
        /* decompress without stomping litBuffer */
1879
14.9M
        for (; seqNb < nbSeq; seqNb++) {
1880
14.8M
            seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);
1881
1882
14.8M
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) {
1883
                /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */
1884
852
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1885
852
                assert(dctx->litBufferEnd >= litPtr);
1886
852
                if (leftoverLit) {
1887
831
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1888
831
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1889
831
                    sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;
1890
831
                    op += leftoverLit;
1891
831
                }
1892
852
                litPtr = dctx->litExtraBuffer;
1893
852
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1894
852
                dctx->litBufferLocation = ZSTD_not_in_dst;
1895
852
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1896
852
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1897
852
                    assert(!ZSTD_isError(oneSeqSize));
1898
852
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1899
852
#endif
1900
852
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1901
1902
852
                    prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1903
852
                    sequences[seqNb & STORED_SEQS_MASK] = sequence;
1904
852
                    op += oneSeqSize;
1905
852
            }   }
1906
14.8M
            else
1907
14.8M
            {
1908
                /* lit buffer is either wholly contained in first or second split, or not split at all*/
1909
14.8M
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1910
111k
                    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) :
1911
14.8M
                    ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1912
14.8M
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1913
14.8M
                assert(!ZSTD_isError(oneSeqSize));
1914
14.8M
                ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1915
14.8M
#endif
1916
14.8M
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1917
1918
14.8M
                prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1919
14.8M
                sequences[seqNb & STORED_SEQS_MASK] = sequence;
1920
14.8M
                op += oneSeqSize;
1921
14.8M
            }
1922
14.8M
        }
1923
108k
        RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");
1924
1925
        /* finish queue */
1926
108k
        seqNb -= seqAdvance;
1927
729k
        for ( ; seqNb<nbSeq ; seqNb++) {
1928
620k
            seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);
1929
620k
            if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) {
1930
887
                const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr);
1931
887
                assert(dctx->litBufferEnd >= litPtr);
1932
887
                if (leftoverLit) {
1933
783
                    RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
1934
783
                    ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
1935
783
                    sequence->litLength -= leftoverLit;
1936
783
                    op += leftoverLit;
1937
783
                }
1938
887
                litPtr = dctx->litExtraBuffer;
1939
887
                litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1940
887
                dctx->litBufferLocation = ZSTD_not_in_dst;
1941
887
                {   size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1942
887
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1943
887
                    assert(!ZSTD_isError(oneSeqSize));
1944
887
                    ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1945
887
#endif
1946
887
                    if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1947
887
                    op += oneSeqSize;
1948
887
                }
1949
887
            }
1950
619k
            else
1951
619k
            {
1952
619k
                size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
1953
2.34k
                    ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
1954
619k
                    ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
1955
619k
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1956
619k
                assert(!ZSTD_isError(oneSeqSize));
1957
619k
                ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1958
619k
#endif
1959
619k
                if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1960
619k
                op += oneSeqSize;
1961
619k
            }
1962
620k
        }
1963
1964
        /* save reps for next block */
1965
434k
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1966
108k
    }
1967
1968
    /* last literal segment */
1969
110k
    if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */
1970
278
        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1971
278
        assert(litBufferEnd >= litPtr);
1972
278
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
1973
278
        if (op != NULL) {
1974
278
            ZSTD_memmove(op, litPtr, lastLLSize);
1975
278
            op += lastLLSize;
1976
278
        }
1977
278
        litPtr = dctx->litExtraBuffer;
1978
278
        litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
1979
278
    }
1980
110k
    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
1981
110k
        assert(litBufferEnd >= litPtr);
1982
110k
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1983
110k
        if (op != NULL) {
1984
110k
            ZSTD_memmove(op, litPtr, lastLLSize);
1985
110k
            op += lastLLSize;
1986
110k
        }
1987
110k
    }
1988
1989
0
    return (size_t)(op - ostart);
1990
110k
}
1991
1992
static size_t
1993
ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
1994
                                 void* dst, size_t maxDstSize,
1995
                           const void* seqStart, size_t seqSize, int nbSeq,
1996
                           const ZSTD_longOffset_e isLongOffset)
1997
0
{
1998
0
    return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
1999
0
}
2000
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
2001
2002
2003
2004
#if DYNAMIC_BMI2
2005
2006
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
2007
static BMI2_TARGET_ATTRIBUTE size_t
2008
DONT_VECTORIZE
2009
ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
2010
                                 void* dst, size_t maxDstSize,
2011
                           const void* seqStart, size_t seqSize, int nbSeq,
2012
                           const ZSTD_longOffset_e isLongOffset)
2013
4.30M
{
2014
4.30M
    return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2015
4.30M
}
2016
static BMI2_TARGET_ATTRIBUTE size_t
2017
DONT_VECTORIZE
2018
ZSTD_decompressSequencesSplitLitBuffer_bmi2(ZSTD_DCtx* dctx,
2019
                                 void* dst, size_t maxDstSize,
2020
                           const void* seqStart, size_t seqSize, int nbSeq,
2021
                           const ZSTD_longOffset_e isLongOffset)
2022
16.7k
{
2023
16.7k
    return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2024
16.7k
}
2025
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
2026
2027
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
2028
static BMI2_TARGET_ATTRIBUTE size_t
2029
ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
2030
                                 void* dst, size_t maxDstSize,
2031
                           const void* seqStart, size_t seqSize, int nbSeq,
2032
                           const ZSTD_longOffset_e isLongOffset)
2033
130k
{
2034
130k
    return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2035
130k
}
2036
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
2037
2038
#endif /* DYNAMIC_BMI2 */
2039
2040
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
2041
static size_t
2042
ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
2043
                   const void* seqStart, size_t seqSize, int nbSeq,
2044
                   const ZSTD_longOffset_e isLongOffset)
2045
4.30M
{
2046
4.30M
    DEBUGLOG(5, "ZSTD_decompressSequences");
2047
4.30M
#if DYNAMIC_BMI2
2048
4.30M
    if (ZSTD_DCtx_get_bmi2(dctx)) {
2049
4.30M
        return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2050
4.30M
    }
2051
0
#endif
2052
0
    return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2053
4.30M
}
2054
static size_t
2055
ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
2056
                                 const void* seqStart, size_t seqSize, int nbSeq,
2057
                                 const ZSTD_longOffset_e isLongOffset)
2058
16.7k
{
2059
16.7k
    DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer");
2060
16.7k
#if DYNAMIC_BMI2
2061
16.7k
    if (ZSTD_DCtx_get_bmi2(dctx)) {
2062
16.7k
        return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2063
16.7k
    }
2064
0
#endif
2065
0
    return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2066
16.7k
}
2067
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
2068
2069
2070
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
2071
/* ZSTD_decompressSequencesLong() :
2072
 * decompression function triggered when a minimum share of offsets is considered "long",
2073
 * aka out of cache.
2074
 * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
2075
 * This function will try to mitigate main memory latency through the use of prefetching */
2076
static size_t
2077
ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
2078
                             void* dst, size_t maxDstSize,
2079
                             const void* seqStart, size_t seqSize, int nbSeq,
2080
                             const ZSTD_longOffset_e isLongOffset)
2081
130k
{
2082
130k
    DEBUGLOG(5, "ZSTD_decompressSequencesLong");
2083
130k
#if DYNAMIC_BMI2
2084
130k
    if (ZSTD_DCtx_get_bmi2(dctx)) {
2085
130k
        return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2086
130k
    }
2087
0
#endif
2088
0
  return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
2089
130k
}
2090
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
2091
2092
2093
/**
2094
 * @returns The total size of the history referenceable by zstd, including
2095
 * both the prefix and the extDict. At @p op any offset larger than this
2096
 * is invalid.
2097
 */
2098
static size_t ZSTD_totalHistorySize(void* curPtr, const void* virtualStart)
2099
4.45M
{
2100
4.45M
    return (size_t)((char*)curPtr - (const char*)virtualStart);
2101
4.45M
}
2102
2103
typedef struct {
2104
    unsigned longOffsetShare;
2105
    unsigned maxNbAdditionalBits;
2106
} ZSTD_OffsetInfo;
2107
2108
/* ZSTD_getOffsetInfo() :
2109
 * condition : offTable must be valid
2110
 * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
2111
 *           compared to maximum possible of (1<<OffFSELog),
2112
 *           as well as the maximum number additional bits required.
2113
 */
2114
static ZSTD_OffsetInfo
2115
ZSTD_getOffsetInfo(const ZSTD_seqSymbol* offTable, int nbSeq)
2116
20.9k
{
2117
20.9k
    ZSTD_OffsetInfo info = {0, 0};
2118
    /* If nbSeq == 0, then the offTable is uninitialized, but we have
2119
     * no sequences, so both values should be 0.
2120
     */
2121
20.9k
    if (nbSeq != 0) {
2122
20.9k
        const void* ptr = offTable;
2123
20.9k
        U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
2124
20.9k
        const ZSTD_seqSymbol* table = offTable + 1;
2125
20.9k
        U32 const max = 1 << tableLog;
2126
20.9k
        U32 u;
2127
20.9k
        DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
2128
2129
20.9k
        assert(max <= (1 << OffFSELog));  /* max not too large */
2130
694k
        for (u=0; u<max; u++) {
2131
673k
            info.maxNbAdditionalBits = MAX(info.maxNbAdditionalBits, table[u].nbAdditionalBits);
2132
673k
            if (table[u].nbAdditionalBits > 22) info.longOffsetShare += 1;
2133
673k
        }
2134
2135
20.9k
        assert(tableLog <= OffFSELog);
2136
20.9k
        info.longOffsetShare <<= (OffFSELog - tableLog);  /* scale to OffFSELog */
2137
20.9k
    }
2138
2139
20.9k
    return info;
2140
20.9k
}
2141
2142
/**
2143
 * @returns The maximum offset we can decode in one read of our bitstream, without
2144
 * reloading more bits in the middle of the offset bits read. Any offsets larger
2145
 * than this must use the long offset decoder.
2146
 */
2147
static size_t ZSTD_maxShortOffset(void)
2148
0
{
2149
0
    if (MEM_64bits()) {
2150
        /* We can decode any offset without reloading bits.
2151
         * This might change if the max window size grows.
2152
         */
2153
0
        ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
2154
0
        return (size_t)-1;
2155
0
    } else {
2156
        /* The maximum offBase is (1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1.
2157
         * This offBase would require STREAM_ACCUMULATOR_MIN extra bits.
2158
         * Then we have to subtract ZSTD_REP_NUM to get the maximum possible offset.
2159
         */
2160
0
        size_t const maxOffbase = ((size_t)1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1;
2161
0
        size_t const maxOffset = maxOffbase - ZSTD_REP_NUM;
2162
0
        assert(ZSTD_highbit32((U32)maxOffbase) == STREAM_ACCUMULATOR_MIN);
2163
0
        return maxOffset;
2164
0
    }
2165
0
}
2166
2167
size_t
2168
ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
2169
                              void* dst, size_t dstCapacity,
2170
                        const void* src, size_t srcSize, const streaming_operation streaming)
2171
4.47M
{   /* blockType == blockCompressed */
2172
4.47M
    const BYTE* ip = (const BYTE*)src;
2173
4.47M
    DEBUGLOG(5, "ZSTD_decompressBlock_internal (cSize : %u)", (unsigned)srcSize);
2174
2175
    /* Note : the wording of the specification
2176
     * allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx).
2177
     * This generally does not happen, as it makes little sense,
2178
     * since an uncompressed block would feature same size and have no decompression cost.
2179
     * Also, note that decoder from reference libzstd before < v1.5.4
2180
     * would consider this edge case as an error.
2181
     * As a consequence, avoid generating compressed blocks of size ZSTD_blockSizeMax(dctx)
2182
     * for broader compatibility with the deployed ecosystem of zstd decoders */
2183
4.47M
    RETURN_ERROR_IF(srcSize > ZSTD_blockSizeMax(dctx), srcSize_wrong, "");
2184
2185
    /* Decode literals section */
2186
4.47M
    {   size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming);
2187
4.47M
        DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : cSize=%u, nbLiterals=%zu", (U32)litCSize, dctx->litSize);
2188
4.47M
        if (ZSTD_isError(litCSize)) return litCSize;
2189
4.45M
        ip += litCSize;
2190
4.45M
        srcSize -= litCSize;
2191
4.45M
    }
2192
2193
    /* Build Decoding Tables */
2194
0
    {
2195
        /* Compute the maximum block size, which must also work when !frame and fParams are unset.
2196
         * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t.
2197
         */
2198
4.45M
        size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx));
2199
4.45M
        size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd(dst, (ptrdiff_t)blockSizeMax), (BYTE const*)dctx->virtualStart);
2200
        /* isLongOffset must be true if there are long offsets.
2201
         * Offsets are long if they are larger than ZSTD_maxShortOffset().
2202
         * We don't expect that to be the case in 64-bit mode.
2203
         *
2204
         * We check here to see if our history is large enough to allow long offsets.
2205
         * If it isn't, then we can't possible have (valid) long offsets. If the offset
2206
         * is invalid, then it is okay to read it incorrectly.
2207
         *
2208
         * If isLongOffsets is true, then we will later check our decoding table to see
2209
         * if it is even possible to generate long offsets.
2210
         */
2211
4.45M
        ZSTD_longOffset_e isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (totalHistorySize > ZSTD_maxShortOffset()));
2212
        /* These macros control at build-time which decompressor implementation
2213
         * we use. If neither is defined, we do some inspection and dispatch at
2214
         * runtime.
2215
         */
2216
4.45M
#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
2217
4.45M
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
2218
4.45M
        int usePrefetchDecoder = dctx->ddictIsCold;
2219
#else
2220
        /* Set to 1 to avoid computing offset info if we don't need to.
2221
         * Otherwise this value is ignored.
2222
         */
2223
        int usePrefetchDecoder = 1;
2224
#endif
2225
4.45M
        int nbSeq;
2226
4.45M
        size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
2227
4.45M
        if (ZSTD_isError(seqHSize)) return seqHSize;
2228
4.45M
        ip += seqHSize;
2229
4.45M
        srcSize -= seqHSize;
2230
2231
4.45M
        RETURN_ERROR_IF((dst == NULL || dstCapacity == 0) && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
2232
4.45M
        RETURN_ERROR_IF(MEM_64bits() && sizeof(size_t) == sizeof(void*) && (size_t)(-1) - (size_t)dst < (size_t)(1 << 20), dstSize_tooSmall,
2233
4.45M
                "invalid dst");
2234
2235
        /* If we could potentially have long offsets, or we might want to use the prefetch decoder,
2236
         * compute information about the share of long offsets, and the maximum nbAdditionalBits.
2237
         * NOTE: could probably use a larger nbSeq limit
2238
         */
2239
4.45M
        if (isLongOffset || (!usePrefetchDecoder && (totalHistorySize > (1u << 24)) && (nbSeq > 8))) {
2240
20.9k
            ZSTD_OffsetInfo const info = ZSTD_getOffsetInfo(dctx->OFTptr, nbSeq);
2241
20.9k
            if (isLongOffset && info.maxNbAdditionalBits <= STREAM_ACCUMULATOR_MIN) {
2242
                /* If isLongOffset, but the maximum number of additional bits that we see in our table is small
2243
                 * enough, then we know it is impossible to have too long an offset in this block, so we can
2244
                 * use the regular offset decoder.
2245
                 */
2246
0
                isLongOffset = ZSTD_lo_isRegularOffset;
2247
0
            }
2248
20.9k
            if (!usePrefetchDecoder) {
2249
20.9k
                U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
2250
20.9k
                usePrefetchDecoder = (info.longOffsetShare >= minShare);
2251
20.9k
            }
2252
20.9k
        }
2253
2254
4.45M
        dctx->ddictIsCold = 0;
2255
2256
4.45M
#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
2257
4.45M
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
2258
4.45M
        if (usePrefetchDecoder) {
2259
#else
2260
        (void)usePrefetchDecoder;
2261
        {
2262
#endif
2263
130k
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
2264
130k
            return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
2265
130k
#endif
2266
130k
        }
2267
2268
4.32M
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
2269
        /* else */
2270
4.32M
        if (dctx->litBufferLocation == ZSTD_split)
2271
16.7k
            return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
2272
4.30M
        else
2273
4.30M
            return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
2274
4.32M
#endif
2275
4.32M
    }
2276
4.32M
}
2277
2278
2279
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
2280
void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
2281
59.2M
{
2282
59.2M
    if (dst != dctx->previousDstEnd && dstSize > 0) {   /* not contiguous */
2283
1.06M
        dctx->dictEnd = dctx->previousDstEnd;
2284
1.06M
        dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
2285
1.06M
        dctx->prefixStart = dst;
2286
1.06M
        dctx->previousDstEnd = dst;
2287
1.06M
    }
2288
59.2M
}
2289
2290
2291
size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx,
2292
                                       void* dst, size_t dstCapacity,
2293
                                 const void* src, size_t srcSize)
2294
13.4k
{
2295
13.4k
    size_t dSize;
2296
13.4k
    dctx->isFrameDecompression = 0;
2297
13.4k
    ZSTD_checkContinuity(dctx, dst, dstCapacity);
2298
13.4k
    dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, not_streaming);
2299
13.4k
    FORWARD_IF_ERROR(dSize, "");
2300
9.97k
    dctx->previousDstEnd = (char*)dst + dSize;
2301
9.97k
    return dSize;
2302
13.4k
}
2303
2304
2305
/* NOTE: Must just wrap ZSTD_decompressBlock_deprecated() */
2306
size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
2307
                            void* dst, size_t dstCapacity,
2308
                      const void* src, size_t srcSize)
2309
13.4k
{
2310
13.4k
    return ZSTD_decompressBlock_deprecated(dctx, dst, dstCapacity, src, srcSize);
2311
13.4k
}