Path: blob/main/sys/contrib/openzfs/module/zstd/lib/decompress/zstd_decompress.c
48774 views
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-only1/*2* Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.3* All rights reserved.4*5* This source code is licensed under both the BSD-style license (found in the6* LICENSE file in the root directory of this source tree) and the GPLv2 (found7* 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*/101112/* ***************************************************************13* Tuning parameters14*****************************************************************/15/*!16* HEAPMODE :17* Select how default decompression function ZSTD_decompress() allocates its context,18* on stack (0), or into heap (1, default; requires malloc()).19* Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.20*/21#ifndef ZSTD_HEAPMODE22# define ZSTD_HEAPMODE 123#endif2425/*!26* LEGACY_SUPPORT :27* if set to 1+, ZSTD_decompress() can decode older formats (v0.1+)28*/29#ifndef ZSTD_LEGACY_SUPPORT30# define ZSTD_LEGACY_SUPPORT 031#endif3233/*!34* MAXWINDOWSIZE_DEFAULT :35* maximum window size accepted by DStream __by default__.36* Frames requiring more memory will be rejected.37* It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize().38*/39#ifndef ZSTD_MAXWINDOWSIZE_DEFAULT40# define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1)41#endif4243/*!44* NO_FORWARD_PROGRESS_MAX :45* maximum allowed nb of calls to ZSTD_decompressStream()46* without any forward progress47* (defined as: no byte read from input, and no byte flushed to output)48* before triggering an error.49*/50#ifndef ZSTD_NO_FORWARD_PROGRESS_MAX51# define ZSTD_NO_FORWARD_PROGRESS_MAX 1652#endif535455/*-*******************************************************56* Dependencies57*********************************************************/58#include <string.h> /* memcpy, memmove, memset */59#include "../common/cpu.h" /* bmi2 */60#include "../common/mem.h" /* low level memory routines */61#define FSE_STATIC_LINKING_ONLY62#include "../common/fse.h"63#define HUF_STATIC_LINKING_ONLY64#include "../common/huf.h"65#include "../common/zstd_internal.h" /* blockProperties_t */66#include "zstd_decompress_internal.h" /* ZSTD_DCtx */67#include "zstd_ddict.h" /* ZSTD_DDictDictContent */68#include "zstd_decompress_block.h" /* ZSTD_decompressBlock_internal */6970#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)71# include "../legacy/zstd_legacy.h"72#endif737475/*-*************************************************************76* Context management77***************************************************************/78size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)79{80if (dctx==NULL) return 0; /* support sizeof NULL */81return sizeof(*dctx)82+ ZSTD_sizeof_DDict(dctx->ddictLocal)83+ dctx->inBuffSize + dctx->outBuffSize;84}8586size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }878889static size_t ZSTD_startingInputLength(ZSTD_format_e format)90{91size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format);92/* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */93assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );94return startingInputLength;95}9697static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)98{99dctx->format = ZSTD_f_zstd1; /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */100dctx->staticSize = 0;101dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;102dctx->ddict = NULL;103dctx->ddictLocal = NULL;104dctx->dictEnd = NULL;105dctx->ddictIsCold = 0;106dctx->dictUses = ZSTD_dont_use;107dctx->inBuff = NULL;108dctx->inBuffSize = 0;109dctx->outBuffSize = 0;110dctx->streamStage = zdss_init;111dctx->legacyContext = NULL;112dctx->previousLegacyVersion = 0;113dctx->noForwardProgress = 0;114dctx->oversizedDuration = 0;115dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());116dctx->outBufferMode = ZSTD_obm_buffered;117#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION118dctx->dictContentEndForFuzzing = NULL;119#endif120}121122ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)123{124ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace;125126if ((size_t)workspace & 7) return NULL; /* 8-aligned */127if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */128129ZSTD_initDCtx_internal(dctx);130dctx->staticSize = workspaceSize;131dctx->inBuff = (char*)(dctx+1);132return dctx;133}134135ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)136{137if (!customMem.customAlloc ^ !customMem.customFree) return NULL;138139{ ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem);140if (!dctx) return NULL;141dctx->customMem = customMem;142ZSTD_initDCtx_internal(dctx);143return dctx;144}145}146147ZSTD_DCtx* ZSTD_createDCtx(void)148{149DEBUGLOG(3, "ZSTD_createDCtx");150return ZSTD_createDCtx_advanced(ZSTD_defaultCMem);151}152153static void ZSTD_clearDict(ZSTD_DCtx* dctx)154{155ZSTD_freeDDict(dctx->ddictLocal);156dctx->ddictLocal = NULL;157dctx->ddict = NULL;158dctx->dictUses = ZSTD_dont_use;159}160161size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)162{163if (dctx==NULL) return 0; /* support free on NULL */164RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx");165{ ZSTD_customMem const cMem = dctx->customMem;166ZSTD_clearDict(dctx);167ZSTD_free(dctx->inBuff, cMem);168dctx->inBuff = NULL;169#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)170if (dctx->legacyContext)171ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);172#endif173ZSTD_free(dctx, cMem);174return 0;175}176}177178/* no longer useful */179void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)180{181size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);182memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */183}184185186/*-*************************************************************187* Frame header decoding188***************************************************************/189190/*! ZSTD_isFrame() :191* Tells if the content of `buffer` starts with a valid Frame Identifier.192* Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.193* Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.194* Note 3 : Skippable Frame Identifiers are considered valid. */195unsigned ZSTD_isFrame(const void* buffer, size_t size)196{197if (size < ZSTD_FRAMEIDSIZE) return 0;198{ U32 const magic = MEM_readLE32(buffer);199if (magic == ZSTD_MAGICNUMBER) return 1;200if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;201}202#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)203if (ZSTD_isLegacy(buffer, size)) return 1;204#endif205return 0;206}207208/** ZSTD_frameHeaderSize_internal() :209* srcSize must be large enough to reach header size fields.210* note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.211* @return : size of the Frame Header212* or an error code, which can be tested with ZSTD_isError() */213static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format)214{215size_t const minInputSize = ZSTD_startingInputLength(format);216RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, "");217218{ BYTE const fhd = ((const BYTE*)src)[minInputSize-1];219U32 const dictID= fhd & 3;220U32 const singleSegment = (fhd >> 5) & 1;221U32 const fcsId = fhd >> 6;222return minInputSize + !singleSegment223+ ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]224+ (singleSegment && !fcsId);225}226}227228/** ZSTD_frameHeaderSize() :229* srcSize must be >= ZSTD_frameHeaderSize_prefix.230* @return : size of the Frame Header,231* or an error code (if srcSize is too small) */232size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)233{234return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1);235}236237238/** ZSTD_getFrameHeader_advanced() :239* decode Frame Header, or require larger `srcSize`.240* note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless241* @return : 0, `zfhPtr` is correctly filled,242* >0, `srcSize` is too small, value is wanted `srcSize` amount,243* or an error code, which can be tested using ZSTD_isError() */244size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format)245{246const BYTE* ip = (const BYTE*)src;247size_t const minInputSize = ZSTD_startingInputLength(format);248249memset(zfhPtr, 0, sizeof(*zfhPtr)); /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */250if (srcSize < minInputSize) return minInputSize;251RETURN_ERROR_IF(src==NULL, GENERIC, "invalid parameter");252253if ( (format != ZSTD_f_zstd1_magicless)254&& (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) {255if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {256/* skippable frame */257if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)258return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */259memset(zfhPtr, 0, sizeof(*zfhPtr));260zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE);261zfhPtr->frameType = ZSTD_skippableFrame;262return 0;263}264RETURN_ERROR(prefix_unknown, "");265}266267/* ensure there is enough `srcSize` to fully read/decode frame header */268{ size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format);269if (srcSize < fhsize) return fhsize;270zfhPtr->headerSize = (U32)fhsize;271}272273{ BYTE const fhdByte = ip[minInputSize-1];274size_t pos = minInputSize;275U32 const dictIDSizeCode = fhdByte&3;276U32 const checksumFlag = (fhdByte>>2)&1;277U32 const singleSegment = (fhdByte>>5)&1;278U32 const fcsID = fhdByte>>6;279U64 windowSize = 0;280U32 dictID = 0;281U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;282RETURN_ERROR_IF((fhdByte & 0x08) != 0, frameParameter_unsupported,283"reserved bits, must be zero");284285if (!singleSegment) {286BYTE const wlByte = ip[pos++];287U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;288RETURN_ERROR_IF(windowLog > ZSTD_WINDOWLOG_MAX, frameParameter_windowTooLarge, "");289windowSize = (1ULL << windowLog);290windowSize += (windowSize >> 3) * (wlByte&7);291}292switch(dictIDSizeCode)293{294default: assert(0); /* impossible */295case 0 : break;296case 1 : dictID = ip[pos]; pos++; break;297case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;298case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;299}300switch(fcsID)301{302default: assert(0); /* impossible */303case 0 : if (singleSegment) frameContentSize = ip[pos]; break;304case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;305case 2 : frameContentSize = MEM_readLE32(ip+pos); break;306case 3 : frameContentSize = MEM_readLE64(ip+pos); break;307}308if (singleSegment) windowSize = frameContentSize;309310zfhPtr->frameType = ZSTD_frame;311zfhPtr->frameContentSize = frameContentSize;312zfhPtr->windowSize = windowSize;313zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);314zfhPtr->dictID = dictID;315zfhPtr->checksumFlag = checksumFlag;316}317return 0;318}319320/** ZSTD_getFrameHeader() :321* decode Frame Header, or require larger `srcSize`.322* note : this function does not consume input, it only reads it.323* @return : 0, `zfhPtr` is correctly filled,324* >0, `srcSize` is too small, value is wanted `srcSize` amount,325* or an error code, which can be tested using ZSTD_isError() */326size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)327{328return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1);329}330331332/** ZSTD_getFrameContentSize() :333* compatible with legacy mode334* @return : decompressed size of the single frame pointed to be `src` if known, otherwise335* - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined336* - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */337unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)338{339#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)340if (ZSTD_isLegacy(src, srcSize)) {341unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);342return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;343}344#endif345{ ZSTD_frameHeader zfh;346if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)347return ZSTD_CONTENTSIZE_ERROR;348if (zfh.frameType == ZSTD_skippableFrame) {349return 0;350} else {351return zfh.frameContentSize;352} }353}354355static size_t readSkippableFrameSize(void const* src, size_t srcSize)356{357size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;358U32 sizeU32;359360RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, "");361362sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);363RETURN_ERROR_IF((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32,364frameParameter_unsupported, "");365{366size_t const skippableSize = skippableHeaderSize + sizeU32;367RETURN_ERROR_IF(skippableSize > srcSize, srcSize_wrong, "");368return skippableSize;369}370}371372/** ZSTD_findDecompressedSize() :373* compatible with legacy mode374* `srcSize` must be the exact length of some number of ZSTD compressed and/or375* skippable frames376* @return : decompressed size of the frames contained */377unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)378{379unsigned long long totalDstSize = 0;380381while (srcSize >= ZSTD_startingInputLength(ZSTD_f_zstd1)) {382U32 const magicNumber = MEM_readLE32(src);383384if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {385size_t const skippableSize = readSkippableFrameSize(src, srcSize);386if (ZSTD_isError(skippableSize)) {387return ZSTD_CONTENTSIZE_ERROR;388}389assert(skippableSize <= srcSize);390391src = (const BYTE *)src + skippableSize;392srcSize -= skippableSize;393continue;394}395396{ unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);397if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret;398399/* check for overflow */400if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR;401totalDstSize += ret;402}403{ size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);404if (ZSTD_isError(frameSrcSize)) {405return ZSTD_CONTENTSIZE_ERROR;406}407408src = (const BYTE *)src + frameSrcSize;409srcSize -= frameSrcSize;410}411} /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */412413if (srcSize) return ZSTD_CONTENTSIZE_ERROR;414415return totalDstSize;416}417418/** ZSTD_getDecompressedSize() :419* compatible with legacy mode420* @return : decompressed size if known, 0 otherwise421note : 0 can mean any of the following :422- frame content is empty423- decompressed size field is not present in frame header424- frame header unknown / not supported425- frame header not complete (`srcSize` too small) */426unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)427{428unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);429ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN);430return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret;431}432433434/** ZSTD_decodeFrameHeader() :435* `headerSize` must be the size provided by ZSTD_frameHeaderSize().436* @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */437static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)438{439size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);440if (ZSTD_isError(result)) return result; /* invalid header */441RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small");442#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION443/* Skip the dictID check in fuzzing mode, because it makes the search444* harder.445*/446RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID),447dictionary_wrong, "");448#endif449if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);450return 0;451}452453static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret)454{455ZSTD_frameSizeInfo frameSizeInfo;456frameSizeInfo.compressedSize = ret;457frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;458return frameSizeInfo;459}460461static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize)462{463ZSTD_frameSizeInfo frameSizeInfo;464memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo));465466#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)467if (ZSTD_isLegacy(src, srcSize))468return ZSTD_findFrameSizeInfoLegacy(src, srcSize);469#endif470471if ((srcSize >= ZSTD_SKIPPABLEHEADERSIZE)472&& (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {473frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize);474assert(ZSTD_isError(frameSizeInfo.compressedSize) ||475frameSizeInfo.compressedSize <= srcSize);476return frameSizeInfo;477} else {478const BYTE* ip = (const BYTE*)src;479const BYTE* const ipstart = ip;480size_t remainingSize = srcSize;481size_t nbBlocks = 0;482ZSTD_frameHeader zfh;483484/* Extract Frame Header */485{ size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize);486if (ZSTD_isError(ret))487return ZSTD_errorFrameSizeInfo(ret);488if (ret > 0)489return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));490}491492ip += zfh.headerSize;493remainingSize -= zfh.headerSize;494495/* Iterate over each block */496while (1) {497blockProperties_t blockProperties;498size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);499if (ZSTD_isError(cBlockSize))500return ZSTD_errorFrameSizeInfo(cBlockSize);501502if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)503return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));504505ip += ZSTD_blockHeaderSize + cBlockSize;506remainingSize -= ZSTD_blockHeaderSize + cBlockSize;507nbBlocks++;508509if (blockProperties.lastBlock) break;510}511512/* Final frame content checksum */513if (zfh.checksumFlag) {514if (remainingSize < 4)515return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));516ip += 4;517}518519frameSizeInfo.compressedSize = ip - ipstart;520frameSizeInfo.decompressedBound = (zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN)521? zfh.frameContentSize522: nbBlocks * zfh.blockSizeMax;523return frameSizeInfo;524}525}526527/** ZSTD_findFrameCompressedSize() :528* compatible with legacy mode529* `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame530* `srcSize` must be at least as large as the frame contained531* @return : the compressed size of the frame starting at `src` */532size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)533{534ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize);535return frameSizeInfo.compressedSize;536}537538/** ZSTD_decompressBound() :539* compatible with legacy mode540* `src` must point to the start of a ZSTD frame or a skippeable frame541* `srcSize` must be at least as large as the frame contained542* @return : the maximum decompressed size of the compressed source543*/544unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize)545{546unsigned long long bound = 0;547/* Iterate over each frame */548while (srcSize > 0) {549ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize);550size_t const compressedSize = frameSizeInfo.compressedSize;551unsigned long long const decompressedBound = frameSizeInfo.decompressedBound;552if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR)553return ZSTD_CONTENTSIZE_ERROR;554assert(srcSize >= compressedSize);555src = (const BYTE*)src + compressedSize;556srcSize -= compressedSize;557bound += decompressedBound;558}559return bound;560}561562563/*-*************************************************************564* Frame decoding565***************************************************************/566567/** ZSTD_insertBlock() :568* insert `src` block into `dctx` history. Useful to track uncompressed blocks. */569size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)570{571DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize);572ZSTD_checkContinuity(dctx, blockStart);573dctx->previousDstEnd = (const char*)blockStart + blockSize;574return blockSize;575}576577578static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,579const void* src, size_t srcSize)580{581DEBUGLOG(5, "ZSTD_copyRawBlock");582if (dst == NULL) {583if (srcSize == 0) return 0;584RETURN_ERROR(dstBuffer_null, "");585}586RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, "");587memcpy(dst, src, srcSize);588return srcSize;589}590591static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,592BYTE b,593size_t regenSize)594{595if (dst == NULL) {596if (regenSize == 0) return 0;597RETURN_ERROR(dstBuffer_null, "");598}599RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, "");600memset(dst, b, regenSize);601return regenSize;602}603604605/*! ZSTD_decompressFrame() :606* @dctx must be properly initialized607* will update *srcPtr and *srcSizePtr,608* to make *srcPtr progress by one frame. */609static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,610void* dst, size_t dstCapacity,611const void** srcPtr, size_t *srcSizePtr)612{613const BYTE* ip = (const BYTE*)(*srcPtr);614BYTE* const ostart = (BYTE* const)dst;615BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart;616BYTE* op = ostart;617size_t remainingSrcSize = *srcSizePtr;618619DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);620621/* check */622RETURN_ERROR_IF(623remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize,624srcSize_wrong, "");625626/* Frame Header */627{ size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal(628ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format);629if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;630RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize,631srcSize_wrong, "");632FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , "");633ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;634}635636/* Loop on each block */637while (1) {638size_t decodedSize;639blockProperties_t blockProperties;640size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);641if (ZSTD_isError(cBlockSize)) return cBlockSize;642643ip += ZSTD_blockHeaderSize;644remainingSrcSize -= ZSTD_blockHeaderSize;645RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, "");646647switch(blockProperties.blockType)648{649case bt_compressed:650decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1);651break;652case bt_raw :653decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);654break;655case bt_rle :656decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize);657break;658case bt_reserved :659default:660RETURN_ERROR(corruption_detected, "invalid block type");661}662663if (ZSTD_isError(decodedSize)) return decodedSize;664if (dctx->fParams.checksumFlag)665XXH64_update(&dctx->xxhState, op, decodedSize);666if (decodedSize != 0)667op += decodedSize;668assert(ip != NULL);669ip += cBlockSize;670remainingSrcSize -= cBlockSize;671if (blockProperties.lastBlock) break;672}673674if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {675RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize,676corruption_detected, "");677}678if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */679U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);680U32 checkRead;681RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, "");682checkRead = MEM_readLE32(ip);683RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, "");684ip += 4;685remainingSrcSize -= 4;686}687688/* Allow caller to get size read */689*srcPtr = ip;690*srcSizePtr = remainingSrcSize;691return op-ostart;692}693694static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,695void* dst, size_t dstCapacity,696const void* src, size_t srcSize,697const void* dict, size_t dictSize,698const ZSTD_DDict* ddict)699{700void* const dststart = dst;701int moreThan1Frame = 0;702703DEBUGLOG(5, "ZSTD_decompressMultiFrame");704assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */705706if (ddict) {707dict = ZSTD_DDict_dictContent(ddict);708dictSize = ZSTD_DDict_dictSize(ddict);709}710711while (srcSize >= ZSTD_startingInputLength(dctx->format)) {712713#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)714if (ZSTD_isLegacy(src, srcSize)) {715size_t decodedSize;716size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);717if (ZSTD_isError(frameSize)) return frameSize;718RETURN_ERROR_IF(dctx->staticSize, memory_allocation,719"legacy support is not compatible with static dctx");720721decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);722if (ZSTD_isError(decodedSize)) return decodedSize;723724assert(decodedSize <=- dstCapacity);725dst = (BYTE*)dst + decodedSize;726dstCapacity -= decodedSize;727728src = (const BYTE*)src + frameSize;729srcSize -= frameSize;730731continue;732}733#endif734735{ U32 const magicNumber = MEM_readLE32(src);736DEBUGLOG(4, "reading magic number %08X (expecting %08X)",737(unsigned)magicNumber, ZSTD_MAGICNUMBER);738if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {739size_t const skippableSize = readSkippableFrameSize(src, srcSize);740FORWARD_IF_ERROR(skippableSize, "readSkippableFrameSize failed");741assert(skippableSize <= srcSize);742743src = (const BYTE *)src + skippableSize;744srcSize -= skippableSize;745continue;746} }747748if (ddict) {749/* we were called from ZSTD_decompress_usingDDict */750FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), "");751} else {752/* this will initialize correctly with no dict if dict == NULL, so753* use this in all cases but ddict */754FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), "");755}756ZSTD_checkContinuity(dctx, dst);757758{ const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,759&src, &srcSize);760RETURN_ERROR_IF(761(ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)762&& (moreThan1Frame==1),763srcSize_wrong,764"at least one frame successfully completed, but following "765"bytes are garbage: it's more likely to be a srcSize error, "766"specifying more bytes than compressed size of frame(s). This "767"error message replaces ERROR(prefix_unknown), which would be "768"confusing, as the first header is actually correct. Note that "769"one could be unlucky, it might be a corruption error instead, "770"happening right at the place where we expect zstd magic "771"bytes. But this is _much_ less likely than a srcSize field "772"error.");773if (ZSTD_isError(res)) return res;774assert(res <= dstCapacity);775if (res != 0)776dst = (BYTE*)dst + res;777dstCapacity -= res;778}779moreThan1Frame = 1;780} /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */781782RETURN_ERROR_IF(srcSize, srcSize_wrong, "input not entirely consumed");783784return (BYTE*)dst - (BYTE*)dststart;785}786787size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,788void* dst, size_t dstCapacity,789const void* src, size_t srcSize,790const void* dict, size_t dictSize)791{792return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);793}794795796static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx)797{798switch (dctx->dictUses) {799default:800assert(0 /* Impossible */);801/* fall-through */802case ZSTD_dont_use:803ZSTD_clearDict(dctx);804return NULL;805case ZSTD_use_indefinitely:806return dctx->ddict;807case ZSTD_use_once:808dctx->dictUses = ZSTD_dont_use;809return dctx->ddict;810}811}812813size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)814{815return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx));816}817818819size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)820{821#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)822size_t regenSize;823ZSTD_DCtx* const dctx = ZSTD_createDCtx();824RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!");825regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);826ZSTD_freeDCtx(dctx);827return regenSize;828#else /* stack mode */829ZSTD_DCtx dctx;830ZSTD_initDCtx_internal(&dctx);831return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);832#endif833}834835836/*-**************************************837* Advanced Streaming Decompression API838* Bufferless and synchronous839****************************************/840size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }841842/**843* Similar to ZSTD_nextSrcSizeToDecompress(), but when when a block input can be streamed,844* we allow taking a partial block as the input. Currently only raw uncompressed blocks can845* be streamed.846*847* For blocks that can be streamed, this allows us to reduce the latency until we produce848* output, and avoid copying the input.849*850* @param inputSize - The total amount of input that the caller currently has.851*/852static size_t ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx* dctx, size_t inputSize) {853if (!(dctx->stage == ZSTDds_decompressBlock || dctx->stage == ZSTDds_decompressLastBlock))854return dctx->expected;855if (dctx->bType != bt_raw)856return dctx->expected;857return MIN(MAX(inputSize, 1), dctx->expected);858}859860ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {861switch(dctx->stage)862{863default: /* should not happen */864assert(0);865case ZSTDds_getFrameHeaderSize:866case ZSTDds_decodeFrameHeader:867return ZSTDnit_frameHeader;868case ZSTDds_decodeBlockHeader:869return ZSTDnit_blockHeader;870case ZSTDds_decompressBlock:871return ZSTDnit_block;872case ZSTDds_decompressLastBlock:873return ZSTDnit_lastBlock;874case ZSTDds_checkChecksum:875return ZSTDnit_checksum;876case ZSTDds_decodeSkippableHeader:877case ZSTDds_skipFrame:878return ZSTDnit_skippableFrame;879}880}881882static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }883884/** ZSTD_decompressContinue() :885* srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())886* @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)887* or an error code, which can be tested using ZSTD_isError() */888size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)889{890DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize);891/* Sanity check */892RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed");893if (dstCapacity) ZSTD_checkContinuity(dctx, dst);894895switch (dctx->stage)896{897case ZSTDds_getFrameHeaderSize :898assert(src != NULL);899if (dctx->format == ZSTD_f_zstd1) { /* allows header */900assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */901if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */902memcpy(dctx->headerBuffer, src, srcSize);903dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */904dctx->stage = ZSTDds_decodeSkippableHeader;905return 0;906} }907dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);908if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;909memcpy(dctx->headerBuffer, src, srcSize);910dctx->expected = dctx->headerSize - srcSize;911dctx->stage = ZSTDds_decodeFrameHeader;912return 0;913914case ZSTDds_decodeFrameHeader:915assert(src != NULL);916memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);917FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), "");918dctx->expected = ZSTD_blockHeaderSize;919dctx->stage = ZSTDds_decodeBlockHeader;920return 0;921922case ZSTDds_decodeBlockHeader:923{ blockProperties_t bp;924size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);925if (ZSTD_isError(cBlockSize)) return cBlockSize;926RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum");927dctx->expected = cBlockSize;928dctx->bType = bp.blockType;929dctx->rleSize = bp.origSize;930if (cBlockSize) {931dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;932return 0;933}934/* empty block */935if (bp.lastBlock) {936if (dctx->fParams.checksumFlag) {937dctx->expected = 4;938dctx->stage = ZSTDds_checkChecksum;939} else {940dctx->expected = 0; /* end of frame */941dctx->stage = ZSTDds_getFrameHeaderSize;942}943} else {944dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */945dctx->stage = ZSTDds_decodeBlockHeader;946}947return 0;948}949950case ZSTDds_decompressLastBlock:951case ZSTDds_decompressBlock:952DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");953{ size_t rSize;954switch(dctx->bType)955{956case bt_compressed:957DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");958rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1);959dctx->expected = 0; /* Streaming not supported */960break;961case bt_raw :962assert(srcSize <= dctx->expected);963rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);964FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed");965assert(rSize == srcSize);966dctx->expected -= rSize;967break;968case bt_rle :969rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);970dctx->expected = 0; /* Streaming not supported */971break;972case bt_reserved : /* should never happen */973default:974RETURN_ERROR(corruption_detected, "invalid block type");975}976FORWARD_IF_ERROR(rSize, "");977RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum");978DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);979dctx->decodedSize += rSize;980if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);981dctx->previousDstEnd = (char*)dst + rSize;982983/* Stay on the same stage until we are finished streaming the block. */984if (dctx->expected > 0) {985return rSize;986}987988if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */989DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);990RETURN_ERROR_IF(991dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN992&& dctx->decodedSize != dctx->fParams.frameContentSize,993corruption_detected, "");994if (dctx->fParams.checksumFlag) { /* another round for frame checksum */995dctx->expected = 4;996dctx->stage = ZSTDds_checkChecksum;997} else {998dctx->expected = 0; /* ends here */999dctx->stage = ZSTDds_getFrameHeaderSize;1000}1001} else {1002dctx->stage = ZSTDds_decodeBlockHeader;1003dctx->expected = ZSTD_blockHeaderSize;1004}1005return rSize;1006}10071008case ZSTDds_checkChecksum:1009assert(srcSize == 4); /* guaranteed by dctx->expected */1010{ U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);1011U32 const check32 = MEM_readLE32(src);1012DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);1013RETURN_ERROR_IF(check32 != h32, checksum_wrong, "");1014dctx->expected = 0;1015dctx->stage = ZSTDds_getFrameHeaderSize;1016return 0;1017}10181019case ZSTDds_decodeSkippableHeader:1020assert(src != NULL);1021assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);1022memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */1023dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */1024dctx->stage = ZSTDds_skipFrame;1025return 0;10261027case ZSTDds_skipFrame:1028dctx->expected = 0;1029dctx->stage = ZSTDds_getFrameHeaderSize;1030return 0;10311032default:1033assert(0); /* impossible */1034RETURN_ERROR(GENERIC, "impossible to reach"); /* some compiler require default to do something */1035}1036}103710381039static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)1040{1041dctx->dictEnd = dctx->previousDstEnd;1042dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));1043dctx->prefixStart = dict;1044dctx->previousDstEnd = (const char*)dict + dictSize;1045#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION1046dctx->dictContentBeginForFuzzing = dctx->prefixStart;1047dctx->dictContentEndForFuzzing = dctx->previousDstEnd;1048#endif1049return 0;1050}10511052/*! ZSTD_loadDEntropy() :1053* dict : must point at beginning of a valid zstd dictionary.1054* @return : size of entropy tables read */1055size_t1056ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,1057const void* const dict, size_t const dictSize)1058{1059const BYTE* dictPtr = (const BYTE*)dict;1060const BYTE* const dictEnd = dictPtr + dictSize;10611062RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small");1063assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */1064dictPtr += 8; /* skip header = magic + dictID */10651066ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));1067ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));1068ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);1069{ void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */1070size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);1071#ifdef HUF_FORCE_DECOMPRESS_X11072/* in minimal huffman, we always use X1 variants */1073size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,1074dictPtr, dictEnd - dictPtr,1075workspace, workspaceSize);1076#else1077size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,1078dictPtr, dictEnd - dictPtr,1079workspace, workspaceSize);1080#endif1081RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, "");1082dictPtr += hSize;1083}10841085{ short offcodeNCount[MaxOff+1];1086unsigned offcodeMaxValue = MaxOff, offcodeLog;1087size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);1088RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");1089RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, "");1090RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");1091ZSTD_buildFSETable( entropy->OFTable,1092offcodeNCount, offcodeMaxValue,1093OF_base, OF_bits,1094offcodeLog);1095dictPtr += offcodeHeaderSize;1096}10971098{ short matchlengthNCount[MaxML+1];1099unsigned matchlengthMaxValue = MaxML, matchlengthLog;1100size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);1101RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");1102RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, "");1103RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");1104ZSTD_buildFSETable( entropy->MLTable,1105matchlengthNCount, matchlengthMaxValue,1106ML_base, ML_bits,1107matchlengthLog);1108dictPtr += matchlengthHeaderSize;1109}11101111{ short litlengthNCount[MaxLL+1];1112unsigned litlengthMaxValue = MaxLL, litlengthLog;1113size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);1114RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");1115RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, "");1116RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");1117ZSTD_buildFSETable( entropy->LLTable,1118litlengthNCount, litlengthMaxValue,1119LL_base, LL_bits,1120litlengthLog);1121dictPtr += litlengthHeaderSize;1122}11231124RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");1125{ int i;1126size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));1127for (i=0; i<3; i++) {1128U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;1129RETURN_ERROR_IF(rep==0 || rep > dictContentSize,1130dictionary_corrupted, "");1131entropy->rep[i] = rep;1132} }11331134return dictPtr - (const BYTE*)dict;1135}11361137static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)1138{1139if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);1140{ U32 const magic = MEM_readLE32(dict);1141if (magic != ZSTD_MAGIC_DICTIONARY) {1142return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */1143} }1144dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);11451146/* load entropy tables */1147{ size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);1148RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, "");1149dict = (const char*)dict + eSize;1150dictSize -= eSize;1151}1152dctx->litEntropy = dctx->fseEntropy = 1;11531154/* reference dictionary content */1155return ZSTD_refDictContent(dctx, dict, dictSize);1156}11571158size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)1159{1160assert(dctx != NULL);1161dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */1162dctx->stage = ZSTDds_getFrameHeaderSize;1163dctx->decodedSize = 0;1164dctx->previousDstEnd = NULL;1165dctx->prefixStart = NULL;1166dctx->virtualStart = NULL;1167dctx->dictEnd = NULL;1168dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */1169dctx->litEntropy = dctx->fseEntropy = 0;1170dctx->dictID = 0;1171dctx->bType = bt_reserved;1172ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));1173memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */1174dctx->LLTptr = dctx->entropy.LLTable;1175dctx->MLTptr = dctx->entropy.MLTable;1176dctx->OFTptr = dctx->entropy.OFTable;1177dctx->HUFptr = dctx->entropy.hufTable;1178return 0;1179}11801181size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)1182{1183FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , "");1184if (dict && dictSize)1185RETURN_ERROR_IF(1186ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)),1187dictionary_corrupted, "");1188return 0;1189}119011911192/* ====== ZSTD_DDict ====== */11931194size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)1195{1196DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict");1197assert(dctx != NULL);1198if (ddict) {1199const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict);1200size_t const dictSize = ZSTD_DDict_dictSize(ddict);1201const void* const dictEnd = dictStart + dictSize;1202dctx->ddictIsCold = (dctx->dictEnd != dictEnd);1203DEBUGLOG(4, "DDict is %s",1204dctx->ddictIsCold ? "~cold~" : "hot!");1205}1206FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , "");1207if (ddict) { /* NULL ddict is equivalent to no dictionary */1208ZSTD_copyDDictParameters(dctx, ddict);1209}1210return 0;1211}12121213/*! ZSTD_getDictID_fromDict() :1214* Provides the dictID stored within dictionary.1215* if @return == 0, the dictionary is not conformant with Zstandard specification.1216* It can still be loaded, but as a content-only dictionary. */1217unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)1218{1219if (dictSize < 8) return 0;1220if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;1221return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);1222}12231224/*! ZSTD_getDictID_fromFrame() :1225* Provides the dictID required to decompress frame stored within `src`.1226* If @return == 0, the dictID could not be decoded.1227* This could for one of the following reasons :1228* - The frame does not require a dictionary (most common case).1229* - The frame was built with dictID intentionally removed.1230* Needed dictionary is a hidden information.1231* Note : this use case also happens when using a non-conformant dictionary.1232* - `srcSize` is too small, and as a result, frame header could not be decoded.1233* Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.1234* - This is not a Zstandard frame.1235* When identifying the exact failure cause, it's possible to use1236* ZSTD_getFrameHeader(), which will provide a more precise error code. */1237unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)1238{1239ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 };1240size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);1241if (ZSTD_isError(hError)) return 0;1242return zfp.dictID;1243}124412451246/*! ZSTD_decompress_usingDDict() :1247* Decompression using a pre-digested Dictionary1248* Use dictionary without significant overhead. */1249size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,1250void* dst, size_t dstCapacity,1251const void* src, size_t srcSize,1252const ZSTD_DDict* ddict)1253{1254/* pass content and size in case legacy frames are encountered */1255return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,1256NULL, 0,1257ddict);1258}125912601261/*=====================================1262* Streaming decompression1263*====================================*/12641265ZSTD_DStream* ZSTD_createDStream(void)1266{1267DEBUGLOG(3, "ZSTD_createDStream");1268return ZSTD_createDStream_advanced(ZSTD_defaultCMem);1269}12701271ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)1272{1273return ZSTD_initStaticDCtx(workspace, workspaceSize);1274}12751276ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)1277{1278return ZSTD_createDCtx_advanced(customMem);1279}12801281size_t ZSTD_freeDStream(ZSTD_DStream* zds)1282{1283return ZSTD_freeDCtx(zds);1284}128512861287/* *** Initialization *** */12881289size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }1290size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }12911292size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx,1293const void* dict, size_t dictSize,1294ZSTD_dictLoadMethod_e dictLoadMethod,1295ZSTD_dictContentType_e dictContentType)1296{1297RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");1298ZSTD_clearDict(dctx);1299if (dict && dictSize != 0) {1300dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem);1301RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!");1302dctx->ddict = dctx->ddictLocal;1303dctx->dictUses = ZSTD_use_indefinitely;1304}1305return 0;1306}13071308size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)1309{1310return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);1311}13121313size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)1314{1315return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);1316}13171318size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)1319{1320FORWARD_IF_ERROR(ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType), "");1321dctx->dictUses = ZSTD_use_once;1322return 0;1323}13241325size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize)1326{1327return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent);1328}132913301331/* ZSTD_initDStream_usingDict() :1332* return : expected size, aka ZSTD_startingInputLength().1333* this function cannot fail */1334size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)1335{1336DEBUGLOG(4, "ZSTD_initDStream_usingDict");1337FORWARD_IF_ERROR( ZSTD_DCtx_reset(zds, ZSTD_reset_session_only) , "");1338FORWARD_IF_ERROR( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) , "");1339return ZSTD_startingInputLength(zds->format);1340}13411342/* note : this variant can't fail */1343size_t ZSTD_initDStream(ZSTD_DStream* zds)1344{1345DEBUGLOG(4, "ZSTD_initDStream");1346return ZSTD_initDStream_usingDDict(zds, NULL);1347}13481349/* ZSTD_initDStream_usingDDict() :1350* ddict will just be referenced, and must outlive decompression session1351* this function cannot fail */1352size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict)1353{1354FORWARD_IF_ERROR( ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) , "");1355FORWARD_IF_ERROR( ZSTD_DCtx_refDDict(dctx, ddict) , "");1356return ZSTD_startingInputLength(dctx->format);1357}13581359/* ZSTD_resetDStream() :1360* return : expected size, aka ZSTD_startingInputLength().1361* this function cannot fail */1362size_t ZSTD_resetDStream(ZSTD_DStream* dctx)1363{1364FORWARD_IF_ERROR(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only), "");1365return ZSTD_startingInputLength(dctx->format);1366}136713681369size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)1370{1371RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");1372ZSTD_clearDict(dctx);1373if (ddict) {1374dctx->ddict = ddict;1375dctx->dictUses = ZSTD_use_indefinitely;1376}1377return 0;1378}13791380/* ZSTD_DCtx_setMaxWindowSize() :1381* note : no direct equivalence in ZSTD_DCtx_setParameter,1382* since this version sets windowSize, and the other sets windowLog */1383size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize)1384{1385ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);1386size_t const min = (size_t)1 << bounds.lowerBound;1387size_t const max = (size_t)1 << bounds.upperBound;1388RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");1389RETURN_ERROR_IF(maxWindowSize < min, parameter_outOfBound, "");1390RETURN_ERROR_IF(maxWindowSize > max, parameter_outOfBound, "");1391dctx->maxWindowSize = maxWindowSize;1392return 0;1393}13941395size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format)1396{1397return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format);1398}13991400ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)1401{1402ZSTD_bounds bounds = { 0, 0, 0 };1403switch(dParam) {1404case ZSTD_d_windowLogMax:1405bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;1406bounds.upperBound = ZSTD_WINDOWLOG_MAX;1407return bounds;1408case ZSTD_d_format:1409bounds.lowerBound = (int)ZSTD_f_zstd1;1410bounds.upperBound = (int)ZSTD_f_zstd1_magicless;1411ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);1412return bounds;1413case ZSTD_d_stableOutBuffer:1414bounds.lowerBound = (int)ZSTD_obm_buffered;1415bounds.upperBound = (int)ZSTD_obm_stable;1416return bounds;1417default:;1418}1419bounds.error = ERROR(parameter_unsupported);1420return bounds;1421}14221423/* ZSTD_dParam_withinBounds:1424* @return 1 if value is within dParam bounds,1425* 0 otherwise */1426static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value)1427{1428ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam);1429if (ZSTD_isError(bounds.error)) return 0;1430if (value < bounds.lowerBound) return 0;1431if (value > bounds.upperBound) return 0;1432return 1;1433}14341435#define CHECK_DBOUNDS(p,v) { \1436RETURN_ERROR_IF(!ZSTD_dParam_withinBounds(p, v), parameter_outOfBound, ""); \1437}14381439size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)1440{1441RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");1442switch(dParam) {1443case ZSTD_d_windowLogMax:1444if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT;1445CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);1446dctx->maxWindowSize = ((size_t)1) << value;1447return 0;1448case ZSTD_d_format:1449CHECK_DBOUNDS(ZSTD_d_format, value);1450dctx->format = (ZSTD_format_e)value;1451return 0;1452case ZSTD_d_stableOutBuffer:1453CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value);1454dctx->outBufferMode = (ZSTD_outBufferMode_e)value;1455return 0;1456default:;1457}1458RETURN_ERROR(parameter_unsupported, "");1459}14601461size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)1462{1463if ( (reset == ZSTD_reset_session_only)1464|| (reset == ZSTD_reset_session_and_parameters) ) {1465dctx->streamStage = zdss_init;1466dctx->noForwardProgress = 0;1467}1468if ( (reset == ZSTD_reset_parameters)1469|| (reset == ZSTD_reset_session_and_parameters) ) {1470RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");1471ZSTD_clearDict(dctx);1472dctx->format = ZSTD_f_zstd1;1473dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;1474}1475return 0;1476}147714781479size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx)1480{1481return ZSTD_sizeof_DCtx(dctx);1482}14831484size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)1485{1486size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);1487unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2);1488unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);1489size_t const minRBSize = (size_t) neededSize;1490RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize,1491frameParameter_windowTooLarge, "");1492return minRBSize;1493}14941495size_t ZSTD_estimateDStreamSize(size_t windowSize)1496{1497size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);1498size_t const inBuffSize = blockSize; /* no block can be larger */1499size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);1500return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;1501}15021503size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)1504{1505U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */1506ZSTD_frameHeader zfh;1507size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);1508if (ZSTD_isError(err)) return err;1509RETURN_ERROR_IF(err>0, srcSize_wrong, "");1510RETURN_ERROR_IF(zfh.windowSize > windowSizeMax,1511frameParameter_windowTooLarge, "");1512return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);1513}151415151516/* ***** Decompression ***** */15171518static int ZSTD_DCtx_isOverflow(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)1519{1520return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR;1521}15221523static void ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)1524{1525if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize))1526zds->oversizedDuration++;1527else1528zds->oversizedDuration = 0;1529}15301531static int ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream* zds)1532{1533return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION;1534}15351536/* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */1537static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output)1538{1539ZSTD_outBuffer const expect = zds->expectedOutBuffer;1540/* No requirement when ZSTD_obm_stable is not enabled. */1541if (zds->outBufferMode != ZSTD_obm_stable)1542return 0;1543/* Any buffer is allowed in zdss_init, this must be the same for every other call until1544* the context is reset.1545*/1546if (zds->streamStage == zdss_init)1547return 0;1548/* The buffer must match our expectation exactly. */1549if (expect.dst == output->dst && expect.pos == output->pos && expect.size == output->size)1550return 0;1551RETURN_ERROR(dstBuffer_wrong, "ZSTD_obm_stable enabled but output differs!");1552}15531554/* Calls ZSTD_decompressContinue() with the right parameters for ZSTD_decompressStream()1555* and updates the stage and the output buffer state. This call is extracted so it can be1556* used both when reading directly from the ZSTD_inBuffer, and in buffered input mode.1557* NOTE: You must break after calling this function since the streamStage is modified.1558*/1559static size_t ZSTD_decompressContinueStream(1560ZSTD_DStream* zds, char** op, char* oend,1561void const* src, size_t srcSize) {1562int const isSkipFrame = ZSTD_isSkipFrame(zds);1563if (zds->outBufferMode == ZSTD_obm_buffered) {1564size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart;1565size_t const decodedSize = ZSTD_decompressContinue(zds,1566zds->outBuff + zds->outStart, dstSize, src, srcSize);1567FORWARD_IF_ERROR(decodedSize, "");1568if (!decodedSize && !isSkipFrame) {1569zds->streamStage = zdss_read;1570} else {1571zds->outEnd = zds->outStart + decodedSize;1572zds->streamStage = zdss_flush;1573}1574} else {1575/* Write directly into the output buffer */1576size_t const dstSize = isSkipFrame ? 0 : oend - *op;1577size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize);1578FORWARD_IF_ERROR(decodedSize, "");1579*op += decodedSize;1580/* Flushing is not needed. */1581zds->streamStage = zdss_read;1582assert(*op <= oend);1583assert(zds->outBufferMode == ZSTD_obm_stable);1584}1585return 0;1586}15871588size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)1589{1590const char* const src = (const char*)input->src;1591const char* const istart = input->pos != 0 ? src + input->pos : src;1592const char* const iend = input->size != 0 ? src + input->size : src;1593const char* ip = istart;1594char* const dst = (char*)output->dst;1595char* const ostart = output->pos != 0 ? dst + output->pos : dst;1596char* const oend = output->size != 0 ? dst + output->size : dst;1597char* op = ostart;1598U32 someMoreWork = 1;15991600DEBUGLOG(5, "ZSTD_decompressStream");1601RETURN_ERROR_IF(1602input->pos > input->size,1603srcSize_wrong,1604"forbidden. in: pos: %u vs size: %u",1605(U32)input->pos, (U32)input->size);1606RETURN_ERROR_IF(1607output->pos > output->size,1608dstSize_tooSmall,1609"forbidden. out: pos: %u vs size: %u",1610(U32)output->pos, (U32)output->size);1611DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));1612FORWARD_IF_ERROR(ZSTD_checkOutBuffer(zds, output), "");16131614while (someMoreWork) {1615switch(zds->streamStage)1616{1617case zdss_init :1618DEBUGLOG(5, "stage zdss_init => transparent reset ");1619zds->streamStage = zdss_loadHeader;1620zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;1621zds->legacyVersion = 0;1622zds->hostageByte = 0;1623zds->expectedOutBuffer = *output;1624/* fall-through */16251626case zdss_loadHeader :1627DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip));1628#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)1629if (zds->legacyVersion) {1630RETURN_ERROR_IF(zds->staticSize, memory_allocation,1631"legacy support is incompatible with static dctx");1632{ size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);1633if (hint==0) zds->streamStage = zdss_init;1634return hint;1635} }1636#endif1637{ size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format);1638DEBUGLOG(5, "header size : %u", (U32)hSize);1639if (ZSTD_isError(hSize)) {1640#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)1641U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);1642if (legacyVersion) {1643ZSTD_DDict const* const ddict = ZSTD_getDDict(zds);1644const void* const dict = ddict ? ZSTD_DDict_dictContent(ddict) : NULL;1645size_t const dictSize = ddict ? ZSTD_DDict_dictSize(ddict) : 0;1646DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion);1647RETURN_ERROR_IF(zds->staticSize, memory_allocation,1648"legacy support is incompatible with static dctx");1649FORWARD_IF_ERROR(ZSTD_initLegacyStream(&zds->legacyContext,1650zds->previousLegacyVersion, legacyVersion,1651dict, dictSize), "");1652zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;1653{ size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);1654if (hint==0) zds->streamStage = zdss_init; /* or stay in stage zdss_loadHeader */1655return hint;1656} }1657#endif1658return hSize; /* error */1659}1660if (hSize != 0) { /* need more input */1661size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */1662size_t const remainingInput = (size_t)(iend-ip);1663assert(iend >= ip);1664if (toLoad > remainingInput) { /* not enough input to load full header */1665if (remainingInput > 0) {1666memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput);1667zds->lhSize += remainingInput;1668}1669input->pos = input->size;1670return (MAX((size_t)ZSTD_FRAMEHEADERSIZE_MIN(zds->format), hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */1671}1672assert(ip != NULL);1673memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;1674break;1675} }16761677/* check for single-pass mode opportunity */1678if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN1679&& zds->fParams.frameType != ZSTD_skippableFrame1680&& (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {1681size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart);1682if (cSize <= (size_t)(iend-istart)) {1683/* shortcut : using single-pass mode */1684size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, ZSTD_getDDict(zds));1685if (ZSTD_isError(decompressedSize)) return decompressedSize;1686DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()")1687ip = istart + cSize;1688op += decompressedSize;1689zds->expected = 0;1690zds->streamStage = zdss_init;1691someMoreWork = 0;1692break;1693} }16941695/* Check output buffer is large enough for ZSTD_odm_stable. */1696if (zds->outBufferMode == ZSTD_obm_stable1697&& zds->fParams.frameType != ZSTD_skippableFrame1698&& zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN1699&& (U64)(size_t)(oend-op) < zds->fParams.frameContentSize) {1700RETURN_ERROR(dstSize_tooSmall, "ZSTD_obm_stable passed but ZSTD_outBuffer is too small");1701}17021703/* Consume header (see ZSTDds_decodeFrameHeader) */1704DEBUGLOG(4, "Consume header");1705FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), "");17061707if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */1708zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE);1709zds->stage = ZSTDds_skipFrame;1710} else {1711FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), "");1712zds->expected = ZSTD_blockHeaderSize;1713zds->stage = ZSTDds_decodeBlockHeader;1714}17151716/* control buffer memory usage */1717DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)",1718(U32)(zds->fParams.windowSize >>10),1719(U32)(zds->maxWindowSize >> 10) );1720zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);1721RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize,1722frameParameter_windowTooLarge, "");17231724/* Adapt buffer sizes to frame header instructions */1725{ size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);1726size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_obm_buffered1727? ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize)1728: 0;17291730ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize);17311732{ int const tooSmall = (zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize);1733int const tooLarge = ZSTD_DCtx_isOversizedTooLong(zds);17341735if (tooSmall || tooLarge) {1736size_t const bufferSize = neededInBuffSize + neededOutBuffSize;1737DEBUGLOG(4, "inBuff : from %u to %u",1738(U32)zds->inBuffSize, (U32)neededInBuffSize);1739DEBUGLOG(4, "outBuff : from %u to %u",1740(U32)zds->outBuffSize, (U32)neededOutBuffSize);1741if (zds->staticSize) { /* static DCtx */1742DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);1743assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */1744RETURN_ERROR_IF(1745bufferSize > zds->staticSize - sizeof(ZSTD_DCtx),1746memory_allocation, "");1747} else {1748ZSTD_free(zds->inBuff, zds->customMem);1749zds->inBuffSize = 0;1750zds->outBuffSize = 0;1751zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem);1752RETURN_ERROR_IF(zds->inBuff == NULL, memory_allocation, "");1753}1754zds->inBuffSize = neededInBuffSize;1755zds->outBuff = zds->inBuff + zds->inBuffSize;1756zds->outBuffSize = neededOutBuffSize;1757} } }1758zds->streamStage = zdss_read;1759/* fall-through */17601761case zdss_read:1762DEBUGLOG(5, "stage zdss_read");1763{ size_t const neededInSize = ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip);1764DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);1765if (neededInSize==0) { /* end of frame */1766zds->streamStage = zdss_init;1767someMoreWork = 0;1768break;1769}1770if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */1771FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, ip, neededInSize), "");1772ip += neededInSize;1773/* Function modifies the stage so we must break */1774break;1775} }1776if (ip==iend) { someMoreWork = 0; break; } /* no more input */1777zds->streamStage = zdss_load;1778/* fall-through */17791780case zdss_load:1781{ size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);1782size_t const toLoad = neededInSize - zds->inPos;1783int const isSkipFrame = ZSTD_isSkipFrame(zds);1784size_t loadedSize;1785/* At this point we shouldn't be decompressing a block that we can stream. */1786assert(neededInSize == ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip));1787if (isSkipFrame) {1788loadedSize = MIN(toLoad, (size_t)(iend-ip));1789} else {1790RETURN_ERROR_IF(toLoad > zds->inBuffSize - zds->inPos,1791corruption_detected,1792"should never happen");1793loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip);1794}1795ip += loadedSize;1796zds->inPos += loadedSize;1797if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */17981799/* decode loaded input */1800zds->inPos = 0; /* input is consumed */1801FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, zds->inBuff, neededInSize), "");1802/* Function modifies the stage so we must break */1803break;1804}1805case zdss_flush:1806{ size_t const toFlushSize = zds->outEnd - zds->outStart;1807size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize);1808op += flushedSize;1809zds->outStart += flushedSize;1810if (flushedSize == toFlushSize) { /* flush completed */1811zds->streamStage = zdss_read;1812if ( (zds->outBuffSize < zds->fParams.frameContentSize)1813&& (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {1814DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",1815(int)(zds->outBuffSize - zds->outStart),1816(U32)zds->fParams.blockSizeMax);1817zds->outStart = zds->outEnd = 0;1818}1819break;1820} }1821/* cannot complete flush */1822someMoreWork = 0;1823break;18241825default:1826assert(0); /* impossible */1827RETURN_ERROR(GENERIC, "impossible to reach"); /* some compiler require default to do something */1828} }18291830/* result */1831input->pos = (size_t)(ip - (const char*)(input->src));1832output->pos = (size_t)(op - (char*)(output->dst));18331834/* Update the expected output buffer for ZSTD_obm_stable. */1835zds->expectedOutBuffer = *output;18361837if ((ip==istart) && (op==ostart)) { /* no forward progress */1838zds->noForwardProgress ++;1839if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) {1840RETURN_ERROR_IF(op==oend, dstSize_tooSmall, "");1841RETURN_ERROR_IF(ip==iend, srcSize_wrong, "");1842assert(0);1843}1844} else {1845zds->noForwardProgress = 0;1846}1847{ size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);1848if (!nextSrcSizeHint) { /* frame fully decoded */1849if (zds->outEnd == zds->outStart) { /* output fully flushed */1850if (zds->hostageByte) {1851if (input->pos >= input->size) {1852/* can't release hostage (not present) */1853zds->streamStage = zdss_read;1854return 1;1855}1856input->pos++; /* release hostage */1857} /* zds->hostageByte */1858return 0;1859} /* zds->outEnd == zds->outStart */1860if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */1861input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */1862zds->hostageByte=1;1863}1864return 1;1865} /* nextSrcSizeHint==0 */1866nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */1867assert(zds->inPos <= nextSrcSizeHint);1868nextSrcSizeHint -= zds->inPos; /* part already loaded*/1869return nextSrcSizeHint;1870}1871}18721873size_t ZSTD_decompressStream_simpleArgs (1874ZSTD_DCtx* dctx,1875void* dst, size_t dstCapacity, size_t* dstPos,1876const void* src, size_t srcSize, size_t* srcPos)1877{1878ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };1879ZSTD_inBuffer input = { src, srcSize, *srcPos };1880/* ZSTD_compress_generic() will check validity of dstPos and srcPos */1881size_t const cErr = ZSTD_decompressStream(dctx, &output, &input);1882*dstPos = output.pos;1883*srcPos = input.pos;1884return cErr;1885}188618871888