zstd_decompress_block.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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. ZSTD_FALLTHROUGH;
  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. const BYTE* match;
  609. } seq_t;
  610. typedef struct {
  611. size_t state;
  612. const ZSTD_seqSymbol* table;
  613. } ZSTD_fseState;
  614. typedef struct {
  615. BIT_DStream_t DStream;
  616. ZSTD_fseState stateLL;
  617. ZSTD_fseState stateOffb;
  618. ZSTD_fseState stateML;
  619. size_t prevOffset[ZSTD_REP_NUM];
  620. const BYTE* prefixStart;
  621. const BYTE* dictEnd;
  622. size_t pos;
  623. } seqState_t;
  624. /*! ZSTD_overlapCopy8() :
  625. * Copies 8 bytes from ip to op and updates op and ip where ip <= op.
  626. * If the offset is < 8 then the offset is spread to at least 8 bytes.
  627. *
  628. * Precondition: *ip <= *op
  629. * Postcondition: *op - *op >= 8
  630. */
  631. HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) {
  632. assert(*ip <= *op);
  633. if (offset < 8) {
  634. /* close range match, overlap */
  635. static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  636. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
  637. int const sub2 = dec64table[offset];
  638. (*op)[0] = (*ip)[0];
  639. (*op)[1] = (*ip)[1];
  640. (*op)[2] = (*ip)[2];
  641. (*op)[3] = (*ip)[3];
  642. *ip += dec32table[offset];
  643. ZSTD_copy4(*op+4, *ip);
  644. *ip -= sub2;
  645. } else {
  646. ZSTD_copy8(*op, *ip);
  647. }
  648. *ip += 8;
  649. *op += 8;
  650. assert(*op - *ip >= 8);
  651. }
  652. /*! ZSTD_safecopy() :
  653. * Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer
  654. * and write up to 16 bytes past oend_w (op >= oend_w is allowed).
  655. * This function is only called in the uncommon case where the sequence is near the end of the block. It
  656. * should be fast for a single long sequence, but can be slow for several short sequences.
  657. *
  658. * @param ovtype controls the overlap detection
  659. * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  660. * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
  661. * The src buffer must be before the dst buffer.
  662. */
  663. static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {
  664. ptrdiff_t const diff = op - ip;
  665. BYTE* const oend = op + length;
  666. assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
  667. (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
  668. if (length < 8) {
  669. /* Handle short lengths. */
  670. while (op < oend) *op++ = *ip++;
  671. return;
  672. }
  673. if (ovtype == ZSTD_overlap_src_before_dst) {
  674. /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
  675. assert(length >= 8);
  676. ZSTD_overlapCopy8(&op, &ip, diff);
  677. assert(op - ip >= 8);
  678. assert(op <= oend);
  679. }
  680. if (oend <= oend_w) {
  681. /* No risk of overwrite. */
  682. ZSTD_wildcopy(op, ip, length, ovtype);
  683. return;
  684. }
  685. if (op <= oend_w) {
  686. /* Wildcopy until we get close to the end. */
  687. assert(oend > oend_w);
  688. ZSTD_wildcopy(op, ip, oend_w - op, ovtype);
  689. ip += oend_w - op;
  690. op = oend_w;
  691. }
  692. /* Handle the leftovers. */
  693. while (op < oend) *op++ = *ip++;
  694. }
  695. /* ZSTD_execSequenceEnd():
  696. * This version handles cases that are near the end of the output buffer. It requires
  697. * more careful checks to make sure there is no overflow. By separating out these hard
  698. * and unlikely cases, we can speed up the common cases.
  699. *
  700. * NOTE: This function needs to be fast for a single long sequence, but doesn't need
  701. * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
  702. */
  703. FORCE_NOINLINE
  704. size_t ZSTD_execSequenceEnd(BYTE* op,
  705. BYTE* const oend, seq_t sequence,
  706. const BYTE** litPtr, const BYTE* const litLimit,
  707. const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
  708. {
  709. BYTE* const oLitEnd = op + sequence.litLength;
  710. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  711. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  712. const BYTE* match = oLitEnd - sequence.offset;
  713. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
  714. /* bounds checks : careful of address space overflow in 32-bit mode */
  715. RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
  716. RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
  717. assert(op < op + sequenceLength);
  718. assert(oLitEnd < op + sequenceLength);
  719. /* copy literals */
  720. ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
  721. op = oLitEnd;
  722. *litPtr = iLitEnd;
  723. /* copy Match */
  724. if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
  725. /* offset beyond prefix */
  726. RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
  727. match = dictEnd - (prefixStart-match);
  728. if (match + sequence.matchLength <= dictEnd) {
  729. ZSTD_memmove(oLitEnd, match, sequence.matchLength);
  730. return sequenceLength;
  731. }
  732. /* span extDict & currentPrefixSegment */
  733. { size_t const length1 = dictEnd - match;
  734. ZSTD_memmove(oLitEnd, match, length1);
  735. op = oLitEnd + length1;
  736. sequence.matchLength -= length1;
  737. match = prefixStart;
  738. } }
  739. ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
  740. return sequenceLength;
  741. }
  742. HINT_INLINE
  743. size_t ZSTD_execSequence(BYTE* op,
  744. BYTE* const oend, seq_t sequence,
  745. const BYTE** litPtr, const BYTE* const litLimit,
  746. const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
  747. {
  748. BYTE* const oLitEnd = op + sequence.litLength;
  749. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  750. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  751. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */
  752. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  753. const BYTE* match = oLitEnd - sequence.offset;
  754. assert(op != NULL /* Precondition */);
  755. assert(oend_w < oend /* No underflow */);
  756. /* Handle edge cases in a slow path:
  757. * - Read beyond end of literals
  758. * - Match end is within WILDCOPY_OVERLIMIT of oend
  759. * - 32-bit mode and the match length overflows
  760. */
  761. if (UNLIKELY(
  762. iLitEnd > litLimit ||
  763. oMatchEnd > oend_w ||
  764. (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
  765. return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
  766. /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
  767. assert(op <= oLitEnd /* No overflow */);
  768. assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
  769. assert(oMatchEnd <= oend /* No underflow */);
  770. assert(iLitEnd <= litLimit /* Literal length is in bounds */);
  771. assert(oLitEnd <= oend_w /* Can wildcopy literals */);
  772. assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
  773. /* Copy Literals:
  774. * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
  775. * We likely don't need the full 32-byte wildcopy.
  776. */
  777. assert(WILDCOPY_OVERLENGTH >= 16);
  778. ZSTD_copy16(op, (*litPtr));
  779. if (UNLIKELY(sequence.litLength > 16)) {
  780. ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
  781. }
  782. op = oLitEnd;
  783. *litPtr = iLitEnd; /* update for next sequence */
  784. /* Copy Match */
  785. if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
  786. /* offset beyond prefix -> go into extDict */
  787. RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
  788. match = dictEnd + (match - prefixStart);
  789. if (match + sequence.matchLength <= dictEnd) {
  790. ZSTD_memmove(oLitEnd, match, sequence.matchLength);
  791. return sequenceLength;
  792. }
  793. /* span extDict & currentPrefixSegment */
  794. { size_t const length1 = dictEnd - match;
  795. ZSTD_memmove(oLitEnd, match, length1);
  796. op = oLitEnd + length1;
  797. sequence.matchLength -= length1;
  798. match = prefixStart;
  799. } }
  800. /* Match within prefix of 1 or more bytes */
  801. assert(op <= oMatchEnd);
  802. assert(oMatchEnd <= oend_w);
  803. assert(match >= prefixStart);
  804. assert(sequence.matchLength >= 1);
  805. /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
  806. * without overlap checking.
  807. */
  808. if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
  809. /* We bet on a full wildcopy for matches, since we expect matches to be
  810. * longer than literals (in general). In silesia, ~10% of matches are longer
  811. * than 16 bytes.
  812. */
  813. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
  814. return sequenceLength;
  815. }
  816. assert(sequence.offset < WILDCOPY_VECLEN);
  817. /* Copy 8 bytes and spread the offset to be >= 8. */
  818. ZSTD_overlapCopy8(&op, &match, sequence.offset);
  819. /* If the match length is > 8 bytes, then continue with the wildcopy. */
  820. if (sequence.matchLength > 8) {
  821. assert(op < oMatchEnd);
  822. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst);
  823. }
  824. return sequenceLength;
  825. }
  826. static void
  827. ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
  828. {
  829. const void* ptr = dt;
  830. const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
  831. DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
  832. DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
  833. (U32)DStatePtr->state, DTableH->tableLog);
  834. BIT_reloadDStream(bitD);
  835. DStatePtr->table = dt + 1;
  836. }
  837. FORCE_INLINE_TEMPLATE void
  838. ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD)
  839. {
  840. ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state];
  841. U32 const nbBits = DInfo.nbBits;
  842. size_t const lowBits = BIT_readBits(bitD, nbBits);
  843. DStatePtr->state = DInfo.nextState + lowBits;
  844. }
  845. FORCE_INLINE_TEMPLATE void
  846. ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, ZSTD_seqSymbol const DInfo)
  847. {
  848. U32 const nbBits = DInfo.nbBits;
  849. size_t const lowBits = BIT_readBits(bitD, nbBits);
  850. DStatePtr->state = DInfo.nextState + lowBits;
  851. }
  852. /* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
  853. * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1)
  854. * bits before reloading. This value is the maximum number of bytes we read
  855. * after reloading when we are decoding long offsets.
  856. */
  857. #define LONG_OFFSETS_MAX_EXTRA_BITS_32 \
  858. (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \
  859. ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \
  860. : 0)
  861. typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
  862. typedef enum { ZSTD_p_noPrefetch=0, ZSTD_p_prefetch=1 } ZSTD_prefetch_e;
  863. FORCE_INLINE_TEMPLATE seq_t
  864. ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const ZSTD_prefetch_e prefetch)
  865. {
  866. seq_t seq;
  867. ZSTD_seqSymbol const llDInfo = seqState->stateLL.table[seqState->stateLL.state];
  868. ZSTD_seqSymbol const mlDInfo = seqState->stateML.table[seqState->stateML.state];
  869. ZSTD_seqSymbol const ofDInfo = seqState->stateOffb.table[seqState->stateOffb.state];
  870. U32 const llBase = llDInfo.baseValue;
  871. U32 const mlBase = mlDInfo.baseValue;
  872. U32 const ofBase = ofDInfo.baseValue;
  873. BYTE const llBits = llDInfo.nbAdditionalBits;
  874. BYTE const mlBits = mlDInfo.nbAdditionalBits;
  875. BYTE const ofBits = ofDInfo.nbAdditionalBits;
  876. BYTE const totalBits = llBits+mlBits+ofBits;
  877. /* sequence */
  878. { size_t offset;
  879. if (ofBits > 1) {
  880. ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
  881. ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
  882. assert(ofBits <= MaxOff);
  883. if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
  884. U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed);
  885. offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  886. BIT_reloadDStream(&seqState->DStream);
  887. if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  888. assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32); /* to avoid another reload */
  889. } else {
  890. offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  891. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
  892. }
  893. seqState->prevOffset[2] = seqState->prevOffset[1];
  894. seqState->prevOffset[1] = seqState->prevOffset[0];
  895. seqState->prevOffset[0] = offset;
  896. } else {
  897. U32 const ll0 = (llBase == 0);
  898. if (LIKELY((ofBits == 0))) {
  899. if (LIKELY(!ll0))
  900. offset = seqState->prevOffset[0];
  901. else {
  902. offset = seqState->prevOffset[1];
  903. seqState->prevOffset[1] = seqState->prevOffset[0];
  904. seqState->prevOffset[0] = offset;
  905. }
  906. } else {
  907. offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
  908. { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  909. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  910. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  911. seqState->prevOffset[1] = seqState->prevOffset[0];
  912. seqState->prevOffset[0] = offset = temp;
  913. } } }
  914. seq.offset = offset;
  915. }
  916. seq.matchLength = mlBase;
  917. if (mlBits > 0)
  918. seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
  919. if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
  920. BIT_reloadDStream(&seqState->DStream);
  921. if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
  922. BIT_reloadDStream(&seqState->DStream);
  923. /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
  924. ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
  925. seq.litLength = llBase;
  926. if (llBits > 0)
  927. seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
  928. if (MEM_32bits())
  929. BIT_reloadDStream(&seqState->DStream);
  930. DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
  931. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  932. if (prefetch == ZSTD_p_prefetch) {
  933. size_t const pos = seqState->pos + seq.litLength;
  934. const BYTE* const matchBase = (seq.offset > pos) ? seqState->dictEnd : seqState->prefixStart;
  935. seq.match = matchBase + pos - seq.offset; /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.
  936. * No consequence though : no memory access will occur, offset is only used for prefetching */
  937. seqState->pos = pos + seq.matchLength;
  938. }
  939. /* ANS state update
  940. * gcc-9.0.0 does 2.5% worse with ZSTD_updateFseStateWithDInfo().
  941. * clang-9.2.0 does 7% worse with ZSTD_updateFseState().
  942. * Naturally it seems like ZSTD_updateFseStateWithDInfo() should be the
  943. * better option, so it is the default for other compilers. But, if you
  944. * measure that it is worse, please put up a pull request.
  945. */
  946. {
  947. #if !defined(__clang__)
  948. const int kUseUpdateFseState = 1;
  949. #else
  950. const int kUseUpdateFseState = 0;
  951. #endif
  952. if (kUseUpdateFseState) {
  953. ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  954. ZSTD_updateFseState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  955. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  956. ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  957. } else {
  958. ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llDInfo); /* <= 9 bits */
  959. ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlDInfo); /* <= 9 bits */
  960. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  961. ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofDInfo); /* <= 8 bits */
  962. }
  963. }
  964. return seq;
  965. }
  966. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  967. MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
  968. {
  969. size_t const windowSize = dctx->fParams.windowSize;
  970. /* No dictionary used. */
  971. if (dctx->dictContentEndForFuzzing == NULL) return 0;
  972. /* Dictionary is our prefix. */
  973. if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
  974. /* Dictionary is not our ext-dict. */
  975. if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
  976. /* Dictionary is not within our window size. */
  977. if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
  978. /* Dictionary is active. */
  979. return 1;
  980. }
  981. MEM_STATIC void ZSTD_assertValidSequence(
  982. ZSTD_DCtx const* dctx,
  983. BYTE const* op, BYTE const* oend,
  984. seq_t const seq,
  985. BYTE const* prefixStart, BYTE const* virtualStart)
  986. {
  987. #if DEBUGLEVEL >= 1
  988. size_t const windowSize = dctx->fParams.windowSize;
  989. size_t const sequenceSize = seq.litLength + seq.matchLength;
  990. BYTE const* const oLitEnd = op + seq.litLength;
  991. DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
  992. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  993. assert(op <= oend);
  994. assert((size_t)(oend - op) >= sequenceSize);
  995. assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX);
  996. if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
  997. size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
  998. /* Offset must be within the dictionary. */
  999. assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
  1000. assert(seq.offset <= windowSize + dictSize);
  1001. } else {
  1002. /* Offset must be within our window. */
  1003. assert(seq.offset <= windowSize);
  1004. }
  1005. #else
  1006. (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
  1007. #endif
  1008. }
  1009. #endif
  1010. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1011. FORCE_INLINE_TEMPLATE size_t
  1012. DONT_VECTORIZE
  1013. ZSTD_decompressSequences_body( ZSTD_DCtx* dctx,
  1014. void* dst, size_t maxDstSize,
  1015. const void* seqStart, size_t seqSize, int nbSeq,
  1016. const ZSTD_longOffset_e isLongOffset,
  1017. const int frame)
  1018. {
  1019. const BYTE* ip = (const BYTE*)seqStart;
  1020. const BYTE* const iend = ip + seqSize;
  1021. BYTE* const ostart = (BYTE*)dst;
  1022. BYTE* const oend = ostart + maxDstSize;
  1023. BYTE* op = ostart;
  1024. const BYTE* litPtr = dctx->litPtr;
  1025. const BYTE* const litEnd = litPtr + dctx->litSize;
  1026. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1027. const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
  1028. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1029. DEBUGLOG(5, "ZSTD_decompressSequences_body");
  1030. (void)frame;
  1031. /* Regen sequences */
  1032. if (nbSeq) {
  1033. seqState_t seqState;
  1034. size_t error = 0;
  1035. dctx->fseEntropy = 1;
  1036. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1037. RETURN_ERROR_IF(
  1038. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1039. corruption_detected, "");
  1040. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1041. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1042. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1043. assert(dst != NULL);
  1044. ZSTD_STATIC_ASSERT(
  1045. BIT_DStream_unfinished < BIT_DStream_completed &&
  1046. BIT_DStream_endOfBuffer < BIT_DStream_completed &&
  1047. BIT_DStream_completed < BIT_DStream_overflow);
  1048. #if defined(__x86_64__)
  1049. /* Align the decompression loop to 32 + 16 bytes.
  1050. *
  1051. * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
  1052. * speed swings based on the alignment of the decompression loop. This
  1053. * performance swing is caused by parts of the decompression loop falling
  1054. * out of the DSB. The entire decompression loop should fit in the DSB,
  1055. * when it can't we get much worse performance. You can measure if you've
  1056. * hit the good case or the bad case with this perf command for some
  1057. * compressed file test.zst:
  1058. *
  1059. * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
  1060. * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
  1061. *
  1062. * If you see most cycles served out of the MITE you've hit the bad case.
  1063. * If you see most cycles served out of the DSB you've hit the good case.
  1064. * If it is pretty even then you may be in an okay case.
  1065. *
  1066. * I've been able to reproduce this issue on the following CPUs:
  1067. * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
  1068. * Use Instruments->Counters to get DSB/MITE cycles.
  1069. * I never got performance swings, but I was able to
  1070. * go from the good case of mostly DSB to half of the
  1071. * cycles served from MITE.
  1072. * - Coffeelake: Intel i9-9900k
  1073. *
  1074. * I haven't been able to reproduce the instability or DSB misses on any
  1075. * of the following CPUS:
  1076. * - Haswell
  1077. * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
  1078. * - Skylake
  1079. *
  1080. * If you are seeing performance stability this script can help test.
  1081. * It tests on 4 commits in zstd where I saw performance change.
  1082. *
  1083. * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
  1084. */
  1085. __asm__(".p2align 5");
  1086. __asm__("nop");
  1087. __asm__(".p2align 4");
  1088. #endif
  1089. for ( ; ; ) {
  1090. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_noPrefetch);
  1091. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
  1092. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1093. assert(!ZSTD_isError(oneSeqSize));
  1094. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  1095. #endif
  1096. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  1097. BIT_reloadDStream(&(seqState.DStream));
  1098. op += oneSeqSize;
  1099. /* gcc and clang both don't like early returns in this loop.
  1100. * Instead break and check for an error at the end of the loop.
  1101. */
  1102. if (UNLIKELY(ZSTD_isError(oneSeqSize))) {
  1103. error = oneSeqSize;
  1104. break;
  1105. }
  1106. if (UNLIKELY(!--nbSeq)) break;
  1107. }
  1108. /* check if reached exact end */
  1109. DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
  1110. if (ZSTD_isError(error)) return error;
  1111. RETURN_ERROR_IF(nbSeq, corruption_detected, "");
  1112. RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
  1113. /* save reps for next block */
  1114. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1115. }
  1116. /* last literal segment */
  1117. { size_t const lastLLSize = litEnd - litPtr;
  1118. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1119. if (op != NULL) {
  1120. ZSTD_memcpy(op, litPtr, lastLLSize);
  1121. op += lastLLSize;
  1122. }
  1123. }
  1124. return op-ostart;
  1125. }
  1126. static size_t
  1127. ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
  1128. void* dst, size_t maxDstSize,
  1129. const void* seqStart, size_t seqSize, int nbSeq,
  1130. const ZSTD_longOffset_e isLongOffset,
  1131. const int frame)
  1132. {
  1133. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1134. }
  1135. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1136. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1137. FORCE_INLINE_TEMPLATE size_t
  1138. ZSTD_decompressSequencesLong_body(
  1139. ZSTD_DCtx* dctx,
  1140. void* dst, size_t maxDstSize,
  1141. const void* seqStart, size_t seqSize, int nbSeq,
  1142. const ZSTD_longOffset_e isLongOffset,
  1143. const int frame)
  1144. {
  1145. const BYTE* ip = (const BYTE*)seqStart;
  1146. const BYTE* const iend = ip + seqSize;
  1147. BYTE* const ostart = (BYTE*)dst;
  1148. BYTE* const oend = ostart + maxDstSize;
  1149. BYTE* op = ostart;
  1150. const BYTE* litPtr = dctx->litPtr;
  1151. const BYTE* const litEnd = litPtr + dctx->litSize;
  1152. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1153. const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
  1154. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1155. (void)frame;
  1156. /* Regen sequences */
  1157. if (nbSeq) {
  1158. #define STORED_SEQS 4
  1159. #define STORED_SEQS_MASK (STORED_SEQS-1)
  1160. #define ADVANCED_SEQS 4
  1161. seq_t sequences[STORED_SEQS];
  1162. int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
  1163. seqState_t seqState;
  1164. int seqNb;
  1165. dctx->fseEntropy = 1;
  1166. { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1167. seqState.prefixStart = prefixStart;
  1168. seqState.pos = (size_t)(op-prefixStart);
  1169. seqState.dictEnd = dictEnd;
  1170. assert(dst != NULL);
  1171. assert(iend >= ip);
  1172. RETURN_ERROR_IF(
  1173. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1174. corruption_detected, "");
  1175. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1176. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1177. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1178. /* prepare in advance */
  1179. for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
  1180. sequences[seqNb] = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_prefetch);
  1181. PREFETCH_L1(sequences[seqNb].match); PREFETCH_L1(sequences[seqNb].match + sequences[seqNb].matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
  1182. }
  1183. RETURN_ERROR_IF(seqNb<seqAdvance, corruption_detected, "");
  1184. /* decode and decompress */
  1185. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) {
  1186. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_prefetch);
  1187. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
  1188. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1189. assert(!ZSTD_isError(oneSeqSize));
  1190. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
  1191. #endif
  1192. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1193. PREFETCH_L1(sequence.match); PREFETCH_L1(sequence.match + sequence.matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
  1194. sequences[seqNb & STORED_SEQS_MASK] = sequence;
  1195. op += oneSeqSize;
  1196. }
  1197. RETURN_ERROR_IF(seqNb<nbSeq, corruption_detected, "");
  1198. /* finish queue */
  1199. seqNb -= seqAdvance;
  1200. for ( ; seqNb<nbSeq ; seqNb++) {
  1201. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
  1202. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1203. assert(!ZSTD_isError(oneSeqSize));
  1204. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
  1205. #endif
  1206. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1207. op += oneSeqSize;
  1208. }
  1209. /* save reps for next block */
  1210. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1211. }
  1212. /* last literal segment */
  1213. { size_t const lastLLSize = litEnd - litPtr;
  1214. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1215. if (op != NULL) {
  1216. ZSTD_memcpy(op, litPtr, lastLLSize);
  1217. op += lastLLSize;
  1218. }
  1219. }
  1220. return op-ostart;
  1221. }
  1222. static size_t
  1223. ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
  1224. void* dst, size_t maxDstSize,
  1225. const void* seqStart, size_t seqSize, int nbSeq,
  1226. const ZSTD_longOffset_e isLongOffset,
  1227. const int frame)
  1228. {
  1229. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1230. }
  1231. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1232. #if DYNAMIC_BMI2
  1233. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1234. static TARGET_ATTRIBUTE("bmi2") size_t
  1235. DONT_VECTORIZE
  1236. ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
  1237. void* dst, size_t maxDstSize,
  1238. const void* seqStart, size_t seqSize, int nbSeq,
  1239. const ZSTD_longOffset_e isLongOffset,
  1240. const int frame)
  1241. {
  1242. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1243. }
  1244. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1245. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1246. static TARGET_ATTRIBUTE("bmi2") size_t
  1247. ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
  1248. void* dst, size_t maxDstSize,
  1249. const void* seqStart, size_t seqSize, int nbSeq,
  1250. const ZSTD_longOffset_e isLongOffset,
  1251. const int frame)
  1252. {
  1253. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1254. }
  1255. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1256. #endif /* DYNAMIC_BMI2 */
  1257. typedef size_t (*ZSTD_decompressSequences_t)(
  1258. ZSTD_DCtx* dctx,
  1259. void* dst, size_t maxDstSize,
  1260. const void* seqStart, size_t seqSize, int nbSeq,
  1261. const ZSTD_longOffset_e isLongOffset,
  1262. const int frame);
  1263. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1264. static size_t
  1265. ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
  1266. const void* seqStart, size_t seqSize, int nbSeq,
  1267. const ZSTD_longOffset_e isLongOffset,
  1268. const int frame)
  1269. {
  1270. DEBUGLOG(5, "ZSTD_decompressSequences");
  1271. #if DYNAMIC_BMI2
  1272. if (dctx->bmi2) {
  1273. return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1274. }
  1275. #endif
  1276. return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1277. }
  1278. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1279. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1280. /* ZSTD_decompressSequencesLong() :
  1281. * decompression function triggered when a minimum share of offsets is considered "long",
  1282. * aka out of cache.
  1283. * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
  1284. * This function will try to mitigate main memory latency through the use of prefetching */
  1285. static size_t
  1286. ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
  1287. void* dst, size_t maxDstSize,
  1288. const void* seqStart, size_t seqSize, int nbSeq,
  1289. const ZSTD_longOffset_e isLongOffset,
  1290. const int frame)
  1291. {
  1292. DEBUGLOG(5, "ZSTD_decompressSequencesLong");
  1293. #if DYNAMIC_BMI2
  1294. if (dctx->bmi2) {
  1295. return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1296. }
  1297. #endif
  1298. return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1299. }
  1300. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1301. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1302. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1303. /* ZSTD_getLongOffsetsShare() :
  1304. * condition : offTable must be valid
  1305. * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
  1306. * compared to maximum possible of (1<<OffFSELog) */
  1307. static unsigned
  1308. ZSTD_getLongOffsetsShare(const ZSTD_seqSymbol* offTable)
  1309. {
  1310. const void* ptr = offTable;
  1311. U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
  1312. const ZSTD_seqSymbol* table = offTable + 1;
  1313. U32 const max = 1 << tableLog;
  1314. U32 u, total = 0;
  1315. DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
  1316. assert(max <= (1 << OffFSELog)); /* max not too large */
  1317. for (u=0; u<max; u++) {
  1318. if (table[u].nbAdditionalBits > 22) total += 1;
  1319. }
  1320. assert(tableLog <= OffFSELog);
  1321. total <<= (OffFSELog - tableLog); /* scale to OffFSELog */
  1322. return total;
  1323. }
  1324. #endif
  1325. size_t
  1326. ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
  1327. void* dst, size_t dstCapacity,
  1328. const void* src, size_t srcSize, const int frame)
  1329. { /* blockType == blockCompressed */
  1330. const BYTE* ip = (const BYTE*)src;
  1331. /* isLongOffset must be true if there are long offsets.
  1332. * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
  1333. * We don't expect that to be the case in 64-bit mode.
  1334. * In block mode, window size is not known, so we have to be conservative.
  1335. * (note: but it could be evaluated from current-lowLimit)
  1336. */
  1337. ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN))));
  1338. DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
  1339. RETURN_ERROR_IF(srcSize >= ZSTD_BLOCKSIZE_MAX, srcSize_wrong, "");
  1340. /* Decode literals section */
  1341. { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
  1342. DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
  1343. if (ZSTD_isError(litCSize)) return litCSize;
  1344. ip += litCSize;
  1345. srcSize -= litCSize;
  1346. }
  1347. /* Build Decoding Tables */
  1348. {
  1349. /* These macros control at build-time which decompressor implementation
  1350. * we use. If neither is defined, we do some inspection and dispatch at
  1351. * runtime.
  1352. */
  1353. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1354. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1355. int usePrefetchDecoder = dctx->ddictIsCold;
  1356. #endif
  1357. int nbSeq;
  1358. size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
  1359. if (ZSTD_isError(seqHSize)) return seqHSize;
  1360. ip += seqHSize;
  1361. srcSize -= seqHSize;
  1362. RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
  1363. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1364. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1365. if ( !usePrefetchDecoder
  1366. && (!frame || (dctx->fParams.windowSize > (1<<24)))
  1367. && (nbSeq>ADVANCED_SEQS) ) { /* could probably use a larger nbSeq limit */
  1368. U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr);
  1369. U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
  1370. usePrefetchDecoder = (shareLongOffsets >= minShare);
  1371. }
  1372. #endif
  1373. dctx->ddictIsCold = 0;
  1374. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1375. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1376. if (usePrefetchDecoder)
  1377. #endif
  1378. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1379. return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1380. #endif
  1381. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1382. /* else */
  1383. return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1384. #endif
  1385. }
  1386. }
  1387. void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
  1388. {
  1389. if (dst != dctx->previousDstEnd && dstSize > 0) { /* not contiguous */
  1390. dctx->dictEnd = dctx->previousDstEnd;
  1391. dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
  1392. dctx->prefixStart = dst;
  1393. dctx->previousDstEnd = dst;
  1394. }
  1395. }
  1396. size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
  1397. void* dst, size_t dstCapacity,
  1398. const void* src, size_t srcSize)
  1399. {
  1400. size_t dSize;
  1401. ZSTD_checkContinuity(dctx, dst, dstCapacity);
  1402. dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
  1403. dctx->previousDstEnd = (char*)dst + dSize;
  1404. return dSize;
  1405. }