zstd_decompress_block.c 99 KB

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