Coverage Report

Created: 2026-10-28 07:26

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