zstd_decompress_block.c 97 KB

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