You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_internal.h 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #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. #include "compiler.h"
  20. #include "cpu.h"
  21. #include "mem.h"
  22. #include "debug.h" /* assert, DEBUGLOG, RAWLOG, g_debuglevel */
  23. #include "error_private.h"
  24. #define ZSTD_STATIC_LINKING_ONLY
  25. #include "zstd.h"
  26. #define FSE_STATIC_LINKING_ONLY
  27. #include "fse.h"
  28. #include "huf.h"
  29. #ifndef XXH_STATIC_LINKING_ONLY
  30. # define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
  31. #endif
  32. #include "xxhash.h" /* XXH_reset, update, digest */
  33. #ifndef ZSTD_NO_TRACE
  34. # include "zstd_trace.h"
  35. #else
  36. # define ZSTD_TRACE 0
  37. #endif
  38. #if defined (__cplusplus)
  39. extern "C" {
  40. #endif
  41. /* ---- static assert (debug) --- */
  42. #define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)
  43. #define ZSTD_isError ERR_isError /* for inlining */
  44. #define FSE_isError ERR_isError
  45. #define HUF_isError ERR_isError
  46. /*-*************************************
  47. * shared macros
  48. ***************************************/
  49. #undef MIN
  50. #undef MAX
  51. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  52. #define MAX(a,b) ((a)>(b) ? (a) : (b))
  53. #define BOUNDED(min,val,max) (MAX(min,MIN(val,max)))
  54. /*-*************************************
  55. * Common constants
  56. ***************************************/
  57. #define ZSTD_OPT_NUM (1<<12)
  58. #define ZSTD_REP_NUM 3 /* number of repcodes */
  59. static UNUSED_ATTR const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 };
  60. #define KB *(1 <<10)
  61. #define MB *(1 <<20)
  62. #define GB *(1U<<30)
  63. #define BIT7 128
  64. #define BIT6 64
  65. #define BIT5 32
  66. #define BIT4 16
  67. #define BIT1 2
  68. #define BIT0 1
  69. #define ZSTD_WINDOWLOG_ABSOLUTEMIN 10
  70. static UNUSED_ATTR const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 };
  71. static UNUSED_ATTR const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 };
  72. #define ZSTD_FRAMEIDSIZE 4 /* magic number size */
  73. #define ZSTD_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */
  74. static UNUSED_ATTR const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE;
  75. typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e;
  76. #define ZSTD_FRAMECHECKSUMSIZE 4
  77. #define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
  78. #define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */) /* for a non-null block */
  79. #define MIN_LITERALS_FOR_4_STREAMS 6
  80. typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e;
  81. #define LONGNBSEQ 0x7F00
  82. #define MINMATCH 3
  83. #define Litbits 8
  84. #define LitHufLog 11
  85. #define MaxLit ((1<<Litbits) - 1)
  86. #define MaxML 52
  87. #define MaxLL 35
  88. #define DefaultMaxOff 28
  89. #define MaxOff 31
  90. #define MaxSeq MAX(MaxLL, MaxML) /* Assumption : MaxOff < MaxLL,MaxML */
  91. #define MLFSELog 9
  92. #define LLFSELog 9
  93. #define OffFSELog 8
  94. #define MaxFSELog MAX(MAX(MLFSELog, LLFSELog), OffFSELog)
  95. #define MaxMLBits 16
  96. #define MaxLLBits 16
  97. #define ZSTD_MAX_HUF_HEADER_SIZE 128 /* header + <= 127 byte tree description */
  98. /* Each table cannot take more than #symbols * FSELog bits */
  99. #define ZSTD_MAX_FSE_HEADERS_SIZE (((MaxML + 1) * MLFSELog + (MaxLL + 1) * LLFSELog + (MaxOff + 1) * OffFSELog + 7) / 8)
  100. static UNUSED_ATTR const U8 LL_bits[MaxLL+1] = {
  101. 0, 0, 0, 0, 0, 0, 0, 0,
  102. 0, 0, 0, 0, 0, 0, 0, 0,
  103. 1, 1, 1, 1, 2, 2, 3, 3,
  104. 4, 6, 7, 8, 9,10,11,12,
  105. 13,14,15,16
  106. };
  107. static UNUSED_ATTR const S16 LL_defaultNorm[MaxLL+1] = {
  108. 4, 3, 2, 2, 2, 2, 2, 2,
  109. 2, 2, 2, 2, 2, 1, 1, 1,
  110. 2, 2, 2, 2, 2, 2, 2, 2,
  111. 2, 3, 2, 1, 1, 1, 1, 1,
  112. -1,-1,-1,-1
  113. };
  114. #define LL_DEFAULTNORMLOG 6 /* for static allocation */
  115. static UNUSED_ATTR const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG;
  116. static UNUSED_ATTR const U8 ML_bits[MaxML+1] = {
  117. 0, 0, 0, 0, 0, 0, 0, 0,
  118. 0, 0, 0, 0, 0, 0, 0, 0,
  119. 0, 0, 0, 0, 0, 0, 0, 0,
  120. 0, 0, 0, 0, 0, 0, 0, 0,
  121. 1, 1, 1, 1, 2, 2, 3, 3,
  122. 4, 4, 5, 7, 8, 9,10,11,
  123. 12,13,14,15,16
  124. };
  125. static UNUSED_ATTR const S16 ML_defaultNorm[MaxML+1] = {
  126. 1, 4, 3, 2, 2, 2, 2, 2,
  127. 2, 1, 1, 1, 1, 1, 1, 1,
  128. 1, 1, 1, 1, 1, 1, 1, 1,
  129. 1, 1, 1, 1, 1, 1, 1, 1,
  130. 1, 1, 1, 1, 1, 1, 1, 1,
  131. 1, 1, 1, 1, 1, 1,-1,-1,
  132. -1,-1,-1,-1,-1
  133. };
  134. #define ML_DEFAULTNORMLOG 6 /* for static allocation */
  135. static UNUSED_ATTR const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG;
  136. static UNUSED_ATTR const S16 OF_defaultNorm[DefaultMaxOff+1] = {
  137. 1, 1, 1, 1, 1, 1, 2, 2,
  138. 2, 1, 1, 1, 1, 1, 1, 1,
  139. 1, 1, 1, 1, 1, 1, 1, 1,
  140. -1,-1,-1,-1,-1
  141. };
  142. #define OF_DEFAULTNORMLOG 5 /* for static allocation */
  143. static UNUSED_ATTR const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG;
  144. /*-*******************************************
  145. * Shared functions to include for inlining
  146. *********************************************/
  147. static void ZSTD_copy8(void* dst, const void* src) {
  148. #if defined(ZSTD_ARCH_ARM_NEON)
  149. vst1_u8((uint8_t*)dst, vld1_u8((const uint8_t*)src));
  150. #else
  151. ZSTD_memcpy(dst, src, 8);
  152. #endif
  153. }
  154. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  155. /* Need to use memmove here since the literal buffer can now be located within
  156. the dst buffer. In circumstances where the op "catches up" to where the
  157. literal buffer is, there can be partial overlaps in this call on the final
  158. copy if the literal is being shifted by less than 16 bytes. */
  159. static void ZSTD_copy16(void* dst, const void* src) {
  160. #if defined(ZSTD_ARCH_ARM_NEON)
  161. vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src));
  162. #elif defined(ZSTD_ARCH_X86_SSE2)
  163. _mm_storeu_si128((__m128i*)dst, _mm_loadu_si128((const __m128i*)src));
  164. #elif defined(__clang__)
  165. ZSTD_memmove(dst, src, 16);
  166. #else
  167. /* ZSTD_memmove is not inlined properly by gcc */
  168. BYTE copy16_buf[16];
  169. ZSTD_memcpy(copy16_buf, src, 16);
  170. ZSTD_memcpy(dst, copy16_buf, 16);
  171. #endif
  172. }
  173. #define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; }
  174. #define WILDCOPY_OVERLENGTH 32
  175. #define WILDCOPY_VECLEN 16
  176. typedef enum {
  177. ZSTD_no_overlap,
  178. ZSTD_overlap_src_before_dst
  179. /* ZSTD_overlap_dst_before_src, */
  180. } ZSTD_overlap_e;
  181. /*! ZSTD_wildcopy() :
  182. * Custom version of ZSTD_memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0)
  183. * @param ovtype controls the overlap detection
  184. * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  185. * - ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart.
  186. * The src buffer must be before the dst buffer.
  187. */
  188. MEM_STATIC FORCE_INLINE_ATTR
  189. void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e const ovtype)
  190. {
  191. ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src;
  192. const BYTE* ip = (const BYTE*)src;
  193. BYTE* op = (BYTE*)dst;
  194. BYTE* const oend = op + length;
  195. if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) {
  196. /* Handle short offset copies. */
  197. do {
  198. COPY8(op, ip)
  199. } while (op < oend);
  200. } else {
  201. assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN);
  202. /* Separate out the first COPY16() call because the copy length is
  203. * almost certain to be short, so the branches have different
  204. * probabilities. Since it is almost certain to be short, only do
  205. * one COPY16() in the first call. Then, do two calls per loop since
  206. * at that point it is more likely to have a high trip count.
  207. */
  208. ZSTD_copy16(op, ip);
  209. if (16 >= length) return;
  210. op += 16;
  211. ip += 16;
  212. do {
  213. COPY16(op, ip);
  214. COPY16(op, ip);
  215. }
  216. while (op < oend);
  217. }
  218. }
  219. MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  220. {
  221. size_t const length = MIN(dstCapacity, srcSize);
  222. if (length > 0) {
  223. ZSTD_memcpy(dst, src, length);
  224. }
  225. return length;
  226. }
  227. /* define "workspace is too large" as this number of times larger than needed */
  228. #define ZSTD_WORKSPACETOOLARGE_FACTOR 3
  229. /* when workspace is continuously too large
  230. * during at least this number of times,
  231. * context's memory usage is considered wasteful,
  232. * because it's sized to handle a worst case scenario which rarely happens.
  233. * In which case, resize it down to free some memory */
  234. #define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128
  235. /* Controls whether the input/output buffer is buffered or stable. */
  236. typedef enum {
  237. ZSTD_bm_buffered = 0, /* Buffer the input/output */
  238. ZSTD_bm_stable = 1 /* ZSTD_inBuffer/ZSTD_outBuffer is stable */
  239. } ZSTD_bufferMode_e;
  240. /*-*******************************************
  241. * Private declarations
  242. *********************************************/
  243. typedef struct seqDef_s {
  244. U32 offBase; /* offBase == Offset + ZSTD_REP_NUM, or repcode 1,2,3 */
  245. U16 litLength;
  246. U16 mlBase; /* mlBase == matchLength - MINMATCH */
  247. } seqDef;
  248. /* Controls whether seqStore has a single "long" litLength or matchLength. See seqStore_t. */
  249. typedef enum {
  250. ZSTD_llt_none = 0, /* no longLengthType */
  251. ZSTD_llt_literalLength = 1, /* represents a long literal */
  252. ZSTD_llt_matchLength = 2 /* represents a long match */
  253. } ZSTD_longLengthType_e;
  254. typedef struct {
  255. seqDef* sequencesStart;
  256. seqDef* sequences; /* ptr to end of sequences */
  257. BYTE* litStart;
  258. BYTE* lit; /* ptr to end of literals */
  259. BYTE* llCode;
  260. BYTE* mlCode;
  261. BYTE* ofCode;
  262. size_t maxNbSeq;
  263. size_t maxNbLit;
  264. /* longLengthPos and longLengthType to allow us to represent either a single litLength or matchLength
  265. * in the seqStore that has a value larger than U16 (if it exists). To do so, we increment
  266. * the existing value of the litLength or matchLength by 0x10000.
  267. */
  268. ZSTD_longLengthType_e longLengthType;
  269. U32 longLengthPos; /* Index of the sequence to apply long length modification to */
  270. } seqStore_t;
  271. typedef struct {
  272. U32 litLength;
  273. U32 matchLength;
  274. } ZSTD_sequenceLength;
  275. /**
  276. * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences
  277. * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength.
  278. */
  279. MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq)
  280. {
  281. ZSTD_sequenceLength seqLen;
  282. seqLen.litLength = seq->litLength;
  283. seqLen.matchLength = seq->mlBase + MINMATCH;
  284. if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {
  285. if (seqStore->longLengthType == ZSTD_llt_literalLength) {
  286. seqLen.litLength += 0x10000;
  287. }
  288. if (seqStore->longLengthType == ZSTD_llt_matchLength) {
  289. seqLen.matchLength += 0x10000;
  290. }
  291. }
  292. return seqLen;
  293. }
  294. /**
  295. * Contains the compressed frame size and an upper-bound for the decompressed frame size.
  296. * Note: before using `compressedSize`, check for errors using ZSTD_isError().
  297. * similarly, before using `decompressedBound`, check for errors using:
  298. * `decompressedBound != ZSTD_CONTENTSIZE_ERROR`
  299. */
  300. typedef struct {
  301. size_t nbBlocks;
  302. size_t compressedSize;
  303. unsigned long long decompressedBound;
  304. } ZSTD_frameSizeInfo; /* decompress & legacy */
  305. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */
  306. int ZSTD_seqToCodes(const seqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */
  307. /* custom memory allocation functions */
  308. void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem);
  309. void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem);
  310. void ZSTD_customFree(void* ptr, ZSTD_customMem customMem);
  311. /* ZSTD_invalidateRepCodes() :
  312. * ensures next compression will not use repcodes from previous block.
  313. * Note : only works with regular variant;
  314. * do not use with extDict variant ! */
  315. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */
  316. typedef struct {
  317. blockType_e blockType;
  318. U32 lastBlock;
  319. U32 origSize;
  320. } blockProperties_t; /* declared here for decompress and fullbench */
  321. /*! ZSTD_getcBlockSize() :
  322. * Provides the size of compressed block from block header `src` */
  323. /* Used by: decompress, fullbench (does not get its definition from here) */
  324. size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
  325. blockProperties_t* bpPtr);
  326. /*! ZSTD_decodeSeqHeaders() :
  327. * decode sequence header from src */
  328. /* Used by: decompress, fullbench (does not get its definition from here) */
  329. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
  330. const void* src, size_t srcSize);
  331. /**
  332. * @returns true iff the CPU supports dynamic BMI2 dispatch.
  333. */
  334. MEM_STATIC int ZSTD_cpuSupportsBmi2(void)
  335. {
  336. ZSTD_cpuid_t cpuid = ZSTD_cpuid();
  337. return ZSTD_cpuid_bmi1(cpuid) && ZSTD_cpuid_bmi2(cpuid);
  338. }
  339. #if defined (__cplusplus)
  340. }
  341. #endif
  342. #endif /* ZSTD_CCOMMON_H_MODULE */