1 /*
2  * Copyright (c) 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 
11  /*-*************************************
12  *  Dependencies
13  ***************************************/
14 #include "zstd_compress_superblock.h"
15 
16 #include "../common/zstd_internal.h"  /* ZSTD_getSequenceLength */
17 #include "hist.h"                     /* HIST_countFast_wksp */
18 #include "zstd_compress_internal.h"   /* ZSTD_[huf|fse|entropy]CTablesMetadata_t */
19 #include "zstd_compress_sequences.h"
20 #include "zstd_compress_literals.h"
21 
22 /** ZSTD_compressSubBlock_literal() :
23  *  Compresses literals section for a sub-block.
24  *  When we have to write the Huffman table we will sometimes choose a header
25  *  size larger than necessary. This is because we have to pick the header size
26  *  before we know the table size + compressed size, so we have a bound on the
27  *  table size. If we guessed incorrectly, we fall back to uncompressed literals.
28  *
29  *  We write the header when writeEntropy=1 and set entropyWritten=1 when we succeeded
30  *  in writing the header, otherwise it is set to 0.
31  *
32  *  hufMetadata->hType has literals block type info.
33  *      If it is set_basic, all sub-blocks literals section will be Raw_Literals_Block.
34  *      If it is set_rle, all sub-blocks literals section will be RLE_Literals_Block.
35  *      If it is set_compressed, first sub-block's literals section will be Compressed_Literals_Block
36  *      If it is set_compressed, first sub-block's literals section will be Treeless_Literals_Block
37  *      and the following sub-blocks' literals sections will be Treeless_Literals_Block.
38  *  @return : compressed size of literals section of a sub-block
39  *            Or 0 if it unable to compress.
40  *            Or error code */
ZSTD_compressSubBlock_literal(const HUF_CElt * hufTable,const ZSTD_hufCTablesMetadata_t * hufMetadata,const BYTE * literals,size_t litSize,void * dst,size_t dstSize,const int bmi2,int writeEntropy,int * entropyWritten)41 static size_t ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
42                                     const ZSTD_hufCTablesMetadata_t* hufMetadata,
43                                     const BYTE* literals, size_t litSize,
44                                     void* dst, size_t dstSize,
45                                     const int bmi2, int writeEntropy, int* entropyWritten)
46 {
47     size_t const header = writeEntropy ? 200 : 0;
48     size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header));
49     BYTE* const ostart = (BYTE*)dst;
50     BYTE* const oend = ostart + dstSize;
51     BYTE* op = ostart + lhSize;
52     U32 const singleStream = lhSize == 3;
53     symbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat;
54     size_t cLitSize = 0;
55 
56     (void)bmi2; /* TODO bmi2... */
57 
58     DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy);
59 
60     *entropyWritten = 0;
61     if (litSize == 0 || hufMetadata->hType == set_basic) {
62       DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal");
63       return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
64     } else if (hufMetadata->hType == set_rle) {
65       DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal");
66       return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize);
67     }
68 
69     assert(litSize > 0);
70     assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat);
71 
72     if (writeEntropy && hufMetadata->hType == set_compressed) {
73         ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize);
74         op += hufMetadata->hufDesSize;
75         cLitSize += hufMetadata->hufDesSize;
76         DEBUGLOG(5, "ZSTD_compressSubBlock_literal (hSize=%zu)", hufMetadata->hufDesSize);
77     }
78 
79     /* TODO bmi2 */
80     {   const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, oend-op, literals, litSize, hufTable)
81                                           : HUF_compress4X_usingCTable(op, oend-op, literals, litSize, hufTable);
82         op += cSize;
83         cLitSize += cSize;
84         if (cSize == 0 || ERR_isError(cSize)) {
85             DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize));
86             return 0;
87         }
88         /* If we expand and we aren't writing a header then emit uncompressed */
89         if (!writeEntropy && cLitSize >= litSize) {
90             DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible");
91             return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
92         }
93         /* If we are writing headers then allow expansion that doesn't change our header size. */
94         if (lhSize < (size_t)(3 + (cLitSize >= 1 KB) + (cLitSize >= 16 KB))) {
95             assert(cLitSize > litSize);
96             DEBUGLOG(5, "Literals expanded beyond allowed header size");
97             return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
98         }
99         DEBUGLOG(5, "ZSTD_compressSubBlock_literal (cSize=%zu)", cSize);
100     }
101 
102     /* Build header */
103     switch(lhSize)
104     {
105     case 3: /* 2 - 2 - 10 - 10 */
106         {   U32 const lhc = hType + ((!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
107             MEM_writeLE24(ostart, lhc);
108             break;
109         }
110     case 4: /* 2 - 2 - 14 - 14 */
111         {   U32 const lhc = hType + (2 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<18);
112             MEM_writeLE32(ostart, lhc);
113             break;
114         }
115     case 5: /* 2 - 2 - 18 - 18 */
116         {   U32 const lhc = hType + (3 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<22);
117             MEM_writeLE32(ostart, lhc);
118             ostart[4] = (BYTE)(cLitSize >> 10);
119             break;
120         }
121     default:  /* not possible : lhSize is {3,4,5} */
122         assert(0);
123     }
124     *entropyWritten = 1;
125     DEBUGLOG(5, "Compressed literals: %u -> %u", (U32)litSize, (U32)(op-ostart));
126     return op-ostart;
127 }
128 
ZSTD_seqDecompressedSize(seqStore_t const * seqStore,const seqDef * sequences,size_t nbSeq,size_t litSize,int lastSequence)129 static size_t ZSTD_seqDecompressedSize(seqStore_t const* seqStore, const seqDef* sequences, size_t nbSeq, size_t litSize, int lastSequence) {
130     const seqDef* const sstart = sequences;
131     const seqDef* const send = sequences + nbSeq;
132     const seqDef* sp = sstart;
133     size_t matchLengthSum = 0;
134     size_t litLengthSum = 0;
135     while (send-sp > 0) {
136         ZSTD_sequenceLength const seqLen = ZSTD_getSequenceLength(seqStore, sp);
137         litLengthSum += seqLen.litLength;
138         matchLengthSum += seqLen.matchLength;
139         sp++;
140     }
141     assert(litLengthSum <= litSize);
142     if (!lastSequence) {
143         assert(litLengthSum == litSize);
144     }
145     return matchLengthSum + litSize;
146 }
147 
148 /** ZSTD_compressSubBlock_sequences() :
149  *  Compresses sequences section for a sub-block.
150  *  fseMetadata->llType, fseMetadata->ofType, and fseMetadata->mlType have
151  *  symbol compression modes for the super-block.
152  *  The first successfully compressed block will have these in its header.
153  *  We set entropyWritten=1 when we succeed in compressing the sequences.
154  *  The following sub-blocks will always have repeat mode.
155  *  @return : compressed size of sequences section of a sub-block
156  *            Or 0 if it is unable to compress
157  *            Or error code. */
ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t * fseTables,const ZSTD_fseCTablesMetadata_t * fseMetadata,const seqDef * sequences,size_t nbSeq,const BYTE * llCode,const BYTE * mlCode,const BYTE * ofCode,const ZSTD_CCtx_params * cctxParams,void * dst,size_t dstCapacity,const int bmi2,int writeEntropy,int * entropyWritten)158 static size_t ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
159                                               const ZSTD_fseCTablesMetadata_t* fseMetadata,
160                                               const seqDef* sequences, size_t nbSeq,
161                                               const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
162                                               const ZSTD_CCtx_params* cctxParams,
163                                               void* dst, size_t dstCapacity,
164                                               const int bmi2, int writeEntropy, int* entropyWritten)
165 {
166     const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
167     BYTE* const ostart = (BYTE*)dst;
168     BYTE* const oend = ostart + dstCapacity;
169     BYTE* op = ostart;
170     BYTE* seqHead;
171 
172     DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (nbSeq=%zu, writeEntropy=%d, longOffsets=%d)", nbSeq, writeEntropy, longOffsets);
173 
174     *entropyWritten = 0;
175     /* Sequences Header */
176     RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
177                     dstSize_tooSmall, "");
178     if (nbSeq < 0x7F)
179         *op++ = (BYTE)nbSeq;
180     else if (nbSeq < LONGNBSEQ)
181         op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
182     else
183         op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
184     if (nbSeq==0) {
185         return op - ostart;
186     }
187 
188     /* seqHead : flags for FSE encoding type */
189     seqHead = op++;
190 
191     DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (seqHeadSize=%u)", (unsigned)(op-ostart));
192 
193     if (writeEntropy) {
194         const U32 LLtype = fseMetadata->llType;
195         const U32 Offtype = fseMetadata->ofType;
196         const U32 MLtype = fseMetadata->mlType;
197         DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize);
198         *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
199         ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize);
200         op += fseMetadata->fseTablesSize;
201     } else {
202         const U32 repeat = set_repeat;
203         *seqHead = (BYTE)((repeat<<6) + (repeat<<4) + (repeat<<2));
204     }
205 
206     {   size_t const bitstreamSize = ZSTD_encodeSequences(
207                                         op, oend - op,
208                                         fseTables->matchlengthCTable, mlCode,
209                                         fseTables->offcodeCTable, ofCode,
210                                         fseTables->litlengthCTable, llCode,
211                                         sequences, nbSeq,
212                                         longOffsets, bmi2);
213         FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
214         op += bitstreamSize;
215         /* zstd versions <= 1.3.4 mistakenly report corruption when
216          * FSE_readNCount() receives a buffer < 4 bytes.
217          * Fixed by https://github.com/facebook/zstd/pull/1146.
218          * This can happen when the last set_compressed table present is 2
219          * bytes and the bitstream is only one byte.
220          * In this exceedingly rare case, we will simply emit an uncompressed
221          * block, since it isn't worth optimizing.
222          */
223 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
224         if (writeEntropy && fseMetadata->lastCountSize && fseMetadata->lastCountSize + bitstreamSize < 4) {
225             /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
226             assert(fseMetadata->lastCountSize + bitstreamSize == 3);
227             DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
228                         "emitting an uncompressed block.");
229             return 0;
230         }
231 #endif
232         DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (bitstreamSize=%zu)", bitstreamSize);
233     }
234 
235     /* zstd versions <= 1.4.0 mistakenly report error when
236      * sequences section body size is less than 3 bytes.
237      * Fixed by https://github.com/facebook/zstd/pull/1664.
238      * This can happen when the previous sequences section block is compressed
239      * with rle mode and the current block's sequences section is compressed
240      * with repeat mode where sequences section body size can be 1 byte.
241      */
242 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
243     if (op-seqHead < 4) {
244         DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.4.0 by emitting "
245                     "an uncompressed block when sequences are < 4 bytes");
246         return 0;
247     }
248 #endif
249 
250     *entropyWritten = 1;
251     return op - ostart;
252 }
253 
254 /** ZSTD_compressSubBlock() :
255  *  Compresses a single sub-block.
256  *  @return : compressed size of the sub-block
257  *            Or 0 if it failed to compress. */
ZSTD_compressSubBlock(const ZSTD_entropyCTables_t * entropy,const ZSTD_entropyCTablesMetadata_t * entropyMetadata,const seqDef * sequences,size_t nbSeq,const BYTE * literals,size_t litSize,const BYTE * llCode,const BYTE * mlCode,const BYTE * ofCode,const ZSTD_CCtx_params * cctxParams,void * dst,size_t dstCapacity,const int bmi2,int writeLitEntropy,int writeSeqEntropy,int * litEntropyWritten,int * seqEntropyWritten,U32 lastBlock)258 static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
259                                     const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
260                                     const seqDef* sequences, size_t nbSeq,
261                                     const BYTE* literals, size_t litSize,
262                                     const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
263                                     const ZSTD_CCtx_params* cctxParams,
264                                     void* dst, size_t dstCapacity,
265                                     const int bmi2,
266                                     int writeLitEntropy, int writeSeqEntropy,
267                                     int* litEntropyWritten, int* seqEntropyWritten,
268                                     U32 lastBlock)
269 {
270     BYTE* const ostart = (BYTE*)dst;
271     BYTE* const oend = ostart + dstCapacity;
272     BYTE* op = ostart + ZSTD_blockHeaderSize;
273     DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)",
274                 litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);
275     {   size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,
276                                                         &entropyMetadata->hufMetadata, literals, litSize,
277                                                         op, oend-op, bmi2, writeLitEntropy, litEntropyWritten);
278         FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");
279         if (cLitSize == 0) return 0;
280         op += cLitSize;
281     }
282     {   size_t cSeqSize = ZSTD_compressSubBlock_sequences(&entropy->fse,
283                                                   &entropyMetadata->fseMetadata,
284                                                   sequences, nbSeq,
285                                                   llCode, mlCode, ofCode,
286                                                   cctxParams,
287                                                   op, oend-op,
288                                                   bmi2, writeSeqEntropy, seqEntropyWritten);
289         FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");
290         if (cSeqSize == 0) return 0;
291         op += cSeqSize;
292     }
293     /* Write block header */
294     {   size_t cSize = (op-ostart)-ZSTD_blockHeaderSize;
295         U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
296         MEM_writeLE24(ostart, cBlockHeader24);
297     }
298     return op-ostart;
299 }
300 
ZSTD_estimateSubBlockSize_literal(const BYTE * literals,size_t litSize,const ZSTD_hufCTables_t * huf,const ZSTD_hufCTablesMetadata_t * hufMetadata,void * workspace,size_t wkspSize,int writeEntropy)301 static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,
302                                                 const ZSTD_hufCTables_t* huf,
303                                                 const ZSTD_hufCTablesMetadata_t* hufMetadata,
304                                                 void* workspace, size_t wkspSize,
305                                                 int writeEntropy)
306 {
307     unsigned* const countWksp = (unsigned*)workspace;
308     unsigned maxSymbolValue = 255;
309     size_t literalSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
310 
311     if (hufMetadata->hType == set_basic) return litSize;
312     else if (hufMetadata->hType == set_rle) return 1;
313     else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
314         size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
315         if (ZSTD_isError(largest)) return litSize;
316         {   size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
317             if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
318             return cLitSizeEstimate + literalSectionHeaderSize;
319     }   }
320     assert(0); /* impossible */
321     return 0;
322 }
323 
ZSTD_estimateSubBlockSize_symbolType(symbolEncodingType_e type,const BYTE * codeTable,unsigned maxCode,size_t nbSeq,const FSE_CTable * fseCTable,const U32 * additionalBits,short const * defaultNorm,U32 defaultNormLog,U32 defaultMax,void * workspace,size_t wkspSize)324 static size_t ZSTD_estimateSubBlockSize_symbolType(symbolEncodingType_e type,
325                         const BYTE* codeTable, unsigned maxCode,
326                         size_t nbSeq, const FSE_CTable* fseCTable,
327                         const U32* additionalBits,
328                         short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
329                         void* workspace, size_t wkspSize)
330 {
331     unsigned* const countWksp = (unsigned*)workspace;
332     const BYTE* ctp = codeTable;
333     const BYTE* const ctStart = ctp;
334     const BYTE* const ctEnd = ctStart + nbSeq;
335     size_t cSymbolTypeSizeEstimateInBits = 0;
336     unsigned max = maxCode;
337 
338     HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize);  /* can't fail */
339     if (type == set_basic) {
340         /* We selected this encoding type, so it must be valid. */
341         assert(max <= defaultMax);
342         cSymbolTypeSizeEstimateInBits = max <= defaultMax
343                 ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max)
344                 : ERROR(GENERIC);
345     } else if (type == set_rle) {
346         cSymbolTypeSizeEstimateInBits = 0;
347     } else if (type == set_compressed || type == set_repeat) {
348         cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
349     }
350     if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) return nbSeq * 10;
351     while (ctp < ctEnd) {
352         if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
353         else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
354         ctp++;
355     }
356     return cSymbolTypeSizeEstimateInBits / 8;
357 }
358 
ZSTD_estimateSubBlockSize_sequences(const BYTE * ofCodeTable,const BYTE * llCodeTable,const BYTE * mlCodeTable,size_t nbSeq,const ZSTD_fseCTables_t * fseTables,const ZSTD_fseCTablesMetadata_t * fseMetadata,void * workspace,size_t wkspSize,int writeEntropy)359 static size_t ZSTD_estimateSubBlockSize_sequences(const BYTE* ofCodeTable,
360                                                   const BYTE* llCodeTable,
361                                                   const BYTE* mlCodeTable,
362                                                   size_t nbSeq,
363                                                   const ZSTD_fseCTables_t* fseTables,
364                                                   const ZSTD_fseCTablesMetadata_t* fseMetadata,
365                                                   void* workspace, size_t wkspSize,
366                                                   int writeEntropy)
367 {
368     size_t const sequencesSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
369     size_t cSeqSizeEstimate = 0;
370     if (nbSeq == 0) return sequencesSectionHeaderSize;
371     cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, MaxOff,
372                                          nbSeq, fseTables->offcodeCTable, NULL,
373                                          OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
374                                          workspace, wkspSize);
375     cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->llType, llCodeTable, MaxLL,
376                                          nbSeq, fseTables->litlengthCTable, LL_bits,
377                                          LL_defaultNorm, LL_defaultNormLog, MaxLL,
378                                          workspace, wkspSize);
379     cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, MaxML,
380                                          nbSeq, fseTables->matchlengthCTable, ML_bits,
381                                          ML_defaultNorm, ML_defaultNormLog, MaxML,
382                                          workspace, wkspSize);
383     if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
384     return cSeqSizeEstimate + sequencesSectionHeaderSize;
385 }
386 
ZSTD_estimateSubBlockSize(const BYTE * literals,size_t litSize,const BYTE * ofCodeTable,const BYTE * llCodeTable,const BYTE * mlCodeTable,size_t nbSeq,const ZSTD_entropyCTables_t * entropy,const ZSTD_entropyCTablesMetadata_t * entropyMetadata,void * workspace,size_t wkspSize,int writeLitEntropy,int writeSeqEntropy)387 static size_t ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
388                                         const BYTE* ofCodeTable,
389                                         const BYTE* llCodeTable,
390                                         const BYTE* mlCodeTable,
391                                         size_t nbSeq,
392                                         const ZSTD_entropyCTables_t* entropy,
393                                         const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
394                                         void* workspace, size_t wkspSize,
395                                         int writeLitEntropy, int writeSeqEntropy) {
396     size_t cSizeEstimate = 0;
397     cSizeEstimate += ZSTD_estimateSubBlockSize_literal(literals, litSize,
398                                                          &entropy->huf, &entropyMetadata->hufMetadata,
399                                                          workspace, wkspSize, writeLitEntropy);
400     cSizeEstimate += ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
401                                                          nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
402                                                          workspace, wkspSize, writeSeqEntropy);
403     return cSizeEstimate + ZSTD_blockHeaderSize;
404 }
405 
ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const * fseMetadata)406 static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMetadata)
407 {
408     if (fseMetadata->llType == set_compressed || fseMetadata->llType == set_rle)
409         return 1;
410     if (fseMetadata->mlType == set_compressed || fseMetadata->mlType == set_rle)
411         return 1;
412     if (fseMetadata->ofType == set_compressed || fseMetadata->ofType == set_rle)
413         return 1;
414     return 0;
415 }
416 
417 /** ZSTD_compressSubBlock_multi() :
418  *  Breaks super-block into multiple sub-blocks and compresses them.
419  *  Entropy will be written to the first block.
420  *  The following blocks will use repeat mode to compress.
421  *  All sub-blocks are compressed blocks (no raw or rle blocks).
422  *  @return : compressed size of the super block (which is multiple ZSTD blocks)
423  *            Or 0 if it failed to compress. */
ZSTD_compressSubBlock_multi(const seqStore_t * seqStorePtr,const ZSTD_compressedBlockState_t * prevCBlock,ZSTD_compressedBlockState_t * nextCBlock,const ZSTD_entropyCTablesMetadata_t * entropyMetadata,const ZSTD_CCtx_params * cctxParams,void * dst,size_t dstCapacity,const void * src,size_t srcSize,const int bmi2,U32 lastBlock,void * workspace,size_t wkspSize)424 static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
425                             const ZSTD_compressedBlockState_t* prevCBlock,
426                             ZSTD_compressedBlockState_t* nextCBlock,
427                             const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
428                             const ZSTD_CCtx_params* cctxParams,
429                                   void* dst, size_t dstCapacity,
430                             const void* src, size_t srcSize,
431                             const int bmi2, U32 lastBlock,
432                             void* workspace, size_t wkspSize)
433 {
434     const seqDef* const sstart = seqStorePtr->sequencesStart;
435     const seqDef* const send = seqStorePtr->sequences;
436     const seqDef* sp = sstart;
437     const BYTE* const lstart = seqStorePtr->litStart;
438     const BYTE* const lend = seqStorePtr->lit;
439     const BYTE* lp = lstart;
440     BYTE const* ip = (BYTE const*)src;
441     BYTE const* const iend = ip + srcSize;
442     BYTE* const ostart = (BYTE*)dst;
443     BYTE* const oend = ostart + dstCapacity;
444     BYTE* op = ostart;
445     const BYTE* llCodePtr = seqStorePtr->llCode;
446     const BYTE* mlCodePtr = seqStorePtr->mlCode;
447     const BYTE* ofCodePtr = seqStorePtr->ofCode;
448     size_t targetCBlockSize = cctxParams->targetCBlockSize;
449     size_t litSize, seqCount;
450     int writeLitEntropy = entropyMetadata->hufMetadata.hType == set_compressed;
451     int writeSeqEntropy = 1;
452     int lastSequence = 0;
453 
454     DEBUGLOG(5, "ZSTD_compressSubBlock_multi (litSize=%u, nbSeq=%u)",
455                 (unsigned)(lend-lp), (unsigned)(send-sstart));
456 
457     litSize = 0;
458     seqCount = 0;
459     do {
460         size_t cBlockSizeEstimate = 0;
461         if (sstart == send) {
462             lastSequence = 1;
463         } else {
464             const seqDef* const sequence = sp + seqCount;
465             lastSequence = sequence == send - 1;
466             litSize += ZSTD_getSequenceLength(seqStorePtr, sequence).litLength;
467             seqCount++;
468         }
469         if (lastSequence) {
470             assert(lp <= lend);
471             assert(litSize <= (size_t)(lend - lp));
472             litSize = (size_t)(lend - lp);
473         }
474         /* I think there is an optimization opportunity here.
475          * Calling ZSTD_estimateSubBlockSize for every sequence can be wasteful
476          * since it recalculates estimate from scratch.
477          * For example, it would recount literal distribution and symbol codes everytime.
478          */
479         cBlockSizeEstimate = ZSTD_estimateSubBlockSize(lp, litSize, ofCodePtr, llCodePtr, mlCodePtr, seqCount,
480                                                        &nextCBlock->entropy, entropyMetadata,
481                                                        workspace, wkspSize, writeLitEntropy, writeSeqEntropy);
482         if (cBlockSizeEstimate > targetCBlockSize || lastSequence) {
483             int litEntropyWritten = 0;
484             int seqEntropyWritten = 0;
485             const size_t decompressedSize = ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSequence);
486             const size_t cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
487                                                        sp, seqCount,
488                                                        lp, litSize,
489                                                        llCodePtr, mlCodePtr, ofCodePtr,
490                                                        cctxParams,
491                                                        op, oend-op,
492                                                        bmi2, writeLitEntropy, writeSeqEntropy,
493                                                        &litEntropyWritten, &seqEntropyWritten,
494                                                        lastBlock && lastSequence);
495             FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
496             if (cSize > 0 && cSize < decompressedSize) {
497                 DEBUGLOG(5, "Committed the sub-block");
498                 assert(ip + decompressedSize <= iend);
499                 ip += decompressedSize;
500                 sp += seqCount;
501                 lp += litSize;
502                 op += cSize;
503                 llCodePtr += seqCount;
504                 mlCodePtr += seqCount;
505                 ofCodePtr += seqCount;
506                 litSize = 0;
507                 seqCount = 0;
508                 /* Entropy only needs to be written once */
509                 if (litEntropyWritten) {
510                     writeLitEntropy = 0;
511                 }
512                 if (seqEntropyWritten) {
513                     writeSeqEntropy = 0;
514                 }
515             }
516         }
517     } while (!lastSequence);
518     if (writeLitEntropy) {
519         DEBUGLOG(5, "ZSTD_compressSubBlock_multi has literal entropy tables unwritten");
520         ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
521     }
522     if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {
523         /* If we haven't written our entropy tables, then we've violated our contract and
524          * must emit an uncompressed block.
525          */
526         DEBUGLOG(5, "ZSTD_compressSubBlock_multi has sequence entropy tables unwritten");
527         return 0;
528     }
529     if (ip < iend) {
530         size_t const cSize = ZSTD_noCompressBlock(op, oend - op, ip, iend - ip, lastBlock);
531         DEBUGLOG(5, "ZSTD_compressSubBlock_multi last sub-block uncompressed, %zu bytes", (size_t)(iend - ip));
532         FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
533         assert(cSize != 0);
534         op += cSize;
535         /* We have to regenerate the repcodes because we've skipped some sequences */
536         if (sp < send) {
537             seqDef const* seq;
538             repcodes_t rep;
539             ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
540             for (seq = sstart; seq < sp; ++seq) {
541                 rep = ZSTD_updateRep(rep.rep, seq->offset - 1, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
542             }
543             ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
544         }
545     }
546     DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed");
547     return op-ostart;
548 }
549 
ZSTD_compressSuperBlock(ZSTD_CCtx * zc,void * dst,size_t dstCapacity,void const * src,size_t srcSize,unsigned lastBlock)550 size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
551                                void* dst, size_t dstCapacity,
552                                void const* src, size_t srcSize,
553                                unsigned lastBlock) {
554     ZSTD_entropyCTablesMetadata_t entropyMetadata;
555 
556     FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,
557           &zc->blockState.prevCBlock->entropy,
558           &zc->blockState.nextCBlock->entropy,
559           &zc->appliedParams,
560           &entropyMetadata,
561           zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */), "");
562 
563     return ZSTD_compressSubBlock_multi(&zc->seqStore,
564             zc->blockState.prevCBlock,
565             zc->blockState.nextCBlock,
566             &entropyMetadata,
567             &zc->appliedParams,
568             dst, dstCapacity,
569             src, srcSize,
570             zc->bmi2, lastBlock,
571             zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */);
572 }
573