zstd_compress_internal.h 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  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. /* This header contains definitions
  11. * that shall **only** be used by modules within lib/compress.
  12. */
  13. #ifndef ZSTD_COMPRESS_H
  14. #define ZSTD_COMPRESS_H
  15. /*-*************************************
  16. * Dependencies
  17. ***************************************/
  18. #include "../common/zstd_internal.h"
  19. #include "zstd_cwksp.h"
  20. #ifdef ZSTD_MULTITHREAD
  21. # include "zstdmt_compress.h"
  22. #endif
  23. #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */
  24. #include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */
  25. /*-*************************************
  26. * Constants
  27. ***************************************/
  28. #define kSearchStrength 8
  29. #define HASH_READ_SIZE 8
  30. #define ZSTD_DUBT_UNSORTED_MARK 1 /* For btlazy2 strategy, index ZSTD_DUBT_UNSORTED_MARK==1 means "unsorted".
  31. It could be confused for a real successor at index "1", if sorted as larger than its predecessor.
  32. It's not a big deal though : candidate will just be sorted again.
  33. Additionally, candidate position 1 will be lost.
  34. But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.
  35. The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table reuse with a different strategy.
  36. This constant is required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */
  37. /*-*************************************
  38. * Context memory management
  39. ***************************************/
  40. typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;
  41. typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;
  42. typedef struct ZSTD_prefixDict_s {
  43. const void* dict;
  44. size_t dictSize;
  45. ZSTD_dictContentType_e dictContentType;
  46. } ZSTD_prefixDict;
  47. typedef struct {
  48. void* dictBuffer;
  49. void const* dict;
  50. size_t dictSize;
  51. ZSTD_dictContentType_e dictContentType;
  52. ZSTD_CDict* cdict;
  53. } ZSTD_localDict;
  54. typedef struct {
  55. HUF_CElt CTable[HUF_CTABLE_SIZE_ST(255)];
  56. HUF_repeat repeatMode;
  57. } ZSTD_hufCTables_t;
  58. typedef struct {
  59. FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];
  60. FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];
  61. FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];
  62. FSE_repeat offcode_repeatMode;
  63. FSE_repeat matchlength_repeatMode;
  64. FSE_repeat litlength_repeatMode;
  65. } ZSTD_fseCTables_t;
  66. typedef struct {
  67. ZSTD_hufCTables_t huf;
  68. ZSTD_fseCTables_t fse;
  69. } ZSTD_entropyCTables_t;
  70. /***********************************************
  71. * Sequences *
  72. ***********************************************/
  73. typedef struct SeqDef_s {
  74. U32 offBase; /* offBase == Offset + ZSTD_REP_NUM, or repcode 1,2,3 */
  75. U16 litLength;
  76. U16 mlBase; /* mlBase == matchLength - MINMATCH */
  77. } SeqDef;
  78. /* Controls whether seqStore has a single "long" litLength or matchLength. See SeqStore_t. */
  79. typedef enum {
  80. ZSTD_llt_none = 0, /* no longLengthType */
  81. ZSTD_llt_literalLength = 1, /* represents a long literal */
  82. ZSTD_llt_matchLength = 2 /* represents a long match */
  83. } ZSTD_longLengthType_e;
  84. typedef struct {
  85. SeqDef* sequencesStart;
  86. SeqDef* sequences; /* ptr to end of sequences */
  87. BYTE* litStart;
  88. BYTE* lit; /* ptr to end of literals */
  89. BYTE* llCode;
  90. BYTE* mlCode;
  91. BYTE* ofCode;
  92. size_t maxNbSeq;
  93. size_t maxNbLit;
  94. /* longLengthPos and longLengthType to allow us to represent either a single litLength or matchLength
  95. * in the seqStore that has a value larger than U16 (if it exists). To do so, we increment
  96. * the existing value of the litLength or matchLength by 0x10000.
  97. */
  98. ZSTD_longLengthType_e longLengthType;
  99. U32 longLengthPos; /* Index of the sequence to apply long length modification to */
  100. } SeqStore_t;
  101. typedef struct {
  102. U32 litLength;
  103. U32 matchLength;
  104. } ZSTD_SequenceLength;
  105. /**
  106. * Returns the ZSTD_SequenceLength for the given sequences. It handles the decoding of long sequences
  107. * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength.
  108. */
  109. MEM_STATIC ZSTD_SequenceLength ZSTD_getSequenceLength(SeqStore_t const* seqStore, SeqDef const* seq)
  110. {
  111. ZSTD_SequenceLength seqLen;
  112. seqLen.litLength = seq->litLength;
  113. seqLen.matchLength = seq->mlBase + MINMATCH;
  114. if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {
  115. if (seqStore->longLengthType == ZSTD_llt_literalLength) {
  116. seqLen.litLength += 0x10000;
  117. }
  118. if (seqStore->longLengthType == ZSTD_llt_matchLength) {
  119. seqLen.matchLength += 0x10000;
  120. }
  121. }
  122. return seqLen;
  123. }
  124. const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */
  125. int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */
  126. /***********************************************
  127. * Entropy buffer statistics structs and funcs *
  128. ***********************************************/
  129. /** ZSTD_hufCTablesMetadata_t :
  130. * Stores Literals Block Type for a super-block in hType, and
  131. * huffman tree description in hufDesBuffer.
  132. * hufDesSize refers to the size of huffman tree description in bytes.
  133. * This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */
  134. typedef struct {
  135. SymbolEncodingType_e hType;
  136. BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE];
  137. size_t hufDesSize;
  138. } ZSTD_hufCTablesMetadata_t;
  139. /** ZSTD_fseCTablesMetadata_t :
  140. * Stores symbol compression modes for a super-block in {ll, ol, ml}Type, and
  141. * fse tables in fseTablesBuffer.
  142. * fseTablesSize refers to the size of fse tables in bytes.
  143. * This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */
  144. typedef struct {
  145. SymbolEncodingType_e llType;
  146. SymbolEncodingType_e ofType;
  147. SymbolEncodingType_e mlType;
  148. BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE];
  149. size_t fseTablesSize;
  150. size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */
  151. } ZSTD_fseCTablesMetadata_t;
  152. typedef struct {
  153. ZSTD_hufCTablesMetadata_t hufMetadata;
  154. ZSTD_fseCTablesMetadata_t fseMetadata;
  155. } ZSTD_entropyCTablesMetadata_t;
  156. /** ZSTD_buildBlockEntropyStats() :
  157. * Builds entropy for the block.
  158. * @return : 0 on success or error code */
  159. size_t ZSTD_buildBlockEntropyStats(
  160. const SeqStore_t* seqStorePtr,
  161. const ZSTD_entropyCTables_t* prevEntropy,
  162. ZSTD_entropyCTables_t* nextEntropy,
  163. const ZSTD_CCtx_params* cctxParams,
  164. ZSTD_entropyCTablesMetadata_t* entropyMetadata,
  165. void* workspace, size_t wkspSize);
  166. /*********************************
  167. * Compression internals structs *
  168. *********************************/
  169. typedef struct {
  170. U32 off; /* Offset sumtype code for the match, using ZSTD_storeSeq() format */
  171. U32 len; /* Raw length of match */
  172. } ZSTD_match_t;
  173. typedef struct {
  174. U32 offset; /* Offset of sequence */
  175. U32 litLength; /* Length of literals prior to match */
  176. U32 matchLength; /* Raw length of match */
  177. } rawSeq;
  178. typedef struct {
  179. rawSeq* seq; /* The start of the sequences */
  180. size_t pos; /* The index in seq where reading stopped. pos <= size. */
  181. size_t posInSequence; /* The position within the sequence at seq[pos] where reading
  182. stopped. posInSequence <= seq[pos].litLength + seq[pos].matchLength */
  183. size_t size; /* The number of sequences. <= capacity. */
  184. size_t capacity; /* The capacity starting from `seq` pointer */
  185. } RawSeqStore_t;
  186. UNUSED_ATTR static const RawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};
  187. typedef struct {
  188. int price; /* price from beginning of segment to this position */
  189. U32 off; /* offset of previous match */
  190. U32 mlen; /* length of previous match */
  191. U32 litlen; /* nb of literals since previous match */
  192. U32 rep[ZSTD_REP_NUM]; /* offset history after previous match */
  193. } ZSTD_optimal_t;
  194. typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
  195. #define ZSTD_OPT_SIZE (ZSTD_OPT_NUM+3)
  196. typedef struct {
  197. /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
  198. unsigned* litFreq; /* table of literals statistics, of size 256 */
  199. unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */
  200. unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */
  201. unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */
  202. ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_SIZE */
  203. ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_SIZE */
  204. U32 litSum; /* nb of literals */
  205. U32 litLengthSum; /* nb of litLength codes */
  206. U32 matchLengthSum; /* nb of matchLength codes */
  207. U32 offCodeSum; /* nb of offset codes */
  208. U32 litSumBasePrice; /* to compare to log2(litfreq) */
  209. U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */
  210. U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */
  211. U32 offCodeSumBasePrice; /* to compare to log2(offreq) */
  212. ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */
  213. const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */
  214. ZSTD_ParamSwitch_e literalCompressionMode;
  215. } optState_t;
  216. typedef struct {
  217. ZSTD_entropyCTables_t entropy;
  218. U32 rep[ZSTD_REP_NUM];
  219. } ZSTD_compressedBlockState_t;
  220. typedef struct {
  221. BYTE const* nextSrc; /* next block here to continue on current prefix */
  222. BYTE const* base; /* All regular indexes relative to this position */
  223. BYTE const* dictBase; /* extDict indexes relative to this position */
  224. U32 dictLimit; /* below that point, need extDict */
  225. U32 lowLimit; /* below that point, no more valid data */
  226. U32 nbOverflowCorrections; /* Number of times overflow correction has run since
  227. * ZSTD_window_init(). Useful for debugging coredumps
  228. * and for ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY.
  229. */
  230. } ZSTD_window_t;
  231. #define ZSTD_WINDOW_START_INDEX 2
  232. typedef struct ZSTD_MatchState_t ZSTD_MatchState_t;
  233. #define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */
  234. struct ZSTD_MatchState_t {
  235. ZSTD_window_t window; /* State for window round buffer management */
  236. U32 loadedDictEnd; /* index of end of dictionary, within context's referential.
  237. * When loadedDictEnd != 0, a dictionary is in use, and still valid.
  238. * This relies on a mechanism to set loadedDictEnd=0 when dictionary is no longer within distance.
  239. * Such mechanism is provided within ZSTD_window_enforceMaxDist() and ZSTD_checkDictValidity().
  240. * When dict referential is copied into active context (i.e. not attached),
  241. * loadedDictEnd == dictSize, since referential starts from zero.
  242. */
  243. U32 nextToUpdate; /* index from which to continue table update */
  244. U32 hashLog3; /* dispatch table for matches of len==3 : larger == faster, more memory */
  245. U32 rowHashLog; /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/
  246. BYTE* tagTable; /* For row-based matchFinder: A row-based table containing the hashes and head index. */
  247. U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */
  248. U64 hashSalt; /* For row-based matchFinder: salts the hash for reuse of tag table */
  249. U32 hashSaltEntropy; /* For row-based matchFinder: collects entropy for salt generation */
  250. U32* hashTable;
  251. U32* hashTable3;
  252. U32* chainTable;
  253. int forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */
  254. int dedicatedDictSearch; /* Indicates whether this matchState is using the
  255. * dedicated dictionary search structure.
  256. */
  257. optState_t opt; /* optimal parser state */
  258. const ZSTD_MatchState_t* dictMatchState;
  259. ZSTD_compressionParameters cParams;
  260. const RawSeqStore_t* ldmSeqStore;
  261. /* Controls prefetching in some dictMatchState matchfinders.
  262. * This behavior is controlled from the cctx ms.
  263. * This parameter has no effect in the cdict ms. */
  264. int prefetchCDictTables;
  265. /* When == 0, lazy match finders insert every position.
  266. * When != 0, lazy match finders only insert positions they search.
  267. * This allows them to skip much faster over incompressible data,
  268. * at a small cost to compression ratio.
  269. */
  270. int lazySkipping;
  271. };
  272. typedef struct {
  273. ZSTD_compressedBlockState_t* prevCBlock;
  274. ZSTD_compressedBlockState_t* nextCBlock;
  275. ZSTD_MatchState_t matchState;
  276. } ZSTD_blockState_t;
  277. typedef struct {
  278. U32 offset;
  279. U32 checksum;
  280. } ldmEntry_t;
  281. typedef struct {
  282. BYTE const* split;
  283. U32 hash;
  284. U32 checksum;
  285. ldmEntry_t* bucket;
  286. } ldmMatchCandidate_t;
  287. #define LDM_BATCH_SIZE 64
  288. typedef struct {
  289. ZSTD_window_t window; /* State for the window round buffer management */
  290. ldmEntry_t* hashTable;
  291. U32 loadedDictEnd;
  292. BYTE* bucketOffsets; /* Next position in bucket to insert entry */
  293. size_t splitIndices[LDM_BATCH_SIZE];
  294. ldmMatchCandidate_t matchCandidates[LDM_BATCH_SIZE];
  295. } ldmState_t;
  296. typedef struct {
  297. ZSTD_ParamSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */
  298. U32 hashLog; /* Log size of hashTable */
  299. U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */
  300. U32 minMatchLength; /* Minimum match length */
  301. U32 hashRateLog; /* Log number of entries to skip */
  302. U32 windowLog; /* Window log for the LDM */
  303. } ldmParams_t;
  304. typedef struct {
  305. int collectSequences;
  306. ZSTD_Sequence* seqStart;
  307. size_t seqIndex;
  308. size_t maxSequences;
  309. } SeqCollector;
  310. struct ZSTD_CCtx_params_s {
  311. ZSTD_format_e format;
  312. ZSTD_compressionParameters cParams;
  313. ZSTD_frameParameters fParams;
  314. int compressionLevel;
  315. int forceWindow; /* force back-references to respect limit of
  316. * 1<<wLog, even for dictionary */
  317. size_t targetCBlockSize; /* Tries to fit compressed block size to be around targetCBlockSize.
  318. * No target when targetCBlockSize == 0.
  319. * There is no guarantee on compressed block size */
  320. int srcSizeHint; /* User's best guess of source size.
  321. * Hint is not valid when srcSizeHint == 0.
  322. * There is no guarantee that hint is close to actual source size */
  323. ZSTD_dictAttachPref_e attachDictPref;
  324. ZSTD_ParamSwitch_e literalCompressionMode;
  325. /* Multithreading: used to pass parameters to mtctx */
  326. int nbWorkers;
  327. size_t jobSize;
  328. int overlapLog;
  329. int rsyncable;
  330. /* Long distance matching parameters */
  331. ldmParams_t ldmParams;
  332. /* Dedicated dict search algorithm trigger */
  333. int enableDedicatedDictSearch;
  334. /* Input/output buffer modes */
  335. ZSTD_bufferMode_e inBufferMode;
  336. ZSTD_bufferMode_e outBufferMode;
  337. /* Sequence compression API */
  338. ZSTD_SequenceFormat_e blockDelimiters;
  339. int validateSequences;
  340. /* Block splitting
  341. * @postBlockSplitter executes split analysis after sequences are produced,
  342. * it's more accurate but consumes more resources.
  343. * @preBlockSplitter_level splits before knowing sequences,
  344. * it's more approximative but also cheaper.
  345. * Valid @preBlockSplitter_level values range from 0 to 6 (included).
  346. * 0 means auto, 1 means do not split,
  347. * then levels are sorted in increasing cpu budget, from 2 (fastest) to 6 (slowest).
  348. * Highest @preBlockSplitter_level combines well with @postBlockSplitter.
  349. */
  350. ZSTD_ParamSwitch_e postBlockSplitter;
  351. int preBlockSplitter_level;
  352. /* Adjust the max block size*/
  353. size_t maxBlockSize;
  354. /* Param for deciding whether to use row-based matchfinder */
  355. ZSTD_ParamSwitch_e useRowMatchFinder;
  356. /* Always load a dictionary in ext-dict mode (not prefix mode)? */
  357. int deterministicRefPrefix;
  358. /* Internal use, for createCCtxParams() and freeCCtxParams() only */
  359. ZSTD_customMem customMem;
  360. /* Controls prefetching in some dictMatchState matchfinders */
  361. ZSTD_ParamSwitch_e prefetchCDictTables;
  362. /* Controls whether zstd will fall back to an internal matchfinder
  363. * if the external matchfinder returns an error code. */
  364. int enableMatchFinderFallback;
  365. /* Parameters for the external sequence producer API.
  366. * Users set these parameters through ZSTD_registerSequenceProducer().
  367. * It is not possible to set these parameters individually through the public API. */
  368. void* extSeqProdState;
  369. ZSTD_sequenceProducer_F extSeqProdFunc;
  370. /* Controls repcode search in external sequence parsing */
  371. ZSTD_ParamSwitch_e searchForExternalRepcodes;
  372. }; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
  373. #define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))
  374. #define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE)
  375. #define TMP_WORKSPACE_SIZE (MAX(ENTROPY_WORKSPACE_SIZE, ZSTD_SLIPBLOCK_WORKSPACESIZE))
  376. /**
  377. * Indicates whether this compression proceeds directly from user-provided
  378. * source buffer to user-provided destination buffer (ZSTDb_not_buffered), or
  379. * whether the context needs to buffer the input/output (ZSTDb_buffered).
  380. */
  381. typedef enum {
  382. ZSTDb_not_buffered,
  383. ZSTDb_buffered
  384. } ZSTD_buffered_policy_e;
  385. /**
  386. * Struct that contains all elements of block splitter that should be allocated
  387. * in a wksp.
  388. */
  389. #define ZSTD_MAX_NB_BLOCK_SPLITS 196
  390. typedef struct {
  391. SeqStore_t fullSeqStoreChunk;
  392. SeqStore_t firstHalfSeqStore;
  393. SeqStore_t secondHalfSeqStore;
  394. SeqStore_t currSeqStore;
  395. SeqStore_t nextSeqStore;
  396. U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS];
  397. ZSTD_entropyCTablesMetadata_t entropyMetadata;
  398. } ZSTD_blockSplitCtx;
  399. struct ZSTD_CCtx_s {
  400. ZSTD_compressionStage_e stage;
  401. int cParamsChanged; /* == 1 if cParams(except wlog) or compression level are changed in requestedParams. Triggers transmission of new params to ZSTDMT (if available) then reset to 0. */
  402. int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
  403. ZSTD_CCtx_params requestedParams;
  404. ZSTD_CCtx_params appliedParams;
  405. ZSTD_CCtx_params simpleApiParams; /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */
  406. U32 dictID;
  407. size_t dictContentSize;
  408. ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */
  409. size_t blockSizeMax;
  410. unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */
  411. unsigned long long consumedSrcSize;
  412. unsigned long long producedCSize;
  413. XXH64_state_t xxhState;
  414. ZSTD_customMem customMem;
  415. ZSTD_threadPool* pool;
  416. size_t staticSize;
  417. SeqCollector seqCollector;
  418. int isFirstBlock;
  419. int initialized;
  420. SeqStore_t seqStore; /* sequences storage ptrs */
  421. ldmState_t ldmState; /* long distance matching state */
  422. rawSeq* ldmSequences; /* Storage for the ldm output sequences */
  423. size_t maxNbLdmSequences;
  424. RawSeqStore_t externSeqStore; /* Mutable reference to external sequences */
  425. ZSTD_blockState_t blockState;
  426. void* tmpWorkspace; /* used as substitute of stack space - must be aligned for S64 type */
  427. size_t tmpWkspSize;
  428. /* Whether we are streaming or not */
  429. ZSTD_buffered_policy_e bufferedPolicy;
  430. /* streaming */
  431. char* inBuff;
  432. size_t inBuffSize;
  433. size_t inToCompress;
  434. size_t inBuffPos;
  435. size_t inBuffTarget;
  436. char* outBuff;
  437. size_t outBuffSize;
  438. size_t outBuffContentSize;
  439. size_t outBuffFlushedSize;
  440. ZSTD_cStreamStage streamStage;
  441. U32 frameEnded;
  442. /* Stable in/out buffer verification */
  443. ZSTD_inBuffer expectedInBuffer;
  444. size_t stableIn_notConsumed; /* nb bytes within stable input buffer that are said to be consumed but are not */
  445. size_t expectedOutBufferSize;
  446. /* Dictionary */
  447. ZSTD_localDict localDict;
  448. const ZSTD_CDict* cdict;
  449. ZSTD_prefixDict prefixDict; /* single-usage dictionary */
  450. /* Multi-threading */
  451. #ifdef ZSTD_MULTITHREAD
  452. ZSTDMT_CCtx* mtctx;
  453. #endif
  454. /* Tracing */
  455. #if ZSTD_TRACE
  456. ZSTD_TraceCtx traceCtx;
  457. #endif
  458. /* Workspace for block splitter */
  459. ZSTD_blockSplitCtx blockSplitCtx;
  460. /* Buffer for output from external sequence producer */
  461. ZSTD_Sequence* extSeqBuf;
  462. size_t extSeqBufCapacity;
  463. };
  464. typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
  465. typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e;
  466. typedef enum {
  467. ZSTD_noDict = 0,
  468. ZSTD_extDict = 1,
  469. ZSTD_dictMatchState = 2,
  470. ZSTD_dedicatedDictSearch = 3
  471. } ZSTD_dictMode_e;
  472. typedef enum {
  473. ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict.
  474. * In this mode we use both the srcSize and the dictSize
  475. * when selecting and adjusting parameters.
  476. */
  477. ZSTD_cpm_attachDict = 1, /* Compression with ZSTD_dictMatchState or ZSTD_dedicatedDictSearch.
  478. * In this mode we only take the srcSize into account when selecting
  479. * and adjusting parameters.
  480. */
  481. ZSTD_cpm_createCDict = 2, /* Creating a CDict.
  482. * In this mode we take both the source size and the dictionary size
  483. * into account when selecting and adjusting the parameters.
  484. */
  485. ZSTD_cpm_unknown = 3 /* ZSTD_getCParams, ZSTD_getParams, ZSTD_adjustParams.
  486. * We don't know what these parameters are for. We default to the legacy
  487. * behavior of taking both the source size and the dict size into account
  488. * when selecting and adjusting parameters.
  489. */
  490. } ZSTD_CParamMode_e;
  491. typedef size_t (*ZSTD_BlockCompressor_f) (
  492. ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  493. void const* src, size_t srcSize);
  494. ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);
  495. MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
  496. {
  497. static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,
  498. 8, 9, 10, 11, 12, 13, 14, 15,
  499. 16, 16, 17, 17, 18, 18, 19, 19,
  500. 20, 20, 20, 20, 21, 21, 21, 21,
  501. 22, 22, 22, 22, 22, 22, 22, 22,
  502. 23, 23, 23, 23, 23, 23, 23, 23,
  503. 24, 24, 24, 24, 24, 24, 24, 24,
  504. 24, 24, 24, 24, 24, 24, 24, 24 };
  505. static const U32 LL_deltaCode = 19;
  506. return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];
  507. }
  508. /* ZSTD_MLcode() :
  509. * note : mlBase = matchLength - MINMATCH;
  510. * because it's the format it's stored in seqStore->sequences */
  511. MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
  512. {
  513. static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  514. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  515. 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
  516. 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
  517. 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
  518. 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
  519. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
  520. 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
  521. static const U32 ML_deltaCode = 36;
  522. return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];
  523. }
  524. /* ZSTD_cParam_withinBounds:
  525. * @return 1 if value is within cParam bounds,
  526. * 0 otherwise */
  527. MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)
  528. {
  529. ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
  530. if (ZSTD_isError(bounds.error)) return 0;
  531. if (value < bounds.lowerBound) return 0;
  532. if (value > bounds.upperBound) return 0;
  533. return 1;
  534. }
  535. /* ZSTD_selectAddr:
  536. * @return index >= lowLimit ? candidate : backup,
  537. * tries to force branchless codegen. */
  538. MEM_STATIC const BYTE*
  539. ZSTD_selectAddr(U32 index, U32 lowLimit, const BYTE* candidate, const BYTE* backup)
  540. {
  541. #if defined(__GNUC__) && defined(__x86_64__)
  542. __asm__ (
  543. "cmp %1, %2\n"
  544. "cmova %3, %0\n"
  545. : "+r"(candidate)
  546. : "r"(index), "r"(lowLimit), "r"(backup)
  547. );
  548. return candidate;
  549. #else
  550. return index >= lowLimit ? candidate : backup;
  551. #endif
  552. }
  553. /* ZSTD_noCompressBlock() :
  554. * Writes uncompressed block to dst buffer from given src.
  555. * Returns the size of the block */
  556. MEM_STATIC size_t
  557. ZSTD_noCompressBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
  558. {
  559. U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);
  560. DEBUGLOG(5, "ZSTD_noCompressBlock (srcSize=%zu, dstCapacity=%zu)", srcSize, dstCapacity);
  561. RETURN_ERROR_IF(srcSize + ZSTD_blockHeaderSize > dstCapacity,
  562. dstSize_tooSmall, "dst buf too small for uncompressed block");
  563. MEM_writeLE24(dst, cBlockHeader24);
  564. ZSTD_memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
  565. return ZSTD_blockHeaderSize + srcSize;
  566. }
  567. MEM_STATIC size_t
  568. ZSTD_rleCompressBlock(void* dst, size_t dstCapacity, BYTE src, size_t srcSize, U32 lastBlock)
  569. {
  570. BYTE* const op = (BYTE*)dst;
  571. U32 const cBlockHeader = lastBlock + (((U32)bt_rle)<<1) + (U32)(srcSize << 3);
  572. RETURN_ERROR_IF(dstCapacity < 4, dstSize_tooSmall, "");
  573. MEM_writeLE24(op, cBlockHeader);
  574. op[3] = src;
  575. return 4;
  576. }
  577. /* ZSTD_minGain() :
  578. * minimum compression required
  579. * to generate a compress block or a compressed literals section.
  580. * note : use same formula for both situations */
  581. MEM_STATIC size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)
  582. {
  583. U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
  584. ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
  585. assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat));
  586. return (srcSize >> minlog) + 2;
  587. }
  588. MEM_STATIC int ZSTD_literalsCompressionIsDisabled(const ZSTD_CCtx_params* cctxParams)
  589. {
  590. switch (cctxParams->literalCompressionMode) {
  591. case ZSTD_ps_enable:
  592. return 0;
  593. case ZSTD_ps_disable:
  594. return 1;
  595. default:
  596. assert(0 /* impossible: pre-validated */);
  597. ZSTD_FALLTHROUGH;
  598. case ZSTD_ps_auto:
  599. return (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
  600. }
  601. }
  602. /*! ZSTD_safecopyLiterals() :
  603. * memcpy() function that won't read beyond more than WILDCOPY_OVERLENGTH bytes past ilimit_w.
  604. * Only called when the sequence ends past ilimit_w, so it only needs to be optimized for single
  605. * large copies.
  606. */
  607. static void
  608. ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE const* ilimit_w)
  609. {
  610. assert(iend > ilimit_w);
  611. if (ip <= ilimit_w) {
  612. ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap);
  613. op += ilimit_w - ip;
  614. ip = ilimit_w;
  615. }
  616. while (ip < iend) *op++ = *ip++;
  617. }
  618. #define REPCODE1_TO_OFFBASE REPCODE_TO_OFFBASE(1)
  619. #define REPCODE2_TO_OFFBASE REPCODE_TO_OFFBASE(2)
  620. #define REPCODE3_TO_OFFBASE REPCODE_TO_OFFBASE(3)
  621. #define REPCODE_TO_OFFBASE(r) (assert((r)>=1), assert((r)<=ZSTD_REP_NUM), (r)) /* accepts IDs 1,2,3 */
  622. #define OFFSET_TO_OFFBASE(o) (assert((o)>0), o + ZSTD_REP_NUM)
  623. #define OFFBASE_IS_OFFSET(o) ((o) > ZSTD_REP_NUM)
  624. #define OFFBASE_IS_REPCODE(o) ( 1 <= (o) && (o) <= ZSTD_REP_NUM)
  625. #define OFFBASE_TO_OFFSET(o) (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)
  626. #define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o)) /* returns ID 1,2,3 */
  627. /*! ZSTD_storeSeqOnly() :
  628. * Store a sequence (litlen, litPtr, offBase and matchLength) into SeqStore_t.
  629. * Literals themselves are not copied, but @litPtr is updated.
  630. * @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
  631. * @matchLength : must be >= MINMATCH
  632. */
  633. HINT_INLINE UNUSED_ATTR void
  634. ZSTD_storeSeqOnly(SeqStore_t* seqStorePtr,
  635. size_t litLength,
  636. U32 offBase,
  637. size_t matchLength)
  638. {
  639. assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
  640. /* literal Length */
  641. assert(litLength <= ZSTD_BLOCKSIZE_MAX);
  642. if (UNLIKELY(litLength>0xFFFF)) {
  643. assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
  644. seqStorePtr->longLengthType = ZSTD_llt_literalLength;
  645. seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  646. }
  647. seqStorePtr->sequences[0].litLength = (U16)litLength;
  648. /* match offset */
  649. seqStorePtr->sequences[0].offBase = offBase;
  650. /* match Length */
  651. assert(matchLength <= ZSTD_BLOCKSIZE_MAX);
  652. assert(matchLength >= MINMATCH);
  653. { size_t const mlBase = matchLength - MINMATCH;
  654. if (UNLIKELY(mlBase>0xFFFF)) {
  655. assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
  656. seqStorePtr->longLengthType = ZSTD_llt_matchLength;
  657. seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  658. }
  659. seqStorePtr->sequences[0].mlBase = (U16)mlBase;
  660. }
  661. seqStorePtr->sequences++;
  662. }
  663. /*! ZSTD_storeSeq() :
  664. * Store a sequence (litlen, litPtr, offBase and matchLength) into SeqStore_t.
  665. * @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
  666. * @matchLength : must be >= MINMATCH
  667. * Allowed to over-read literals up to litLimit.
  668. */
  669. HINT_INLINE UNUSED_ATTR void
  670. ZSTD_storeSeq(SeqStore_t* seqStorePtr,
  671. size_t litLength, const BYTE* literals, const BYTE* litLimit,
  672. U32 offBase,
  673. size_t matchLength)
  674. {
  675. BYTE const* const litLimit_w = litLimit - WILDCOPY_OVERLENGTH;
  676. BYTE const* const litEnd = literals + litLength;
  677. #if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
  678. static const BYTE* g_start = NULL;
  679. if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */
  680. { U32 const pos = (U32)((const BYTE*)literals - g_start);
  681. DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",
  682. pos, (U32)litLength, (U32)matchLength, (U32)offBase);
  683. }
  684. #endif
  685. assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
  686. /* copy Literals */
  687. assert(seqStorePtr->maxNbLit <= 128 KB);
  688. assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
  689. assert(literals + litLength <= litLimit);
  690. if (litEnd <= litLimit_w) {
  691. /* Common case we can use wildcopy.
  692. * First copy 16 bytes, because literals are likely short.
  693. */
  694. ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16);
  695. ZSTD_copy16(seqStorePtr->lit, literals);
  696. if (litLength > 16) {
  697. ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap);
  698. }
  699. } else {
  700. ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);
  701. }
  702. seqStorePtr->lit += litLength;
  703. ZSTD_storeSeqOnly(seqStorePtr, litLength, offBase, matchLength);
  704. }
  705. /* ZSTD_updateRep() :
  706. * updates in-place @rep (array of repeat offsets)
  707. * @offBase : sum-type, using numeric representation of ZSTD_storeSeq()
  708. */
  709. MEM_STATIC void
  710. ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
  711. {
  712. if (OFFBASE_IS_OFFSET(offBase)) { /* full offset */
  713. rep[2] = rep[1];
  714. rep[1] = rep[0];
  715. rep[0] = OFFBASE_TO_OFFSET(offBase);
  716. } else { /* repcode */
  717. U32 const repCode = OFFBASE_TO_REPCODE(offBase) - 1 + ll0;
  718. if (repCode > 0) { /* note : if repCode==0, no change */
  719. U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
  720. rep[2] = (repCode >= 2) ? rep[1] : rep[2];
  721. rep[1] = rep[0];
  722. rep[0] = currentOffset;
  723. } else { /* repCode == 0 */
  724. /* nothing to do */
  725. }
  726. }
  727. }
  728. typedef struct repcodes_s {
  729. U32 rep[3];
  730. } Repcodes_t;
  731. MEM_STATIC Repcodes_t
  732. ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0)
  733. {
  734. Repcodes_t newReps;
  735. ZSTD_memcpy(&newReps, rep, sizeof(newReps));
  736. ZSTD_updateRep(newReps.rep, offBase, ll0);
  737. return newReps;
  738. }
  739. /*-*************************************
  740. * Match length counter
  741. ***************************************/
  742. MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)
  743. {
  744. const BYTE* const pStart = pIn;
  745. const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);
  746. if (pIn < pInLoopLimit) {
  747. { size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  748. if (diff) return ZSTD_NbCommonBytes(diff); }
  749. pIn+=sizeof(size_t); pMatch+=sizeof(size_t);
  750. while (pIn < pInLoopLimit) {
  751. size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  752. if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
  753. pIn += ZSTD_NbCommonBytes(diff);
  754. return (size_t)(pIn - pStart);
  755. } }
  756. if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }
  757. if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }
  758. if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
  759. return (size_t)(pIn - pStart);
  760. }
  761. /** ZSTD_count_2segments() :
  762. * can count match length with `ip` & `match` in 2 different segments.
  763. * convention : on reaching mEnd, match count continue starting from iStart
  764. */
  765. MEM_STATIC size_t
  766. ZSTD_count_2segments(const BYTE* ip, const BYTE* match,
  767. const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)
  768. {
  769. const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);
  770. size_t const matchLength = ZSTD_count(ip, match, vEnd);
  771. if (match + matchLength != mEnd) return matchLength;
  772. DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);
  773. DEBUGLOG(7, "distance from match beginning to end dictionary = %i", (int)(mEnd - match));
  774. DEBUGLOG(7, "distance from current pos to end buffer = %i", (int)(iEnd - ip));
  775. DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);
  776. DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));
  777. return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);
  778. }
  779. /*-*************************************
  780. * Hashes
  781. ***************************************/
  782. static const U32 prime3bytes = 506832829U;
  783. static U32 ZSTD_hash3(U32 u, U32 h, U32 s) { assert(h <= 32); return (((u << (32-24)) * prime3bytes) ^ s) >> (32-h) ; }
  784. MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h, 0); } /* only in zstd_opt.h */
  785. MEM_STATIC size_t ZSTD_hash3PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash3(MEM_readLE32(ptr), h, s); }
  786. static const U32 prime4bytes = 2654435761U;
  787. static U32 ZSTD_hash4(U32 u, U32 h, U32 s) { assert(h <= 32); return ((u * prime4bytes) ^ s) >> (32-h) ; }
  788. static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_readLE32(ptr), h, 0); }
  789. static size_t ZSTD_hash4PtrS(const void* ptr, U32 h, U32 s) { return ZSTD_hash4(MEM_readLE32(ptr), h, s); }
  790. static const U64 prime5bytes = 889523592379ULL;
  791. static size_t ZSTD_hash5(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-40)) * prime5bytes) ^ s) >> (64-h)) ; }
  792. static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h, 0); }
  793. static size_t ZSTD_hash5PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash5(MEM_readLE64(p), h, s); }
  794. static const U64 prime6bytes = 227718039650203ULL;
  795. static size_t ZSTD_hash6(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-48)) * prime6bytes) ^ s) >> (64-h)) ; }
  796. static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h, 0); }
  797. static size_t ZSTD_hash6PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash6(MEM_readLE64(p), h, s); }
  798. static const U64 prime7bytes = 58295818150454627ULL;
  799. static size_t ZSTD_hash7(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u << (64-56)) * prime7bytes) ^ s) >> (64-h)) ; }
  800. static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h, 0); }
  801. static size_t ZSTD_hash7PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash7(MEM_readLE64(p), h, s); }
  802. static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
  803. static size_t ZSTD_hash8(U64 u, U32 h, U64 s) { assert(h <= 64); return (size_t)((((u) * prime8bytes) ^ s) >> (64-h)) ; }
  804. static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h, 0); }
  805. static size_t ZSTD_hash8PtrS(const void* p, U32 h, U64 s) { return ZSTD_hash8(MEM_readLE64(p), h, s); }
  806. MEM_STATIC FORCE_INLINE_ATTR
  807. size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
  808. {
  809. /* Although some of these hashes do support hBits up to 64, some do not.
  810. * To be on the safe side, always avoid hBits > 32. */
  811. assert(hBits <= 32);
  812. switch(mls)
  813. {
  814. default:
  815. case 4: return ZSTD_hash4Ptr(p, hBits);
  816. case 5: return ZSTD_hash5Ptr(p, hBits);
  817. case 6: return ZSTD_hash6Ptr(p, hBits);
  818. case 7: return ZSTD_hash7Ptr(p, hBits);
  819. case 8: return ZSTD_hash8Ptr(p, hBits);
  820. }
  821. }
  822. MEM_STATIC FORCE_INLINE_ATTR
  823. size_t ZSTD_hashPtrSalted(const void* p, U32 hBits, U32 mls, const U64 hashSalt) {
  824. /* Although some of these hashes do support hBits up to 64, some do not.
  825. * To be on the safe side, always avoid hBits > 32. */
  826. assert(hBits <= 32);
  827. switch(mls)
  828. {
  829. default:
  830. case 4: return ZSTD_hash4PtrS(p, hBits, (U32)hashSalt);
  831. case 5: return ZSTD_hash5PtrS(p, hBits, hashSalt);
  832. case 6: return ZSTD_hash6PtrS(p, hBits, hashSalt);
  833. case 7: return ZSTD_hash7PtrS(p, hBits, hashSalt);
  834. case 8: return ZSTD_hash8PtrS(p, hBits, hashSalt);
  835. }
  836. }
  837. /** ZSTD_ipow() :
  838. * Return base^exponent.
  839. */
  840. static U64 ZSTD_ipow(U64 base, U64 exponent)
  841. {
  842. U64 power = 1;
  843. while (exponent) {
  844. if (exponent & 1) power *= base;
  845. exponent >>= 1;
  846. base *= base;
  847. }
  848. return power;
  849. }
  850. #define ZSTD_ROLL_HASH_CHAR_OFFSET 10
  851. /** ZSTD_rollingHash_append() :
  852. * Add the buffer to the hash value.
  853. */
  854. static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)
  855. {
  856. BYTE const* istart = (BYTE const*)buf;
  857. size_t pos;
  858. for (pos = 0; pos < size; ++pos) {
  859. hash *= prime8bytes;
  860. hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;
  861. }
  862. return hash;
  863. }
  864. /** ZSTD_rollingHash_compute() :
  865. * Compute the rolling hash value of the buffer.
  866. */
  867. MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)
  868. {
  869. return ZSTD_rollingHash_append(0, buf, size);
  870. }
  871. /** ZSTD_rollingHash_primePower() :
  872. * Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash
  873. * over a window of length bytes.
  874. */
  875. MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)
  876. {
  877. return ZSTD_ipow(prime8bytes, length - 1);
  878. }
  879. /** ZSTD_rollingHash_rotate() :
  880. * Rotate the rolling hash by one byte.
  881. */
  882. MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
  883. {
  884. hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;
  885. hash *= prime8bytes;
  886. hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;
  887. return hash;
  888. }
  889. /*-*************************************
  890. * Round buffer management
  891. ***************************************/
  892. /* Max @current value allowed:
  893. * In 32-bit mode: we want to avoid crossing the 2 GB limit,
  894. * reducing risks of side effects in case of signed operations on indexes.
  895. * In 64-bit mode: we want to ensure that adding the maximum job size (512 MB)
  896. * doesn't overflow U32 index capacity (4 GB) */
  897. #define ZSTD_CURRENT_MAX (MEM_64bits() ? 3500U MB : 2000U MB)
  898. /* Maximum chunk size before overflow correction needs to be called again */
  899. #define ZSTD_CHUNKSIZE_MAX \
  900. ( ((U32)-1) /* Maximum ending current index */ \
  901. - ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */
  902. /**
  903. * ZSTD_window_clear():
  904. * Clears the window containing the history by simply setting it to empty.
  905. */
  906. MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)
  907. {
  908. size_t const endT = (size_t)(window->nextSrc - window->base);
  909. U32 const end = (U32)endT;
  910. window->lowLimit = end;
  911. window->dictLimit = end;
  912. }
  913. MEM_STATIC U32 ZSTD_window_isEmpty(ZSTD_window_t const window)
  914. {
  915. return window.dictLimit == ZSTD_WINDOW_START_INDEX &&
  916. window.lowLimit == ZSTD_WINDOW_START_INDEX &&
  917. (window.nextSrc - window.base) == ZSTD_WINDOW_START_INDEX;
  918. }
  919. /**
  920. * ZSTD_window_hasExtDict():
  921. * Returns non-zero if the window has a non-empty extDict.
  922. */
  923. MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)
  924. {
  925. return window.lowLimit < window.dictLimit;
  926. }
  927. /**
  928. * ZSTD_matchState_dictMode():
  929. * Inspects the provided matchState and figures out what dictMode should be
  930. * passed to the compressor.
  931. */
  932. MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms)
  933. {
  934. return ZSTD_window_hasExtDict(ms->window) ?
  935. ZSTD_extDict :
  936. ms->dictMatchState != NULL ?
  937. (ms->dictMatchState->dedicatedDictSearch ? ZSTD_dedicatedDictSearch : ZSTD_dictMatchState) :
  938. ZSTD_noDict;
  939. }
  940. /* Defining this macro to non-zero tells zstd to run the overflow correction
  941. * code much more frequently. This is very inefficient, and should only be
  942. * used for tests and fuzzers.
  943. */
  944. #ifndef ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY
  945. # ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  946. # define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 1
  947. # else
  948. # define ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY 0
  949. # endif
  950. #endif
  951. /**
  952. * ZSTD_window_canOverflowCorrect():
  953. * Returns non-zero if the indices are large enough for overflow correction
  954. * to work correctly without impacting compression ratio.
  955. */
  956. MEM_STATIC U32 ZSTD_window_canOverflowCorrect(ZSTD_window_t const window,
  957. U32 cycleLog,
  958. U32 maxDist,
  959. U32 loadedDictEnd,
  960. void const* src)
  961. {
  962. U32 const cycleSize = 1u << cycleLog;
  963. U32 const curr = (U32)((BYTE const*)src - window.base);
  964. U32 const minIndexToOverflowCorrect = cycleSize
  965. + MAX(maxDist, cycleSize)
  966. + ZSTD_WINDOW_START_INDEX;
  967. /* Adjust the min index to backoff the overflow correction frequency,
  968. * so we don't waste too much CPU in overflow correction. If this
  969. * computation overflows we don't really care, we just need to make
  970. * sure it is at least minIndexToOverflowCorrect.
  971. */
  972. U32 const adjustment = window.nbOverflowCorrections + 1;
  973. U32 const adjustedIndex = MAX(minIndexToOverflowCorrect * adjustment,
  974. minIndexToOverflowCorrect);
  975. U32 const indexLargeEnough = curr > adjustedIndex;
  976. /* Only overflow correct early if the dictionary is invalidated already,
  977. * so we don't hurt compression ratio.
  978. */
  979. U32 const dictionaryInvalidated = curr > maxDist + loadedDictEnd;
  980. return indexLargeEnough && dictionaryInvalidated;
  981. }
  982. /**
  983. * ZSTD_window_needOverflowCorrection():
  984. * Returns non-zero if the indices are getting too large and need overflow
  985. * protection.
  986. */
  987. MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
  988. U32 cycleLog,
  989. U32 maxDist,
  990. U32 loadedDictEnd,
  991. void const* src,
  992. void const* srcEnd)
  993. {
  994. U32 const curr = (U32)((BYTE const*)srcEnd - window.base);
  995. if (ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
  996. if (ZSTD_window_canOverflowCorrect(window, cycleLog, maxDist, loadedDictEnd, src)) {
  997. return 1;
  998. }
  999. }
  1000. return curr > ZSTD_CURRENT_MAX;
  1001. }
  1002. /**
  1003. * ZSTD_window_correctOverflow():
  1004. * Reduces the indices to protect from index overflow.
  1005. * Returns the correction made to the indices, which must be applied to every
  1006. * stored index.
  1007. *
  1008. * The least significant cycleLog bits of the indices must remain the same,
  1009. * which may be 0. Every index up to maxDist in the past must be valid.
  1010. */
  1011. MEM_STATIC
  1012. ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  1013. U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
  1014. U32 maxDist, void const* src)
  1015. {
  1016. /* preemptive overflow correction:
  1017. * 1. correction is large enough:
  1018. * lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog
  1019. * 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
  1020. *
  1021. * current - newCurrent
  1022. * > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)
  1023. * > (3<<29) - (1<<chainLog)
  1024. * > (3<<29) - (1<<30) (NOTE: chainLog <= 30)
  1025. * > 1<<29
  1026. *
  1027. * 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:
  1028. * After correction, current is less than (1<<chainLog + 1<<windowLog).
  1029. * In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.
  1030. * In 32-bit mode we are safe, because (chainLog <= 29), so
  1031. * ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.
  1032. * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
  1033. * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
  1034. */
  1035. U32 const cycleSize = 1u << cycleLog;
  1036. U32 const cycleMask = cycleSize - 1;
  1037. U32 const curr = (U32)((BYTE const*)src - window->base);
  1038. U32 const currentCycle = curr & cycleMask;
  1039. /* Ensure newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX. */
  1040. U32 const currentCycleCorrection = currentCycle < ZSTD_WINDOW_START_INDEX
  1041. ? MAX(cycleSize, ZSTD_WINDOW_START_INDEX)
  1042. : 0;
  1043. U32 const newCurrent = currentCycle
  1044. + currentCycleCorrection
  1045. + MAX(maxDist, cycleSize);
  1046. U32 const correction = curr - newCurrent;
  1047. /* maxDist must be a power of two so that:
  1048. * (newCurrent & cycleMask) == (curr & cycleMask)
  1049. * This is required to not corrupt the chains / binary tree.
  1050. */
  1051. assert((maxDist & (maxDist - 1)) == 0);
  1052. assert((curr & cycleMask) == (newCurrent & cycleMask));
  1053. assert(curr > newCurrent);
  1054. if (!ZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY) {
  1055. /* Loose bound, should be around 1<<29 (see above) */
  1056. assert(correction > 1<<28);
  1057. }
  1058. window->base += correction;
  1059. window->dictBase += correction;
  1060. if (window->lowLimit < correction + ZSTD_WINDOW_START_INDEX) {
  1061. window->lowLimit = ZSTD_WINDOW_START_INDEX;
  1062. } else {
  1063. window->lowLimit -= correction;
  1064. }
  1065. if (window->dictLimit < correction + ZSTD_WINDOW_START_INDEX) {
  1066. window->dictLimit = ZSTD_WINDOW_START_INDEX;
  1067. } else {
  1068. window->dictLimit -= correction;
  1069. }
  1070. /* Ensure we can still reference the full window. */
  1071. assert(newCurrent >= maxDist);
  1072. assert(newCurrent - maxDist >= ZSTD_WINDOW_START_INDEX);
  1073. /* Ensure that lowLimit and dictLimit didn't underflow. */
  1074. assert(window->lowLimit <= newCurrent);
  1075. assert(window->dictLimit <= newCurrent);
  1076. ++window->nbOverflowCorrections;
  1077. DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,
  1078. window->lowLimit);
  1079. return correction;
  1080. }
  1081. /**
  1082. * ZSTD_window_enforceMaxDist():
  1083. * Updates lowLimit so that:
  1084. * (srcEnd - base) - lowLimit == maxDist + loadedDictEnd
  1085. *
  1086. * It ensures index is valid as long as index >= lowLimit.
  1087. * This must be called before a block compression call.
  1088. *
  1089. * loadedDictEnd is only defined if a dictionary is in use for current compression.
  1090. * As the name implies, loadedDictEnd represents the index at end of dictionary.
  1091. * The value lies within context's referential, it can be directly compared to blockEndIdx.
  1092. *
  1093. * If loadedDictEndPtr is NULL, no dictionary is in use, and we use loadedDictEnd == 0.
  1094. * If loadedDictEndPtr is not NULL, we set it to zero after updating lowLimit.
  1095. * This is because dictionaries are allowed to be referenced fully
  1096. * as long as the last byte of the dictionary is in the window.
  1097. * Once input has progressed beyond window size, dictionary cannot be referenced anymore.
  1098. *
  1099. * In normal dict mode, the dictionary lies between lowLimit and dictLimit.
  1100. * In dictMatchState mode, lowLimit and dictLimit are the same,
  1101. * and the dictionary is below them.
  1102. * forceWindow and dictMatchState are therefore incompatible.
  1103. */
  1104. MEM_STATIC void
  1105. ZSTD_window_enforceMaxDist(ZSTD_window_t* window,
  1106. const void* blockEnd,
  1107. U32 maxDist,
  1108. U32* loadedDictEndPtr,
  1109. const ZSTD_MatchState_t** dictMatchStatePtr)
  1110. {
  1111. U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
  1112. U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;
  1113. DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
  1114. (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
  1115. /* - When there is no dictionary : loadedDictEnd == 0.
  1116. In which case, the test (blockEndIdx > maxDist) is merely to avoid
  1117. overflowing next operation `newLowLimit = blockEndIdx - maxDist`.
  1118. - When there is a standard dictionary :
  1119. Index referential is copied from the dictionary,
  1120. which means it starts from 0.
  1121. In which case, loadedDictEnd == dictSize,
  1122. and it makes sense to compare `blockEndIdx > maxDist + dictSize`
  1123. since `blockEndIdx` also starts from zero.
  1124. - When there is an attached dictionary :
  1125. loadedDictEnd is expressed within the referential of the context,
  1126. so it can be directly compared against blockEndIdx.
  1127. */
  1128. if (blockEndIdx > maxDist + loadedDictEnd) {
  1129. U32 const newLowLimit = blockEndIdx - maxDist;
  1130. if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;
  1131. if (window->dictLimit < window->lowLimit) {
  1132. DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",
  1133. (unsigned)window->dictLimit, (unsigned)window->lowLimit);
  1134. window->dictLimit = window->lowLimit;
  1135. }
  1136. /* On reaching window size, dictionaries are invalidated */
  1137. if (loadedDictEndPtr) *loadedDictEndPtr = 0;
  1138. if (dictMatchStatePtr) *dictMatchStatePtr = NULL;
  1139. }
  1140. }
  1141. /* Similar to ZSTD_window_enforceMaxDist(),
  1142. * but only invalidates dictionary
  1143. * when input progresses beyond window size.
  1144. * assumption : loadedDictEndPtr and dictMatchStatePtr are valid (non NULL)
  1145. * loadedDictEnd uses same referential as window->base
  1146. * maxDist is the window size */
  1147. MEM_STATIC void
  1148. ZSTD_checkDictValidity(const ZSTD_window_t* window,
  1149. const void* blockEnd,
  1150. U32 maxDist,
  1151. U32* loadedDictEndPtr,
  1152. const ZSTD_MatchState_t** dictMatchStatePtr)
  1153. {
  1154. assert(loadedDictEndPtr != NULL);
  1155. assert(dictMatchStatePtr != NULL);
  1156. { U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base);
  1157. U32 const loadedDictEnd = *loadedDictEndPtr;
  1158. DEBUGLOG(5, "ZSTD_checkDictValidity: blockEndIdx=%u, maxDist=%u, loadedDictEnd=%u",
  1159. (unsigned)blockEndIdx, (unsigned)maxDist, (unsigned)loadedDictEnd);
  1160. assert(blockEndIdx >= loadedDictEnd);
  1161. if (blockEndIdx > loadedDictEnd + maxDist || loadedDictEnd != window->dictLimit) {
  1162. /* On reaching window size, dictionaries are invalidated.
  1163. * For simplification, if window size is reached anywhere within next block,
  1164. * the dictionary is invalidated for the full block.
  1165. *
  1166. * We also have to invalidate the dictionary if ZSTD_window_update() has detected
  1167. * non-contiguous segments, which means that loadedDictEnd != window->dictLimit.
  1168. * loadedDictEnd may be 0, if forceWindow is true, but in that case we never use
  1169. * dictMatchState, so setting it to NULL is not a problem.
  1170. */
  1171. DEBUGLOG(6, "invalidating dictionary for current block (distance > windowSize)");
  1172. *loadedDictEndPtr = 0;
  1173. *dictMatchStatePtr = NULL;
  1174. } else {
  1175. if (*loadedDictEndPtr != 0) {
  1176. DEBUGLOG(6, "dictionary considered valid for current block");
  1177. } } }
  1178. }
  1179. MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
  1180. ZSTD_memset(window, 0, sizeof(*window));
  1181. window->base = (BYTE const*)" ";
  1182. window->dictBase = (BYTE const*)" ";
  1183. ZSTD_STATIC_ASSERT(ZSTD_DUBT_UNSORTED_MARK < ZSTD_WINDOW_START_INDEX); /* Start above ZSTD_DUBT_UNSORTED_MARK */
  1184. window->dictLimit = ZSTD_WINDOW_START_INDEX; /* start from >0, so that 1st position is valid */
  1185. window->lowLimit = ZSTD_WINDOW_START_INDEX; /* it ensures first and later CCtx usages compress the same */
  1186. window->nextSrc = window->base + ZSTD_WINDOW_START_INDEX; /* see issue #1241 */
  1187. window->nbOverflowCorrections = 0;
  1188. }
  1189. /**
  1190. * ZSTD_window_update():
  1191. * Updates the window by appending [src, src + srcSize) to the window.
  1192. * If it is not contiguous, the current prefix becomes the extDict, and we
  1193. * forget about the extDict. Handles overlap of the prefix and extDict.
  1194. * Returns non-zero if the segment is contiguous.
  1195. */
  1196. MEM_STATIC
  1197. ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  1198. U32 ZSTD_window_update(ZSTD_window_t* window,
  1199. const void* src, size_t srcSize,
  1200. int forceNonContiguous)
  1201. {
  1202. BYTE const* const ip = (BYTE const*)src;
  1203. U32 contiguous = 1;
  1204. DEBUGLOG(5, "ZSTD_window_update");
  1205. if (srcSize == 0)
  1206. return contiguous;
  1207. assert(window->base != NULL);
  1208. assert(window->dictBase != NULL);
  1209. /* Check if blocks follow each other */
  1210. if (src != window->nextSrc || forceNonContiguous) {
  1211. /* not contiguous */
  1212. size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);
  1213. DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);
  1214. window->lowLimit = window->dictLimit;
  1215. assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */
  1216. window->dictLimit = (U32)distanceFromBase;
  1217. window->dictBase = window->base;
  1218. window->base = ip - distanceFromBase;
  1219. /* ms->nextToUpdate = window->dictLimit; */
  1220. if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */
  1221. contiguous = 0;
  1222. }
  1223. window->nextSrc = ip + srcSize;
  1224. /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
  1225. if ( (ip+srcSize > window->dictBase + window->lowLimit)
  1226. & (ip < window->dictBase + window->dictLimit)) {
  1227. size_t const highInputIdx = (size_t)((ip + srcSize) - window->dictBase);
  1228. U32 const lowLimitMax = (highInputIdx > (size_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;
  1229. assert(highInputIdx < UINT_MAX);
  1230. window->lowLimit = lowLimitMax;
  1231. DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);
  1232. }
  1233. return contiguous;
  1234. }
  1235. /**
  1236. * Returns the lowest allowed match index. It may either be in the ext-dict or the prefix.
  1237. */
  1238. MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_MatchState_t* ms, U32 curr, unsigned windowLog)
  1239. {
  1240. U32 const maxDistance = 1U << windowLog;
  1241. U32 const lowestValid = ms->window.lowLimit;
  1242. U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
  1243. U32 const isDictionary = (ms->loadedDictEnd != 0);
  1244. /* When using a dictionary the entire dictionary is valid if a single byte of the dictionary
  1245. * is within the window. We invalidate the dictionary (and set loadedDictEnd to 0) when it isn't
  1246. * valid for the entire block. So this check is sufficient to find the lowest valid match index.
  1247. */
  1248. U32 const matchLowest = isDictionary ? lowestValid : withinWindow;
  1249. return matchLowest;
  1250. }
  1251. /**
  1252. * Returns the lowest allowed match index in the prefix.
  1253. */
  1254. MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_MatchState_t* ms, U32 curr, unsigned windowLog)
  1255. {
  1256. U32 const maxDistance = 1U << windowLog;
  1257. U32 const lowestValid = ms->window.dictLimit;
  1258. U32 const withinWindow = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
  1259. U32 const isDictionary = (ms->loadedDictEnd != 0);
  1260. /* When computing the lowest prefix index we need to take the dictionary into account to handle
  1261. * the edge case where the dictionary and the source are contiguous in memory.
  1262. */
  1263. U32 const matchLowest = isDictionary ? lowestValid : withinWindow;
  1264. return matchLowest;
  1265. }
  1266. /* index_safety_check:
  1267. * intentional underflow : ensure repIndex isn't overlapping dict + prefix
  1268. * @return 1 if values are not overlapping,
  1269. * 0 otherwise */
  1270. MEM_STATIC int ZSTD_index_overlap_check(const U32 prefixLowestIndex, const U32 repIndex) {
  1271. return ((U32)((prefixLowestIndex-1) - repIndex) >= 3);
  1272. }
  1273. /* debug functions */
  1274. #if (DEBUGLEVEL>=2)
  1275. MEM_STATIC double ZSTD_fWeight(U32 rawStat)
  1276. {
  1277. U32 const fp_accuracy = 8;
  1278. U32 const fp_multiplier = (1 << fp_accuracy);
  1279. U32 const newStat = rawStat + 1;
  1280. U32 const hb = ZSTD_highbit32(newStat);
  1281. U32 const BWeight = hb * fp_multiplier;
  1282. U32 const FWeight = (newStat << fp_accuracy) >> hb;
  1283. U32 const weight = BWeight + FWeight;
  1284. assert(hb + fp_accuracy < 31);
  1285. return (double)weight / fp_multiplier;
  1286. }
  1287. /* display a table content,
  1288. * listing each element, its frequency, and its predicted bit cost */
  1289. MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)
  1290. {
  1291. unsigned u, sum;
  1292. for (u=0, sum=0; u<=max; u++) sum += table[u];
  1293. DEBUGLOG(2, "total nb elts: %u", sum);
  1294. for (u=0; u<=max; u++) {
  1295. DEBUGLOG(2, "%2u: %5u (%.2f)",
  1296. u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );
  1297. }
  1298. }
  1299. #endif
  1300. /* Short Cache */
  1301. /* Normally, zstd matchfinders follow this flow:
  1302. * 1. Compute hash at ip
  1303. * 2. Load index from hashTable[hash]
  1304. * 3. Check if *ip == *(base + index)
  1305. * In dictionary compression, loading *(base + index) is often an L2 or even L3 miss.
  1306. *
  1307. * Short cache is an optimization which allows us to avoid step 3 most of the time
  1308. * when the data doesn't actually match. With short cache, the flow becomes:
  1309. * 1. Compute (hash, currentTag) at ip. currentTag is an 8-bit independent hash at ip.
  1310. * 2. Load (index, matchTag) from hashTable[hash]. See ZSTD_writeTaggedIndex to understand how this works.
  1311. * 3. Only if currentTag == matchTag, check *ip == *(base + index). Otherwise, continue.
  1312. *
  1313. * Currently, short cache is only implemented in CDict hashtables. Thus, its use is limited to
  1314. * dictMatchState matchfinders.
  1315. */
  1316. #define ZSTD_SHORT_CACHE_TAG_BITS 8
  1317. #define ZSTD_SHORT_CACHE_TAG_MASK ((1u << ZSTD_SHORT_CACHE_TAG_BITS) - 1)
  1318. /* Helper function for ZSTD_fillHashTable and ZSTD_fillDoubleHashTable.
  1319. * Unpacks hashAndTag into (hash, tag), then packs (index, tag) into hashTable[hash]. */
  1320. MEM_STATIC void ZSTD_writeTaggedIndex(U32* const hashTable, size_t hashAndTag, U32 index) {
  1321. size_t const hash = hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS;
  1322. U32 const tag = (U32)(hashAndTag & ZSTD_SHORT_CACHE_TAG_MASK);
  1323. assert(index >> (32 - ZSTD_SHORT_CACHE_TAG_BITS) == 0);
  1324. hashTable[hash] = (index << ZSTD_SHORT_CACHE_TAG_BITS) | tag;
  1325. }
  1326. /* Helper function for short cache matchfinders.
  1327. * Unpacks tag1 and tag2 from lower bits of packedTag1 and packedTag2, then checks if the tags match. */
  1328. MEM_STATIC int ZSTD_comparePackedTags(size_t packedTag1, size_t packedTag2) {
  1329. U32 const tag1 = packedTag1 & ZSTD_SHORT_CACHE_TAG_MASK;
  1330. U32 const tag2 = packedTag2 & ZSTD_SHORT_CACHE_TAG_MASK;
  1331. return tag1 == tag2;
  1332. }
  1333. /* ===============================================================
  1334. * Shared internal declarations
  1335. * These prototypes may be called from sources not in lib/compress
  1336. * =============================================================== */
  1337. /* ZSTD_loadCEntropy() :
  1338. * dict : must point at beginning of a valid zstd dictionary.
  1339. * return : size of dictionary header (size of magic number + dict ID + entropy tables)
  1340. * assumptions : magic number supposed already checked
  1341. * and dictSize >= 8 */
  1342. size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace,
  1343. const void* const dict, size_t dictSize);
  1344. void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs);
  1345. typedef struct {
  1346. U32 idx; /* Index in array of ZSTD_Sequence */
  1347. U32 posInSequence; /* Position within sequence at idx */
  1348. size_t posInSrc; /* Number of bytes given by sequences provided so far */
  1349. } ZSTD_SequencePosition;
  1350. /* for benchmark */
  1351. size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx,
  1352. const ZSTD_Sequence* const inSeqs, size_t nbSequences,
  1353. int const repcodeResolution);
  1354. typedef struct {
  1355. size_t nbSequences;
  1356. size_t blockSize;
  1357. size_t litSize;
  1358. } BlockSummary;
  1359. BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs);
  1360. /* ==============================================================
  1361. * Private declarations
  1362. * These prototypes shall only be called from within lib/compress
  1363. * ============================================================== */
  1364. /* ZSTD_getCParamsFromCCtxParams() :
  1365. * cParams are built depending on compressionLevel, src size hints,
  1366. * LDM and manually set compression parameters.
  1367. * Note: srcSizeHint == 0 means 0!
  1368. */
  1369. ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
  1370. const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
  1371. /*! ZSTD_initCStream_internal() :
  1372. * Private use only. Init streaming operation.
  1373. * expects params to be valid.
  1374. * must receive dict, or cdict, or none, but not both.
  1375. * @return : 0, or an error code */
  1376. size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
  1377. const void* dict, size_t dictSize,
  1378. const ZSTD_CDict* cdict,
  1379. const ZSTD_CCtx_params* params, unsigned long long pledgedSrcSize);
  1380. void ZSTD_resetSeqStore(SeqStore_t* ssPtr);
  1381. /*! ZSTD_getCParamsFromCDict() :
  1382. * as the name implies */
  1383. ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);
  1384. /* ZSTD_compressBegin_advanced_internal() :
  1385. * Private use only. To be called from zstdmt_compress.c. */
  1386. size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
  1387. const void* dict, size_t dictSize,
  1388. ZSTD_dictContentType_e dictContentType,
  1389. ZSTD_dictTableLoadMethod_e dtlm,
  1390. const ZSTD_CDict* cdict,
  1391. const ZSTD_CCtx_params* params,
  1392. unsigned long long pledgedSrcSize);
  1393. /* ZSTD_compress_advanced_internal() :
  1394. * Private use only. To be called from zstdmt_compress.c. */
  1395. size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,
  1396. void* dst, size_t dstCapacity,
  1397. const void* src, size_t srcSize,
  1398. const void* dict,size_t dictSize,
  1399. const ZSTD_CCtx_params* params);
  1400. /* ZSTD_writeLastEmptyBlock() :
  1401. * output an empty Block with end-of-frame mark to complete a frame
  1402. * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
  1403. * or an error code if `dstCapacity` is too small (<ZSTD_blockHeaderSize)
  1404. */
  1405. size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);
  1406. /* ZSTD_referenceExternalSequences() :
  1407. * Must be called before starting a compression operation.
  1408. * seqs must parse a prefix of the source.
  1409. * This cannot be used when long range matching is enabled.
  1410. * Zstd will use these sequences, and pass the literals to a secondary block
  1411. * compressor.
  1412. * NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory
  1413. * access and data corruption.
  1414. */
  1415. void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);
  1416. /** ZSTD_cycleLog() :
  1417. * condition for correct operation : hashLog > 1 */
  1418. U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat);
  1419. /** ZSTD_CCtx_trace() :
  1420. * Trace the end of a compression call.
  1421. */
  1422. void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize);
  1423. /* Returns 1 if an external sequence producer is registered, otherwise returns 0. */
  1424. MEM_STATIC int ZSTD_hasExtSeqProd(const ZSTD_CCtx_params* params) {
  1425. return params->extSeqProdFunc != NULL;
  1426. }
  1427. /* ===============================================================
  1428. * Deprecated definitions that are still used internally to avoid
  1429. * deprecation warnings. These functions are exactly equivalent to
  1430. * their public variants, but avoid the deprecation warnings.
  1431. * =============================================================== */
  1432. size_t ZSTD_compressBegin_usingCDict_deprecated(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
  1433. size_t ZSTD_compressContinue_public(ZSTD_CCtx* cctx,
  1434. void* dst, size_t dstCapacity,
  1435. const void* src, size_t srcSize);
  1436. size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx,
  1437. void* dst, size_t dstCapacity,
  1438. const void* src, size_t srcSize);
  1439. size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
  1440. #endif /* ZSTD_COMPRESS_H */