1 /*
2  * Copyright (c) Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  * You may select, at your option, one of the above-listed licenses.
9  */
10 
11 /* zstd_decompress_block :
12  * this module takes care of decompressing _compressed_ block */
13 
14 /*-*******************************************************
15 *  Dependencies
16 *********************************************************/
17 #include "../common/zstd_deps.h"   /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
18 #include "../common/compiler.h"    /* prefetch */
19 #include "../common/cpu.h"         /* bmi2 */
20 #include "../common/mem.h"         /* low level memory routines */
21 #define FSE_STATIC_LINKING_ONLY
22 #include "../common/fse.h"
23 #define HUF_STATIC_LINKING_ONLY
24 #include "../common/huf.h"
25 #include "../common/zstd_internal.h"
26 #include "zstd_decompress_internal.h"   /* ZSTD_DCtx */
27 #include "zstd_ddict.h"  /* ZSTD_DDictDictContent */
28 #include "zstd_decompress_block.h"
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 static void ZSTD_copy4(void* dst, const void* src) { ZSTD_memcpy(dst, src, 4); }
48 
49 
50 /*-*************************************************************
51  *   Block decoding
52  ***************************************************************/
53 
54 /*! ZSTD_getcBlockSize() :
55  *  Provides the size of compressed block from block header `src` */
56 size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
57                           blockProperties_t* bpPtr)
58 {
59     RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, "");
60 
61     {   U32 const cBlockHeader = MEM_readLE24(src);
62         U32 const cSize = cBlockHeader >> 3;
63         bpPtr->lastBlock = cBlockHeader & 1;
64         bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
65         bpPtr->origSize = cSize;   /* only useful for RLE */
66         if (bpPtr->blockType == bt_rle) return 1;
67         RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, "");
68         return cSize;
69     }
70 }
71 
72 
73 /* Hidden declaration for fullbench */
74 size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
75                           const void* src, size_t srcSize);
76 /*! ZSTD_decodeLiteralsBlock() :
77  * @return : nb of bytes read from src (< srcSize )
78  *  note : symbol not declared but exposed for fullbench */
79 size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
80                           const void* src, size_t srcSize)   /* note : srcSize < BLOCKSIZE */
81 {
82     DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");
83     RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");
84 
85     {   const BYTE* const istart = (const BYTE*) src;
86         symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);
87 
88         switch(litEncType)
89         {
90         case set_repeat:
91             DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");
92             RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");
93             /* fall-through */
ZSTD_DDictHashSet_getIndex(const ZSTD_DDictHashSet * hashSet,U32 dictID)94 
95         case set_compressed:
96             RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3");
97             {   size_t lhSize, litSize, litCSize;
98                 U32 singleStream=0;
99                 U32 const lhlCode = (istart[0] >> 2) & 3;
100                 U32 const lhc = MEM_readLE32(istart);
101                 size_t hufSuccess;
102                 switch(lhlCode)
103                 {
ZSTD_DDictHashSet_emplaceDDict(ZSTD_DDictHashSet * hashSet,const ZSTD_DDict * ddict)104                 case 0: case 1: default:   /* note : default is impossible, since lhlCode into [0..3] */
105                     /* 2 - 2 - 10 - 10 */
106                     singleStream = !lhlCode;
107                     lhSize = 3;
108                     litSize  = (lhc >> 4) & 0x3FF;
109                     litCSize = (lhc >> 14) & 0x3FF;
110                     break;
111                 case 2:
112                     /* 2 - 2 - 14 - 14 */
113                     lhSize = 4;
114                     litSize  = (lhc >> 4) & 0x3FFF;
115                     litCSize = lhc >> 18;
116                     break;
117                 case 3:
118                     /* 2 - 2 - 18 - 18 */
119                     lhSize = 5;
120                     litSize  = (lhc >> 4) & 0x3FFFF;
121                     litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);
122                     break;
123                 }
124                 RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, "");
125                 RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");
126 
127                 /* prefetch huffman table if cold */
128                 if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
129                     PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
ZSTD_DDictHashSet_expand(ZSTD_DDictHashSet * hashSet,ZSTD_customMem customMem)130                 }
131 
132                 if (litEncType==set_repeat) {
133                     if (singleStream) {
134                         hufSuccess = HUF_decompress1X_usingDTable_bmi2(
135                             dctx->litBuffer, litSize, istart+lhSize, litCSize,
136                             dctx->HUFptr, dctx->bmi2);
137                     } else {
138                         hufSuccess = HUF_decompress4X_usingDTable_bmi2(
139                             dctx->litBuffer, litSize, istart+lhSize, litCSize,
140                             dctx->HUFptr, dctx->bmi2);
141                     }
142                 } else {
143                     if (singleStream) {
144 #if defined(HUF_FORCE_DECOMPRESS_X2)
145                         hufSuccess = HUF_decompress1X_DCtx_wksp(
146                             dctx->entropy.hufTable, dctx->litBuffer, litSize,
147                             istart+lhSize, litCSize, dctx->workspace,
148                             sizeof(dctx->workspace));
149 #else
150                         hufSuccess = HUF_decompress1X1_DCtx_wksp_bmi2(
151                             dctx->entropy.hufTable, dctx->litBuffer, litSize,
152                             istart+lhSize, litCSize, dctx->workspace,
153                             sizeof(dctx->workspace), dctx->bmi2);
154 #endif
ZSTD_DDictHashSet_getDDict(ZSTD_DDictHashSet * hashSet,U32 dictID)155                     } else {
156                         hufSuccess = HUF_decompress4X_hufOnly_wksp_bmi2(
157                             dctx->entropy.hufTable, dctx->litBuffer, litSize,
158                             istart+lhSize, litCSize, dctx->workspace,
159                             sizeof(dctx->workspace), dctx->bmi2);
160                     }
161                 }
162 
163                 RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");
164 
165                 dctx->litPtr = dctx->litBuffer;
166                 dctx->litSize = litSize;
167                 dctx->litEntropy = 1;
168                 if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
169                 ZSTD_memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
170                 return litCSize + lhSize;
171             }
172 
173         case set_basic:
174             {   size_t litSize, lhSize;
175                 U32 const lhlCode = ((istart[0]) >> 2) & 3;
176                 switch(lhlCode)
ZSTD_createDDictHashSet(ZSTD_customMem customMem)177                 {
178                 case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
179                     lhSize = 1;
180                     litSize = istart[0] >> 3;
181                     break;
182                 case 1:
183                     lhSize = 2;
184                     litSize = MEM_readLE16(istart) >> 4;
185                     break;
186                 case 3:
187                     lhSize = 3;
188                     litSize = MEM_readLE24(istart) >> 4;
189                     break;
190                 }
191 
ZSTD_freeDDictHashSet(ZSTD_DDictHashSet * hashSet,ZSTD_customMem customMem)192                 if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) {  /* risk reading beyond src buffer with wildcopy */
193                     RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");
194                     ZSTD_memcpy(dctx->litBuffer, istart+lhSize, litSize);
195                     dctx->litPtr = dctx->litBuffer;
196                     dctx->litSize = litSize;
197                     ZSTD_memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
198                     return lhSize+litSize;
199                 }
200                 /* direct reference into compressed stream */
201                 dctx->litPtr = istart+lhSize;
202                 dctx->litSize = litSize;
203                 return lhSize+litSize;
204             }
ZSTD_DDictHashSet_addDDict(ZSTD_DDictHashSet * hashSet,const ZSTD_DDict * ddict,ZSTD_customMem customMem)205 
206         case set_rle:
207             {   U32 const lhlCode = ((istart[0]) >> 2) & 3;
208                 size_t litSize, lhSize;
209                 switch(lhlCode)
210                 {
211                 case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
212                     lhSize = 1;
213                     litSize = istart[0] >> 3;
214                     break;
215                 case 1:
216                     lhSize = 2;
217                     litSize = MEM_readLE16(istart) >> 4;
218                     break;
219                 case 3:
220                     lhSize = 3;
221                     litSize = MEM_readLE24(istart) >> 4;
222                     RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4");
223                     break;
224                 }
225                 RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, "");
226                 ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
227                 dctx->litPtr = dctx->litBuffer;
228                 dctx->litSize = litSize;
229                 return lhSize+1;
230             }
231         default:
232             RETURN_ERROR(corruption_detected, "impossible");
233         }
234     }
235 }
ZSTD_DCtx_resetParameters(ZSTD_DCtx * dctx)236 
237 /* Default FSE distribution tables.
238  * These are pre-calculated FSE decoding tables using default distributions as defined in specification :
239  * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#default-distributions
240  * They were generated programmatically with following method :
241  * - start from default distributions, present in /lib/common/zstd_internal.h
242  * - generate tables normally, using ZSTD_buildFSETable()
243  * - printout the content of tables
244  * - pretify output, report below, test with fuzzer to ensure it's correct */
245 
246 /* Default FSE distribution table for Literal Lengths */
247 static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
248      {  1,  1,  1, LL_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
249      /* nextState, nbAddBits, nbBits, baseVal */
250      {  0,  0,  4,    0},  { 16,  0,  4,    0},
251      { 32,  0,  5,    1},  {  0,  0,  5,    3},
252      {  0,  0,  5,    4},  {  0,  0,  5,    6},
253      {  0,  0,  5,    7},  {  0,  0,  5,    9},
254      {  0,  0,  5,   10},  {  0,  0,  5,   12},
255      {  0,  0,  6,   14},  {  0,  1,  5,   16},
256      {  0,  1,  5,   20},  {  0,  1,  5,   22},
257      {  0,  2,  5,   28},  {  0,  3,  5,   32},
258      {  0,  4,  5,   48},  { 32,  6,  5,   64},
259      {  0,  7,  5,  128},  {  0,  8,  6,  256},
260      {  0, 10,  6, 1024},  {  0, 12,  6, 4096},
261      { 32,  0,  4,    0},  {  0,  0,  4,    1},
262      {  0,  0,  5,    2},  { 32,  0,  5,    4},
263      {  0,  0,  5,    5},  { 32,  0,  5,    7},
264      {  0,  0,  5,    8},  { 32,  0,  5,   10},
265      {  0,  0,  5,   11},  {  0,  0,  6,   13},
266      { 32,  1,  5,   16},  {  0,  1,  5,   18},
267      { 32,  1,  5,   22},  {  0,  2,  5,   24},
268      { 32,  3,  5,   32},  {  0,  3,  5,   40},
269      {  0,  6,  4,   64},  { 16,  6,  4,   64},
270      { 32,  7,  5,  128},  {  0,  9,  6,  512},
271      {  0, 11,  6, 2048},  { 48,  0,  4,    0},
272      { 16,  0,  4,    1},  { 32,  0,  5,    2},
273      { 32,  0,  5,    3},  { 32,  0,  5,    5},
274      { 32,  0,  5,    6},  { 32,  0,  5,    8},
275      { 32,  0,  5,    9},  { 32,  0,  5,   11},
276      { 32,  0,  5,   12},  {  0,  0,  6,   15},
277      { 32,  1,  5,   18},  { 32,  1,  5,   20},
278      { 32,  2,  5,   24},  { 32,  2,  5,   28},
279      { 32,  3,  5,   40},  { 32,  4,  5,   48},
280      {  0, 16,  6,65536},  {  0, 15,  6,32768},
281      {  0, 14,  6,16384},  {  0, 13,  6, 8192},
282 };   /* LL_defaultDTable */
ZSTD_createDCtx_advanced(ZSTD_customMem customMem)283 
284 /* Default FSE distribution table for Offset Codes */
285 static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
286     {  1,  1,  1, OF_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
287     /* nextState, nbAddBits, nbBits, baseVal */
288     {  0,  0,  5,    0},     {  0,  6,  4,   61},
289     {  0,  9,  5,  509},     {  0, 15,  5,32765},
290     {  0, 21,  5,2097149},   {  0,  3,  5,    5},
291     {  0,  7,  4,  125},     {  0, 12,  5, 4093},
292     {  0, 18,  5,262141},    {  0, 23,  5,8388605},
293     {  0,  5,  5,   29},     {  0,  8,  4,  253},
294     {  0, 14,  5,16381},     {  0, 20,  5,1048573},
295     {  0,  2,  5,    1},     { 16,  7,  4,  125},
296     {  0, 11,  5, 2045},     {  0, 17,  5,131069},
297     {  0, 22,  5,4194301},   {  0,  4,  5,   13},
298     { 16,  8,  4,  253},     {  0, 13,  5, 8189},
299     {  0, 19,  5,524285},    {  0,  1,  5,    1},
300     { 16,  6,  4,   61},     {  0, 10,  5, 1021},
301     {  0, 16,  5,65533},     {  0, 28,  5,268435453},
302     {  0, 27,  5,134217725}, {  0, 26,  5,67108861},
303     {  0, 25,  5,33554429},  {  0, 24,  5,16777213},
304 };   /* OF_defaultDTable */
305 
306 
307 /* Default FSE distribution table for Match Lengths */
308 static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
ZSTD_freeDCtx(ZSTD_DCtx * dctx)309     {  1,  1,  1, ML_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
310     /* nextState, nbAddBits, nbBits, baseVal */
311     {  0,  0,  6,    3},  {  0,  0,  4,    4},
312     { 32,  0,  5,    5},  {  0,  0,  5,    6},
313     {  0,  0,  5,    8},  {  0,  0,  5,    9},
314     {  0,  0,  5,   11},  {  0,  0,  6,   13},
315     {  0,  0,  6,   16},  {  0,  0,  6,   19},
316     {  0,  0,  6,   22},  {  0,  0,  6,   25},
317     {  0,  0,  6,   28},  {  0,  0,  6,   31},
318     {  0,  0,  6,   34},  {  0,  1,  6,   37},
319     {  0,  1,  6,   41},  {  0,  2,  6,   47},
320     {  0,  3,  6,   59},  {  0,  4,  6,   83},
321     {  0,  7,  6,  131},  {  0,  9,  6,  515},
322     { 16,  0,  4,    4},  {  0,  0,  4,    5},
323     { 32,  0,  5,    6},  {  0,  0,  5,    7},
324     { 32,  0,  5,    9},  {  0,  0,  5,   10},
325     {  0,  0,  6,   12},  {  0,  0,  6,   15},
326     {  0,  0,  6,   18},  {  0,  0,  6,   21},
327     {  0,  0,  6,   24},  {  0,  0,  6,   27},
328     {  0,  0,  6,   30},  {  0,  0,  6,   33},
329     {  0,  1,  6,   35},  {  0,  1,  6,   39},
330     {  0,  2,  6,   43},  {  0,  3,  6,   51},
ZSTD_copyDCtx(ZSTD_DCtx * dstDCtx,const ZSTD_DCtx * srcDCtx)331     {  0,  4,  6,   67},  {  0,  5,  6,   99},
332     {  0,  8,  6,  259},  { 32,  0,  4,    4},
333     { 48,  0,  4,    4},  { 16,  0,  4,    5},
334     { 32,  0,  5,    7},  { 32,  0,  5,    8},
335     { 32,  0,  5,   10},  { 32,  0,  5,   11},
336     {  0,  0,  6,   14},  {  0,  0,  6,   17},
337     {  0,  0,  6,   20},  {  0,  0,  6,   23},
338     {  0,  0,  6,   26},  {  0,  0,  6,   29},
339     {  0,  0,  6,   32},  {  0, 16,  6,65539},
340     {  0, 15,  6,32771},  {  0, 14,  6,16387},
341     {  0, 13,  6, 8195},  {  0, 12,  6, 4099},
342     {  0, 11,  6, 2051},  {  0, 10,  6, 1027},
343 };   /* ML_defaultDTable */
344 
ZSTD_DCtx_selectFrameDDict(ZSTD_DCtx * dctx)345 
346 static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U32 nbAddBits)
347 {
348     void* ptr = dt;
349     ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
350     ZSTD_seqSymbol* const cell = dt + 1;
351 
352     DTableH->tableLog = 0;
353     DTableH->fastMode = 0;
354 
355     cell->nbBits = 0;
356     cell->nextState = 0;
357     assert(nbAddBits < 255);
358     cell->nbAdditionalBits = (BYTE)nbAddBits;
359     cell->baseValue = baseValue;
360 }
361 
362 
363 /* ZSTD_buildFSETable() :
364  * generate FSE decoding table for one symbol (ll, ml or off)
365  * cannot fail if input is valid =>
366  * all inputs are presumed validated at this stage */
367 FORCE_INLINE_TEMPLATE
368 void ZSTD_buildFSETable_body(ZSTD_seqSymbol* dt,
369             const short* normalizedCounter, unsigned maxSymbolValue,
ZSTD_isFrame(const void * buffer,size_t size)370             const U32* baseValue, const U32* nbAdditionalBits,
371             unsigned tableLog, void* wksp, size_t wkspSize)
372 {
373     ZSTD_seqSymbol* const tableDecode = dt+1;
374     U32 const maxSV1 = maxSymbolValue + 1;
375     U32 const tableSize = 1 << tableLog;
376 
377     U16* symbolNext = (U16*)wksp;
378     BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1);
379     U32 highThreshold = tableSize - 1;
380 
381 
382     /* Sanity Checks */
383     assert(maxSymbolValue <= MaxSeq);
384     assert(tableLog <= MaxFSELog);
385     assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE);
386     (void)wkspSize;
387     /* Init, lay down lowprob symbols */
388     {   ZSTD_seqSymbol_header DTableH;
389         DTableH.tableLog = tableLog;
390         DTableH.fastMode = 1;
391         {   S16 const largeLimit= (S16)(1 << (tableLog-1));
392             U32 s;
393             for (s=0; s<maxSV1; s++) {
394                 if (normalizedCounter[s]==-1) {
395                     tableDecode[highThreshold--].baseValue = s;
396                     symbolNext[s] = 1;
397                 } else {
398                     if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
399                     assert(normalizedCounter[s]>=0);
400                     symbolNext[s] = (U16)normalizedCounter[s];
401         }   }   }
402         ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
403     }
404 
405     /* Spread symbols */
406     assert(tableSize <= 512);
407     /* Specialized symbol spreading for the case when there are
408      * no low probability (-1 count) symbols. When compressing
409      * small blocks we avoid low probability symbols to hit this
410      * case, since header decoding speed matters more.
411      */
412     if (highThreshold == tableSize - 1) {
413         size_t const tableMask = tableSize-1;
414         size_t const step = FSE_TABLESTEP(tableSize);
415         /* First lay down the symbols in order.
416          * We use a uint64_t to lay down 8 bytes at a time. This reduces branch
417          * misses since small blocks generally have small table logs, so nearly
418          * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
419          * our buffer to handle the over-write.
420          */
421         {
422             U64 const add = 0x0101010101010101ull;
423             size_t pos = 0;
424             U64 sv = 0;
425             U32 s;
426             for (s=0; s<maxSV1; ++s, sv += add) {
427                 int i;
428                 int const n = normalizedCounter[s];
429                 MEM_write64(spread + pos, sv);
430                 for (i = 8; i < n; i += 8) {
431                     MEM_write64(spread + pos + i, sv);
432                 }
433                 pos += n;
434             }
435         }
436         /* Now we spread those positions across the table.
437          * The benefit of doing it in two stages is that we avoid the the
438          * variable size inner loop, which caused lots of branch misses.
439          * Now we can run through all the positions without any branch misses.
440          * We unroll the loop twice, since that is what emperically worked best.
441          */
442         {
443             size_t position = 0;
444             size_t s;
445             size_t const unroll = 2;
446             assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
447             for (s = 0; s < (size_t)tableSize; s += unroll) {
448                 size_t u;
449                 for (u = 0; u < unroll; ++u) {
450                     size_t const uPosition = (position + (u * step)) & tableMask;
451                     tableDecode[uPosition].baseValue = spread[s + u];
452                 }
453                 position = (position + (unroll * step)) & tableMask;
454             }
455             assert(position == 0);
456         }
457     } else {
458         U32 const tableMask = tableSize-1;
459         U32 const step = FSE_TABLESTEP(tableSize);
460         U32 s, position = 0;
461         for (s=0; s<maxSV1; s++) {
462             int i;
463             int const n = normalizedCounter[s];
464             for (i=0; i<n; i++) {
465                 tableDecode[position].baseValue = s;
466                 position = (position + step) & tableMask;
467                 while (position > highThreshold) position = (position + step) & tableMask;   /* lowprob area */
468         }   }
469         assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
470     }
471 
472     /* Build Decoding table */
473     {
474         U32 u;
475         for (u=0; u<tableSize; u++) {
476             U32 const symbol = tableDecode[u].baseValue;
477             U32 const nextState = symbolNext[symbol]++;
478             tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
479             tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
480             assert(nbAdditionalBits[symbol] < 255);
481             tableDecode[u].nbAdditionalBits = (BYTE)nbAdditionalBits[symbol];
482             tableDecode[u].baseValue = baseValue[symbol];
483         }
484     }
485 }
486 
487 /* Avoids the FORCE_INLINE of the _body() function. */
488 static void ZSTD_buildFSETable_body_default(ZSTD_seqSymbol* dt,
489             const short* normalizedCounter, unsigned maxSymbolValue,
490             const U32* baseValue, const U32* nbAdditionalBits,
491             unsigned tableLog, void* wksp, size_t wkspSize)
492 {
493     ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
494             baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
495 }
496 
497 #if DYNAMIC_BMI2
498 TARGET_ATTRIBUTE("bmi2") static void ZSTD_buildFSETable_body_bmi2(ZSTD_seqSymbol* dt,
499             const short* normalizedCounter, unsigned maxSymbolValue,
500             const U32* baseValue, const U32* nbAdditionalBits,
ZSTD_getFrameHeader(ZSTD_frameHeader * zfhPtr,const void * src,size_t srcSize)501             unsigned tableLog, void* wksp, size_t wkspSize)
502 {
503     ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
504             baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
505 }
506 #endif
507 
508 void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
509             const short* normalizedCounter, unsigned maxSymbolValue,
510             const U32* baseValue, const U32* nbAdditionalBits,
511             unsigned tableLog, void* wksp, size_t wkspSize, int bmi2)
ZSTD_getFrameContentSize(const void * src,size_t srcSize)512 {
513 #if DYNAMIC_BMI2
514     if (bmi2) {
515         ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue,
516                 baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
517         return;
518     }
519 #endif
520     (void)bmi2;
521     ZSTD_buildFSETable_body_default(dt, normalizedCounter, maxSymbolValue,
522             baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
523 }
524 
525 
526 /*! ZSTD_buildSeqTable() :
527  * @return : nb bytes read from src,
528  *           or an error code if it fails */
529 static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
readSkippableFrameSize(void const * src,size_t srcSize)530                                  symbolEncodingType_e type, unsigned max, U32 maxLog,
531                                  const void* src, size_t srcSize,
532                                  const U32* baseValue, const U32* nbAdditionalBits,
533                                  const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
534                                  int ddictIsCold, int nbSeq, U32* wksp, size_t wkspSize,
535                                  int bmi2)
536 {
537     switch(type)
538     {
539     case set_rle :
540         RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
541         RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
542         {   U32 const symbol = *(const BYTE*)src;
543             U32 const baseline = baseValue[symbol];
544             U32 const nbBits = nbAdditionalBits[symbol];
545             ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
546         }
547         *DTablePtr = DTableSpace;
548         return 1;
549     case set_basic :
550         *DTablePtr = defaultTable;
551         return 0;
552     case set_repeat:
553         RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
554         /* prefetch FSE table if used */
555         if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
556             const void* const pStart = *DTablePtr;
557             size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
558             PREFETCH_AREA(pStart, pSize);
559         }
560         return 0;
561     case set_compressed :
562         {   unsigned tableLog;
563             S16 norm[MaxSeq+1];
564             size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
565             RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
566             RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
567             ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2);
568             *DTablePtr = DTableSpace;
569             return headerSize;
570         }
571     default :
572         assert(0);
573         RETURN_ERROR(GENERIC, "impossible");
574     }
575 }
576 
577 size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
578                              const void* src, size_t srcSize)
579 {
580     const BYTE* const istart = (const BYTE*)src;
581     const BYTE* const iend = istart + srcSize;
582     const BYTE* ip = istart;
583     int nbSeq;
584     DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
585 
586     /* check */
587     RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");
588 
589     /* SeqHead */
590     nbSeq = *ip++;
591     if (!nbSeq) {
592         *nbSeqPtr=0;
593         RETURN_ERROR_IF(srcSize != 1, srcSize_wrong, "");
594         return 1;
595     }
596     if (nbSeq > 0x7F) {
597         if (nbSeq == 0xFF) {
598             RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
599             nbSeq = MEM_readLE16(ip) + LONGNBSEQ;
600             ip+=2;
ZSTD_getDecompressedSize(const void * src,size_t srcSize)601         } else {
602             RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
603             nbSeq = ((nbSeq-0x80)<<8) + *ip++;
604         }
605     }
606     *nbSeqPtr = nbSeq;
607 
608     /* FSE table descriptors */
609     RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
610     {   symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
611         symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
612         symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
ZSTD_decodeFrameHeader(ZSTD_DCtx * dctx,const void * src,size_t headerSize)613         ip++;
614 
615         /* Build DTables */
616         {   size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
617                                                       LLtype, MaxLL, LLFSELog,
618                                                       ip, iend-ip,
619                                                       LL_base, LL_bits,
620                                                       LL_defaultDTable, dctx->fseEntropy,
621                                                       dctx->ddictIsCold, nbSeq,
622                                                       dctx->workspace, sizeof(dctx->workspace),
623                                                       dctx->bmi2);
624             RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
625             ip += llhSize;
626         }
627 
628         {   size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
629                                                       OFtype, MaxOff, OffFSELog,
630                                                       ip, iend-ip,
631                                                       OF_base, OF_bits,
632                                                       OF_defaultDTable, dctx->fseEntropy,
633                                                       dctx->ddictIsCold, nbSeq,
634                                                       dctx->workspace, sizeof(dctx->workspace),
635                                                       dctx->bmi2);
636             RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
ZSTD_errorFrameSizeInfo(size_t ret)637             ip += ofhSize;
638         }
639 
640         {   size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
641                                                       MLtype, MaxML, MLFSELog,
642                                                       ip, iend-ip,
643                                                       ML_base, ML_bits,
644                                                       ML_defaultDTable, dctx->fseEntropy,
ZSTD_findFrameSizeInfo(const void * src,size_t srcSize)645                                                       dctx->ddictIsCold, nbSeq,
646                                                       dctx->workspace, sizeof(dctx->workspace),
647                                                       dctx->bmi2);
648             RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");
649             ip += mlhSize;
650         }
651     }
652 
653     return ip-istart;
654 }
655 
656 
657 typedef struct {
658     size_t litLength;
659     size_t matchLength;
660     size_t offset;
661 } seq_t;
662 
663 typedef struct {
664     size_t state;
665     const ZSTD_seqSymbol* table;
666 } ZSTD_fseState;
667 
668 typedef struct {
669     BIT_DStream_t DStream;
670     ZSTD_fseState stateLL;
671     ZSTD_fseState stateOffb;
672     ZSTD_fseState stateML;
673     size_t prevOffset[ZSTD_REP_NUM];
674 } seqState_t;
675 
676 /*! ZSTD_overlapCopy8() :
677  *  Copies 8 bytes from ip to op and updates op and ip where ip <= op.
678  *  If the offset is < 8 then the offset is spread to at least 8 bytes.
679  *
680  *  Precondition: *ip <= *op
681  *  Postcondition: *op - *op >= 8
682  */
683 HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) {
684     assert(*ip <= *op);
685     if (offset < 8) {
686         /* close range match, overlap */
687         static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 };   /* added */
688         static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 };   /* subtracted */
689         int const sub2 = dec64table[offset];
690         (*op)[0] = (*ip)[0];
691         (*op)[1] = (*ip)[1];
692         (*op)[2] = (*ip)[2];
693         (*op)[3] = (*ip)[3];
694         *ip += dec32table[offset];
695         ZSTD_copy4(*op+4, *ip);
696         *ip -= sub2;
697     } else {
698         ZSTD_copy8(*op, *ip);
699     }
700     *ip += 8;
701     *op += 8;
702     assert(*op - *ip >= 8);
703 }
704 
705 /*! ZSTD_safecopy() :
706  *  Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer
707  *  and write up to 16 bytes past oend_w (op >= oend_w is allowed).
708  *  This function is only called in the uncommon case where the sequence is near the end of the block. It
709  *  should be fast for a single long sequence, but can be slow for several short sequences.
710  *
711  *  @param ovtype controls the overlap detection
712  *         - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
713  *         - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
714  *           The src buffer must be before the dst buffer.
715  */
ZSTD_findFrameCompressedSize(const void * src,size_t srcSize)716 static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {
717     ptrdiff_t const diff = op - ip;
718     BYTE* const oend = op + length;
719 
720     assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
721            (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
722 
723     if (length < 8) {
724         /* Handle short lengths. */
725         while (op < oend) *op++ = *ip++;
726         return;
727     }
728     if (ovtype == ZSTD_overlap_src_before_dst) {
729         /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
730         assert(length >= 8);
731         ZSTD_overlapCopy8(&op, &ip, diff);
732         assert(op - ip >= 8);
733         assert(op <= oend);
734     }
735 
736     if (oend <= oend_w) {
737         /* No risk of overwrite. */
738         ZSTD_wildcopy(op, ip, length, ovtype);
739         return;
740     }
741     if (op <= oend_w) {
742         /* Wildcopy until we get close to the end. */
743         assert(oend > oend_w);
744         ZSTD_wildcopy(op, ip, oend_w - op, ovtype);
745         ip += oend_w - op;
746         op = oend_w;
747     }
748     /* Handle the leftovers. */
749     while (op < oend) *op++ = *ip++;
750 }
751 
752 /* ZSTD_execSequenceEnd():
ZSTD_insertBlock(ZSTD_DCtx * dctx,const void * blockStart,size_t blockSize)753  * This version handles cases that are near the end of the output buffer. It requires
754  * more careful checks to make sure there is no overflow. By separating out these hard
755  * and unlikely cases, we can speed up the common cases.
756  *
757  * NOTE: This function needs to be fast for a single long sequence, but doesn't need
758  * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
759  */
760 FORCE_NOINLINE
761 size_t ZSTD_execSequenceEnd(BYTE* op,
762                             BYTE* const oend, seq_t sequence,
763                             const BYTE** litPtr, const BYTE* const litLimit,
764                             const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
765 {
766     BYTE* const oLitEnd = op + sequence.litLength;
767     size_t const sequenceLength = sequence.litLength + sequence.matchLength;
768     const BYTE* const iLitEnd = *litPtr + sequence.litLength;
769     const BYTE* match = oLitEnd - sequence.offset;
770     BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
771 
772     /* bounds checks : careful of address space overflow in 32-bit mode */
773     RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
774     RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
775     assert(op < op + sequenceLength);
776     assert(oLitEnd < op + sequenceLength);
777 
778     /* copy literals */
779     ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
780     op = oLitEnd;
781     *litPtr = iLitEnd;
782 
783     /* copy Match */
784     if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
785         /* offset beyond prefix */
786         RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
787         match = dictEnd - (prefixStart-match);
788         if (match + sequence.matchLength <= dictEnd) {
789             ZSTD_memmove(oLitEnd, match, sequence.matchLength);
790             return sequenceLength;
791         }
792         /* span extDict & currentPrefixSegment */
793         {   size_t const length1 = dictEnd - match;
794             ZSTD_memmove(oLitEnd, match, length1);
795             op = oLitEnd + length1;
796             sequence.matchLength -= length1;
797             match = prefixStart;
798     }   }
799     ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
800     return sequenceLength;
801 }
802 
803 HINT_INLINE
804 size_t ZSTD_execSequence(BYTE* op,
805                          BYTE* const oend, seq_t sequence,
806                          const BYTE** litPtr, const BYTE* const litLimit,
807                          const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
808 {
809     BYTE* const oLitEnd = op + sequence.litLength;
810     size_t const sequenceLength = sequence.litLength + sequence.matchLength;
811     BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
812     BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;   /* risk : address space underflow on oend=NULL */
813     const BYTE* const iLitEnd = *litPtr + sequence.litLength;
814     const BYTE* match = oLitEnd - sequence.offset;
815 
816     assert(op != NULL /* Precondition */);
817     assert(oend_w < oend /* No underflow */);
818     /* Handle edge cases in a slow path:
ZSTD_decompressFrame(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void ** srcPtr,size_t * srcSizePtr)819      *   - Read beyond end of literals
820      *   - Match end is within WILDCOPY_OVERLIMIT of oend
821      *   - 32-bit mode and the match length overflows
822      */
823     if (UNLIKELY(
824             iLitEnd > litLimit ||
825             oMatchEnd > oend_w ||
826             (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
827         return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
828 
829     /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
830     assert(op <= oLitEnd /* No overflow */);
831     assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
832     assert(oMatchEnd <= oend /* No underflow */);
833     assert(iLitEnd <= litLimit /* Literal length is in bounds */);
834     assert(oLitEnd <= oend_w /* Can wildcopy literals */);
835     assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
836 
837     /* Copy Literals:
838      * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
839      * We likely don't need the full 32-byte wildcopy.
840      */
841     assert(WILDCOPY_OVERLENGTH >= 16);
842     ZSTD_copy16(op, (*litPtr));
843     if (UNLIKELY(sequence.litLength > 16)) {
844         ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
845     }
846     op = oLitEnd;
847     *litPtr = iLitEnd;   /* update for next sequence */
848 
849     /* Copy Match */
850     if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
851         /* offset beyond prefix -> go into extDict */
852         RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
853         match = dictEnd + (match - prefixStart);
854         if (match + sequence.matchLength <= dictEnd) {
855             ZSTD_memmove(oLitEnd, match, sequence.matchLength);
856             return sequenceLength;
857         }
858         /* span extDict & currentPrefixSegment */
859         {   size_t const length1 = dictEnd - match;
860             ZSTD_memmove(oLitEnd, match, length1);
861             op = oLitEnd + length1;
862             sequence.matchLength -= length1;
863             match = prefixStart;
864     }   }
865     /* Match within prefix of 1 or more bytes */
866     assert(op <= oMatchEnd);
867     assert(oMatchEnd <= oend_w);
868     assert(match >= prefixStart);
869     assert(sequence.matchLength >= 1);
870 
871     /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
872      * without overlap checking.
873      */
874     if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
875         /* We bet on a full wildcopy for matches, since we expect matches to be
876          * longer than literals (in general). In silesia, ~10% of matches are longer
877          * than 16 bytes.
878          */
879         ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
880         return sequenceLength;
881     }
882     assert(sequence.offset < WILDCOPY_VECLEN);
883 
884     /* Copy 8 bytes and spread the offset to be >= 8. */
885     ZSTD_overlapCopy8(&op, &match, sequence.offset);
886 
887     /* If the match length is > 8 bytes, then continue with the wildcopy. */
888     if (sequence.matchLength > 8) {
889         assert(op < oMatchEnd);
890         ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst);
891     }
892     return sequenceLength;
893 }
894 
895 static void
896 ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
897 {
898     const void* ptr = dt;
899     const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
900     DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
901     DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
902                 (U32)DStatePtr->state, DTableH->tableLog);
903     BIT_reloadDStream(bitD);
904     DStatePtr->table = dt + 1;
905 }
906 
ZSTD_decompressMultiFrame(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize,const ZSTD_DDict * ddict)907 FORCE_INLINE_TEMPLATE void
908 ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD)
909 {
910     ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state];
911     U32 const nbBits = DInfo.nbBits;
912     size_t const lowBits = BIT_readBits(bitD, nbBits);
913     DStatePtr->state = DInfo.nextState + lowBits;
914 }
915 
916 FORCE_INLINE_TEMPLATE void
917 ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, ZSTD_seqSymbol const DInfo)
918 {
919     U32 const nbBits = DInfo.nbBits;
920     size_t const lowBits = BIT_readBits(bitD, nbBits);
921     DStatePtr->state = DInfo.nextState + lowBits;
922 }
923 
924 /* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
925  * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1)
926  * bits before reloading. This value is the maximum number of bytes we read
927  * after reloading when we are decoding long offsets.
928  */
929 #define LONG_OFFSETS_MAX_EXTRA_BITS_32                       \
930     (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32       \
931         ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32  \
932         : 0)
933 
934 typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
935 
936 FORCE_INLINE_TEMPLATE seq_t
937 ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets)
938 {
939     seq_t seq;
940     ZSTD_seqSymbol const llDInfo = seqState->stateLL.table[seqState->stateLL.state];
941     ZSTD_seqSymbol const mlDInfo = seqState->stateML.table[seqState->stateML.state];
942     ZSTD_seqSymbol const ofDInfo = seqState->stateOffb.table[seqState->stateOffb.state];
943     U32 const llBase = llDInfo.baseValue;
944     U32 const mlBase = mlDInfo.baseValue;
945     U32 const ofBase = ofDInfo.baseValue;
946     BYTE const llBits = llDInfo.nbAdditionalBits;
947     BYTE const mlBits = mlDInfo.nbAdditionalBits;
948     BYTE const ofBits = ofDInfo.nbAdditionalBits;
949     BYTE const totalBits = llBits+mlBits+ofBits;
950 
951     /* sequence */
952     {   size_t offset;
953         if (ofBits > 1) {
954             ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
955             ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
956             assert(ofBits <= MaxOff);
957             if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
958                 U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed);
959                 offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
960                 BIT_reloadDStream(&seqState->DStream);
961                 if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
962                 assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32);   /* to avoid another reload */
963             } else {
964                 offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/);   /* <=  (ZSTD_WINDOWLOG_MAX-1) bits */
965                 if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
966             }
967             seqState->prevOffset[2] = seqState->prevOffset[1];
968             seqState->prevOffset[1] = seqState->prevOffset[0];
969             seqState->prevOffset[0] = offset;
970         } else {
971             U32 const ll0 = (llBase == 0);
972             if (LIKELY((ofBits == 0))) {
973                 if (LIKELY(!ll0))
974                     offset = seqState->prevOffset[0];
975                 else {
976                     offset = seqState->prevOffset[1];
977                     seqState->prevOffset[1] = seqState->prevOffset[0];
978                     seqState->prevOffset[0] = offset;
979                 }
980             } else {
981                 offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
982                 {   size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
983                     temp += !temp;   /* 0 is not valid; input is corrupted; force offset to 1 */
984                     if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
985                     seqState->prevOffset[1] = seqState->prevOffset[0];
986                     seqState->prevOffset[0] = offset = temp;
987         }   }   }
988         seq.offset = offset;
989     }
990 
991     seq.matchLength = mlBase;
992     if (mlBits > 0)
993         seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
994 
995     if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
996         BIT_reloadDStream(&seqState->DStream);
997     if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
ZSTD_decompress_usingDict(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const void * dict,size_t dictSize)998         BIT_reloadDStream(&seqState->DStream);
999     /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
1000     ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
1001 
1002     seq.litLength = llBase;
1003     if (llBits > 0)
1004         seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
1005 
1006     if (MEM_32bits())
ZSTD_getDDict(ZSTD_DCtx * dctx)1007         BIT_reloadDStream(&seqState->DStream);
1008 
1009     DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
1010                 (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1011 
1012     /* ANS state update
1013      * gcc-9.0.0 does 2.5% worse with ZSTD_updateFseStateWithDInfo().
1014      * clang-9.2.0 does 7% worse with ZSTD_updateFseState().
1015      * Naturally it seems like ZSTD_updateFseStateWithDInfo() should be the
1016      * better option, so it is the default for other compilers. But, if you
1017      * measure that it is worse, please put up a pull request.
1018      */
1019     {
1020 #if defined(__GNUC__) && !defined(__clang__)
1021         const int kUseUpdateFseState = 1;
1022 #else
1023         const int kUseUpdateFseState = 0;
ZSTD_decompressDCtx(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize)1024 #endif
1025         if (kUseUpdateFseState) {
1026             ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream);    /* <=  9 bits */
1027             ZSTD_updateFseState(&seqState->stateML, &seqState->DStream);    /* <=  9 bits */
1028             if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);    /* <= 18 bits */
1029             ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream);  /* <=  8 bits */
1030         } else {
1031             ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llDInfo);    /* <=  9 bits */
1032             ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlDInfo);    /* <=  9 bits */
1033             if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);    /* <= 18 bits */
1034             ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofDInfo);  /* <=  8 bits */
1035         }
1036     }
1037 
1038     return seq;
1039 }
1040 
1041 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1042 MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
1043 {
1044     size_t const windowSize = dctx->fParams.windowSize;
1045     /* No dictionary used. */
1046     if (dctx->dictContentEndForFuzzing == NULL) return 0;
1047     /* Dictionary is our prefix. */
1048     if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
1049     /* Dictionary is not our ext-dict. */
1050     if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx * dctx)1051     /* Dictionary is not within our window size. */
1052     if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
1053     /* Dictionary is active. */
1054     return 1;
1055 }
1056 
1057 MEM_STATIC void ZSTD_assertValidSequence(
1058         ZSTD_DCtx const* dctx,
1059         BYTE const* op, BYTE const* oend,
1060         seq_t const seq,
1061         BYTE const* prefixStart, BYTE const* virtualStart)
1062 {
ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx * dctx,size_t inputSize)1063 #if DEBUGLEVEL >= 1
1064     size_t const windowSize = dctx->fParams.windowSize;
1065     size_t const sequenceSize = seq.litLength + seq.matchLength;
1066     BYTE const* const oLitEnd = op + seq.litLength;
1067     DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
1068             (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
1069     assert(op <= oend);
1070     assert((size_t)(oend - op) >= sequenceSize);
ZSTD_nextInputType(ZSTD_DCtx * dctx)1071     assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX);
1072     if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
1073         size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
1074         /* Offset must be within the dictionary. */
1075         assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
1076         assert(seq.offset <= windowSize + dictSize);
1077     } else {
1078         /* Offset must be within our window. */
1079         assert(seq.offset <= windowSize);
1080     }
1081 #else
1082     (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
1083 #endif
1084 }
1085 #endif
1086 
1087 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1088 FORCE_INLINE_TEMPLATE size_t
1089 DONT_VECTORIZE
1090 ZSTD_decompressSequences_body( ZSTD_DCtx* dctx,
1091                                void* dst, size_t maxDstSize,
1092                          const void* seqStart, size_t seqSize, int nbSeq,
ZSTD_isSkipFrame(ZSTD_DCtx * dctx)1093                          const ZSTD_longOffset_e isLongOffset,
1094                          const int frame)
1095 {
1096     const BYTE* ip = (const BYTE*)seqStart;
1097     const BYTE* const iend = ip + seqSize;
1098     BYTE* const ostart = (BYTE*)dst;
1099     BYTE* const oend = ostart + maxDstSize;
1100     BYTE* op = ostart;
1101     const BYTE* litPtr = dctx->litPtr;
1102     const BYTE* const litEnd = litPtr + dctx->litSize;
1103     const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1104     const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
1105     const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1106     DEBUGLOG(5, "ZSTD_decompressSequences_body");
1107     (void)frame;
1108 
1109     /* Regen sequences */
1110     if (nbSeq) {
1111         seqState_t seqState;
1112         dctx->fseEntropy = 1;
1113         { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1114         RETURN_ERROR_IF(
1115             ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
1116             corruption_detected, "");
1117         ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1118         ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1119         ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1120         assert(dst != NULL);
1121 
1122         ZSTD_STATIC_ASSERT(
1123                 BIT_DStream_unfinished < BIT_DStream_completed &&
1124                 BIT_DStream_endOfBuffer < BIT_DStream_completed &&
1125                 BIT_DStream_completed < BIT_DStream_overflow);
1126 
1127 #if defined(__GNUC__) && defined(__x86_64__)
1128         /* Align the decompression loop to 32 + 16 bytes.
1129          *
1130          * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
1131          * speed swings based on the alignment of the decompression loop. This
1132          * performance swing is caused by parts of the decompression loop falling
1133          * out of the DSB. The entire decompression loop should fit in the DSB,
1134          * when it can't we get much worse performance. You can measure if you've
1135          * hit the good case or the bad case with this perf command for some
1136          * compressed file test.zst:
1137          *
1138          *   perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
1139          *             -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
1140          *
1141          * If you see most cycles served out of the MITE you've hit the bad case.
1142          * If you see most cycles served out of the DSB you've hit the good case.
1143          * If it is pretty even then you may be in an okay case.
1144          *
1145          * This issue has been reproduced on the following CPUs:
1146          *   - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
1147          *               Use Instruments->Counters to get DSB/MITE cycles.
1148          *               I never got performance swings, but I was able to
1149          *               go from the good case of mostly DSB to half of the
1150          *               cycles served from MITE.
1151          *   - Coffeelake: Intel i9-9900k
1152          *   - Coffeelake: Intel i7-9700k
1153          *
1154          * I haven't been able to reproduce the instability or DSB misses on any
1155          * of the following CPUS:
1156          *   - Haswell
1157          *   - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
1158          *   - Skylake
1159          *
1160          * If you are seeing performance stability this script can help test.
1161          * It tests on 4 commits in zstd where I saw performance change.
1162          *
1163          *   https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
1164          */
1165         __asm__(".p2align 6");
1166         __asm__("nop");
1167         __asm__(".p2align 5");
1168         __asm__("nop");
1169 #  if __GNUC__ >= 9
1170         /* better for gcc-9 and gcc-10, worse for clang and gcc-8 */
1171         __asm__(".p2align 3");
1172 #  else
1173         __asm__(".p2align 4");
1174 #  endif
1175 #endif
1176         for ( ; ; ) {
1177             seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
1178             size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
1179 #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1180             assert(!ZSTD_isError(oneSeqSize));
1181             if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
1182 #endif
1183             if (UNLIKELY(ZSTD_isError(oneSeqSize)))
1184                 return oneSeqSize;
1185             DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
1186             op += oneSeqSize;
1187             if (UNLIKELY(!--nbSeq))
1188                 break;
1189             BIT_reloadDStream(&(seqState.DStream));
1190         }
1191 
1192         /* check if reached exact end */
1193         DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
1194         RETURN_ERROR_IF(nbSeq, corruption_detected, "");
1195         RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
1196         /* save reps for next block */
1197         { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1198     }
1199 
1200     /* last literal segment */
1201     {   size_t const lastLLSize = litEnd - litPtr;
1202         RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1203         if (op != NULL) {
1204             ZSTD_memcpy(op, litPtr, lastLLSize);
1205             op += lastLLSize;
1206         }
1207     }
1208 
1209     return op-ostart;
1210 }
1211 
1212 static size_t
1213 ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
1214                                  void* dst, size_t maxDstSize,
1215                            const void* seqStart, size_t seqSize, int nbSeq,
1216                            const ZSTD_longOffset_e isLongOffset,
1217                            const int frame)
1218 {
1219     return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1220 }
1221 #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1222 
1223 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1224 
1225 FORCE_INLINE_TEMPLATE size_t
1226 ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
1227                    const BYTE* const prefixStart, const BYTE* const dictEnd)
1228 {
1229     prefetchPos += sequence.litLength;
1230     {   const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;
1231         const BYTE* const match = matchBase + prefetchPos - sequence.offset; /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.
1232                                                                               * No consequence though : memory address is only used for prefetching, not for dereferencing */
1233         PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE);   /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
1234     }
1235     return prefetchPos + sequence.matchLength;
1236 }
1237 
1238 /* This decoding function employs prefetching
1239  * to reduce latency impact of cache misses.
1240  * It's generally employed when block contains a significant portion of long-distance matches
1241  * or when coupled with a "cold" dictionary */
1242 FORCE_INLINE_TEMPLATE size_t
1243 ZSTD_decompressSequencesLong_body(
1244                                ZSTD_DCtx* dctx,
1245                                void* dst, size_t maxDstSize,
1246                          const void* seqStart, size_t seqSize, int nbSeq,
1247                          const ZSTD_longOffset_e isLongOffset,
1248                          const int frame)
1249 {
1250     const BYTE* ip = (const BYTE*)seqStart;
1251     const BYTE* const iend = ip + seqSize;
1252     BYTE* const ostart = (BYTE*)dst;
1253     BYTE* const oend = ostart + maxDstSize;
1254     BYTE* op = ostart;
1255     const BYTE* litPtr = dctx->litPtr;
1256     const BYTE* const litEnd = litPtr + dctx->litSize;
ZSTD_refDictContent(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1257     const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
1258     const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
1259     const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
1260     (void)frame;
1261 
1262     /* Regen sequences */
1263     if (nbSeq) {
1264 #define STORED_SEQS 8
1265 #define STORED_SEQS_MASK (STORED_SEQS-1)
1266 #define ADVANCED_SEQS STORED_SEQS
1267         seq_t sequences[STORED_SEQS];
1268         int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
1269         seqState_t seqState;
1270         int seqNb;
1271         size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
1272 
1273         dctx->fseEntropy = 1;
ZSTD_loadDEntropy(ZSTD_entropyDTables_t * entropy,const void * const dict,size_t const dictSize)1274         { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
1275         assert(dst != NULL);
1276         assert(iend >= ip);
1277         RETURN_ERROR_IF(
1278             ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
1279             corruption_detected, "");
1280         ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
1281         ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
1282         ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
1283 
1284         /* prepare in advance */
1285         for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
1286             seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
1287             prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1288             sequences[seqNb] = sequence;
1289         }
1290         RETURN_ERROR_IF(seqNb<seqAdvance, corruption_detected, "");
1291 
1292         /* decode and decompress */
1293         for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) {
1294             seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
1295             size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
1296 #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1297             assert(!ZSTD_isError(oneSeqSize));
1298             if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
1299 #endif
1300             if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1301 
1302             prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
1303             sequences[seqNb & STORED_SEQS_MASK] = sequence;
1304             op += oneSeqSize;
1305         }
1306         RETURN_ERROR_IF(seqNb<nbSeq, corruption_detected, "");
1307 
1308         /* finish queue */
1309         seqNb -= seqAdvance;
1310         for ( ; seqNb<nbSeq ; seqNb++) {
1311             size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
1312 #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
1313             assert(!ZSTD_isError(oneSeqSize));
1314             if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
1315 #endif
1316             if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
1317             op += oneSeqSize;
1318         }
1319 
1320         /* save reps for next block */
1321         { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
1322     }
1323 
1324     /* last literal segment */
1325     {   size_t const lastLLSize = litEnd - litPtr;
1326         RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
1327         if (op != NULL) {
1328             ZSTD_memcpy(op, litPtr, lastLLSize);
1329             op += lastLLSize;
1330         }
1331     }
1332 
1333     return op-ostart;
1334 }
1335 
1336 static size_t
1337 ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
1338                                  void* dst, size_t maxDstSize,
1339                            const void* seqStart, size_t seqSize, int nbSeq,
1340                            const ZSTD_longOffset_e isLongOffset,
1341                            const int frame)
1342 {
1343     return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1344 }
1345 #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
1346 
1347 
1348 
1349 #if DYNAMIC_BMI2
1350 
1351 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1352 static TARGET_ATTRIBUTE("bmi2") size_t
1353 DONT_VECTORIZE
1354 ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
1355                                  void* dst, size_t maxDstSize,
1356                            const void* seqStart, size_t seqSize, int nbSeq,
1357                            const ZSTD_longOffset_e isLongOffset,
1358                            const int frame)
1359 {
1360     return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
ZSTD_decompress_insertDictionary(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1361 }
1362 #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1363 
1364 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1365 static TARGET_ATTRIBUTE("bmi2") size_t
1366 ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
1367                                  void* dst, size_t maxDstSize,
1368                            const void* seqStart, size_t seqSize, int nbSeq,
1369                            const ZSTD_longOffset_e isLongOffset,
1370                            const int frame)
1371 {
1372     return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1373 }
1374 #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
1375 
1376 #endif /* DYNAMIC_BMI2 */
1377 
1378 typedef size_t (*ZSTD_decompressSequences_t)(
1379                             ZSTD_DCtx* dctx,
1380                             void* dst, size_t maxDstSize,
1381                             const void* seqStart, size_t seqSize, int nbSeq,
ZSTD_decompressBegin(ZSTD_DCtx * dctx)1382                             const ZSTD_longOffset_e isLongOffset,
1383                             const int frame);
1384 
1385 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1386 static size_t
1387 ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
1388                    const void* seqStart, size_t seqSize, int nbSeq,
1389                    const ZSTD_longOffset_e isLongOffset,
1390                    const int frame)
1391 {
1392     DEBUGLOG(5, "ZSTD_decompressSequences");
1393 #if DYNAMIC_BMI2
1394     if (dctx->bmi2) {
1395         return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1396     }
1397 #endif
1398   return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1399 }
1400 #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
1401 
1402 
1403 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
1404 /* ZSTD_decompressSequencesLong() :
1405  * decompression function triggered when a minimum share of offsets is considered "long",
1406  * aka out of cache.
1407  * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
1408  * This function will try to mitigate main memory latency through the use of prefetching */
ZSTD_decompressBegin_usingDict(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1409 static size_t
1410 ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
1411                              void* dst, size_t maxDstSize,
1412                              const void* seqStart, size_t seqSize, int nbSeq,
1413                              const ZSTD_longOffset_e isLongOffset,
1414                              const int frame)
1415 {
1416     DEBUGLOG(5, "ZSTD_decompressSequencesLong");
1417 #if DYNAMIC_BMI2
1418     if (dctx->bmi2) {
1419         return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1420     }
1421 #endif
1422   return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
1423 }
1424 #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
1425 
1426 
1427 
1428 #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
1429     !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
1430 /* ZSTD_getLongOffsetsShare() :
1431  * condition : offTable must be valid
1432  * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
1433  *           compared to maximum possible of (1<<OffFSELog) */
1434 static unsigned
1435 ZSTD_getLongOffsetsShare(const ZSTD_seqSymbol* offTable)
1436 {
1437     const void* ptr = offTable;
1438     U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
1439     const ZSTD_seqSymbol* table = offTable + 1;
1440     U32 const max = 1 << tableLog;
1441     U32 u, total = 0;
1442     DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
1443 
1444     assert(max <= (1 << OffFSELog));  /* max not too large */
ZSTD_getDictID_fromDict(const void * dict,size_t dictSize)1445     for (u=0; u<max; u++) {
1446         if (table[u].nbAdditionalBits > 22) total += 1;
1447     }
1448 
1449     assert(tableLog <= OffFSELog);
1450     total <<= (OffFSELog - tableLog);  /* scale to OffFSELog */
1451 
1452     return total;
1453 }
1454 #endif
1455 
1456 size_t
1457 ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
1458                               void* dst, size_t dstCapacity,
1459                         const void* src, size_t srcSize, const int frame)
1460 {   /* blockType == blockCompressed */
1461     const BYTE* ip = (const BYTE*)src;
1462     /* isLongOffset must be true if there are long offsets.
1463      * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
1464      * We don't expect that to be the case in 64-bit mode.
ZSTD_getDictID_fromFrame(const void * src,size_t srcSize)1465      * In block mode, window size is not known, so we have to be conservative.
1466      * (note: but it could be evaluated from current-lowLimit)
1467      */
1468     ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN))));
1469     DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
1470 
1471     RETURN_ERROR_IF(srcSize >= ZSTD_BLOCKSIZE_MAX, srcSize_wrong, "");
1472 
1473     /* Decode literals section */
1474     {   size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
1475         DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
1476         if (ZSTD_isError(litCSize)) return litCSize;
ZSTD_decompress_usingDDict(ZSTD_DCtx * dctx,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const ZSTD_DDict * ddict)1477         ip += litCSize;
1478         srcSize -= litCSize;
1479     }
1480 
1481     /* Build Decoding Tables */
1482     {
1483         /* These macros control at build-time which decompressor implementation
1484          * we use. If neither is defined, we do some inspection and dispatch at
1485          * runtime.
1486          */
1487 #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
1488     !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
1489         int usePrefetchDecoder = dctx->ddictIsCold;
1490 #endif
1491         int nbSeq;
1492         size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
ZSTD_createDStream(void)1493         if (ZSTD_isError(seqHSize)) return seqHSize;
1494         ip += seqHSize;
1495         srcSize -= seqHSize;
1496 
1497         RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
1498 
ZSTD_initStaticDStream(void * workspace,size_t workspaceSize)1499 #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
1500     !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
1501         if ( !usePrefetchDecoder
1502           && (!frame || (dctx->fParams.windowSize > (1<<24)))
1503           && (nbSeq>ADVANCED_SEQS) ) {  /* could probably use a larger nbSeq limit */
1504             U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr);
1505             U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
1506             usePrefetchDecoder = (shareLongOffsets >= minShare);
1507         }
1508 #endif
ZSTD_freeDStream(ZSTD_DStream * zds)1509 
1510         dctx->ddictIsCold = 0;
1511 
1512 #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
1513     !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
1514         if (usePrefetchDecoder)
1515 #endif
1516 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
ZSTD_DStreamInSize(void)1517             return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
ZSTD_DStreamOutSize(void)1518 #endif
1519 
1520 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
1521         /* else */
1522         return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
1523 #endif
1524     }
1525 }
1526 
1527 
1528 void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
1529 {
1530     if (dst != dctx->previousDstEnd && dstSize > 0) {   /* not contiguous */
1531         dctx->dictEnd = dctx->previousDstEnd;
1532         dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
1533         dctx->prefixStart = dst;
1534         dctx->previousDstEnd = dst;
1535     }
ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx * dctx,const void * dict,size_t dictSize)1536 }
1537 
1538 
1539 size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
1540                             void* dst, size_t dstCapacity,
1541                       const void* src, size_t srcSize)
1542 {
1543     size_t dSize;
1544     ZSTD_checkContinuity(dctx, dst, dstCapacity);
1545     dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
1546     dctx->previousDstEnd = (char*)dst + dSize;
1547     return dSize;
1548 }
1549