zstd_v01.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. /*
  2. * Copyright (c) Yann Collet, 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. /******************************************
  11. * Includes
  12. ******************************************/
  13. #include <stddef.h> /* size_t, ptrdiff_t */
  14. #include "zstd_v01.h"
  15. #include "../common/compiler.h"
  16. #include "../common/error_private.h"
  17. /******************************************
  18. * Static allocation
  19. ******************************************/
  20. /* You can statically allocate FSE CTable/DTable as a table of unsigned using below macro */
  21. #define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
  22. /* You can statically allocate Huff0 DTable as a table of unsigned short using below macro */
  23. #define HUF_DTABLE_SIZE_U16(maxTableLog) (1 + (1<<maxTableLog))
  24. #define HUF_CREATE_STATIC_DTABLE(DTable, maxTableLog) \
  25. unsigned short DTable[HUF_DTABLE_SIZE_U16(maxTableLog)] = { maxTableLog }
  26. /******************************************
  27. * Error Management
  28. ******************************************/
  29. #define FSE_LIST_ERRORS(ITEM) \
  30. ITEM(FSE_OK_NoError) ITEM(FSE_ERROR_GENERIC) \
  31. ITEM(FSE_ERROR_tableLog_tooLarge) ITEM(FSE_ERROR_maxSymbolValue_tooLarge) ITEM(FSE_ERROR_maxSymbolValue_tooSmall) \
  32. ITEM(FSE_ERROR_dstSize_tooSmall) ITEM(FSE_ERROR_srcSize_wrong)\
  33. ITEM(FSE_ERROR_corruptionDetected) \
  34. ITEM(FSE_ERROR_maxCode)
  35. #define FSE_GENERATE_ENUM(ENUM) ENUM,
  36. typedef enum { FSE_LIST_ERRORS(FSE_GENERATE_ENUM) } FSE_errorCodes; /* enum is exposed, to detect & handle specific errors; compare function result to -enum value */
  37. /******************************************
  38. * FSE symbol compression API
  39. ******************************************/
  40. /*
  41. This API consists of small unitary functions, which highly benefit from being inlined.
  42. You will want to enable link-time-optimization to ensure these functions are properly inlined in your binary.
  43. Visual seems to do it automatically.
  44. For gcc or clang, you'll need to add -flto flag at compilation and linking stages.
  45. If none of these solutions is applicable, include "fse.c" directly.
  46. */
  47. typedef unsigned FSE_CTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  48. typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  49. typedef struct
  50. {
  51. size_t bitContainer;
  52. int bitPos;
  53. char* startPtr;
  54. char* ptr;
  55. char* endPtr;
  56. } FSE_CStream_t;
  57. typedef struct
  58. {
  59. ptrdiff_t value;
  60. const void* stateTable;
  61. const void* symbolTT;
  62. unsigned stateLog;
  63. } FSE_CState_t;
  64. typedef struct
  65. {
  66. size_t bitContainer;
  67. unsigned bitsConsumed;
  68. const char* ptr;
  69. const char* start;
  70. } FSE_DStream_t;
  71. typedef struct
  72. {
  73. size_t state;
  74. const void* table; /* precise table may vary, depending on U16 */
  75. } FSE_DState_t;
  76. typedef enum { FSE_DStream_unfinished = 0,
  77. FSE_DStream_endOfBuffer = 1,
  78. FSE_DStream_completed = 2,
  79. FSE_DStream_tooFar = 3 } FSE_DStream_status; /* result of FSE_reloadDStream() */
  80. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... ?! */
  81. /****************************************************************
  82. * Tuning parameters
  83. ****************************************************************/
  84. /* MEMORY_USAGE :
  85. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  86. * Increasing memory usage improves compression ratio
  87. * Reduced memory usage can improve speed, due to cache effect
  88. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  89. #define FSE_MAX_MEMORY_USAGE 14
  90. #define FSE_DEFAULT_MEMORY_USAGE 13
  91. /* FSE_MAX_SYMBOL_VALUE :
  92. * Maximum symbol value authorized.
  93. * Required for proper stack allocation */
  94. #define FSE_MAX_SYMBOL_VALUE 255
  95. /****************************************************************
  96. * template functions type & suffix
  97. ****************************************************************/
  98. #define FSE_FUNCTION_TYPE BYTE
  99. #define FSE_FUNCTION_EXTENSION
  100. /****************************************************************
  101. * Byte symbol type
  102. ****************************************************************/
  103. typedef struct
  104. {
  105. unsigned short newState;
  106. unsigned char symbol;
  107. unsigned char nbBits;
  108. } FSE_decode_t; /* size == U32 */
  109. /****************************************************************
  110. * Compiler specifics
  111. ****************************************************************/
  112. #ifdef _MSC_VER /* Visual Studio */
  113. # define FORCE_INLINE static __forceinline
  114. # include <intrin.h> /* For Visual 2005 */
  115. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  116. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  117. #else
  118. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  119. # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  120. # ifdef __GNUC__
  121. # define FORCE_INLINE static inline __attribute__((always_inline))
  122. # else
  123. # define FORCE_INLINE static inline
  124. # endif
  125. # else
  126. # define FORCE_INLINE static
  127. # endif /* __STDC_VERSION__ */
  128. #endif
  129. /****************************************************************
  130. * Includes
  131. ****************************************************************/
  132. #include <stdlib.h> /* malloc, free, qsort */
  133. #include <string.h> /* memcpy, memset */
  134. #include <stdio.h> /* printf (debug) */
  135. #ifndef MEM_ACCESS_MODULE
  136. #define MEM_ACCESS_MODULE
  137. /****************************************************************
  138. * Basic Types
  139. *****************************************************************/
  140. #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  141. # include <stdint.h>
  142. typedef uint8_t BYTE;
  143. typedef uint16_t U16;
  144. typedef int16_t S16;
  145. typedef uint32_t U32;
  146. typedef int32_t S32;
  147. typedef uint64_t U64;
  148. typedef int64_t S64;
  149. #else
  150. typedef unsigned char BYTE;
  151. typedef unsigned short U16;
  152. typedef signed short S16;
  153. typedef unsigned int U32;
  154. typedef signed int S32;
  155. typedef unsigned long long U64;
  156. typedef signed long long S64;
  157. #endif
  158. #endif /* MEM_ACCESS_MODULE */
  159. /****************************************************************
  160. * Memory I/O
  161. *****************************************************************/
  162. static unsigned FSE_32bits(void)
  163. {
  164. return sizeof(void*)==4;
  165. }
  166. static unsigned FSE_isLittleEndian(void)
  167. {
  168. const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  169. return one.c[0];
  170. }
  171. static U16 FSE_read16(const void* memPtr)
  172. {
  173. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  174. }
  175. static U32 FSE_read32(const void* memPtr)
  176. {
  177. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  178. }
  179. static U64 FSE_read64(const void* memPtr)
  180. {
  181. U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
  182. }
  183. static U16 FSE_readLE16(const void* memPtr)
  184. {
  185. if (FSE_isLittleEndian())
  186. return FSE_read16(memPtr);
  187. else
  188. {
  189. const BYTE* p = (const BYTE*)memPtr;
  190. return (U16)(p[0] + (p[1]<<8));
  191. }
  192. }
  193. static U32 FSE_readLE32(const void* memPtr)
  194. {
  195. if (FSE_isLittleEndian())
  196. return FSE_read32(memPtr);
  197. else
  198. {
  199. const BYTE* p = (const BYTE*)memPtr;
  200. return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
  201. }
  202. }
  203. static U64 FSE_readLE64(const void* memPtr)
  204. {
  205. if (FSE_isLittleEndian())
  206. return FSE_read64(memPtr);
  207. else
  208. {
  209. const BYTE* p = (const BYTE*)memPtr;
  210. return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24)
  211. + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56));
  212. }
  213. }
  214. static size_t FSE_readLEST(const void* memPtr)
  215. {
  216. if (FSE_32bits())
  217. return (size_t)FSE_readLE32(memPtr);
  218. else
  219. return (size_t)FSE_readLE64(memPtr);
  220. }
  221. /****************************************************************
  222. * Constants
  223. *****************************************************************/
  224. #define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
  225. #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
  226. #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
  227. #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
  228. #define FSE_MIN_TABLELOG 5
  229. #define FSE_TABLELOG_ABSOLUTE_MAX 15
  230. #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
  231. #error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
  232. #endif
  233. /****************************************************************
  234. * Error Management
  235. ****************************************************************/
  236. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  237. /****************************************************************
  238. * Complex types
  239. ****************************************************************/
  240. typedef struct
  241. {
  242. int deltaFindState;
  243. U32 deltaNbBits;
  244. } FSE_symbolCompressionTransform; /* total 8 bytes */
  245. typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
  246. /****************************************************************
  247. * Internal functions
  248. ****************************************************************/
  249. FORCE_INLINE unsigned FSE_highbit32 (U32 val)
  250. {
  251. # if defined(_MSC_VER) /* Visual */
  252. unsigned long r;
  253. return _BitScanReverse(&r, val) ? (unsigned)r : 0;
  254. # elif defined(__GNUC__) && (GCC_VERSION >= 304) /* GCC Intrinsic */
  255. return __builtin_clz (val) ^ 31;
  256. # else /* Software version */
  257. static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
  258. U32 v = val;
  259. unsigned r;
  260. v |= v >> 1;
  261. v |= v >> 2;
  262. v |= v >> 4;
  263. v |= v >> 8;
  264. v |= v >> 16;
  265. r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  266. return r;
  267. # endif
  268. }
  269. /****************************************************************
  270. * Templates
  271. ****************************************************************/
  272. /*
  273. designed to be included
  274. for type-specific functions (template emulation in C)
  275. Objective is to write these functions only once, for improved maintenance
  276. */
  277. /* safety checks */
  278. #ifndef FSE_FUNCTION_EXTENSION
  279. # error "FSE_FUNCTION_EXTENSION must be defined"
  280. #endif
  281. #ifndef FSE_FUNCTION_TYPE
  282. # error "FSE_FUNCTION_TYPE must be defined"
  283. #endif
  284. /* Function names */
  285. #define FSE_CAT(X,Y) X##Y
  286. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  287. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  288. static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
  289. #define FSE_DECODE_TYPE FSE_decode_t
  290. typedef struct {
  291. U16 tableLog;
  292. U16 fastMode;
  293. } FSE_DTableHeader; /* sizeof U32 */
  294. static size_t FSE_buildDTable
  295. (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  296. {
  297. void* ptr = dt;
  298. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  299. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*)(ptr) + 1; /* because dt is unsigned, 32-bits aligned on 32-bits */
  300. const U32 tableSize = 1 << tableLog;
  301. const U32 tableMask = tableSize-1;
  302. const U32 step = FSE_tableStep(tableSize);
  303. U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
  304. U32 position = 0;
  305. U32 highThreshold = tableSize-1;
  306. const S16 largeLimit= (S16)(1 << (tableLog-1));
  307. U32 noLarge = 1;
  308. U32 s;
  309. /* Sanity Checks */
  310. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return (size_t)-FSE_ERROR_maxSymbolValue_tooLarge;
  311. if (tableLog > FSE_MAX_TABLELOG) return (size_t)-FSE_ERROR_tableLog_tooLarge;
  312. /* Init, lay down lowprob symbols */
  313. DTableH[0].tableLog = (U16)tableLog;
  314. for (s=0; s<=maxSymbolValue; s++)
  315. {
  316. if (normalizedCounter[s]==-1)
  317. {
  318. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  319. symbolNext[s] = 1;
  320. }
  321. else
  322. {
  323. if (normalizedCounter[s] >= largeLimit) noLarge=0;
  324. symbolNext[s] = normalizedCounter[s];
  325. }
  326. }
  327. /* Spread symbols */
  328. for (s=0; s<=maxSymbolValue; s++)
  329. {
  330. int i;
  331. for (i=0; i<normalizedCounter[s]; i++)
  332. {
  333. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  334. position = (position + step) & tableMask;
  335. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  336. }
  337. }
  338. if (position!=0) return (size_t)-FSE_ERROR_GENERIC; /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  339. /* Build Decoding table */
  340. {
  341. U32 i;
  342. for (i=0; i<tableSize; i++)
  343. {
  344. FSE_FUNCTION_TYPE symbol = (FSE_FUNCTION_TYPE)(tableDecode[i].symbol);
  345. U16 nextState = symbolNext[symbol]++;
  346. tableDecode[i].nbBits = (BYTE) (tableLog - FSE_highbit32 ((U32)nextState) );
  347. tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
  348. }
  349. }
  350. DTableH->fastMode = (U16)noLarge;
  351. return 0;
  352. }
  353. /******************************************
  354. * FSE byte symbol
  355. ******************************************/
  356. #ifndef FSE_COMMONDEFS_ONLY
  357. static unsigned FSE_isError(size_t code) { return (code > (size_t)(-FSE_ERROR_maxCode)); }
  358. static short FSE_abs(short a)
  359. {
  360. return a<0? -a : a;
  361. }
  362. /****************************************************************
  363. * Header bitstream management
  364. ****************************************************************/
  365. static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  366. const void* headerBuffer, size_t hbSize)
  367. {
  368. const BYTE* const istart = (const BYTE*) headerBuffer;
  369. const BYTE* const iend = istart + hbSize;
  370. const BYTE* ip = istart;
  371. int nbBits;
  372. int remaining;
  373. int threshold;
  374. U32 bitStream;
  375. int bitCount;
  376. unsigned charnum = 0;
  377. int previous0 = 0;
  378. if (hbSize < 4) return (size_t)-FSE_ERROR_srcSize_wrong;
  379. bitStream = FSE_readLE32(ip);
  380. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  381. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return (size_t)-FSE_ERROR_tableLog_tooLarge;
  382. bitStream >>= 4;
  383. bitCount = 4;
  384. *tableLogPtr = nbBits;
  385. remaining = (1<<nbBits)+1;
  386. threshold = 1<<nbBits;
  387. nbBits++;
  388. while ((remaining>1) && (charnum<=*maxSVPtr))
  389. {
  390. if (previous0)
  391. {
  392. unsigned n0 = charnum;
  393. while ((bitStream & 0xFFFF) == 0xFFFF)
  394. {
  395. n0+=24;
  396. if (ip < iend-5)
  397. {
  398. ip+=2;
  399. bitStream = FSE_readLE32(ip) >> bitCount;
  400. }
  401. else
  402. {
  403. bitStream >>= 16;
  404. bitCount+=16;
  405. }
  406. }
  407. while ((bitStream & 3) == 3)
  408. {
  409. n0+=3;
  410. bitStream>>=2;
  411. bitCount+=2;
  412. }
  413. n0 += bitStream & 3;
  414. bitCount += 2;
  415. if (n0 > *maxSVPtr) return (size_t)-FSE_ERROR_maxSymbolValue_tooSmall;
  416. while (charnum < n0) normalizedCounter[charnum++] = 0;
  417. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  418. {
  419. ip += bitCount>>3;
  420. bitCount &= 7;
  421. bitStream = FSE_readLE32(ip) >> bitCount;
  422. }
  423. else
  424. bitStream >>= 2;
  425. }
  426. {
  427. const short max = (short)((2*threshold-1)-remaining);
  428. short count;
  429. if ((bitStream & (threshold-1)) < (U32)max)
  430. {
  431. count = (short)(bitStream & (threshold-1));
  432. bitCount += nbBits-1;
  433. }
  434. else
  435. {
  436. count = (short)(bitStream & (2*threshold-1));
  437. if (count >= threshold) count -= max;
  438. bitCount += nbBits;
  439. }
  440. count--; /* extra accuracy */
  441. remaining -= FSE_abs(count);
  442. normalizedCounter[charnum++] = count;
  443. previous0 = !count;
  444. while (remaining < threshold)
  445. {
  446. nbBits--;
  447. threshold >>= 1;
  448. }
  449. {
  450. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  451. {
  452. ip += bitCount>>3;
  453. bitCount &= 7;
  454. }
  455. else
  456. {
  457. bitCount -= (int)(8 * (iend - 4 - ip));
  458. ip = iend - 4;
  459. }
  460. bitStream = FSE_readLE32(ip) >> (bitCount & 31);
  461. }
  462. }
  463. }
  464. if (remaining != 1) return (size_t)-FSE_ERROR_GENERIC;
  465. *maxSVPtr = charnum-1;
  466. ip += (bitCount+7)>>3;
  467. if ((size_t)(ip-istart) > hbSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  468. return ip-istart;
  469. }
  470. /*********************************************************
  471. * Decompression (Byte symbols)
  472. *********************************************************/
  473. static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
  474. {
  475. void* ptr = dt;
  476. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  477. FSE_decode_t* const cell = (FSE_decode_t*)(ptr) + 1; /* because dt is unsigned */
  478. DTableH->tableLog = 0;
  479. DTableH->fastMode = 0;
  480. cell->newState = 0;
  481. cell->symbol = symbolValue;
  482. cell->nbBits = 0;
  483. return 0;
  484. }
  485. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
  486. {
  487. void* ptr = dt;
  488. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  489. FSE_decode_t* const dinfo = (FSE_decode_t*)(ptr) + 1; /* because dt is unsigned */
  490. const unsigned tableSize = 1 << nbBits;
  491. const unsigned tableMask = tableSize - 1;
  492. const unsigned maxSymbolValue = tableMask;
  493. unsigned s;
  494. /* Sanity checks */
  495. if (nbBits < 1) return (size_t)-FSE_ERROR_GENERIC; /* min size */
  496. /* Build Decoding Table */
  497. DTableH->tableLog = (U16)nbBits;
  498. DTableH->fastMode = 1;
  499. for (s=0; s<=maxSymbolValue; s++)
  500. {
  501. dinfo[s].newState = 0;
  502. dinfo[s].symbol = (BYTE)s;
  503. dinfo[s].nbBits = (BYTE)nbBits;
  504. }
  505. return 0;
  506. }
  507. /* FSE_initDStream
  508. * Initialize a FSE_DStream_t.
  509. * srcBuffer must point at the beginning of an FSE block.
  510. * The function result is the size of the FSE_block (== srcSize).
  511. * If srcSize is too small, the function will return an errorCode;
  512. */
  513. static size_t FSE_initDStream(FSE_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  514. {
  515. if (srcSize < 1) return (size_t)-FSE_ERROR_srcSize_wrong;
  516. if (srcSize >= sizeof(size_t))
  517. {
  518. U32 contain32;
  519. bitD->start = (const char*)srcBuffer;
  520. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(size_t);
  521. bitD->bitContainer = FSE_readLEST(bitD->ptr);
  522. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  523. if (contain32 == 0) return (size_t)-FSE_ERROR_GENERIC; /* stop bit not present */
  524. bitD->bitsConsumed = 8 - FSE_highbit32(contain32);
  525. }
  526. else
  527. {
  528. U32 contain32;
  529. bitD->start = (const char*)srcBuffer;
  530. bitD->ptr = bitD->start;
  531. bitD->bitContainer = *(const BYTE*)(bitD->start);
  532. switch(srcSize)
  533. {
  534. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16);
  535. /* fallthrough */
  536. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24);
  537. /* fallthrough */
  538. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32);
  539. /* fallthrough */
  540. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24;
  541. /* fallthrough */
  542. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16;
  543. /* fallthrough */
  544. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) << 8;
  545. /* fallthrough */
  546. default:;
  547. }
  548. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  549. if (contain32 == 0) return (size_t)-FSE_ERROR_GENERIC; /* stop bit not present */
  550. bitD->bitsConsumed = 8 - FSE_highbit32(contain32);
  551. bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8;
  552. }
  553. return srcSize;
  554. }
  555. /*!FSE_lookBits
  556. * Provides next n bits from the bitContainer.
  557. * bitContainer is not modified (bits are still present for next read/look)
  558. * On 32-bits, maxNbBits==25
  559. * On 64-bits, maxNbBits==57
  560. * return : value extracted.
  561. */
  562. static size_t FSE_lookBits(FSE_DStream_t* bitD, U32 nbBits)
  563. {
  564. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  565. return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
  566. }
  567. static size_t FSE_lookBitsFast(FSE_DStream_t* bitD, U32 nbBits) /* only if nbBits >= 1 !! */
  568. {
  569. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  570. return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
  571. }
  572. static void FSE_skipBits(FSE_DStream_t* bitD, U32 nbBits)
  573. {
  574. bitD->bitsConsumed += nbBits;
  575. }
  576. /*!FSE_readBits
  577. * Read next n bits from the bitContainer.
  578. * On 32-bits, don't read more than maxNbBits==25
  579. * On 64-bits, don't read more than maxNbBits==57
  580. * Use the fast variant *only* if n >= 1.
  581. * return : value extracted.
  582. */
  583. static size_t FSE_readBits(FSE_DStream_t* bitD, U32 nbBits)
  584. {
  585. size_t value = FSE_lookBits(bitD, nbBits);
  586. FSE_skipBits(bitD, nbBits);
  587. return value;
  588. }
  589. static size_t FSE_readBitsFast(FSE_DStream_t* bitD, U32 nbBits) /* only if nbBits >= 1 !! */
  590. {
  591. size_t value = FSE_lookBitsFast(bitD, nbBits);
  592. FSE_skipBits(bitD, nbBits);
  593. return value;
  594. }
  595. static unsigned FSE_reloadDStream(FSE_DStream_t* bitD)
  596. {
  597. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should never happen */
  598. return FSE_DStream_tooFar;
  599. if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer))
  600. {
  601. bitD->ptr -= bitD->bitsConsumed >> 3;
  602. bitD->bitsConsumed &= 7;
  603. bitD->bitContainer = FSE_readLEST(bitD->ptr);
  604. return FSE_DStream_unfinished;
  605. }
  606. if (bitD->ptr == bitD->start)
  607. {
  608. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return FSE_DStream_endOfBuffer;
  609. return FSE_DStream_completed;
  610. }
  611. {
  612. U32 nbBytes = bitD->bitsConsumed >> 3;
  613. U32 result = FSE_DStream_unfinished;
  614. if (bitD->ptr - nbBytes < bitD->start)
  615. {
  616. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  617. result = FSE_DStream_endOfBuffer;
  618. }
  619. bitD->ptr -= nbBytes;
  620. bitD->bitsConsumed -= nbBytes*8;
  621. bitD->bitContainer = FSE_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */
  622. return result;
  623. }
  624. }
  625. static void FSE_initDState(FSE_DState_t* DStatePtr, FSE_DStream_t* bitD, const FSE_DTable* dt)
  626. {
  627. const void* ptr = dt;
  628. const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;
  629. DStatePtr->state = FSE_readBits(bitD, DTableH->tableLog);
  630. FSE_reloadDStream(bitD);
  631. DStatePtr->table = dt + 1;
  632. }
  633. static BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, FSE_DStream_t* bitD)
  634. {
  635. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  636. const U32 nbBits = DInfo.nbBits;
  637. BYTE symbol = DInfo.symbol;
  638. size_t lowBits = FSE_readBits(bitD, nbBits);
  639. DStatePtr->state = DInfo.newState + lowBits;
  640. return symbol;
  641. }
  642. static BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, FSE_DStream_t* bitD)
  643. {
  644. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  645. const U32 nbBits = DInfo.nbBits;
  646. BYTE symbol = DInfo.symbol;
  647. size_t lowBits = FSE_readBitsFast(bitD, nbBits);
  648. DStatePtr->state = DInfo.newState + lowBits;
  649. return symbol;
  650. }
  651. /* FSE_endOfDStream
  652. Tells if bitD has reached end of bitStream or not */
  653. static unsigned FSE_endOfDStream(const FSE_DStream_t* bitD)
  654. {
  655. return ((bitD->ptr == bitD->start) && (bitD->bitsConsumed == sizeof(bitD->bitContainer)*8));
  656. }
  657. static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
  658. {
  659. return DStatePtr->state == 0;
  660. }
  661. FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
  662. void* dst, size_t maxDstSize,
  663. const void* cSrc, size_t cSrcSize,
  664. const FSE_DTable* dt, const unsigned fast)
  665. {
  666. BYTE* const ostart = (BYTE*) dst;
  667. BYTE* op = ostart;
  668. BYTE* const omax = op + maxDstSize;
  669. BYTE* const olimit = omax-3;
  670. FSE_DStream_t bitD;
  671. FSE_DState_t state1;
  672. FSE_DState_t state2;
  673. size_t errorCode;
  674. /* Init */
  675. errorCode = FSE_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  676. if (FSE_isError(errorCode)) return errorCode;
  677. FSE_initDState(&state1, &bitD, dt);
  678. FSE_initDState(&state2, &bitD, dt);
  679. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  680. /* 4 symbols per loop */
  681. for ( ; (FSE_reloadDStream(&bitD)==FSE_DStream_unfinished) && (op<olimit) ; op+=4)
  682. {
  683. op[0] = FSE_GETSYMBOL(&state1);
  684. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  685. FSE_reloadDStream(&bitD);
  686. op[1] = FSE_GETSYMBOL(&state2);
  687. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  688. { if (FSE_reloadDStream(&bitD) > FSE_DStream_unfinished) { op+=2; break; } }
  689. op[2] = FSE_GETSYMBOL(&state1);
  690. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  691. FSE_reloadDStream(&bitD);
  692. op[3] = FSE_GETSYMBOL(&state2);
  693. }
  694. /* tail */
  695. /* note : FSE_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly FSE_DStream_completed */
  696. while (1)
  697. {
  698. if ( (FSE_reloadDStream(&bitD)>FSE_DStream_completed) || (op==omax) || (FSE_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) )
  699. break;
  700. *op++ = FSE_GETSYMBOL(&state1);
  701. if ( (FSE_reloadDStream(&bitD)>FSE_DStream_completed) || (op==omax) || (FSE_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) )
  702. break;
  703. *op++ = FSE_GETSYMBOL(&state2);
  704. }
  705. /* end ? */
  706. if (FSE_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2))
  707. return op-ostart;
  708. if (op==omax) return (size_t)-FSE_ERROR_dstSize_tooSmall; /* dst buffer is full, but cSrc unfinished */
  709. return (size_t)-FSE_ERROR_corruptionDetected;
  710. }
  711. static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
  712. const void* cSrc, size_t cSrcSize,
  713. const FSE_DTable* dt)
  714. {
  715. FSE_DTableHeader DTableH;
  716. memcpy(&DTableH, dt, sizeof(DTableH)); /* memcpy() into local variable, to avoid strict aliasing warning */
  717. /* select fast mode (static) */
  718. if (DTableH.fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  719. return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  720. }
  721. static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  722. {
  723. const BYTE* const istart = (const BYTE*)cSrc;
  724. const BYTE* ip = istart;
  725. short counting[FSE_MAX_SYMBOL_VALUE+1];
  726. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  727. unsigned tableLog;
  728. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  729. size_t errorCode;
  730. if (cSrcSize<2) return (size_t)-FSE_ERROR_srcSize_wrong; /* too small input size */
  731. /* normal FSE decoding mode */
  732. errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  733. if (FSE_isError(errorCode)) return errorCode;
  734. if (errorCode >= cSrcSize) return (size_t)-FSE_ERROR_srcSize_wrong; /* too small input size */
  735. ip += errorCode;
  736. cSrcSize -= errorCode;
  737. errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
  738. if (FSE_isError(errorCode)) return errorCode;
  739. /* always return, even if it is an error code */
  740. return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
  741. }
  742. /* *******************************************************
  743. * Huff0 : Huffman block compression
  744. *********************************************************/
  745. #define HUF_MAX_SYMBOL_VALUE 255
  746. #define HUF_DEFAULT_TABLELOG 12 /* used by default, when not specified */
  747. #define HUF_MAX_TABLELOG 12 /* max possible tableLog; for allocation purpose; can be modified */
  748. #define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
  749. #if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG)
  750. # error "HUF_MAX_TABLELOG is too large !"
  751. #endif
  752. typedef struct HUF_CElt_s {
  753. U16 val;
  754. BYTE nbBits;
  755. } HUF_CElt ;
  756. typedef struct nodeElt_s {
  757. U32 count;
  758. U16 parent;
  759. BYTE byte;
  760. BYTE nbBits;
  761. } nodeElt;
  762. /* *******************************************************
  763. * Huff0 : Huffman block decompression
  764. *********************************************************/
  765. typedef struct {
  766. BYTE byte;
  767. BYTE nbBits;
  768. } HUF_DElt;
  769. static size_t HUF_readDTable (U16* DTable, const void* src, size_t srcSize)
  770. {
  771. BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1];
  772. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */
  773. U32 weightTotal;
  774. U32 maxBits;
  775. const BYTE* ip = (const BYTE*) src;
  776. size_t iSize;
  777. size_t oSize;
  778. U32 n;
  779. U32 nextRankStart;
  780. void* ptr = DTable+1;
  781. HUF_DElt* const dt = (HUF_DElt*)ptr;
  782. if (!srcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  783. iSize = ip[0];
  784. FSE_STATIC_ASSERT(sizeof(HUF_DElt) == sizeof(U16)); /* if compilation fails here, assertion is false */
  785. //memset(huffWeight, 0, sizeof(huffWeight)); /* should not be necessary, but some analyzer complain ... */
  786. if (iSize >= 128) /* special header */
  787. {
  788. if (iSize >= (242)) /* RLE */
  789. {
  790. static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  791. oSize = l[iSize-242];
  792. memset(huffWeight, 1, sizeof(huffWeight));
  793. iSize = 0;
  794. }
  795. else /* Incompressible */
  796. {
  797. oSize = iSize - 127;
  798. iSize = ((oSize+1)/2);
  799. if (iSize+1 > srcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  800. ip += 1;
  801. for (n=0; n<oSize; n+=2)
  802. {
  803. huffWeight[n] = ip[n/2] >> 4;
  804. huffWeight[n+1] = ip[n/2] & 15;
  805. }
  806. }
  807. }
  808. else /* header compressed with FSE (normal case) */
  809. {
  810. if (iSize+1 > srcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  811. oSize = FSE_decompress(huffWeight, HUF_MAX_SYMBOL_VALUE, ip+1, iSize); /* max 255 values decoded, last one is implied */
  812. if (FSE_isError(oSize)) return oSize;
  813. }
  814. /* collect weight stats */
  815. memset(rankVal, 0, sizeof(rankVal));
  816. weightTotal = 0;
  817. for (n=0; n<oSize; n++)
  818. {
  819. if (huffWeight[n] >= HUF_ABSOLUTEMAX_TABLELOG) return (size_t)-FSE_ERROR_corruptionDetected;
  820. rankVal[huffWeight[n]]++;
  821. weightTotal += (1 << huffWeight[n]) >> 1;
  822. }
  823. if (weightTotal == 0) return (size_t)-FSE_ERROR_corruptionDetected;
  824. /* get last non-null symbol weight (implied, total must be 2^n) */
  825. maxBits = FSE_highbit32(weightTotal) + 1;
  826. if (maxBits > DTable[0]) return (size_t)-FSE_ERROR_tableLog_tooLarge; /* DTable is too small */
  827. DTable[0] = (U16)maxBits;
  828. {
  829. U32 total = 1 << maxBits;
  830. U32 rest = total - weightTotal;
  831. U32 verif = 1 << FSE_highbit32(rest);
  832. U32 lastWeight = FSE_highbit32(rest) + 1;
  833. if (verif != rest) return (size_t)-FSE_ERROR_corruptionDetected; /* last value must be a clean power of 2 */
  834. huffWeight[oSize] = (BYTE)lastWeight;
  835. rankVal[lastWeight]++;
  836. }
  837. /* check tree construction validity */
  838. if ((rankVal[1] < 2) || (rankVal[1] & 1)) return (size_t)-FSE_ERROR_corruptionDetected; /* by construction : at least 2 elts of rank 1, must be even */
  839. /* Prepare ranks */
  840. nextRankStart = 0;
  841. for (n=1; n<=maxBits; n++)
  842. {
  843. U32 current = nextRankStart;
  844. nextRankStart += (rankVal[n] << (n-1));
  845. rankVal[n] = current;
  846. }
  847. /* fill DTable */
  848. for (n=0; n<=oSize; n++)
  849. {
  850. const U32 w = huffWeight[n];
  851. const U32 length = (1 << w) >> 1;
  852. U32 i;
  853. HUF_DElt D;
  854. D.byte = (BYTE)n; D.nbBits = (BYTE)(maxBits + 1 - w);
  855. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  856. dt[i] = D;
  857. rankVal[w] += length;
  858. }
  859. return iSize+1;
  860. }
  861. static BYTE HUF_decodeSymbol(FSE_DStream_t* Dstream, const HUF_DElt* dt, const U32 dtLog)
  862. {
  863. const size_t val = FSE_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  864. const BYTE c = dt[val].byte;
  865. FSE_skipBits(Dstream, dt[val].nbBits);
  866. return c;
  867. }
  868. static size_t HUF_decompress_usingDTable( /* -3% slower when non static */
  869. void* dst, size_t maxDstSize,
  870. const void* cSrc, size_t cSrcSize,
  871. const U16* DTable)
  872. {
  873. if (cSrcSize < 6) return (size_t)-FSE_ERROR_srcSize_wrong;
  874. {
  875. BYTE* const ostart = (BYTE*) dst;
  876. BYTE* op = ostart;
  877. BYTE* const omax = op + maxDstSize;
  878. BYTE* const olimit = maxDstSize < 15 ? op : omax-15;
  879. const void* ptr = DTable;
  880. const HUF_DElt* const dt = (const HUF_DElt*)(ptr)+1;
  881. const U32 dtLog = DTable[0];
  882. size_t errorCode;
  883. U32 reloadStatus;
  884. /* Init */
  885. const U16* jumpTable = (const U16*)cSrc;
  886. const size_t length1 = FSE_readLE16(jumpTable);
  887. const size_t length2 = FSE_readLE16(jumpTable+1);
  888. const size_t length3 = FSE_readLE16(jumpTable+2);
  889. const size_t length4 = cSrcSize - 6 - length1 - length2 - length3; /* check coherency !! */
  890. const char* const start1 = (const char*)(cSrc) + 6;
  891. const char* const start2 = start1 + length1;
  892. const char* const start3 = start2 + length2;
  893. const char* const start4 = start3 + length3;
  894. FSE_DStream_t bitD1, bitD2, bitD3, bitD4;
  895. if (length1+length2+length3+6 >= cSrcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  896. errorCode = FSE_initDStream(&bitD1, start1, length1);
  897. if (FSE_isError(errorCode)) return errorCode;
  898. errorCode = FSE_initDStream(&bitD2, start2, length2);
  899. if (FSE_isError(errorCode)) return errorCode;
  900. errorCode = FSE_initDStream(&bitD3, start3, length3);
  901. if (FSE_isError(errorCode)) return errorCode;
  902. errorCode = FSE_initDStream(&bitD4, start4, length4);
  903. if (FSE_isError(errorCode)) return errorCode;
  904. reloadStatus=FSE_reloadDStream(&bitD2);
  905. /* 16 symbols per loop */
  906. for ( ; (reloadStatus<FSE_DStream_completed) && (op<olimit); /* D2-3-4 are supposed to be synchronized and finish together */
  907. op+=16, reloadStatus = FSE_reloadDStream(&bitD2) | FSE_reloadDStream(&bitD3) | FSE_reloadDStream(&bitD4), FSE_reloadDStream(&bitD1))
  908. {
  909. #define HUF_DECODE_SYMBOL_0(n, Dstream) \
  910. op[n] = HUF_decodeSymbol(&Dstream, dt, dtLog);
  911. #define HUF_DECODE_SYMBOL_1(n, Dstream) \
  912. op[n] = HUF_decodeSymbol(&Dstream, dt, dtLog); \
  913. if (FSE_32bits() && (HUF_MAX_TABLELOG>12)) FSE_reloadDStream(&Dstream)
  914. #define HUF_DECODE_SYMBOL_2(n, Dstream) \
  915. op[n] = HUF_decodeSymbol(&Dstream, dt, dtLog); \
  916. if (FSE_32bits()) FSE_reloadDStream(&Dstream)
  917. HUF_DECODE_SYMBOL_1( 0, bitD1);
  918. HUF_DECODE_SYMBOL_1( 1, bitD2);
  919. HUF_DECODE_SYMBOL_1( 2, bitD3);
  920. HUF_DECODE_SYMBOL_1( 3, bitD4);
  921. HUF_DECODE_SYMBOL_2( 4, bitD1);
  922. HUF_DECODE_SYMBOL_2( 5, bitD2);
  923. HUF_DECODE_SYMBOL_2( 6, bitD3);
  924. HUF_DECODE_SYMBOL_2( 7, bitD4);
  925. HUF_DECODE_SYMBOL_1( 8, bitD1);
  926. HUF_DECODE_SYMBOL_1( 9, bitD2);
  927. HUF_DECODE_SYMBOL_1(10, bitD3);
  928. HUF_DECODE_SYMBOL_1(11, bitD4);
  929. HUF_DECODE_SYMBOL_0(12, bitD1);
  930. HUF_DECODE_SYMBOL_0(13, bitD2);
  931. HUF_DECODE_SYMBOL_0(14, bitD3);
  932. HUF_DECODE_SYMBOL_0(15, bitD4);
  933. }
  934. if (reloadStatus!=FSE_DStream_completed) /* not complete : some bitStream might be FSE_DStream_unfinished */
  935. return (size_t)-FSE_ERROR_corruptionDetected;
  936. /* tail */
  937. {
  938. /* bitTail = bitD1; */ /* *much* slower : -20% !??! */
  939. FSE_DStream_t bitTail;
  940. bitTail.ptr = bitD1.ptr;
  941. bitTail.bitsConsumed = bitD1.bitsConsumed;
  942. bitTail.bitContainer = bitD1.bitContainer; /* required in case of FSE_DStream_endOfBuffer */
  943. bitTail.start = start1;
  944. for ( ; (FSE_reloadDStream(&bitTail) < FSE_DStream_completed) && (op<omax) ; op++)
  945. {
  946. HUF_DECODE_SYMBOL_0(0, bitTail);
  947. }
  948. if (FSE_endOfDStream(&bitTail))
  949. return op-ostart;
  950. }
  951. if (op==omax) return (size_t)-FSE_ERROR_dstSize_tooSmall; /* dst buffer is full, but cSrc unfinished */
  952. return (size_t)-FSE_ERROR_corruptionDetected;
  953. }
  954. }
  955. static size_t HUF_decompress (void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  956. {
  957. HUF_CREATE_STATIC_DTABLE(DTable, HUF_MAX_TABLELOG);
  958. const BYTE* ip = (const BYTE*) cSrc;
  959. size_t errorCode;
  960. errorCode = HUF_readDTable (DTable, cSrc, cSrcSize);
  961. if (FSE_isError(errorCode)) return errorCode;
  962. if (errorCode >= cSrcSize) return (size_t)-FSE_ERROR_srcSize_wrong;
  963. ip += errorCode;
  964. cSrcSize -= errorCode;
  965. return HUF_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, DTable);
  966. }
  967. #endif /* FSE_COMMONDEFS_ONLY */
  968. /*
  969. zstd - standard compression library
  970. Copyright (C) 2014-2015, Yann Collet.
  971. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  972. Redistribution and use in source and binary forms, with or without
  973. modification, are permitted provided that the following conditions are
  974. met:
  975. * Redistributions of source code must retain the above copyright
  976. notice, this list of conditions and the following disclaimer.
  977. * Redistributions in binary form must reproduce the above
  978. copyright notice, this list of conditions and the following disclaimer
  979. in the documentation and/or other materials provided with the
  980. distribution.
  981. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  982. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  983. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  984. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  985. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  986. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  987. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  988. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  989. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  990. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  991. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  992. You can contact the author at :
  993. - zstd source repository : https://github.com/Cyan4973/zstd
  994. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  995. */
  996. /****************************************************************
  997. * Tuning parameters
  998. *****************************************************************/
  999. /* MEMORY_USAGE :
  1000. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  1001. * Increasing memory usage improves compression ratio
  1002. * Reduced memory usage can improve speed, due to cache effect */
  1003. #define ZSTD_MEMORY_USAGE 17
  1004. /**************************************
  1005. CPU Feature Detection
  1006. **************************************/
  1007. /*
  1008. * Automated efficient unaligned memory access detection
  1009. * Based on known hardware architectures
  1010. * This list will be updated thanks to feedbacks
  1011. */
  1012. #if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \
  1013. || defined(__ARM_FEATURE_UNALIGNED) \
  1014. || defined(__i386__) || defined(__x86_64__) \
  1015. || defined(_M_IX86) || defined(_M_X64) \
  1016. || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \
  1017. || (defined(_M_ARM) && (_M_ARM >= 7))
  1018. # define ZSTD_UNALIGNED_ACCESS 1
  1019. #else
  1020. # define ZSTD_UNALIGNED_ACCESS 0
  1021. #endif
  1022. /********************************************************
  1023. * Includes
  1024. *********************************************************/
  1025. #include <stdlib.h> /* calloc */
  1026. #include <string.h> /* memcpy, memmove */
  1027. #include <stdio.h> /* debug : printf */
  1028. /********************************************************
  1029. * Compiler specifics
  1030. *********************************************************/
  1031. #ifdef __AVX2__
  1032. # include <immintrin.h> /* AVX2 intrinsics */
  1033. #endif
  1034. #ifdef _MSC_VER /* Visual Studio */
  1035. # include <intrin.h> /* For Visual 2005 */
  1036. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1037. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  1038. #endif
  1039. #ifndef MEM_ACCESS_MODULE
  1040. #define MEM_ACCESS_MODULE
  1041. /********************************************************
  1042. * Basic Types
  1043. *********************************************************/
  1044. #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  1045. # if defined(_AIX)
  1046. # include <inttypes.h>
  1047. # else
  1048. # include <stdint.h> /* intptr_t */
  1049. # endif
  1050. typedef uint8_t BYTE;
  1051. typedef uint16_t U16;
  1052. typedef int16_t S16;
  1053. typedef uint32_t U32;
  1054. typedef int32_t S32;
  1055. typedef uint64_t U64;
  1056. #else
  1057. typedef unsigned char BYTE;
  1058. typedef unsigned short U16;
  1059. typedef signed short S16;
  1060. typedef unsigned int U32;
  1061. typedef signed int S32;
  1062. typedef unsigned long long U64;
  1063. #endif
  1064. #endif /* MEM_ACCESS_MODULE */
  1065. /********************************************************
  1066. * Constants
  1067. *********************************************************/
  1068. static const U32 ZSTD_magicNumber = 0xFD2FB51E; /* 3rd version : seqNb header */
  1069. #define HASH_LOG (ZSTD_MEMORY_USAGE - 2)
  1070. #define HASH_TABLESIZE (1 << HASH_LOG)
  1071. #define HASH_MASK (HASH_TABLESIZE - 1)
  1072. #define KNUTH 2654435761
  1073. #define BIT7 128
  1074. #define BIT6 64
  1075. #define BIT5 32
  1076. #define BIT4 16
  1077. #define KB *(1 <<10)
  1078. #define MB *(1 <<20)
  1079. #define GB *(1U<<30)
  1080. #define BLOCKSIZE (128 KB) /* define, for static allocation */
  1081. #define WORKPLACESIZE (BLOCKSIZE*3)
  1082. #define MINMATCH 4
  1083. #define MLbits 7
  1084. #define LLbits 6
  1085. #define Offbits 5
  1086. #define MaxML ((1<<MLbits )-1)
  1087. #define MaxLL ((1<<LLbits )-1)
  1088. #define MaxOff ((1<<Offbits)-1)
  1089. #define LitFSELog 11
  1090. #define MLFSELog 10
  1091. #define LLFSELog 10
  1092. #define OffFSELog 9
  1093. #define MAX(a,b) ((a)<(b)?(b):(a))
  1094. #define MaxSeq MAX(MaxLL, MaxML)
  1095. #define LITERAL_NOENTROPY 63
  1096. #define COMMAND_NOENTROPY 7 /* to remove */
  1097. #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)
  1098. static const size_t ZSTD_blockHeaderSize = 3;
  1099. static const size_t ZSTD_frameHeaderSize = 4;
  1100. /********************************************************
  1101. * Memory operations
  1102. *********************************************************/
  1103. static unsigned ZSTD_32bits(void) { return sizeof(void*)==4; }
  1104. static unsigned ZSTD_isLittleEndian(void)
  1105. {
  1106. const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  1107. return one.c[0];
  1108. }
  1109. static U16 ZSTD_read16(const void* p) { U16 r; memcpy(&r, p, sizeof(r)); return r; }
  1110. static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  1111. static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  1112. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  1113. static void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length)
  1114. {
  1115. const BYTE* ip = (const BYTE*)src;
  1116. BYTE* op = (BYTE*)dst;
  1117. BYTE* const oend = op + length;
  1118. while (op < oend) COPY8(op, ip);
  1119. }
  1120. static U16 ZSTD_readLE16(const void* memPtr)
  1121. {
  1122. if (ZSTD_isLittleEndian()) return ZSTD_read16(memPtr);
  1123. else
  1124. {
  1125. const BYTE* p = (const BYTE*)memPtr;
  1126. return (U16)((U16)p[0] + ((U16)p[1]<<8));
  1127. }
  1128. }
  1129. static U32 ZSTD_readLE24(const void* memPtr)
  1130. {
  1131. return ZSTD_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16);
  1132. }
  1133. static U32 ZSTD_readBE32(const void* memPtr)
  1134. {
  1135. const BYTE* p = (const BYTE*)memPtr;
  1136. return (U32)(((U32)p[0]<<24) + ((U32)p[1]<<16) + ((U32)p[2]<<8) + ((U32)p[3]<<0));
  1137. }
  1138. /**************************************
  1139. * Local structures
  1140. ***************************************/
  1141. typedef struct ZSTD_Cctx_s ZSTD_Cctx;
  1142. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  1143. typedef struct
  1144. {
  1145. blockType_t blockType;
  1146. U32 origSize;
  1147. } blockProperties_t;
  1148. typedef struct {
  1149. void* buffer;
  1150. U32* offsetStart;
  1151. U32* offset;
  1152. BYTE* offCodeStart;
  1153. BYTE* offCode;
  1154. BYTE* litStart;
  1155. BYTE* lit;
  1156. BYTE* litLengthStart;
  1157. BYTE* litLength;
  1158. BYTE* matchLengthStart;
  1159. BYTE* matchLength;
  1160. BYTE* dumpsStart;
  1161. BYTE* dumps;
  1162. } seqStore_t;
  1163. typedef struct ZSTD_Cctx_s
  1164. {
  1165. const BYTE* base;
  1166. U32 current;
  1167. U32 nextUpdate;
  1168. seqStore_t seqStore;
  1169. #ifdef __AVX2__
  1170. __m256i hashTable[HASH_TABLESIZE>>3];
  1171. #else
  1172. U32 hashTable[HASH_TABLESIZE];
  1173. #endif
  1174. BYTE buffer[WORKPLACESIZE];
  1175. } cctxi_t;
  1176. /**************************************
  1177. * Error Management
  1178. **************************************/
  1179. /* published entry point */
  1180. unsigned ZSTDv01_isError(size_t code) { return ERR_isError(code); }
  1181. /**************************************
  1182. * Tool functions
  1183. **************************************/
  1184. #define ZSTD_VERSION_MAJOR 0 /* for breaking interface changes */
  1185. #define ZSTD_VERSION_MINOR 1 /* for new (non-breaking) interface capabilities */
  1186. #define ZSTD_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */
  1187. #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
  1188. /**************************************************************
  1189. * Decompression code
  1190. **************************************************************/
  1191. static size_t ZSTDv01_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  1192. {
  1193. const BYTE* const in = (const BYTE* const)src;
  1194. BYTE headerFlags;
  1195. U32 cSize;
  1196. if (srcSize < 3) return ERROR(srcSize_wrong);
  1197. headerFlags = *in;
  1198. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  1199. bpPtr->blockType = (blockType_t)(headerFlags >> 6);
  1200. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  1201. if (bpPtr->blockType == bt_end) return 0;
  1202. if (bpPtr->blockType == bt_rle) return 1;
  1203. return cSize;
  1204. }
  1205. static size_t ZSTD_copyUncompressedBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1206. {
  1207. if (srcSize > maxDstSize) return ERROR(dstSize_tooSmall);
  1208. if (srcSize > 0) {
  1209. memcpy(dst, src, srcSize);
  1210. }
  1211. return srcSize;
  1212. }
  1213. static size_t ZSTD_decompressLiterals(void* ctx,
  1214. void* dst, size_t maxDstSize,
  1215. const void* src, size_t srcSize)
  1216. {
  1217. BYTE* op = (BYTE*)dst;
  1218. BYTE* const oend = op + maxDstSize;
  1219. const BYTE* ip = (const BYTE*)src;
  1220. size_t errorCode;
  1221. size_t litSize;
  1222. /* check : minimum 2, for litSize, +1, for content */
  1223. if (srcSize <= 3) return ERROR(corruption_detected);
  1224. litSize = ip[1] + (ip[0]<<8);
  1225. litSize += ((ip[-3] >> 3) & 7) << 16; /* mmmmh.... */
  1226. op = oend - litSize;
  1227. (void)ctx;
  1228. if (litSize > maxDstSize) return ERROR(dstSize_tooSmall);
  1229. errorCode = HUF_decompress(op, litSize, ip+2, srcSize-2);
  1230. if (FSE_isError(errorCode)) return ERROR(GENERIC);
  1231. return litSize;
  1232. }
  1233. static size_t ZSTDv01_decodeLiteralsBlock(void* ctx,
  1234. void* dst, size_t maxDstSize,
  1235. const BYTE** litStart, size_t* litSize,
  1236. const void* src, size_t srcSize)
  1237. {
  1238. const BYTE* const istart = (const BYTE* const)src;
  1239. const BYTE* ip = istart;
  1240. BYTE* const ostart = (BYTE* const)dst;
  1241. BYTE* const oend = ostart + maxDstSize;
  1242. blockProperties_t litbp;
  1243. size_t litcSize = ZSTDv01_getcBlockSize(src, srcSize, &litbp);
  1244. if (ZSTDv01_isError(litcSize)) return litcSize;
  1245. if (litcSize > srcSize - ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  1246. ip += ZSTD_blockHeaderSize;
  1247. switch(litbp.blockType)
  1248. {
  1249. case bt_raw:
  1250. *litStart = ip;
  1251. ip += litcSize;
  1252. *litSize = litcSize;
  1253. break;
  1254. case bt_rle:
  1255. {
  1256. size_t rleSize = litbp.origSize;
  1257. if (rleSize>maxDstSize) return ERROR(dstSize_tooSmall);
  1258. if (!srcSize) return ERROR(srcSize_wrong);
  1259. if (rleSize > 0) {
  1260. memset(oend - rleSize, *ip, rleSize);
  1261. }
  1262. *litStart = oend - rleSize;
  1263. *litSize = rleSize;
  1264. ip++;
  1265. break;
  1266. }
  1267. case bt_compressed:
  1268. {
  1269. size_t decodedLitSize = ZSTD_decompressLiterals(ctx, dst, maxDstSize, ip, litcSize);
  1270. if (ZSTDv01_isError(decodedLitSize)) return decodedLitSize;
  1271. *litStart = oend - decodedLitSize;
  1272. *litSize = decodedLitSize;
  1273. ip += litcSize;
  1274. break;
  1275. }
  1276. case bt_end:
  1277. default:
  1278. return ERROR(GENERIC);
  1279. }
  1280. return ip-istart;
  1281. }
  1282. static size_t ZSTDv01_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
  1283. FSE_DTable* DTableLL, FSE_DTable* DTableML, FSE_DTable* DTableOffb,
  1284. const void* src, size_t srcSize)
  1285. {
  1286. const BYTE* const istart = (const BYTE* const)src;
  1287. const BYTE* ip = istart;
  1288. const BYTE* const iend = istart + srcSize;
  1289. U32 LLtype, Offtype, MLtype;
  1290. U32 LLlog, Offlog, MLlog;
  1291. size_t dumpsLength;
  1292. /* check */
  1293. if (srcSize < 5) return ERROR(srcSize_wrong);
  1294. /* SeqHead */
  1295. *nbSeq = ZSTD_readLE16(ip); ip+=2;
  1296. LLtype = *ip >> 6;
  1297. Offtype = (*ip >> 4) & 3;
  1298. MLtype = (*ip >> 2) & 3;
  1299. if (*ip & 2)
  1300. {
  1301. dumpsLength = ip[2];
  1302. dumpsLength += ip[1] << 8;
  1303. ip += 3;
  1304. }
  1305. else
  1306. {
  1307. dumpsLength = ip[1];
  1308. dumpsLength += (ip[0] & 1) << 8;
  1309. ip += 2;
  1310. }
  1311. *dumpsPtr = ip;
  1312. ip += dumpsLength;
  1313. *dumpsLengthPtr = dumpsLength;
  1314. /* check */
  1315. if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  1316. /* sequences */
  1317. {
  1318. S16 norm[MaxML+1]; /* assumption : MaxML >= MaxLL and MaxOff */
  1319. size_t headerSize;
  1320. /* Build DTables */
  1321. switch(LLtype)
  1322. {
  1323. case bt_rle :
  1324. LLlog = 0;
  1325. FSE_buildDTable_rle(DTableLL, *ip++); break;
  1326. case bt_raw :
  1327. LLlog = LLbits;
  1328. FSE_buildDTable_raw(DTableLL, LLbits); break;
  1329. default :
  1330. { U32 max = MaxLL;
  1331. headerSize = FSE_readNCount(norm, &max, &LLlog, ip, iend-ip);
  1332. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  1333. if (LLlog > LLFSELog) return ERROR(corruption_detected);
  1334. ip += headerSize;
  1335. FSE_buildDTable(DTableLL, norm, max, LLlog);
  1336. } }
  1337. switch(Offtype)
  1338. {
  1339. case bt_rle :
  1340. Offlog = 0;
  1341. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  1342. FSE_buildDTable_rle(DTableOffb, *ip++); break;
  1343. case bt_raw :
  1344. Offlog = Offbits;
  1345. FSE_buildDTable_raw(DTableOffb, Offbits); break;
  1346. default :
  1347. { U32 max = MaxOff;
  1348. headerSize = FSE_readNCount(norm, &max, &Offlog, ip, iend-ip);
  1349. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  1350. if (Offlog > OffFSELog) return ERROR(corruption_detected);
  1351. ip += headerSize;
  1352. FSE_buildDTable(DTableOffb, norm, max, Offlog);
  1353. } }
  1354. switch(MLtype)
  1355. {
  1356. case bt_rle :
  1357. MLlog = 0;
  1358. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  1359. FSE_buildDTable_rle(DTableML, *ip++); break;
  1360. case bt_raw :
  1361. MLlog = MLbits;
  1362. FSE_buildDTable_raw(DTableML, MLbits); break;
  1363. default :
  1364. { U32 max = MaxML;
  1365. headerSize = FSE_readNCount(norm, &max, &MLlog, ip, iend-ip);
  1366. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  1367. if (MLlog > MLFSELog) return ERROR(corruption_detected);
  1368. ip += headerSize;
  1369. FSE_buildDTable(DTableML, norm, max, MLlog);
  1370. } } }
  1371. return ip-istart;
  1372. }
  1373. typedef struct {
  1374. size_t litLength;
  1375. size_t offset;
  1376. size_t matchLength;
  1377. } seq_t;
  1378. typedef struct {
  1379. FSE_DStream_t DStream;
  1380. FSE_DState_t stateLL;
  1381. FSE_DState_t stateOffb;
  1382. FSE_DState_t stateML;
  1383. size_t prevOffset;
  1384. const BYTE* dumps;
  1385. const BYTE* dumpsEnd;
  1386. } seqState_t;
  1387. static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState)
  1388. {
  1389. size_t litLength;
  1390. size_t prevOffset;
  1391. size_t offset;
  1392. size_t matchLength;
  1393. const BYTE* dumps = seqState->dumps;
  1394. const BYTE* const de = seqState->dumpsEnd;
  1395. /* Literal length */
  1396. litLength = FSE_decodeSymbol(&(seqState->stateLL), &(seqState->DStream));
  1397. prevOffset = litLength ? seq->offset : seqState->prevOffset;
  1398. seqState->prevOffset = seq->offset;
  1399. if (litLength == MaxLL)
  1400. {
  1401. const U32 add = dumps<de ? *dumps++ : 0;
  1402. if (add < 255) litLength += add;
  1403. else
  1404. {
  1405. if (dumps<=(de-3))
  1406. {
  1407. litLength = ZSTD_readLE24(dumps);
  1408. dumps += 3;
  1409. }
  1410. }
  1411. }
  1412. /* Offset */
  1413. {
  1414. U32 offsetCode, nbBits;
  1415. offsetCode = FSE_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream));
  1416. if (ZSTD_32bits()) FSE_reloadDStream(&(seqState->DStream));
  1417. nbBits = offsetCode - 1;
  1418. if (offsetCode==0) nbBits = 0; /* cmove */
  1419. offset = ((size_t)1 << (nbBits & ((sizeof(offset)*8)-1))) + FSE_readBits(&(seqState->DStream), nbBits);
  1420. if (ZSTD_32bits()) FSE_reloadDStream(&(seqState->DStream));
  1421. if (offsetCode==0) offset = prevOffset;
  1422. }
  1423. /* MatchLength */
  1424. matchLength = FSE_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
  1425. if (matchLength == MaxML)
  1426. {
  1427. const U32 add = dumps<de ? *dumps++ : 0;
  1428. if (add < 255) matchLength += add;
  1429. else
  1430. {
  1431. if (dumps<=(de-3))
  1432. {
  1433. matchLength = ZSTD_readLE24(dumps);
  1434. dumps += 3;
  1435. }
  1436. }
  1437. }
  1438. matchLength += MINMATCH;
  1439. /* save result */
  1440. seq->litLength = litLength;
  1441. seq->offset = offset;
  1442. seq->matchLength = matchLength;
  1443. seqState->dumps = dumps;
  1444. }
  1445. static size_t ZSTD_execSequence(BYTE* op,
  1446. seq_t sequence,
  1447. const BYTE** litPtr, const BYTE* const litLimit,
  1448. BYTE* const base, BYTE* const oend)
  1449. {
  1450. static const int dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */
  1451. static const int dec64table[] = {8, 8, 8, 7, 8, 9,10,11}; /* subtracted */
  1452. const BYTE* const ostart = op;
  1453. BYTE* const oLitEnd = op + sequence.litLength;
  1454. const size_t litLength = sequence.litLength;
  1455. BYTE* const endMatch = op + litLength + sequence.matchLength; /* risk : address space overflow (32-bits) */
  1456. const BYTE* const litEnd = *litPtr + litLength;
  1457. /* checks */
  1458. size_t const seqLength = sequence.litLength + sequence.matchLength;
  1459. if (seqLength > (size_t)(oend - op)) return ERROR(dstSize_tooSmall);
  1460. if (sequence.litLength > (size_t)(litLimit - *litPtr)) return ERROR(corruption_detected);
  1461. /* Now we know there are no overflow in literal nor match lengths, can use pointer checks */
  1462. if (sequence.offset > (U32)(oLitEnd - base)) return ERROR(corruption_detected);
  1463. if (endMatch > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */
  1464. if (litEnd > litLimit) return ERROR(corruption_detected); /* overRead beyond lit buffer */
  1465. if (sequence.matchLength > (size_t)(*litPtr-op)) return ERROR(dstSize_tooSmall); /* overwrite literal segment */
  1466. /* copy Literals */
  1467. ZSTD_memmove(op, *litPtr, sequence.litLength); /* note : v0.1 seems to allow scenarios where output or input are close to end of buffer */
  1468. op += litLength;
  1469. *litPtr = litEnd; /* update for next sequence */
  1470. /* check : last match must be at a minimum distance of 8 from end of dest buffer */
  1471. if (oend-op < 8) return ERROR(dstSize_tooSmall);
  1472. /* copy Match */
  1473. {
  1474. const U32 overlapRisk = (((size_t)(litEnd - endMatch)) < 12);
  1475. const BYTE* match = op - sequence.offset; /* possible underflow at op - offset ? */
  1476. size_t qutt = 12;
  1477. U64 saved[2];
  1478. /* check */
  1479. if (match < base) return ERROR(corruption_detected);
  1480. if (sequence.offset > (size_t)base) return ERROR(corruption_detected);
  1481. /* save beginning of literal sequence, in case of write overlap */
  1482. if (overlapRisk)
  1483. {
  1484. if ((endMatch + qutt) > oend) qutt = oend-endMatch;
  1485. memcpy(saved, endMatch, qutt);
  1486. }
  1487. if (sequence.offset < 8)
  1488. {
  1489. const int dec64 = dec64table[sequence.offset];
  1490. op[0] = match[0];
  1491. op[1] = match[1];
  1492. op[2] = match[2];
  1493. op[3] = match[3];
  1494. match += dec32table[sequence.offset];
  1495. ZSTD_copy4(op+4, match);
  1496. match -= dec64;
  1497. } else { ZSTD_copy8(op, match); }
  1498. op += 8; match += 8;
  1499. if (endMatch > oend-(16-MINMATCH))
  1500. {
  1501. if (op < oend-8)
  1502. {
  1503. ZSTD_wildcopy(op, match, (oend-8) - op);
  1504. match += (oend-8) - op;
  1505. op = oend-8;
  1506. }
  1507. while (op<endMatch) *op++ = *match++;
  1508. }
  1509. else
  1510. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
  1511. /* restore, in case of overlap */
  1512. if (overlapRisk) memcpy(endMatch, saved, qutt);
  1513. }
  1514. return endMatch-ostart;
  1515. }
  1516. typedef struct ZSTDv01_Dctx_s
  1517. {
  1518. U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  1519. U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  1520. U32 MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  1521. void* previousDstEnd;
  1522. void* base;
  1523. size_t expected;
  1524. blockType_t bType;
  1525. U32 phase;
  1526. } dctx_t;
  1527. static size_t ZSTD_decompressSequences(
  1528. void* ctx,
  1529. void* dst, size_t maxDstSize,
  1530. const void* seqStart, size_t seqSize,
  1531. const BYTE* litStart, size_t litSize)
  1532. {
  1533. dctx_t* dctx = (dctx_t*)ctx;
  1534. const BYTE* ip = (const BYTE*)seqStart;
  1535. const BYTE* const iend = ip + seqSize;
  1536. BYTE* const ostart = (BYTE* const)dst;
  1537. BYTE* op = ostart;
  1538. BYTE* const oend = ostart + maxDstSize;
  1539. size_t errorCode, dumpsLength;
  1540. const BYTE* litPtr = litStart;
  1541. const BYTE* const litEnd = litStart + litSize;
  1542. int nbSeq;
  1543. const BYTE* dumps;
  1544. U32* DTableLL = dctx->LLTable;
  1545. U32* DTableML = dctx->MLTable;
  1546. U32* DTableOffb = dctx->OffTable;
  1547. BYTE* const base = (BYTE*) (dctx->base);
  1548. /* Build Decoding Tables */
  1549. errorCode = ZSTDv01_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
  1550. DTableLL, DTableML, DTableOffb,
  1551. ip, iend-ip);
  1552. if (ZSTDv01_isError(errorCode)) return errorCode;
  1553. ip += errorCode;
  1554. /* Regen sequences */
  1555. {
  1556. seq_t sequence;
  1557. seqState_t seqState;
  1558. memset(&sequence, 0, sizeof(sequence));
  1559. seqState.dumps = dumps;
  1560. seqState.dumpsEnd = dumps + dumpsLength;
  1561. seqState.prevOffset = 1;
  1562. errorCode = FSE_initDStream(&(seqState.DStream), ip, iend-ip);
  1563. if (FSE_isError(errorCode)) return ERROR(corruption_detected);
  1564. FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  1565. FSE_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  1566. FSE_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  1567. for ( ; (FSE_reloadDStream(&(seqState.DStream)) <= FSE_DStream_completed) && (nbSeq>0) ; )
  1568. {
  1569. size_t oneSeqSize;
  1570. nbSeq--;
  1571. ZSTD_decodeSequence(&sequence, &seqState);
  1572. oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litEnd, base, oend);
  1573. if (ZSTDv01_isError(oneSeqSize)) return oneSeqSize;
  1574. op += oneSeqSize;
  1575. }
  1576. /* check if reached exact end */
  1577. if ( !FSE_endOfDStream(&(seqState.DStream)) ) return ERROR(corruption_detected); /* requested too much : data is corrupted */
  1578. if (nbSeq<0) return ERROR(corruption_detected); /* requested too many sequences : data is corrupted */
  1579. /* last literal segment */
  1580. {
  1581. size_t lastLLSize = litEnd - litPtr;
  1582. if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
  1583. if (lastLLSize > 0) {
  1584. if (op != litPtr) memmove(op, litPtr, lastLLSize);
  1585. op += lastLLSize;
  1586. }
  1587. }
  1588. }
  1589. return op-ostart;
  1590. }
  1591. static size_t ZSTD_decompressBlock(
  1592. void* ctx,
  1593. void* dst, size_t maxDstSize,
  1594. const void* src, size_t srcSize)
  1595. {
  1596. /* blockType == blockCompressed, srcSize is trusted */
  1597. const BYTE* ip = (const BYTE*)src;
  1598. const BYTE* litPtr = NULL;
  1599. size_t litSize = 0;
  1600. size_t errorCode;
  1601. /* Decode literals sub-block */
  1602. errorCode = ZSTDv01_decodeLiteralsBlock(ctx, dst, maxDstSize, &litPtr, &litSize, src, srcSize);
  1603. if (ZSTDv01_isError(errorCode)) return errorCode;
  1604. ip += errorCode;
  1605. srcSize -= errorCode;
  1606. return ZSTD_decompressSequences(ctx, dst, maxDstSize, ip, srcSize, litPtr, litSize);
  1607. }
  1608. size_t ZSTDv01_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1609. {
  1610. const BYTE* ip = (const BYTE*)src;
  1611. const BYTE* iend = ip + srcSize;
  1612. BYTE* const ostart = (BYTE* const)dst;
  1613. BYTE* op = ostart;
  1614. BYTE* const oend = ostart + maxDstSize;
  1615. size_t remainingSize = srcSize;
  1616. U32 magicNumber;
  1617. size_t errorCode=0;
  1618. blockProperties_t blockProperties;
  1619. /* Frame Header */
  1620. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  1621. magicNumber = ZSTD_readBE32(src);
  1622. if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
  1623. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  1624. /* Loop on each block */
  1625. while (1)
  1626. {
  1627. size_t blockSize = ZSTDv01_getcBlockSize(ip, iend-ip, &blockProperties);
  1628. if (ZSTDv01_isError(blockSize)) return blockSize;
  1629. ip += ZSTD_blockHeaderSize;
  1630. remainingSize -= ZSTD_blockHeaderSize;
  1631. if (blockSize > remainingSize) return ERROR(srcSize_wrong);
  1632. switch(blockProperties.blockType)
  1633. {
  1634. case bt_compressed:
  1635. errorCode = ZSTD_decompressBlock(ctx, op, oend-op, ip, blockSize);
  1636. break;
  1637. case bt_raw :
  1638. errorCode = ZSTD_copyUncompressedBlock(op, oend-op, ip, blockSize);
  1639. break;
  1640. case bt_rle :
  1641. return ERROR(GENERIC); /* not yet supported */
  1642. break;
  1643. case bt_end :
  1644. /* end of frame */
  1645. if (remainingSize) return ERROR(srcSize_wrong);
  1646. break;
  1647. default:
  1648. return ERROR(GENERIC);
  1649. }
  1650. if (blockSize == 0) break; /* bt_end */
  1651. if (ZSTDv01_isError(errorCode)) return errorCode;
  1652. op += errorCode;
  1653. ip += blockSize;
  1654. remainingSize -= blockSize;
  1655. }
  1656. return op-ostart;
  1657. }
  1658. size_t ZSTDv01_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1659. {
  1660. dctx_t ctx;
  1661. ctx.base = dst;
  1662. return ZSTDv01_decompressDCtx(&ctx, dst, maxDstSize, src, srcSize);
  1663. }
  1664. /* ZSTD_errorFrameSizeInfoLegacy() :
  1665. assumes `cSize` and `dBound` are _not_ NULL */
  1666. static void ZSTD_errorFrameSizeInfoLegacy(size_t* cSize, unsigned long long* dBound, size_t ret)
  1667. {
  1668. *cSize = ret;
  1669. *dBound = ZSTD_CONTENTSIZE_ERROR;
  1670. }
  1671. void ZSTDv01_findFrameSizeInfoLegacy(const void *src, size_t srcSize, size_t* cSize, unsigned long long* dBound)
  1672. {
  1673. const BYTE* ip = (const BYTE*)src;
  1674. size_t remainingSize = srcSize;
  1675. size_t nbBlocks = 0;
  1676. U32 magicNumber;
  1677. blockProperties_t blockProperties;
  1678. /* Frame Header */
  1679. if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) {
  1680. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  1681. return;
  1682. }
  1683. magicNumber = ZSTD_readBE32(src);
  1684. if (magicNumber != ZSTD_magicNumber) {
  1685. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(prefix_unknown));
  1686. return;
  1687. }
  1688. ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize;
  1689. /* Loop on each block */
  1690. while (1)
  1691. {
  1692. size_t blockSize = ZSTDv01_getcBlockSize(ip, remainingSize, &blockProperties);
  1693. if (ZSTDv01_isError(blockSize)) {
  1694. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, blockSize);
  1695. return;
  1696. }
  1697. ip += ZSTD_blockHeaderSize;
  1698. remainingSize -= ZSTD_blockHeaderSize;
  1699. if (blockSize > remainingSize) {
  1700. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  1701. return;
  1702. }
  1703. if (blockSize == 0) break; /* bt_end */
  1704. ip += blockSize;
  1705. remainingSize -= blockSize;
  1706. nbBlocks++;
  1707. }
  1708. *cSize = ip - (const BYTE*)src;
  1709. *dBound = nbBlocks * BLOCKSIZE;
  1710. }
  1711. /*******************************
  1712. * Streaming Decompression API
  1713. *******************************/
  1714. size_t ZSTDv01_resetDCtx(ZSTDv01_Dctx* dctx)
  1715. {
  1716. dctx->expected = ZSTD_frameHeaderSize;
  1717. dctx->phase = 0;
  1718. dctx->previousDstEnd = NULL;
  1719. dctx->base = NULL;
  1720. return 0;
  1721. }
  1722. ZSTDv01_Dctx* ZSTDv01_createDCtx(void)
  1723. {
  1724. ZSTDv01_Dctx* dctx = (ZSTDv01_Dctx*)malloc(sizeof(ZSTDv01_Dctx));
  1725. if (dctx==NULL) return NULL;
  1726. ZSTDv01_resetDCtx(dctx);
  1727. return dctx;
  1728. }
  1729. size_t ZSTDv01_freeDCtx(ZSTDv01_Dctx* dctx)
  1730. {
  1731. free(dctx);
  1732. return 0;
  1733. }
  1734. size_t ZSTDv01_nextSrcSizeToDecompress(ZSTDv01_Dctx* dctx)
  1735. {
  1736. return ((dctx_t*)dctx)->expected;
  1737. }
  1738. size_t ZSTDv01_decompressContinue(ZSTDv01_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  1739. {
  1740. dctx_t* ctx = (dctx_t*)dctx;
  1741. /* Sanity check */
  1742. if (srcSize != ctx->expected) return ERROR(srcSize_wrong);
  1743. if (dst != ctx->previousDstEnd) /* not contiguous */
  1744. ctx->base = dst;
  1745. /* Decompress : frame header */
  1746. if (ctx->phase == 0)
  1747. {
  1748. /* Check frame magic header */
  1749. U32 magicNumber = ZSTD_readBE32(src);
  1750. if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown);
  1751. ctx->phase = 1;
  1752. ctx->expected = ZSTD_blockHeaderSize;
  1753. return 0;
  1754. }
  1755. /* Decompress : block header */
  1756. if (ctx->phase == 1)
  1757. {
  1758. blockProperties_t bp;
  1759. size_t blockSize = ZSTDv01_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  1760. if (ZSTDv01_isError(blockSize)) return blockSize;
  1761. if (bp.blockType == bt_end)
  1762. {
  1763. ctx->expected = 0;
  1764. ctx->phase = 0;
  1765. }
  1766. else
  1767. {
  1768. ctx->expected = blockSize;
  1769. ctx->bType = bp.blockType;
  1770. ctx->phase = 2;
  1771. }
  1772. return 0;
  1773. }
  1774. /* Decompress : block content */
  1775. {
  1776. size_t rSize;
  1777. switch(ctx->bType)
  1778. {
  1779. case bt_compressed:
  1780. rSize = ZSTD_decompressBlock(ctx, dst, maxDstSize, src, srcSize);
  1781. break;
  1782. case bt_raw :
  1783. rSize = ZSTD_copyUncompressedBlock(dst, maxDstSize, src, srcSize);
  1784. break;
  1785. case bt_rle :
  1786. return ERROR(GENERIC); /* not yet handled */
  1787. break;
  1788. case bt_end : /* should never happen (filtered at phase 1) */
  1789. rSize = 0;
  1790. break;
  1791. default:
  1792. return ERROR(GENERIC);
  1793. }
  1794. ctx->phase = 1;
  1795. ctx->expected = ZSTD_blockHeaderSize;
  1796. if (ZSTDv01_isError(rSize)) return rSize;
  1797. ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
  1798. return rSize;
  1799. }
  1800. }