Path: blob/master/Utilities/cmzstd/lib/decompress/zstd_decompress_block.c
5053 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910/* zstd_decompress_block :11* this module takes care of decompressing _compressed_ block */1213/*-*******************************************************14* Dependencies15*********************************************************/16#include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */17#include "../common/compiler.h" /* prefetch */18#include "../common/cpu.h" /* bmi2 */19#include "../common/mem.h" /* low level memory routines */20#define FSE_STATIC_LINKING_ONLY21#include "../common/fse.h"22#include "../common/huf.h"23#include "../common/zstd_internal.h"24#include "zstd_decompress_internal.h" /* ZSTD_DCtx */25#include "zstd_ddict.h" /* ZSTD_DDictDictContent */26#include "zstd_decompress_block.h"27#include "../common/bits.h" /* ZSTD_highbit32 */2829/*_*******************************************************30* Macros31**********************************************************/3233/* These two optional macros force the use one way or another of the two34* ZSTD_decompressSequences implementations. You can't force in both directions35* at the same time.36*/37#if defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \38defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)39#error "Cannot force the use of the short and the long ZSTD_decompressSequences variants!"40#endif414243/*_*******************************************************44* Memory operations45**********************************************************/46static void ZSTD_copy4(void* dst, const void* src) { ZSTD_memcpy(dst, src, 4); }474849/*-*************************************************************50* Block decoding51***************************************************************/5253static size_t ZSTD_blockSizeMax(ZSTD_DCtx const* dctx)54{55size_t const blockSizeMax = dctx->isFrameDecompression ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX;56assert(blockSizeMax <= ZSTD_BLOCKSIZE_MAX);57return blockSizeMax;58}5960/*! ZSTD_getcBlockSize() :61* Provides the size of compressed block from block header `src` */62size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,63blockProperties_t* bpPtr)64{65RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, "");6667{ U32 const cBlockHeader = MEM_readLE24(src);68U32 const cSize = cBlockHeader >> 3;69bpPtr->lastBlock = cBlockHeader & 1;70bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);71bpPtr->origSize = cSize; /* only useful for RLE */72if (bpPtr->blockType == bt_rle) return 1;73RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, "");74return cSize;75}76}7778/* Allocate buffer for literals, either overlapping current dst, or split between dst and litExtraBuffer, or stored entirely within litExtraBuffer */79static void ZSTD_allocateLiteralsBuffer(ZSTD_DCtx* dctx, void* const dst, const size_t dstCapacity, const size_t litSize,80const streaming_operation streaming, const size_t expectedWriteSize, const unsigned splitImmediately)81{82size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);83assert(litSize <= blockSizeMax);84assert(dctx->isFrameDecompression || streaming == not_streaming);85assert(expectedWriteSize <= blockSizeMax);86if (streaming == not_streaming && dstCapacity > blockSizeMax + WILDCOPY_OVERLENGTH + litSize + WILDCOPY_OVERLENGTH) {87/* If we aren't streaming, we can just put the literals after the output88* of the current block. We don't need to worry about overwriting the89* extDict of our window, because it doesn't exist.90* So if we have space after the end of the block, just put it there.91*/92dctx->litBuffer = (BYTE*)dst + blockSizeMax + WILDCOPY_OVERLENGTH;93dctx->litBufferEnd = dctx->litBuffer + litSize;94dctx->litBufferLocation = ZSTD_in_dst;95} else if (litSize <= ZSTD_LITBUFFEREXTRASIZE) {96/* Literals fit entirely within the extra buffer, put them there to avoid97* having to split the literals.98*/99dctx->litBuffer = dctx->litExtraBuffer;100dctx->litBufferEnd = dctx->litBuffer + litSize;101dctx->litBufferLocation = ZSTD_not_in_dst;102} else {103assert(blockSizeMax > ZSTD_LITBUFFEREXTRASIZE);104/* Literals must be split between the output block and the extra lit105* buffer. We fill the extra lit buffer with the tail of the literals,106* and put the rest of the literals at the end of the block, with107* WILDCOPY_OVERLENGTH of buffer room to allow for overreads.108* This MUST not write more than our maxBlockSize beyond dst, because in109* streaming mode, that could overwrite part of our extDict window.110*/111if (splitImmediately) {112/* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */113dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;114dctx->litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE;115} else {116/* initially this will be stored entirely in dst during huffman decoding, it will partially be shifted to litExtraBuffer after */117dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize;118dctx->litBufferEnd = (BYTE*)dst + expectedWriteSize;119}120dctx->litBufferLocation = ZSTD_split;121assert(dctx->litBufferEnd <= (BYTE*)dst + expectedWriteSize);122}123}124125/*! ZSTD_decodeLiteralsBlock() :126* Where it is possible to do so without being stomped by the output during decompression, the literals block will be stored127* in the dstBuffer. If there is room to do so, it will be stored in full in the excess dst space after where the current128* block will be output. Otherwise it will be stored at the end of the current dst blockspace, with a small portion being129* stored in dctx->litExtraBuffer to help keep it "ahead" of the current output write.130*131* @return : nb of bytes read from src (< srcSize )132* note : symbol not declared but exposed for fullbench */133static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,134const void* src, size_t srcSize, /* note : srcSize < BLOCKSIZE */135void* dst, size_t dstCapacity, const streaming_operation streaming)136{137DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");138RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");139140{ const BYTE* const istart = (const BYTE*) src;141SymbolEncodingType_e const litEncType = (SymbolEncodingType_e)(istart[0] & 3);142size_t const blockSizeMax = ZSTD_blockSizeMax(dctx);143144switch(litEncType)145{146case set_repeat:147DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");148RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");149ZSTD_FALLTHROUGH;150151case set_compressed:152RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need up to 5 for case 3");153{ size_t lhSize, litSize, litCSize;154U32 singleStream=0;155U32 const lhlCode = (istart[0] >> 2) & 3;156U32 const lhc = MEM_readLE32(istart);157size_t hufSuccess;158size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);159int const flags = 0160| (ZSTD_DCtx_get_bmi2(dctx) ? HUF_flags_bmi2 : 0)161| (dctx->disableHufAsm ? HUF_flags_disableAsm : 0);162switch(lhlCode)163{164case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */165/* 2 - 2 - 10 - 10 */166singleStream = !lhlCode;167lhSize = 3;168litSize = (lhc >> 4) & 0x3FF;169litCSize = (lhc >> 14) & 0x3FF;170break;171case 2:172/* 2 - 2 - 14 - 14 */173lhSize = 4;174litSize = (lhc >> 4) & 0x3FFF;175litCSize = lhc >> 18;176break;177case 3:178/* 2 - 2 - 18 - 18 */179lhSize = 5;180litSize = (lhc >> 4) & 0x3FFFF;181litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);182break;183}184RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");185RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");186if (!singleStream)187RETURN_ERROR_IF(litSize < MIN_LITERALS_FOR_4_STREAMS, literals_headerWrong,188"Not enough literals (%zu) for the 4-streams mode (min %u)",189litSize, MIN_LITERALS_FOR_4_STREAMS);190RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");191RETURN_ERROR_IF(expectedWriteSize < litSize , dstSize_tooSmall, "");192ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 0);193194/* prefetch huffman table if cold */195if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {196PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));197}198199if (litEncType==set_repeat) {200if (singleStream) {201hufSuccess = HUF_decompress1X_usingDTable(202dctx->litBuffer, litSize, istart+lhSize, litCSize,203dctx->HUFptr, flags);204} else {205assert(litSize >= MIN_LITERALS_FOR_4_STREAMS);206hufSuccess = HUF_decompress4X_usingDTable(207dctx->litBuffer, litSize, istart+lhSize, litCSize,208dctx->HUFptr, flags);209}210} else {211if (singleStream) {212#if defined(HUF_FORCE_DECOMPRESS_X2)213hufSuccess = HUF_decompress1X_DCtx_wksp(214dctx->entropy.hufTable, dctx->litBuffer, litSize,215istart+lhSize, litCSize, dctx->workspace,216sizeof(dctx->workspace), flags);217#else218hufSuccess = HUF_decompress1X1_DCtx_wksp(219dctx->entropy.hufTable, dctx->litBuffer, litSize,220istart+lhSize, litCSize, dctx->workspace,221sizeof(dctx->workspace), flags);222#endif223} else {224hufSuccess = HUF_decompress4X_hufOnly_wksp(225dctx->entropy.hufTable, dctx->litBuffer, litSize,226istart+lhSize, litCSize, dctx->workspace,227sizeof(dctx->workspace), flags);228}229}230if (dctx->litBufferLocation == ZSTD_split)231{232assert(litSize > ZSTD_LITBUFFEREXTRASIZE);233ZSTD_memcpy(dctx->litExtraBuffer, dctx->litBufferEnd - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);234ZSTD_memmove(dctx->litBuffer + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH, dctx->litBuffer, litSize - ZSTD_LITBUFFEREXTRASIZE);235dctx->litBuffer += ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH;236dctx->litBufferEnd -= WILDCOPY_OVERLENGTH;237assert(dctx->litBufferEnd <= (BYTE*)dst + blockSizeMax);238}239240RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");241242dctx->litPtr = dctx->litBuffer;243dctx->litSize = litSize;244dctx->litEntropy = 1;245if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;246return litCSize + lhSize;247}248249case set_basic:250{ size_t litSize, lhSize;251U32 const lhlCode = ((istart[0]) >> 2) & 3;252size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);253switch(lhlCode)254{255case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */256lhSize = 1;257litSize = istart[0] >> 3;258break;259case 1:260lhSize = 2;261litSize = MEM_readLE16(istart) >> 4;262break;263case 3:264lhSize = 3;265RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize = 3");266litSize = MEM_readLE24(istart) >> 4;267break;268}269270RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");271RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");272RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");273ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);274if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */275RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");276if (dctx->litBufferLocation == ZSTD_split)277{278ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize - ZSTD_LITBUFFEREXTRASIZE);279ZSTD_memcpy(dctx->litExtraBuffer, istart + lhSize + litSize - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE);280}281else282{283ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize);284}285dctx->litPtr = dctx->litBuffer;286dctx->litSize = litSize;287return lhSize+litSize;288}289/* direct reference into compressed stream */290dctx->litPtr = istart+lhSize;291dctx->litSize = litSize;292dctx->litBufferEnd = dctx->litPtr + litSize;293dctx->litBufferLocation = ZSTD_not_in_dst;294return lhSize+litSize;295}296297case set_rle:298{ U32 const lhlCode = ((istart[0]) >> 2) & 3;299size_t litSize, lhSize;300size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity);301switch(lhlCode)302{303case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */304lhSize = 1;305litSize = istart[0] >> 3;306break;307case 1:308lhSize = 2;309RETURN_ERROR_IF(srcSize<3, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 3");310litSize = MEM_readLE16(istart) >> 4;311break;312case 3:313lhSize = 3;314RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 2; here we need lhSize+1 = 4");315litSize = MEM_readLE24(istart) >> 4;316break;317}318RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled");319RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, "");320RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, "");321ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1);322if (dctx->litBufferLocation == ZSTD_split)323{324ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize - ZSTD_LITBUFFEREXTRASIZE);325ZSTD_memset(dctx->litExtraBuffer, istart[lhSize], ZSTD_LITBUFFEREXTRASIZE);326}327else328{329ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize);330}331dctx->litPtr = dctx->litBuffer;332dctx->litSize = litSize;333return lhSize+1;334}335default:336RETURN_ERROR(corruption_detected, "impossible");337}338}339}340341/* Hidden declaration for fullbench */342size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx,343const void* src, size_t srcSize,344void* dst, size_t dstCapacity);345size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx,346const void* src, size_t srcSize,347void* dst, size_t dstCapacity)348{349dctx->isFrameDecompression = 0;350return ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, not_streaming);351}352353/* Default FSE distribution tables.354* These are pre-calculated FSE decoding tables using default distributions as defined in specification :355* https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#default-distributions356* They were generated programmatically with following method :357* - start from default distributions, present in /lib/common/zstd_internal.h358* - generate tables normally, using ZSTD_buildFSETable()359* - printout the content of tables360* - prettify output, report below, test with fuzzer to ensure it's correct */361362/* Default FSE distribution table for Literal Lengths */363static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {364{ 1, 1, 1, LL_DEFAULTNORMLOG}, /* header : fastMode, tableLog */365/* nextState, nbAddBits, nbBits, baseVal */366{ 0, 0, 4, 0}, { 16, 0, 4, 0},367{ 32, 0, 5, 1}, { 0, 0, 5, 3},368{ 0, 0, 5, 4}, { 0, 0, 5, 6},369{ 0, 0, 5, 7}, { 0, 0, 5, 9},370{ 0, 0, 5, 10}, { 0, 0, 5, 12},371{ 0, 0, 6, 14}, { 0, 1, 5, 16},372{ 0, 1, 5, 20}, { 0, 1, 5, 22},373{ 0, 2, 5, 28}, { 0, 3, 5, 32},374{ 0, 4, 5, 48}, { 32, 6, 5, 64},375{ 0, 7, 5, 128}, { 0, 8, 6, 256},376{ 0, 10, 6, 1024}, { 0, 12, 6, 4096},377{ 32, 0, 4, 0}, { 0, 0, 4, 1},378{ 0, 0, 5, 2}, { 32, 0, 5, 4},379{ 0, 0, 5, 5}, { 32, 0, 5, 7},380{ 0, 0, 5, 8}, { 32, 0, 5, 10},381{ 0, 0, 5, 11}, { 0, 0, 6, 13},382{ 32, 1, 5, 16}, { 0, 1, 5, 18},383{ 32, 1, 5, 22}, { 0, 2, 5, 24},384{ 32, 3, 5, 32}, { 0, 3, 5, 40},385{ 0, 6, 4, 64}, { 16, 6, 4, 64},386{ 32, 7, 5, 128}, { 0, 9, 6, 512},387{ 0, 11, 6, 2048}, { 48, 0, 4, 0},388{ 16, 0, 4, 1}, { 32, 0, 5, 2},389{ 32, 0, 5, 3}, { 32, 0, 5, 5},390{ 32, 0, 5, 6}, { 32, 0, 5, 8},391{ 32, 0, 5, 9}, { 32, 0, 5, 11},392{ 32, 0, 5, 12}, { 0, 0, 6, 15},393{ 32, 1, 5, 18}, { 32, 1, 5, 20},394{ 32, 2, 5, 24}, { 32, 2, 5, 28},395{ 32, 3, 5, 40}, { 32, 4, 5, 48},396{ 0, 16, 6,65536}, { 0, 15, 6,32768},397{ 0, 14, 6,16384}, { 0, 13, 6, 8192},398}; /* LL_defaultDTable */399400/* Default FSE distribution table for Offset Codes */401static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {402{ 1, 1, 1, OF_DEFAULTNORMLOG}, /* header : fastMode, tableLog */403/* nextState, nbAddBits, nbBits, baseVal */404{ 0, 0, 5, 0}, { 0, 6, 4, 61},405{ 0, 9, 5, 509}, { 0, 15, 5,32765},406{ 0, 21, 5,2097149}, { 0, 3, 5, 5},407{ 0, 7, 4, 125}, { 0, 12, 5, 4093},408{ 0, 18, 5,262141}, { 0, 23, 5,8388605},409{ 0, 5, 5, 29}, { 0, 8, 4, 253},410{ 0, 14, 5,16381}, { 0, 20, 5,1048573},411{ 0, 2, 5, 1}, { 16, 7, 4, 125},412{ 0, 11, 5, 2045}, { 0, 17, 5,131069},413{ 0, 22, 5,4194301}, { 0, 4, 5, 13},414{ 16, 8, 4, 253}, { 0, 13, 5, 8189},415{ 0, 19, 5,524285}, { 0, 1, 5, 1},416{ 16, 6, 4, 61}, { 0, 10, 5, 1021},417{ 0, 16, 5,65533}, { 0, 28, 5,268435453},418{ 0, 27, 5,134217725}, { 0, 26, 5,67108861},419{ 0, 25, 5,33554429}, { 0, 24, 5,16777213},420}; /* OF_defaultDTable */421422423/* Default FSE distribution table for Match Lengths */424static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {425{ 1, 1, 1, ML_DEFAULTNORMLOG}, /* header : fastMode, tableLog */426/* nextState, nbAddBits, nbBits, baseVal */427{ 0, 0, 6, 3}, { 0, 0, 4, 4},428{ 32, 0, 5, 5}, { 0, 0, 5, 6},429{ 0, 0, 5, 8}, { 0, 0, 5, 9},430{ 0, 0, 5, 11}, { 0, 0, 6, 13},431{ 0, 0, 6, 16}, { 0, 0, 6, 19},432{ 0, 0, 6, 22}, { 0, 0, 6, 25},433{ 0, 0, 6, 28}, { 0, 0, 6, 31},434{ 0, 0, 6, 34}, { 0, 1, 6, 37},435{ 0, 1, 6, 41}, { 0, 2, 6, 47},436{ 0, 3, 6, 59}, { 0, 4, 6, 83},437{ 0, 7, 6, 131}, { 0, 9, 6, 515},438{ 16, 0, 4, 4}, { 0, 0, 4, 5},439{ 32, 0, 5, 6}, { 0, 0, 5, 7},440{ 32, 0, 5, 9}, { 0, 0, 5, 10},441{ 0, 0, 6, 12}, { 0, 0, 6, 15},442{ 0, 0, 6, 18}, { 0, 0, 6, 21},443{ 0, 0, 6, 24}, { 0, 0, 6, 27},444{ 0, 0, 6, 30}, { 0, 0, 6, 33},445{ 0, 1, 6, 35}, { 0, 1, 6, 39},446{ 0, 2, 6, 43}, { 0, 3, 6, 51},447{ 0, 4, 6, 67}, { 0, 5, 6, 99},448{ 0, 8, 6, 259}, { 32, 0, 4, 4},449{ 48, 0, 4, 4}, { 16, 0, 4, 5},450{ 32, 0, 5, 7}, { 32, 0, 5, 8},451{ 32, 0, 5, 10}, { 32, 0, 5, 11},452{ 0, 0, 6, 14}, { 0, 0, 6, 17},453{ 0, 0, 6, 20}, { 0, 0, 6, 23},454{ 0, 0, 6, 26}, { 0, 0, 6, 29},455{ 0, 0, 6, 32}, { 0, 16, 6,65539},456{ 0, 15, 6,32771}, { 0, 14, 6,16387},457{ 0, 13, 6, 8195}, { 0, 12, 6, 4099},458{ 0, 11, 6, 2051}, { 0, 10, 6, 1027},459}; /* ML_defaultDTable */460461462static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U8 nbAddBits)463{464void* ptr = dt;465ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;466ZSTD_seqSymbol* const cell = dt + 1;467468DTableH->tableLog = 0;469DTableH->fastMode = 0;470471cell->nbBits = 0;472cell->nextState = 0;473assert(nbAddBits < 255);474cell->nbAdditionalBits = nbAddBits;475cell->baseValue = baseValue;476}477478479/* ZSTD_buildFSETable() :480* generate FSE decoding table for one symbol (ll, ml or off)481* cannot fail if input is valid =>482* all inputs are presumed validated at this stage */483FORCE_INLINE_TEMPLATE484void ZSTD_buildFSETable_body(ZSTD_seqSymbol* dt,485const short* normalizedCounter, unsigned maxSymbolValue,486const U32* baseValue, const U8* nbAdditionalBits,487unsigned tableLog, void* wksp, size_t wkspSize)488{489ZSTD_seqSymbol* const tableDecode = dt+1;490U32 const maxSV1 = maxSymbolValue + 1;491U32 const tableSize = 1 << tableLog;492493U16* symbolNext = (U16*)wksp;494BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1);495U32 highThreshold = tableSize - 1;496497498/* Sanity Checks */499assert(maxSymbolValue <= MaxSeq);500assert(tableLog <= MaxFSELog);501assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE);502(void)wkspSize;503/* Init, lay down lowprob symbols */504{ ZSTD_seqSymbol_header DTableH;505DTableH.tableLog = tableLog;506DTableH.fastMode = 1;507{ S16 const largeLimit= (S16)(1 << (tableLog-1));508U32 s;509for (s=0; s<maxSV1; s++) {510if (normalizedCounter[s]==-1) {511tableDecode[highThreshold--].baseValue = s;512symbolNext[s] = 1;513} else {514if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;515assert(normalizedCounter[s]>=0);516symbolNext[s] = (U16)normalizedCounter[s];517} } }518ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));519}520521/* Spread symbols */522assert(tableSize <= 512);523/* Specialized symbol spreading for the case when there are524* no low probability (-1 count) symbols. When compressing525* small blocks we avoid low probability symbols to hit this526* case, since header decoding speed matters more.527*/528if (highThreshold == tableSize - 1) {529size_t const tableMask = tableSize-1;530size_t const step = FSE_TABLESTEP(tableSize);531/* First lay down the symbols in order.532* We use a uint64_t to lay down 8 bytes at a time. This reduces branch533* misses since small blocks generally have small table logs, so nearly534* all symbols have counts <= 8. We ensure we have 8 bytes at the end of535* our buffer to handle the over-write.536*/537{538U64 const add = 0x0101010101010101ull;539size_t pos = 0;540U64 sv = 0;541U32 s;542for (s=0; s<maxSV1; ++s, sv += add) {543int i;544int const n = normalizedCounter[s];545MEM_write64(spread + pos, sv);546for (i = 8; i < n; i += 8) {547MEM_write64(spread + pos + i, sv);548}549assert(n>=0);550pos += (size_t)n;551}552}553/* Now we spread those positions across the table.554* The benefit of doing it in two stages is that we avoid the555* variable size inner loop, which caused lots of branch misses.556* Now we can run through all the positions without any branch misses.557* We unroll the loop twice, since that is what empirically worked best.558*/559{560size_t position = 0;561size_t s;562size_t const unroll = 2;563assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */564for (s = 0; s < (size_t)tableSize; s += unroll) {565size_t u;566for (u = 0; u < unroll; ++u) {567size_t const uPosition = (position + (u * step)) & tableMask;568tableDecode[uPosition].baseValue = spread[s + u];569}570position = (position + (unroll * step)) & tableMask;571}572assert(position == 0);573}574} else {575U32 const tableMask = tableSize-1;576U32 const step = FSE_TABLESTEP(tableSize);577U32 s, position = 0;578for (s=0; s<maxSV1; s++) {579int i;580int const n = normalizedCounter[s];581for (i=0; i<n; i++) {582tableDecode[position].baseValue = s;583position = (position + step) & tableMask;584while (UNLIKELY(position > highThreshold)) position = (position + step) & tableMask; /* lowprob area */585} }586assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */587}588589/* Build Decoding table */590{591U32 u;592for (u=0; u<tableSize; u++) {593U32 const symbol = tableDecode[u].baseValue;594U32 const nextState = symbolNext[symbol]++;595tableDecode[u].nbBits = (BYTE) (tableLog - ZSTD_highbit32(nextState) );596tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);597assert(nbAdditionalBits[symbol] < 255);598tableDecode[u].nbAdditionalBits = nbAdditionalBits[symbol];599tableDecode[u].baseValue = baseValue[symbol];600}601}602}603604/* Avoids the FORCE_INLINE of the _body() function. */605static void ZSTD_buildFSETable_body_default(ZSTD_seqSymbol* dt,606const short* normalizedCounter, unsigned maxSymbolValue,607const U32* baseValue, const U8* nbAdditionalBits,608unsigned tableLog, void* wksp, size_t wkspSize)609{610ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,611baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);612}613614#if DYNAMIC_BMI2615BMI2_TARGET_ATTRIBUTE static void ZSTD_buildFSETable_body_bmi2(ZSTD_seqSymbol* dt,616const short* normalizedCounter, unsigned maxSymbolValue,617const U32* baseValue, const U8* nbAdditionalBits,618unsigned tableLog, void* wksp, size_t wkspSize)619{620ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,621baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);622}623#endif624625void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,626const short* normalizedCounter, unsigned maxSymbolValue,627const U32* baseValue, const U8* nbAdditionalBits,628unsigned tableLog, void* wksp, size_t wkspSize, int bmi2)629{630#if DYNAMIC_BMI2631if (bmi2) {632ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue,633baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);634return;635}636#endif637(void)bmi2;638ZSTD_buildFSETable_body_default(dt, normalizedCounter, maxSymbolValue,639baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);640}641642643/*! ZSTD_buildSeqTable() :644* @return : nb bytes read from src,645* or an error code if it fails */646static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,647SymbolEncodingType_e type, unsigned max, U32 maxLog,648const void* src, size_t srcSize,649const U32* baseValue, const U8* nbAdditionalBits,650const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,651int ddictIsCold, int nbSeq, U32* wksp, size_t wkspSize,652int bmi2)653{654switch(type)655{656case set_rle :657RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");658RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");659{ U32 const symbol = *(const BYTE*)src;660U32 const baseline = baseValue[symbol];661U8 const nbBits = nbAdditionalBits[symbol];662ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);663}664*DTablePtr = DTableSpace;665return 1;666case set_basic :667*DTablePtr = defaultTable;668return 0;669case set_repeat:670RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");671/* prefetch FSE table if used */672if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {673const void* const pStart = *DTablePtr;674size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));675PREFETCH_AREA(pStart, pSize);676}677return 0;678case set_compressed :679{ unsigned tableLog;680S16 norm[MaxSeq+1];681size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);682RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");683RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");684ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2);685*DTablePtr = DTableSpace;686return headerSize;687}688default :689assert(0);690RETURN_ERROR(GENERIC, "impossible");691}692}693694size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,695const void* src, size_t srcSize)696{697const BYTE* const istart = (const BYTE*)src;698const BYTE* const iend = istart + srcSize;699const BYTE* ip = istart;700int nbSeq;701DEBUGLOG(5, "ZSTD_decodeSeqHeaders");702703/* check */704RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");705706/* SeqHead */707nbSeq = *ip++;708if (nbSeq > 0x7F) {709if (nbSeq == 0xFF) {710RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");711nbSeq = MEM_readLE16(ip) + LONGNBSEQ;712ip+=2;713} else {714RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");715nbSeq = ((nbSeq-0x80)<<8) + *ip++;716}717}718*nbSeqPtr = nbSeq;719720if (nbSeq == 0) {721/* No sequence : section ends immediately */722RETURN_ERROR_IF(ip != iend, corruption_detected,723"extraneous data present in the Sequences section");724return (size_t)(ip - istart);725}726727/* FSE table descriptors */728RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */729RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */730{ SymbolEncodingType_e const LLtype = (SymbolEncodingType_e)(*ip >> 6);731SymbolEncodingType_e const OFtype = (SymbolEncodingType_e)((*ip >> 4) & 3);732SymbolEncodingType_e const MLtype = (SymbolEncodingType_e)((*ip >> 2) & 3);733ip++;734735/* Build DTables */736{ size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,737LLtype, MaxLL, LLFSELog,738ip, iend-ip,739LL_base, LL_bits,740LL_defaultDTable, dctx->fseEntropy,741dctx->ddictIsCold, nbSeq,742dctx->workspace, sizeof(dctx->workspace),743ZSTD_DCtx_get_bmi2(dctx));744RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");745ip += llhSize;746}747748{ size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,749OFtype, MaxOff, OffFSELog,750ip, iend-ip,751OF_base, OF_bits,752OF_defaultDTable, dctx->fseEntropy,753dctx->ddictIsCold, nbSeq,754dctx->workspace, sizeof(dctx->workspace),755ZSTD_DCtx_get_bmi2(dctx));756RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");757ip += ofhSize;758}759760{ size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,761MLtype, MaxML, MLFSELog,762ip, iend-ip,763ML_base, ML_bits,764ML_defaultDTable, dctx->fseEntropy,765dctx->ddictIsCold, nbSeq,766dctx->workspace, sizeof(dctx->workspace),767ZSTD_DCtx_get_bmi2(dctx));768RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");769ip += mlhSize;770}771}772773return ip-istart;774}775776777typedef struct {778size_t litLength;779size_t matchLength;780size_t offset;781} seq_t;782783typedef struct {784size_t state;785const ZSTD_seqSymbol* table;786} ZSTD_fseState;787788typedef struct {789BIT_DStream_t DStream;790ZSTD_fseState stateLL;791ZSTD_fseState stateOffb;792ZSTD_fseState stateML;793size_t prevOffset[ZSTD_REP_NUM];794} seqState_t;795796/*! ZSTD_overlapCopy8() :797* Copies 8 bytes from ip to op and updates op and ip where ip <= op.798* If the offset is < 8 then the offset is spread to at least 8 bytes.799*800* Precondition: *ip <= *op801* Postcondition: *op - *op >= 8802*/803HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) {804assert(*ip <= *op);805if (offset < 8) {806/* close range match, overlap */807static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */808static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */809int const sub2 = dec64table[offset];810(*op)[0] = (*ip)[0];811(*op)[1] = (*ip)[1];812(*op)[2] = (*ip)[2];813(*op)[3] = (*ip)[3];814*ip += dec32table[offset];815ZSTD_copy4(*op+4, *ip);816*ip -= sub2;817} else {818ZSTD_copy8(*op, *ip);819}820*ip += 8;821*op += 8;822assert(*op - *ip >= 8);823}824825/*! ZSTD_safecopy() :826* Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer827* and write up to 16 bytes past oend_w (op >= oend_w is allowed).828* This function is only called in the uncommon case where the sequence is near the end of the block. It829* should be fast for a single long sequence, but can be slow for several short sequences.830*831* @param ovtype controls the overlap detection832* - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.833* - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.834* The src buffer must be before the dst buffer.835*/836static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {837ptrdiff_t const diff = op - ip;838BYTE* const oend = op + length;839840assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||841(ovtype == ZSTD_overlap_src_before_dst && diff >= 0));842843if (length < 8) {844/* Handle short lengths. */845while (op < oend) *op++ = *ip++;846return;847}848if (ovtype == ZSTD_overlap_src_before_dst) {849/* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */850assert(length >= 8);851ZSTD_overlapCopy8(&op, &ip, diff);852length -= 8;853assert(op - ip >= 8);854assert(op <= oend);855}856857if (oend <= oend_w) {858/* No risk of overwrite. */859ZSTD_wildcopy(op, ip, length, ovtype);860return;861}862if (op <= oend_w) {863/* Wildcopy until we get close to the end. */864assert(oend > oend_w);865ZSTD_wildcopy(op, ip, oend_w - op, ovtype);866ip += oend_w - op;867op += oend_w - op;868}869/* Handle the leftovers. */870while (op < oend) *op++ = *ip++;871}872873/* ZSTD_safecopyDstBeforeSrc():874* This version allows overlap with dst before src, or handles the non-overlap case with dst after src875* Kept separate from more common ZSTD_safecopy case to avoid performance impact to the safecopy common case */876static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length) {877ptrdiff_t const diff = op - ip;878BYTE* const oend = op + length;879880if (length < 8 || diff > -8) {881/* Handle short lengths, close overlaps, and dst not before src. */882while (op < oend) *op++ = *ip++;883return;884}885886if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) {887ZSTD_wildcopy(op, ip, oend - WILDCOPY_OVERLENGTH - op, ZSTD_no_overlap);888ip += oend - WILDCOPY_OVERLENGTH - op;889op += oend - WILDCOPY_OVERLENGTH - op;890}891892/* Handle the leftovers. */893while (op < oend) *op++ = *ip++;894}895896/* ZSTD_execSequenceEnd():897* This version handles cases that are near the end of the output buffer. It requires898* more careful checks to make sure there is no overflow. By separating out these hard899* and unlikely cases, we can speed up the common cases.900*901* NOTE: This function needs to be fast for a single long sequence, but doesn't need902* to be optimized for many small sequences, since those fall into ZSTD_execSequence().903*/904FORCE_NOINLINE905ZSTD_ALLOW_POINTER_OVERFLOW_ATTR906size_t ZSTD_execSequenceEnd(BYTE* op,907BYTE* const oend, seq_t sequence,908const BYTE** litPtr, const BYTE* const litLimit,909const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)910{911BYTE* const oLitEnd = op + sequence.litLength;912size_t const sequenceLength = sequence.litLength + sequence.matchLength;913const BYTE* const iLitEnd = *litPtr + sequence.litLength;914const BYTE* match = oLitEnd - sequence.offset;915BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;916917/* bounds checks : careful of address space overflow in 32-bit mode */918RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");919RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");920assert(op < op + sequenceLength);921assert(oLitEnd < op + sequenceLength);922923/* copy literals */924ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);925op = oLitEnd;926*litPtr = iLitEnd;927928/* copy Match */929if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {930/* offset beyond prefix */931RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");932match = dictEnd - (prefixStart - match);933if (match + sequence.matchLength <= dictEnd) {934ZSTD_memmove(oLitEnd, match, sequence.matchLength);935return sequenceLength;936}937/* span extDict & currentPrefixSegment */938{ size_t const length1 = dictEnd - match;939ZSTD_memmove(oLitEnd, match, length1);940op = oLitEnd + length1;941sequence.matchLength -= length1;942match = prefixStart;943}944}945ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);946return sequenceLength;947}948949/* ZSTD_execSequenceEndSplitLitBuffer():950* 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.951*/952FORCE_NOINLINE953ZSTD_ALLOW_POINTER_OVERFLOW_ATTR954size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op,955BYTE* const oend, const BYTE* const oend_w, seq_t sequence,956const BYTE** litPtr, const BYTE* const litLimit,957const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)958{959BYTE* const oLitEnd = op + sequence.litLength;960size_t const sequenceLength = sequence.litLength + sequence.matchLength;961const BYTE* const iLitEnd = *litPtr + sequence.litLength;962const BYTE* match = oLitEnd - sequence.offset;963964965/* bounds checks : careful of address space overflow in 32-bit mode */966RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");967RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");968assert(op < op + sequenceLength);969assert(oLitEnd < op + sequenceLength);970971/* copy literals */972RETURN_ERROR_IF(op > *litPtr && op < *litPtr + sequence.litLength, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer");973ZSTD_safecopyDstBeforeSrc(op, *litPtr, sequence.litLength);974op = oLitEnd;975*litPtr = iLitEnd;976977/* copy Match */978if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {979/* offset beyond prefix */980RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");981match = dictEnd - (prefixStart - match);982if (match + sequence.matchLength <= dictEnd) {983ZSTD_memmove(oLitEnd, match, sequence.matchLength);984return sequenceLength;985}986/* span extDict & currentPrefixSegment */987{ size_t const length1 = dictEnd - match;988ZSTD_memmove(oLitEnd, match, length1);989op = oLitEnd + length1;990sequence.matchLength -= length1;991match = prefixStart;992}993}994ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);995return sequenceLength;996}997998HINT_INLINE999ZSTD_ALLOW_POINTER_OVERFLOW_ATTR1000size_t ZSTD_execSequence(BYTE* op,1001BYTE* const oend, seq_t sequence,1002const BYTE** litPtr, const BYTE* const litLimit,1003const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)1004{1005BYTE* const oLitEnd = op + sequence.litLength;1006size_t const sequenceLength = sequence.litLength + sequence.matchLength;1007BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */1008BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */1009const BYTE* const iLitEnd = *litPtr + sequence.litLength;1010const BYTE* match = oLitEnd - sequence.offset;10111012assert(op != NULL /* Precondition */);1013assert(oend_w < oend /* No underflow */);10141015#if defined(__aarch64__)1016/* prefetch sequence starting from match that will be used for copy later */1017PREFETCH_L1(match);1018#endif1019/* Handle edge cases in a slow path:1020* - Read beyond end of literals1021* - Match end is within WILDCOPY_OVERLIMIT of oend1022* - 32-bit mode and the match length overflows1023*/1024if (UNLIKELY(1025iLitEnd > litLimit ||1026oMatchEnd > oend_w ||1027(MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))1028return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);10291030/* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */1031assert(op <= oLitEnd /* No overflow */);1032assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);1033assert(oMatchEnd <= oend /* No underflow */);1034assert(iLitEnd <= litLimit /* Literal length is in bounds */);1035assert(oLitEnd <= oend_w /* Can wildcopy literals */);1036assert(oMatchEnd <= oend_w /* Can wildcopy matches */);10371038/* Copy Literals:1039* Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.1040* We likely don't need the full 32-byte wildcopy.1041*/1042assert(WILDCOPY_OVERLENGTH >= 16);1043ZSTD_copy16(op, (*litPtr));1044if (UNLIKELY(sequence.litLength > 16)) {1045ZSTD_wildcopy(op + 16, (*litPtr) + 16, sequence.litLength - 16, ZSTD_no_overlap);1046}1047op = oLitEnd;1048*litPtr = iLitEnd; /* update for next sequence */10491050/* Copy Match */1051if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {1052/* offset beyond prefix -> go into extDict */1053RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");1054match = dictEnd + (match - prefixStart);1055if (match + sequence.matchLength <= dictEnd) {1056ZSTD_memmove(oLitEnd, match, sequence.matchLength);1057return sequenceLength;1058}1059/* span extDict & currentPrefixSegment */1060{ size_t const length1 = dictEnd - match;1061ZSTD_memmove(oLitEnd, match, length1);1062op = oLitEnd + length1;1063sequence.matchLength -= length1;1064match = prefixStart;1065}1066}1067/* Match within prefix of 1 or more bytes */1068assert(op <= oMatchEnd);1069assert(oMatchEnd <= oend_w);1070assert(match >= prefixStart);1071assert(sequence.matchLength >= 1);10721073/* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy1074* without overlap checking.1075*/1076if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {1077/* We bet on a full wildcopy for matches, since we expect matches to be1078* longer than literals (in general). In silesia, ~10% of matches are longer1079* than 16 bytes.1080*/1081ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);1082return sequenceLength;1083}1084assert(sequence.offset < WILDCOPY_VECLEN);10851086/* Copy 8 bytes and spread the offset to be >= 8. */1087ZSTD_overlapCopy8(&op, &match, sequence.offset);10881089/* If the match length is > 8 bytes, then continue with the wildcopy. */1090if (sequence.matchLength > 8) {1091assert(op < oMatchEnd);1092ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength - 8, ZSTD_overlap_src_before_dst);1093}1094return sequenceLength;1095}10961097HINT_INLINE1098ZSTD_ALLOW_POINTER_OVERFLOW_ATTR1099size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op,1100BYTE* const oend, const BYTE* const oend_w, seq_t sequence,1101const BYTE** litPtr, const BYTE* const litLimit,1102const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)1103{1104BYTE* const oLitEnd = op + sequence.litLength;1105size_t const sequenceLength = sequence.litLength + sequence.matchLength;1106BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */1107const BYTE* const iLitEnd = *litPtr + sequence.litLength;1108const BYTE* match = oLitEnd - sequence.offset;11091110assert(op != NULL /* Precondition */);1111assert(oend_w < oend /* No underflow */);1112/* Handle edge cases in a slow path:1113* - Read beyond end of literals1114* - Match end is within WILDCOPY_OVERLIMIT of oend1115* - 32-bit mode and the match length overflows1116*/1117if (UNLIKELY(1118iLitEnd > litLimit ||1119oMatchEnd > oend_w ||1120(MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))1121return ZSTD_execSequenceEndSplitLitBuffer(op, oend, oend_w, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);11221123/* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */1124assert(op <= oLitEnd /* No overflow */);1125assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);1126assert(oMatchEnd <= oend /* No underflow */);1127assert(iLitEnd <= litLimit /* Literal length is in bounds */);1128assert(oLitEnd <= oend_w /* Can wildcopy literals */);1129assert(oMatchEnd <= oend_w /* Can wildcopy matches */);11301131/* Copy Literals:1132* Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.1133* We likely don't need the full 32-byte wildcopy.1134*/1135assert(WILDCOPY_OVERLENGTH >= 16);1136ZSTD_copy16(op, (*litPtr));1137if (UNLIKELY(sequence.litLength > 16)) {1138ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);1139}1140op = oLitEnd;1141*litPtr = iLitEnd; /* update for next sequence */11421143/* Copy Match */1144if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {1145/* offset beyond prefix -> go into extDict */1146RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");1147match = dictEnd + (match - prefixStart);1148if (match + sequence.matchLength <= dictEnd) {1149ZSTD_memmove(oLitEnd, match, sequence.matchLength);1150return sequenceLength;1151}1152/* span extDict & currentPrefixSegment */1153{ size_t const length1 = dictEnd - match;1154ZSTD_memmove(oLitEnd, match, length1);1155op = oLitEnd + length1;1156sequence.matchLength -= length1;1157match = prefixStart;1158} }1159/* Match within prefix of 1 or more bytes */1160assert(op <= oMatchEnd);1161assert(oMatchEnd <= oend_w);1162assert(match >= prefixStart);1163assert(sequence.matchLength >= 1);11641165/* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy1166* without overlap checking.1167*/1168if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {1169/* We bet on a full wildcopy for matches, since we expect matches to be1170* longer than literals (in general). In silesia, ~10% of matches are longer1171* than 16 bytes.1172*/1173ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);1174return sequenceLength;1175}1176assert(sequence.offset < WILDCOPY_VECLEN);11771178/* Copy 8 bytes and spread the offset to be >= 8. */1179ZSTD_overlapCopy8(&op, &match, sequence.offset);11801181/* If the match length is > 8 bytes, then continue with the wildcopy. */1182if (sequence.matchLength > 8) {1183assert(op < oMatchEnd);1184ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst);1185}1186return sequenceLength;1187}118811891190static void1191ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)1192{1193const void* ptr = dt;1194const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;1195DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);1196DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",1197(U32)DStatePtr->state, DTableH->tableLog);1198BIT_reloadDStream(bitD);1199DStatePtr->table = dt + 1;1200}12011202FORCE_INLINE_TEMPLATE void1203ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, U16 nextState, U32 nbBits)1204{1205size_t const lowBits = BIT_readBits(bitD, nbBits);1206DStatePtr->state = nextState + lowBits;1207}12081209/* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum1210* offset bits. But we can only read at most STREAM_ACCUMULATOR_MIN_321211* bits before reloading. This value is the maximum number of bytes we read1212* after reloading when we are decoding long offsets.1213*/1214#define LONG_OFFSETS_MAX_EXTRA_BITS_32 \1215(ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \1216? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \1217: 0)12181219typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;12201221/**1222* ZSTD_decodeSequence():1223* @p longOffsets : tells the decoder to reload more bit while decoding large offsets1224* only used in 32-bit mode1225* @return : Sequence (litL + matchL + offset)1226*/1227FORCE_INLINE_TEMPLATE seq_t1228ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq)1229{1230seq_t seq;1231/*1232* ZSTD_seqSymbol is a 64 bits wide structure.1233* It can be loaded in one operation1234* and its fields extracted by simply shifting or bit-extracting on aarch64.1235* GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh1236* operations that cause performance drop. This can be avoided by using this1237* ZSTD_memcpy hack.1238*/1239#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__))1240ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS;1241ZSTD_seqSymbol* const llDInfo = &llDInfoS;1242ZSTD_seqSymbol* const mlDInfo = &mlDInfoS;1243ZSTD_seqSymbol* const ofDInfo = &ofDInfoS;1244ZSTD_memcpy(llDInfo, seqState->stateLL.table + seqState->stateLL.state, sizeof(ZSTD_seqSymbol));1245ZSTD_memcpy(mlDInfo, seqState->stateML.table + seqState->stateML.state, sizeof(ZSTD_seqSymbol));1246ZSTD_memcpy(ofDInfo, seqState->stateOffb.table + seqState->stateOffb.state, sizeof(ZSTD_seqSymbol));1247#else1248const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state;1249const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state;1250const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state;1251#endif1252seq.matchLength = mlDInfo->baseValue;1253seq.litLength = llDInfo->baseValue;1254{ U32 const ofBase = ofDInfo->baseValue;1255BYTE const llBits = llDInfo->nbAdditionalBits;1256BYTE const mlBits = mlDInfo->nbAdditionalBits;1257BYTE const ofBits = ofDInfo->nbAdditionalBits;1258BYTE const totalBits = llBits+mlBits+ofBits;12591260U16 const llNext = llDInfo->nextState;1261U16 const mlNext = mlDInfo->nextState;1262U16 const ofNext = ofDInfo->nextState;1263U32 const llnbBits = llDInfo->nbBits;1264U32 const mlnbBits = mlDInfo->nbBits;1265U32 const ofnbBits = ofDInfo->nbBits;12661267assert(llBits <= MaxLLBits);1268assert(mlBits <= MaxMLBits);1269assert(ofBits <= MaxOff);1270/*1271* As gcc has better branch and block analyzers, sometimes it is only1272* valuable to mark likeliness for clang, it gives around 3-4% of1273* performance.1274*/12751276/* sequence */1277{ size_t offset;1278if (ofBits > 1) {1279ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);1280ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);1281ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32);1282ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits);1283if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {1284/* Always read extra bits, this keeps the logic simple,1285* avoids branches, and avoids accidentally reading 0 bits.1286*/1287U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32;1288offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);1289BIT_reloadDStream(&seqState->DStream);1290offset += BIT_readBitsFast(&seqState->DStream, extraBits);1291} else {1292offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */1293if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);1294}1295seqState->prevOffset[2] = seqState->prevOffset[1];1296seqState->prevOffset[1] = seqState->prevOffset[0];1297seqState->prevOffset[0] = offset;1298} else {1299U32 const ll0 = (llDInfo->baseValue == 0);1300if (LIKELY((ofBits == 0))) {1301offset = seqState->prevOffset[ll0];1302seqState->prevOffset[1] = seqState->prevOffset[!ll0];1303seqState->prevOffset[0] = offset;1304} else {1305offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);1306{ size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];1307temp -= !temp; /* 0 is not valid: input corrupted => force offset to -1 => corruption detected at execSequence */1308if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];1309seqState->prevOffset[1] = seqState->prevOffset[0];1310seqState->prevOffset[0] = offset = temp;1311} } }1312seq.offset = offset;1313}13141315if (mlBits > 0)1316seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);13171318if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))1319BIT_reloadDStream(&seqState->DStream);1320if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))1321BIT_reloadDStream(&seqState->DStream);1322/* Ensure there are enough bits to read the rest of data in 64-bit mode. */1323ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);13241325if (llBits > 0)1326seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);13271328if (MEM_32bits())1329BIT_reloadDStream(&seqState->DStream);13301331DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",1332(U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);13331334if (!isLastSeq) {1335/* don't update FSE state for last Sequence */1336ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */1337ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */1338if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */1339ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */1340BIT_reloadDStream(&seqState->DStream);1341}1342}13431344return seq;1345}13461347#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1348#if DEBUGLEVEL >= 11349static int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)1350{1351size_t const windowSize = dctx->fParams.windowSize;1352/* No dictionary used. */1353if (dctx->dictContentEndForFuzzing == NULL) return 0;1354/* Dictionary is our prefix. */1355if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;1356/* Dictionary is not our ext-dict. */1357if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;1358/* Dictionary is not within our window size. */1359if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;1360/* Dictionary is active. */1361return 1;1362}1363#endif13641365static void ZSTD_assertValidSequence(1366ZSTD_DCtx const* dctx,1367BYTE const* op, BYTE const* oend,1368seq_t const seq,1369BYTE const* prefixStart, BYTE const* virtualStart)1370{1371#if DEBUGLEVEL >= 11372if (dctx->isFrameDecompression) {1373size_t const windowSize = dctx->fParams.windowSize;1374size_t const sequenceSize = seq.litLength + seq.matchLength;1375BYTE const* const oLitEnd = op + seq.litLength;1376DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",1377(U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);1378assert(op <= oend);1379assert((size_t)(oend - op) >= sequenceSize);1380assert(sequenceSize <= ZSTD_blockSizeMax(dctx));1381if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {1382size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);1383/* Offset must be within the dictionary. */1384assert(seq.offset <= (size_t)(oLitEnd - virtualStart));1385assert(seq.offset <= windowSize + dictSize);1386} else {1387/* Offset must be within our window. */1388assert(seq.offset <= windowSize);1389}1390}1391#else1392(void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;1393#endif1394}1395#endif13961397#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG139813991400FORCE_INLINE_TEMPLATE size_t1401DONT_VECTORIZE1402ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,1403void* dst, size_t maxDstSize,1404const void* seqStart, size_t seqSize, int nbSeq,1405const ZSTD_longOffset_e isLongOffset)1406{1407const BYTE* ip = (const BYTE*)seqStart;1408const BYTE* const iend = ip + seqSize;1409BYTE* const ostart = (BYTE*)dst;1410BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, maxDstSize);1411BYTE* op = ostart;1412const BYTE* litPtr = dctx->litPtr;1413const BYTE* litBufferEnd = dctx->litBufferEnd;1414const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);1415const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);1416const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);1417DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq);14181419/* Literals are split between internal buffer & output buffer */1420if (nbSeq) {1421seqState_t seqState;1422dctx->fseEntropy = 1;1423{ U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }1424RETURN_ERROR_IF(1425ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),1426corruption_detected, "");1427ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);1428ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);1429ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);1430assert(dst != NULL);14311432ZSTD_STATIC_ASSERT(1433BIT_DStream_unfinished < BIT_DStream_completed &&1434BIT_DStream_endOfBuffer < BIT_DStream_completed &&1435BIT_DStream_completed < BIT_DStream_overflow);14361437/* decompress without overrunning litPtr begins */1438{ 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) */1439/* Align the decompression loop to 32 + 16 bytes.1440*1441* zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression1442* speed swings based on the alignment of the decompression loop. This1443* performance swing is caused by parts of the decompression loop falling1444* out of the DSB. The entire decompression loop should fit in the DSB,1445* when it can't we get much worse performance. You can measure if you've1446* hit the good case or the bad case with this perf command for some1447* compressed file test.zst:1448*1449* perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \1450* -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst1451*1452* If you see most cycles served out of the MITE you've hit the bad case.1453* If you see most cycles served out of the DSB you've hit the good case.1454* If it is pretty even then you may be in an okay case.1455*1456* This issue has been reproduced on the following CPUs:1457* - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i91458* Use Instruments->Counters to get DSB/MITE cycles.1459* I never got performance swings, but I was able to1460* go from the good case of mostly DSB to half of the1461* cycles served from MITE.1462* - Coffeelake: Intel i9-9900k1463* - Coffeelake: Intel i7-9700k1464*1465* I haven't been able to reproduce the instability or DSB misses on any1466* of the following CPUS:1467* - Haswell1468* - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH1469* - Skylake1470*1471* Alignment is done for each of the three major decompression loops:1472* - ZSTD_decompressSequences_bodySplitLitBuffer - presplit section of the literal buffer1473* - ZSTD_decompressSequences_bodySplitLitBuffer - postsplit section of the literal buffer1474* - ZSTD_decompressSequences_body1475* Alignment choices are made to minimize large swings on bad cases and influence on performance1476* from changes external to this code, rather than to overoptimize on the current commit.1477*1478* If you are seeing performance stability this script can help test.1479* It tests on 4 commits in zstd where I saw performance change.1480*1481* https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f41482*/1483#if defined(__GNUC__) && defined(__x86_64__)1484__asm__(".p2align 6");1485# if __GNUC__ >= 71486/* good for gcc-7, gcc-9, and gcc-11 */1487__asm__("nop");1488__asm__(".p2align 5");1489__asm__("nop");1490__asm__(".p2align 4");1491# if __GNUC__ == 8 || __GNUC__ == 101492/* good for gcc-8 and gcc-10 */1493__asm__("nop");1494__asm__(".p2align 3");1495# endif1496# endif1497#endif14981499/* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */1500for ( ; nbSeq; nbSeq--) {1501sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);1502if (litPtr + sequence.litLength > dctx->litBufferEnd) break;1503{ size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);1504#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1505assert(!ZSTD_isError(oneSeqSize));1506ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);1507#endif1508if (UNLIKELY(ZSTD_isError(oneSeqSize)))1509return oneSeqSize;1510DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);1511op += oneSeqSize;1512} }1513DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)");15141515/* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */1516if (nbSeq > 0) {1517const size_t leftoverLit = dctx->litBufferEnd - litPtr;1518DEBUGLOG(6, "There are %i sequences left, and %zu/%zu literals left in buffer", nbSeq, leftoverLit, sequence.litLength);1519if (leftoverLit) {1520RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");1521ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);1522sequence.litLength -= leftoverLit;1523op += leftoverLit;1524}1525litPtr = dctx->litExtraBuffer;1526litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;1527dctx->litBufferLocation = ZSTD_not_in_dst;1528{ size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);1529#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1530assert(!ZSTD_isError(oneSeqSize));1531ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);1532#endif1533if (UNLIKELY(ZSTD_isError(oneSeqSize)))1534return oneSeqSize;1535DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);1536op += oneSeqSize;1537}1538nbSeq--;1539}1540}15411542if (nbSeq > 0) {1543/* there is remaining lit from extra buffer */15441545#if defined(__GNUC__) && defined(__x86_64__)1546__asm__(".p2align 6");1547__asm__("nop");1548# if __GNUC__ != 71549/* worse for gcc-7 better for gcc-8, gcc-9, and gcc-10 and clang */1550__asm__(".p2align 4");1551__asm__("nop");1552__asm__(".p2align 3");1553# elif __GNUC__ >= 111554__asm__(".p2align 3");1555# else1556__asm__(".p2align 5");1557__asm__("nop");1558__asm__(".p2align 3");1559# endif1560#endif15611562for ( ; nbSeq ; nbSeq--) {1563seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);1564size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);1565#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1566assert(!ZSTD_isError(oneSeqSize));1567ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);1568#endif1569if (UNLIKELY(ZSTD_isError(oneSeqSize)))1570return oneSeqSize;1571DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);1572op += oneSeqSize;1573}1574}15751576/* check if reached exact end */1577DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq);1578RETURN_ERROR_IF(nbSeq, corruption_detected, "");1579DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed);1580RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");1581/* save reps for next block */1582{ U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }1583}15841585/* last literal segment */1586if (dctx->litBufferLocation == ZSTD_split) {1587/* split hasn't been reached yet, first get dst then copy litExtraBuffer */1588size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);1589DEBUGLOG(6, "copy last literals from segment : %u", (U32)lastLLSize);1590RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");1591if (op != NULL) {1592ZSTD_memmove(op, litPtr, lastLLSize);1593op += lastLLSize;1594}1595litPtr = dctx->litExtraBuffer;1596litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;1597dctx->litBufferLocation = ZSTD_not_in_dst;1598}1599/* copy last literals from internal buffer */1600{ size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);1601DEBUGLOG(6, "copy last literals from internal buffer : %u", (U32)lastLLSize);1602RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");1603if (op != NULL) {1604ZSTD_memcpy(op, litPtr, lastLLSize);1605op += lastLLSize;1606} }16071608DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));1609return (size_t)(op - ostart);1610}16111612FORCE_INLINE_TEMPLATE size_t1613DONT_VECTORIZE1614ZSTD_decompressSequences_body(ZSTD_DCtx* dctx,1615void* dst, size_t maxDstSize,1616const void* seqStart, size_t seqSize, int nbSeq,1617const ZSTD_longOffset_e isLongOffset)1618{1619const BYTE* ip = (const BYTE*)seqStart;1620const BYTE* const iend = ip + seqSize;1621BYTE* const ostart = (BYTE*)dst;1622BYTE* const oend = dctx->litBufferLocation == ZSTD_not_in_dst ? ZSTD_maybeNullPtrAdd(ostart, maxDstSize) : dctx->litBuffer;1623BYTE* op = ostart;1624const BYTE* litPtr = dctx->litPtr;1625const BYTE* const litEnd = litPtr + dctx->litSize;1626const BYTE* const prefixStart = (const BYTE*)(dctx->prefixStart);1627const BYTE* const vBase = (const BYTE*)(dctx->virtualStart);1628const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd);1629DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq);16301631/* Regen sequences */1632if (nbSeq) {1633seqState_t seqState;1634dctx->fseEntropy = 1;1635{ U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }1636RETURN_ERROR_IF(1637ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend - ip)),1638corruption_detected, "");1639ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);1640ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);1641ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);1642assert(dst != NULL);16431644#if defined(__GNUC__) && defined(__x86_64__)1645__asm__(".p2align 6");1646__asm__("nop");1647# if __GNUC__ >= 71648__asm__(".p2align 5");1649__asm__("nop");1650__asm__(".p2align 3");1651# else1652__asm__(".p2align 4");1653__asm__("nop");1654__asm__(".p2align 3");1655# endif1656#endif16571658for ( ; nbSeq ; nbSeq--) {1659seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1);1660size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);1661#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1662assert(!ZSTD_isError(oneSeqSize));1663ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);1664#endif1665if (UNLIKELY(ZSTD_isError(oneSeqSize)))1666return oneSeqSize;1667DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);1668op += oneSeqSize;1669}16701671/* check if reached exact end */1672assert(nbSeq == 0);1673RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");1674/* save reps for next block */1675{ U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }1676}16771678/* last literal segment */1679{ size_t const lastLLSize = (size_t)(litEnd - litPtr);1680DEBUGLOG(6, "copy last literals : %u", (U32)lastLLSize);1681RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");1682if (op != NULL) {1683ZSTD_memcpy(op, litPtr, lastLLSize);1684op += lastLLSize;1685} }16861687DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));1688return (size_t)(op - ostart);1689}16901691static size_t1692ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,1693void* dst, size_t maxDstSize,1694const void* seqStart, size_t seqSize, int nbSeq,1695const ZSTD_longOffset_e isLongOffset)1696{1697return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1698}16991700static size_t1701ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx,1702void* dst, size_t maxDstSize,1703const void* seqStart, size_t seqSize, int nbSeq,1704const ZSTD_longOffset_e isLongOffset)1705{1706return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1707}1708#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */17091710#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT17111712FORCE_INLINE_TEMPLATE17131714size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,1715const BYTE* const prefixStart, const BYTE* const dictEnd)1716{1717prefetchPos += sequence.litLength;1718{ const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;1719/* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.1720* No consequence though : memory address is only used for prefetching, not for dereferencing */1721const BYTE* const match = ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, prefetchPos), sequence.offset);1722PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */1723}1724return prefetchPos + sequence.matchLength;1725}17261727/* This decoding function employs prefetching1728* to reduce latency impact of cache misses.1729* It's generally employed when block contains a significant portion of long-distance matches1730* or when coupled with a "cold" dictionary */1731FORCE_INLINE_TEMPLATE size_t1732ZSTD_decompressSequencesLong_body(1733ZSTD_DCtx* dctx,1734void* dst, size_t maxDstSize,1735const void* seqStart, size_t seqSize, int nbSeq,1736const ZSTD_longOffset_e isLongOffset)1737{1738const BYTE* ip = (const BYTE*)seqStart;1739const BYTE* const iend = ip + seqSize;1740BYTE* const ostart = (BYTE*)dst;1741BYTE* const oend = dctx->litBufferLocation == ZSTD_in_dst ? dctx->litBuffer : ZSTD_maybeNullPtrAdd(ostart, maxDstSize);1742BYTE* op = ostart;1743const BYTE* litPtr = dctx->litPtr;1744const BYTE* litBufferEnd = dctx->litBufferEnd;1745const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);1746const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);1747const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);17481749/* Regen sequences */1750if (nbSeq) {1751#define STORED_SEQS 81752#define STORED_SEQS_MASK (STORED_SEQS-1)1753#define ADVANCED_SEQS STORED_SEQS1754seq_t sequences[STORED_SEQS];1755int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);1756seqState_t seqState;1757int seqNb;1758size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */17591760dctx->fseEntropy = 1;1761{ int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }1762assert(dst != NULL);1763assert(iend >= ip);1764RETURN_ERROR_IF(1765ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),1766corruption_detected, "");1767ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);1768ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);1769ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);17701771/* prepare in advance */1772for (seqNb=0; seqNb<seqAdvance; seqNb++) {1773seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);1774prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);1775sequences[seqNb] = sequence;1776}17771778/* decompress without stomping litBuffer */1779for (; seqNb < nbSeq; seqNb++) {1780seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, seqNb == nbSeq-1);17811782if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) {1783/* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */1784const size_t leftoverLit = dctx->litBufferEnd - litPtr;1785if (leftoverLit)1786{1787RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");1788ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);1789sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;1790op += leftoverLit;1791}1792litPtr = dctx->litExtraBuffer;1793litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;1794dctx->litBufferLocation = ZSTD_not_in_dst;1795{ size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);1796#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1797assert(!ZSTD_isError(oneSeqSize));1798ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);1799#endif1800if (ZSTD_isError(oneSeqSize)) return oneSeqSize;18011802prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);1803sequences[seqNb & STORED_SEQS_MASK] = sequence;1804op += oneSeqSize;1805} }1806else1807{1808/* lit buffer is either wholly contained in first or second split, or not split at all*/1809size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?1810ZSTD_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) :1811ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);1812#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1813assert(!ZSTD_isError(oneSeqSize));1814ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);1815#endif1816if (ZSTD_isError(oneSeqSize)) return oneSeqSize;18171818prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);1819sequences[seqNb & STORED_SEQS_MASK] = sequence;1820op += oneSeqSize;1821}1822}1823RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, "");18241825/* finish queue */1826seqNb -= seqAdvance;1827for ( ; seqNb<nbSeq ; seqNb++) {1828seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);1829if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) {1830const size_t leftoverLit = dctx->litBufferEnd - litPtr;1831if (leftoverLit) {1832RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");1833ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);1834sequence->litLength -= leftoverLit;1835op += leftoverLit;1836}1837litPtr = dctx->litExtraBuffer;1838litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;1839dctx->litBufferLocation = ZSTD_not_in_dst;1840{ size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);1841#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1842assert(!ZSTD_isError(oneSeqSize));1843ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);1844#endif1845if (ZSTD_isError(oneSeqSize)) return oneSeqSize;1846op += oneSeqSize;1847}1848}1849else1850{1851size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?1852ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :1853ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);1854#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)1855assert(!ZSTD_isError(oneSeqSize));1856ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);1857#endif1858if (ZSTD_isError(oneSeqSize)) return oneSeqSize;1859op += oneSeqSize;1860}1861}18621863/* save reps for next block */1864{ U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }1865}18661867/* last literal segment */1868if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */1869size_t const lastLLSize = litBufferEnd - litPtr;1870RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");1871if (op != NULL) {1872ZSTD_memmove(op, litPtr, lastLLSize);1873op += lastLLSize;1874}1875litPtr = dctx->litExtraBuffer;1876litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;1877}1878{ size_t const lastLLSize = litBufferEnd - litPtr;1879RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");1880if (op != NULL) {1881ZSTD_memmove(op, litPtr, lastLLSize);1882op += lastLLSize;1883}1884}18851886return (size_t)(op - ostart);1887}18881889static size_t1890ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,1891void* dst, size_t maxDstSize,1892const void* seqStart, size_t seqSize, int nbSeq,1893const ZSTD_longOffset_e isLongOffset)1894{1895return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1896}1897#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */1898189919001901#if DYNAMIC_BMI219021903#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG1904static BMI2_TARGET_ATTRIBUTE size_t1905DONT_VECTORIZE1906ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,1907void* dst, size_t maxDstSize,1908const void* seqStart, size_t seqSize, int nbSeq,1909const ZSTD_longOffset_e isLongOffset)1910{1911return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1912}1913static BMI2_TARGET_ATTRIBUTE size_t1914DONT_VECTORIZE1915ZSTD_decompressSequencesSplitLitBuffer_bmi2(ZSTD_DCtx* dctx,1916void* dst, size_t maxDstSize,1917const void* seqStart, size_t seqSize, int nbSeq,1918const ZSTD_longOffset_e isLongOffset)1919{1920return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1921}1922#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */19231924#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT1925static BMI2_TARGET_ATTRIBUTE size_t1926ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,1927void* dst, size_t maxDstSize,1928const void* seqStart, size_t seqSize, int nbSeq,1929const ZSTD_longOffset_e isLongOffset)1930{1931return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1932}1933#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */19341935#endif /* DYNAMIC_BMI2 */19361937#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG1938static size_t1939ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,1940const void* seqStart, size_t seqSize, int nbSeq,1941const ZSTD_longOffset_e isLongOffset)1942{1943DEBUGLOG(5, "ZSTD_decompressSequences");1944#if DYNAMIC_BMI21945if (ZSTD_DCtx_get_bmi2(dctx)) {1946return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1947}1948#endif1949return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1950}1951static size_t1952ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,1953const void* seqStart, size_t seqSize, int nbSeq,1954const ZSTD_longOffset_e isLongOffset)1955{1956DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer");1957#if DYNAMIC_BMI21958if (ZSTD_DCtx_get_bmi2(dctx)) {1959return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1960}1961#endif1962return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1963}1964#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */196519661967#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT1968/* ZSTD_decompressSequencesLong() :1969* decompression function triggered when a minimum share of offsets is considered "long",1970* aka out of cache.1971* note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".1972* This function will try to mitigate main memory latency through the use of prefetching */1973static size_t1974ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,1975void* dst, size_t maxDstSize,1976const void* seqStart, size_t seqSize, int nbSeq,1977const ZSTD_longOffset_e isLongOffset)1978{1979DEBUGLOG(5, "ZSTD_decompressSequencesLong");1980#if DYNAMIC_BMI21981if (ZSTD_DCtx_get_bmi2(dctx)) {1982return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1983}1984#endif1985return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);1986}1987#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */198819891990/**1991* @returns The total size of the history referenceable by zstd, including1992* both the prefix and the extDict. At @p op any offset larger than this1993* is invalid.1994*/1995static size_t ZSTD_totalHistorySize(BYTE* op, BYTE const* virtualStart)1996{1997return (size_t)(op - virtualStart);1998}19992000typedef struct {2001unsigned longOffsetShare;2002unsigned maxNbAdditionalBits;2003} ZSTD_OffsetInfo;20042005/* ZSTD_getOffsetInfo() :2006* condition : offTable must be valid2007* @return : "share" of long offsets (arbitrarily defined as > (1<<23))2008* compared to maximum possible of (1<<OffFSELog),2009* as well as the maximum number additional bits required.2010*/2011static ZSTD_OffsetInfo2012ZSTD_getOffsetInfo(const ZSTD_seqSymbol* offTable, int nbSeq)2013{2014ZSTD_OffsetInfo info = {0, 0};2015/* If nbSeq == 0, then the offTable is uninitialized, but we have2016* no sequences, so both values should be 0.2017*/2018if (nbSeq != 0) {2019const void* ptr = offTable;2020U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;2021const ZSTD_seqSymbol* table = offTable + 1;2022U32 const max = 1 << tableLog;2023U32 u;2024DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);20252026assert(max <= (1 << OffFSELog)); /* max not too large */2027for (u=0; u<max; u++) {2028info.maxNbAdditionalBits = MAX(info.maxNbAdditionalBits, table[u].nbAdditionalBits);2029if (table[u].nbAdditionalBits > 22) info.longOffsetShare += 1;2030}20312032assert(tableLog <= OffFSELog);2033info.longOffsetShare <<= (OffFSELog - tableLog); /* scale to OffFSELog */2034}20352036return info;2037}20382039/**2040* @returns The maximum offset we can decode in one read of our bitstream, without2041* reloading more bits in the middle of the offset bits read. Any offsets larger2042* than this must use the long offset decoder.2043*/2044static size_t ZSTD_maxShortOffset(void)2045{2046if (MEM_64bits()) {2047/* We can decode any offset without reloading bits.2048* This might change if the max window size grows.2049*/2050ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);2051return (size_t)-1;2052} else {2053/* The maximum offBase is (1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1.2054* This offBase would require STREAM_ACCUMULATOR_MIN extra bits.2055* Then we have to subtract ZSTD_REP_NUM to get the maximum possible offset.2056*/2057size_t const maxOffbase = ((size_t)1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1;2058size_t const maxOffset = maxOffbase - ZSTD_REP_NUM;2059assert(ZSTD_highbit32((U32)maxOffbase) == STREAM_ACCUMULATOR_MIN);2060return maxOffset;2061}2062}20632064size_t2065ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,2066void* dst, size_t dstCapacity,2067const void* src, size_t srcSize, const streaming_operation streaming)2068{ /* blockType == blockCompressed */2069const BYTE* ip = (const BYTE*)src;2070DEBUGLOG(5, "ZSTD_decompressBlock_internal (cSize : %u)", (unsigned)srcSize);20712072/* Note : the wording of the specification2073* allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx).2074* This generally does not happen, as it makes little sense,2075* since an uncompressed block would feature same size and have no decompression cost.2076* Also, note that decoder from reference libzstd before < v1.5.42077* would consider this edge case as an error.2078* As a consequence, avoid generating compressed blocks of size ZSTD_blockSizeMax(dctx)2079* for broader compatibility with the deployed ecosystem of zstd decoders */2080RETURN_ERROR_IF(srcSize > ZSTD_blockSizeMax(dctx), srcSize_wrong, "");20812082/* Decode literals section */2083{ size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming);2084DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : cSize=%u, nbLiterals=%zu", (U32)litCSize, dctx->litSize);2085if (ZSTD_isError(litCSize)) return litCSize;2086ip += litCSize;2087srcSize -= litCSize;2088}20892090/* Build Decoding Tables */2091{2092/* Compute the maximum block size, which must also work when !frame and fParams are unset.2093* Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t.2094*/2095size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx));2096size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd((BYTE*)dst, blockSizeMax), (BYTE const*)dctx->virtualStart);2097/* isLongOffset must be true if there are long offsets.2098* Offsets are long if they are larger than ZSTD_maxShortOffset().2099* We don't expect that to be the case in 64-bit mode.2100*2101* We check here to see if our history is large enough to allow long offsets.2102* If it isn't, then we can't possible have (valid) long offsets. If the offset2103* is invalid, then it is okay to read it incorrectly.2104*2105* If isLongOffsets is true, then we will later check our decoding table to see2106* if it is even possible to generate long offsets.2107*/2108ZSTD_longOffset_e isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (totalHistorySize > ZSTD_maxShortOffset()));2109/* These macros control at build-time which decompressor implementation2110* we use. If neither is defined, we do some inspection and dispatch at2111* runtime.2112*/2113#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \2114!defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)2115int usePrefetchDecoder = dctx->ddictIsCold;2116#else2117/* Set to 1 to avoid computing offset info if we don't need to.2118* Otherwise this value is ignored.2119*/2120int usePrefetchDecoder = 1;2121#endif2122int nbSeq;2123size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);2124if (ZSTD_isError(seqHSize)) return seqHSize;2125ip += seqHSize;2126srcSize -= seqHSize;21272128RETURN_ERROR_IF((dst == NULL || dstCapacity == 0) && nbSeq > 0, dstSize_tooSmall, "NULL not handled");2129RETURN_ERROR_IF(MEM_64bits() && sizeof(size_t) == sizeof(void*) && (size_t)(-1) - (size_t)dst < (size_t)(1 << 20), dstSize_tooSmall,2130"invalid dst");21312132/* If we could potentially have long offsets, or we might want to use the prefetch decoder,2133* compute information about the share of long offsets, and the maximum nbAdditionalBits.2134* NOTE: could probably use a larger nbSeq limit2135*/2136if (isLongOffset || (!usePrefetchDecoder && (totalHistorySize > (1u << 24)) && (nbSeq > 8))) {2137ZSTD_OffsetInfo const info = ZSTD_getOffsetInfo(dctx->OFTptr, nbSeq);2138if (isLongOffset && info.maxNbAdditionalBits <= STREAM_ACCUMULATOR_MIN) {2139/* If isLongOffset, but the maximum number of additional bits that we see in our table is small2140* enough, then we know it is impossible to have too long an offset in this block, so we can2141* use the regular offset decoder.2142*/2143isLongOffset = ZSTD_lo_isRegularOffset;2144}2145if (!usePrefetchDecoder) {2146U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */2147usePrefetchDecoder = (info.longOffsetShare >= minShare);2148}2149}21502151dctx->ddictIsCold = 0;21522153#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \2154!defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)2155if (usePrefetchDecoder) {2156#else2157(void)usePrefetchDecoder;2158{2159#endif2160#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT2161return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);2162#endif2163}21642165#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG2166/* else */2167if (dctx->litBufferLocation == ZSTD_split)2168return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);2169else2170return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);2171#endif2172}2173}217421752176ZSTD_ALLOW_POINTER_OVERFLOW_ATTR2177void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)2178{2179if (dst != dctx->previousDstEnd && dstSize > 0) { /* not contiguous */2180dctx->dictEnd = dctx->previousDstEnd;2181dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));2182dctx->prefixStart = dst;2183dctx->previousDstEnd = dst;2184}2185}218621872188size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx,2189void* dst, size_t dstCapacity,2190const void* src, size_t srcSize)2191{2192size_t dSize;2193dctx->isFrameDecompression = 0;2194ZSTD_checkContinuity(dctx, dst, dstCapacity);2195dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, not_streaming);2196FORWARD_IF_ERROR(dSize, "");2197dctx->previousDstEnd = (char*)dst + dSize;2198return dSize;2199}220022012202/* NOTE: Must just wrap ZSTD_decompressBlock_deprecated() */2203size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,2204void* dst, size_t dstCapacity,2205const void* src, size_t srcSize)2206{2207return ZSTD_decompressBlock_deprecated(dctx, dst, dstCapacity, src, srcSize);2208}220922102211