Coverage Report

Created: 2025-07-23 08:18

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