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 15KB

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