zstd_decompress_block.c 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. /*
  2. * Copyright (c) 2016-2020, 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 <string.h> /* memcpy, memmove, 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) { 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. 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. memcpy(dctx->litBuffer, istart+lhSize, litSize);
  174. dctx->litPtr = dctx->litBuffer;
  175. dctx->litSize = litSize;
  176. 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. 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/master/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. void
  335. ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
  336. const short* normalizedCounter, unsigned maxSymbolValue,
  337. const U32* baseValue, const U32* nbAdditionalBits,
  338. unsigned tableLog)
  339. {
  340. ZSTD_seqSymbol* const tableDecode = dt+1;
  341. U16 symbolNext[MaxSeq+1];
  342. U32 const maxSV1 = maxSymbolValue + 1;
  343. U32 const tableSize = 1 << tableLog;
  344. U32 highThreshold = tableSize-1;
  345. /* Sanity Checks */
  346. assert(maxSymbolValue <= MaxSeq);
  347. assert(tableLog <= MaxFSELog);
  348. /* Init, lay down lowprob symbols */
  349. { ZSTD_seqSymbol_header DTableH;
  350. DTableH.tableLog = tableLog;
  351. DTableH.fastMode = 1;
  352. { S16 const largeLimit= (S16)(1 << (tableLog-1));
  353. U32 s;
  354. for (s=0; s<maxSV1; s++) {
  355. if (normalizedCounter[s]==-1) {
  356. tableDecode[highThreshold--].baseValue = s;
  357. symbolNext[s] = 1;
  358. } else {
  359. if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
  360. assert(normalizedCounter[s]>=0);
  361. symbolNext[s] = (U16)normalizedCounter[s];
  362. } } }
  363. memcpy(dt, &DTableH, sizeof(DTableH));
  364. }
  365. /* Spread symbols */
  366. { U32 const tableMask = tableSize-1;
  367. U32 const step = FSE_TABLESTEP(tableSize);
  368. U32 s, position = 0;
  369. for (s=0; s<maxSV1; s++) {
  370. int i;
  371. for (i=0; i<normalizedCounter[s]; i++) {
  372. tableDecode[position].baseValue = s;
  373. position = (position + step) & tableMask;
  374. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  375. } }
  376. assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  377. }
  378. /* Build Decoding table */
  379. { U32 u;
  380. for (u=0; u<tableSize; u++) {
  381. U32 const symbol = tableDecode[u].baseValue;
  382. U32 const nextState = symbolNext[symbol]++;
  383. tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
  384. tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
  385. assert(nbAdditionalBits[symbol] < 255);
  386. tableDecode[u].nbAdditionalBits = (BYTE)nbAdditionalBits[symbol];
  387. tableDecode[u].baseValue = baseValue[symbol];
  388. } }
  389. }
  390. /*! ZSTD_buildSeqTable() :
  391. * @return : nb bytes read from src,
  392. * or an error code if it fails */
  393. static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
  394. symbolEncodingType_e type, unsigned max, U32 maxLog,
  395. const void* src, size_t srcSize,
  396. const U32* baseValue, const U32* nbAdditionalBits,
  397. const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
  398. int ddictIsCold, int nbSeq)
  399. {
  400. switch(type)
  401. {
  402. case set_rle :
  403. RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
  404. RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
  405. { U32 const symbol = *(const BYTE*)src;
  406. U32 const baseline = baseValue[symbol];
  407. U32 const nbBits = nbAdditionalBits[symbol];
  408. ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
  409. }
  410. *DTablePtr = DTableSpace;
  411. return 1;
  412. case set_basic :
  413. *DTablePtr = defaultTable;
  414. return 0;
  415. case set_repeat:
  416. RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
  417. /* prefetch FSE table if used */
  418. if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
  419. const void* const pStart = *DTablePtr;
  420. size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
  421. PREFETCH_AREA(pStart, pSize);
  422. }
  423. return 0;
  424. case set_compressed :
  425. { unsigned tableLog;
  426. S16 norm[MaxSeq+1];
  427. size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
  428. RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
  429. RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
  430. ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog);
  431. *DTablePtr = DTableSpace;
  432. return headerSize;
  433. }
  434. default :
  435. assert(0);
  436. RETURN_ERROR(GENERIC, "impossible");
  437. }
  438. }
  439. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
  440. const void* src, size_t srcSize)
  441. {
  442. const BYTE* const istart = (const BYTE* const)src;
  443. const BYTE* const iend = istart + srcSize;
  444. const BYTE* ip = istart;
  445. int nbSeq;
  446. DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
  447. /* check */
  448. RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");
  449. /* SeqHead */
  450. nbSeq = *ip++;
  451. if (!nbSeq) {
  452. *nbSeqPtr=0;
  453. RETURN_ERROR_IF(srcSize != 1, srcSize_wrong, "");
  454. return 1;
  455. }
  456. if (nbSeq > 0x7F) {
  457. if (nbSeq == 0xFF) {
  458. RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
  459. nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2;
  460. } else {
  461. RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
  462. nbSeq = ((nbSeq-0x80)<<8) + *ip++;
  463. }
  464. }
  465. *nbSeqPtr = nbSeq;
  466. /* FSE table descriptors */
  467. RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
  468. { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
  469. symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
  470. symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
  471. ip++;
  472. /* Build DTables */
  473. { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
  474. LLtype, MaxLL, LLFSELog,
  475. ip, iend-ip,
  476. LL_base, LL_bits,
  477. LL_defaultDTable, dctx->fseEntropy,
  478. dctx->ddictIsCold, nbSeq);
  479. RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
  480. ip += llhSize;
  481. }
  482. { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
  483. OFtype, MaxOff, OffFSELog,
  484. ip, iend-ip,
  485. OF_base, OF_bits,
  486. OF_defaultDTable, dctx->fseEntropy,
  487. dctx->ddictIsCold, nbSeq);
  488. RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
  489. ip += ofhSize;
  490. }
  491. { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
  492. MLtype, MaxML, MLFSELog,
  493. ip, iend-ip,
  494. ML_base, ML_bits,
  495. ML_defaultDTable, dctx->fseEntropy,
  496. dctx->ddictIsCold, nbSeq);
  497. RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");
  498. ip += mlhSize;
  499. }
  500. }
  501. return ip-istart;
  502. }
  503. typedef struct {
  504. size_t litLength;
  505. size_t matchLength;
  506. size_t offset;
  507. const BYTE* match;
  508. } seq_t;
  509. typedef struct {
  510. size_t state;
  511. const ZSTD_seqSymbol* table;
  512. } ZSTD_fseState;
  513. typedef struct {
  514. BIT_DStream_t DStream;
  515. ZSTD_fseState stateLL;
  516. ZSTD_fseState stateOffb;
  517. ZSTD_fseState stateML;
  518. size_t prevOffset[ZSTD_REP_NUM];
  519. const BYTE* prefixStart;
  520. const BYTE* dictEnd;
  521. size_t pos;
  522. } seqState_t;
  523. /*! ZSTD_overlapCopy8() :
  524. * Copies 8 bytes from ip to op and updates op and ip where ip <= op.
  525. * If the offset is < 8 then the offset is spread to at least 8 bytes.
  526. *
  527. * Precondition: *ip <= *op
  528. * Postcondition: *op - *op >= 8
  529. */
  530. HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) {
  531. assert(*ip <= *op);
  532. if (offset < 8) {
  533. /* close range match, overlap */
  534. static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  535. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
  536. int const sub2 = dec64table[offset];
  537. (*op)[0] = (*ip)[0];
  538. (*op)[1] = (*ip)[1];
  539. (*op)[2] = (*ip)[2];
  540. (*op)[3] = (*ip)[3];
  541. *ip += dec32table[offset];
  542. ZSTD_copy4(*op+4, *ip);
  543. *ip -= sub2;
  544. } else {
  545. ZSTD_copy8(*op, *ip);
  546. }
  547. *ip += 8;
  548. *op += 8;
  549. assert(*op - *ip >= 8);
  550. }
  551. /*! ZSTD_safecopy() :
  552. * Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer
  553. * and write up to 16 bytes past oend_w (op >= oend_w is allowed).
  554. * This function is only called in the uncommon case where the sequence is near the end of the block. It
  555. * should be fast for a single long sequence, but can be slow for several short sequences.
  556. *
  557. * @param ovtype controls the overlap detection
  558. * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  559. * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
  560. * The src buffer must be before the dst buffer.
  561. */
  562. static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {
  563. ptrdiff_t const diff = op - ip;
  564. BYTE* const oend = op + length;
  565. assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
  566. (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));
  567. if (length < 8) {
  568. /* Handle short lengths. */
  569. while (op < oend) *op++ = *ip++;
  570. return;
  571. }
  572. if (ovtype == ZSTD_overlap_src_before_dst) {
  573. /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
  574. assert(length >= 8);
  575. ZSTD_overlapCopy8(&op, &ip, diff);
  576. assert(op - ip >= 8);
  577. assert(op <= oend);
  578. }
  579. if (oend <= oend_w) {
  580. /* No risk of overwrite. */
  581. ZSTD_wildcopy(op, ip, length, ovtype);
  582. return;
  583. }
  584. if (op <= oend_w) {
  585. /* Wildcopy until we get close to the end. */
  586. assert(oend > oend_w);
  587. ZSTD_wildcopy(op, ip, oend_w - op, ovtype);
  588. ip += oend_w - op;
  589. op = oend_w;
  590. }
  591. /* Handle the leftovers. */
  592. while (op < oend) *op++ = *ip++;
  593. }
  594. /* ZSTD_execSequenceEnd():
  595. * This version handles cases that are near the end of the output buffer. It requires
  596. * more careful checks to make sure there is no overflow. By separating out these hard
  597. * and unlikely cases, we can speed up the common cases.
  598. *
  599. * NOTE: This function needs to be fast for a single long sequence, but doesn't need
  600. * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
  601. */
  602. FORCE_NOINLINE
  603. size_t ZSTD_execSequenceEnd(BYTE* op,
  604. BYTE* const oend, seq_t sequence,
  605. const BYTE** litPtr, const BYTE* const litLimit,
  606. const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
  607. {
  608. BYTE* const oLitEnd = op + sequence.litLength;
  609. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  610. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  611. const BYTE* match = oLitEnd - sequence.offset;
  612. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
  613. /* bounds checks : careful of address space overflow in 32-bit mode */
  614. RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
  615. RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
  616. assert(op < op + sequenceLength);
  617. assert(oLitEnd < op + sequenceLength);
  618. /* copy literals */
  619. ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
  620. op = oLitEnd;
  621. *litPtr = iLitEnd;
  622. /* copy Match */
  623. if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
  624. /* offset beyond prefix */
  625. RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
  626. match = dictEnd - (prefixStart-match);
  627. if (match + sequence.matchLength <= dictEnd) {
  628. memmove(oLitEnd, match, sequence.matchLength);
  629. return sequenceLength;
  630. }
  631. /* span extDict & currentPrefixSegment */
  632. { size_t const length1 = dictEnd - match;
  633. memmove(oLitEnd, match, length1);
  634. op = oLitEnd + length1;
  635. sequence.matchLength -= length1;
  636. match = prefixStart;
  637. } }
  638. ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
  639. return sequenceLength;
  640. }
  641. HINT_INLINE
  642. size_t ZSTD_execSequence(BYTE* op,
  643. BYTE* const oend, seq_t sequence,
  644. const BYTE** litPtr, const BYTE* const litLimit,
  645. const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
  646. {
  647. BYTE* const oLitEnd = op + sequence.litLength;
  648. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  649. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  650. BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */
  651. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  652. const BYTE* match = oLitEnd - sequence.offset;
  653. assert(op != NULL /* Precondition */);
  654. assert(oend_w < oend /* No underflow */);
  655. /* Handle edge cases in a slow path:
  656. * - Read beyond end of literals
  657. * - Match end is within WILDCOPY_OVERLIMIT of oend
  658. * - 32-bit mode and the match length overflows
  659. */
  660. if (UNLIKELY(
  661. iLitEnd > litLimit ||
  662. oMatchEnd > oend_w ||
  663. (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
  664. return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
  665. /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
  666. assert(op <= oLitEnd /* No overflow */);
  667. assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
  668. assert(oMatchEnd <= oend /* No underflow */);
  669. assert(iLitEnd <= litLimit /* Literal length is in bounds */);
  670. assert(oLitEnd <= oend_w /* Can wildcopy literals */);
  671. assert(oMatchEnd <= oend_w /* Can wildcopy matches */);
  672. /* Copy Literals:
  673. * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
  674. * We likely don't need the full 32-byte wildcopy.
  675. */
  676. assert(WILDCOPY_OVERLENGTH >= 16);
  677. ZSTD_copy16(op, (*litPtr));
  678. if (UNLIKELY(sequence.litLength > 16)) {
  679. ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
  680. }
  681. op = oLitEnd;
  682. *litPtr = iLitEnd; /* update for next sequence */
  683. /* Copy Match */
  684. if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
  685. /* offset beyond prefix -> go into extDict */
  686. RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
  687. match = dictEnd + (match - prefixStart);
  688. if (match + sequence.matchLength <= dictEnd) {
  689. memmove(oLitEnd, match, sequence.matchLength);
  690. return sequenceLength;
  691. }
  692. /* span extDict & currentPrefixSegment */
  693. { size_t const length1 = dictEnd - match;
  694. memmove(oLitEnd, match, length1);
  695. op = oLitEnd + length1;
  696. sequence.matchLength -= length1;
  697. match = prefixStart;
  698. } }
  699. /* Match within prefix of 1 or more bytes */
  700. assert(op <= oMatchEnd);
  701. assert(oMatchEnd <= oend_w);
  702. assert(match >= prefixStart);
  703. assert(sequence.matchLength >= 1);
  704. /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
  705. * without overlap checking.
  706. */
  707. if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
  708. /* We bet on a full wildcopy for matches, since we expect matches to be
  709. * longer than literals (in general). In silesia, ~10% of matches are longer
  710. * than 16 bytes.
  711. */
  712. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
  713. return sequenceLength;
  714. }
  715. assert(sequence.offset < WILDCOPY_VECLEN);
  716. /* Copy 8 bytes and spread the offset to be >= 8. */
  717. ZSTD_overlapCopy8(&op, &match, sequence.offset);
  718. /* If the match length is > 8 bytes, then continue with the wildcopy. */
  719. if (sequence.matchLength > 8) {
  720. assert(op < oMatchEnd);
  721. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst);
  722. }
  723. return sequenceLength;
  724. }
  725. static void
  726. ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
  727. {
  728. const void* ptr = dt;
  729. const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
  730. DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
  731. DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
  732. (U32)DStatePtr->state, DTableH->tableLog);
  733. BIT_reloadDStream(bitD);
  734. DStatePtr->table = dt + 1;
  735. }
  736. FORCE_INLINE_TEMPLATE void
  737. ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD)
  738. {
  739. ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state];
  740. U32 const nbBits = DInfo.nbBits;
  741. size_t const lowBits = BIT_readBits(bitD, nbBits);
  742. DStatePtr->state = DInfo.nextState + lowBits;
  743. }
  744. FORCE_INLINE_TEMPLATE void
  745. ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, ZSTD_seqSymbol const DInfo)
  746. {
  747. U32 const nbBits = DInfo.nbBits;
  748. size_t const lowBits = BIT_readBits(bitD, nbBits);
  749. DStatePtr->state = DInfo.nextState + lowBits;
  750. }
  751. /* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
  752. * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1)
  753. * bits before reloading. This value is the maximum number of bytes we read
  754. * after reloading when we are decoding long offsets.
  755. */
  756. #define LONG_OFFSETS_MAX_EXTRA_BITS_32 \
  757. (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \
  758. ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \
  759. : 0)
  760. typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
  761. typedef enum { ZSTD_p_noPrefetch=0, ZSTD_p_prefetch=1 } ZSTD_prefetch_e;
  762. FORCE_INLINE_TEMPLATE seq_t
  763. ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const ZSTD_prefetch_e prefetch)
  764. {
  765. seq_t seq;
  766. ZSTD_seqSymbol const llDInfo = seqState->stateLL.table[seqState->stateLL.state];
  767. ZSTD_seqSymbol const mlDInfo = seqState->stateML.table[seqState->stateML.state];
  768. ZSTD_seqSymbol const ofDInfo = seqState->stateOffb.table[seqState->stateOffb.state];
  769. U32 const llBase = llDInfo.baseValue;
  770. U32 const mlBase = mlDInfo.baseValue;
  771. U32 const ofBase = ofDInfo.baseValue;
  772. BYTE const llBits = llDInfo.nbAdditionalBits;
  773. BYTE const mlBits = mlDInfo.nbAdditionalBits;
  774. BYTE const ofBits = ofDInfo.nbAdditionalBits;
  775. BYTE const totalBits = llBits+mlBits+ofBits;
  776. /* sequence */
  777. { size_t offset;
  778. if (ofBits > 1) {
  779. ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
  780. ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
  781. assert(ofBits <= MaxOff);
  782. if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
  783. U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed);
  784. offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
  785. BIT_reloadDStream(&seqState->DStream);
  786. if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
  787. assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32); /* to avoid another reload */
  788. } else {
  789. offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
  790. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
  791. }
  792. seqState->prevOffset[2] = seqState->prevOffset[1];
  793. seqState->prevOffset[1] = seqState->prevOffset[0];
  794. seqState->prevOffset[0] = offset;
  795. } else {
  796. U32 const ll0 = (llBase == 0);
  797. if (LIKELY((ofBits == 0))) {
  798. if (LIKELY(!ll0))
  799. offset = seqState->prevOffset[0];
  800. else {
  801. offset = seqState->prevOffset[1];
  802. seqState->prevOffset[1] = seqState->prevOffset[0];
  803. seqState->prevOffset[0] = offset;
  804. }
  805. } else {
  806. offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
  807. { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
  808. temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
  809. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  810. seqState->prevOffset[1] = seqState->prevOffset[0];
  811. seqState->prevOffset[0] = offset = temp;
  812. } } }
  813. seq.offset = offset;
  814. }
  815. seq.matchLength = mlBase;
  816. if (mlBits > 0)
  817. seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);
  818. if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
  819. BIT_reloadDStream(&seqState->DStream);
  820. if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
  821. BIT_reloadDStream(&seqState->DStream);
  822. /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
  823. ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
  824. seq.litLength = llBase;
  825. if (llBits > 0)
  826. seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);
  827. if (MEM_32bits())
  828. BIT_reloadDStream(&seqState->DStream);
  829. DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
  830. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  831. if (prefetch == ZSTD_p_prefetch) {
  832. size_t const pos = seqState->pos + seq.litLength;
  833. const BYTE* const matchBase = (seq.offset > pos) ? seqState->dictEnd : seqState->prefixStart;
  834. 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.
  835. * No consequence though : no memory access will occur, offset is only used for prefetching */
  836. seqState->pos = pos + seq.matchLength;
  837. }
  838. /* ANS state update
  839. * gcc-9.0.0 does 2.5% worse with ZSTD_updateFseStateWithDInfo().
  840. * clang-9.2.0 does 7% worse with ZSTD_updateFseState().
  841. * Naturally it seems like ZSTD_updateFseStateWithDInfo() should be the
  842. * better option, so it is the default for other compilers. But, if you
  843. * measure that it is worse, please put up a pull request.
  844. */
  845. {
  846. #if defined(__GNUC__) && !defined(__clang__)
  847. const int kUseUpdateFseState = 1;
  848. #else
  849. const int kUseUpdateFseState = 0;
  850. #endif
  851. if (kUseUpdateFseState) {
  852. ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
  853. ZSTD_updateFseState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
  854. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  855. ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
  856. } else {
  857. ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llDInfo); /* <= 9 bits */
  858. ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlDInfo); /* <= 9 bits */
  859. if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
  860. ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofDInfo); /* <= 8 bits */
  861. }
  862. }
  863. return seq;
  864. }
  865. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  866. static int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
  867. {
  868. size_t const windowSize = dctx->fParams.windowSize;
  869. /* No dictionary used. */
  870. if (dctx->dictContentEndForFuzzing == NULL) return 0;
  871. /* Dictionary is our prefix. */
  872. if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
  873. /* Dictionary is not our ext-dict. */
  874. if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
  875. /* Dictionary is not within our window size. */
  876. if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
  877. /* Dictionary is active. */
  878. return 1;
  879. }
  880. MEM_STATIC void ZSTD_assertValidSequence(
  881. ZSTD_DCtx const* dctx,
  882. BYTE const* op, BYTE const* oend,
  883. seq_t const seq,
  884. BYTE const* prefixStart, BYTE const* virtualStart)
  885. {
  886. size_t const windowSize = dctx->fParams.windowSize;
  887. size_t const sequenceSize = seq.litLength + seq.matchLength;
  888. BYTE const* const oLitEnd = op + seq.litLength;
  889. DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
  890. (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
  891. assert(op <= oend);
  892. assert((size_t)(oend - op) >= sequenceSize);
  893. assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX);
  894. if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
  895. size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
  896. /* Offset must be within the dictionary. */
  897. assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
  898. assert(seq.offset <= windowSize + dictSize);
  899. } else {
  900. /* Offset must be within our window. */
  901. assert(seq.offset <= windowSize);
  902. }
  903. }
  904. #endif
  905. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  906. FORCE_INLINE_TEMPLATE size_t
  907. DONT_VECTORIZE
  908. ZSTD_decompressSequences_body( ZSTD_DCtx* dctx,
  909. void* dst, size_t maxDstSize,
  910. const void* seqStart, size_t seqSize, int nbSeq,
  911. const ZSTD_longOffset_e isLongOffset,
  912. const int frame)
  913. {
  914. const BYTE* ip = (const BYTE*)seqStart;
  915. const BYTE* const iend = ip + seqSize;
  916. BYTE* const ostart = (BYTE* const)dst;
  917. BYTE* const oend = ostart + maxDstSize;
  918. BYTE* op = ostart;
  919. const BYTE* litPtr = dctx->litPtr;
  920. const BYTE* const litEnd = litPtr + dctx->litSize;
  921. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  922. const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
  923. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  924. DEBUGLOG(5, "ZSTD_decompressSequences_body");
  925. (void)frame;
  926. /* Regen sequences */
  927. if (nbSeq) {
  928. seqState_t seqState;
  929. size_t error = 0;
  930. dctx->fseEntropy = 1;
  931. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  932. RETURN_ERROR_IF(
  933. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  934. corruption_detected, "");
  935. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  936. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  937. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  938. assert(dst != NULL);
  939. ZSTD_STATIC_ASSERT(
  940. BIT_DStream_unfinished < BIT_DStream_completed &&
  941. BIT_DStream_endOfBuffer < BIT_DStream_completed &&
  942. BIT_DStream_completed < BIT_DStream_overflow);
  943. #if defined(__GNUC__) && defined(__x86_64__)
  944. /* Align the decompression loop to 32 + 16 bytes.
  945. *
  946. * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
  947. * speed swings based on the alignment of the decompression loop. This
  948. * performance swing is caused by parts of the decompression loop falling
  949. * out of the DSB. The entire decompression loop should fit in the DSB,
  950. * when it can't we get much worse performance. You can measure if you've
  951. * hit the good case or the bad case with this perf command for some
  952. * compressed file test.zst:
  953. *
  954. * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
  955. * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
  956. *
  957. * If you see most cycles served out of the MITE you've hit the bad case.
  958. * If you see most cycles served out of the DSB you've hit the good case.
  959. * If it is pretty even then you may be in an okay case.
  960. *
  961. * I've been able to reproduce this issue on the following CPUs:
  962. * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
  963. * Use Instruments->Counters to get DSB/MITE cycles.
  964. * I never got performance swings, but I was able to
  965. * go from the good case of mostly DSB to half of the
  966. * cycles served from MITE.
  967. * - Coffeelake: Intel i9-9900k
  968. *
  969. * I haven't been able to reproduce the instability or DSB misses on any
  970. * of the following CPUS:
  971. * - Haswell
  972. * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
  973. * - Skylake
  974. *
  975. * If you are seeing performance stability this script can help test.
  976. * It tests on 4 commits in zstd where I saw performance change.
  977. *
  978. * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
  979. */
  980. __asm__(".p2align 5");
  981. __asm__("nop");
  982. __asm__(".p2align 4");
  983. #endif
  984. for ( ; ; ) {
  985. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_noPrefetch);
  986. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
  987. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  988. assert(!ZSTD_isError(oneSeqSize));
  989. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
  990. #endif
  991. DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
  992. BIT_reloadDStream(&(seqState.DStream));
  993. /* gcc and clang both don't like early returns in this loop.
  994. * gcc doesn't like early breaks either.
  995. * Instead save an error and report it at the end.
  996. * When there is an error, don't increment op, so we don't
  997. * overwrite.
  998. */
  999. if (UNLIKELY(ZSTD_isError(oneSeqSize))) error = oneSeqSize;
  1000. else op += oneSeqSize;
  1001. if (UNLIKELY(!--nbSeq)) break;
  1002. }
  1003. /* check if reached exact end */
  1004. DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
  1005. if (ZSTD_isError(error)) return error;
  1006. RETURN_ERROR_IF(nbSeq, corruption_detected, "");
  1007. RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
  1008. /* save reps for next block */
  1009. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1010. }
  1011. /* last literal segment */
  1012. { size_t const lastLLSize = litEnd - litPtr;
  1013. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1014. if (op != NULL) {
  1015. memcpy(op, litPtr, lastLLSize);
  1016. op += lastLLSize;
  1017. }
  1018. }
  1019. return op-ostart;
  1020. }
  1021. static size_t
  1022. ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
  1023. void* dst, size_t maxDstSize,
  1024. const void* seqStart, size_t seqSize, int nbSeq,
  1025. const ZSTD_longOffset_e isLongOffset,
  1026. const int frame)
  1027. {
  1028. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1029. }
  1030. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1031. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1032. FORCE_INLINE_TEMPLATE size_t
  1033. ZSTD_decompressSequencesLong_body(
  1034. ZSTD_DCtx* dctx,
  1035. void* dst, size_t maxDstSize,
  1036. const void* seqStart, size_t seqSize, int nbSeq,
  1037. const ZSTD_longOffset_e isLongOffset,
  1038. const int frame)
  1039. {
  1040. const BYTE* ip = (const BYTE*)seqStart;
  1041. const BYTE* const iend = ip + seqSize;
  1042. BYTE* const ostart = (BYTE* const)dst;
  1043. BYTE* const oend = ostart + maxDstSize;
  1044. BYTE* op = ostart;
  1045. const BYTE* litPtr = dctx->litPtr;
  1046. const BYTE* const litEnd = litPtr + dctx->litSize;
  1047. const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
  1048. const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
  1049. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  1050. (void)frame;
  1051. /* Regen sequences */
  1052. if (nbSeq) {
  1053. #define STORED_SEQS 4
  1054. #define STORED_SEQS_MASK (STORED_SEQS-1)
  1055. #define ADVANCED_SEQS 4
  1056. seq_t sequences[STORED_SEQS];
  1057. int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
  1058. seqState_t seqState;
  1059. int seqNb;
  1060. dctx->fseEntropy = 1;
  1061. { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
  1062. seqState.prefixStart = prefixStart;
  1063. seqState.pos = (size_t)(op-prefixStart);
  1064. seqState.dictEnd = dictEnd;
  1065. assert(dst != NULL);
  1066. assert(iend >= ip);
  1067. RETURN_ERROR_IF(
  1068. ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
  1069. corruption_detected, "");
  1070. ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
  1071. ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
  1072. ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
  1073. /* prepare in advance */
  1074. for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
  1075. sequences[seqNb] = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_prefetch);
  1076. 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 */
  1077. }
  1078. RETURN_ERROR_IF(seqNb<seqAdvance, corruption_detected, "");
  1079. /* decode and decompress */
  1080. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) {
  1081. seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_prefetch);
  1082. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
  1083. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1084. assert(!ZSTD_isError(oneSeqSize));
  1085. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
  1086. #endif
  1087. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1088. 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 */
  1089. sequences[seqNb & STORED_SEQS_MASK] = sequence;
  1090. op += oneSeqSize;
  1091. }
  1092. RETURN_ERROR_IF(seqNb<nbSeq, corruption_detected, "");
  1093. /* finish queue */
  1094. seqNb -= seqAdvance;
  1095. for ( ; seqNb<nbSeq ; seqNb++) {
  1096. size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
  1097. #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
  1098. assert(!ZSTD_isError(oneSeqSize));
  1099. if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
  1100. #endif
  1101. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  1102. op += oneSeqSize;
  1103. }
  1104. /* save reps for next block */
  1105. { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
  1106. }
  1107. /* last literal segment */
  1108. { size_t const lastLLSize = litEnd - litPtr;
  1109. RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
  1110. if (op != NULL) {
  1111. memcpy(op, litPtr, lastLLSize);
  1112. op += lastLLSize;
  1113. }
  1114. }
  1115. return op-ostart;
  1116. }
  1117. static size_t
  1118. ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
  1119. void* dst, size_t maxDstSize,
  1120. const void* seqStart, size_t seqSize, int nbSeq,
  1121. const ZSTD_longOffset_e isLongOffset,
  1122. const int frame)
  1123. {
  1124. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1125. }
  1126. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1127. #if DYNAMIC_BMI2
  1128. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1129. static TARGET_ATTRIBUTE("bmi2") size_t
  1130. DONT_VECTORIZE
  1131. ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
  1132. void* dst, size_t maxDstSize,
  1133. const void* seqStart, size_t seqSize, int nbSeq,
  1134. const ZSTD_longOffset_e isLongOffset,
  1135. const int frame)
  1136. {
  1137. return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1138. }
  1139. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1140. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1141. static TARGET_ATTRIBUTE("bmi2") size_t
  1142. ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
  1143. void* dst, size_t maxDstSize,
  1144. const void* seqStart, size_t seqSize, int nbSeq,
  1145. const ZSTD_longOffset_e isLongOffset,
  1146. const int frame)
  1147. {
  1148. return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1149. }
  1150. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1151. #endif /* DYNAMIC_BMI2 */
  1152. typedef size_t (*ZSTD_decompressSequences_t)(
  1153. ZSTD_DCtx* dctx,
  1154. void* dst, size_t maxDstSize,
  1155. const void* seqStart, size_t seqSize, int nbSeq,
  1156. const ZSTD_longOffset_e isLongOffset,
  1157. const int frame);
  1158. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1159. static size_t
  1160. ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
  1161. const void* seqStart, size_t seqSize, int nbSeq,
  1162. const ZSTD_longOffset_e isLongOffset,
  1163. const int frame)
  1164. {
  1165. DEBUGLOG(5, "ZSTD_decompressSequences");
  1166. #if DYNAMIC_BMI2
  1167. if (dctx->bmi2) {
  1168. return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1169. }
  1170. #endif
  1171. return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1172. }
  1173. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
  1174. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1175. /* ZSTD_decompressSequencesLong() :
  1176. * decompression function triggered when a minimum share of offsets is considered "long",
  1177. * aka out of cache.
  1178. * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
  1179. * This function will try to mitigate main memory latency through the use of prefetching */
  1180. static size_t
  1181. ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
  1182. void* dst, size_t maxDstSize,
  1183. const void* seqStart, size_t seqSize, int nbSeq,
  1184. const ZSTD_longOffset_e isLongOffset,
  1185. const int frame)
  1186. {
  1187. DEBUGLOG(5, "ZSTD_decompressSequencesLong");
  1188. #if DYNAMIC_BMI2
  1189. if (dctx->bmi2) {
  1190. return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1191. }
  1192. #endif
  1193. return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
  1194. }
  1195. #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
  1196. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1197. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1198. /* ZSTD_getLongOffsetsShare() :
  1199. * condition : offTable must be valid
  1200. * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
  1201. * compared to maximum possible of (1<<OffFSELog) */
  1202. static unsigned
  1203. ZSTD_getLongOffsetsShare(const ZSTD_seqSymbol* offTable)
  1204. {
  1205. const void* ptr = offTable;
  1206. U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
  1207. const ZSTD_seqSymbol* table = offTable + 1;
  1208. U32 const max = 1 << tableLog;
  1209. U32 u, total = 0;
  1210. DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
  1211. assert(max <= (1 << OffFSELog)); /* max not too large */
  1212. for (u=0; u<max; u++) {
  1213. if (table[u].nbAdditionalBits > 22) total += 1;
  1214. }
  1215. assert(tableLog <= OffFSELog);
  1216. total <<= (OffFSELog - tableLog); /* scale to OffFSELog */
  1217. return total;
  1218. }
  1219. #endif
  1220. size_t
  1221. ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
  1222. void* dst, size_t dstCapacity,
  1223. const void* src, size_t srcSize, const int frame)
  1224. { /* blockType == blockCompressed */
  1225. const BYTE* ip = (const BYTE*)src;
  1226. /* isLongOffset must be true if there are long offsets.
  1227. * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
  1228. * We don't expect that to be the case in 64-bit mode.
  1229. * In block mode, window size is not known, so we have to be conservative.
  1230. * (note: but it could be evaluated from current-lowLimit)
  1231. */
  1232. ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN))));
  1233. DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
  1234. RETURN_ERROR_IF(srcSize >= ZSTD_BLOCKSIZE_MAX, srcSize_wrong, "");
  1235. /* Decode literals section */
  1236. { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
  1237. DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
  1238. if (ZSTD_isError(litCSize)) return litCSize;
  1239. ip += litCSize;
  1240. srcSize -= litCSize;
  1241. }
  1242. /* Build Decoding Tables */
  1243. {
  1244. /* These macros control at build-time which decompressor implementation
  1245. * we use. If neither is defined, we do some inspection and dispatch at
  1246. * runtime.
  1247. */
  1248. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1249. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1250. int usePrefetchDecoder = dctx->ddictIsCold;
  1251. #endif
  1252. int nbSeq;
  1253. size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
  1254. if (ZSTD_isError(seqHSize)) return seqHSize;
  1255. ip += seqHSize;
  1256. srcSize -= seqHSize;
  1257. RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled");
  1258. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1259. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1260. if ( !usePrefetchDecoder
  1261. && (!frame || (dctx->fParams.windowSize > (1<<24)))
  1262. && (nbSeq>ADVANCED_SEQS) ) { /* could probably use a larger nbSeq limit */
  1263. U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr);
  1264. U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
  1265. usePrefetchDecoder = (shareLongOffsets >= minShare);
  1266. }
  1267. #endif
  1268. dctx->ddictIsCold = 0;
  1269. #if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
  1270. !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
  1271. if (usePrefetchDecoder)
  1272. #endif
  1273. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
  1274. return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1275. #endif
  1276. #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
  1277. /* else */
  1278. return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
  1279. #endif
  1280. }
  1281. }
  1282. void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
  1283. {
  1284. if (dst != dctx->previousDstEnd) { /* not contiguous */
  1285. dctx->dictEnd = dctx->previousDstEnd;
  1286. dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
  1287. dctx->prefixStart = dst;
  1288. dctx->previousDstEnd = dst;
  1289. }
  1290. }
  1291. size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
  1292. void* dst, size_t dstCapacity,
  1293. const void* src, size_t srcSize)
  1294. {
  1295. size_t dSize;
  1296. ZSTD_checkContinuity(dctx, dst);
  1297. dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
  1298. dctx->previousDstEnd = (char*)dst + dSize;
  1299. return dSize;
  1300. }