zstd_internal.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. #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 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 const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 };
  139. static 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 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. static const U32 LL_bits[MaxLL+1] = { 0, 0, 0, 0, 0, 0, 0, 0,
  163. 0, 0, 0, 0, 0, 0, 0, 0,
  164. 1, 1, 1, 1, 2, 2, 3, 3,
  165. 4, 6, 7, 8, 9,10,11,12,
  166. 13,14,15,16 };
  167. static const S16 LL_defaultNorm[MaxLL+1] = { 4, 3, 2, 2, 2, 2, 2, 2,
  168. 2, 2, 2, 2, 2, 1, 1, 1,
  169. 2, 2, 2, 2, 2, 2, 2, 2,
  170. 2, 3, 2, 1, 1, 1, 1, 1,
  171. -1,-1,-1,-1 };
  172. #define LL_DEFAULTNORMLOG 6 /* for static allocation */
  173. static const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG;
  174. static const U32 ML_bits[MaxML+1] = { 0, 0, 0, 0, 0, 0, 0, 0,
  175. 0, 0, 0, 0, 0, 0, 0, 0,
  176. 0, 0, 0, 0, 0, 0, 0, 0,
  177. 0, 0, 0, 0, 0, 0, 0, 0,
  178. 1, 1, 1, 1, 2, 2, 3, 3,
  179. 4, 4, 5, 7, 8, 9,10,11,
  180. 12,13,14,15,16 };
  181. static const S16 ML_defaultNorm[MaxML+1] = { 1, 4, 3, 2, 2, 2, 2, 2,
  182. 2, 1, 1, 1, 1, 1, 1, 1,
  183. 1, 1, 1, 1, 1, 1, 1, 1,
  184. 1, 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 };
  188. #define ML_DEFAULTNORMLOG 6 /* for static allocation */
  189. static const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG;
  190. static const S16 OF_defaultNorm[DefaultMaxOff+1] = { 1, 1, 1, 1, 1, 1, 2, 2,
  191. 2, 1, 1, 1, 1, 1, 1, 1,
  192. 1, 1, 1, 1, 1, 1, 1, 1,
  193. -1,-1,-1,-1,-1 };
  194. #define OF_DEFAULTNORMLOG 5 /* for static allocation */
  195. static const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG;
  196. /*-*******************************************
  197. * Shared functions to include for inlining
  198. *********************************************/
  199. static void ZSTD_copy8(void* dst, const void* src) {
  200. #ifdef __aarch64__
  201. vst1_u8((uint8_t*)dst, vld1_u8((const uint8_t*)src));
  202. #else
  203. memcpy(dst, src, 8);
  204. #endif
  205. }
  206. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  207. static void ZSTD_copy16(void* dst, const void* src) {
  208. #ifdef __aarch64__
  209. vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src));
  210. #else
  211. memcpy(dst, src, 16);
  212. #endif
  213. }
  214. #define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; }
  215. #define WILDCOPY_OVERLENGTH 32
  216. #define WILDCOPY_VECLEN 16
  217. typedef enum {
  218. ZSTD_no_overlap,
  219. ZSTD_overlap_src_before_dst
  220. /* ZSTD_overlap_dst_before_src, */
  221. } ZSTD_overlap_e;
  222. /*! ZSTD_wildcopy() :
  223. * Custom version of memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0)
  224. * @param ovtype controls the overlap detection
  225. * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
  226. * - ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart.
  227. * The src buffer must be before the dst buffer.
  228. */
  229. MEM_STATIC FORCE_INLINE_ATTR
  230. void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e const ovtype)
  231. {
  232. ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src;
  233. const BYTE* ip = (const BYTE*)src;
  234. BYTE* op = (BYTE*)dst;
  235. BYTE* const oend = op + length;
  236. assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff <= -WILDCOPY_VECLEN));
  237. if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) {
  238. /* Handle short offset copies. */
  239. do {
  240. COPY8(op, ip)
  241. } while (op < oend);
  242. } else {
  243. assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN);
  244. /* Separate out the first COPY16() call because the copy length is
  245. * almost certain to be short, so the branches have different
  246. * probabilities. Since it is almost certain to be short, only do
  247. * one COPY16() in the first call. Then, do two calls per loop since
  248. * at that point it is more likely to have a high trip count.
  249. */
  250. #ifndef __aarch64__
  251. do {
  252. COPY16(op, ip);
  253. }
  254. while (op < oend);
  255. #else
  256. COPY16(op, ip);
  257. if (op >= oend) return;
  258. do {
  259. COPY16(op, ip);
  260. COPY16(op, ip);
  261. }
  262. while (op < oend);
  263. #endif
  264. }
  265. }
  266. MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  267. {
  268. size_t const length = MIN(dstCapacity, srcSize);
  269. if (length > 0) {
  270. memcpy(dst, src, length);
  271. }
  272. return length;
  273. }
  274. /* define "workspace is too large" as this number of times larger than needed */
  275. #define ZSTD_WORKSPACETOOLARGE_FACTOR 3
  276. /* when workspace is continuously too large
  277. * during at least this number of times,
  278. * context's memory usage is considered wasteful,
  279. * because it's sized to handle a worst case scenario which rarely happens.
  280. * In which case, resize it down to free some memory */
  281. #define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128
  282. /*-*******************************************
  283. * Private declarations
  284. *********************************************/
  285. typedef struct seqDef_s {
  286. U32 offset;
  287. U16 litLength;
  288. U16 matchLength;
  289. } seqDef;
  290. typedef struct {
  291. seqDef* sequencesStart;
  292. seqDef* sequences;
  293. BYTE* litStart;
  294. BYTE* lit;
  295. BYTE* llCode;
  296. BYTE* mlCode;
  297. BYTE* ofCode;
  298. size_t maxNbSeq;
  299. size_t maxNbLit;
  300. U32 longLengthID; /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */
  301. U32 longLengthPos;
  302. } seqStore_t;
  303. typedef struct {
  304. U32 litLength;
  305. U32 matchLength;
  306. } ZSTD_sequenceLength;
  307. /**
  308. * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences
  309. * indicated by longLengthPos and longLengthID, and adds MINMATCH back to matchLength.
  310. */
  311. MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq)
  312. {
  313. ZSTD_sequenceLength seqLen;
  314. seqLen.litLength = seq->litLength;
  315. seqLen.matchLength = seq->matchLength + MINMATCH;
  316. if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {
  317. if (seqStore->longLengthID == 1) {
  318. seqLen.litLength += 0xFFFF;
  319. }
  320. if (seqStore->longLengthID == 2) {
  321. seqLen.matchLength += 0xFFFF;
  322. }
  323. }
  324. return seqLen;
  325. }
  326. /**
  327. * Contains the compressed frame size and an upper-bound for the decompressed frame size.
  328. * Note: before using `compressedSize`, check for errors using ZSTD_isError().
  329. * similarly, before using `decompressedBound`, check for errors using:
  330. * `decompressedBound != ZSTD_CONTENTSIZE_ERROR`
  331. */
  332. typedef struct {
  333. size_t compressedSize;
  334. unsigned long long decompressedBound;
  335. } ZSTD_frameSizeInfo; /* decompress & legacy */
  336. const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */
  337. void ZSTD_seqToCodes(const seqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */
  338. /* custom memory allocation functions */
  339. void* ZSTD_malloc(size_t size, ZSTD_customMem customMem);
  340. void* ZSTD_calloc(size_t size, ZSTD_customMem customMem);
  341. void ZSTD_free(void* ptr, ZSTD_customMem customMem);
  342. MEM_STATIC U32 ZSTD_highbit32(U32 val) /* compress, dictBuilder, decodeCorpus */
  343. {
  344. assert(val != 0);
  345. {
  346. # if defined(_MSC_VER) /* Visual */
  347. unsigned long r=0;
  348. return _BitScanReverse(&r, val) ? (unsigned)r : 0;
  349. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */
  350. return __builtin_clz (val) ^ 31;
  351. # elif defined(__ICCARM__) /* IAR Intrinsic */
  352. return 31 - __CLZ(val);
  353. # else /* Software version */
  354. 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 };
  355. U32 v = val;
  356. v |= v >> 1;
  357. v |= v >> 2;
  358. v |= v >> 4;
  359. v |= v >> 8;
  360. v |= v >> 16;
  361. return DeBruijnClz[(v * 0x07C4ACDDU) >> 27];
  362. # endif
  363. }
  364. }
  365. /* ZSTD_invalidateRepCodes() :
  366. * ensures next compression will not use repcodes from previous block.
  367. * Note : only works with regular variant;
  368. * do not use with extDict variant ! */
  369. void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */
  370. typedef struct {
  371. blockType_e blockType;
  372. U32 lastBlock;
  373. U32 origSize;
  374. } blockProperties_t; /* declared here for decompress and fullbench */
  375. /*! ZSTD_getcBlockSize() :
  376. * Provides the size of compressed block from block header `src` */
  377. /* Used by: decompress, fullbench (does not get its definition from here) */
  378. size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
  379. blockProperties_t* bpPtr);
  380. /*! ZSTD_decodeSeqHeaders() :
  381. * decode sequence header from src */
  382. /* Used by: decompress, fullbench (does not get its definition from here) */
  383. size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
  384. const void* src, size_t srcSize);
  385. #if defined (__cplusplus)
  386. }
  387. #endif
  388. #endif /* ZSTD_CCOMMON_H_MODULE */