huf_decompress.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. /* ******************************************************************
  2. * huff0 huffman decoder,
  3. * part of Finite State Entropy library
  4. * Copyright (c) Meta Platforms, Inc. and affiliates.
  5. *
  6. * You can contact the author at :
  7. * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
  8. *
  9. * This source code is licensed under both the BSD-style license (found in the
  10. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  11. * in the COPYING file in the root directory of this source tree).
  12. * You may select, at your option, one of the above-listed licenses.
  13. ****************************************************************** */
  14. /* **************************************************************
  15. * Dependencies
  16. ****************************************************************/
  17. #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset */
  18. #include "../common/compiler.h"
  19. #include "../common/bitstream.h" /* BIT_* */
  20. #include "../common/fse.h" /* to compress headers */
  21. #include "../common/huf.h"
  22. #include "../common/error_private.h"
  23. #include "../common/zstd_internal.h"
  24. #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_countTrailingZeros64 */
  25. /* **************************************************************
  26. * Constants
  27. ****************************************************************/
  28. #define HUF_DECODER_FAST_TABLELOG 11
  29. /* **************************************************************
  30. * Macros
  31. ****************************************************************/
  32. /* These two optional macros force the use one way or another of the two
  33. * Huffman decompression implementations. You can't force in both directions
  34. * at the same time.
  35. */
  36. #if defined(HUF_FORCE_DECOMPRESS_X1) && \
  37. defined(HUF_FORCE_DECOMPRESS_X2)
  38. #error "Cannot force the use of the X1 and X2 decoders at the same time!"
  39. #endif
  40. /* When DYNAMIC_BMI2 is enabled, fast decoders are only called when bmi2 is
  41. * supported at runtime, so we can add the BMI2 target attribute.
  42. * When it is disabled, we will still get BMI2 if it is enabled statically.
  43. */
  44. #if DYNAMIC_BMI2
  45. # define HUF_FAST_BMI2_ATTRS BMI2_TARGET_ATTRIBUTE
  46. #else
  47. # define HUF_FAST_BMI2_ATTRS
  48. #endif
  49. #ifdef __cplusplus
  50. # define HUF_EXTERN_C extern "C"
  51. #else
  52. # define HUF_EXTERN_C
  53. #endif
  54. #define HUF_ASM_DECL HUF_EXTERN_C
  55. #if DYNAMIC_BMI2
  56. # define HUF_NEED_BMI2_FUNCTION 1
  57. #else
  58. # define HUF_NEED_BMI2_FUNCTION 0
  59. #endif
  60. /* **************************************************************
  61. * Error Management
  62. ****************************************************************/
  63. #define HUF_isError ERR_isError
  64. /* **************************************************************
  65. * Byte alignment for workSpace management
  66. ****************************************************************/
  67. #define HUF_ALIGN(x, a) HUF_ALIGN_MASK((x), (a) - 1)
  68. #define HUF_ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))
  69. /* **************************************************************
  70. * BMI2 Variant Wrappers
  71. ****************************************************************/
  72. typedef size_t (*HUF_DecompressUsingDTableFn)(void *dst, size_t dstSize,
  73. const void *cSrc,
  74. size_t cSrcSize,
  75. const HUF_DTable *DTable);
  76. #if DYNAMIC_BMI2
  77. #define HUF_DGEN(fn) \
  78. \
  79. static size_t fn##_default( \
  80. void* dst, size_t dstSize, \
  81. const void* cSrc, size_t cSrcSize, \
  82. const HUF_DTable* DTable) \
  83. { \
  84. return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \
  85. } \
  86. \
  87. static BMI2_TARGET_ATTRIBUTE size_t fn##_bmi2( \
  88. void* dst, size_t dstSize, \
  89. const void* cSrc, size_t cSrcSize, \
  90. const HUF_DTable* DTable) \
  91. { \
  92. return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \
  93. } \
  94. \
  95. static size_t fn(void* dst, size_t dstSize, void const* cSrc, \
  96. size_t cSrcSize, HUF_DTable const* DTable, int flags) \
  97. { \
  98. if (flags & HUF_flags_bmi2) { \
  99. return fn##_bmi2(dst, dstSize, cSrc, cSrcSize, DTable); \
  100. } \
  101. return fn##_default(dst, dstSize, cSrc, cSrcSize, DTable); \
  102. }
  103. #else
  104. #define HUF_DGEN(fn) \
  105. static size_t fn(void* dst, size_t dstSize, void const* cSrc, \
  106. size_t cSrcSize, HUF_DTable const* DTable, int flags) \
  107. { \
  108. (void)flags; \
  109. return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \
  110. }
  111. #endif
  112. /*-***************************/
  113. /* generic DTableDesc */
  114. /*-***************************/
  115. typedef struct { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc;
  116. static DTableDesc HUF_getDTableDesc(const HUF_DTable* table)
  117. {
  118. DTableDesc dtd;
  119. ZSTD_memcpy(&dtd, table, sizeof(dtd));
  120. return dtd;
  121. }
  122. static size_t HUF_initFastDStream(BYTE const* ip) {
  123. BYTE const lastByte = ip[7];
  124. size_t const bitsConsumed = lastByte ? 8 - ZSTD_highbit32(lastByte) : 0;
  125. size_t const value = MEM_readLEST(ip) | 1;
  126. assert(bitsConsumed <= 8);
  127. assert(sizeof(size_t) == 8);
  128. return value << bitsConsumed;
  129. }
  130. /**
  131. * The input/output arguments to the Huffman fast decoding loop:
  132. *
  133. * ip [in/out] - The input pointers, must be updated to reflect what is consumed.
  134. * op [in/out] - The output pointers, must be updated to reflect what is written.
  135. * bits [in/out] - The bitstream containers, must be updated to reflect the current state.
  136. * dt [in] - The decoding table.
  137. * ilimit [in] - The input limit, stop when any input pointer is below ilimit.
  138. * oend [in] - The end of the output stream. op[3] must not cross oend.
  139. * iend [in] - The end of each input stream. ip[i] may cross iend[i],
  140. * as long as it is above ilimit, but that indicates corruption.
  141. */
  142. typedef struct {
  143. BYTE const* ip[4];
  144. BYTE* op[4];
  145. U64 bits[4];
  146. void const* dt;
  147. BYTE const* ilimit;
  148. BYTE* oend;
  149. BYTE const* iend[4];
  150. } HUF_DecompressFastArgs;
  151. typedef void (*HUF_DecompressFastLoopFn)(HUF_DecompressFastArgs*);
  152. /**
  153. * Initializes args for the fast decoding loop.
  154. * @returns 1 on success
  155. * 0 if the fallback implementation should be used.
  156. * Or an error code on failure.
  157. */
  158. static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* dst, size_t dstSize, void const* src, size_t srcSize, const HUF_DTable* DTable)
  159. {
  160. void const* dt = DTable + 1;
  161. U32 const dtLog = HUF_getDTableDesc(DTable).tableLog;
  162. const BYTE* const ilimit = (const BYTE*)src + 6 + 8;
  163. BYTE* const oend = (BYTE*)dst + dstSize;
  164. /* The fast decoding loop assumes 64-bit little-endian.
  165. * This condition is false on x32.
  166. */
  167. if (!MEM_isLittleEndian() || MEM_32bits())
  168. return 0;
  169. /* strict minimum : jump table + 1 byte per stream */
  170. if (srcSize < 10)
  171. return ERROR(corruption_detected);
  172. /* Must have at least 8 bytes per stream because we don't handle initializing smaller bit containers.
  173. * If table log is not correct at this point, fallback to the old decoder.
  174. * On small inputs we don't have enough data to trigger the fast loop, so use the old decoder.
  175. */
  176. if (dtLog != HUF_DECODER_FAST_TABLELOG)
  177. return 0;
  178. /* Read the jump table. */
  179. {
  180. const BYTE* const istart = (const BYTE*)src;
  181. size_t const length1 = MEM_readLE16(istart);
  182. size_t const length2 = MEM_readLE16(istart+2);
  183. size_t const length3 = MEM_readLE16(istart+4);
  184. size_t const length4 = srcSize - (length1 + length2 + length3 + 6);
  185. args->iend[0] = istart + 6; /* jumpTable */
  186. args->iend[1] = args->iend[0] + length1;
  187. args->iend[2] = args->iend[1] + length2;
  188. args->iend[3] = args->iend[2] + length3;
  189. /* HUF_initFastDStream() requires this, and this small of an input
  190. * won't benefit from the ASM loop anyways.
  191. * length1 must be >= 16 so that ip[0] >= ilimit before the loop
  192. * starts.
  193. */
  194. if (length1 < 16 || length2 < 8 || length3 < 8 || length4 < 8)
  195. return 0;
  196. if (length4 > srcSize) return ERROR(corruption_detected); /* overflow */
  197. }
  198. /* ip[] contains the position that is currently loaded into bits[]. */
  199. args->ip[0] = args->iend[1] - sizeof(U64);
  200. args->ip[1] = args->iend[2] - sizeof(U64);
  201. args->ip[2] = args->iend[3] - sizeof(U64);
  202. args->ip[3] = (BYTE const*)src + srcSize - sizeof(U64);
  203. /* op[] contains the output pointers. */
  204. args->op[0] = (BYTE*)dst;
  205. args->op[1] = args->op[0] + (dstSize+3)/4;
  206. args->op[2] = args->op[1] + (dstSize+3)/4;
  207. args->op[3] = args->op[2] + (dstSize+3)/4;
  208. /* No point to call the ASM loop for tiny outputs. */
  209. if (args->op[3] >= oend)
  210. return 0;
  211. /* bits[] is the bit container.
  212. * It is read from the MSB down to the LSB.
  213. * It is shifted left as it is read, and zeros are
  214. * shifted in. After the lowest valid bit a 1 is
  215. * set, so that CountTrailingZeros(bits[]) can be used
  216. * to count how many bits we've consumed.
  217. */
  218. args->bits[0] = HUF_initFastDStream(args->ip[0]);
  219. args->bits[1] = HUF_initFastDStream(args->ip[1]);
  220. args->bits[2] = HUF_initFastDStream(args->ip[2]);
  221. args->bits[3] = HUF_initFastDStream(args->ip[3]);
  222. /* If ip[] >= ilimit, it is guaranteed to be safe to
  223. * reload bits[]. It may be beyond its section, but is
  224. * guaranteed to be valid (>= istart).
  225. */
  226. args->ilimit = ilimit;
  227. args->oend = oend;
  228. args->dt = dt;
  229. return 1;
  230. }
  231. static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArgs const* args, int stream, BYTE* segmentEnd)
  232. {
  233. /* Validate that we haven't overwritten. */
  234. if (args->op[stream] > segmentEnd)
  235. return ERROR(corruption_detected);
  236. /* Validate that we haven't read beyond iend[].
  237. * Note that ip[] may be < iend[] because the MSB is
  238. * the next bit to read, and we may have consumed 100%
  239. * of the stream, so down to iend[i] - 8 is valid.
  240. */
  241. if (args->ip[stream] < args->iend[stream] - 8)
  242. return ERROR(corruption_detected);
  243. /* Construct the BIT_DStream_t. */
  244. assert(sizeof(size_t) == 8);
  245. bit->bitContainer = MEM_readLEST(args->ip[stream]);
  246. bit->bitsConsumed = ZSTD_countTrailingZeros64(args->bits[stream]);
  247. bit->start = (const char*)args->iend[0];
  248. bit->limitPtr = bit->start + sizeof(size_t);
  249. bit->ptr = (const char*)args->ip[stream];
  250. return 0;
  251. }
  252. #ifndef HUF_FORCE_DECOMPRESS_X2
  253. /*-***************************/
  254. /* single-symbol decoding */
  255. /*-***************************/
  256. typedef struct { BYTE nbBits; BYTE byte; } HUF_DEltX1; /* single-symbol decoding */
  257. /**
  258. * Packs 4 HUF_DEltX1 structs into a U64. This is used to lay down 4 entries at
  259. * a time.
  260. */
  261. static U64 HUF_DEltX1_set4(BYTE symbol, BYTE nbBits) {
  262. U64 D4;
  263. if (MEM_isLittleEndian()) {
  264. D4 = (U64)((symbol << 8) + nbBits);
  265. } else {
  266. D4 = (U64)(symbol + (nbBits << 8));
  267. }
  268. assert(D4 < (1U << 16));
  269. D4 *= 0x0001000100010001ULL;
  270. return D4;
  271. }
  272. /**
  273. * Increase the tableLog to targetTableLog and rescales the stats.
  274. * If tableLog > targetTableLog this is a no-op.
  275. * @returns New tableLog
  276. */
  277. static U32 HUF_rescaleStats(BYTE* huffWeight, U32* rankVal, U32 nbSymbols, U32 tableLog, U32 targetTableLog)
  278. {
  279. if (tableLog > targetTableLog)
  280. return tableLog;
  281. if (tableLog < targetTableLog) {
  282. U32 const scale = targetTableLog - tableLog;
  283. U32 s;
  284. /* Increase the weight for all non-zero probability symbols by scale. */
  285. for (s = 0; s < nbSymbols; ++s) {
  286. huffWeight[s] += (BYTE)((huffWeight[s] == 0) ? 0 : scale);
  287. }
  288. /* Update rankVal to reflect the new weights.
  289. * All weights except 0 get moved to weight + scale.
  290. * Weights [1, scale] are empty.
  291. */
  292. for (s = targetTableLog; s > scale; --s) {
  293. rankVal[s] = rankVal[s - scale];
  294. }
  295. for (s = scale; s > 0; --s) {
  296. rankVal[s] = 0;
  297. }
  298. }
  299. return targetTableLog;
  300. }
  301. typedef struct {
  302. U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1];
  303. U32 rankStart[HUF_TABLELOG_ABSOLUTEMAX + 1];
  304. U32 statsWksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
  305. BYTE symbols[HUF_SYMBOLVALUE_MAX + 1];
  306. BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1];
  307. } HUF_ReadDTableX1_Workspace;
  308. size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags)
  309. {
  310. U32 tableLog = 0;
  311. U32 nbSymbols = 0;
  312. size_t iSize;
  313. void* const dtPtr = DTable + 1;
  314. HUF_DEltX1* const dt = (HUF_DEltX1*)dtPtr;
  315. HUF_ReadDTableX1_Workspace* wksp = (HUF_ReadDTableX1_Workspace*)workSpace;
  316. DEBUG_STATIC_ASSERT(HUF_DECOMPRESS_WORKSPACE_SIZE >= sizeof(*wksp));
  317. if (sizeof(*wksp) > wkspSize) return ERROR(tableLog_tooLarge);
  318. DEBUG_STATIC_ASSERT(sizeof(DTableDesc) == sizeof(HUF_DTable));
  319. /* ZSTD_memset(huffWeight, 0, sizeof(huffWeight)); */ /* is not necessary, even though some analyzer complain ... */
  320. iSize = HUF_readStats_wksp(wksp->huffWeight, HUF_SYMBOLVALUE_MAX + 1, wksp->rankVal, &nbSymbols, &tableLog, src, srcSize, wksp->statsWksp, sizeof(wksp->statsWksp), flags);
  321. if (HUF_isError(iSize)) return iSize;
  322. /* Table header */
  323. { DTableDesc dtd = HUF_getDTableDesc(DTable);
  324. U32 const maxTableLog = dtd.maxTableLog + 1;
  325. U32 const targetTableLog = MIN(maxTableLog, HUF_DECODER_FAST_TABLELOG);
  326. tableLog = HUF_rescaleStats(wksp->huffWeight, wksp->rankVal, nbSymbols, tableLog, targetTableLog);
  327. if (tableLog > (U32)(dtd.maxTableLog+1)) return ERROR(tableLog_tooLarge); /* DTable too small, Huffman tree cannot fit in */
  328. dtd.tableType = 0;
  329. dtd.tableLog = (BYTE)tableLog;
  330. ZSTD_memcpy(DTable, &dtd, sizeof(dtd));
  331. }
  332. /* Compute symbols and rankStart given rankVal:
  333. *
  334. * rankVal already contains the number of values of each weight.
  335. *
  336. * symbols contains the symbols ordered by weight. First are the rankVal[0]
  337. * weight 0 symbols, followed by the rankVal[1] weight 1 symbols, and so on.
  338. * symbols[0] is filled (but unused) to avoid a branch.
  339. *
  340. * rankStart contains the offset where each rank belongs in the DTable.
  341. * rankStart[0] is not filled because there are no entries in the table for
  342. * weight 0.
  343. */
  344. { int n;
  345. U32 nextRankStart = 0;
  346. int const unroll = 4;
  347. int const nLimit = (int)nbSymbols - unroll + 1;
  348. for (n=0; n<(int)tableLog+1; n++) {
  349. U32 const curr = nextRankStart;
  350. nextRankStart += wksp->rankVal[n];
  351. wksp->rankStart[n] = curr;
  352. }
  353. for (n=0; n < nLimit; n += unroll) {
  354. int u;
  355. for (u=0; u < unroll; ++u) {
  356. size_t const w = wksp->huffWeight[n+u];
  357. wksp->symbols[wksp->rankStart[w]++] = (BYTE)(n+u);
  358. }
  359. }
  360. for (; n < (int)nbSymbols; ++n) {
  361. size_t const w = wksp->huffWeight[n];
  362. wksp->symbols[wksp->rankStart[w]++] = (BYTE)n;
  363. }
  364. }
  365. /* fill DTable
  366. * We fill all entries of each weight in order.
  367. * That way length is a constant for each iteration of the outer loop.
  368. * We can switch based on the length to a different inner loop which is
  369. * optimized for that particular case.
  370. */
  371. { U32 w;
  372. int symbol = wksp->rankVal[0];
  373. int rankStart = 0;
  374. for (w=1; w<tableLog+1; ++w) {
  375. int const symbolCount = wksp->rankVal[w];
  376. int const length = (1 << w) >> 1;
  377. int uStart = rankStart;
  378. BYTE const nbBits = (BYTE)(tableLog + 1 - w);
  379. int s;
  380. int u;
  381. switch (length) {
  382. case 1:
  383. for (s=0; s<symbolCount; ++s) {
  384. HUF_DEltX1 D;
  385. D.byte = wksp->symbols[symbol + s];
  386. D.nbBits = nbBits;
  387. dt[uStart] = D;
  388. uStart += 1;
  389. }
  390. break;
  391. case 2:
  392. for (s=0; s<symbolCount; ++s) {
  393. HUF_DEltX1 D;
  394. D.byte = wksp->symbols[symbol + s];
  395. D.nbBits = nbBits;
  396. dt[uStart+0] = D;
  397. dt[uStart+1] = D;
  398. uStart += 2;
  399. }
  400. break;
  401. case 4:
  402. for (s=0; s<symbolCount; ++s) {
  403. U64 const D4 = HUF_DEltX1_set4(wksp->symbols[symbol + s], nbBits);
  404. MEM_write64(dt + uStart, D4);
  405. uStart += 4;
  406. }
  407. break;
  408. case 8:
  409. for (s=0; s<symbolCount; ++s) {
  410. U64 const D4 = HUF_DEltX1_set4(wksp->symbols[symbol + s], nbBits);
  411. MEM_write64(dt + uStart, D4);
  412. MEM_write64(dt + uStart + 4, D4);
  413. uStart += 8;
  414. }
  415. break;
  416. default:
  417. for (s=0; s<symbolCount; ++s) {
  418. U64 const D4 = HUF_DEltX1_set4(wksp->symbols[symbol + s], nbBits);
  419. for (u=0; u < length; u += 16) {
  420. MEM_write64(dt + uStart + u + 0, D4);
  421. MEM_write64(dt + uStart + u + 4, D4);
  422. MEM_write64(dt + uStart + u + 8, D4);
  423. MEM_write64(dt + uStart + u + 12, D4);
  424. }
  425. assert(u == length);
  426. uStart += length;
  427. }
  428. break;
  429. }
  430. symbol += symbolCount;
  431. rankStart += symbolCount * length;
  432. }
  433. }
  434. return iSize;
  435. }
  436. FORCE_INLINE_TEMPLATE BYTE
  437. HUF_decodeSymbolX1(BIT_DStream_t* Dstream, const HUF_DEltX1* dt, const U32 dtLog)
  438. {
  439. size_t const val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  440. BYTE const c = dt[val].byte;
  441. BIT_skipBits(Dstream, dt[val].nbBits);
  442. return c;
  443. }
  444. #define HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) \
  445. *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog)
  446. #define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr) \
  447. if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
  448. HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)
  449. #define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr) \
  450. if (MEM_64bits()) \
  451. HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)
  452. HINT_INLINE size_t
  453. HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog)
  454. {
  455. BYTE* const pStart = p;
  456. /* up to 4 symbols at a time */
  457. if ((pEnd - p) > 3) {
  458. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-3)) {
  459. HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
  460. HUF_DECODE_SYMBOLX1_1(p, bitDPtr);
  461. HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
  462. HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
  463. }
  464. } else {
  465. BIT_reloadDStream(bitDPtr);
  466. }
  467. /* [0-3] symbols remaining */
  468. if (MEM_32bits())
  469. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd))
  470. HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
  471. /* no more data to retrieve from bitstream, no need to reload */
  472. while (p < pEnd)
  473. HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
  474. return (size_t)(pEnd-pStart);
  475. }
  476. FORCE_INLINE_TEMPLATE size_t
  477. HUF_decompress1X1_usingDTable_internal_body(
  478. void* dst, size_t dstSize,
  479. const void* cSrc, size_t cSrcSize,
  480. const HUF_DTable* DTable)
  481. {
  482. BYTE* op = (BYTE*)dst;
  483. BYTE* const oend = op + dstSize;
  484. const void* dtPtr = DTable + 1;
  485. const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
  486. BIT_DStream_t bitD;
  487. DTableDesc const dtd = HUF_getDTableDesc(DTable);
  488. U32 const dtLog = dtd.tableLog;
  489. CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );
  490. HUF_decodeStreamX1(op, &bitD, oend, dt, dtLog);
  491. if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected);
  492. return dstSize;
  493. }
  494. /* HUF_decompress4X1_usingDTable_internal_body():
  495. * Conditions :
  496. * @dstSize >= 6
  497. */
  498. FORCE_INLINE_TEMPLATE size_t
  499. HUF_decompress4X1_usingDTable_internal_body(
  500. void* dst, size_t dstSize,
  501. const void* cSrc, size_t cSrcSize,
  502. const HUF_DTable* DTable)
  503. {
  504. /* Check */
  505. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  506. { const BYTE* const istart = (const BYTE*) cSrc;
  507. BYTE* const ostart = (BYTE*) dst;
  508. BYTE* const oend = ostart + dstSize;
  509. BYTE* const olimit = oend - 3;
  510. const void* const dtPtr = DTable + 1;
  511. const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
  512. /* Init */
  513. BIT_DStream_t bitD1;
  514. BIT_DStream_t bitD2;
  515. BIT_DStream_t bitD3;
  516. BIT_DStream_t bitD4;
  517. size_t const length1 = MEM_readLE16(istart);
  518. size_t const length2 = MEM_readLE16(istart+2);
  519. size_t const length3 = MEM_readLE16(istart+4);
  520. size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
  521. const BYTE* const istart1 = istart + 6; /* jumpTable */
  522. const BYTE* const istart2 = istart1 + length1;
  523. const BYTE* const istart3 = istart2 + length2;
  524. const BYTE* const istart4 = istart3 + length3;
  525. const size_t segmentSize = (dstSize+3) / 4;
  526. BYTE* const opStart2 = ostart + segmentSize;
  527. BYTE* const opStart3 = opStart2 + segmentSize;
  528. BYTE* const opStart4 = opStart3 + segmentSize;
  529. BYTE* op1 = ostart;
  530. BYTE* op2 = opStart2;
  531. BYTE* op3 = opStart3;
  532. BYTE* op4 = opStart4;
  533. DTableDesc const dtd = HUF_getDTableDesc(DTable);
  534. U32 const dtLog = dtd.tableLog;
  535. U32 endSignal = 1;
  536. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  537. if (opStart4 > oend) return ERROR(corruption_detected); /* overflow */
  538. if (dstSize < 6) return ERROR(corruption_detected); /* stream 4-split doesn't work */
  539. CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
  540. CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
  541. CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
  542. CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );
  543. /* up to 16 symbols per loop (4 symbols per stream) in 64-bit mode */
  544. if ((size_t)(oend - op4) >= sizeof(size_t)) {
  545. for ( ; (endSignal) & (op4 < olimit) ; ) {
  546. HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
  547. HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
  548. HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
  549. HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
  550. HUF_DECODE_SYMBOLX1_1(op1, &bitD1);
  551. HUF_DECODE_SYMBOLX1_1(op2, &bitD2);
  552. HUF_DECODE_SYMBOLX1_1(op3, &bitD3);
  553. HUF_DECODE_SYMBOLX1_1(op4, &bitD4);
  554. HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
  555. HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
  556. HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
  557. HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
  558. HUF_DECODE_SYMBOLX1_0(op1, &bitD1);
  559. HUF_DECODE_SYMBOLX1_0(op2, &bitD2);
  560. HUF_DECODE_SYMBOLX1_0(op3, &bitD3);
  561. HUF_DECODE_SYMBOLX1_0(op4, &bitD4);
  562. endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished;
  563. endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished;
  564. endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished;
  565. endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished;
  566. }
  567. }
  568. /* check corruption */
  569. /* note : should not be necessary : op# advance in lock step, and we control op4.
  570. * but curiously, binary generated by gcc 7.2 & 7.3 with -mbmi2 runs faster when >=1 test is present */
  571. if (op1 > opStart2) return ERROR(corruption_detected);
  572. if (op2 > opStart3) return ERROR(corruption_detected);
  573. if (op3 > opStart4) return ERROR(corruption_detected);
  574. /* note : op4 supposed already verified within main loop */
  575. /* finish bitStreams one by one */
  576. HUF_decodeStreamX1(op1, &bitD1, opStart2, dt, dtLog);
  577. HUF_decodeStreamX1(op2, &bitD2, opStart3, dt, dtLog);
  578. HUF_decodeStreamX1(op3, &bitD3, opStart4, dt, dtLog);
  579. HUF_decodeStreamX1(op4, &bitD4, oend, dt, dtLog);
  580. /* check */
  581. { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  582. if (!endCheck) return ERROR(corruption_detected); }
  583. /* decoded size */
  584. return dstSize;
  585. }
  586. }
  587. #if HUF_NEED_BMI2_FUNCTION
  588. static BMI2_TARGET_ATTRIBUTE
  589. size_t HUF_decompress4X1_usingDTable_internal_bmi2(void* dst, size_t dstSize, void const* cSrc,
  590. size_t cSrcSize, HUF_DTable const* DTable) {
  591. return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
  592. }
  593. #endif
  594. static
  595. size_t HUF_decompress4X1_usingDTable_internal_default(void* dst, size_t dstSize, void const* cSrc,
  596. size_t cSrcSize, HUF_DTable const* DTable) {
  597. return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
  598. }
  599. #if ZSTD_ENABLE_ASM_X86_64_BMI2
  600. HUF_ASM_DECL void HUF_decompress4X1_usingDTable_internal_fast_asm_loop(HUF_DecompressFastArgs* args) ZSTDLIB_HIDDEN;
  601. #endif
  602. static HUF_FAST_BMI2_ATTRS
  603. void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* args)
  604. {
  605. U64 bits[4];
  606. BYTE const* ip[4];
  607. BYTE* op[4];
  608. U16 const* const dtable = (U16 const*)args->dt;
  609. BYTE* const oend = args->oend;
  610. BYTE const* const ilimit = args->ilimit;
  611. /* Copy the arguments to local variables */
  612. ZSTD_memcpy(&bits, &args->bits, sizeof(bits));
  613. ZSTD_memcpy((void*)(&ip), &args->ip, sizeof(ip));
  614. ZSTD_memcpy(&op, &args->op, sizeof(op));
  615. assert(MEM_isLittleEndian());
  616. assert(!MEM_32bits());
  617. for (;;) {
  618. BYTE* olimit;
  619. int stream;
  620. int symbol;
  621. /* Assert loop preconditions */
  622. #ifndef NDEBUG
  623. for (stream = 0; stream < 4; ++stream) {
  624. assert(op[stream] <= (stream == 3 ? oend : op[stream + 1]));
  625. assert(ip[stream] >= ilimit);
  626. }
  627. #endif
  628. /* Compute olimit */
  629. {
  630. /* Each iteration produces 5 output symbols per stream */
  631. size_t const oiters = (size_t)(oend - op[3]) / 5;
  632. /* Each iteration consumes up to 11 bits * 5 = 55 bits < 7 bytes
  633. * per stream.
  634. */
  635. size_t const iiters = (size_t)(ip[0] - ilimit) / 7;
  636. /* We can safely run iters iterations before running bounds checks */
  637. size_t const iters = MIN(oiters, iiters);
  638. size_t const symbols = iters * 5;
  639. /* We can simply check that op[3] < olimit, instead of checking all
  640. * of our bounds, since we can't hit the other bounds until we've run
  641. * iters iterations, which only happens when op[3] == olimit.
  642. */
  643. olimit = op[3] + symbols;
  644. /* Exit fast decoding loop once we get close to the end. */
  645. if (op[3] + 20 > olimit)
  646. break;
  647. /* Exit the decoding loop if any input pointer has crossed the
  648. * previous one. This indicates corruption, and a precondition
  649. * to our loop is that ip[i] >= ip[0].
  650. */
  651. for (stream = 1; stream < 4; ++stream) {
  652. if (ip[stream] < ip[stream - 1])
  653. goto _out;
  654. }
  655. }
  656. #ifndef NDEBUG
  657. for (stream = 1; stream < 4; ++stream) {
  658. assert(ip[stream] >= ip[stream - 1]);
  659. }
  660. #endif
  661. do {
  662. /* Decode 5 symbols in each of the 4 streams */
  663. for (symbol = 0; symbol < 5; ++symbol) {
  664. for (stream = 0; stream < 4; ++stream) {
  665. int const index = (int)(bits[stream] >> 53);
  666. int const entry = (int)dtable[index];
  667. bits[stream] <<= (entry & 63);
  668. op[stream][symbol] = (BYTE)((entry >> 8) & 0xFF);
  669. }
  670. }
  671. /* Reload the bitstreams */
  672. for (stream = 0; stream < 4; ++stream) {
  673. int const ctz = ZSTD_countTrailingZeros64(bits[stream]);
  674. int const nbBits = ctz & 7;
  675. int const nbBytes = ctz >> 3;
  676. op[stream] += 5;
  677. ip[stream] -= nbBytes;
  678. bits[stream] = MEM_read64(ip[stream]) | 1;
  679. bits[stream] <<= nbBits;
  680. }
  681. } while (op[3] < olimit);
  682. }
  683. _out:
  684. /* Save the final values of each of the state variables back to args. */
  685. ZSTD_memcpy(&args->bits, &bits, sizeof(bits));
  686. ZSTD_memcpy((void*)(&args->ip), &ip, sizeof(ip));
  687. ZSTD_memcpy(&args->op, &op, sizeof(op));
  688. }
  689. /**
  690. * @returns @p dstSize on success (>= 6)
  691. * 0 if the fallback implementation should be used
  692. * An error if an error occurred
  693. */
  694. static HUF_FAST_BMI2_ATTRS
  695. size_t
  696. HUF_decompress4X1_usingDTable_internal_fast(
  697. void* dst, size_t dstSize,
  698. const void* cSrc, size_t cSrcSize,
  699. const HUF_DTable* DTable,
  700. HUF_DecompressFastLoopFn loopFn)
  701. {
  702. void const* dt = DTable + 1;
  703. const BYTE* const iend = (const BYTE*)cSrc + 6;
  704. BYTE* const oend = (BYTE*)dst + dstSize;
  705. HUF_DecompressFastArgs args;
  706. { size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable);
  707. FORWARD_IF_ERROR(ret, "Failed to init fast loop args");
  708. if (ret == 0)
  709. return 0;
  710. }
  711. assert(args.ip[0] >= args.ilimit);
  712. loopFn(&args);
  713. /* Our loop guarantees that ip[] >= ilimit and that we haven't
  714. * overwritten any op[].
  715. */
  716. assert(args.ip[0] >= iend);
  717. assert(args.ip[1] >= iend);
  718. assert(args.ip[2] >= iend);
  719. assert(args.ip[3] >= iend);
  720. assert(args.op[3] <= oend);
  721. (void)iend;
  722. /* finish bit streams one by one. */
  723. { size_t const segmentSize = (dstSize+3) / 4;
  724. BYTE* segmentEnd = (BYTE*)dst;
  725. int i;
  726. for (i = 0; i < 4; ++i) {
  727. BIT_DStream_t bit;
  728. if (segmentSize <= (size_t)(oend - segmentEnd))
  729. segmentEnd += segmentSize;
  730. else
  731. segmentEnd = oend;
  732. FORWARD_IF_ERROR(HUF_initRemainingDStream(&bit, &args, i, segmentEnd), "corruption");
  733. /* Decompress and validate that we've produced exactly the expected length. */
  734. args.op[i] += HUF_decodeStreamX1(args.op[i], &bit, segmentEnd, (HUF_DEltX1 const*)dt, HUF_DECODER_FAST_TABLELOG);
  735. if (args.op[i] != segmentEnd) return ERROR(corruption_detected);
  736. }
  737. }
  738. /* decoded size */
  739. assert(dstSize != 0);
  740. return dstSize;
  741. }
  742. HUF_DGEN(HUF_decompress1X1_usingDTable_internal)
  743. static size_t HUF_decompress4X1_usingDTable_internal(void* dst, size_t dstSize, void const* cSrc,
  744. size_t cSrcSize, HUF_DTable const* DTable, int flags)
  745. {
  746. HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X1_usingDTable_internal_default;
  747. HUF_DecompressFastLoopFn loopFn = HUF_decompress4X1_usingDTable_internal_fast_c_loop;
  748. #if DYNAMIC_BMI2
  749. if (flags & HUF_flags_bmi2) {
  750. fallbackFn = HUF_decompress4X1_usingDTable_internal_bmi2;
  751. # if ZSTD_ENABLE_ASM_X86_64_BMI2
  752. if (!(flags & HUF_flags_disableAsm)) {
  753. loopFn = HUF_decompress4X1_usingDTable_internal_fast_asm_loop;
  754. }
  755. # endif
  756. } else {
  757. return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable);
  758. }
  759. #endif
  760. #if ZSTD_ENABLE_ASM_X86_64_BMI2 && defined(__BMI2__)
  761. if (!(flags & HUF_flags_disableAsm)) {
  762. loopFn = HUF_decompress4X1_usingDTable_internal_fast_asm_loop;
  763. }
  764. #endif
  765. if (!(flags & HUF_flags_disableFast)) {
  766. size_t const ret = HUF_decompress4X1_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn);
  767. if (ret != 0)
  768. return ret;
  769. }
  770. return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable);
  771. }
  772. static size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
  773. const void* cSrc, size_t cSrcSize,
  774. void* workSpace, size_t wkspSize, int flags)
  775. {
  776. const BYTE* ip = (const BYTE*) cSrc;
  777. size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize, flags);
  778. if (HUF_isError(hSize)) return hSize;
  779. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  780. ip += hSize; cSrcSize -= hSize;
  781. return HUF_decompress4X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, flags);
  782. }
  783. #endif /* HUF_FORCE_DECOMPRESS_X2 */
  784. #ifndef HUF_FORCE_DECOMPRESS_X1
  785. /* *************************/
  786. /* double-symbols decoding */
  787. /* *************************/
  788. typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX2; /* double-symbols decoding */
  789. typedef struct { BYTE symbol; } sortedSymbol_t;
  790. typedef U32 rankValCol_t[HUF_TABLELOG_MAX + 1];
  791. typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX];
  792. /**
  793. * Constructs a HUF_DEltX2 in a U32.
  794. */
  795. static U32 HUF_buildDEltX2U32(U32 symbol, U32 nbBits, U32 baseSeq, int level)
  796. {
  797. U32 seq;
  798. DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, sequence) == 0);
  799. DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, nbBits) == 2);
  800. DEBUG_STATIC_ASSERT(offsetof(HUF_DEltX2, length) == 3);
  801. DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U32));
  802. if (MEM_isLittleEndian()) {
  803. seq = level == 1 ? symbol : (baseSeq + (symbol << 8));
  804. return seq + (nbBits << 16) + ((U32)level << 24);
  805. } else {
  806. seq = level == 1 ? (symbol << 8) : ((baseSeq << 8) + symbol);
  807. return (seq << 16) + (nbBits << 8) + (U32)level;
  808. }
  809. }
  810. /**
  811. * Constructs a HUF_DEltX2.
  812. */
  813. static HUF_DEltX2 HUF_buildDEltX2(U32 symbol, U32 nbBits, U32 baseSeq, int level)
  814. {
  815. HUF_DEltX2 DElt;
  816. U32 const val = HUF_buildDEltX2U32(symbol, nbBits, baseSeq, level);
  817. DEBUG_STATIC_ASSERT(sizeof(DElt) == sizeof(val));
  818. ZSTD_memcpy(&DElt, &val, sizeof(val));
  819. return DElt;
  820. }
  821. /**
  822. * Constructs 2 HUF_DEltX2s and packs them into a U64.
  823. */
  824. static U64 HUF_buildDEltX2U64(U32 symbol, U32 nbBits, U16 baseSeq, int level)
  825. {
  826. U32 DElt = HUF_buildDEltX2U32(symbol, nbBits, baseSeq, level);
  827. return (U64)DElt + ((U64)DElt << 32);
  828. }
  829. /**
  830. * Fills the DTable rank with all the symbols from [begin, end) that are each
  831. * nbBits long.
  832. *
  833. * @param DTableRank The start of the rank in the DTable.
  834. * @param begin The first symbol to fill (inclusive).
  835. * @param end The last symbol to fill (exclusive).
  836. * @param nbBits Each symbol is nbBits long.
  837. * @param tableLog The table log.
  838. * @param baseSeq If level == 1 { 0 } else { the first level symbol }
  839. * @param level The level in the table. Must be 1 or 2.
  840. */
  841. static void HUF_fillDTableX2ForWeight(
  842. HUF_DEltX2* DTableRank,
  843. sortedSymbol_t const* begin, sortedSymbol_t const* end,
  844. U32 nbBits, U32 tableLog,
  845. U16 baseSeq, int const level)
  846. {
  847. U32 const length = 1U << ((tableLog - nbBits) & 0x1F /* quiet static-analyzer */);
  848. const sortedSymbol_t* ptr;
  849. assert(level >= 1 && level <= 2);
  850. switch (length) {
  851. case 1:
  852. for (ptr = begin; ptr != end; ++ptr) {
  853. HUF_DEltX2 const DElt = HUF_buildDEltX2(ptr->symbol, nbBits, baseSeq, level);
  854. *DTableRank++ = DElt;
  855. }
  856. break;
  857. case 2:
  858. for (ptr = begin; ptr != end; ++ptr) {
  859. HUF_DEltX2 const DElt = HUF_buildDEltX2(ptr->symbol, nbBits, baseSeq, level);
  860. DTableRank[0] = DElt;
  861. DTableRank[1] = DElt;
  862. DTableRank += 2;
  863. }
  864. break;
  865. case 4:
  866. for (ptr = begin; ptr != end; ++ptr) {
  867. U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level);
  868. ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2));
  869. ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2));
  870. DTableRank += 4;
  871. }
  872. break;
  873. case 8:
  874. for (ptr = begin; ptr != end; ++ptr) {
  875. U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level);
  876. ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2));
  877. ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2));
  878. ZSTD_memcpy(DTableRank + 4, &DEltX2, sizeof(DEltX2));
  879. ZSTD_memcpy(DTableRank + 6, &DEltX2, sizeof(DEltX2));
  880. DTableRank += 8;
  881. }
  882. break;
  883. default:
  884. for (ptr = begin; ptr != end; ++ptr) {
  885. U64 const DEltX2 = HUF_buildDEltX2U64(ptr->symbol, nbBits, baseSeq, level);
  886. HUF_DEltX2* const DTableRankEnd = DTableRank + length;
  887. for (; DTableRank != DTableRankEnd; DTableRank += 8) {
  888. ZSTD_memcpy(DTableRank + 0, &DEltX2, sizeof(DEltX2));
  889. ZSTD_memcpy(DTableRank + 2, &DEltX2, sizeof(DEltX2));
  890. ZSTD_memcpy(DTableRank + 4, &DEltX2, sizeof(DEltX2));
  891. ZSTD_memcpy(DTableRank + 6, &DEltX2, sizeof(DEltX2));
  892. }
  893. }
  894. break;
  895. }
  896. }
  897. /* HUF_fillDTableX2Level2() :
  898. * `rankValOrigin` must be a table of at least (HUF_TABLELOG_MAX + 1) U32 */
  899. static void HUF_fillDTableX2Level2(HUF_DEltX2* DTable, U32 targetLog, const U32 consumedBits,
  900. const U32* rankVal, const int minWeight, const int maxWeight1,
  901. const sortedSymbol_t* sortedSymbols, U32 const* rankStart,
  902. U32 nbBitsBaseline, U16 baseSeq)
  903. {
  904. /* Fill skipped values (all positions up to rankVal[minWeight]).
  905. * These are positions only get a single symbol because the combined weight
  906. * is too large.
  907. */
  908. if (minWeight>1) {
  909. U32 const length = 1U << ((targetLog - consumedBits) & 0x1F /* quiet static-analyzer */);
  910. U64 const DEltX2 = HUF_buildDEltX2U64(baseSeq, consumedBits, /* baseSeq */ 0, /* level */ 1);
  911. int const skipSize = rankVal[minWeight];
  912. assert(length > 1);
  913. assert((U32)skipSize < length);
  914. switch (length) {
  915. case 2:
  916. assert(skipSize == 1);
  917. ZSTD_memcpy(DTable, &DEltX2, sizeof(DEltX2));
  918. break;
  919. case 4:
  920. assert(skipSize <= 4);
  921. ZSTD_memcpy(DTable + 0, &DEltX2, sizeof(DEltX2));
  922. ZSTD_memcpy(DTable + 2, &DEltX2, sizeof(DEltX2));
  923. break;
  924. default:
  925. {
  926. int i;
  927. for (i = 0; i < skipSize; i += 8) {
  928. ZSTD_memcpy(DTable + i + 0, &DEltX2, sizeof(DEltX2));
  929. ZSTD_memcpy(DTable + i + 2, &DEltX2, sizeof(DEltX2));
  930. ZSTD_memcpy(DTable + i + 4, &DEltX2, sizeof(DEltX2));
  931. ZSTD_memcpy(DTable + i + 6, &DEltX2, sizeof(DEltX2));
  932. }
  933. }
  934. }
  935. }
  936. /* Fill each of the second level symbols by weight. */
  937. {
  938. int w;
  939. for (w = minWeight; w < maxWeight1; ++w) {
  940. int const begin = rankStart[w];
  941. int const end = rankStart[w+1];
  942. U32 const nbBits = nbBitsBaseline - w;
  943. U32 const totalBits = nbBits + consumedBits;
  944. HUF_fillDTableX2ForWeight(
  945. DTable + rankVal[w],
  946. sortedSymbols + begin, sortedSymbols + end,
  947. totalBits, targetLog,
  948. baseSeq, /* level */ 2);
  949. }
  950. }
  951. }
  952. static void HUF_fillDTableX2(HUF_DEltX2* DTable, const U32 targetLog,
  953. const sortedSymbol_t* sortedList,
  954. const U32* rankStart, rankValCol_t* rankValOrigin, const U32 maxWeight,
  955. const U32 nbBitsBaseline)
  956. {
  957. U32* const rankVal = rankValOrigin[0];
  958. const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
  959. const U32 minBits = nbBitsBaseline - maxWeight;
  960. int w;
  961. int const wEnd = (int)maxWeight + 1;
  962. /* Fill DTable in order of weight. */
  963. for (w = 1; w < wEnd; ++w) {
  964. int const begin = (int)rankStart[w];
  965. int const end = (int)rankStart[w+1];
  966. U32 const nbBits = nbBitsBaseline - w;
  967. if (targetLog-nbBits >= minBits) {
  968. /* Enough room for a second symbol. */
  969. int start = rankVal[w];
  970. U32 const length = 1U << ((targetLog - nbBits) & 0x1F /* quiet static-analyzer */);
  971. int minWeight = nbBits + scaleLog;
  972. int s;
  973. if (minWeight < 1) minWeight = 1;
  974. /* Fill the DTable for every symbol of weight w.
  975. * These symbols get at least 1 second symbol.
  976. */
  977. for (s = begin; s != end; ++s) {
  978. HUF_fillDTableX2Level2(
  979. DTable + start, targetLog, nbBits,
  980. rankValOrigin[nbBits], minWeight, wEnd,
  981. sortedList, rankStart,
  982. nbBitsBaseline, sortedList[s].symbol);
  983. start += length;
  984. }
  985. } else {
  986. /* Only a single symbol. */
  987. HUF_fillDTableX2ForWeight(
  988. DTable + rankVal[w],
  989. sortedList + begin, sortedList + end,
  990. nbBits, targetLog,
  991. /* baseSeq */ 0, /* level */ 1);
  992. }
  993. }
  994. }
  995. typedef struct {
  996. rankValCol_t rankVal[HUF_TABLELOG_MAX];
  997. U32 rankStats[HUF_TABLELOG_MAX + 1];
  998. U32 rankStart0[HUF_TABLELOG_MAX + 3];
  999. sortedSymbol_t sortedSymbol[HUF_SYMBOLVALUE_MAX + 1];
  1000. BYTE weightList[HUF_SYMBOLVALUE_MAX + 1];
  1001. U32 calleeWksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
  1002. } HUF_ReadDTableX2_Workspace;
  1003. size_t HUF_readDTableX2_wksp(HUF_DTable* DTable,
  1004. const void* src, size_t srcSize,
  1005. void* workSpace, size_t wkspSize, int flags)
  1006. {
  1007. U32 tableLog, maxW, nbSymbols;
  1008. DTableDesc dtd = HUF_getDTableDesc(DTable);
  1009. U32 maxTableLog = dtd.maxTableLog;
  1010. size_t iSize;
  1011. void* dtPtr = DTable+1; /* force compiler to avoid strict-aliasing */
  1012. HUF_DEltX2* const dt = (HUF_DEltX2*)dtPtr;
  1013. U32 *rankStart;
  1014. HUF_ReadDTableX2_Workspace* const wksp = (HUF_ReadDTableX2_Workspace*)workSpace;
  1015. if (sizeof(*wksp) > wkspSize) return ERROR(GENERIC);
  1016. rankStart = wksp->rankStart0 + 1;
  1017. ZSTD_memset(wksp->rankStats, 0, sizeof(wksp->rankStats));
  1018. ZSTD_memset(wksp->rankStart0, 0, sizeof(wksp->rankStart0));
  1019. DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(HUF_DTable)); /* if compiler fails here, assertion is wrong */
  1020. if (maxTableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
  1021. /* ZSTD_memset(weightList, 0, sizeof(weightList)); */ /* is not necessary, even though some analyzer complain ... */
  1022. iSize = HUF_readStats_wksp(wksp->weightList, HUF_SYMBOLVALUE_MAX + 1, wksp->rankStats, &nbSymbols, &tableLog, src, srcSize, wksp->calleeWksp, sizeof(wksp->calleeWksp), flags);
  1023. if (HUF_isError(iSize)) return iSize;
  1024. /* check result */
  1025. if (tableLog > maxTableLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
  1026. if (tableLog <= HUF_DECODER_FAST_TABLELOG && maxTableLog > HUF_DECODER_FAST_TABLELOG) maxTableLog = HUF_DECODER_FAST_TABLELOG;
  1027. /* find maxWeight */
  1028. for (maxW = tableLog; wksp->rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */
  1029. /* Get start index of each weight */
  1030. { U32 w, nextRankStart = 0;
  1031. for (w=1; w<maxW+1; w++) {
  1032. U32 curr = nextRankStart;
  1033. nextRankStart += wksp->rankStats[w];
  1034. rankStart[w] = curr;
  1035. }
  1036. rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
  1037. rankStart[maxW+1] = nextRankStart;
  1038. }
  1039. /* sort symbols by weight */
  1040. { U32 s;
  1041. for (s=0; s<nbSymbols; s++) {
  1042. U32 const w = wksp->weightList[s];
  1043. U32 const r = rankStart[w]++;
  1044. wksp->sortedSymbol[r].symbol = (BYTE)s;
  1045. }
  1046. rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
  1047. }
  1048. /* Build rankVal */
  1049. { U32* const rankVal0 = wksp->rankVal[0];
  1050. { int const rescale = (maxTableLog-tableLog) - 1; /* tableLog <= maxTableLog */
  1051. U32 nextRankVal = 0;
  1052. U32 w;
  1053. for (w=1; w<maxW+1; w++) {
  1054. U32 curr = nextRankVal;
  1055. nextRankVal += wksp->rankStats[w] << (w+rescale);
  1056. rankVal0[w] = curr;
  1057. } }
  1058. { U32 const minBits = tableLog+1 - maxW;
  1059. U32 consumed;
  1060. for (consumed = minBits; consumed < maxTableLog - minBits + 1; consumed++) {
  1061. U32* const rankValPtr = wksp->rankVal[consumed];
  1062. U32 w;
  1063. for (w = 1; w < maxW+1; w++) {
  1064. rankValPtr[w] = rankVal0[w] >> consumed;
  1065. } } } }
  1066. HUF_fillDTableX2(dt, maxTableLog,
  1067. wksp->sortedSymbol,
  1068. wksp->rankStart0, wksp->rankVal, maxW,
  1069. tableLog+1);
  1070. dtd.tableLog = (BYTE)maxTableLog;
  1071. dtd.tableType = 1;
  1072. ZSTD_memcpy(DTable, &dtd, sizeof(dtd));
  1073. return iSize;
  1074. }
  1075. FORCE_INLINE_TEMPLATE U32
  1076. HUF_decodeSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog)
  1077. {
  1078. size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1079. ZSTD_memcpy(op, &dt[val].sequence, 2);
  1080. BIT_skipBits(DStream, dt[val].nbBits);
  1081. return dt[val].length;
  1082. }
  1083. FORCE_INLINE_TEMPLATE U32
  1084. HUF_decodeLastSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog)
  1085. {
  1086. size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1087. ZSTD_memcpy(op, &dt[val].sequence, 1);
  1088. if (dt[val].length==1) {
  1089. BIT_skipBits(DStream, dt[val].nbBits);
  1090. } else {
  1091. if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
  1092. BIT_skipBits(DStream, dt[val].nbBits);
  1093. if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
  1094. /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */
  1095. DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8);
  1096. }
  1097. }
  1098. return 1;
  1099. }
  1100. #define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
  1101. ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
  1102. #define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
  1103. if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
  1104. ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
  1105. #define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
  1106. if (MEM_64bits()) \
  1107. ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
  1108. HINT_INLINE size_t
  1109. HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd,
  1110. const HUF_DEltX2* const dt, const U32 dtLog)
  1111. {
  1112. BYTE* const pStart = p;
  1113. /* up to 8 symbols at a time */
  1114. if ((size_t)(pEnd - p) >= sizeof(bitDPtr->bitContainer)) {
  1115. if (dtLog <= 11 && MEM_64bits()) {
  1116. /* up to 10 symbols at a time */
  1117. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-9)) {
  1118. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1119. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1120. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1121. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1122. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1123. }
  1124. } else {
  1125. /* up to 8 symbols at a time */
  1126. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-(sizeof(bitDPtr->bitContainer)-1))) {
  1127. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1128. HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
  1129. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1130. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1131. }
  1132. }
  1133. } else {
  1134. BIT_reloadDStream(bitDPtr);
  1135. }
  1136. /* closer to end : up to 2 symbols at a time */
  1137. if ((size_t)(pEnd - p) >= 2) {
  1138. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p <= pEnd-2))
  1139. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1140. while (p <= pEnd-2)
  1141. HUF_DECODE_SYMBOLX2_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
  1142. }
  1143. if (p < pEnd)
  1144. p += HUF_decodeLastSymbolX2(p, bitDPtr, dt, dtLog);
  1145. return p-pStart;
  1146. }
  1147. FORCE_INLINE_TEMPLATE size_t
  1148. HUF_decompress1X2_usingDTable_internal_body(
  1149. void* dst, size_t dstSize,
  1150. const void* cSrc, size_t cSrcSize,
  1151. const HUF_DTable* DTable)
  1152. {
  1153. BIT_DStream_t bitD;
  1154. /* Init */
  1155. CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );
  1156. /* decode */
  1157. { BYTE* const ostart = (BYTE*) dst;
  1158. BYTE* const oend = ostart + dstSize;
  1159. const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */
  1160. const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
  1161. DTableDesc const dtd = HUF_getDTableDesc(DTable);
  1162. HUF_decodeStreamX2(ostart, &bitD, oend, dt, dtd.tableLog);
  1163. }
  1164. /* check */
  1165. if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected);
  1166. /* decoded size */
  1167. return dstSize;
  1168. }
  1169. /* HUF_decompress4X2_usingDTable_internal_body():
  1170. * Conditions:
  1171. * @dstSize >= 6
  1172. */
  1173. FORCE_INLINE_TEMPLATE size_t
  1174. HUF_decompress4X2_usingDTable_internal_body(
  1175. void* dst, size_t dstSize,
  1176. const void* cSrc, size_t cSrcSize,
  1177. const HUF_DTable* DTable)
  1178. {
  1179. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1180. { const BYTE* const istart = (const BYTE*) cSrc;
  1181. BYTE* const ostart = (BYTE*) dst;
  1182. BYTE* const oend = ostart + dstSize;
  1183. BYTE* const olimit = oend - (sizeof(size_t)-1);
  1184. const void* const dtPtr = DTable+1;
  1185. const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
  1186. /* Init */
  1187. BIT_DStream_t bitD1;
  1188. BIT_DStream_t bitD2;
  1189. BIT_DStream_t bitD3;
  1190. BIT_DStream_t bitD4;
  1191. size_t const length1 = MEM_readLE16(istart);
  1192. size_t const length2 = MEM_readLE16(istart+2);
  1193. size_t const length3 = MEM_readLE16(istart+4);
  1194. size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1195. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1196. const BYTE* const istart2 = istart1 + length1;
  1197. const BYTE* const istart3 = istart2 + length2;
  1198. const BYTE* const istart4 = istart3 + length3;
  1199. size_t const segmentSize = (dstSize+3) / 4;
  1200. BYTE* const opStart2 = ostart + segmentSize;
  1201. BYTE* const opStart3 = opStart2 + segmentSize;
  1202. BYTE* const opStart4 = opStart3 + segmentSize;
  1203. BYTE* op1 = ostart;
  1204. BYTE* op2 = opStart2;
  1205. BYTE* op3 = opStart3;
  1206. BYTE* op4 = opStart4;
  1207. U32 endSignal = 1;
  1208. DTableDesc const dtd = HUF_getDTableDesc(DTable);
  1209. U32 const dtLog = dtd.tableLog;
  1210. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1211. if (opStart4 > oend) return ERROR(corruption_detected); /* overflow */
  1212. if (dstSize < 6) return ERROR(corruption_detected); /* stream 4-split doesn't work */
  1213. CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
  1214. CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
  1215. CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
  1216. CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );
  1217. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1218. if ((size_t)(oend - op4) >= sizeof(size_t)) {
  1219. for ( ; (endSignal) & (op4 < olimit); ) {
  1220. #if defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
  1221. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1222. HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
  1223. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1224. HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
  1225. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1226. HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
  1227. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1228. HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
  1229. endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished;
  1230. endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished;
  1231. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1232. HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
  1233. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1234. HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
  1235. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1236. HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
  1237. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1238. HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
  1239. endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished;
  1240. endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished;
  1241. #else
  1242. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1243. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1244. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1245. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1246. HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
  1247. HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
  1248. HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
  1249. HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
  1250. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1251. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1252. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1253. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1254. HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
  1255. HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
  1256. HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
  1257. HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
  1258. endSignal = (U32)LIKELY((U32)
  1259. (BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished)
  1260. & (BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished)
  1261. & (BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished)
  1262. & (BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished));
  1263. #endif
  1264. }
  1265. }
  1266. /* check corruption */
  1267. if (op1 > opStart2) return ERROR(corruption_detected);
  1268. if (op2 > opStart3) return ERROR(corruption_detected);
  1269. if (op3 > opStart4) return ERROR(corruption_detected);
  1270. /* note : op4 already verified within main loop */
  1271. /* finish bitStreams one by one */
  1272. HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
  1273. HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
  1274. HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
  1275. HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
  1276. /* check */
  1277. { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1278. if (!endCheck) return ERROR(corruption_detected); }
  1279. /* decoded size */
  1280. return dstSize;
  1281. }
  1282. }
  1283. #if HUF_NEED_BMI2_FUNCTION
  1284. static BMI2_TARGET_ATTRIBUTE
  1285. size_t HUF_decompress4X2_usingDTable_internal_bmi2(void* dst, size_t dstSize, void const* cSrc,
  1286. size_t cSrcSize, HUF_DTable const* DTable) {
  1287. return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
  1288. }
  1289. #endif
  1290. static
  1291. size_t HUF_decompress4X2_usingDTable_internal_default(void* dst, size_t dstSize, void const* cSrc,
  1292. size_t cSrcSize, HUF_DTable const* DTable) {
  1293. return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable);
  1294. }
  1295. #if ZSTD_ENABLE_ASM_X86_64_BMI2
  1296. HUF_ASM_DECL void HUF_decompress4X2_usingDTable_internal_fast_asm_loop(HUF_DecompressFastArgs* args) ZSTDLIB_HIDDEN;
  1297. #endif
  1298. static HUF_FAST_BMI2_ATTRS
  1299. void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* args)
  1300. {
  1301. U64 bits[4];
  1302. BYTE const* ip[4];
  1303. BYTE* op[4];
  1304. BYTE* oend[4];
  1305. HUF_DEltX2 const* const dtable = (HUF_DEltX2 const*)args->dt;
  1306. BYTE const* const ilimit = args->ilimit;
  1307. /* Copy the arguments to local registers. */
  1308. ZSTD_memcpy(&bits, &args->bits, sizeof(bits));
  1309. ZSTD_memcpy((void*)(&ip), &args->ip, sizeof(ip));
  1310. ZSTD_memcpy(&op, &args->op, sizeof(op));
  1311. oend[0] = op[1];
  1312. oend[1] = op[2];
  1313. oend[2] = op[3];
  1314. oend[3] = args->oend;
  1315. assert(MEM_isLittleEndian());
  1316. assert(!MEM_32bits());
  1317. for (;;) {
  1318. BYTE* olimit;
  1319. int stream;
  1320. int symbol;
  1321. /* Assert loop preconditions */
  1322. #ifndef NDEBUG
  1323. for (stream = 0; stream < 4; ++stream) {
  1324. assert(op[stream] <= oend[stream]);
  1325. assert(ip[stream] >= ilimit);
  1326. }
  1327. #endif
  1328. /* Compute olimit */
  1329. {
  1330. /* Each loop does 5 table lookups for each of the 4 streams.
  1331. * Each table lookup consumes up to 11 bits of input, and produces
  1332. * up to 2 bytes of output.
  1333. */
  1334. /* We can consume up to 7 bytes of input per iteration per stream.
  1335. * We also know that each input pointer is >= ip[0]. So we can run
  1336. * iters loops before running out of input.
  1337. */
  1338. size_t iters = (size_t)(ip[0] - ilimit) / 7;
  1339. /* Each iteration can produce up to 10 bytes of output per stream.
  1340. * Each output stream my advance at different rates. So take the
  1341. * minimum number of safe iterations among all the output streams.
  1342. */
  1343. for (stream = 0; stream < 4; ++stream) {
  1344. size_t const oiters = (size_t)(oend[stream] - op[stream]) / 10;
  1345. iters = MIN(iters, oiters);
  1346. }
  1347. /* Each iteration produces at least 5 output symbols. So until
  1348. * op[3] crosses olimit, we know we haven't executed iters
  1349. * iterations yet. This saves us maintaining an iters counter,
  1350. * at the expense of computing the remaining # of iterations
  1351. * more frequently.
  1352. */
  1353. olimit = op[3] + (iters * 5);
  1354. /* Exit the fast decoding loop if we are too close to the end. */
  1355. if (op[3] + 10 > olimit)
  1356. break;
  1357. /* Exit the decoding loop if any input pointer has crossed the
  1358. * previous one. This indicates corruption, and a precondition
  1359. * to our loop is that ip[i] >= ip[0].
  1360. */
  1361. for (stream = 1; stream < 4; ++stream) {
  1362. if (ip[stream] < ip[stream - 1])
  1363. goto _out;
  1364. }
  1365. }
  1366. #ifndef NDEBUG
  1367. for (stream = 1; stream < 4; ++stream) {
  1368. assert(ip[stream] >= ip[stream - 1]);
  1369. }
  1370. #endif
  1371. do {
  1372. /* Do 5 table lookups for each of the first 3 streams */
  1373. for (symbol = 0; symbol < 5; ++symbol) {
  1374. for (stream = 0; stream < 3; ++stream) {
  1375. int const index = (int)(bits[stream] >> 53);
  1376. HUF_DEltX2 const entry = dtable[index];
  1377. MEM_write16(op[stream], entry.sequence);
  1378. bits[stream] <<= (entry.nbBits);
  1379. op[stream] += (entry.length);
  1380. }
  1381. }
  1382. /* Do 1 table lookup from the final stream */
  1383. {
  1384. int const index = (int)(bits[3] >> 53);
  1385. HUF_DEltX2 const entry = dtable[index];
  1386. MEM_write16(op[3], entry.sequence);
  1387. bits[3] <<= (entry.nbBits);
  1388. op[3] += (entry.length);
  1389. }
  1390. /* Do 4 table lookups from the final stream & reload bitstreams */
  1391. for (stream = 0; stream < 4; ++stream) {
  1392. /* Do a table lookup from the final stream.
  1393. * This is interleaved with the reloading to reduce register
  1394. * pressure. This shouldn't be necessary, but compilers can
  1395. * struggle with codegen with high register pressure.
  1396. */
  1397. {
  1398. int const index = (int)(bits[3] >> 53);
  1399. HUF_DEltX2 const entry = dtable[index];
  1400. MEM_write16(op[3], entry.sequence);
  1401. bits[3] <<= (entry.nbBits);
  1402. op[3] += (entry.length);
  1403. }
  1404. /* Reload the bistreams. The final bitstream must be reloaded
  1405. * after the 5th symbol was decoded.
  1406. */
  1407. {
  1408. int const ctz = ZSTD_countTrailingZeros64(bits[stream]);
  1409. int const nbBits = ctz & 7;
  1410. int const nbBytes = ctz >> 3;
  1411. ip[stream] -= nbBytes;
  1412. bits[stream] = MEM_read64(ip[stream]) | 1;
  1413. bits[stream] <<= nbBits;
  1414. }
  1415. }
  1416. } while (op[3] < olimit);
  1417. }
  1418. _out:
  1419. /* Save the final values of each of the state variables back to args. */
  1420. ZSTD_memcpy(&args->bits, &bits, sizeof(bits));
  1421. ZSTD_memcpy((void*)(&args->ip), &ip, sizeof(ip));
  1422. ZSTD_memcpy(&args->op, &op, sizeof(op));
  1423. }
  1424. static HUF_FAST_BMI2_ATTRS size_t
  1425. HUF_decompress4X2_usingDTable_internal_fast(
  1426. void* dst, size_t dstSize,
  1427. const void* cSrc, size_t cSrcSize,
  1428. const HUF_DTable* DTable,
  1429. HUF_DecompressFastLoopFn loopFn) {
  1430. void const* dt = DTable + 1;
  1431. const BYTE* const iend = (const BYTE*)cSrc + 6;
  1432. BYTE* const oend = (BYTE*)dst + dstSize;
  1433. HUF_DecompressFastArgs args;
  1434. {
  1435. size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable);
  1436. FORWARD_IF_ERROR(ret, "Failed to init asm args");
  1437. if (ret == 0)
  1438. return 0;
  1439. }
  1440. assert(args.ip[0] >= args.ilimit);
  1441. loopFn(&args);
  1442. /* note : op4 already verified within main loop */
  1443. assert(args.ip[0] >= iend);
  1444. assert(args.ip[1] >= iend);
  1445. assert(args.ip[2] >= iend);
  1446. assert(args.ip[3] >= iend);
  1447. assert(args.op[3] <= oend);
  1448. (void)iend;
  1449. /* finish bitStreams one by one */
  1450. {
  1451. size_t const segmentSize = (dstSize+3) / 4;
  1452. BYTE* segmentEnd = (BYTE*)dst;
  1453. int i;
  1454. for (i = 0; i < 4; ++i) {
  1455. BIT_DStream_t bit;
  1456. if (segmentSize <= (size_t)(oend - segmentEnd))
  1457. segmentEnd += segmentSize;
  1458. else
  1459. segmentEnd = oend;
  1460. FORWARD_IF_ERROR(HUF_initRemainingDStream(&bit, &args, i, segmentEnd), "corruption");
  1461. args.op[i] += HUF_decodeStreamX2(args.op[i], &bit, segmentEnd, (HUF_DEltX2 const*)dt, HUF_DECODER_FAST_TABLELOG);
  1462. if (args.op[i] != segmentEnd)
  1463. return ERROR(corruption_detected);
  1464. }
  1465. }
  1466. /* decoded size */
  1467. return dstSize;
  1468. }
  1469. static size_t HUF_decompress4X2_usingDTable_internal(void* dst, size_t dstSize, void const* cSrc,
  1470. size_t cSrcSize, HUF_DTable const* DTable, int flags)
  1471. {
  1472. HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X2_usingDTable_internal_default;
  1473. HUF_DecompressFastLoopFn loopFn = HUF_decompress4X2_usingDTable_internal_fast_c_loop;
  1474. #if DYNAMIC_BMI2
  1475. if (flags & HUF_flags_bmi2) {
  1476. fallbackFn = HUF_decompress4X2_usingDTable_internal_bmi2;
  1477. # if ZSTD_ENABLE_ASM_X86_64_BMI2
  1478. if (!(flags & HUF_flags_disableAsm)) {
  1479. loopFn = HUF_decompress4X2_usingDTable_internal_fast_asm_loop;
  1480. }
  1481. # endif
  1482. } else {
  1483. return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable);
  1484. }
  1485. #endif
  1486. #if ZSTD_ENABLE_ASM_X86_64_BMI2 && defined(__BMI2__)
  1487. if (!(flags & HUF_flags_disableAsm)) {
  1488. loopFn = HUF_decompress4X2_usingDTable_internal_fast_asm_loop;
  1489. }
  1490. #endif
  1491. if (!(flags & HUF_flags_disableFast)) {
  1492. size_t const ret = HUF_decompress4X2_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn);
  1493. if (ret != 0)
  1494. return ret;
  1495. }
  1496. return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable);
  1497. }
  1498. HUF_DGEN(HUF_decompress1X2_usingDTable_internal)
  1499. size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize,
  1500. const void* cSrc, size_t cSrcSize,
  1501. void* workSpace, size_t wkspSize, int flags)
  1502. {
  1503. const BYTE* ip = (const BYTE*) cSrc;
  1504. size_t const hSize = HUF_readDTableX2_wksp(DCtx, cSrc, cSrcSize,
  1505. workSpace, wkspSize, flags);
  1506. if (HUF_isError(hSize)) return hSize;
  1507. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1508. ip += hSize; cSrcSize -= hSize;
  1509. return HUF_decompress1X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, flags);
  1510. }
  1511. static size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
  1512. const void* cSrc, size_t cSrcSize,
  1513. void* workSpace, size_t wkspSize, int flags)
  1514. {
  1515. const BYTE* ip = (const BYTE*) cSrc;
  1516. size_t hSize = HUF_readDTableX2_wksp(dctx, cSrc, cSrcSize,
  1517. workSpace, wkspSize, flags);
  1518. if (HUF_isError(hSize)) return hSize;
  1519. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1520. ip += hSize; cSrcSize -= hSize;
  1521. return HUF_decompress4X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, flags);
  1522. }
  1523. #endif /* HUF_FORCE_DECOMPRESS_X1 */
  1524. /* ***********************************/
  1525. /* Universal decompression selectors */
  1526. /* ***********************************/
  1527. #if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2)
  1528. typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
  1529. static const algo_time_t algoTime[16 /* Quantization */][2 /* single, double */] =
  1530. {
  1531. /* single, double, quad */
  1532. {{0,0}, {1,1}}, /* Q==0 : impossible */
  1533. {{0,0}, {1,1}}, /* Q==1 : impossible */
  1534. {{ 150,216}, { 381,119}}, /* Q == 2 : 12-18% */
  1535. {{ 170,205}, { 514,112}}, /* Q == 3 : 18-25% */
  1536. {{ 177,199}, { 539,110}}, /* Q == 4 : 25-32% */
  1537. {{ 197,194}, { 644,107}}, /* Q == 5 : 32-38% */
  1538. {{ 221,192}, { 735,107}}, /* Q == 6 : 38-44% */
  1539. {{ 256,189}, { 881,106}}, /* Q == 7 : 44-50% */
  1540. {{ 359,188}, {1167,109}}, /* Q == 8 : 50-56% */
  1541. {{ 582,187}, {1570,114}}, /* Q == 9 : 56-62% */
  1542. {{ 688,187}, {1712,122}}, /* Q ==10 : 62-69% */
  1543. {{ 825,186}, {1965,136}}, /* Q ==11 : 69-75% */
  1544. {{ 976,185}, {2131,150}}, /* Q ==12 : 75-81% */
  1545. {{1180,186}, {2070,175}}, /* Q ==13 : 81-87% */
  1546. {{1377,185}, {1731,202}}, /* Q ==14 : 87-93% */
  1547. {{1412,185}, {1695,202}}, /* Q ==15 : 93-99% */
  1548. };
  1549. #endif
  1550. /** HUF_selectDecoder() :
  1551. * Tells which decoder is likely to decode faster,
  1552. * based on a set of pre-computed metrics.
  1553. * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .
  1554. * Assumption : 0 < dstSize <= 128 KB */
  1555. U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize)
  1556. {
  1557. assert(dstSize > 0);
  1558. assert(dstSize <= 128*1024);
  1559. #if defined(HUF_FORCE_DECOMPRESS_X1)
  1560. (void)dstSize;
  1561. (void)cSrcSize;
  1562. return 0;
  1563. #elif defined(HUF_FORCE_DECOMPRESS_X2)
  1564. (void)dstSize;
  1565. (void)cSrcSize;
  1566. return 1;
  1567. #else
  1568. /* decoder timing evaluation */
  1569. { U32 const Q = (cSrcSize >= dstSize) ? 15 : (U32)(cSrcSize * 16 / dstSize); /* Q < 16 */
  1570. U32 const D256 = (U32)(dstSize >> 8);
  1571. U32 const DTime0 = algoTime[Q][0].tableTime + (algoTime[Q][0].decode256Time * D256);
  1572. U32 DTime1 = algoTime[Q][1].tableTime + (algoTime[Q][1].decode256Time * D256);
  1573. DTime1 += DTime1 >> 5; /* small advantage to algorithm using less memory, to reduce cache eviction */
  1574. return DTime1 < DTime0;
  1575. }
  1576. #endif
  1577. }
  1578. size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
  1579. const void* cSrc, size_t cSrcSize,
  1580. void* workSpace, size_t wkspSize, int flags)
  1581. {
  1582. /* validation checks */
  1583. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  1584. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  1585. if (cSrcSize == dstSize) { ZSTD_memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  1586. if (cSrcSize == 1) { ZSTD_memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  1587. { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
  1588. #if defined(HUF_FORCE_DECOMPRESS_X1)
  1589. (void)algoNb;
  1590. assert(algoNb == 0);
  1591. return HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc,
  1592. cSrcSize, workSpace, wkspSize, flags);
  1593. #elif defined(HUF_FORCE_DECOMPRESS_X2)
  1594. (void)algoNb;
  1595. assert(algoNb == 1);
  1596. return HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
  1597. cSrcSize, workSpace, wkspSize, flags);
  1598. #else
  1599. return algoNb ? HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
  1600. cSrcSize, workSpace, wkspSize, flags):
  1601. HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc,
  1602. cSrcSize, workSpace, wkspSize, flags);
  1603. #endif
  1604. }
  1605. }
  1606. size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags)
  1607. {
  1608. DTableDesc const dtd = HUF_getDTableDesc(DTable);
  1609. #if defined(HUF_FORCE_DECOMPRESS_X1)
  1610. (void)dtd;
  1611. assert(dtd.tableType == 0);
  1612. return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags);
  1613. #elif defined(HUF_FORCE_DECOMPRESS_X2)
  1614. (void)dtd;
  1615. assert(dtd.tableType == 1);
  1616. return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags);
  1617. #else
  1618. return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags) :
  1619. HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags);
  1620. #endif
  1621. }
  1622. #ifndef HUF_FORCE_DECOMPRESS_X2
  1623. size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags)
  1624. {
  1625. const BYTE* ip = (const BYTE*) cSrc;
  1626. size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize, flags);
  1627. if (HUF_isError(hSize)) return hSize;
  1628. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1629. ip += hSize; cSrcSize -= hSize;
  1630. return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, flags);
  1631. }
  1632. #endif
  1633. size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags)
  1634. {
  1635. DTableDesc const dtd = HUF_getDTableDesc(DTable);
  1636. #if defined(HUF_FORCE_DECOMPRESS_X1)
  1637. (void)dtd;
  1638. assert(dtd.tableType == 0);
  1639. return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags);
  1640. #elif defined(HUF_FORCE_DECOMPRESS_X2)
  1641. (void)dtd;
  1642. assert(dtd.tableType == 1);
  1643. return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags);
  1644. #else
  1645. return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags) :
  1646. HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, flags);
  1647. #endif
  1648. }
  1649. size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags)
  1650. {
  1651. /* validation checks */
  1652. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  1653. if (cSrcSize == 0) return ERROR(corruption_detected);
  1654. { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
  1655. #if defined(HUF_FORCE_DECOMPRESS_X1)
  1656. (void)algoNb;
  1657. assert(algoNb == 0);
  1658. return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags);
  1659. #elif defined(HUF_FORCE_DECOMPRESS_X2)
  1660. (void)algoNb;
  1661. assert(algoNb == 1);
  1662. return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags);
  1663. #else
  1664. return algoNb ? HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags) :
  1665. HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, flags);
  1666. #endif
  1667. }
  1668. }