zstd_decompress_block.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /* zstd_decompress_block :
  11. * this module takes care of decompressing _compressed_ block */
  12. /*-*******************************************************
  13. * Dependencies
  14. *********************************************************/
  15. #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
  16. #include "../common/compiler.h" /* prefetch */
  17. #include "../common/cpu.h" /* bmi2 */
  18. #include "../common/mem.h" /* low level memory routines */
  19. #define FSE_STATIC_LINKING_ONLY
  20. #include "../common/fse.h"
  21. #define HUF_STATIC_LINKING_ONLY
  22. #include "../common/huf.h"
  23. #include "../common/zstd_internal.h"
  24. #include "zstd_decompress_internal.h" /* ZSTD_DCtx */
  25. #include "zstd_ddict.h" /* ZSTD_DDictDictContent */
  26. #include "zstd_decompress_block.h"
  27. /*_*******************************************************
  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. /* Hidden declaration for fullbench */
  62. size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
  63. const void* src, size_t srcSize);
  64. /*! ZSTD_decodeLiteralsBlock() :
  65. * @return : nb of bytes read from src (< srcSize )
  66. * note : symbol not declared but exposed for fullbench */
  67. size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
  68. const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
  69. {
  70. DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");
  71. RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");
  72. { const BYTE* const istart = (const BYTE*) src;
  73. symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);
  74. switch(litEncType)
  75. {
  76. case set_repeat:
  77. DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");
  78. RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");
  79. /* fall-through */
  80. case set_compressed:
  81. RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3");
  82. { size_t lhSize, litSize, litCSize;
  83. U32 singleStream=0;
  84. U32 const lhlCode = (istart[0] >> 2) & 3;
  85. U32 const lhc = MEM_readLE32(istart);
  86. size_t hufSuccess;
  87. switch(lhlCode)
  88. {
  89. case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */
  90. /* 2 - 2 - 10 - 10 */
  91. singleStream = !lhlCode;
  92. lhSize = 3;
  93. litSize = (lhc >> 4) & 0x3FF;
  94. litCSize = (lhc >> 14) & 0x3FF;
  95. break;
  96. case 2:
  97. /* 2 - 2 - 14 - 14 */
  98. lhSize = 4;
  99. litSize = (lhc >> 4) & 0x3FFF;
  100. litCSize = lhc >> 18;
  101. break;
  102. case 3:
  103. /* 2 - 2 - 18 - 18 */
  104. lhSize = 5;
  105. litSize = (lhc >> 4) & 0x3FFFF;
  106. litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);
  107. break;
  108. }
  109. RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, "");
  110. RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");
  111. /* prefetch huffman table if cold */
  112. if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
  113. PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
  114. }
  115. if (litEncType==set_repeat) {
  116. if (singleStream) {
  117. hufSuccess = HUF_decompress1X_usingDTable_bmi2(
  118. dctx->litBuffer, litSize, istart+lhSize, litCSize,
  119. dctx->HUFptr, dctx->bmi2);
  120. } else {
  121. hufSuccess = HUF_decompress4X_usingDTable_bmi2(
  122. dctx->litBuffer, litSize, istart+lhSize, litCSize,
  123. dctx->HUFptr, dctx->bmi2);
  124. }
  125. } else {
  126. if (singleStream) {
  127. #if defined(HUF_FORCE_DECOMPRESS_X2)
  128. hufSuccess = HUF_decompress1X_DCtx_wksp(
  129. dctx->entropy.hufTable, dctx->litBuffer, litSize,
  130. istart+lhSize, litCSize, dctx->workspace,
  131. sizeof(dctx->workspace));
  132. #else
  133. hufSuccess = HUF_decompress1X1_DCtx_wksp_bmi2(
  134. dctx->entropy.hufTable, dctx->litBuffer, litSize,
  135. istart+lhSize, litCSize, dctx->workspace,
  136. sizeof(dctx->workspace), dctx->bmi2);
  137. #endif
  138. } else {
  139. hufSuccess = HUF_decompress4X_hufOnly_wksp_bmi2(
  140. dctx->entropy.hufTable, dctx->litBuffer, litSize,
  141. istart+lhSize, litCSize, dctx->workspace,
  142. sizeof(dctx->workspace), dctx->bmi2);
  143. }
  144. }
  145. RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");
  146. dctx->litPtr = dctx->litBuffer;
  147. dctx->litSize = litSize;
  148. dctx->litEntropy = 1;
  149. if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
  150. ZSTD_memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  151. return litCSize + lhSize;
  152. }
  153. case set_basic:
  154. { size_t litSize, lhSize;
  155. U32 const lhlCode = ((istart[0]) >> 2) & 3;
  156. switch(lhlCode)
  157. {
  158. case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
  159. lhSize = 1;
  160. litSize = istart[0] >> 3;
  161. break;
  162. case 1:
  163. lhSize = 2;
  164. litSize = MEM_readLE16(istart) >> 4;
  165. break;
  166. case 3:
  167. lhSize = 3;
  168. litSize = MEM_readLE24(istart) >> 4;
  169. break;
  170. }
  171. if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
  172. RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");
  173. ZSTD_memcpy(dctx->litBuffer, istart+lhSize, litSize);
  174. dctx->litPtr = dctx->litBuffer;
  175. dctx->litSize = litSize;
  176. ZSTD_memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  177. return lhSize+litSize;
  178. }
  179. /* direct reference into compressed stream */
  180. dctx->litPtr = istart+lhSize;
  181. dctx->litSize = litSize;
  182. return lhSize+litSize;
  183. }
  184. case set_rle:
  185. { U32 const lhlCode = ((istart[0]) >> 2) & 3;
  186. size_t litSize, lhSize;
  187. switch(lhlCode)
  188. {
  189. case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
  190. lhSize = 1;
  191. litSize = istart[0] >> 3;
  192. break;
  193. case 1:
  194. lhSize = 2;
  195. litSize = MEM_readLE16(istart) >> 4;
  196. break;
  197. case 3:
  198. lhSize = 3;
  199. litSize = MEM_readLE24(istart) >> 4;
  200. RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4");
  201. break;
  202. }
  203. RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, "");
  204. ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
  205. dctx->litPtr = dctx->litBuffer;
  206. dctx->litSize = litSize;
  207. return lhSize+1;
  208. }
  209. default:
  210. RETURN_ERROR(corruption_detected, "impossible");
  211. }
  212. }
  213. }
  214. /* Default FSE distribution tables.
  215. * These are pre-calculated FSE decoding tables using default distributions as defined in specification :
  216. * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#default-distributions
  217. * They were generated programmatically with following method :
  218. * - start from default distributions, present in /lib/common/zstd_internal.h
  219. * - generate tables normally, using ZSTD_buildFSETable()
  220. * - printout the content of tables
  221. * - pretify output, report below, test with fuzzer to ensure it's correct */
  222. /* Default FSE distribution table for Literal Lengths */
  223. static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
  224. { 1, 1, 1, LL_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
  225. /* nextState, nbAddBits, nbBits, baseVal */
  226. { 0, 0, 4, 0}, { 16, 0, 4, 0},
  227. { 32, 0, 5, 1}, { 0, 0, 5, 3},
  228. { 0, 0, 5, 4}, { 0, 0, 5, 6},
  229. { 0, 0, 5, 7}, { 0, 0, 5, 9},
  230. { 0, 0, 5, 10}, { 0, 0, 5, 12},
  231. { 0, 0, 6, 14}, { 0, 1, 5, 16},
  232. { 0, 1, 5, 20}, { 0, 1, 5, 22},
  233. { 0, 2, 5, 28}, { 0, 3, 5, 32},
  234. { 0, 4, 5, 48}, { 32, 6, 5, 64},
  235. { 0, 7, 5, 128}, { 0, 8, 6, 256},
  236. { 0, 10, 6, 1024}, { 0, 12, 6, 4096},
  237. { 32, 0, 4, 0}, { 0, 0, 4, 1},
  238. { 0, 0, 5, 2}, { 32, 0, 5, 4},
  239. { 0, 0, 5, 5}, { 32, 0, 5, 7},
  240. { 0, 0, 5, 8}, { 32, 0, 5, 10},
  241. { 0, 0, 5, 11}, { 0, 0, 6, 13},
  242. { 32, 1, 5, 16}, { 0, 1, 5, 18},
  243. { 32, 1, 5, 22}, { 0, 2, 5, 24},
  244. { 32, 3, 5, 32}, { 0, 3, 5, 40},
  245. { 0, 6, 4, 64}, { 16, 6, 4, 64},
  246. { 32, 7, 5, 128}, { 0, 9, 6, 512},
  247. { 0, 11, 6, 2048}, { 48, 0, 4, 0},
  248. { 16, 0, 4, 1}, { 32, 0, 5, 2},
  249. { 32, 0, 5, 3}, { 32, 0, 5, 5},
  250. { 32, 0, 5, 6}, { 32, 0, 5, 8},
  251. { 32, 0, 5, 9}, { 32, 0, 5, 11},
  252. { 32, 0, 5, 12}, { 0, 0, 6, 15},
  253. { 32, 1, 5, 18}, { 32, 1, 5, 20},
  254. { 32, 2, 5, 24}, { 32, 2, 5, 28},
  255. { 32, 3, 5, 40}, { 32, 4, 5, 48},
  256. { 0, 16, 6,65536}, { 0, 15, 6,32768},
  257. { 0, 14, 6,16384}, { 0, 13, 6, 8192},
  258. }; /* LL_defaultDTable */
  259. /* Default FSE distribution table for Offset Codes */
  260. static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
  261. { 1, 1, 1, OF_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
  262. /* nextState, nbAddBits, nbBits, baseVal */
  263. { 0, 0, 5, 0}, { 0, 6, 4, 61},
  264. { 0, 9, 5, 509}, { 0, 15, 5,32765},
  265. { 0, 21, 5,2097149}, { 0, 3, 5, 5},
  266. { 0, 7, 4, 125}, { 0, 12, 5, 4093},
  267. { 0, 18, 5,262141}, { 0, 23, 5,8388605},
  268. { 0, 5, 5, 29}, { 0, 8, 4, 253},
  269. { 0, 14, 5,16381}, { 0, 20, 5,1048573},
  270. { 0, 2, 5, 1}, { 16, 7, 4, 125},
  271. { 0, 11, 5, 2045}, { 0, 17, 5,131069},
  272. { 0, 22, 5,4194301}, { 0, 4, 5, 13},
  273. { 16, 8, 4, 253}, { 0, 13, 5, 8189},
  274. { 0, 19, 5,524285}, { 0, 1, 5, 1},
  275. { 16, 6, 4, 61}, { 0, 10, 5, 1021},
  276. { 0, 16, 5,65533}, { 0, 28, 5,268435453},
  277. { 0, 27, 5,134217725}, { 0, 26, 5,67108861},
  278. { 0, 25, 5,33554429}, { 0, 24, 5,16777213},
  279. }; /* OF_defaultDTable */
  280. /* Default FSE distribution table for Match Lengths */
  281. static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
  282. { 1, 1, 1, ML_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
  283. /* nextState, nbAddBits, nbBits, baseVal */
  284. { 0, 0, 6, 3}, { 0, 0, 4, 4},
  285. { 32, 0, 5, 5}, { 0, 0, 5, 6},
  286. { 0, 0, 5, 8}, { 0, 0, 5, 9},
  287. { 0, 0, 5, 11}, { 0, 0, 6, 13},
  288. { 0, 0, 6, 16}, { 0, 0, 6, 19},
  289. { 0, 0, 6, 22}, { 0, 0, 6, 25},
  290. { 0, 0, 6, 28}, { 0, 0, 6, 31},
  291. { 0, 0, 6, 34}, { 0, 1, 6, 37},
  292. { 0, 1, 6, 41}, { 0, 2, 6, 47},
  293. { 0, 3, 6, 59}, { 0, 4, 6, 83},
  294. { 0, 7, 6, 131}, { 0, 9, 6, 515},
  295. { 16, 0, 4, 4}, { 0, 0, 4, 5},
  296. { 32, 0, 5, 6}, { 0, 0, 5, 7},
  297. { 32, 0, 5, 9}, { 0, 0, 5, 10},
  298. { 0, 0, 6, 12}, { 0, 0, 6, 15},
  299. { 0, 0, 6, 18}, { 0, 0, 6, 21},
  300. { 0, 0, 6, 24}, { 0, 0, 6, 27},
  301. { 0, 0, 6, 30}, { 0, 0, 6, 33},
  302. { 0, 1, 6, 35}, { 0, 1, 6, 39},
  303. { 0, 2, 6, 43}, { 0, 3, 6, 51},
  304. { 0, 4, 6, 67}, { 0, 5, 6, 99},
  305. { 0, 8, 6, 259}, { 32, 0, 4, 4},
  306. { 48, 0, 4, 4}, { 16, 0, 4, 5},
  307. { 32, 0, 5, 7}, { 32, 0, 5, 8},
  308. { 32, 0, 5, 10}, { 32, 0, 5, 11},
  309. { 0, 0, 6, 14}, { 0, 0, 6, 17},
  310. { 0, 0, 6, 20}, { 0, 0, 6, 23},
  311. { 0, 0, 6, 26}, { 0, 0, 6, 29},
  312. { 0, 0, 6, 32}, { 0, 16, 6,65539},
  313. { 0, 15, 6,32771}, { 0, 14, 6,16387},
  314. { 0, 13, 6, 8195}, { 0, 12, 6, 4099},
  315. { 0, 11, 6, 2051}, { 0, 10, 6, 1027},
  316. }; /* ML_defaultDTable */
  317. static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U32 nbAddBits)
  318. {
  319. void* ptr = dt;
  320. ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
  321. ZSTD_seqSymbol* const cell = dt + 1;
  322. DTableH->tableLog = 0;
  323. DTableH->fastMode = 0;
  324. cell->nbBits = 0;
  325. cell->nextState = 0;
  326. assert(nbAddBits < 255);
  327. cell->nbAdditionalBits = (BYTE)nbAddBits;
  328. cell->baseValue = baseValue;
  329. }
  330. /* ZSTD_buildFSETable() :
  331. * generate FSE decoding table for one symbol (ll, ml or off)
  332. * cannot fail if input is valid =>
  333. * all inputs are presumed validated at this stage */
  334. FORCE_INLINE_TEMPLATE
  335. void ZSTD_buildFSETable_body(ZSTD_seqSymbol* dt,
  336. const short* normalizedCounter, unsigned maxSymbolValue,
  337. const U32* baseValue, const U32* nbAdditionalBits,
  338. unsigned tableLog, void* wksp, size_t wkspSize)
  339. {
  340. ZSTD_seqSymbol* const tableDecode = dt+1;
  341. U32 const maxSV1 = maxSymbolValue + 1;
  342. U32 const tableSize = 1 << tableLog;
  343. U16* symbolNext = (U16*)wksp;
  344. BYTE* spread = (BYTE*)(symbolNext + MaxSeq + 1);
  345. U32 highThreshold = tableSize - 1;
  346. /* Sanity Checks */
  347. assert(maxSymbolValue <= MaxSeq);
  348. assert(tableLog <= MaxFSELog);
  349. assert(wkspSize >= ZSTD_BUILD_FSE_TABLE_WKSP_SIZE);
  350. (void)wkspSize;
  351. /* Init, lay down lowprob symbols */
  352. { ZSTD_seqSymbol_header DTableH;
  353. DTableH.tableLog = tableLog;
  354. DTableH.fastMode = 1;
  355. { S16 const largeLimit= (S16)(1 << (tableLog-1));
  356. U32 s;
  357. for (s=0; s<maxSV1; s++) {
  358. if (normalizedCounter[s]==-1) {
  359. tableDecode[highThreshold--].baseValue = s;
  360. symbolNext[s] = 1;
  361. } else {
  362. if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
  363. assert(normalizedCounter[s]>=0);
  364. symbolNext[s] = (U16)normalizedCounter[s];
  365. } } }
  366. ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
  367. }
  368. /* Spread symbols */
  369. assert(tableSize <= 512);
  370. /* Specialized symbol spreading for the case when there are
  371. * no low probability (-1 count) symbols. When compressing
  372. * small blocks we avoid low probability symbols to hit this
  373. * case, since header decoding speed matters more.
  374. */
  375. if (highThreshold == tableSize - 1) {
  376. size_t const tableMask = tableSize-1;
  377. size_t const step = FSE_TABLESTEP(tableSize);
  378. /* First lay down the symbols in order.
  379. * We use a uint64_t to lay down 8 bytes at a time. This reduces branch
  380. * misses since small blocks generally have small table logs, so nearly
  381. * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
  382. * our buffer to handle the over-write.
  383. */
  384. {
  385. U64 const add = 0x0101010101010101ull;
  386. size_t pos = 0;
  387. U64 sv = 0;
  388. U32 s;
  389. for (s=0; s<maxSV1; ++s, sv += add) {
  390. int i;
  391. int const n = normalizedCounter[s];
  392. MEM_write64(spread + pos, sv);
  393. for (i = 8; i < n; i += 8) {
  394. MEM_write64(spread + pos + i, sv);
  395. }
  396. pos += n;
  397. }
  398. }
  399. /* Now we spread those positions across the table.
  400. * The benefit of doing it in two stages is that we avoid the the
  401. * variable size inner loop, which caused lots of branch misses.
  402. * Now we can run through all the positions without any branch misses.
  403. * We unroll the loop twice, since that is what emperically worked best.
  404. */
  405. {
  406. size_t position = 0;
  407. size_t s;
  408. size_t const unroll = 2;
  409. assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
  410. for (s = 0; s < (size_t)tableSize; s += unroll) {
  411. size_t u;
  412. for (u = 0; u < unroll; ++u) {
  413. size_t const uPosition = (position + (u * step)) & tableMask;
  414. tableDecode[uPosition].baseValue = spread[s + u];
  415. }
  416. position = (position + (unroll * step)) & tableMask;
  417. }
  418. assert(position == 0);
  419. }
  420. } else {
  421. U32 const tableMask = tableSize-1;
  422. U32 const step = FSE_TABLESTEP(tableSize);
  423. U32 s, position = 0;
  424. for (s=0; s<maxSV1; s++) {
  425. int i;
  426. int const n = normalizedCounter[s];
  427. for (i=0; i<n; i++) {
  428. tableDecode[position].baseValue = s;
  429. position = (position + step) & tableMask;
  430. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  431. } }
  432. assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  433. }
  434. /* Build Decoding table */
  435. {
  436. U32 u;
  437. for (u=0; u<tableSize; u++) {
  438. U32 const symbol = tableDecode[u].baseValue;
  439. U32 const nextState = symbolNext[symbol]++;
  440. tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
  441. tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
  442. assert(nbAdditionalBits[symbol] < 255);
  443. tableDecode[u].nbAdditionalBits = (BYTE)nbAdditionalBits[symbol];
  444. tableDecode[u].baseValue = baseValue[symbol];
  445. }
  446. }
  447. }
  448. /* Avoids the FORCE_INLINE of the _body() function. */
  449. static void ZSTD_buildFSETable_body_default(ZSTD_seqSymbol* dt,
  450. const short* normalizedCounter, unsigned maxSymbolValue,
  451. const U32* baseValue, const U32* nbAdditionalBits,
  452. unsigned tableLog, void* wksp, size_t wkspSize)
  453. {
  454. ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
  455. baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
  456. }
  457. #if DYNAMIC_BMI2
  458. TARGET_ATTRIBUTE("bmi2") static void ZSTD_buildFSETable_body_bmi2(ZSTD_seqSymbol* dt,
  459. const short* normalizedCounter, unsigned maxSymbolValue,
  460. const U32* baseValue, const U32* nbAdditionalBits,
  461. unsigned tableLog, void* wksp, size_t wkspSize)
  462. {
  463. ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue,
  464. baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
  465. }
  466. #endif
  467. void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
  468. const short* normalizedCounter, unsigned maxSymbolValue,
  469. const U32* baseValue, const U32* nbAdditionalBits,
  470. unsigned tableLog, void* wksp, size_t wkspSize, int bmi2)
  471. {
  472. #if DYNAMIC_BMI2
  473. if (bmi2) {
  474. ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue,
  475. baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
  476. return;
  477. }
  478. #endif
  479. (void)bmi2;
  480. ZSTD_buildFSETable_body_default(dt, normalizedCounter, maxSymbolValue,
  481. baseValue, nbAdditionalBits, tableLog, wksp, wkspSize);
  482. }
  483. /*! ZSTD_buildSeqTable() :
  484. * @return : nb bytes read from src,
  485. * or an error code if it fails */
  486. static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
  487. symbolEncodingType_e type, unsigned max, U32 maxLog,
  488. const void* src, size_t srcSize,
  489. const U32* baseValue, const U32* nbAdditionalBits,
  490. const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
  491. int ddictIsCold, int nbSeq, U32* wksp, size_t wkspSize,
  492. int bmi2)
  493. {
  494. switch(type)
  495. {
  496. case set_rle :
  497. RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
  498. RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
  499. { U32 const symbol = *(const BYTE*)src;
  500. U32 const baseline = baseValue[symbol];
  501. U32 const nbBits = nbAdditionalBits[symbol];
  502. ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
  503. }
  504. *DTablePtr = DTableSpace;
  505. return 1;
  506. case set_basic :
  507. *DTablePtr = defaultTable;
  508. return 0;
  509. case set_repeat:
  510. RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
  511. /* prefetch FSE table if used */
  512. if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
  513. const void* const pStart = *DTablePtr;
  514. size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
  515. PREFETCH_AREA(pStart, pSize);
  516. }
  517. return 0;
  518. case set_compressed :
  519. { unsigned tableLog;
  520. S16 norm[MaxSeq+1];
  521. size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
  522. RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
  523. RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
  524. ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize, bmi2);
  525. *DTablePtr = DTableSpace;
  526. return headerSize;
  527. }
  528. default :
  529. assert(0);
  530. RETURN_ERROR(GENERIC, "impossible");
  531. }
  532. }
  533. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
  534. const void* src, size_t srcSize)
  535. {
  536. const BYTE* const istart = (const BYTE*)src;
  537. const BYTE* const iend = istart + srcSize;
  538. const BYTE* ip = istart;
  539. int nbSeq;
  540. DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
  541. /* check */
  542. RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");
  543. /* SeqHead */
  544. nbSeq = *ip++;
  545. if (!nbSeq) {
  546. *nbSeqPtr=0;
  547. RETURN_ERROR_IF(srcSize != 1, srcSize_wrong, "");
  548. return 1;
  549. }
  550. if (nbSeq > 0x7F) {
  551. if (nbSeq == 0xFF) {
  552. RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
  553. nbSeq = MEM_readLE16(ip) + LONGNBSEQ;
  554. ip+=2;
  555. } else {
  556. RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
  557. nbSeq = ((nbSeq-0x80)<<8) + *ip++;
  558. }
  559. }
  560. *nbSeqPtr = nbSeq;
  561. /* FSE table descriptors */
  562. RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
  563. { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
  564. symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
  565. symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
  566. ip++;
  567. /* Build DTables */
  568. { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
  569. LLtype, MaxLL, LLFSELog,
  570. ip, iend-ip,
  571. LL_base, LL_bits,
  572. LL_defaultDTable, dctx->fseEntropy,
  573. dctx->ddictIsCold, nbSeq,
  574. dctx->workspace, sizeof(dctx->workspace),
  575. dctx->bmi2);
  576. RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
  577. ip += llhSize;
  578. }
  579. { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
  580. OFtype, MaxOff, OffFSELog,
  581. ip, iend-ip,
  582. OF_base, OF_bits,
  583. OF_defaultDTable, dctx->fseEntropy,
  584. dctx->ddictIsCold, nbSeq,
  585. dctx->workspace, sizeof(dctx->workspace),
  586. dctx->bmi2);
  587. RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
  588. ip += ofhSize;
  589. }
  590. { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
  591. MLtype, MaxML, MLFSELog,
  592. ip, iend-ip,
  593. ML_base, ML_bits,
  594. ML_defaultDTable, dctx->fseEntropy,
  595. dctx->ddictIsCold, nbSeq,
  596. dctx->workspace, sizeof(dctx->workspace),
  597. dctx->bmi2);
  598. RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");
  599. ip += mlhSize;
  600. }
  601. }
  602. return ip-istart;
  603. }
  604. typedef struct {
  605. size_t litLength;
  606. size_t matchLength;
  607. size_t offset;
  608. } seq_t;
  609. typedef struct {
  610. size_t state;
  611. const ZSTD_seqSymbol* table;
  612. } ZSTD_fseState;
  613. typedef struct {
  614. BIT_DStream_t DStream;
  615. ZSTD_fseState stateLL;
  616. ZSTD_fseState stateOffb;
  617. ZSTD_fseState stateML;
  618. size_t prevOffset[ZSTD_REP_NUM];
  619. } seqState_t;
  620. /*! ZSTD_overlapCopy8() :
  621. * Copies 8 bytes from ip to op and updates op and ip where ip <= op.
  622. * If the offset is < 8 then the offset is spread to at least 8 bytes.
  623. *
  624. * Precondition: *ip <= *op
  625. * Postcondition: *op - *op >= 8
  626. */
  627. HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) {
  628. assert(*ip <= *op);
  629. if (offset < 8) {
  630. /* close range match, overlap */
  631. static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  632. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
  633. int const sub2 = dec64table[offset];
  634. (*op)[0] = (*ip)[0];
  635. (*op)[1] = (*ip)[1];
  636. (*op)[2] = (*ip)[2];
  637. (*op)[3] = (*ip)[3];
  638. *ip += dec32table[offset];
  639. ZSTD_copy4(*op+4, *ip);
  640. *ip -= sub2;
  641. } else {
  642. ZSTD_copy8(*op, *ip);
  643. }
  644. *ip += 8;
  645. *op += 8;
  646. assert(*op - *ip >= 8);
  647. }
  648. /*! ZSTD_safecopy() :
  649. * Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer
  650. * and write up to 16 bytes past oend_w (op >= oend_w is allowed).
  651. * This function is only called in the uncommon case where the sequence is near the end of the block. It
  652. * should be fast for a single long sequence, but can be slow for several short sequences.
  653. *
  654. * @param ovtype controls the overlap detection
  655. * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  656. * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
  657. * The src buffer must be before the dst buffer.
  658. */
  659. static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {
  660. ptrdiff_t const diff = op - ip;
  661. BYTE* const oend = op + length;
  662. assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
  663. (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
  664. if (length < 8) {
  665. /* Handle short lengths. */
  666. while (op < oend) *op++ = *ip++;
  667. return;
  668. }
  669. if (ovtype == ZSTD_overlap_src_before_dst) {
  670. /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
  671. assert(length >= 8);
  672. ZSTD_overlapCopy8(&op, &ip, diff);
  673. assert(op - ip >= 8);
  674. assert(op <= oend);
  675. }
  676. if (oend <= oend_w) {
  677. /* No risk of overwrite. */
  678. ZSTD_wildcopy(op, ip, length, ovtype);
  679. return;
  680. }
  681. if (op <= oend_w) {
  682. /* Wildcopy until we get close to the end. */
  683. assert(oend > oend_w);
  684. ZSTD_wildcopy(op, ip, oend_w - op, ovtype);
  685. ip += oend_w - op;
  686. op = oend_w;
  687. }
  688. /* Handle the leftovers. */
  689. while (op < oend) *op++ = *ip++;
  690. }
  691. /* ZSTD_execSequenceEnd():
  692. * This version handles cases that are near the end of the output buffer. It requires
  693. * more careful checks to make sure there is no overflow. By separating out these hard
  694. * and unlikely cases, we can speed up the common cases.
  695. *
  696. * NOTE: This function needs to be fast for a single long sequence, but doesn't need
  697. * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
  698. */
  699. FORCE_NOINLINE
  700. size_t ZSTD_execSequenceEnd(BYTE* op,
  701. BYTE* const oend, seq_t sequence,
  702. const BYTE** litPtr, const BYTE* const litLimit,
  703. const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
  704. {
  705. BYTE* const oLitEnd = op + sequence.litLength;
  706. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  707. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  708. const BYTE* match = oLitEnd - sequence.offset;
  709. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
  710. /* bounds checks : careful of address space overflow in 32-bit mode */
  711. RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
  712. RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
  713. assert(op < op + sequenceLength);
  714. assert(oLitEnd < op + sequenceLength);
  715. /* copy literals */
  716. ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
  717. op = oLitEnd;
  718. *litPtr = iLitEnd;
  719. /* copy Match */
  720. if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
  721. /* offset beyond prefix */
  722. RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
  723. match = dictEnd - (prefixStart-match);
  724. if (match + sequence.matchLength <= dictEnd) {
  725. ZSTD_memmove(oLitEnd, match, sequence.matchLength);
  726. return sequenceLength;
  727. }
  728. /* span extDict & currentPrefixSegment */
  729. { size_t const length1 = dictEnd - match;
  730. ZSTD_memmove(oLitEnd, match, length1);
  731. op = oLitEnd + length1;
  732. sequence.matchLength -= length1;
  733. match = prefixStart;
  734. } }
  735. ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
  736. return sequenceLength;
  737. }
  738. HINT_INLINE
  739. size_t ZSTD_execSequence(BYTE* op,
  740. BYTE* const oend, seq_t sequence,
  741. const BYTE** litPtr, const BYTE* const litLimit,
  742. const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
  743. {
  744. BYTE* const oLitEnd = op + sequence.litLength;
  745. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  746. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  747. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */
  748. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  749. const BYTE* match = oLitEnd - sequence.offset;
  750. assert(op != NULL /* Precondition */);
  751. assert(oend_w < oend /* No underflow */);
  752. /* Handle edge cases in a slow path:
  753. * - Read beyond end of literals
  754. * - Match end is within WILDCOPY_OVERLIMIT of oend
  755. * - 32-bit mode and the match length overflows
  756. */
  757. if (UNLIKELY(
  758. iLitEnd > litLimit ||
  759. oMatchEnd > oend_w ||
  760. (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
  761. return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
  762. /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
  763. assert(op <= oLitEnd /* No overflow */);
  764. assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
  765. assert(oMatchEnd <= oend /* No underflow */);
  766. assert(iLitEnd <= litLimit /* Literal length is in bounds */);
  767. assert(oLitEnd <= oend_w /* Can wildcopy literals */);
  768. assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
  769. /* Copy Literals:
  770. * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
  771. * We likely don't need the full 32-byte wildcopy.
  772. */
  773. assert(WILDCOPY_OVERLENGTH >= 16);
  774. ZSTD_copy16(op, (*litPtr));
  775. if (UNLIKELY(sequence.litLength > 16)) {
  776. ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
  777. }
  778. op = oLitEnd;
  779. *litPtr = iLitEnd; /* update for next sequence */
  780. /* Copy Match */
  781. if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
  782. /* offset beyond prefix -> go into extDict */
  783. RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
  784. match = dictEnd + (match - prefixStart);
  785. if (match + sequence.matchLength <= dictEnd) {
  786. ZSTD_memmove(oLitEnd, match, sequence.matchLength);
  787. return sequenceLength;
  788. }
  789. /* span extDict & currentPrefixSegment */
  790. { size_t const length1 = dictEnd - match;
  791. ZSTD_memmove(oLitEnd, match, length1);
  792. op = oLitEnd + length1;
  793. sequence.matchLength -= length1;
  794. match = prefixStart;
  795. } }
  796. /* Match within prefix of 1 or more bytes */
  797. assert(op <= oMatchEnd);
  798. assert(oMatchEnd <= oend_w);
  799. assert(match >= prefixStart);
  800. assert(sequence.matchLength >= 1);
  801. /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
  802. * without overlap checking.
  803. */
  804. if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
  805. /* We bet on a full wildcopy for matches, since we expect matches to be
  806. * longer than literals (in general). In silesia, ~10% of matches are longer
  807. * than 16 bytes.
  808. */
  809. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
  810. return sequenceLength;
  811. }
  812. assert(sequence.offset < WILDCOPY_VECLEN);
  813. /* Copy 8 bytes and spread the offset to be >= 8. */
  814. ZSTD_overlapCopy8(&op, &match, sequence.offset);
  815. /* If the match length is > 8 bytes, then continue with the wildcopy. */
  816. if (sequence.matchLength > 8) {
  817. assert(op < oMatchEnd);
  818. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst);
  819. }
  820. return sequenceLength;
  821. }
  822. static void
  823. ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
  824. {
  825. const void* ptr = dt;
  826. const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
  827. DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
  828. DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
  829. (U32)DStatePtr->state, DTableH->tableLog);
  830. BIT_reloadDStream(bitD);
  831. DStatePtr->table = dt + 1;
  832. }
  833. FORCE_INLINE_TEMPLATE void
  834. ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD)
  835. {
  836. ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state];
  837. U32 const nbBits = DInfo.nbBits;
  838. size_t const lowBits = BIT_readBits(bitD, nbBits);
  839. DStatePtr->state = DInfo.nextState + lowBits;
  840. }
  841. FORCE_INLINE_TEMPLATE void
  842. ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, ZSTD_seqSymbol const DInfo)
  843. {
  844. U32 const nbBits = DInfo.nbBits;
  845. size_t const lowBits = BIT_readBits(bitD, nbBits);
  846. DStatePtr->state = DInfo.nextState + lowBits;
  847. }
  848. /* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
  849. * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1)
  850. * bits before reloading. This value is the maximum number of bytes we read
  851. * after reloading when we are decoding long offsets.
  852. */
  853. #define LONG_OFFSETS_MAX_EXTRA_BITS_32 \
  854. (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \
  855. ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \
  856. : 0)
  857. typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
  858. FORCE_INLINE_TEMPLATE seq_t
  859. ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets)
  860. {
  861. seq_t seq;
  862. ZSTD_seqSymbol const llDInfo = seqState->stateLL.table[seqState->stateLL.state];
  863. ZSTD_seqSymbol const mlDInfo = seqState->stateML.table[seqState->stateML.state];
  864. ZSTD_seqSymbol const ofDInfo = seqState->stateOffb.table[seqState->stateOffb.state];
  865. U32 const llBase = llDInfo.baseValue;
  866. U32 const mlBase = mlDInfo.baseValue;
  867. U32 const ofBase = ofDInfo.baseValue;
  868. BYTE const llBits = llDInfo.nbAdditionalBits;
  869. BYTE const mlBits = mlDInfo.nbAdditionalBits;
  870. BYTE const ofBits = ofDInfo.nbAdditionalBits;
  871. BYTE const totalBits = llBits+mlBits+ofBits;
  872. /* sequence */
  873. { size_t offset;
  874. if (ofBits > 1) {
  875. ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
  876. ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
  877. assert(ofBits <= MaxOff);
  878. if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
  879. U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed);
  880. offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  881. BIT_reloadDStream(&seqState->DStream);
  882. if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  883. assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32); /* to avoid another reload */
  884. } else {
  885. offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  886. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
  887. }
  888. seqState->prevOffset[2] = seqState->prevOffset[1];
  889. seqState->prevOffset[1] = seqState->prevOffset[0];
  890. seqState->prevOffset[0] = offset;
  891. } else {
  892. U32 const ll0 = (llBase == 0);
  893. if (LIKELY((ofBits == 0))) {
  894. if (LIKELY(!ll0))
  895. offset = seqState->prevOffset[0];
  896. else {
  897. offset = seqState->prevOffset[1];
  898. seqState->prevOffset[1] = seqState->prevOffset[0];
  899. seqState->prevOffset[0] = offset;
  900. }
  901. } else {
  902. offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
  903. { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  904. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  905. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  906. seqState->prevOffset[1] = seqState->prevOffset[0];
  907. seqState->prevOffset[0] = offset = temp;
  908. } } }
  909. seq.offset = offset;
  910. }
  911. seq.matchLength = mlBase;
  912. if (mlBits > 0)
  913. seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
  914. if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
  915. BIT_reloadDStream(&seqState->DStream);
  916. if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
  917. BIT_reloadDStream(&seqState->DStream);
  918. /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
  919. ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
  920. seq.litLength = llBase;
  921. if (llBits > 0)
  922. seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
  923. if (MEM_32bits())
  924. BIT_reloadDStream(&seqState->DStream);
  925. DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
  926. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  927. /* ANS state update
  928. * gcc-9.0.0 does 2.5% worse with ZSTD_updateFseStateWithDInfo().
  929. * clang-9.2.0 does 7% worse with ZSTD_updateFseState().
  930. * Naturally it seems like ZSTD_updateFseStateWithDInfo() should be the
  931. * better option, so it is the default for other compilers. But, if you
  932. * measure that it is worse, please put up a pull request.
  933. */
  934. {
  935. #if defined(__GNUC__) && !defined(__clang__)
  936. const int kUseUpdateFseState = 1;
  937. #else
  938. const int kUseUpdateFseState = 0;
  939. #endif
  940. if (kUseUpdateFseState) {
  941. ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  942. ZSTD_updateFseState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  943. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  944. ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  945. } else {
  946. ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llDInfo); /* <= 9 bits */
  947. ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlDInfo); /* <= 9 bits */
  948. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  949. ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofDInfo); /* <= 8 bits */
  950. }
  951. }
  952. return seq;
  953. }
  954. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  955. MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
  956. {
  957. size_t const windowSize = dctx->fParams.windowSize;
  958. /* No dictionary used. */
  959. if (dctx->dictContentEndForFuzzing == NULL) return 0;
  960. /* Dictionary is our prefix. */
  961. if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
  962. /* Dictionary is not our ext-dict. */
  963. if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
  964. /* Dictionary is not within our window size. */
  965. if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
  966. /* Dictionary is active. */
  967. return 1;
  968. }
  969. MEM_STATIC void ZSTD_assertValidSequence(
  970. ZSTD_DCtx const* dctx,
  971. BYTE const* op, BYTE const* oend,
  972. seq_t const seq,
  973. BYTE const* prefixStart, BYTE const* virtualStart)
  974. {
  975. #if DEBUGLEVEL >= 1
  976. size_t const windowSize = dctx->fParams.windowSize;
  977. size_t const sequenceSize = seq.litLength + seq.matchLength;
  978. BYTE const* const oLitEnd = op + seq.litLength;
  979. DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
  980. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  981. assert(op <= oend);
  982. assert((size_t)(oend - op) >= sequenceSize);
  983. assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX);
  984. if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
  985. size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
  986. /* Offset must be within the dictionary. */
  987. assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
  988. assert(seq.offset <= windowSize + dictSize);
  989. } else {
  990. /* Offset must be within our window. */
  991. assert(seq.offset <= windowSize);
  992. }
  993. #else
  994. (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
  995. #endif
  996. }
  997. #endif
  998. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  999. FORCE_INLINE_TEMPLATE size_t
  1000. DONT_VECTORIZE
  1001. ZSTD_decompressSequences_body( ZSTD_DCtx* dctx,
  1002. void* dst, size_t maxDstSize,
  1003. const void* seqStart, size_t seqSize, int nbSeq,
  1004. const ZSTD_longOffset_e isLongOffset,
  1005. const int frame)
  1006. {
  1007. const BYTE* ip = (const BYTE*)seqStart;
  1008. const BYTE* const iend = ip + seqSize;
  1009. BYTE* const ostart = (BYTE*)dst;
  1010. BYTE* const oend = ostart + maxDstSize;
  1011. BYTE* op = ostart;
  1012. const BYTE* litPtr = dctx->litPtr;
  1013. const BYTE* const litEnd = litPtr + dctx->litSize;
  1014. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1015. const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
  1016. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1017. DEBUGLOG(5, "ZSTD_decompressSequences_body");
  1018. (void)frame;
  1019. /* Regen sequences */
  1020. if (nbSeq) {
  1021. seqState_t seqState;
  1022. dctx->fseEntropy = 1;
  1023. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1024. RETURN_ERROR_IF(
  1025. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1026. corruption_detected, "");
  1027. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1028. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1029. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1030. assert(dst != NULL);
  1031. ZSTD_STATIC_ASSERT(
  1032. BIT_DStream_unfinished < BIT_DStream_completed &&
  1033. BIT_DStream_endOfBuffer < BIT_DStream_completed &&
  1034. BIT_DStream_completed < BIT_DStream_overflow);
  1035. #if defined(__GNUC__) && defined(__x86_64__)
  1036. /* Align the decompression loop to 32 + 16 bytes.
  1037. *
  1038. * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
  1039. * speed swings based on the alignment of the decompression loop. This
  1040. * performance swing is caused by parts of the decompression loop falling
  1041. * out of the DSB. The entire decompression loop should fit in the DSB,
  1042. * when it can't we get much worse performance. You can measure if you've
  1043. * hit the good case or the bad case with this perf command for some
  1044. * compressed file test.zst:
  1045. *
  1046. * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
  1047. * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
  1048. *
  1049. * If you see most cycles served out of the MITE you've hit the bad case.
  1050. * If you see most cycles served out of the DSB you've hit the good case.
  1051. * If it is pretty even then you may be in an okay case.
  1052. *
  1053. * This issue has been reproduced on the following CPUs:
  1054. * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
  1055. * Use Instruments->Counters to get DSB/MITE cycles.
  1056. * I never got performance swings, but I was able to
  1057. * go from the good case of mostly DSB to half of the
  1058. * cycles served from MITE.
  1059. * - Coffeelake: Intel i9-9900k
  1060. * - Coffeelake: Intel i7-9700k
  1061. *
  1062. * I haven't been able to reproduce the instability or DSB misses on any
  1063. * of the following CPUS:
  1064. * - Haswell
  1065. * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
  1066. * - Skylake
  1067. *
  1068. * If you are seeing performance stability this script can help test.
  1069. * It tests on 4 commits in zstd where I saw performance change.
  1070. *
  1071. * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
  1072. */
  1073. __asm__(".p2align 6");
  1074. __asm__("nop");
  1075. __asm__(".p2align 5");
  1076. __asm__("nop");
  1077. # if __GNUC__ >= 9
  1078. /* better for gcc-9 and gcc-10, worse for clang and gcc-8 */
  1079. __asm__(".p2align 3");
  1080. # else
  1081. __asm__(".p2align 4");
  1082. # endif
  1083. #endif
  1084. for ( ; ; ) {
  1085. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1086. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
  1087. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1088. assert(!ZSTD_isError(oneSeqSize));
  1089. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  1090. #endif
  1091. if (UNLIKELY(ZSTD_isError(oneSeqSize)))
  1092. return oneSeqSize;
  1093. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  1094. op += oneSeqSize;
  1095. if (UNLIKELY(!--nbSeq))
  1096. break;
  1097. BIT_reloadDStream(&(seqState.DStream));
  1098. }
  1099. /* check if reached exact end */
  1100. DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
  1101. RETURN_ERROR_IF(nbSeq, corruption_detected, "");
  1102. RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
  1103. /* save reps for next block */
  1104. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1105. }
  1106. /* last literal segment */
  1107. { size_t const lastLLSize = litEnd - litPtr;
  1108. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1109. if (op != NULL) {
  1110. ZSTD_memcpy(op, litPtr, lastLLSize);
  1111. op += lastLLSize;
  1112. }
  1113. }
  1114. return op-ostart;
  1115. }
  1116. static size_t
  1117. ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
  1118. void* dst, size_t maxDstSize,
  1119. const void* seqStart, size_t seqSize, int nbSeq,
  1120. const ZSTD_longOffset_e isLongOffset,
  1121. const int frame)
  1122. {
  1123. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1124. }
  1125. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1126. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1127. FORCE_INLINE_TEMPLATE size_t
  1128. ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
  1129. const BYTE* const prefixStart, const BYTE* const dictEnd)
  1130. {
  1131. prefetchPos += sequence.litLength;
  1132. { const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;
  1133. 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.
  1134. * No consequence though : memory address is only used for prefetching, not for dereferencing */
  1135. PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
  1136. }
  1137. return prefetchPos + sequence.matchLength;
  1138. }
  1139. /* This decoding function employs prefetching
  1140. * to reduce latency impact of cache misses.
  1141. * It's generally employed when block contains a significant portion of long-distance matches
  1142. * or when coupled with a "cold" dictionary */
  1143. FORCE_INLINE_TEMPLATE size_t
  1144. ZSTD_decompressSequencesLong_body(
  1145. ZSTD_DCtx* dctx,
  1146. void* dst, size_t maxDstSize,
  1147. const void* seqStart, size_t seqSize, int nbSeq,
  1148. const ZSTD_longOffset_e isLongOffset,
  1149. const int frame)
  1150. {
  1151. const BYTE* ip = (const BYTE*)seqStart;
  1152. const BYTE* const iend = ip + seqSize;
  1153. BYTE* const ostart = (BYTE*)dst;
  1154. BYTE* const oend = ostart + maxDstSize;
  1155. BYTE* op = ostart;
  1156. const BYTE* litPtr = dctx->litPtr;
  1157. const BYTE* const litEnd = litPtr + dctx->litSize;
  1158. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1159. const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
  1160. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1161. (void)frame;
  1162. /* Regen sequences */
  1163. if (nbSeq) {
  1164. #define STORED_SEQS 8
  1165. #define STORED_SEQS_MASK (STORED_SEQS-1)
  1166. #define ADVANCED_SEQS STORED_SEQS
  1167. seq_t sequences[STORED_SEQS];
  1168. int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
  1169. seqState_t seqState;
  1170. int seqNb;
  1171. size_t prefetchPos = (size_t)(op-prefixStart); /* track position relative to prefixStart */
  1172. dctx->fseEntropy = 1;
  1173. { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1174. assert(dst != NULL);
  1175. assert(iend >= ip);
  1176. RETURN_ERROR_IF(
  1177. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1178. corruption_detected, "");
  1179. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1180. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1181. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1182. /* prepare in advance */
  1183. for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
  1184. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1185. prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
  1186. sequences[seqNb] = sequence;
  1187. }
  1188. RETURN_ERROR_IF(seqNb<seqAdvance, corruption_detected, "");
  1189. /* decode and decompress */
  1190. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) {
  1191. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
  1192. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
  1193. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1194. assert(!ZSTD_isError(oneSeqSize));
  1195. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
  1196. #endif
  1197. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1198. prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd);
  1199. sequences[seqNb & STORED_SEQS_MASK] = sequence;
  1200. op += oneSeqSize;
  1201. }
  1202. RETURN_ERROR_IF(seqNb<nbSeq, corruption_detected, "");
  1203. /* finish queue */
  1204. seqNb -= seqAdvance;
  1205. for ( ; seqNb<nbSeq ; seqNb++) {
  1206. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
  1207. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1208. assert(!ZSTD_isError(oneSeqSize));
  1209. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
  1210. #endif
  1211. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1212. op += oneSeqSize;
  1213. }
  1214. /* save reps for next block */
  1215. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1216. }
  1217. /* last literal segment */
  1218. { size_t const lastLLSize = litEnd - litPtr;
  1219. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1220. if (op != NULL) {
  1221. ZSTD_memcpy(op, litPtr, lastLLSize);
  1222. op += lastLLSize;
  1223. }
  1224. }
  1225. return op-ostart;
  1226. }
  1227. static size_t
  1228. ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
  1229. void* dst, size_t maxDstSize,
  1230. const void* seqStart, size_t seqSize, int nbSeq,
  1231. const ZSTD_longOffset_e isLongOffset,
  1232. const int frame)
  1233. {
  1234. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1235. }
  1236. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1237. #if DYNAMIC_BMI2
  1238. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1239. static TARGET_ATTRIBUTE("bmi2") size_t
  1240. DONT_VECTORIZE
  1241. ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
  1242. void* dst, size_t maxDstSize,
  1243. const void* seqStart, size_t seqSize, int nbSeq,
  1244. const ZSTD_longOffset_e isLongOffset,
  1245. const int frame)
  1246. {
  1247. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1248. }
  1249. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1250. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1251. static TARGET_ATTRIBUTE("bmi2") size_t
  1252. ZSTD_decompressSequencesLong_bmi2(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. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1259. }
  1260. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1261. #endif /* DYNAMIC_BMI2 */
  1262. typedef size_t (*ZSTD_decompressSequences_t)(
  1263. ZSTD_DCtx* dctx,
  1264. void* dst, size_t maxDstSize,
  1265. const void* seqStart, size_t seqSize, int nbSeq,
  1266. const ZSTD_longOffset_e isLongOffset,
  1267. const int frame);
  1268. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1269. static size_t
  1270. ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
  1271. const void* seqStart, size_t seqSize, int nbSeq,
  1272. const ZSTD_longOffset_e isLongOffset,
  1273. const int frame)
  1274. {
  1275. DEBUGLOG(5, "ZSTD_decompressSequences");
  1276. #if DYNAMIC_BMI2
  1277. if (dctx->bmi2) {
  1278. return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1279. }
  1280. #endif
  1281. return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1282. }
  1283. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1284. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1285. /* ZSTD_decompressSequencesLong() :
  1286. * decompression function triggered when a minimum share of offsets is considered "long",
  1287. * aka out of cache.
  1288. * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
  1289. * This function will try to mitigate main memory latency through the use of prefetching */
  1290. static size_t
  1291. ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
  1292. void* dst, size_t maxDstSize,
  1293. const void* seqStart, size_t seqSize, int nbSeq,
  1294. const ZSTD_longOffset_e isLongOffset,
  1295. const int frame)
  1296. {
  1297. DEBUGLOG(5, "ZSTD_decompressSequencesLong");
  1298. #if DYNAMIC_BMI2
  1299. if (dctx->bmi2) {
  1300. return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1301. }
  1302. #endif
  1303. return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1304. }
  1305. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1306. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1307. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1308. /* ZSTD_getLongOffsetsShare() :
  1309. * condition : offTable must be valid
  1310. * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
  1311. * compared to maximum possible of (1<<OffFSELog) */
  1312. static unsigned
  1313. ZSTD_getLongOffsetsShare(const ZSTD_seqSymbol* offTable)
  1314. {
  1315. const void* ptr = offTable;
  1316. U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
  1317. const ZSTD_seqSymbol* table = offTable + 1;
  1318. U32 const max = 1 << tableLog;
  1319. U32 u, total = 0;
  1320. DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
  1321. assert(max <= (1 << OffFSELog)); /* max not too large */
  1322. for (u=0; u<max; u++) {
  1323. if (table[u].nbAdditionalBits > 22) total += 1;
  1324. }
  1325. assert(tableLog <= OffFSELog);
  1326. total <<= (OffFSELog - tableLog); /* scale to OffFSELog */
  1327. return total;
  1328. }
  1329. #endif
  1330. size_t
  1331. ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
  1332. void* dst, size_t dstCapacity,
  1333. const void* src, size_t srcSize, const int frame)
  1334. { /* blockType == blockCompressed */
  1335. const BYTE* ip = (const BYTE*)src;
  1336. /* isLongOffset must be true if there are long offsets.
  1337. * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
  1338. * We don't expect that to be the case in 64-bit mode.
  1339. * In block mode, window size is not known, so we have to be conservative.
  1340. * (note: but it could be evaluated from current-lowLimit)
  1341. */
  1342. ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN))));
  1343. DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
  1344. RETURN_ERROR_IF(srcSize >= ZSTD_BLOCKSIZE_MAX, srcSize_wrong, "");
  1345. /* Decode literals section */
  1346. { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
  1347. DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
  1348. if (ZSTD_isError(litCSize)) return litCSize;
  1349. ip += litCSize;
  1350. srcSize -= litCSize;
  1351. }
  1352. /* Build Decoding Tables */
  1353. {
  1354. /* These macros control at build-time which decompressor implementation
  1355. * we use. If neither is defined, we do some inspection and dispatch at
  1356. * runtime.
  1357. */
  1358. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1359. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1360. int usePrefetchDecoder = dctx->ddictIsCold;
  1361. #endif
  1362. int nbSeq;
  1363. size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
  1364. if (ZSTD_isError(seqHSize)) return seqHSize;
  1365. ip += seqHSize;
  1366. srcSize -= seqHSize;
  1367. RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
  1368. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1369. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1370. if ( !usePrefetchDecoder
  1371. && (!frame || (dctx->fParams.windowSize > (1<<24)))
  1372. && (nbSeq>ADVANCED_SEQS) ) { /* could probably use a larger nbSeq limit */
  1373. U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr);
  1374. U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
  1375. usePrefetchDecoder = (shareLongOffsets >= minShare);
  1376. }
  1377. #endif
  1378. dctx->ddictIsCold = 0;
  1379. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1380. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1381. if (usePrefetchDecoder)
  1382. #endif
  1383. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1384. return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1385. #endif
  1386. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1387. /* else */
  1388. return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1389. #endif
  1390. }
  1391. }
  1392. void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
  1393. {
  1394. if (dst != dctx->previousDstEnd && dstSize > 0) { /* not contiguous */
  1395. dctx->dictEnd = dctx->previousDstEnd;
  1396. dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
  1397. dctx->prefixStart = dst;
  1398. dctx->previousDstEnd = dst;
  1399. }
  1400. }
  1401. size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
  1402. void* dst, size_t dstCapacity,
  1403. const void* src, size_t srcSize)
  1404. {
  1405. size_t dSize;
  1406. ZSTD_checkContinuity(dctx, dst, dstCapacity);
  1407. dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
  1408. dctx->previousDstEnd = (char*)dst + dSize;
  1409. return dSize;
  1410. }