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

zstd_decompress_block.c 97KB

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 "zstd_deps.h" /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
  16. #include "compiler.h" /* prefetch */
  17. #include "cpu.h" /* bmi2 */
  18. #include "mem.h" /* low level memory routines */
  19. #define FSE_STATIC_LINKING_ONLY
  20. #include "fse.h"
  21. #include "huf.h"
  22. #include "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 "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 defined(__clang__)
  1137. if (LIKELY(ofBits > 1)) {
  1138. #else
  1139. if (ofBits > 1) {
  1140. #endif
  1141. ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
  1142. ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
  1143. ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32);
  1144. ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits);
  1145. if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
  1146. /* Always read extra bits, this keeps the logic simple,
  1147. * avoids branches, and avoids accidentally reading 0 bits.
  1148. */
  1149. U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32;
  1150. offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  1151. BIT_reloadDStream(&seqState->DStream);
  1152. offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  1153. } else {
  1154. offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  1155. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
  1156. }
  1157. seqState->prevOffset[2] = seqState->prevOffset[1];
  1158. seqState->prevOffset[1] = seqState->prevOffset[0];
  1159. seqState->prevOffset[0] = offset;
  1160. } else {
  1161. U32 const ll0 = (llDInfo->baseValue == 0);
  1162. if (LIKELY((ofBits == 0))) {
  1163. offset = seqState->prevOffset[ll0];
  1164. seqState->prevOffset[1] = seqState->prevOffset[!ll0];
  1165. seqState->prevOffset[0] = offset;
  1166. } else {
  1167. offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
  1168. { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  1169. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  1170. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  1171. seqState->prevOffset[1] = seqState->prevOffset[0];
  1172. seqState->prevOffset[0] = offset = temp;
  1173. } } }
  1174. seq.offset = offset;
  1175. }
  1176. #if defined(__clang__)
  1177. if (UNLIKELY(mlBits > 0))
  1178. #else
  1179. if (mlBits > 0)
  1180. #endif
  1181. seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
  1182. if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
  1183. BIT_reloadDStream(&seqState->DStream);
  1184. if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
  1185. BIT_reloadDStream(&seqState->DStream);
  1186. /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
  1187. ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
  1188. #if defined(__clang__)
  1189. if (UNLIKELY(llBits > 0))
  1190. #else
  1191. if (llBits > 0)
  1192. #endif
  1193. seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
  1194. if (MEM_32bits())
  1195. BIT_reloadDStream(&seqState->DStream);
  1196. DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
  1197. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  1198. ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */
  1199. ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */
  1200. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  1201. ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */
  1202. }
  1203. return seq;
  1204. }
  1205. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  1206. MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
  1207. {
  1208. size_t const windowSize = dctx->fParams.windowSize;
  1209. /* No dictionary used. */
  1210. if (dctx->dictContentEndForFuzzing == NULL) return 0;
  1211. /* Dictionary is our prefix. */
  1212. if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
  1213. /* Dictionary is not our ext-dict. */
  1214. if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
  1215. /* Dictionary is not within our window size. */
  1216. if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
  1217. /* Dictionary is active. */
  1218. return 1;
  1219. }
  1220. MEM_STATIC void ZSTD_assertValidSequence(
  1221. ZSTD_DCtx const* dctx,
  1222. BYTE const* op, BYTE const* oend,
  1223. seq_t const seq,
  1224. BYTE const* prefixStart, BYTE const* virtualStart)
  1225. {
  1226. #if DEBUGLEVEL >= 1
  1227. size_t const windowSize = dctx->fParams.windowSize;
  1228. size_t const sequenceSize = seq.litLength + seq.matchLength;
  1229. BYTE const* const oLitEnd = op + seq.litLength;
  1230. DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
  1231. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  1232. assert(op <= oend);
  1233. assert((size_t)(oend - op) >= sequenceSize);
  1234. assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX);
  1235. if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
  1236. size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
  1237. /* Offset must be within the dictionary. */
  1238. assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
  1239. assert(seq.offset <= windowSize + dictSize);
  1240. } else {
  1241. /* Offset must be within our window. */
  1242. assert(seq.offset <= windowSize);
  1243. }
  1244. #else
  1245. (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
  1246. #endif
  1247. }
  1248. #endif
  1249. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1250. FORCE_INLINE_TEMPLATE size_t
  1251. DONT_VECTORIZE
  1252. ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
  1253. void* dst, size_t maxDstSize,
  1254. const void* seqStart, size_t seqSize, int nbSeq,
  1255. const ZSTD_longOffset_e isLongOffset,
  1256. const int frame)
  1257. {
  1258. const BYTE* ip = (const BYTE*)seqStart;
  1259. const BYTE* const iend = ip + seqSize;
  1260. BYTE* const ostart = (BYTE*)dst;
  1261. BYTE* const oend = ostart + maxDstSize;
  1262. BYTE* op = ostart;
  1263. const BYTE* litPtr = dctx->litPtr;
  1264. const BYTE* litBufferEnd = dctx->litBufferEnd;
  1265. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1266. const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
  1267. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1268. DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer");
  1269. (void)frame;
  1270. /* Regen sequences */
  1271. if (nbSeq) {
  1272. seqState_t seqState;
  1273. dctx->fseEntropy = 1;
  1274. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1275. RETURN_ERROR_IF(
  1276. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1277. corruption_detected, "");
  1278. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1279. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1280. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1281. assert(dst != NULL);
  1282. ZSTD_STATIC_ASSERT(
  1283. BIT_DStream_unfinished < BIT_DStream_completed &&
  1284. BIT_DStream_endOfBuffer < BIT_DStream_completed &&
  1285. BIT_DStream_completed < BIT_DStream_overflow);
  1286. /* decompress without overrunning litPtr begins */
  1287. {
  1288. seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1289. /* Align the decompression loop to 32 + 16 bytes.
  1290. *
  1291. * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
  1292. * speed swings based on the alignment of the decompression loop. This
  1293. * performance swing is caused by parts of the decompression loop falling
  1294. * out of the DSB. The entire decompression loop should fit in the DSB,
  1295. * when it can't we get much worse performance. You can measure if you've
  1296. * hit the good case or the bad case with this perf command for some
  1297. * compressed file test.zst:
  1298. *
  1299. * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
  1300. * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
  1301. *
  1302. * If you see most cycles served out of the MITE you've hit the bad case.
  1303. * If you see most cycles served out of the DSB you've hit the good case.
  1304. * If it is pretty even then you may be in an okay case.
  1305. *
  1306. * This issue has been reproduced on the following CPUs:
  1307. * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
  1308. * Use Instruments->Counters to get DSB/MITE cycles.
  1309. * I never got performance swings, but I was able to
  1310. * go from the good case of mostly DSB to half of the
  1311. * cycles served from MITE.
  1312. * - Coffeelake: Intel i9-9900k
  1313. * - Coffeelake: Intel i7-9700k
  1314. *
  1315. * I haven't been able to reproduce the instability or DSB misses on any
  1316. * of the following CPUS:
  1317. * - Haswell
  1318. * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
  1319. * - Skylake
  1320. *
  1321. * Alignment is done for each of the three major decompression loops:
  1322. * - ZSTD_decompressSequences_bodySplitLitBuffer - presplit section of the literal buffer
  1323. * - ZSTD_decompressSequences_bodySplitLitBuffer - postsplit section of the literal buffer
  1324. * - ZSTD_decompressSequences_body
  1325. * Alignment choices are made to minimize large swings on bad cases and influence on performance
  1326. * from changes external to this code, rather than to overoptimize on the current commit.
  1327. *
  1328. * If you are seeing performance stability this script can help test.
  1329. * It tests on 4 commits in zstd where I saw performance change.
  1330. *
  1331. * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
  1332. */
  1333. #if defined(__GNUC__) && defined(__x86_64__)
  1334. __asm__(".p2align 6");
  1335. # if __GNUC__ >= 7
  1336. /* good for gcc-7, gcc-9, and gcc-11 */
  1337. __asm__("nop");
  1338. __asm__(".p2align 5");
  1339. __asm__("nop");
  1340. __asm__(".p2align 4");
  1341. # if __GNUC__ == 8 || __GNUC__ == 10
  1342. /* good for gcc-8 and gcc-10 */
  1343. __asm__("nop");
  1344. __asm__(".p2align 3");
  1345. # endif
  1346. # endif
  1347. #endif
  1348. /* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */
  1349. for (; litPtr + sequence.litLength <= dctx->litBufferEnd; ) {
  1350. size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
  1351. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1352. assert(!ZSTD_isError(oneSeqSize));
  1353. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  1354. #endif
  1355. if (UNLIKELY(ZSTD_isError(oneSeqSize)))
  1356. return oneSeqSize;
  1357. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  1358. op += oneSeqSize;
  1359. if (UNLIKELY(!--nbSeq))
  1360. break;
  1361. BIT_reloadDStream(&(seqState.DStream));
  1362. sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1363. }
  1364. /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */
  1365. if (nbSeq > 0) {
  1366. const size_t leftoverLit = dctx->litBufferEnd - litPtr;
  1367. if (leftoverLit)
  1368. {
  1369. RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
  1370. ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
  1371. sequence.litLength -= leftoverLit;
  1372. op += leftoverLit;
  1373. }
  1374. litPtr = dctx->litExtraBuffer;
  1375. litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
  1376. dctx->litBufferLocation = ZSTD_not_in_dst;
  1377. {
  1378. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
  1379. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1380. assert(!ZSTD_isError(oneSeqSize));
  1381. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  1382. #endif
  1383. if (UNLIKELY(ZSTD_isError(oneSeqSize)))
  1384. return oneSeqSize;
  1385. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  1386. op += oneSeqSize;
  1387. if (--nbSeq)
  1388. BIT_reloadDStream(&(seqState.DStream));
  1389. }
  1390. }
  1391. }
  1392. if (nbSeq > 0) /* there is remaining lit from extra buffer */
  1393. {
  1394. #if defined(__GNUC__) && defined(__x86_64__)
  1395. __asm__(".p2align 6");
  1396. __asm__("nop");
  1397. # if __GNUC__ != 7
  1398. /* worse for gcc-7 better for gcc-8, gcc-9, and gcc-10 and clang */
  1399. __asm__(".p2align 4");
  1400. __asm__("nop");
  1401. __asm__(".p2align 3");
  1402. # elif __GNUC__ >= 11
  1403. __asm__(".p2align 3");
  1404. # else
  1405. __asm__(".p2align 5");
  1406. __asm__("nop");
  1407. __asm__(".p2align 3");
  1408. # endif
  1409. #endif
  1410. for (; ; ) {
  1411. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1412. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd);
  1413. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1414. assert(!ZSTD_isError(oneSeqSize));
  1415. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  1416. #endif
  1417. if (UNLIKELY(ZSTD_isError(oneSeqSize)))
  1418. return oneSeqSize;
  1419. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  1420. op += oneSeqSize;
  1421. if (UNLIKELY(!--nbSeq))
  1422. break;
  1423. BIT_reloadDStream(&(seqState.DStream));
  1424. }
  1425. }
  1426. /* check if reached exact end */
  1427. DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq);
  1428. RETURN_ERROR_IF(nbSeq, corruption_detected, "");
  1429. RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
  1430. /* save reps for next block */
  1431. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1432. }
  1433. /* last literal segment */
  1434. if (dctx->litBufferLocation == ZSTD_split) /* split hasn't been reached yet, first get dst then copy litExtraBuffer */
  1435. {
  1436. size_t const lastLLSize = litBufferEnd - litPtr;
  1437. RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
  1438. if (op != NULL) {
  1439. ZSTD_memmove(op, litPtr, lastLLSize);
  1440. op += lastLLSize;
  1441. }
  1442. litPtr = dctx->litExtraBuffer;
  1443. litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
  1444. dctx->litBufferLocation = ZSTD_not_in_dst;
  1445. }
  1446. { size_t const lastLLSize = litBufferEnd - litPtr;
  1447. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1448. if (op != NULL) {
  1449. ZSTD_memcpy(op, litPtr, lastLLSize);
  1450. op += lastLLSize;
  1451. }
  1452. }
  1453. return op-ostart;
  1454. }
  1455. FORCE_INLINE_TEMPLATE size_t
  1456. DONT_VECTORIZE
  1457. ZSTD_decompressSequences_body(ZSTD_DCtx* dctx,
  1458. void* dst, size_t maxDstSize,
  1459. const void* seqStart, size_t seqSize, int nbSeq,
  1460. const ZSTD_longOffset_e isLongOffset,
  1461. const int frame)
  1462. {
  1463. const BYTE* ip = (const BYTE*)seqStart;
  1464. const BYTE* const iend = ip + seqSize;
  1465. BYTE* const ostart = (BYTE*)dst;
  1466. BYTE* const oend = dctx->litBufferLocation == ZSTD_not_in_dst ? ostart + maxDstSize : dctx->litBuffer;
  1467. BYTE* op = ostart;
  1468. const BYTE* litPtr = dctx->litPtr;
  1469. const BYTE* const litEnd = litPtr + dctx->litSize;
  1470. const BYTE* const prefixStart = (const BYTE*)(dctx->prefixStart);
  1471. const BYTE* const vBase = (const BYTE*)(dctx->virtualStart);
  1472. const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd);
  1473. DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq);
  1474. (void)frame;
  1475. /* Regen sequences */
  1476. if (nbSeq) {
  1477. seqState_t seqState;
  1478. dctx->fseEntropy = 1;
  1479. { U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1480. RETURN_ERROR_IF(
  1481. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend - ip)),
  1482. corruption_detected, "");
  1483. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1484. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1485. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1486. assert(dst != NULL);
  1487. ZSTD_STATIC_ASSERT(
  1488. BIT_DStream_unfinished < BIT_DStream_completed &&
  1489. BIT_DStream_endOfBuffer < BIT_DStream_completed &&
  1490. BIT_DStream_completed < BIT_DStream_overflow);
  1491. #if defined(__GNUC__) && defined(__x86_64__)
  1492. __asm__(".p2align 6");
  1493. __asm__("nop");
  1494. # if __GNUC__ >= 7
  1495. __asm__(".p2align 5");
  1496. __asm__("nop");
  1497. __asm__(".p2align 3");
  1498. # else
  1499. __asm__(".p2align 4");
  1500. __asm__("nop");
  1501. __asm__(".p2align 3");
  1502. # endif
  1503. #endif
  1504. for ( ; ; ) {
  1505. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1506. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
  1507. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1508. assert(!ZSTD_isError(oneSeqSize));
  1509. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  1510. #endif
  1511. if (UNLIKELY(ZSTD_isError(oneSeqSize)))
  1512. return oneSeqSize;
  1513. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  1514. op += oneSeqSize;
  1515. if (UNLIKELY(!--nbSeq))
  1516. break;
  1517. BIT_reloadDStream(&(seqState.DStream));
  1518. }
  1519. /* check if reached exact end */
  1520. DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
  1521. RETURN_ERROR_IF(nbSeq, corruption_detected, "");
  1522. RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
  1523. /* save reps for next block */
  1524. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1525. }
  1526. /* last literal segment */
  1527. { size_t const lastLLSize = litEnd - litPtr;
  1528. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1529. if (op != NULL) {
  1530. ZSTD_memcpy(op, litPtr, lastLLSize);
  1531. op += lastLLSize;
  1532. }
  1533. }
  1534. return op-ostart;
  1535. }
  1536. static size_t
  1537. ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
  1538. void* dst, size_t maxDstSize,
  1539. const void* seqStart, size_t seqSize, int nbSeq,
  1540. const ZSTD_longOffset_e isLongOffset,
  1541. const int frame)
  1542. {
  1543. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1544. }
  1545. static size_t
  1546. ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx,
  1547. void* dst, size_t maxDstSize,
  1548. const void* seqStart, size_t seqSize, int nbSeq,
  1549. const ZSTD_longOffset_e isLongOffset,
  1550. const int frame)
  1551. {
  1552. return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1553. }
  1554. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1555. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1556. FORCE_INLINE_TEMPLATE size_t
  1557. ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
  1558. const BYTE* const prefixStart, const BYTE* const dictEnd)
  1559. {
  1560. prefetchPos += sequence.litLength;
  1561. { const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;
  1562. 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.
  1563. * No consequence though : memory address is only used for prefetching, not for dereferencing */
  1564. PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
  1565. }
  1566. return prefetchPos + sequence.matchLength;
  1567. }
  1568. /* This decoding function employs prefetching
  1569. * to reduce latency impact of cache misses.
  1570. * It's generally employed when block contains a significant portion of long-distance matches
  1571. * or when coupled with a "cold" dictionary */
  1572. FORCE_INLINE_TEMPLATE size_t
  1573. ZSTD_decompressSequencesLong_body(
  1574. ZSTD_DCtx* dctx,
  1575. void* dst, size_t maxDstSize,
  1576. const void* seqStart, size_t seqSize, int nbSeq,
  1577. const ZSTD_longOffset_e isLongOffset,
  1578. const int frame)
  1579. {
  1580. const BYTE* ip = (const BYTE*)seqStart;
  1581. const BYTE* const iend = ip + seqSize;
  1582. BYTE* const ostart = (BYTE*)dst;
  1583. BYTE* const oend = dctx->litBufferLocation == ZSTD_in_dst ? dctx->litBuffer : ostart + maxDstSize;
  1584. BYTE* op = ostart;
  1585. const BYTE* litPtr = dctx->litPtr;
  1586. const BYTE* litBufferEnd = dctx->litBufferEnd;
  1587. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1588. const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
  1589. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1590. (void)frame;
  1591. /* Regen sequences */
  1592. if (nbSeq) {
  1593. #define STORED_SEQS 8
  1594. #define STORED_SEQS_MASK (STORED_SEQS-1)
  1595. #define ADVANCED_SEQS STORED_SEQS
  1596. seq_t sequences[STORED_SEQS];
  1597. int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
  1598. seqState_t seqState;
  1599. int seqNb;
  1600. size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
  1601. dctx->fseEntropy = 1;
  1602. { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1603. assert(dst != NULL);
  1604. assert(iend >= ip);
  1605. RETURN_ERROR_IF(
  1606. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1607. corruption_detected, "");
  1608. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1609. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1610. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1611. /* prepare in advance */
  1612. for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
  1613. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1614. prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
  1615. sequences[seqNb] = sequence;
  1616. }
  1617. RETURN_ERROR_IF(seqNb<seqAdvance, corruption_detected, "");
  1618. /* decompress without stomping litBuffer */
  1619. for (; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb < nbSeq); seqNb++) {
  1620. seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1621. size_t oneSeqSize;
  1622. if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd)
  1623. {
  1624. /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */
  1625. const size_t leftoverLit = dctx->litBufferEnd - litPtr;
  1626. if (leftoverLit)
  1627. {
  1628. RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
  1629. ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
  1630. sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit;
  1631. op += leftoverLit;
  1632. }
  1633. litPtr = dctx->litExtraBuffer;
  1634. litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
  1635. dctx->litBufferLocation = ZSTD_not_in_dst;
  1636. oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
  1637. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1638. assert(!ZSTD_isError(oneSeqSize));
  1639. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
  1640. #endif
  1641. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1642. prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
  1643. sequences[seqNb & STORED_SEQS_MASK] = sequence;
  1644. op += oneSeqSize;
  1645. }
  1646. else
  1647. {
  1648. /* lit buffer is either wholly contained in first or second split, or not split at all*/
  1649. oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
  1650. 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) :
  1651. ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
  1652. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1653. assert(!ZSTD_isError(oneSeqSize));
  1654. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
  1655. #endif
  1656. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1657. prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
  1658. sequences[seqNb & STORED_SEQS_MASK] = sequence;
  1659. op += oneSeqSize;
  1660. }
  1661. }
  1662. RETURN_ERROR_IF(seqNb<nbSeq, corruption_detected, "");
  1663. /* finish queue */
  1664. seqNb -= seqAdvance;
  1665. for ( ; seqNb<nbSeq ; seqNb++) {
  1666. seq_t *sequence = &(sequences[seqNb&STORED_SEQS_MASK]);
  1667. if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd)
  1668. {
  1669. const size_t leftoverLit = dctx->litBufferEnd - litPtr;
  1670. if (leftoverLit)
  1671. {
  1672. RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer");
  1673. ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit);
  1674. sequence->litLength -= leftoverLit;
  1675. op += leftoverLit;
  1676. }
  1677. litPtr = dctx->litExtraBuffer;
  1678. litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
  1679. dctx->litBufferLocation = ZSTD_not_in_dst;
  1680. {
  1681. size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
  1682. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1683. assert(!ZSTD_isError(oneSeqSize));
  1684. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
  1685. #endif
  1686. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1687. op += oneSeqSize;
  1688. }
  1689. }
  1690. else
  1691. {
  1692. size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ?
  1693. ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence->litLength - WILDCOPY_OVERLENGTH, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) :
  1694. ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd);
  1695. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1696. assert(!ZSTD_isError(oneSeqSize));
  1697. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
  1698. #endif
  1699. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1700. op += oneSeqSize;
  1701. }
  1702. }
  1703. /* save reps for next block */
  1704. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1705. }
  1706. /* last literal segment */
  1707. if (dctx->litBufferLocation == ZSTD_split) /* first deplete literal buffer in dst, then copy litExtraBuffer */
  1708. {
  1709. size_t const lastLLSize = litBufferEnd - litPtr;
  1710. RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
  1711. if (op != NULL) {
  1712. ZSTD_memmove(op, litPtr, lastLLSize);
  1713. op += lastLLSize;
  1714. }
  1715. litPtr = dctx->litExtraBuffer;
  1716. litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
  1717. }
  1718. { size_t const lastLLSize = litBufferEnd - litPtr;
  1719. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1720. if (op != NULL) {
  1721. ZSTD_memmove(op, litPtr, lastLLSize);
  1722. op += lastLLSize;
  1723. }
  1724. }
  1725. return op-ostart;
  1726. }
  1727. static size_t
  1728. ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
  1729. void* dst, size_t maxDstSize,
  1730. const void* seqStart, size_t seqSize, int nbSeq,
  1731. const ZSTD_longOffset_e isLongOffset,
  1732. const int frame)
  1733. {
  1734. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1735. }
  1736. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1737. #if DYNAMIC_BMI2
  1738. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1739. static BMI2_TARGET_ATTRIBUTE size_t
  1740. DONT_VECTORIZE
  1741. ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
  1742. void* dst, size_t maxDstSize,
  1743. const void* seqStart, size_t seqSize, int nbSeq,
  1744. const ZSTD_longOffset_e isLongOffset,
  1745. const int frame)
  1746. {
  1747. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1748. }
  1749. static BMI2_TARGET_ATTRIBUTE size_t
  1750. DONT_VECTORIZE
  1751. ZSTD_decompressSequencesSplitLitBuffer_bmi2(ZSTD_DCtx* dctx,
  1752. void* dst, size_t maxDstSize,
  1753. const void* seqStart, size_t seqSize, int nbSeq,
  1754. const ZSTD_longOffset_e isLongOffset,
  1755. const int frame)
  1756. {
  1757. return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1758. }
  1759. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1760. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1761. static BMI2_TARGET_ATTRIBUTE size_t
  1762. ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
  1763. void* dst, size_t maxDstSize,
  1764. const void* seqStart, size_t seqSize, int nbSeq,
  1765. const ZSTD_longOffset_e isLongOffset,
  1766. const int frame)
  1767. {
  1768. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1769. }
  1770. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1771. #endif /* DYNAMIC_BMI2 */
  1772. typedef size_t (*ZSTD_decompressSequences_t)(
  1773. ZSTD_DCtx* dctx,
  1774. void* dst, size_t maxDstSize,
  1775. const void* seqStart, size_t seqSize, int nbSeq,
  1776. const ZSTD_longOffset_e isLongOffset,
  1777. const int frame);
  1778. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1779. static size_t
  1780. ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
  1781. const void* seqStart, size_t seqSize, int nbSeq,
  1782. const ZSTD_longOffset_e isLongOffset,
  1783. const int frame)
  1784. {
  1785. DEBUGLOG(5, "ZSTD_decompressSequences");
  1786. #if DYNAMIC_BMI2
  1787. if (ZSTD_DCtx_get_bmi2(dctx)) {
  1788. return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1789. }
  1790. #endif
  1791. return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1792. }
  1793. static size_t
  1794. ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
  1795. const void* seqStart, size_t seqSize, int nbSeq,
  1796. const ZSTD_longOffset_e isLongOffset,
  1797. const int frame)
  1798. {
  1799. DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer");
  1800. #if DYNAMIC_BMI2
  1801. if (ZSTD_DCtx_get_bmi2(dctx)) {
  1802. return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1803. }
  1804. #endif
  1805. return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1806. }
  1807. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1808. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1809. /* ZSTD_decompressSequencesLong() :
  1810. * decompression function triggered when a minimum share of offsets is considered "long",
  1811. * aka out of cache.
  1812. * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
  1813. * This function will try to mitigate main memory latency through the use of prefetching */
  1814. static size_t
  1815. ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
  1816. void* dst, size_t maxDstSize,
  1817. const void* seqStart, size_t seqSize, int nbSeq,
  1818. const ZSTD_longOffset_e isLongOffset,
  1819. const int frame)
  1820. {
  1821. DEBUGLOG(5, "ZSTD_decompressSequencesLong");
  1822. #if DYNAMIC_BMI2
  1823. if (ZSTD_DCtx_get_bmi2(dctx)) {
  1824. return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1825. }
  1826. #endif
  1827. return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1828. }
  1829. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1830. /**
  1831. * @returns The total size of the history referencable by zstd, including
  1832. * both the prefix and the extDict. At @p op any offset larger than this
  1833. * is invalid.
  1834. */
  1835. static size_t ZSTD_totalHistorySize(BYTE* op, BYTE const* virtualStart)
  1836. {
  1837. return (size_t)(op - virtualStart);
  1838. }
  1839. typedef struct {
  1840. unsigned longOffsetShare;
  1841. unsigned maxNbAdditionalBits;
  1842. } ZSTD_OffsetInfo;
  1843. /* ZSTD_getOffsetInfo() :
  1844. * condition : offTable must be valid
  1845. * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
  1846. * compared to maximum possible of (1<<OffFSELog),
  1847. * as well as the maximum number additional bits required.
  1848. */
  1849. static ZSTD_OffsetInfo
  1850. ZSTD_getOffsetInfo(const ZSTD_seqSymbol* offTable, int nbSeq)
  1851. {
  1852. ZSTD_OffsetInfo info = {0, 0};
  1853. /* If nbSeq == 0, then the offTable is uninitialized, but we have
  1854. * no sequences, so both values should be 0.
  1855. */
  1856. if (nbSeq != 0) {
  1857. const void* ptr = offTable;
  1858. U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
  1859. const ZSTD_seqSymbol* table = offTable + 1;
  1860. U32 const max = 1 << tableLog;
  1861. U32 u;
  1862. DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
  1863. assert(max <= (1 << OffFSELog)); /* max not too large */
  1864. for (u=0; u<max; u++) {
  1865. info.maxNbAdditionalBits = MAX(info.maxNbAdditionalBits, table[u].nbAdditionalBits);
  1866. if (table[u].nbAdditionalBits > 22) info.longOffsetShare += 1;
  1867. }
  1868. assert(tableLog <= OffFSELog);
  1869. info.longOffsetShare <<= (OffFSELog - tableLog); /* scale to OffFSELog */
  1870. }
  1871. return info;
  1872. }
  1873. /**
  1874. * @returns The maximum offset we can decode in one read of our bitstream, without
  1875. * reloading more bits in the middle of the offset bits read. Any offsets larger
  1876. * than this must use the long offset decoder.
  1877. */
  1878. static size_t ZSTD_maxShortOffset(void)
  1879. {
  1880. if (MEM_64bits()) {
  1881. /* We can decode any offset without reloading bits.
  1882. * This might change if the max window size grows.
  1883. */
  1884. ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
  1885. return (size_t)-1;
  1886. } else {
  1887. /* The maximum offBase is (1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1.
  1888. * This offBase would require STREAM_ACCUMULATOR_MIN extra bits.
  1889. * Then we have to subtract ZSTD_REP_NUM to get the maximum possible offset.
  1890. */
  1891. size_t const maxOffbase = ((size_t)1 << (STREAM_ACCUMULATOR_MIN + 1)) - 1;
  1892. size_t const maxOffset = maxOffbase - ZSTD_REP_NUM;
  1893. assert(ZSTD_highbit32((U32)maxOffbase) == STREAM_ACCUMULATOR_MIN);
  1894. return maxOffset;
  1895. }
  1896. }
  1897. size_t
  1898. ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
  1899. void* dst, size_t dstCapacity,
  1900. const void* src, size_t srcSize, const int frame, const streaming_operation streaming)
  1901. { /* blockType == blockCompressed */
  1902. const BYTE* ip = (const BYTE*)src;
  1903. DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
  1904. /* Note : the wording of the specification
  1905. * allows compressed block to be sized exactly ZSTD_BLOCKSIZE_MAX.
  1906. * This generally does not happen, as it makes little sense,
  1907. * since an uncompressed block would feature same size and have no decompression cost.
  1908. * Also, note that decoder from reference libzstd before < v1.5.4
  1909. * would consider this edge case as an error.
  1910. * As a consequence, avoid generating compressed blocks of size ZSTD_BLOCKSIZE_MAX
  1911. * for broader compatibility with the deployed ecosystem of zstd decoders */
  1912. RETURN_ERROR_IF(srcSize > ZSTD_BLOCKSIZE_MAX, srcSize_wrong, "");
  1913. /* Decode literals section */
  1914. { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming);
  1915. DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : cSize=%u, nbLiterals=%zu", (U32)litCSize, dctx->litSize);
  1916. if (ZSTD_isError(litCSize)) return litCSize;
  1917. ip += litCSize;
  1918. srcSize -= litCSize;
  1919. }
  1920. /* Build Decoding Tables */
  1921. {
  1922. /* Compute the maximum block size, which must also work when !frame and fParams are unset.
  1923. * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t.
  1924. */
  1925. size_t const blockSizeMax = MIN(dstCapacity, (frame ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX));
  1926. size_t const totalHistorySize = ZSTD_totalHistorySize((BYTE*)dst + blockSizeMax, (BYTE const*)dctx->virtualStart);
  1927. /* isLongOffset must be true if there are long offsets.
  1928. * Offsets are long if they are larger than ZSTD_maxShortOffset().
  1929. * We don't expect that to be the case in 64-bit mode.
  1930. *
  1931. * We check here to see if our history is large enough to allow long offsets.
  1932. * If it isn't, then we can't possible have (valid) long offsets. If the offset
  1933. * is invalid, then it is okay to read it incorrectly.
  1934. *
  1935. * If isLongOffsets is true, then we will later check our decoding table to see
  1936. * if it is even possible to generate long offsets.
  1937. */
  1938. ZSTD_longOffset_e isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (totalHistorySize > ZSTD_maxShortOffset()));
  1939. /* These macros control at build-time which decompressor implementation
  1940. * we use. If neither is defined, we do some inspection and dispatch at
  1941. * runtime.
  1942. */
  1943. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1944. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1945. int usePrefetchDecoder = dctx->ddictIsCold;
  1946. #else
  1947. /* Set to 1 to avoid computing offset info if we don't need to.
  1948. * Otherwise this value is ignored.
  1949. */
  1950. int usePrefetchDecoder = 1;
  1951. #endif
  1952. int nbSeq;
  1953. size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
  1954. if (ZSTD_isError(seqHSize)) return seqHSize;
  1955. ip += seqHSize;
  1956. srcSize -= seqHSize;
  1957. RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
  1958. /* If we could potentially have long offsets, or we might want to use the prefetch decoder,
  1959. * compute information about the share of long offsets, and the maximum nbAdditionalBits.
  1960. * NOTE: could probably use a larger nbSeq limit
  1961. */
  1962. if (isLongOffset || (!usePrefetchDecoder && (totalHistorySize > (1u << 24)) && (nbSeq > 8))) {
  1963. ZSTD_OffsetInfo const info = ZSTD_getOffsetInfo(dctx->OFTptr, nbSeq);
  1964. if (isLongOffset && info.maxNbAdditionalBits <= STREAM_ACCUMULATOR_MIN) {
  1965. /* If isLongOffset, but the maximum number of additional bits that we see in our table is small
  1966. * enough, then we know it is impossible to have too long an offset in this block, so we can
  1967. * use the regular offset decoder.
  1968. */
  1969. isLongOffset = ZSTD_lo_isRegularOffset;
  1970. }
  1971. if (!usePrefetchDecoder) {
  1972. U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
  1973. usePrefetchDecoder = (info.longOffsetShare >= minShare);
  1974. }
  1975. }
  1976. dctx->ddictIsCold = 0;
  1977. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1978. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1979. if (usePrefetchDecoder) {
  1980. #else
  1981. (void)usePrefetchDecoder;
  1982. {
  1983. #endif
  1984. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1985. return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1986. #endif
  1987. }
  1988. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1989. /* else */
  1990. if (dctx->litBufferLocation == ZSTD_split)
  1991. return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1992. else
  1993. return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1994. #endif
  1995. }
  1996. }
  1997. void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
  1998. {
  1999. if (dst != dctx->previousDstEnd && dstSize > 0) { /* not contiguous */
  2000. dctx->dictEnd = dctx->previousDstEnd;
  2001. dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
  2002. dctx->prefixStart = dst;
  2003. dctx->previousDstEnd = dst;
  2004. }
  2005. }
  2006. size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
  2007. void* dst, size_t dstCapacity,
  2008. const void* src, size_t srcSize)
  2009. {
  2010. size_t dSize;
  2011. ZSTD_checkContinuity(dctx, dst, dstCapacity);
  2012. dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0, not_streaming);
  2013. dctx->previousDstEnd = (char*)dst + dSize;
  2014. return dSize;
  2015. }