zstd_decompress_block.c 99 KB

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