You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_decompress.c 102KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  1. /*
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /* ***************************************************************
  11. * Tuning parameters
  12. *****************************************************************/
  13. /*!
  14. * HEAPMODE :
  15. * Select how default decompression function ZSTD_decompress() will allocate memory,
  16. * in memory stack (0), or in memory heap (1, requires malloc())
  17. */
  18. #ifndef ZSTD_HEAPMODE
  19. # define ZSTD_HEAPMODE 1
  20. #endif
  21. /*!
  22. * LEGACY_SUPPORT :
  23. * if set to 1, ZSTD_decompress() can decode older formats (v0.1+)
  24. */
  25. #ifndef ZSTD_LEGACY_SUPPORT
  26. # define ZSTD_LEGACY_SUPPORT 0
  27. #endif
  28. /*!
  29. * MAXWINDOWSIZE_DEFAULT :
  30. * maximum window size accepted by DStream, by default.
  31. * Frames requiring more memory will be rejected.
  32. */
  33. #ifndef ZSTD_MAXWINDOWSIZE_DEFAULT
  34. # define ZSTD_MAXWINDOWSIZE_DEFAULT ((1 << ZSTD_WINDOWLOG_MAX) + 1) /* defined within zstd.h */
  35. #endif
  36. /*-*******************************************************
  37. * Dependencies
  38. *********************************************************/
  39. #include <string.h> /* memcpy, memmove, memset */
  40. #include "mem.h" /* low level memory routines */
  41. #define FSE_STATIC_LINKING_ONLY
  42. #include "fse.h"
  43. #define HUF_STATIC_LINKING_ONLY
  44. #include "huf.h"
  45. #include "zstd_internal.h"
  46. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
  47. # include "zstd_legacy.h"
  48. #endif
  49. /*-*************************************
  50. * Errors
  51. ***************************************/
  52. #define ZSTD_isError ERR_isError /* for inlining */
  53. #define FSE_isError ERR_isError
  54. #define HUF_isError ERR_isError
  55. /*_*******************************************************
  56. * Memory operations
  57. **********************************************************/
  58. static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  59. /*-*************************************************************
  60. * Context management
  61. ***************************************************************/
  62. typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
  63. ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock,
  64. ZSTDds_decompressLastBlock, ZSTDds_checkChecksum,
  65. ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTD_dStage;
  66. typedef enum { zdss_init=0, zdss_loadHeader,
  67. zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage;
  68. typedef struct {
  69. FSE_DTable LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  70. FSE_DTable OFTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  71. FSE_DTable MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  72. HUF_DTable hufTable[HUF_DTABLE_SIZE(HufLog)]; /* can accommodate HUF_decompress4X */
  73. U32 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
  74. U32 rep[ZSTD_REP_NUM];
  75. } ZSTD_entropyDTables_t;
  76. struct ZSTD_DCtx_s
  77. {
  78. const FSE_DTable* LLTptr;
  79. const FSE_DTable* MLTptr;
  80. const FSE_DTable* OFTptr;
  81. const HUF_DTable* HUFptr;
  82. ZSTD_entropyDTables_t entropy;
  83. const void* previousDstEnd; /* detect continuity */
  84. const void* base; /* start of current segment */
  85. const void* vBase; /* virtual start of previous segment if it was just before current one */
  86. const void* dictEnd; /* end of previous segment */
  87. size_t expected;
  88. ZSTD_frameHeader fParams;
  89. U64 decodedSize;
  90. blockType_e bType; /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */
  91. ZSTD_dStage stage;
  92. U32 litEntropy;
  93. U32 fseEntropy;
  94. XXH64_state_t xxhState;
  95. size_t headerSize;
  96. U32 dictID;
  97. const BYTE* litPtr;
  98. ZSTD_customMem customMem;
  99. size_t litSize;
  100. size_t rleSize;
  101. size_t staticSize;
  102. /* streaming */
  103. ZSTD_DDict* ddictLocal;
  104. const ZSTD_DDict* ddict;
  105. ZSTD_dStreamStage streamStage;
  106. char* inBuff;
  107. size_t inBuffSize;
  108. size_t inPos;
  109. size_t maxWindowSize;
  110. char* outBuff;
  111. size_t outBuffSize;
  112. size_t outStart;
  113. size_t outEnd;
  114. size_t lhSize;
  115. void* legacyContext;
  116. U32 previousLegacyVersion;
  117. U32 legacyVersion;
  118. U32 hostageByte;
  119. /* workspace */
  120. BYTE litBuffer[ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH];
  121. BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];
  122. }; /* typedef'd to ZSTD_DCtx within "zstd.h" */
  123. size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)
  124. {
  125. if (dctx==NULL) return 0; /* support sizeof NULL */
  126. return sizeof(*dctx)
  127. + ZSTD_sizeof_DDict(dctx->ddictLocal)
  128. + dctx->inBuffSize + dctx->outBuffSize;
  129. }
  130. size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }
  131. size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
  132. {
  133. dctx->expected = ZSTD_frameHeaderSize_prefix;
  134. dctx->stage = ZSTDds_getFrameHeaderSize;
  135. dctx->decodedSize = 0;
  136. dctx->previousDstEnd = NULL;
  137. dctx->base = NULL;
  138. dctx->vBase = NULL;
  139. dctx->dictEnd = NULL;
  140. dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
  141. dctx->litEntropy = dctx->fseEntropy = 0;
  142. dctx->dictID = 0;
  143. MEM_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
  144. memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */
  145. dctx->LLTptr = dctx->entropy.LLTable;
  146. dctx->MLTptr = dctx->entropy.MLTable;
  147. dctx->OFTptr = dctx->entropy.OFTable;
  148. dctx->HUFptr = dctx->entropy.hufTable;
  149. return 0;
  150. }
  151. static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)
  152. {
  153. ZSTD_decompressBegin(dctx); /* cannot fail */
  154. dctx->staticSize = 0;
  155. dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
  156. dctx->ddict = NULL;
  157. dctx->ddictLocal = NULL;
  158. dctx->inBuff = NULL;
  159. dctx->inBuffSize = 0;
  160. dctx->outBuffSize = 0;
  161. dctx->streamStage = zdss_init;
  162. }
  163. ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
  164. {
  165. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  166. { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem);
  167. if (!dctx) return NULL;
  168. dctx->customMem = customMem;
  169. dctx->legacyContext = NULL;
  170. dctx->previousLegacyVersion = 0;
  171. ZSTD_initDCtx_internal(dctx);
  172. return dctx;
  173. }
  174. }
  175. ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)
  176. {
  177. ZSTD_DCtx* dctx = (ZSTD_DCtx*) workspace;
  178. if ((size_t)workspace & 7) return NULL; /* 8-aligned */
  179. if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */
  180. ZSTD_initDCtx_internal(dctx);
  181. dctx->staticSize = workspaceSize;
  182. dctx->inBuff = (char*)(dctx+1);
  183. return dctx;
  184. }
  185. ZSTD_DCtx* ZSTD_createDCtx(void)
  186. {
  187. return ZSTD_createDCtx_advanced(ZSTD_defaultCMem);
  188. }
  189. size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
  190. {
  191. if (dctx==NULL) return 0; /* support free on NULL */
  192. if (dctx->staticSize) return ERROR(memory_allocation); /* not compatible with static DCtx */
  193. { ZSTD_customMem const cMem = dctx->customMem;
  194. ZSTD_freeDDict(dctx->ddictLocal);
  195. dctx->ddictLocal = NULL;
  196. ZSTD_free(dctx->inBuff, cMem);
  197. dctx->inBuff = NULL;
  198. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
  199. if (dctx->legacyContext)
  200. ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
  201. #endif
  202. ZSTD_free(dctx, cMem);
  203. return 0;
  204. }
  205. }
  206. /* no longer useful */
  207. void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)
  208. {
  209. size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);
  210. memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */
  211. }
  212. /*-*************************************************************
  213. * Decompression section
  214. ***************************************************************/
  215. /*! ZSTD_isFrame() :
  216. * Tells if the content of `buffer` starts with a valid Frame Identifier.
  217. * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
  218. * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
  219. * Note 3 : Skippable Frame Identifiers are considered valid. */
  220. unsigned ZSTD_isFrame(const void* buffer, size_t size)
  221. {
  222. if (size < 4) return 0;
  223. { U32 const magic = MEM_readLE32(buffer);
  224. if (magic == ZSTD_MAGICNUMBER) return 1;
  225. if ((magic & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
  226. }
  227. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
  228. if (ZSTD_isLegacy(buffer, size)) return 1;
  229. #endif
  230. return 0;
  231. }
  232. /** ZSTD_frameHeaderSize() :
  233. * srcSize must be >= ZSTD_frameHeaderSize_prefix.
  234. * @return : size of the Frame Header */
  235. size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)
  236. {
  237. if (srcSize < ZSTD_frameHeaderSize_prefix) return ERROR(srcSize_wrong);
  238. { BYTE const fhd = ((const BYTE*)src)[4];
  239. U32 const dictID= fhd & 3;
  240. U32 const singleSegment = (fhd >> 5) & 1;
  241. U32 const fcsId = fhd >> 6;
  242. return ZSTD_frameHeaderSize_prefix + !singleSegment + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]
  243. + (singleSegment && !fcsId);
  244. }
  245. }
  246. /** ZSTD_getFrameHeader() :
  247. * decode Frame Header, or require larger `srcSize`.
  248. * @return : 0, `zfhPtr` is correctly filled,
  249. * >0, `srcSize` is too small, result is expected `srcSize`,
  250. * or an error code, which can be tested using ZSTD_isError() */
  251. size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)
  252. {
  253. const BYTE* ip = (const BYTE*)src;
  254. if (srcSize < ZSTD_frameHeaderSize_prefix) return ZSTD_frameHeaderSize_prefix;
  255. if (MEM_readLE32(src) != ZSTD_MAGICNUMBER) {
  256. if ((MEM_readLE32(src) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  257. /* skippable frame */
  258. if (srcSize < ZSTD_skippableHeaderSize)
  259. return ZSTD_skippableHeaderSize; /* magic number + frame length */
  260. memset(zfhPtr, 0, sizeof(*zfhPtr));
  261. zfhPtr->frameContentSize = MEM_readLE32((const char *)src + 4);
  262. zfhPtr->frameType = ZSTD_skippableFrame;
  263. return 0;
  264. }
  265. return ERROR(prefix_unknown);
  266. }
  267. /* ensure there is enough `srcSize` to fully read/decode frame header */
  268. { size_t const fhsize = ZSTD_frameHeaderSize(src, srcSize);
  269. if (srcSize < fhsize) return fhsize;
  270. zfhPtr->headerSize = (U32)fhsize;
  271. }
  272. { BYTE const fhdByte = ip[4];
  273. size_t pos = 5;
  274. U32 const dictIDSizeCode = fhdByte&3;
  275. U32 const checksumFlag = (fhdByte>>2)&1;
  276. U32 const singleSegment = (fhdByte>>5)&1;
  277. U32 const fcsID = fhdByte>>6;
  278. U64 windowSize = 0;
  279. U32 dictID = 0;
  280. U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;
  281. if ((fhdByte & 0x08) != 0)
  282. return ERROR(frameParameter_unsupported); /* reserved bits, must be zero */
  283. if (!singleSegment) {
  284. BYTE const wlByte = ip[pos++];
  285. U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
  286. if (windowLog > ZSTD_WINDOWLOG_MAX)
  287. return ERROR(frameParameter_windowTooLarge);
  288. windowSize = (1ULL << windowLog);
  289. windowSize += (windowSize >> 3) * (wlByte&7);
  290. }
  291. switch(dictIDSizeCode)
  292. {
  293. default: assert(0); /* impossible */
  294. case 0 : break;
  295. case 1 : dictID = ip[pos]; pos++; break;
  296. case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
  297. case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
  298. }
  299. switch(fcsID)
  300. {
  301. default: assert(0); /* impossible */
  302. case 0 : if (singleSegment) frameContentSize = ip[pos]; break;
  303. case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
  304. case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
  305. case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
  306. }
  307. if (singleSegment) windowSize = frameContentSize;
  308. zfhPtr->frameType = ZSTD_frame;
  309. zfhPtr->frameContentSize = frameContentSize;
  310. zfhPtr->windowSize = windowSize;
  311. zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
  312. zfhPtr->dictID = dictID;
  313. zfhPtr->checksumFlag = checksumFlag;
  314. }
  315. return 0;
  316. }
  317. /** ZSTD_getFrameContentSize() :
  318. * compatible with legacy mode
  319. * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
  320. * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
  321. * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
  322. unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
  323. {
  324. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
  325. if (ZSTD_isLegacy(src, srcSize)) {
  326. unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
  327. return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
  328. }
  329. #endif
  330. { ZSTD_frameHeader zfh;
  331. if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
  332. return ZSTD_CONTENTSIZE_ERROR;
  333. if (zfh.frameType == ZSTD_skippableFrame) {
  334. return 0;
  335. } else {
  336. return zfh.frameContentSize;
  337. } }
  338. }
  339. /** ZSTD_findDecompressedSize() :
  340. * compatible with legacy mode
  341. * `srcSize` must be the exact length of some number of ZSTD compressed and/or
  342. * skippable frames
  343. * @return : decompressed size of the frames contained */
  344. unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)
  345. {
  346. unsigned long long totalDstSize = 0;
  347. while (srcSize >= ZSTD_frameHeaderSize_prefix) {
  348. const U32 magicNumber = MEM_readLE32(src);
  349. if ((magicNumber & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  350. size_t skippableSize;
  351. if (srcSize < ZSTD_skippableHeaderSize)
  352. return ERROR(srcSize_wrong);
  353. skippableSize = MEM_readLE32((const BYTE *)src + 4) +
  354. ZSTD_skippableHeaderSize;
  355. if (srcSize < skippableSize) {
  356. return ZSTD_CONTENTSIZE_ERROR;
  357. }
  358. src = (const BYTE *)src + skippableSize;
  359. srcSize -= skippableSize;
  360. continue;
  361. }
  362. { unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
  363. if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret;
  364. /* check for overflow */
  365. if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR;
  366. totalDstSize += ret;
  367. }
  368. { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
  369. if (ZSTD_isError(frameSrcSize)) {
  370. return ZSTD_CONTENTSIZE_ERROR;
  371. }
  372. src = (const BYTE *)src + frameSrcSize;
  373. srcSize -= frameSrcSize;
  374. }
  375. }
  376. if (srcSize) {
  377. return ZSTD_CONTENTSIZE_ERROR;
  378. }
  379. return totalDstSize;
  380. }
  381. /** ZSTD_getDecompressedSize() :
  382. * compatible with legacy mode
  383. * @return : decompressed size if known, 0 otherwise
  384. note : 0 can mean any of the following :
  385. - frame content is empty
  386. - decompressed size field is not present in frame header
  387. - frame header unknown / not supported
  388. - frame header not complete (`srcSize` too small) */
  389. unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)
  390. {
  391. unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
  392. return ret >= ZSTD_CONTENTSIZE_ERROR ? 0 : ret;
  393. }
  394. /** ZSTD_decodeFrameHeader() :
  395. * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
  396. * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
  397. static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)
  398. {
  399. size_t const result = ZSTD_getFrameHeader(&(dctx->fParams), src, headerSize);
  400. if (ZSTD_isError(result)) return result; /* invalid header */
  401. if (result>0) return ERROR(srcSize_wrong); /* headerSize too small */
  402. if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID))
  403. return ERROR(dictionary_wrong);
  404. if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);
  405. return 0;
  406. }
  407. /*! ZSTD_getcBlockSize() :
  408. * Provides the size of compressed block from block header `src` */
  409. size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
  410. blockProperties_t* bpPtr)
  411. {
  412. if (srcSize < ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  413. { U32 const cBlockHeader = MEM_readLE24(src);
  414. U32 const cSize = cBlockHeader >> 3;
  415. bpPtr->lastBlock = cBlockHeader & 1;
  416. bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
  417. bpPtr->origSize = cSize; /* only useful for RLE */
  418. if (bpPtr->blockType == bt_rle) return 1;
  419. if (bpPtr->blockType == bt_reserved) return ERROR(corruption_detected);
  420. return cSize;
  421. }
  422. }
  423. static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
  424. const void* src, size_t srcSize)
  425. {
  426. if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall);
  427. memcpy(dst, src, srcSize);
  428. return srcSize;
  429. }
  430. static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,
  431. const void* src, size_t srcSize,
  432. size_t regenSize)
  433. {
  434. if (srcSize != 1) return ERROR(srcSize_wrong);
  435. if (regenSize > dstCapacity) return ERROR(dstSize_tooSmall);
  436. memset(dst, *(const BYTE*)src, regenSize);
  437. return regenSize;
  438. }
  439. /*! ZSTD_decodeLiteralsBlock() :
  440. @return : nb of bytes read from src (< srcSize ) */
  441. size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
  442. const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
  443. {
  444. if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
  445. { const BYTE* const istart = (const BYTE*) src;
  446. symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);
  447. switch(litEncType)
  448. {
  449. case set_repeat:
  450. if (dctx->litEntropy==0) return ERROR(dictionary_corrupted);
  451. /* fall-through */
  452. case set_compressed:
  453. if (srcSize < 5) return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3 */
  454. { size_t lhSize, litSize, litCSize;
  455. U32 singleStream=0;
  456. U32 const lhlCode = (istart[0] >> 2) & 3;
  457. U32 const lhc = MEM_readLE32(istart);
  458. switch(lhlCode)
  459. {
  460. case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */
  461. /* 2 - 2 - 10 - 10 */
  462. singleStream = !lhlCode;
  463. lhSize = 3;
  464. litSize = (lhc >> 4) & 0x3FF;
  465. litCSize = (lhc >> 14) & 0x3FF;
  466. break;
  467. case 2:
  468. /* 2 - 2 - 14 - 14 */
  469. lhSize = 4;
  470. litSize = (lhc >> 4) & 0x3FFF;
  471. litCSize = lhc >> 18;
  472. break;
  473. case 3:
  474. /* 2 - 2 - 18 - 18 */
  475. lhSize = 5;
  476. litSize = (lhc >> 4) & 0x3FFFF;
  477. litCSize = (lhc >> 22) + (istart[4] << 10);
  478. break;
  479. }
  480. if (litSize > ZSTD_BLOCKSIZE_MAX) return ERROR(corruption_detected);
  481. if (litCSize + lhSize > srcSize) return ERROR(corruption_detected);
  482. if (HUF_isError((litEncType==set_repeat) ?
  483. ( singleStream ?
  484. HUF_decompress1X_usingDTable(dctx->litBuffer, litSize, istart+lhSize, litCSize, dctx->HUFptr) :
  485. HUF_decompress4X_usingDTable(dctx->litBuffer, litSize, istart+lhSize, litCSize, dctx->HUFptr) ) :
  486. ( singleStream ?
  487. HUF_decompress1X2_DCtx_wksp(dctx->entropy.hufTable, dctx->litBuffer, litSize, istart+lhSize, litCSize,
  488. dctx->entropy.workspace, sizeof(dctx->entropy.workspace)) :
  489. HUF_decompress4X_hufOnly_wksp(dctx->entropy.hufTable, dctx->litBuffer, litSize, istart+lhSize, litCSize,
  490. dctx->entropy.workspace, sizeof(dctx->entropy.workspace)))))
  491. return ERROR(corruption_detected);
  492. dctx->litPtr = dctx->litBuffer;
  493. dctx->litSize = litSize;
  494. dctx->litEntropy = 1;
  495. if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
  496. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  497. return litCSize + lhSize;
  498. }
  499. case set_basic:
  500. { size_t litSize, lhSize;
  501. U32 const lhlCode = ((istart[0]) >> 2) & 3;
  502. switch(lhlCode)
  503. {
  504. case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
  505. lhSize = 1;
  506. litSize = istart[0] >> 3;
  507. break;
  508. case 1:
  509. lhSize = 2;
  510. litSize = MEM_readLE16(istart) >> 4;
  511. break;
  512. case 3:
  513. lhSize = 3;
  514. litSize = MEM_readLE24(istart) >> 4;
  515. break;
  516. }
  517. if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
  518. if (litSize+lhSize > srcSize) return ERROR(corruption_detected);
  519. memcpy(dctx->litBuffer, istart+lhSize, litSize);
  520. dctx->litPtr = dctx->litBuffer;
  521. dctx->litSize = litSize;
  522. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  523. return lhSize+litSize;
  524. }
  525. /* direct reference into compressed stream */
  526. dctx->litPtr = istart+lhSize;
  527. dctx->litSize = litSize;
  528. return lhSize+litSize;
  529. }
  530. case set_rle:
  531. { U32 const lhlCode = ((istart[0]) >> 2) & 3;
  532. size_t litSize, lhSize;
  533. switch(lhlCode)
  534. {
  535. case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
  536. lhSize = 1;
  537. litSize = istart[0] >> 3;
  538. break;
  539. case 1:
  540. lhSize = 2;
  541. litSize = MEM_readLE16(istart) >> 4;
  542. break;
  543. case 3:
  544. lhSize = 3;
  545. litSize = MEM_readLE24(istart) >> 4;
  546. if (srcSize<4) return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4 */
  547. break;
  548. }
  549. if (litSize > ZSTD_BLOCKSIZE_MAX) return ERROR(corruption_detected);
  550. memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
  551. dctx->litPtr = dctx->litBuffer;
  552. dctx->litSize = litSize;
  553. return lhSize+1;
  554. }
  555. default:
  556. return ERROR(corruption_detected); /* impossible */
  557. }
  558. }
  559. }
  560. typedef union {
  561. FSE_decode_t realData;
  562. U32 alignedBy4;
  563. } FSE_decode_t4;
  564. /* Default FSE distribution table for Literal Lengths */
  565. static const FSE_decode_t4 LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
  566. { { LL_DEFAULTNORMLOG, 1, 1 } }, /* header : tableLog, fastMode, fastMode */
  567. /* base, symbol, bits */
  568. { { 0, 0, 4 } }, { { 16, 0, 4 } }, { { 32, 1, 5 } }, { { 0, 3, 5 } },
  569. { { 0, 4, 5 } }, { { 0, 6, 5 } }, { { 0, 7, 5 } }, { { 0, 9, 5 } },
  570. { { 0, 10, 5 } }, { { 0, 12, 5 } }, { { 0, 14, 6 } }, { { 0, 16, 5 } },
  571. { { 0, 18, 5 } }, { { 0, 19, 5 } }, { { 0, 21, 5 } }, { { 0, 22, 5 } },
  572. { { 0, 24, 5 } }, { { 32, 25, 5 } }, { { 0, 26, 5 } }, { { 0, 27, 6 } },
  573. { { 0, 29, 6 } }, { { 0, 31, 6 } }, { { 32, 0, 4 } }, { { 0, 1, 4 } },
  574. { { 0, 2, 5 } }, { { 32, 4, 5 } }, { { 0, 5, 5 } }, { { 32, 7, 5 } },
  575. { { 0, 8, 5 } }, { { 32, 10, 5 } }, { { 0, 11, 5 } }, { { 0, 13, 6 } },
  576. { { 32, 16, 5 } }, { { 0, 17, 5 } }, { { 32, 19, 5 } }, { { 0, 20, 5 } },
  577. { { 32, 22, 5 } }, { { 0, 23, 5 } }, { { 0, 25, 4 } }, { { 16, 25, 4 } },
  578. { { 32, 26, 5 } }, { { 0, 28, 6 } }, { { 0, 30, 6 } }, { { 48, 0, 4 } },
  579. { { 16, 1, 4 } }, { { 32, 2, 5 } }, { { 32, 3, 5 } }, { { 32, 5, 5 } },
  580. { { 32, 6, 5 } }, { { 32, 8, 5 } }, { { 32, 9, 5 } }, { { 32, 11, 5 } },
  581. { { 32, 12, 5 } }, { { 0, 15, 6 } }, { { 32, 17, 5 } }, { { 32, 18, 5 } },
  582. { { 32, 20, 5 } }, { { 32, 21, 5 } }, { { 32, 23, 5 } }, { { 32, 24, 5 } },
  583. { { 0, 35, 6 } }, { { 0, 34, 6 } }, { { 0, 33, 6 } }, { { 0, 32, 6 } },
  584. }; /* LL_defaultDTable */
  585. /* Default FSE distribution table for Match Lengths */
  586. static const FSE_decode_t4 ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
  587. { { ML_DEFAULTNORMLOG, 1, 1 } }, /* header : tableLog, fastMode, fastMode */
  588. /* base, symbol, bits */
  589. { { 0, 0, 6 } }, { { 0, 1, 4 } }, { { 32, 2, 5 } }, { { 0, 3, 5 } },
  590. { { 0, 5, 5 } }, { { 0, 6, 5 } }, { { 0, 8, 5 } }, { { 0, 10, 6 } },
  591. { { 0, 13, 6 } }, { { 0, 16, 6 } }, { { 0, 19, 6 } }, { { 0, 22, 6 } },
  592. { { 0, 25, 6 } }, { { 0, 28, 6 } }, { { 0, 31, 6 } }, { { 0, 33, 6 } },
  593. { { 0, 35, 6 } }, { { 0, 37, 6 } }, { { 0, 39, 6 } }, { { 0, 41, 6 } },
  594. { { 0, 43, 6 } }, { { 0, 45, 6 } }, { { 16, 1, 4 } }, { { 0, 2, 4 } },
  595. { { 32, 3, 5 } }, { { 0, 4, 5 } }, { { 32, 6, 5 } }, { { 0, 7, 5 } },
  596. { { 0, 9, 6 } }, { { 0, 12, 6 } }, { { 0, 15, 6 } }, { { 0, 18, 6 } },
  597. { { 0, 21, 6 } }, { { 0, 24, 6 } }, { { 0, 27, 6 } }, { { 0, 30, 6 } },
  598. { { 0, 32, 6 } }, { { 0, 34, 6 } }, { { 0, 36, 6 } }, { { 0, 38, 6 } },
  599. { { 0, 40, 6 } }, { { 0, 42, 6 } }, { { 0, 44, 6 } }, { { 32, 1, 4 } },
  600. { { 48, 1, 4 } }, { { 16, 2, 4 } }, { { 32, 4, 5 } }, { { 32, 5, 5 } },
  601. { { 32, 7, 5 } }, { { 32, 8, 5 } }, { { 0, 11, 6 } }, { { 0, 14, 6 } },
  602. { { 0, 17, 6 } }, { { 0, 20, 6 } }, { { 0, 23, 6 } }, { { 0, 26, 6 } },
  603. { { 0, 29, 6 } }, { { 0, 52, 6 } }, { { 0, 51, 6 } }, { { 0, 50, 6 } },
  604. { { 0, 49, 6 } }, { { 0, 48, 6 } }, { { 0, 47, 6 } }, { { 0, 46, 6 } },
  605. }; /* ML_defaultDTable */
  606. /* Default FSE distribution table for Offset Codes */
  607. static const FSE_decode_t4 OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
  608. { { OF_DEFAULTNORMLOG, 1, 1 } }, /* header : tableLog, fastMode, fastMode */
  609. /* base, symbol, bits */
  610. { { 0, 0, 5 } }, { { 0, 6, 4 } },
  611. { { 0, 9, 5 } }, { { 0, 15, 5 } },
  612. { { 0, 21, 5 } }, { { 0, 3, 5 } },
  613. { { 0, 7, 4 } }, { { 0, 12, 5 } },
  614. { { 0, 18, 5 } }, { { 0, 23, 5 } },
  615. { { 0, 5, 5 } }, { { 0, 8, 4 } },
  616. { { 0, 14, 5 } }, { { 0, 20, 5 } },
  617. { { 0, 2, 5 } }, { { 16, 7, 4 } },
  618. { { 0, 11, 5 } }, { { 0, 17, 5 } },
  619. { { 0, 22, 5 } }, { { 0, 4, 5 } },
  620. { { 16, 8, 4 } }, { { 0, 13, 5 } },
  621. { { 0, 19, 5 } }, { { 0, 1, 5 } },
  622. { { 16, 6, 4 } }, { { 0, 10, 5 } },
  623. { { 0, 16, 5 } }, { { 0, 28, 5 } },
  624. { { 0, 27, 5 } }, { { 0, 26, 5 } },
  625. { { 0, 25, 5 } }, { { 0, 24, 5 } },
  626. }; /* OF_defaultDTable */
  627. /*! ZSTD_buildSeqTable() :
  628. @return : nb bytes read from src,
  629. or an error code if it fails, testable with ZSTD_isError()
  630. */
  631. static size_t ZSTD_buildSeqTable(FSE_DTable* DTableSpace, const FSE_DTable** DTablePtr,
  632. symbolEncodingType_e type, U32 max, U32 maxLog,
  633. const void* src, size_t srcSize,
  634. const FSE_decode_t4* defaultTable, U32 flagRepeatTable)
  635. {
  636. const void* const tmpPtr = defaultTable; /* bypass strict aliasing */
  637. switch(type)
  638. {
  639. case set_rle :
  640. if (!srcSize) return ERROR(srcSize_wrong);
  641. if ( (*(const BYTE*)src) > max) return ERROR(corruption_detected);
  642. FSE_buildDTable_rle(DTableSpace, *(const BYTE*)src);
  643. *DTablePtr = DTableSpace;
  644. return 1;
  645. case set_basic :
  646. *DTablePtr = (const FSE_DTable*)tmpPtr;
  647. return 0;
  648. case set_repeat:
  649. if (!flagRepeatTable) return ERROR(corruption_detected);
  650. return 0;
  651. default : /* impossible */
  652. case set_compressed :
  653. { U32 tableLog;
  654. S16 norm[MaxSeq+1];
  655. size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
  656. if (FSE_isError(headerSize)) return ERROR(corruption_detected);
  657. if (tableLog > maxLog) return ERROR(corruption_detected);
  658. FSE_buildDTable(DTableSpace, norm, max, tableLog);
  659. *DTablePtr = DTableSpace;
  660. return headerSize;
  661. } }
  662. }
  663. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
  664. const void* src, size_t srcSize)
  665. {
  666. const BYTE* const istart = (const BYTE* const)src;
  667. const BYTE* const iend = istart + srcSize;
  668. const BYTE* ip = istart;
  669. DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
  670. /* check */
  671. if (srcSize < MIN_SEQUENCES_SIZE) return ERROR(srcSize_wrong);
  672. /* SeqHead */
  673. { int nbSeq = *ip++;
  674. if (!nbSeq) { *nbSeqPtr=0; return 1; }
  675. if (nbSeq > 0x7F) {
  676. if (nbSeq == 0xFF) {
  677. if (ip+2 > iend) return ERROR(srcSize_wrong);
  678. nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2;
  679. } else {
  680. if (ip >= iend) return ERROR(srcSize_wrong);
  681. nbSeq = ((nbSeq-0x80)<<8) + *ip++;
  682. }
  683. }
  684. *nbSeqPtr = nbSeq;
  685. }
  686. /* FSE table descriptors */
  687. if (ip+4 > iend) return ERROR(srcSize_wrong); /* minimum possible size */
  688. { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
  689. symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
  690. symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
  691. ip++;
  692. /* Build DTables */
  693. { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
  694. LLtype, MaxLL, LLFSELog,
  695. ip, iend-ip, LL_defaultDTable, dctx->fseEntropy);
  696. if (ZSTD_isError(llhSize)) return ERROR(corruption_detected);
  697. ip += llhSize;
  698. }
  699. { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
  700. OFtype, MaxOff, OffFSELog,
  701. ip, iend-ip, OF_defaultDTable, dctx->fseEntropy);
  702. if (ZSTD_isError(ofhSize)) return ERROR(corruption_detected);
  703. ip += ofhSize;
  704. }
  705. { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
  706. MLtype, MaxML, MLFSELog,
  707. ip, iend-ip, ML_defaultDTable, dctx->fseEntropy);
  708. if (ZSTD_isError(mlhSize)) return ERROR(corruption_detected);
  709. ip += mlhSize;
  710. }
  711. }
  712. return ip-istart;
  713. }
  714. typedef struct {
  715. size_t litLength;
  716. size_t matchLength;
  717. size_t offset;
  718. const BYTE* match;
  719. } seq_t;
  720. typedef struct {
  721. BIT_DStream_t DStream;
  722. FSE_DState_t stateLL;
  723. FSE_DState_t stateOffb;
  724. FSE_DState_t stateML;
  725. size_t prevOffset[ZSTD_REP_NUM];
  726. const BYTE* base;
  727. size_t pos;
  728. uPtrDiff gotoDict;
  729. } seqState_t;
  730. FORCE_NOINLINE
  731. size_t ZSTD_execSequenceLast7(BYTE* op,
  732. BYTE* const oend, seq_t sequence,
  733. const BYTE** litPtr, const BYTE* const litLimit,
  734. const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
  735. {
  736. BYTE* const oLitEnd = op + sequence.litLength;
  737. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  738. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  739. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
  740. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  741. const BYTE* match = oLitEnd - sequence.offset;
  742. /* check */
  743. if (oMatchEnd>oend) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  744. if (iLitEnd > litLimit) return ERROR(corruption_detected); /* over-read beyond lit buffer */
  745. if (oLitEnd <= oend_w) return ERROR(GENERIC); /* Precondition */
  746. /* copy literals */
  747. if (op < oend_w) {
  748. ZSTD_wildcopy(op, *litPtr, oend_w - op);
  749. *litPtr += oend_w - op;
  750. op = oend_w;
  751. }
  752. while (op < oLitEnd) *op++ = *(*litPtr)++;
  753. /* copy Match */
  754. if (sequence.offset > (size_t)(oLitEnd - base)) {
  755. /* offset beyond prefix */
  756. if (sequence.offset > (size_t)(oLitEnd - vBase)) return ERROR(corruption_detected);
  757. match = dictEnd - (base-match);
  758. if (match + sequence.matchLength <= dictEnd) {
  759. memmove(oLitEnd, match, sequence.matchLength);
  760. return sequenceLength;
  761. }
  762. /* span extDict & currentPrefixSegment */
  763. { size_t const length1 = dictEnd - match;
  764. memmove(oLitEnd, match, length1);
  765. op = oLitEnd + length1;
  766. sequence.matchLength -= length1;
  767. match = base;
  768. } }
  769. while (op < oMatchEnd) *op++ = *match++;
  770. return sequenceLength;
  771. }
  772. typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
  773. static seq_t ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets)
  774. {
  775. seq_t seq;
  776. U32 const llCode = FSE_peekSymbol(&seqState->stateLL);
  777. U32 const mlCode = FSE_peekSymbol(&seqState->stateML);
  778. U32 const ofCode = FSE_peekSymbol(&seqState->stateOffb); /* <= maxOff, by table construction */
  779. U32 const llBits = LL_bits[llCode];
  780. U32 const mlBits = ML_bits[mlCode];
  781. U32 const ofBits = ofCode;
  782. U32 const totalBits = llBits+mlBits+ofBits;
  783. static const U32 LL_base[MaxLL+1] = {
  784. 0, 1, 2, 3, 4, 5, 6, 7,
  785. 8, 9, 10, 11, 12, 13, 14, 15,
  786. 16, 18, 20, 22, 24, 28, 32, 40,
  787. 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
  788. 0x2000, 0x4000, 0x8000, 0x10000 };
  789. static const U32 ML_base[MaxML+1] = {
  790. 3, 4, 5, 6, 7, 8, 9, 10,
  791. 11, 12, 13, 14, 15, 16, 17, 18,
  792. 19, 20, 21, 22, 23, 24, 25, 26,
  793. 27, 28, 29, 30, 31, 32, 33, 34,
  794. 35, 37, 39, 41, 43, 47, 51, 59,
  795. 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
  796. 0x1003, 0x2003, 0x4003, 0x8003, 0x10003 };
  797. static const U32 OF_base[MaxOff+1] = {
  798. 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D,
  799. 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD,
  800. 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
  801. 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD };
  802. /* sequence */
  803. { size_t offset;
  804. if (!ofCode)
  805. offset = 0;
  806. else {
  807. ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
  808. if (longOffsets) {
  809. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN);
  810. offset = OF_base[ofCode] + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  811. if (MEM_32bits() || extraBits) BIT_reloadDStream(&seqState->DStream);
  812. if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  813. } else {
  814. offset = OF_base[ofCode] + BIT_readBitsFast(&seqState->DStream, ofBits); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  815. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
  816. }
  817. }
  818. if (ofCode <= 1) {
  819. offset += (llCode==0);
  820. if (offset) {
  821. size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  822. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  823. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  824. seqState->prevOffset[1] = seqState->prevOffset[0];
  825. seqState->prevOffset[0] = offset = temp;
  826. } else {
  827. offset = seqState->prevOffset[0];
  828. }
  829. } else {
  830. seqState->prevOffset[2] = seqState->prevOffset[1];
  831. seqState->prevOffset[1] = seqState->prevOffset[0];
  832. seqState->prevOffset[0] = offset;
  833. }
  834. seq.offset = offset;
  835. }
  836. seq.matchLength = ML_base[mlCode]
  837. + ((mlCode>31) ? BIT_readBitsFast(&seqState->DStream, mlBits) : 0); /* <= 16 bits */
  838. if (MEM_32bits() && (mlBits+llBits>24)) BIT_reloadDStream(&seqState->DStream);
  839. seq.litLength = LL_base[llCode]
  840. + ((llCode>15) ? BIT_readBitsFast(&seqState->DStream, llBits) : 0); /* <= 16 bits */
  841. if ( MEM_32bits()
  842. || (totalBits > 64 - 7 - (LLFSELog+MLFSELog+OffFSELog)) )
  843. BIT_reloadDStream(&seqState->DStream);
  844. DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
  845. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  846. /* ANS state update */
  847. FSE_updateState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  848. FSE_updateState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  849. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  850. FSE_updateState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  851. return seq;
  852. }
  853. HINT_INLINE
  854. size_t ZSTD_execSequence(BYTE* op,
  855. BYTE* const oend, seq_t sequence,
  856. const BYTE** litPtr, const BYTE* const litLimit,
  857. const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
  858. {
  859. BYTE* const oLitEnd = op + sequence.litLength;
  860. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  861. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  862. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
  863. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  864. const BYTE* match = oLitEnd - sequence.offset;
  865. /* check */
  866. if (oMatchEnd>oend) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  867. if (iLitEnd > litLimit) return ERROR(corruption_detected); /* over-read beyond lit buffer */
  868. if (oLitEnd>oend_w) return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, base, vBase, dictEnd);
  869. /* copy Literals */
  870. ZSTD_copy8(op, *litPtr);
  871. if (sequence.litLength > 8)
  872. ZSTD_wildcopy(op+8, (*litPtr)+8, sequence.litLength - 8); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
  873. op = oLitEnd;
  874. *litPtr = iLitEnd; /* update for next sequence */
  875. /* copy Match */
  876. if (sequence.offset > (size_t)(oLitEnd - base)) {
  877. /* offset beyond prefix -> go into extDict */
  878. if (sequence.offset > (size_t)(oLitEnd - vBase))
  879. return ERROR(corruption_detected);
  880. match = dictEnd + (match - base);
  881. if (match + sequence.matchLength <= dictEnd) {
  882. memmove(oLitEnd, match, sequence.matchLength);
  883. return sequenceLength;
  884. }
  885. /* span extDict & currentPrefixSegment */
  886. { size_t const length1 = dictEnd - match;
  887. memmove(oLitEnd, match, length1);
  888. op = oLitEnd + length1;
  889. sequence.matchLength -= length1;
  890. match = base;
  891. if (op > oend_w || sequence.matchLength < MINMATCH) {
  892. U32 i;
  893. for (i = 0; i < sequence.matchLength; ++i) op[i] = match[i];
  894. return sequenceLength;
  895. }
  896. } }
  897. /* Requirement: op <= oend_w && sequence.matchLength >= MINMATCH */
  898. /* match within prefix */
  899. if (sequence.offset < 8) {
  900. /* close range match, overlap */
  901. static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  902. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
  903. int const sub2 = dec64table[sequence.offset];
  904. op[0] = match[0];
  905. op[1] = match[1];
  906. op[2] = match[2];
  907. op[3] = match[3];
  908. match += dec32table[sequence.offset];
  909. ZSTD_copy4(op+4, match);
  910. match -= sub2;
  911. } else {
  912. ZSTD_copy8(op, match);
  913. }
  914. op += 8; match += 8;
  915. if (oMatchEnd > oend-(16-MINMATCH)) {
  916. if (op < oend_w) {
  917. ZSTD_wildcopy(op, match, oend_w - op);
  918. match += oend_w - op;
  919. op = oend_w;
  920. }
  921. while (op < oMatchEnd) *op++ = *match++;
  922. } else {
  923. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
  924. }
  925. return sequenceLength;
  926. }
  927. static size_t ZSTD_decompressSequences(
  928. ZSTD_DCtx* dctx,
  929. void* dst, size_t maxDstSize,
  930. const void* seqStart, size_t seqSize,
  931. const ZSTD_longOffset_e isLongOffset)
  932. {
  933. const BYTE* ip = (const BYTE*)seqStart;
  934. const BYTE* const iend = ip + seqSize;
  935. BYTE* const ostart = (BYTE* const)dst;
  936. BYTE* const oend = ostart + maxDstSize;
  937. BYTE* op = ostart;
  938. const BYTE* litPtr = dctx->litPtr;
  939. const BYTE* const litEnd = litPtr + dctx->litSize;
  940. const BYTE* const base = (const BYTE*) (dctx->base);
  941. const BYTE* const vBase = (const BYTE*) (dctx->vBase);
  942. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  943. int nbSeq;
  944. DEBUGLOG(5, "ZSTD_decompressSequences");
  945. /* Build Decoding Tables */
  946. { size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, seqSize);
  947. DEBUGLOG(5, "ZSTD_decodeSeqHeaders: size=%u, nbSeq=%i",
  948. (U32)seqHSize, nbSeq);
  949. if (ZSTD_isError(seqHSize)) return seqHSize;
  950. ip += seqHSize;
  951. }
  952. /* Regen sequences */
  953. if (nbSeq) {
  954. seqState_t seqState;
  955. dctx->fseEntropy = 1;
  956. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  957. CHECK_E(BIT_initDStream(&seqState.DStream, ip, iend-ip), corruption_detected);
  958. FSE_initDState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  959. FSE_initDState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  960. FSE_initDState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  961. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && nbSeq ; ) {
  962. nbSeq--;
  963. { seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  964. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, base, vBase, dictEnd);
  965. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  966. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  967. op += oneSeqSize;
  968. } }
  969. /* check if reached exact end */
  970. DEBUGLOG(5, "after decode loop, remaining nbSeq : %i", nbSeq);
  971. if (nbSeq) return ERROR(corruption_detected);
  972. /* save reps for next block */
  973. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  974. }
  975. /* last literal segment */
  976. { size_t const lastLLSize = litEnd - litPtr;
  977. if (lastLLSize > (size_t)(oend-op)) return ERROR(dstSize_tooSmall);
  978. memcpy(op, litPtr, lastLLSize);
  979. op += lastLLSize;
  980. }
  981. return op-ostart;
  982. }
  983. HINT_INLINE
  984. seq_t ZSTD_decodeSequenceLong(seqState_t* seqState, ZSTD_longOffset_e const longOffsets)
  985. {
  986. seq_t seq;
  987. U32 const llCode = FSE_peekSymbol(&seqState->stateLL);
  988. U32 const mlCode = FSE_peekSymbol(&seqState->stateML);
  989. U32 const ofCode = FSE_peekSymbol(&seqState->stateOffb); /* <= maxOff, by table construction */
  990. U32 const llBits = LL_bits[llCode];
  991. U32 const mlBits = ML_bits[mlCode];
  992. U32 const ofBits = ofCode;
  993. U32 const totalBits = llBits+mlBits+ofBits;
  994. static const U32 LL_base[MaxLL+1] = {
  995. 0, 1, 2, 3, 4, 5, 6, 7,
  996. 8, 9, 10, 11, 12, 13, 14, 15,
  997. 16, 18, 20, 22, 24, 28, 32, 40,
  998. 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
  999. 0x2000, 0x4000, 0x8000, 0x10000 };
  1000. static const U32 ML_base[MaxML+1] = {
  1001. 3, 4, 5, 6, 7, 8, 9, 10,
  1002. 11, 12, 13, 14, 15, 16, 17, 18,
  1003. 19, 20, 21, 22, 23, 24, 25, 26,
  1004. 27, 28, 29, 30, 31, 32, 33, 34,
  1005. 35, 37, 39, 41, 43, 47, 51, 59,
  1006. 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
  1007. 0x1003, 0x2003, 0x4003, 0x8003, 0x10003 };
  1008. static const U32 OF_base[MaxOff+1] = {
  1009. 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D,
  1010. 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD,
  1011. 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
  1012. 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD };
  1013. /* sequence */
  1014. { size_t offset;
  1015. if (!ofCode)
  1016. offset = 0;
  1017. else {
  1018. ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
  1019. if (longOffsets) {
  1020. int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN);
  1021. offset = OF_base[ofCode] + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  1022. if (MEM_32bits() || extraBits) BIT_reloadDStream(&seqState->DStream);
  1023. if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  1024. } else {
  1025. offset = OF_base[ofCode] + BIT_readBitsFast(&seqState->DStream, ofBits); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  1026. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
  1027. }
  1028. }
  1029. if (ofCode <= 1) {
  1030. offset += (llCode==0);
  1031. if (offset) {
  1032. size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  1033. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  1034. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  1035. seqState->prevOffset[1] = seqState->prevOffset[0];
  1036. seqState->prevOffset[0] = offset = temp;
  1037. } else {
  1038. offset = seqState->prevOffset[0];
  1039. }
  1040. } else {
  1041. seqState->prevOffset[2] = seqState->prevOffset[1];
  1042. seqState->prevOffset[1] = seqState->prevOffset[0];
  1043. seqState->prevOffset[0] = offset;
  1044. }
  1045. seq.offset = offset;
  1046. }
  1047. seq.matchLength = ML_base[mlCode] + ((mlCode>31) ? BIT_readBitsFast(&seqState->DStream, mlBits) : 0); /* <= 16 bits */
  1048. if (MEM_32bits() && (mlBits+llBits>24)) BIT_reloadDStream(&seqState->DStream);
  1049. seq.litLength = LL_base[llCode] + ((llCode>15) ? BIT_readBitsFast(&seqState->DStream, llBits) : 0); /* <= 16 bits */
  1050. if (MEM_32bits() ||
  1051. (totalBits > 64 - 7 - (LLFSELog+MLFSELog+OffFSELog)) ) BIT_reloadDStream(&seqState->DStream);
  1052. { size_t const pos = seqState->pos + seq.litLength;
  1053. seq.match = seqState->base + pos - seq.offset; /* single memory segment */
  1054. if (seq.offset > pos) seq.match += seqState->gotoDict; /* separate memory segment */
  1055. seqState->pos = pos + seq.matchLength;
  1056. }
  1057. /* ANS state update */
  1058. FSE_updateState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  1059. FSE_updateState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  1060. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  1061. FSE_updateState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  1062. return seq;
  1063. }
  1064. HINT_INLINE
  1065. size_t ZSTD_execSequenceLong(BYTE* op,
  1066. BYTE* const oend, seq_t sequence,
  1067. const BYTE** litPtr, const BYTE* const litLimit,
  1068. const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
  1069. {
  1070. BYTE* const oLitEnd = op + sequence.litLength;
  1071. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  1072. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  1073. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
  1074. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  1075. const BYTE* match = sequence.match;
  1076. /* check */
  1077. if (oMatchEnd>oend) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  1078. if (iLitEnd > litLimit) return ERROR(corruption_detected); /* over-read beyond lit buffer */
  1079. if (oLitEnd>oend_w) return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, base, vBase, dictEnd);
  1080. /* copy Literals */
  1081. ZSTD_copy8(op, *litPtr);
  1082. if (sequence.litLength > 8)
  1083. ZSTD_wildcopy(op+8, (*litPtr)+8, sequence.litLength - 8); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
  1084. op = oLitEnd;
  1085. *litPtr = iLitEnd; /* update for next sequence */
  1086. /* copy Match */
  1087. if (sequence.offset > (size_t)(oLitEnd - base)) {
  1088. /* offset beyond prefix */
  1089. if (sequence.offset > (size_t)(oLitEnd - vBase)) return ERROR(corruption_detected);
  1090. if (match + sequence.matchLength <= dictEnd) {
  1091. memmove(oLitEnd, match, sequence.matchLength);
  1092. return sequenceLength;
  1093. }
  1094. /* span extDict & currentPrefixSegment */
  1095. { size_t const length1 = dictEnd - match;
  1096. memmove(oLitEnd, match, length1);
  1097. op = oLitEnd + length1;
  1098. sequence.matchLength -= length1;
  1099. match = base;
  1100. if (op > oend_w || sequence.matchLength < MINMATCH) {
  1101. U32 i;
  1102. for (i = 0; i < sequence.matchLength; ++i) op[i] = match[i];
  1103. return sequenceLength;
  1104. }
  1105. } }
  1106. assert(op <= oend_w);
  1107. assert(sequence.matchLength >= MINMATCH);
  1108. /* match within prefix */
  1109. if (sequence.offset < 8) {
  1110. /* close range match, overlap */
  1111. static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  1112. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
  1113. int const sub2 = dec64table[sequence.offset];
  1114. op[0] = match[0];
  1115. op[1] = match[1];
  1116. op[2] = match[2];
  1117. op[3] = match[3];
  1118. match += dec32table[sequence.offset];
  1119. ZSTD_copy4(op+4, match);
  1120. match -= sub2;
  1121. } else {
  1122. ZSTD_copy8(op, match);
  1123. }
  1124. op += 8; match += 8;
  1125. if (oMatchEnd > oend-(16-MINMATCH)) {
  1126. if (op < oend_w) {
  1127. ZSTD_wildcopy(op, match, oend_w - op);
  1128. match += oend_w - op;
  1129. op = oend_w;
  1130. }
  1131. while (op < oMatchEnd) *op++ = *match++;
  1132. } else {
  1133. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
  1134. }
  1135. return sequenceLength;
  1136. }
  1137. static size_t ZSTD_decompressSequencesLong(
  1138. ZSTD_DCtx* dctx,
  1139. void* dst, size_t maxDstSize,
  1140. const void* seqStart, size_t seqSize,
  1141. const ZSTD_longOffset_e isLongOffset)
  1142. {
  1143. const BYTE* ip = (const BYTE*)seqStart;
  1144. const BYTE* const iend = ip + seqSize;
  1145. BYTE* const ostart = (BYTE* const)dst;
  1146. BYTE* const oend = ostart + maxDstSize;
  1147. BYTE* op = ostart;
  1148. const BYTE* litPtr = dctx->litPtr;
  1149. const BYTE* const litEnd = litPtr + dctx->litSize;
  1150. const BYTE* const base = (const BYTE*) (dctx->base);
  1151. const BYTE* const vBase = (const BYTE*) (dctx->vBase);
  1152. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1153. int nbSeq;
  1154. /* Build Decoding Tables */
  1155. { size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, seqSize);
  1156. if (ZSTD_isError(seqHSize)) return seqHSize;
  1157. ip += seqHSize;
  1158. }
  1159. /* Regen sequences */
  1160. if (nbSeq) {
  1161. #define STORED_SEQS 4
  1162. #define STOSEQ_MASK (STORED_SEQS-1)
  1163. #define ADVANCED_SEQS 4
  1164. seq_t sequences[STORED_SEQS];
  1165. int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
  1166. seqState_t seqState;
  1167. int seqNb;
  1168. dctx->fseEntropy = 1;
  1169. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1170. seqState.base = base;
  1171. seqState.pos = (size_t)(op-base);
  1172. seqState.gotoDict = (uPtrDiff)dictEnd - (uPtrDiff)base; /* cast to avoid undefined behaviour */
  1173. CHECK_E(BIT_initDStream(&seqState.DStream, ip, iend-ip), corruption_detected);
  1174. FSE_initDState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1175. FSE_initDState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1176. FSE_initDState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1177. /* prepare in advance */
  1178. for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && seqNb<seqAdvance; seqNb++) {
  1179. sequences[seqNb] = ZSTD_decodeSequenceLong(&seqState, isLongOffset);
  1180. }
  1181. if (seqNb<seqAdvance) return ERROR(corruption_detected);
  1182. /* decode and decompress */
  1183. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && seqNb<nbSeq ; seqNb++) {
  1184. seq_t const sequence = ZSTD_decodeSequenceLong(&seqState, isLongOffset);
  1185. size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STOSEQ_MASK], &litPtr, litEnd, base, vBase, dictEnd);
  1186. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1187. PREFETCH(sequence.match);
  1188. sequences[seqNb&STOSEQ_MASK] = sequence;
  1189. op += oneSeqSize;
  1190. }
  1191. if (seqNb<nbSeq) return ERROR(corruption_detected);
  1192. /* finish queue */
  1193. seqNb -= seqAdvance;
  1194. for ( ; seqNb<nbSeq ; seqNb++) {
  1195. size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[seqNb&STOSEQ_MASK], &litPtr, litEnd, base, vBase, dictEnd);
  1196. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1197. op += oneSeqSize;
  1198. }
  1199. /* save reps for next block */
  1200. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1201. }
  1202. /* last literal segment */
  1203. { size_t const lastLLSize = litEnd - litPtr;
  1204. if (lastLLSize > (size_t)(oend-op)) return ERROR(dstSize_tooSmall);
  1205. memcpy(op, litPtr, lastLLSize);
  1206. op += lastLLSize;
  1207. }
  1208. return op-ostart;
  1209. }
  1210. static size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
  1211. void* dst, size_t dstCapacity,
  1212. const void* src, size_t srcSize, const int frame)
  1213. { /* blockType == blockCompressed */
  1214. const BYTE* ip = (const BYTE*)src;
  1215. /* isLongOffset must be true if there are long offsets.
  1216. * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
  1217. * We don't expect that to be the case in 64-bit mode.
  1218. * If we are in block mode we don't know the window size, so we have to be
  1219. * conservative.
  1220. */
  1221. ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN)));
  1222. /* windowSize could be any value at this point, since it is only validated
  1223. * in the streaming API.
  1224. */
  1225. DEBUGLOG(5, "ZSTD_decompressBlock_internal");
  1226. if (srcSize >= ZSTD_BLOCKSIZE_MAX) return ERROR(srcSize_wrong);
  1227. /* Decode literals section */
  1228. { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
  1229. DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
  1230. if (ZSTD_isError(litCSize)) return litCSize;
  1231. ip += litCSize;
  1232. srcSize -= litCSize;
  1233. }
  1234. if (frame && dctx->fParams.windowSize > (1<<23))
  1235. return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, isLongOffset);
  1236. return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, isLongOffset);
  1237. }
  1238. static void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
  1239. {
  1240. if (dst != dctx->previousDstEnd) { /* not contiguous */
  1241. dctx->dictEnd = dctx->previousDstEnd;
  1242. dctx->vBase = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  1243. dctx->base = dst;
  1244. dctx->previousDstEnd = dst;
  1245. }
  1246. }
  1247. size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
  1248. void* dst, size_t dstCapacity,
  1249. const void* src, size_t srcSize)
  1250. {
  1251. size_t dSize;
  1252. ZSTD_checkContinuity(dctx, dst);
  1253. dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
  1254. dctx->previousDstEnd = (char*)dst + dSize;
  1255. return dSize;
  1256. }
  1257. /** ZSTD_insertBlock() :
  1258. insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
  1259. ZSTDLIB_API size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)
  1260. {
  1261. ZSTD_checkContinuity(dctx, blockStart);
  1262. dctx->previousDstEnd = (const char*)blockStart + blockSize;
  1263. return blockSize;
  1264. }
  1265. size_t ZSTD_generateNxBytes(void* dst, size_t dstCapacity, BYTE byte, size_t length)
  1266. {
  1267. if (length > dstCapacity) return ERROR(dstSize_tooSmall);
  1268. memset(dst, byte, length);
  1269. return length;
  1270. }
  1271. /** ZSTD_findFrameCompressedSize() :
  1272. * compatible with legacy mode
  1273. * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
  1274. * `srcSize` must be at least as large as the frame contained
  1275. * @return : the compressed size of the frame starting at `src` */
  1276. size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
  1277. {
  1278. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
  1279. if (ZSTD_isLegacy(src, srcSize))
  1280. return ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
  1281. #endif
  1282. if ( (srcSize >= ZSTD_skippableHeaderSize)
  1283. && (MEM_readLE32(src) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START ) {
  1284. return ZSTD_skippableHeaderSize + MEM_readLE32((const BYTE*)src + 4);
  1285. } else {
  1286. const BYTE* ip = (const BYTE*)src;
  1287. const BYTE* const ipstart = ip;
  1288. size_t remainingSize = srcSize;
  1289. ZSTD_frameHeader zfh;
  1290. /* Extract Frame Header */
  1291. { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize);
  1292. if (ZSTD_isError(ret)) return ret;
  1293. if (ret > 0) return ERROR(srcSize_wrong);
  1294. }
  1295. ip += zfh.headerSize;
  1296. remainingSize -= zfh.headerSize;
  1297. /* Loop on each block */
  1298. while (1) {
  1299. blockProperties_t blockProperties;
  1300. size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  1301. if (ZSTD_isError(cBlockSize)) return cBlockSize;
  1302. if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
  1303. return ERROR(srcSize_wrong);
  1304. ip += ZSTD_blockHeaderSize + cBlockSize;
  1305. remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
  1306. if (blockProperties.lastBlock) break;
  1307. }
  1308. if (zfh.checksumFlag) { /* Final frame content checksum */
  1309. if (remainingSize < 4) return ERROR(srcSize_wrong);
  1310. ip += 4;
  1311. remainingSize -= 4;
  1312. }
  1313. return ip - ipstart;
  1314. }
  1315. }
  1316. /*! ZSTD_decompressFrame() :
  1317. * @dctx must be properly initialized */
  1318. static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
  1319. void* dst, size_t dstCapacity,
  1320. const void** srcPtr, size_t *srcSizePtr)
  1321. {
  1322. const BYTE* ip = (const BYTE*)(*srcPtr);
  1323. BYTE* const ostart = (BYTE* const)dst;
  1324. BYTE* const oend = ostart + dstCapacity;
  1325. BYTE* op = ostart;
  1326. size_t remainingSize = *srcSizePtr;
  1327. /* check */
  1328. if (remainingSize < ZSTD_frameHeaderSize_min+ZSTD_blockHeaderSize)
  1329. return ERROR(srcSize_wrong);
  1330. /* Frame Header */
  1331. { size_t const frameHeaderSize = ZSTD_frameHeaderSize(ip, ZSTD_frameHeaderSize_prefix);
  1332. if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
  1333. if (remainingSize < frameHeaderSize+ZSTD_blockHeaderSize)
  1334. return ERROR(srcSize_wrong);
  1335. CHECK_F( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) );
  1336. ip += frameHeaderSize; remainingSize -= frameHeaderSize;
  1337. }
  1338. /* Loop on each block */
  1339. while (1) {
  1340. size_t decodedSize;
  1341. blockProperties_t blockProperties;
  1342. size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  1343. if (ZSTD_isError(cBlockSize)) return cBlockSize;
  1344. ip += ZSTD_blockHeaderSize;
  1345. remainingSize -= ZSTD_blockHeaderSize;
  1346. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  1347. switch(blockProperties.blockType)
  1348. {
  1349. case bt_compressed:
  1350. decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1);
  1351. break;
  1352. case bt_raw :
  1353. decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);
  1354. break;
  1355. case bt_rle :
  1356. decodedSize = ZSTD_generateNxBytes(op, oend-op, *ip, blockProperties.origSize);
  1357. break;
  1358. case bt_reserved :
  1359. default:
  1360. return ERROR(corruption_detected);
  1361. }
  1362. if (ZSTD_isError(decodedSize)) return decodedSize;
  1363. if (dctx->fParams.checksumFlag)
  1364. XXH64_update(&dctx->xxhState, op, decodedSize);
  1365. op += decodedSize;
  1366. ip += cBlockSize;
  1367. remainingSize -= cBlockSize;
  1368. if (blockProperties.lastBlock) break;
  1369. }
  1370. if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
  1371. U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
  1372. U32 checkRead;
  1373. if (remainingSize<4) return ERROR(checksum_wrong);
  1374. checkRead = MEM_readLE32(ip);
  1375. if (checkRead != checkCalc) return ERROR(checksum_wrong);
  1376. ip += 4;
  1377. remainingSize -= 4;
  1378. }
  1379. /* Allow caller to get size read */
  1380. *srcPtr = ip;
  1381. *srcSizePtr = remainingSize;
  1382. return op-ostart;
  1383. }
  1384. static const void* ZSTD_DDictDictContent(const ZSTD_DDict* ddict);
  1385. static size_t ZSTD_DDictDictSize(const ZSTD_DDict* ddict);
  1386. static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
  1387. void* dst, size_t dstCapacity,
  1388. const void* src, size_t srcSize,
  1389. const void* dict, size_t dictSize,
  1390. const ZSTD_DDict* ddict)
  1391. {
  1392. void* const dststart = dst;
  1393. assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */
  1394. if (ddict) {
  1395. dict = ZSTD_DDictDictContent(ddict);
  1396. dictSize = ZSTD_DDictDictSize(ddict);
  1397. }
  1398. while (srcSize >= ZSTD_frameHeaderSize_prefix) {
  1399. U32 magicNumber;
  1400. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
  1401. if (ZSTD_isLegacy(src, srcSize)) {
  1402. size_t decodedSize;
  1403. size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
  1404. if (ZSTD_isError(frameSize)) return frameSize;
  1405. /* legacy support is not compatible with static dctx */
  1406. if (dctx->staticSize) return ERROR(memory_allocation);
  1407. decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
  1408. dst = (BYTE*)dst + decodedSize;
  1409. dstCapacity -= decodedSize;
  1410. src = (const BYTE*)src + frameSize;
  1411. srcSize -= frameSize;
  1412. continue;
  1413. }
  1414. #endif
  1415. magicNumber = MEM_readLE32(src);
  1416. if (magicNumber != ZSTD_MAGICNUMBER) {
  1417. if ((magicNumber & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
  1418. size_t skippableSize;
  1419. if (srcSize < ZSTD_skippableHeaderSize)
  1420. return ERROR(srcSize_wrong);
  1421. skippableSize = MEM_readLE32((const BYTE *)src + 4) +
  1422. ZSTD_skippableHeaderSize;
  1423. if (srcSize < skippableSize) return ERROR(srcSize_wrong);
  1424. src = (const BYTE *)src + skippableSize;
  1425. srcSize -= skippableSize;
  1426. continue;
  1427. }
  1428. return ERROR(prefix_unknown);
  1429. }
  1430. if (ddict) {
  1431. /* we were called from ZSTD_decompress_usingDDict */
  1432. CHECK_F(ZSTD_decompressBegin_usingDDict(dctx, ddict));
  1433. } else {
  1434. /* this will initialize correctly with no dict if dict == NULL, so
  1435. * use this in all cases but ddict */
  1436. CHECK_F(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize));
  1437. }
  1438. ZSTD_checkContinuity(dctx, dst);
  1439. { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
  1440. &src, &srcSize);
  1441. if (ZSTD_isError(res)) return res;
  1442. /* no need to bound check, ZSTD_decompressFrame already has */
  1443. dst = (BYTE*)dst + res;
  1444. dstCapacity -= res;
  1445. }
  1446. } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
  1447. if (srcSize) return ERROR(srcSize_wrong); /* input not entirely consumed */
  1448. return (BYTE*)dst - (BYTE*)dststart;
  1449. }
  1450. size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
  1451. void* dst, size_t dstCapacity,
  1452. const void* src, size_t srcSize,
  1453. const void* dict, size_t dictSize)
  1454. {
  1455. return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
  1456. }
  1457. size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1458. {
  1459. return ZSTD_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
  1460. }
  1461. size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1462. {
  1463. #if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
  1464. size_t regenSize;
  1465. ZSTD_DCtx* const dctx = ZSTD_createDCtx();
  1466. if (dctx==NULL) return ERROR(memory_allocation);
  1467. regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
  1468. ZSTD_freeDCtx(dctx);
  1469. return regenSize;
  1470. #else /* stack mode */
  1471. ZSTD_DCtx dctx;
  1472. return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
  1473. #endif
  1474. }
  1475. /*-**************************************
  1476. * Advanced Streaming Decompression API
  1477. * Bufferless and synchronous
  1478. ****************************************/
  1479. size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }
  1480. ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {
  1481. switch(dctx->stage)
  1482. {
  1483. default: /* should not happen */
  1484. assert(0);
  1485. case ZSTDds_getFrameHeaderSize:
  1486. case ZSTDds_decodeFrameHeader:
  1487. return ZSTDnit_frameHeader;
  1488. case ZSTDds_decodeBlockHeader:
  1489. return ZSTDnit_blockHeader;
  1490. case ZSTDds_decompressBlock:
  1491. return ZSTDnit_block;
  1492. case ZSTDds_decompressLastBlock:
  1493. return ZSTDnit_lastBlock;
  1494. case ZSTDds_checkChecksum:
  1495. return ZSTDnit_checksum;
  1496. case ZSTDds_decodeSkippableHeader:
  1497. case ZSTDds_skipFrame:
  1498. return ZSTDnit_skippableFrame;
  1499. }
  1500. }
  1501. static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }
  1502. /** ZSTD_decompressContinue() :
  1503. * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())
  1504. * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
  1505. * or an error code, which can be tested using ZSTD_isError() */
  1506. size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  1507. {
  1508. DEBUGLOG(5, "ZSTD_decompressContinue");
  1509. /* Sanity check */
  1510. if (srcSize != dctx->expected) return ERROR(srcSize_wrong); /* unauthorized */
  1511. if (dstCapacity) ZSTD_checkContinuity(dctx, dst);
  1512. switch (dctx->stage)
  1513. {
  1514. case ZSTDds_getFrameHeaderSize :
  1515. if (srcSize != ZSTD_frameHeaderSize_prefix) return ERROR(srcSize_wrong); /* unauthorized */
  1516. assert(src != NULL);
  1517. if ((MEM_readLE32(src) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
  1518. memcpy(dctx->headerBuffer, src, ZSTD_frameHeaderSize_prefix);
  1519. dctx->expected = ZSTD_skippableHeaderSize - ZSTD_frameHeaderSize_prefix; /* magic number + skippable frame length */
  1520. dctx->stage = ZSTDds_decodeSkippableHeader;
  1521. return 0;
  1522. }
  1523. dctx->headerSize = ZSTD_frameHeaderSize(src, ZSTD_frameHeaderSize_prefix);
  1524. if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
  1525. memcpy(dctx->headerBuffer, src, ZSTD_frameHeaderSize_prefix);
  1526. if (dctx->headerSize > ZSTD_frameHeaderSize_prefix) {
  1527. dctx->expected = dctx->headerSize - ZSTD_frameHeaderSize_prefix;
  1528. dctx->stage = ZSTDds_decodeFrameHeader;
  1529. return 0;
  1530. }
  1531. dctx->expected = 0; /* not necessary to copy more */
  1532. /* fall-through */
  1533. case ZSTDds_decodeFrameHeader:
  1534. assert(src != NULL);
  1535. memcpy(dctx->headerBuffer + ZSTD_frameHeaderSize_prefix, src, dctx->expected);
  1536. CHECK_F(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize));
  1537. dctx->expected = ZSTD_blockHeaderSize;
  1538. dctx->stage = ZSTDds_decodeBlockHeader;
  1539. return 0;
  1540. case ZSTDds_decodeBlockHeader:
  1541. { blockProperties_t bp;
  1542. size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  1543. if (ZSTD_isError(cBlockSize)) return cBlockSize;
  1544. dctx->expected = cBlockSize;
  1545. dctx->bType = bp.blockType;
  1546. dctx->rleSize = bp.origSize;
  1547. if (cBlockSize) {
  1548. dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
  1549. return 0;
  1550. }
  1551. /* empty block */
  1552. if (bp.lastBlock) {
  1553. if (dctx->fParams.checksumFlag) {
  1554. dctx->expected = 4;
  1555. dctx->stage = ZSTDds_checkChecksum;
  1556. } else {
  1557. dctx->expected = 0; /* end of frame */
  1558. dctx->stage = ZSTDds_getFrameHeaderSize;
  1559. }
  1560. } else {
  1561. dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */
  1562. dctx->stage = ZSTDds_decodeBlockHeader;
  1563. }
  1564. return 0;
  1565. }
  1566. case ZSTDds_decompressLastBlock:
  1567. case ZSTDds_decompressBlock:
  1568. DEBUGLOG(5, "case ZSTDds_decompressBlock");
  1569. { size_t rSize;
  1570. switch(dctx->bType)
  1571. {
  1572. case bt_compressed:
  1573. DEBUGLOG(5, "case bt_compressed");
  1574. rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1);
  1575. break;
  1576. case bt_raw :
  1577. rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
  1578. break;
  1579. case bt_rle :
  1580. rSize = ZSTD_setRleBlock(dst, dstCapacity, src, srcSize, dctx->rleSize);
  1581. break;
  1582. case bt_reserved : /* should never happen */
  1583. default:
  1584. return ERROR(corruption_detected);
  1585. }
  1586. if (ZSTD_isError(rSize)) return rSize;
  1587. DEBUGLOG(5, "decoded size from block : %u", (U32)rSize);
  1588. dctx->decodedSize += rSize;
  1589. if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
  1590. if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */
  1591. DEBUGLOG(4, "decoded size from frame : %u", (U32)dctx->decodedSize);
  1592. if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
  1593. if (dctx->decodedSize != dctx->fParams.frameContentSize) {
  1594. return ERROR(corruption_detected);
  1595. } }
  1596. if (dctx->fParams.checksumFlag) { /* another round for frame checksum */
  1597. dctx->expected = 4;
  1598. dctx->stage = ZSTDds_checkChecksum;
  1599. } else {
  1600. dctx->expected = 0; /* ends here */
  1601. dctx->stage = ZSTDds_getFrameHeaderSize;
  1602. }
  1603. } else {
  1604. dctx->stage = ZSTDds_decodeBlockHeader;
  1605. dctx->expected = ZSTD_blockHeaderSize;
  1606. dctx->previousDstEnd = (char*)dst + rSize;
  1607. }
  1608. return rSize;
  1609. }
  1610. case ZSTDds_checkChecksum:
  1611. DEBUGLOG(4, "case ZSTDds_checkChecksum");
  1612. assert(srcSize == 4); /* guaranteed by dctx->expected */
  1613. { U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
  1614. U32 const check32 = MEM_readLE32(src);
  1615. DEBUGLOG(4, "calculated %08X :: %08X read", h32, check32);
  1616. if (check32 != h32) return ERROR(checksum_wrong);
  1617. dctx->expected = 0;
  1618. dctx->stage = ZSTDds_getFrameHeaderSize;
  1619. return 0;
  1620. }
  1621. case ZSTDds_decodeSkippableHeader:
  1622. { assert(src != NULL);
  1623. memcpy(dctx->headerBuffer + ZSTD_frameHeaderSize_prefix, src, dctx->expected);
  1624. dctx->expected = MEM_readLE32(dctx->headerBuffer + 4);
  1625. dctx->stage = ZSTDds_skipFrame;
  1626. return 0;
  1627. }
  1628. case ZSTDds_skipFrame:
  1629. { dctx->expected = 0;
  1630. dctx->stage = ZSTDds_getFrameHeaderSize;
  1631. return 0;
  1632. }
  1633. default:
  1634. return ERROR(GENERIC); /* impossible */
  1635. }
  1636. }
  1637. static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
  1638. {
  1639. dctx->dictEnd = dctx->previousDstEnd;
  1640. dctx->vBase = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  1641. dctx->base = dict;
  1642. dctx->previousDstEnd = (const char*)dict + dictSize;
  1643. return 0;
  1644. }
  1645. /* ZSTD_loadEntropy() :
  1646. * dict : must point at beginning of a valid zstd dictionary
  1647. * @return : size of entropy tables read */
  1648. static size_t ZSTD_loadEntropy(ZSTD_entropyDTables_t* entropy, const void* const dict, size_t const dictSize)
  1649. {
  1650. const BYTE* dictPtr = (const BYTE*)dict;
  1651. const BYTE* const dictEnd = dictPtr + dictSize;
  1652. if (dictSize <= 8) return ERROR(dictionary_corrupted);
  1653. dictPtr += 8; /* skip header = magic + dictID */
  1654. { size_t const hSize = HUF_readDTableX4_wksp(
  1655. entropy->hufTable, dictPtr, dictEnd - dictPtr,
  1656. entropy->workspace, sizeof(entropy->workspace));
  1657. if (HUF_isError(hSize)) return ERROR(dictionary_corrupted);
  1658. dictPtr += hSize;
  1659. }
  1660. { short offcodeNCount[MaxOff+1];
  1661. U32 offcodeMaxValue = MaxOff, offcodeLog;
  1662. size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
  1663. if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  1664. if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
  1665. CHECK_E(FSE_buildDTable(entropy->OFTable, offcodeNCount, offcodeMaxValue, offcodeLog), dictionary_corrupted);
  1666. dictPtr += offcodeHeaderSize;
  1667. }
  1668. { short matchlengthNCount[MaxML+1];
  1669. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  1670. size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
  1671. if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1672. if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
  1673. CHECK_E(FSE_buildDTable(entropy->MLTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog), dictionary_corrupted);
  1674. dictPtr += matchlengthHeaderSize;
  1675. }
  1676. { short litlengthNCount[MaxLL+1];
  1677. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  1678. size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
  1679. if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  1680. if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
  1681. CHECK_E(FSE_buildDTable(entropy->LLTable, litlengthNCount, litlengthMaxValue, litlengthLog), dictionary_corrupted);
  1682. dictPtr += litlengthHeaderSize;
  1683. }
  1684. if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
  1685. { int i;
  1686. size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
  1687. for (i=0; i<3; i++) {
  1688. U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
  1689. if (rep==0 || rep >= dictContentSize) return ERROR(dictionary_corrupted);
  1690. entropy->rep[i] = rep;
  1691. } }
  1692. return dictPtr - (const BYTE*)dict;
  1693. }
  1694. static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
  1695. {
  1696. if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
  1697. { U32 const magic = MEM_readLE32(dict);
  1698. if (magic != ZSTD_MAGIC_DICTIONARY) {
  1699. return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */
  1700. } }
  1701. dctx->dictID = MEM_readLE32((const char*)dict + 4);
  1702. /* load entropy tables */
  1703. { size_t const eSize = ZSTD_loadEntropy(&dctx->entropy, dict, dictSize);
  1704. if (ZSTD_isError(eSize)) return ERROR(dictionary_corrupted);
  1705. dict = (const char*)dict + eSize;
  1706. dictSize -= eSize;
  1707. }
  1708. dctx->litEntropy = dctx->fseEntropy = 1;
  1709. /* reference dictionary content */
  1710. return ZSTD_refDictContent(dctx, dict, dictSize);
  1711. }
  1712. size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
  1713. {
  1714. CHECK_F( ZSTD_decompressBegin(dctx) );
  1715. if (dict && dictSize)
  1716. CHECK_E(ZSTD_decompress_insertDictionary(dctx, dict, dictSize), dictionary_corrupted);
  1717. return 0;
  1718. }
  1719. /* ====== ZSTD_DDict ====== */
  1720. struct ZSTD_DDict_s {
  1721. void* dictBuffer;
  1722. const void* dictContent;
  1723. size_t dictSize;
  1724. ZSTD_entropyDTables_t entropy;
  1725. U32 dictID;
  1726. U32 entropyPresent;
  1727. ZSTD_customMem cMem;
  1728. }; /* typedef'd to ZSTD_DDict within "zstd.h" */
  1729. static const void* ZSTD_DDictDictContent(const ZSTD_DDict* ddict)
  1730. {
  1731. return ddict->dictContent;
  1732. }
  1733. static size_t ZSTD_DDictDictSize(const ZSTD_DDict* ddict)
  1734. {
  1735. return ddict->dictSize;
  1736. }
  1737. size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dstDCtx, const ZSTD_DDict* ddict)
  1738. {
  1739. CHECK_F( ZSTD_decompressBegin(dstDCtx) );
  1740. if (ddict) { /* support begin on NULL */
  1741. dstDCtx->dictID = ddict->dictID;
  1742. dstDCtx->base = ddict->dictContent;
  1743. dstDCtx->vBase = ddict->dictContent;
  1744. dstDCtx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize;
  1745. dstDCtx->previousDstEnd = dstDCtx->dictEnd;
  1746. if (ddict->entropyPresent) {
  1747. dstDCtx->litEntropy = 1;
  1748. dstDCtx->fseEntropy = 1;
  1749. dstDCtx->LLTptr = ddict->entropy.LLTable;
  1750. dstDCtx->MLTptr = ddict->entropy.MLTable;
  1751. dstDCtx->OFTptr = ddict->entropy.OFTable;
  1752. dstDCtx->HUFptr = ddict->entropy.hufTable;
  1753. dstDCtx->entropy.rep[0] = ddict->entropy.rep[0];
  1754. dstDCtx->entropy.rep[1] = ddict->entropy.rep[1];
  1755. dstDCtx->entropy.rep[2] = ddict->entropy.rep[2];
  1756. } else {
  1757. dstDCtx->litEntropy = 0;
  1758. dstDCtx->fseEntropy = 0;
  1759. }
  1760. }
  1761. return 0;
  1762. }
  1763. static size_t ZSTD_loadEntropy_inDDict(ZSTD_DDict* ddict)
  1764. {
  1765. ddict->dictID = 0;
  1766. ddict->entropyPresent = 0;
  1767. if (ddict->dictSize < 8) return 0;
  1768. { U32 const magic = MEM_readLE32(ddict->dictContent);
  1769. if (magic != ZSTD_MAGIC_DICTIONARY) return 0; /* pure content mode */
  1770. }
  1771. ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + 4);
  1772. /* load entropy tables */
  1773. CHECK_E( ZSTD_loadEntropy(&ddict->entropy, ddict->dictContent, ddict->dictSize), dictionary_corrupted );
  1774. ddict->entropyPresent = 1;
  1775. return 0;
  1776. }
  1777. static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod)
  1778. {
  1779. if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) {
  1780. ddict->dictBuffer = NULL;
  1781. ddict->dictContent = dict;
  1782. } else {
  1783. void* const internalBuffer = ZSTD_malloc(dictSize, ddict->cMem);
  1784. ddict->dictBuffer = internalBuffer;
  1785. ddict->dictContent = internalBuffer;
  1786. if (!internalBuffer) return ERROR(memory_allocation);
  1787. memcpy(internalBuffer, dict, dictSize);
  1788. }
  1789. ddict->dictSize = dictSize;
  1790. ddict->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
  1791. /* parse dictionary content */
  1792. CHECK_F( ZSTD_loadEntropy_inDDict(ddict) );
  1793. return 0;
  1794. }
  1795. ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_customMem customMem)
  1796. {
  1797. if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
  1798. { ZSTD_DDict* const ddict = (ZSTD_DDict*) ZSTD_malloc(sizeof(ZSTD_DDict), customMem);
  1799. if (!ddict) return NULL;
  1800. ddict->cMem = customMem;
  1801. if (ZSTD_isError( ZSTD_initDDict_internal(ddict, dict, dictSize, dictLoadMethod) )) {
  1802. ZSTD_freeDDict(ddict);
  1803. return NULL;
  1804. }
  1805. return ddict;
  1806. }
  1807. }
  1808. /*! ZSTD_createDDict() :
  1809. * Create a digested dictionary, to start decompression without startup delay.
  1810. * `dict` content is copied inside DDict.
  1811. * Consequently, `dict` can be released after `ZSTD_DDict` creation */
  1812. ZSTD_DDict* ZSTD_createDDict(const void* dict, size_t dictSize)
  1813. {
  1814. ZSTD_customMem const allocator = { NULL, NULL, NULL };
  1815. return ZSTD_createDDict_advanced(dict, dictSize, ZSTD_dlm_byCopy, allocator);
  1816. }
  1817. /*! ZSTD_createDDict_byReference() :
  1818. * Create a digested dictionary, to start decompression without startup delay.
  1819. * Dictionary content is simply referenced, it will be accessed during decompression.
  1820. * Warning : dictBuffer must outlive DDict (DDict must be freed before dictBuffer) */
  1821. ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize)
  1822. {
  1823. ZSTD_customMem const allocator = { NULL, NULL, NULL };
  1824. return ZSTD_createDDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, allocator);
  1825. }
  1826. ZSTD_DDict* ZSTD_initStaticDDict(void* workspace, size_t workspaceSize,
  1827. const void* dict, size_t dictSize,
  1828. ZSTD_dictLoadMethod_e dictLoadMethod)
  1829. {
  1830. size_t const neededSpace =
  1831. sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
  1832. ZSTD_DDict* const ddict = (ZSTD_DDict*)workspace;
  1833. assert(workspace != NULL);
  1834. assert(dict != NULL);
  1835. if ((size_t)workspace & 7) return NULL; /* 8-aligned */
  1836. if (workspaceSize < neededSpace) return NULL;
  1837. if (dictLoadMethod == ZSTD_dlm_byCopy) {
  1838. memcpy(ddict+1, dict, dictSize); /* local copy */
  1839. dict = ddict+1;
  1840. }
  1841. if (ZSTD_isError( ZSTD_initDDict_internal(ddict, dict, dictSize, ZSTD_dlm_byRef) ))
  1842. return NULL;
  1843. return ddict;
  1844. }
  1845. size_t ZSTD_freeDDict(ZSTD_DDict* ddict)
  1846. {
  1847. if (ddict==NULL) return 0; /* support free on NULL */
  1848. { ZSTD_customMem const cMem = ddict->cMem;
  1849. ZSTD_free(ddict->dictBuffer, cMem);
  1850. ZSTD_free(ddict, cMem);
  1851. return 0;
  1852. }
  1853. }
  1854. /*! ZSTD_estimateDDictSize() :
  1855. * Estimate amount of memory that will be needed to create a dictionary for decompression.
  1856. * Note : dictionary created by reference using ZSTD_dlm_byRef are smaller */
  1857. size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod)
  1858. {
  1859. return sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
  1860. }
  1861. size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict)
  1862. {
  1863. if (ddict==NULL) return 0; /* support sizeof on NULL */
  1864. return sizeof(*ddict) + (ddict->dictBuffer ? ddict->dictSize : 0) ;
  1865. }
  1866. /*! ZSTD_getDictID_fromDict() :
  1867. * Provides the dictID stored within dictionary.
  1868. * if @return == 0, the dictionary is not conformant with Zstandard specification.
  1869. * It can still be loaded, but as a content-only dictionary. */
  1870. unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)
  1871. {
  1872. if (dictSize < 8) return 0;
  1873. if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;
  1874. return MEM_readLE32((const char*)dict + 4);
  1875. }
  1876. /*! ZSTD_getDictID_fromDDict() :
  1877. * Provides the dictID of the dictionary loaded into `ddict`.
  1878. * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
  1879. * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
  1880. unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict)
  1881. {
  1882. if (ddict==NULL) return 0;
  1883. return ZSTD_getDictID_fromDict(ddict->dictContent, ddict->dictSize);
  1884. }
  1885. /*! ZSTD_getDictID_fromFrame() :
  1886. * Provides the dictID required to decompresse frame stored within `src`.
  1887. * If @return == 0, the dictID could not be decoded.
  1888. * This could for one of the following reasons :
  1889. * - The frame does not require a dictionary (most common case).
  1890. * - The frame was built with dictID intentionally removed.
  1891. * Needed dictionary is a hidden information.
  1892. * Note : this use case also happens when using a non-conformant dictionary.
  1893. * - `srcSize` is too small, and as a result, frame header could not be decoded.
  1894. * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.
  1895. * - This is not a Zstandard frame.
  1896. * When identifying the exact failure cause, it's possible to use
  1897. * ZSTD_getFrameHeader(), which will provide a more precise error code. */
  1898. unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)
  1899. {
  1900. ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 };
  1901. size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);
  1902. if (ZSTD_isError(hError)) return 0;
  1903. return zfp.dictID;
  1904. }
  1905. /*! ZSTD_decompress_usingDDict() :
  1906. * Decompression using a pre-digested Dictionary
  1907. * Use dictionary without significant overhead. */
  1908. size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
  1909. void* dst, size_t dstCapacity,
  1910. const void* src, size_t srcSize,
  1911. const ZSTD_DDict* ddict)
  1912. {
  1913. /* pass content and size in case legacy frames are encountered */
  1914. return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,
  1915. NULL, 0,
  1916. ddict);
  1917. }
  1918. /*=====================================
  1919. * Streaming decompression
  1920. *====================================*/
  1921. ZSTD_DStream* ZSTD_createDStream(void)
  1922. {
  1923. return ZSTD_createDStream_advanced(ZSTD_defaultCMem);
  1924. }
  1925. ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)
  1926. {
  1927. return ZSTD_initStaticDCtx(workspace, workspaceSize);
  1928. }
  1929. ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)
  1930. {
  1931. return ZSTD_createDCtx_advanced(customMem);
  1932. }
  1933. size_t ZSTD_freeDStream(ZSTD_DStream* zds)
  1934. {
  1935. return ZSTD_freeDCtx(zds);
  1936. }
  1937. /* *** Initialization *** */
  1938. size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }
  1939. size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }
  1940. size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)
  1941. {
  1942. zds->streamStage = zdss_loadHeader;
  1943. zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;
  1944. ZSTD_freeDDict(zds->ddictLocal);
  1945. if (dict && dictSize >= 8) {
  1946. zds->ddictLocal = ZSTD_createDDict(dict, dictSize);
  1947. if (zds->ddictLocal == NULL) return ERROR(memory_allocation);
  1948. } else zds->ddictLocal = NULL;
  1949. zds->ddict = zds->ddictLocal;
  1950. zds->legacyVersion = 0;
  1951. zds->hostageByte = 0;
  1952. return ZSTD_frameHeaderSize_prefix;
  1953. }
  1954. size_t ZSTD_initDStream(ZSTD_DStream* zds)
  1955. {
  1956. return ZSTD_initDStream_usingDict(zds, NULL, 0);
  1957. }
  1958. /* ZSTD_initDStream_usingDDict() :
  1959. * ddict will just be referenced, and must outlive decompression session */
  1960. size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict)
  1961. {
  1962. size_t const initResult = ZSTD_initDStream(zds);
  1963. zds->ddict = ddict;
  1964. return initResult;
  1965. }
  1966. size_t ZSTD_resetDStream(ZSTD_DStream* zds)
  1967. {
  1968. zds->streamStage = zdss_loadHeader;
  1969. zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;
  1970. zds->legacyVersion = 0;
  1971. zds->hostageByte = 0;
  1972. return ZSTD_frameHeaderSize_prefix;
  1973. }
  1974. size_t ZSTD_setDStreamParameter(ZSTD_DStream* zds,
  1975. ZSTD_DStreamParameter_e paramType, unsigned paramValue)
  1976. {
  1977. switch(paramType)
  1978. {
  1979. default : return ERROR(parameter_unsupported);
  1980. case DStream_p_maxWindowSize : zds->maxWindowSize = paramValue ? paramValue : (U32)(-1); break;
  1981. }
  1982. return 0;
  1983. }
  1984. size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds)
  1985. {
  1986. return ZSTD_sizeof_DCtx(zds);
  1987. }
  1988. size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)
  1989. {
  1990. size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
  1991. unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2);
  1992. unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);
  1993. size_t const minRBSize = (size_t) neededSize;
  1994. if ((unsigned long long)minRBSize != neededSize) return ERROR(frameParameter_windowTooLarge);
  1995. return minRBSize;
  1996. }
  1997. size_t ZSTD_estimateDStreamSize(size_t windowSize)
  1998. {
  1999. size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
  2000. size_t const inBuffSize = blockSize; /* no block can be larger */
  2001. size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);
  2002. return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;
  2003. }
  2004. ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)
  2005. {
  2006. U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable */
  2007. ZSTD_frameHeader zfh;
  2008. size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);
  2009. if (ZSTD_isError(err)) return err;
  2010. if (err>0) return ERROR(srcSize_wrong);
  2011. if (zfh.windowSize > windowSizeMax)
  2012. return ERROR(frameParameter_windowTooLarge);
  2013. return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);
  2014. }
  2015. /* ***** Decompression ***** */
  2016. MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  2017. {
  2018. size_t const length = MIN(dstCapacity, srcSize);
  2019. memcpy(dst, src, length);
  2020. return length;
  2021. }
  2022. size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  2023. {
  2024. const char* const istart = (const char*)(input->src) + input->pos;
  2025. const char* const iend = (const char*)(input->src) + input->size;
  2026. const char* ip = istart;
  2027. char* const ostart = (char*)(output->dst) + output->pos;
  2028. char* const oend = (char*)(output->dst) + output->size;
  2029. char* op = ostart;
  2030. U32 someMoreWork = 1;
  2031. DEBUGLOG(5, "ZSTD_decompressStream");
  2032. DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));
  2033. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
  2034. if (zds->legacyVersion) {
  2035. /* legacy support is incompatible with static dctx */
  2036. if (zds->staticSize) return ERROR(memory_allocation);
  2037. return ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);
  2038. }
  2039. #endif
  2040. while (someMoreWork) {
  2041. switch(zds->streamStage)
  2042. {
  2043. case zdss_init :
  2044. ZSTD_resetDStream(zds); /* transparent reset on starting decoding a new frame */
  2045. /* fall-through */
  2046. case zdss_loadHeader :
  2047. { size_t const hSize = ZSTD_getFrameHeader(&zds->fParams, zds->headerBuffer, zds->lhSize);
  2048. if (ZSTD_isError(hSize)) {
  2049. #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
  2050. U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);
  2051. if (legacyVersion) {
  2052. const void* const dict = zds->ddict ? zds->ddict->dictContent : NULL;
  2053. size_t const dictSize = zds->ddict ? zds->ddict->dictSize : 0;
  2054. /* legacy support is incompatible with static dctx */
  2055. if (zds->staticSize) return ERROR(memory_allocation);
  2056. CHECK_F(ZSTD_initLegacyStream(&zds->legacyContext,
  2057. zds->previousLegacyVersion, legacyVersion,
  2058. dict, dictSize));
  2059. zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;
  2060. return ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);
  2061. }
  2062. #endif
  2063. return hSize; /* error */
  2064. }
  2065. if (hSize != 0) { /* need more input */
  2066. size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */
  2067. if (toLoad > (size_t)(iend-ip)) { /* not enough input to load full header */
  2068. if (iend-ip > 0) {
  2069. memcpy(zds->headerBuffer + zds->lhSize, ip, iend-ip);
  2070. zds->lhSize += iend-ip;
  2071. }
  2072. input->pos = input->size;
  2073. return (MAX(ZSTD_frameHeaderSize_min, hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */
  2074. }
  2075. assert(ip != NULL);
  2076. memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;
  2077. break;
  2078. } }
  2079. /* check for single-pass mode opportunity */
  2080. if (zds->fParams.frameContentSize && zds->fParams.windowSize /* skippable frame if == 0 */
  2081. && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {
  2082. size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart);
  2083. if (cSize <= (size_t)(iend-istart)) {
  2084. size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, zds->ddict);
  2085. if (ZSTD_isError(decompressedSize)) return decompressedSize;
  2086. ip = istart + cSize;
  2087. op += decompressedSize;
  2088. zds->expected = 0;
  2089. zds->streamStage = zdss_init;
  2090. someMoreWork = 0;
  2091. break;
  2092. } }
  2093. /* Consume header (see ZSTDds_decodeFrameHeader) */
  2094. DEBUGLOG(4, "Consume header");
  2095. CHECK_F(ZSTD_decompressBegin_usingDDict(zds, zds->ddict));
  2096. if ((MEM_readLE32(zds->headerBuffer) & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
  2097. zds->expected = MEM_readLE32(zds->headerBuffer + 4);
  2098. zds->stage = ZSTDds_skipFrame;
  2099. } else {
  2100. CHECK_F(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize));
  2101. zds->expected = ZSTD_blockHeaderSize;
  2102. zds->stage = ZSTDds_decodeBlockHeader;
  2103. }
  2104. /* control buffer memory usage */
  2105. DEBUGLOG(4, "Control max buffer memory usage");
  2106. zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
  2107. if (zds->fParams.windowSize > zds->maxWindowSize) return ERROR(frameParameter_windowTooLarge);
  2108. /* Adapt buffer sizes to frame header instructions */
  2109. { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);
  2110. size_t const neededOutBuffSize = ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize);
  2111. if ((zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize)) {
  2112. size_t const bufferSize = neededInBuffSize + neededOutBuffSize;
  2113. DEBUGLOG(4, "inBuff : from %u to %u",
  2114. (U32)zds->inBuffSize, (U32)neededInBuffSize);
  2115. DEBUGLOG(4, "outBuff : from %u to %u",
  2116. (U32)zds->outBuffSize, (U32)neededOutBuffSize);
  2117. if (zds->staticSize) { /* static DCtx */
  2118. DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);
  2119. assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */
  2120. if (bufferSize > zds->staticSize - sizeof(ZSTD_DCtx))
  2121. return ERROR(memory_allocation);
  2122. } else {
  2123. ZSTD_free(zds->inBuff, zds->customMem);
  2124. zds->inBuffSize = 0;
  2125. zds->outBuffSize = 0;
  2126. zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem);
  2127. if (zds->inBuff == NULL) return ERROR(memory_allocation);
  2128. }
  2129. zds->inBuffSize = neededInBuffSize;
  2130. zds->outBuff = zds->inBuff + zds->inBuffSize;
  2131. zds->outBuffSize = neededOutBuffSize;
  2132. } }
  2133. zds->streamStage = zdss_read;
  2134. /* fall-through */
  2135. case zdss_read:
  2136. DEBUGLOG(5, "stage zdss_read");
  2137. { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
  2138. DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);
  2139. if (neededInSize==0) { /* end of frame */
  2140. zds->streamStage = zdss_init;
  2141. someMoreWork = 0;
  2142. break;
  2143. }
  2144. if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */
  2145. int const isSkipFrame = ZSTD_isSkipFrame(zds);
  2146. size_t const decodedSize = ZSTD_decompressContinue(zds,
  2147. zds->outBuff + zds->outStart, (isSkipFrame ? 0 : zds->outBuffSize - zds->outStart),
  2148. ip, neededInSize);
  2149. if (ZSTD_isError(decodedSize)) return decodedSize;
  2150. ip += neededInSize;
  2151. if (!decodedSize && !isSkipFrame) break; /* this was just a header */
  2152. zds->outEnd = zds->outStart + decodedSize;
  2153. zds->streamStage = zdss_flush;
  2154. break;
  2155. } }
  2156. if (ip==iend) { someMoreWork = 0; break; } /* no more input */
  2157. zds->streamStage = zdss_load;
  2158. /* fall-through */
  2159. case zdss_load:
  2160. { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
  2161. size_t const toLoad = neededInSize - zds->inPos; /* should always be <= remaining space within inBuff */
  2162. size_t loadedSize;
  2163. if (toLoad > zds->inBuffSize - zds->inPos) return ERROR(corruption_detected); /* should never happen */
  2164. loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip);
  2165. ip += loadedSize;
  2166. zds->inPos += loadedSize;
  2167. if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */
  2168. /* decode loaded input */
  2169. { const int isSkipFrame = ZSTD_isSkipFrame(zds);
  2170. size_t const decodedSize = ZSTD_decompressContinue(zds,
  2171. zds->outBuff + zds->outStart, zds->outBuffSize - zds->outStart,
  2172. zds->inBuff, neededInSize);
  2173. if (ZSTD_isError(decodedSize)) return decodedSize;
  2174. zds->inPos = 0; /* input is consumed */
  2175. if (!decodedSize && !isSkipFrame) { zds->streamStage = zdss_read; break; } /* this was just a header */
  2176. zds->outEnd = zds->outStart + decodedSize;
  2177. } }
  2178. zds->streamStage = zdss_flush;
  2179. /* fall-through */
  2180. case zdss_flush:
  2181. { size_t const toFlushSize = zds->outEnd - zds->outStart;
  2182. size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize);
  2183. op += flushedSize;
  2184. zds->outStart += flushedSize;
  2185. if (flushedSize == toFlushSize) { /* flush completed */
  2186. zds->streamStage = zdss_read;
  2187. if ( (zds->outBuffSize < zds->fParams.frameContentSize)
  2188. && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {
  2189. DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",
  2190. (int)(zds->outBuffSize - zds->outStart),
  2191. (U32)zds->fParams.blockSizeMax);
  2192. zds->outStart = zds->outEnd = 0;
  2193. }
  2194. break;
  2195. } }
  2196. /* cannot complete flush */
  2197. someMoreWork = 0;
  2198. break;
  2199. default: return ERROR(GENERIC); /* impossible */
  2200. } }
  2201. /* result */
  2202. input->pos += (size_t)(ip-istart);
  2203. output->pos += (size_t)(op-ostart);
  2204. { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
  2205. if (!nextSrcSizeHint) { /* frame fully decoded */
  2206. if (zds->outEnd == zds->outStart) { /* output fully flushed */
  2207. if (zds->hostageByte) {
  2208. if (input->pos >= input->size) {
  2209. /* can't release hostage (not present) */
  2210. zds->streamStage = zdss_read;
  2211. return 1;
  2212. }
  2213. input->pos++; /* release hostage */
  2214. } /* zds->hostageByte */
  2215. return 0;
  2216. } /* zds->outEnd == zds->outStart */
  2217. if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
  2218. input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */
  2219. zds->hostageByte=1;
  2220. }
  2221. return 1;
  2222. } /* nextSrcSizeHint==0 */
  2223. nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */
  2224. if (zds->inPos > nextSrcSizeHint) return ERROR(GENERIC); /* should never happen */
  2225. nextSrcSizeHint -= zds->inPos; /* already loaded*/
  2226. return nextSrcSizeHint;
  2227. }
  2228. }