2
0

zstd_internal.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #ifndef ZSTD_CCOMMON_H_MODULE
  11. #define ZSTD_CCOMMON_H_MODULE
  12. /* this module contains definitions which must be identical
  13. * across compression, decompression and dictBuilder.
  14. * It also contains a few functions useful to at least 2 of them
  15. * and which benefit from being inlined */
  16. /*-*************************************
  17. * Dependencies
  18. ***************************************/
  19. #if !defined(ZSTD_NO_INTRINSICS) && defined(__ARM_NEON)
  20. #include <arm_neon.h>
  21. #endif
  22. #include "compiler.h"
  23. #include "mem.h"
  24. #include "debug.h" /* assert, DEBUGLOG, RAWLOG, g_debuglevel */
  25. #include "error_private.h"
  26. #define ZSTD_STATIC_LINKING_ONLY
  27. #include "../zstd.h"
  28. #define FSE_STATIC_LINKING_ONLY
  29. #include "fse.h"
  30. #define HUF_STATIC_LINKING_ONLY
  31. #include "huf.h"
  32. #ifndef XXH_STATIC_LINKING_ONLY
  33. # define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
  34. #endif
  35. #include "xxhash.h" /* XXH_reset, update, digest */
  36. #if defined (__cplusplus)
  37. extern "C" {
  38. #endif
  39. /* ---- static assert (debug) --- */
  40. #define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)
  41. #define ZSTD_isError ERR_isError /* for inlining */
  42. #define FSE_isError ERR_isError
  43. #define HUF_isError ERR_isError
  44. /*-*************************************
  45. * shared macros
  46. ***************************************/
  47. #undef MIN
  48. #undef MAX
  49. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  50. #define MAX(a,b) ((a)>(b) ? (a) : (b))
  51. /**
  52. * Ignore: this is an internal helper.
  53. *
  54. * This is a helper function to help force C99-correctness during compilation.
  55. * Under strict compilation modes, variadic macro arguments can't be empty.
  56. * However, variadic function arguments can be. Using a function therefore lets
  57. * us statically check that at least one (string) argument was passed,
  58. * independent of the compilation flags.
  59. */
  60. static INLINE_KEYWORD UNUSED_ATTR
  61. void _force_has_format_string(const char *format, ...) {
  62. (void)format;
  63. }
  64. /**
  65. * Ignore: this is an internal helper.
  66. *
  67. * We want to force this function invocation to be syntactically correct, but
  68. * we don't want to force runtime evaluation of its arguments.
  69. */
  70. #define _FORCE_HAS_FORMAT_STRING(...) \
  71. if (0) { \
  72. _force_has_format_string(__VA_ARGS__); \
  73. }
  74. /**
  75. * Return the specified error if the condition evaluates to true.
  76. *
  77. * In debug modes, prints additional information.
  78. * In order to do that (particularly, printing the conditional that failed),
  79. * this can't just wrap RETURN_ERROR().
  80. */
  81. #define RETURN_ERROR_IF(cond, err, ...) \
  82. if (cond) { \
  83. RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s", \
  84. __FILE__, __LINE__, ZSTD_QUOTE(cond), ZSTD_QUOTE(ERROR(err))); \
  85. _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
  86. RAWLOG(3, ": " __VA_ARGS__); \
  87. RAWLOG(3, "\n"); \
  88. return ERROR(err); \
  89. }
  90. /**
  91. * Unconditionally return the specified error.
  92. *
  93. * In debug modes, prints additional information.
  94. */
  95. #define RETURN_ERROR(err, ...) \
  96. do { \
  97. RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \
  98. __FILE__, __LINE__, ZSTD_QUOTE(ERROR(err))); \
  99. _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
  100. RAWLOG(3, ": " __VA_ARGS__); \
  101. RAWLOG(3, "\n"); \
  102. return ERROR(err); \
  103. } while(0);
  104. /**
  105. * If the provided expression evaluates to an error code, returns that error code.
  106. *
  107. * In debug modes, prints additional information.
  108. */
  109. #define FORWARD_IF_ERROR(err, ...) \
  110. do { \
  111. size_t const err_code = (err); \
  112. if (ERR_isError(err_code)) { \
  113. RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s", \
  114. __FILE__, __LINE__, ZSTD_QUOTE(err), ERR_getErrorName(err_code)); \
  115. _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
  116. RAWLOG(3, ": " __VA_ARGS__); \
  117. RAWLOG(3, "\n"); \
  118. return err_code; \
  119. } \
  120. } while(0);
  121. /*-*************************************
  122. * Common constants
  123. ***************************************/
  124. #define ZSTD_OPT_NUM (1<<12)
  125. #define ZSTD_REP_NUM 3 /* number of repcodes */
  126. #define ZSTD_REP_MOVE (ZSTD_REP_NUM-1)
  127. static UNUSED_ATTR const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 };
  128. #define KB *(1 <<10)
  129. #define MB *(1 <<20)
  130. #define GB *(1U<<30)
  131. #define BIT7 128
  132. #define BIT6 64
  133. #define BIT5 32
  134. #define BIT4 16
  135. #define BIT1 2
  136. #define BIT0 1
  137. #define ZSTD_WINDOWLOG_ABSOLUTEMIN 10
  138. static UNUSED_ATTR const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 };
  139. static UNUSED_ATTR const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 };
  140. #define ZSTD_FRAMEIDSIZE 4 /* magic number size */
  141. #define ZSTD_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */
  142. static UNUSED_ATTR const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE;
  143. typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e;
  144. #define ZSTD_FRAMECHECKSUMSIZE 4
  145. #define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
  146. #define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */) /* for a non-null block */
  147. #define HufLog 12
  148. typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e;
  149. #define LONGNBSEQ 0x7F00
  150. #define MINMATCH 3
  151. #define Litbits 8
  152. #define MaxLit ((1<<Litbits) - 1)
  153. #define MaxML 52
  154. #define MaxLL 35
  155. #define DefaultMaxOff 28
  156. #define MaxOff 31
  157. #define MaxSeq MAX(MaxLL, MaxML) /* Assumption : MaxOff < MaxLL,MaxML */
  158. #define MLFSELog 9
  159. #define LLFSELog 9
  160. #define OffFSELog 8
  161. #define MaxFSELog MAX(MAX(MLFSELog, LLFSELog), OffFSELog)
  162. #define ZSTD_MAX_HUF_HEADER_SIZE 128 /* header + <= 127 byte tree description */
  163. /* Each table cannot take more than #symbols * FSELog bits */
  164. #define ZSTD_MAX_FSE_HEADERS_SIZE (((MaxML + 1) * MLFSELog + (MaxLL + 1) * LLFSELog + (MaxOff + 1) * OffFSELog + 7) / 8)
  165. static UNUSED_ATTR const U32 LL_bits[MaxLL+1] = {
  166. 0, 0, 0, 0, 0, 0, 0, 0,
  167. 0, 0, 0, 0, 0, 0, 0, 0,
  168. 1, 1, 1, 1, 2, 2, 3, 3,
  169. 4, 6, 7, 8, 9,10,11,12,
  170. 13,14,15,16
  171. };
  172. static UNUSED_ATTR const S16 LL_defaultNorm[MaxLL+1] = {
  173. 4, 3, 2, 2, 2, 2, 2, 2,
  174. 2, 2, 2, 2, 2, 1, 1, 1,
  175. 2, 2, 2, 2, 2, 2, 2, 2,
  176. 2, 3, 2, 1, 1, 1, 1, 1,
  177. -1,-1,-1,-1
  178. };
  179. #define LL_DEFAULTNORMLOG 6 /* for static allocation */
  180. static UNUSED_ATTR const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG;
  181. static UNUSED_ATTR const U32 ML_bits[MaxML+1] = {
  182. 0, 0, 0, 0, 0, 0, 0, 0,
  183. 0, 0, 0, 0, 0, 0, 0, 0,
  184. 0, 0, 0, 0, 0, 0, 0, 0,
  185. 0, 0, 0, 0, 0, 0, 0, 0,
  186. 1, 1, 1, 1, 2, 2, 3, 3,
  187. 4, 4, 5, 7, 8, 9,10,11,
  188. 12,13,14,15,16
  189. };
  190. static UNUSED_ATTR const S16 ML_defaultNorm[MaxML+1] = {
  191. 1, 4, 3, 2, 2, 2, 2, 2,
  192. 2, 1, 1, 1, 1, 1, 1, 1,
  193. 1, 1, 1, 1, 1, 1, 1, 1,
  194. 1, 1, 1, 1, 1, 1, 1, 1,
  195. 1, 1, 1, 1, 1, 1, 1, 1,
  196. 1, 1, 1, 1, 1, 1,-1,-1,
  197. -1,-1,-1,-1,-1
  198. };
  199. #define ML_DEFAULTNORMLOG 6 /* for static allocation */
  200. static UNUSED_ATTR const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG;
  201. static UNUSED_ATTR const S16 OF_defaultNorm[DefaultMaxOff+1] = {
  202. 1, 1, 1, 1, 1, 1, 2, 2,
  203. 2, 1, 1, 1, 1, 1, 1, 1,
  204. 1, 1, 1, 1, 1, 1, 1, 1,
  205. -1,-1,-1,-1,-1
  206. };
  207. #define OF_DEFAULTNORMLOG 5 /* for static allocation */
  208. static UNUSED_ATTR const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG;
  209. /*-*******************************************
  210. * Shared functions to include for inlining
  211. *********************************************/
  212. static void ZSTD_copy8(void* dst, const void* src) {
  213. #if !defined(ZSTD_NO_INTRINSICS) && defined(__ARM_NEON)
  214. vst1_u8((uint8_t*)dst, vld1_u8((const uint8_t*)src));
  215. #else
  216. ZSTD_memcpy(dst, src, 8);
  217. #endif
  218. }
  219. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  220. static void ZSTD_copy16(void* dst, const void* src) {
  221. #if !defined(ZSTD_NO_INTRINSICS) && defined(__ARM_NEON)
  222. vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src));
  223. #else
  224. ZSTD_memcpy(dst, src, 16);
  225. #endif
  226. }
  227. #define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; }
  228. #define WILDCOPY_OVERLENGTH 32
  229. #define WILDCOPY_VECLEN 16
  230. typedef enum {
  231. ZSTD_no_overlap,
  232. ZSTD_overlap_src_before_dst
  233. /* ZSTD_overlap_dst_before_src, */
  234. } ZSTD_overlap_e;
  235. /*! ZSTD_wildcopy() :
  236. * Custom version of ZSTD_memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0)
  237. * @param ovtype controls the overlap detection
  238. * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  239. * - ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart.
  240. * The src buffer must be before the dst buffer.
  241. */
  242. MEM_STATIC FORCE_INLINE_ATTR
  243. void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e const ovtype)
  244. {
  245. ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src;
  246. const BYTE* ip = (const BYTE*)src;
  247. BYTE* op = (BYTE*)dst;
  248. BYTE* const oend = op + length;
  249. assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff <= -WILDCOPY_VECLEN));
  250. if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) {
  251. /* Handle short offset copies. */
  252. do {
  253. COPY8(op, ip)
  254. } while (op < oend);
  255. } else {
  256. assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN);
  257. /* Separate out the first COPY16() call because the copy length is
  258. * almost certain to be short, so the branches have different
  259. * probabilities. Since it is almost certain to be short, only do
  260. * one COPY16() in the first call. Then, do two calls per loop since
  261. * at that point it is more likely to have a high trip count.
  262. */
  263. #ifdef __aarch64__
  264. do {
  265. COPY16(op, ip);
  266. }
  267. while (op < oend);
  268. #else
  269. ZSTD_copy16(op, ip);
  270. if (16 >= length) return;
  271. op += 16;
  272. ip += 16;
  273. do {
  274. COPY16(op, ip);
  275. COPY16(op, ip);
  276. }
  277. while (op < oend);
  278. #endif
  279. }
  280. }
  281. MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  282. {
  283. size_t const length = MIN(dstCapacity, srcSize);
  284. if (length > 0) {
  285. ZSTD_memcpy(dst, src, length);
  286. }
  287. return length;
  288. }
  289. /* define "workspace is too large" as this number of times larger than needed */
  290. #define ZSTD_WORKSPACETOOLARGE_FACTOR 3
  291. /* when workspace is continuously too large
  292. * during at least this number of times,
  293. * context's memory usage is considered wasteful,
  294. * because it's sized to handle a worst case scenario which rarely happens.
  295. * In which case, resize it down to free some memory */
  296. #define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128
  297. /* Controls whether the input/output buffer is buffered or stable. */
  298. typedef enum {
  299. ZSTD_bm_buffered = 0, /* Buffer the input/output */
  300. ZSTD_bm_stable = 1 /* ZSTD_inBuffer/ZSTD_outBuffer is stable */
  301. } ZSTD_bufferMode_e;
  302. /*-*******************************************
  303. * Private declarations
  304. *********************************************/
  305. typedef struct seqDef_s {
  306. U32 offset; /* Offset code of the sequence */
  307. U16 litLength;
  308. U16 matchLength;
  309. } seqDef;
  310. typedef struct {
  311. seqDef* sequencesStart;
  312. seqDef* sequences; /* ptr to end of sequences */
  313. BYTE* litStart;
  314. BYTE* lit; /* ptr to end of literals */
  315. BYTE* llCode;
  316. BYTE* mlCode;
  317. BYTE* ofCode;
  318. size_t maxNbSeq;
  319. size_t maxNbLit;
  320. /* longLengthPos and longLengthID to allow us to represent either a single litLength or matchLength
  321. * in the seqStore that has a value larger than U16 (if it exists). To do so, we increment
  322. * the existing value of the litLength or matchLength by 0x10000.
  323. */
  324. U32 longLengthID; /* 0 == no longLength; 1 == Represent the long literal; 2 == Represent the long match; */
  325. U32 longLengthPos; /* Index of the sequence to apply long length modification to */
  326. } seqStore_t;
  327. typedef struct {
  328. U32 litLength;
  329. U32 matchLength;
  330. } ZSTD_sequenceLength;
  331. /**
  332. * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences
  333. * indicated by longLengthPos and longLengthID, and adds MINMATCH back to matchLength.
  334. */
  335. MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq)
  336. {
  337. ZSTD_sequenceLength seqLen;
  338. seqLen.litLength = seq->litLength;
  339. seqLen.matchLength = seq->matchLength + MINMATCH;
  340. if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {
  341. if (seqStore->longLengthID == 1) {
  342. seqLen.litLength += 0xFFFF;
  343. }
  344. if (seqStore->longLengthID == 2) {
  345. seqLen.matchLength += 0xFFFF;
  346. }
  347. }
  348. return seqLen;
  349. }
  350. /**
  351. * Contains the compressed frame size and an upper-bound for the decompressed frame size.
  352. * Note: before using `compressedSize`, check for errors using ZSTD_isError().
  353. * similarly, before using `decompressedBound`, check for errors using:
  354. * `decompressedBound != ZSTD_CONTENTSIZE_ERROR`
  355. */
  356. typedef struct {
  357. size_t compressedSize;
  358. unsigned long long decompressedBound;
  359. } ZSTD_frameSizeInfo; /* decompress & legacy */
  360. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */
  361. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */
  362. /* custom memory allocation functions */
  363. void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem);
  364. void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem);
  365. void ZSTD_customFree(void* ptr, ZSTD_customMem customMem);
  366. MEM_STATIC U32 ZSTD_highbit32(U32 val) /* compress, dictBuilder, decodeCorpus */
  367. {
  368. assert(val != 0);
  369. {
  370. # if defined(_MSC_VER) /* Visual */
  371. # if STATIC_BMI2 == 1
  372. return _lzcnt_u32(val)^31;
  373. # else
  374. unsigned long r=0;
  375. return _BitScanReverse(&r, val) ? (unsigned)r : 0;
  376. # endif
  377. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */
  378. return __builtin_clz (val) ^ 31;
  379. # elif defined(__ICCARM__) /* IAR Intrinsic */
  380. return 31 - __CLZ(val);
  381. # else /* Software version */
  382. static const U32 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 };
  383. U32 v = val;
  384. v |= v >> 1;
  385. v |= v >> 2;
  386. v |= v >> 4;
  387. v |= v >> 8;
  388. v |= v >> 16;
  389. return DeBruijnClz[(v * 0x07C4ACDDU) >> 27];
  390. # endif
  391. }
  392. }
  393. /* ZSTD_invalidateRepCodes() :
  394. * ensures next compression will not use repcodes from previous block.
  395. * Note : only works with regular variant;
  396. * do not use with extDict variant ! */
  397. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */
  398. typedef struct {
  399. blockType_e blockType;
  400. U32 lastBlock;
  401. U32 origSize;
  402. } blockProperties_t; /* declared here for decompress and fullbench */
  403. /*! ZSTD_getcBlockSize() :
  404. * Provides the size of compressed block from block header `src` */
  405. /* Used by: decompress, fullbench (does not get its definition from here) */
  406. size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
  407. blockProperties_t* bpPtr);
  408. /*! ZSTD_decodeSeqHeaders() :
  409. * decode sequence header from src */
  410. /* Used by: decompress, fullbench (does not get its definition from here) */
  411. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
  412. const void* src, size_t srcSize);
  413. #if defined (__cplusplus)
  414. }
  415. #endif
  416. #endif /* ZSTD_CCOMMON_H_MODULE */