Coverage Report

Created: 2025-08-24 07:06

/src/zstd/lib/compress/zstd_compress_superblock.c
Line
Count
Source (jump to first uncovered line)
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
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 unable to compress.
40
 *            Or error code */
41
static size_t
42
ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
43
                              const ZSTD_hufCTablesMetadata_t* hufMetadata,
44
                              const BYTE* literals, size_t litSize,
45
                              void* dst, size_t dstSize,
46
                              const int bmi2, int writeEntropy, int* entropyWritten)
47
1.27M
{
48
1.27M
    size_t const header = writeEntropy ? 200 : 0;
49
1.27M
    size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header));
50
1.27M
    BYTE* const ostart = (BYTE*)dst;
51
1.27M
    BYTE* const oend = ostart + dstSize;
52
1.27M
    BYTE* op = ostart + lhSize;
53
1.27M
    U32 const singleStream = lhSize == 3;
54
1.27M
    SymbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat;
55
1.27M
    size_t cLitSize = 0;
56
57
1.27M
    DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy);
58
59
1.27M
    *entropyWritten = 0;
60
1.27M
    if (litSize == 0 || hufMetadata->hType == set_basic) {
61
741k
      DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal");
62
741k
      return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
63
741k
    } else if (hufMetadata->hType == set_rle) {
64
3.25k
      DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal");
65
3.25k
      return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize);
66
3.25k
    }
67
68
531k
    assert(litSize > 0);
69
531k
    assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat);
70
71
531k
    if (writeEntropy && hufMetadata->hType == set_compressed) {
72
449k
        ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize);
73
449k
        op += hufMetadata->hufDesSize;
74
449k
        cLitSize += hufMetadata->hufDesSize;
75
449k
        DEBUGLOG(5, "ZSTD_compressSubBlock_literal (hSize=%zu)", hufMetadata->hufDesSize);
76
449k
    }
77
78
531k
    {   int const flags = bmi2 ? HUF_flags_bmi2 : 0;
79
531k
        const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags)
80
531k
                                          : HUF_compress4X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags);
81
531k
        op += cSize;
82
531k
        cLitSize += cSize;
83
531k
        if (cSize == 0 || ERR_isError(cSize)) {
84
0
            DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize));
85
0
            return 0;
86
0
        }
87
        /* If we expand and we aren't writing a header then emit uncompressed */
88
531k
        if (!writeEntropy && cLitSize >= litSize) {
89
6.24k
            DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible");
90
6.24k
            return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
91
6.24k
        }
92
        /* If we are writing headers then allow expansion that doesn't change our header size. */
93
525k
        if (lhSize < (size_t)(3 + (cLitSize >= 1 KB) + (cLitSize >= 16 KB))) {
94
25
            assert(cLitSize > litSize);
95
25
            DEBUGLOG(5, "Literals expanded beyond allowed header size");
96
25
            return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
97
25
        }
98
525k
        DEBUGLOG(5, "ZSTD_compressSubBlock_literal (cSize=%zu)", cSize);
99
525k
    }
100
101
    /* Build header */
102
0
    switch(lhSize)
103
525k
    {
104
418k
    case 3: /* 2 - 2 - 10 - 10 */
105
418k
        {   U32 const lhc = hType + ((U32)(!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
106
418k
            MEM_writeLE24(ostart, lhc);
107
418k
            break;
108
0
        }
109
104k
    case 4: /* 2 - 2 - 14 - 14 */
110
104k
        {   U32 const lhc = hType + (2 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<18);
111
104k
            MEM_writeLE32(ostart, lhc);
112
104k
            break;
113
0
        }
114
1.31k
    case 5: /* 2 - 2 - 18 - 18 */
115
1.31k
        {   U32 const lhc = hType + (3 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<22);
116
1.31k
            MEM_writeLE32(ostart, lhc);
117
1.31k
            ostart[4] = (BYTE)(cLitSize >> 10);
118
1.31k
            break;
119
0
        }
120
0
    default:  /* not possible : lhSize is {3,4,5} */
121
0
        assert(0);
122
525k
    }
123
525k
    *entropyWritten = 1;
124
525k
    DEBUGLOG(5, "Compressed literals: %u -> %u", (U32)litSize, (U32)(op-ostart));
125
525k
    return (size_t)(op-ostart);
126
525k
}
127
128
static size_t
129
ZSTD_seqDecompressedSize(SeqStore_t const* seqStore,
130
                   const SeqDef* sequences, size_t nbSeqs,
131
                         size_t litSize, int lastSubBlock)
132
1.27M
{
133
1.27M
    size_t matchLengthSum = 0;
134
1.27M
    size_t litLengthSum = 0;
135
1.27M
    size_t n;
136
53.6M
    for (n=0; n<nbSeqs; n++) {
137
52.3M
        const ZSTD_SequenceLength seqLen = ZSTD_getSequenceLength(seqStore, sequences+n);
138
52.3M
        litLengthSum += seqLen.litLength;
139
52.3M
        matchLengthSum += seqLen.matchLength;
140
52.3M
    }
141
1.27M
    DEBUGLOG(5, "ZSTD_seqDecompressedSize: %u sequences from %p: %u literals + %u matchlength",
142
1.27M
                (unsigned)nbSeqs, (const void*)sequences,
143
1.27M
                (unsigned)litLengthSum, (unsigned)matchLengthSum);
144
1.27M
    if (!lastSubBlock)
145
19.9k
        assert(litLengthSum == litSize);
146
1.25M
    else
147
1.25M
        assert(litLengthSum <= litSize);
148
1.27M
    (void)litLengthSum;
149
1.27M
    return matchLengthSum + litSize;
150
1.27M
}
151
152
/** ZSTD_compressSubBlock_sequences() :
153
 *  Compresses sequences section for a sub-block.
154
 *  fseMetadata->llType, fseMetadata->ofType, and fseMetadata->mlType have
155
 *  symbol compression modes for the super-block.
156
 *  The first successfully compressed block will have these in its header.
157
 *  We set entropyWritten=1 when we succeed in compressing the sequences.
158
 *  The following sub-blocks will always have repeat mode.
159
 *  @return : compressed size of sequences section of a sub-block
160
 *            Or 0 if it is unable to compress
161
 *            Or error code. */
162
static size_t
163
ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
164
                                const ZSTD_fseCTablesMetadata_t* fseMetadata,
165
                                const SeqDef* sequences, size_t nbSeq,
166
                                const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
167
                                const ZSTD_CCtx_params* cctxParams,
168
                                void* dst, size_t dstCapacity,
169
                                const int bmi2, int writeEntropy, int* entropyWritten)
170
1.27M
{
171
1.27M
    const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
172
1.27M
    BYTE* const ostart = (BYTE*)dst;
173
1.27M
    BYTE* const oend = ostart + dstCapacity;
174
1.27M
    BYTE* op = ostart;
175
1.27M
    BYTE* seqHead;
176
177
1.27M
    DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (nbSeq=%zu, writeEntropy=%d, longOffsets=%d)", nbSeq, writeEntropy, longOffsets);
178
179
1.27M
    *entropyWritten = 0;
180
    /* Sequences Header */
181
1.27M
    RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
182
1.27M
                    dstSize_tooSmall, "");
183
1.27M
    if (nbSeq < 128)
184
1.20M
        *op++ = (BYTE)nbSeq;
185
75.7k
    else if (nbSeq < LONGNBSEQ)
186
75.7k
        op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
187
18.4E
    else
188
18.4E
        op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
189
1.27M
    if (nbSeq==0) {
190
123k
        return (size_t)(op - ostart);
191
123k
    }
192
193
    /* seqHead : flags for FSE encoding type */
194
1.15M
    seqHead = op++;
195
196
1.15M
    DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (seqHeadSize=%u)", (unsigned)(op-ostart));
197
198
1.15M
    if (writeEntropy) {
199
1.13M
        const U32 LLtype = fseMetadata->llType;
200
1.13M
        const U32 Offtype = fseMetadata->ofType;
201
1.13M
        const U32 MLtype = fseMetadata->mlType;
202
1.13M
        DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize);
203
1.13M
        *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
204
1.13M
        ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize);
205
1.13M
        op += fseMetadata->fseTablesSize;
206
1.13M
    } else {
207
16.1k
        const U32 repeat = set_repeat;
208
16.1k
        *seqHead = (BYTE)((repeat<<6) + (repeat<<4) + (repeat<<2));
209
16.1k
    }
210
211
1.15M
    {   size_t const bitstreamSize = ZSTD_encodeSequences(
212
1.15M
                                        op, (size_t)(oend - op),
213
1.15M
                                        fseTables->matchlengthCTable, mlCode,
214
1.15M
                                        fseTables->offcodeCTable, ofCode,
215
1.15M
                                        fseTables->litlengthCTable, llCode,
216
1.15M
                                        sequences, nbSeq,
217
1.15M
                                        longOffsets, bmi2);
218
1.15M
        FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
219
1.15M
        op += bitstreamSize;
220
        /* zstd versions <= 1.3.4 mistakenly report corruption when
221
         * FSE_readNCount() receives a buffer < 4 bytes.
222
         * Fixed by https://github.com/facebook/zstd/pull/1146.
223
         * This can happen when the last set_compressed table present is 2
224
         * bytes and the bitstream is only one byte.
225
         * In this exceedingly rare case, we will simply emit an uncompressed
226
         * block, since it isn't worth optimizing.
227
         */
228
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
229
        if (writeEntropy && fseMetadata->lastCountSize && fseMetadata->lastCountSize + bitstreamSize < 4) {
230
            /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
231
            assert(fseMetadata->lastCountSize + bitstreamSize == 3);
232
            DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
233
                        "emitting an uncompressed block.");
234
            return 0;
235
        }
236
#endif
237
1.15M
        DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (bitstreamSize=%zu)", bitstreamSize);
238
1.15M
    }
239
240
    /* zstd versions <= 1.4.0 mistakenly report error when
241
     * sequences section body size is less than 3 bytes.
242
     * Fixed by https://github.com/facebook/zstd/pull/1664.
243
     * This can happen when the previous sequences section block is compressed
244
     * with rle mode and the current block's sequences section is compressed
245
     * with repeat mode where sequences section body size can be 1 byte.
246
     */
247
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
248
    if (op-seqHead < 4) {
249
        DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.4.0 by emitting "
250
                    "an uncompressed block when sequences are < 4 bytes");
251
        return 0;
252
    }
253
#endif
254
255
0
    *entropyWritten = 1;
256
1.15M
    return (size_t)(op - ostart);
257
1.15M
}
258
259
/** ZSTD_compressSubBlock() :
260
 *  Compresses a single sub-block.
261
 *  @return : compressed size of the sub-block
262
 *            Or 0 if it failed to compress. */
263
static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
264
                                    const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
265
                                    const SeqDef* sequences, size_t nbSeq,
266
                                    const BYTE* literals, size_t litSize,
267
                                    const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
268
                                    const ZSTD_CCtx_params* cctxParams,
269
                                    void* dst, size_t dstCapacity,
270
                                    const int bmi2,
271
                                    int writeLitEntropy, int writeSeqEntropy,
272
                                    int* litEntropyWritten, int* seqEntropyWritten,
273
                                    U32 lastBlock)
274
1.27M
{
275
1.27M
    BYTE* const ostart = (BYTE*)dst;
276
1.27M
    BYTE* const oend = ostart + dstCapacity;
277
1.27M
    BYTE* op = ostart + ZSTD_blockHeaderSize;
278
1.27M
    DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)",
279
1.27M
                litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);
280
1.27M
    {   size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,
281
1.27M
                                                        &entropyMetadata->hufMetadata, literals, litSize,
282
1.27M
                                                        op, (size_t)(oend-op),
283
1.27M
                                                        bmi2, writeLitEntropy, litEntropyWritten);
284
1.27M
        FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");
285
1.27M
        if (cLitSize == 0) return 0;
286
1.27M
        op += cLitSize;
287
1.27M
    }
288
0
    {   size_t cSeqSize = ZSTD_compressSubBlock_sequences(&entropy->fse,
289
1.27M
                                                  &entropyMetadata->fseMetadata,
290
1.27M
                                                  sequences, nbSeq,
291
1.27M
                                                  llCode, mlCode, ofCode,
292
1.27M
                                                  cctxParams,
293
1.27M
                                                  op, (size_t)(oend-op),
294
1.27M
                                                  bmi2, writeSeqEntropy, seqEntropyWritten);
295
1.27M
        FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");
296
1.27M
        if (cSeqSize == 0) return 0;
297
1.27M
        op += cSeqSize;
298
1.27M
    }
299
    /* Write block header */
300
0
    {   size_t cSize = (size_t)(op-ostart) - ZSTD_blockHeaderSize;
301
1.27M
        U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
302
1.27M
        MEM_writeLE24(ostart, cBlockHeader24);
303
1.27M
    }
304
1.27M
    return (size_t)(op-ostart);
305
1.27M
}
306
307
static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,
308
                                                const ZSTD_hufCTables_t* huf,
309
                                                const ZSTD_hufCTablesMetadata_t* hufMetadata,
310
                                                void* workspace, size_t wkspSize,
311
                                                int writeEntropy)
312
1.15M
{
313
1.15M
    unsigned* const countWksp = (unsigned*)workspace;
314
1.15M
    unsigned maxSymbolValue = 255;
315
1.15M
    size_t literalSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
316
317
1.15M
    if (hufMetadata->hType == set_basic) return litSize;
318
499k
    else if (hufMetadata->hType == set_rle) return 1;
319
496k
    else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
320
496k
        size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
321
496k
        if (ZSTD_isError(largest)) return litSize;
322
496k
        {   size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
323
496k
            if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
324
496k
            return cLitSizeEstimate + literalSectionHeaderSize;
325
496k
    }   }
326
18.4E
    assert(0); /* impossible */
327
0
    return 0;
328
18.4E
}
329
330
static size_t ZSTD_estimateSubBlockSize_symbolType(SymbolEncodingType_e type,
331
                        const BYTE* codeTable, unsigned maxCode,
332
                        size_t nbSeq, const FSE_CTable* fseCTable,
333
                        const U8* additionalBits,
334
                        short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
335
                        void* workspace, size_t wkspSize)
336
3.45M
{
337
3.45M
    unsigned* const countWksp = (unsigned*)workspace;
338
3.45M
    const BYTE* ctp = codeTable;
339
3.45M
    const BYTE* const ctStart = ctp;
340
3.45M
    const BYTE* const ctEnd = ctStart + nbSeq;
341
3.45M
    size_t cSymbolTypeSizeEstimateInBits = 0;
342
3.45M
    unsigned max = maxCode;
343
344
3.45M
    HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize);  /* can't fail */
345
3.45M
    if (type == set_basic) {
346
        /* We selected this encoding type, so it must be valid. */
347
1.92M
        assert(max <= defaultMax);
348
1.92M
        cSymbolTypeSizeEstimateInBits = max <= defaultMax
349
1.92M
                ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max)
350
1.92M
                : ERROR(GENERIC);
351
1.92M
    } else if (type == set_rle) {
352
98.2k
        cSymbolTypeSizeEstimateInBits = 0;
353
1.42M
    } else if (type == set_compressed || type == set_repeat) {
354
1.42M
        cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
355
1.42M
    }
356
3.45M
    if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) return nbSeq * 10;
357
160M
    while (ctp < ctEnd) {
358
157M
        if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
359
52.3M
        else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
360
157M
        ctp++;
361
157M
    }
362
3.45M
    return cSymbolTypeSizeEstimateInBits / 8;
363
3.45M
}
364
365
static size_t ZSTD_estimateSubBlockSize_sequences(const BYTE* ofCodeTable,
366
                                                  const BYTE* llCodeTable,
367
                                                  const BYTE* mlCodeTable,
368
                                                  size_t nbSeq,
369
                                                  const ZSTD_fseCTables_t* fseTables,
370
                                                  const ZSTD_fseCTablesMetadata_t* fseMetadata,
371
                                                  void* workspace, size_t wkspSize,
372
                                                  int writeEntropy)
373
1.15M
{
374
1.15M
    size_t const sequencesSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
375
1.15M
    size_t cSeqSizeEstimate = 0;
376
1.15M
    if (nbSeq == 0) return sequencesSectionHeaderSize;
377
1.15M
    cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, MaxOff,
378
1.15M
                                         nbSeq, fseTables->offcodeCTable, NULL,
379
1.15M
                                         OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
380
1.15M
                                         workspace, wkspSize);
381
1.15M
    cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->llType, llCodeTable, MaxLL,
382
1.15M
                                         nbSeq, fseTables->litlengthCTable, LL_bits,
383
1.15M
                                         LL_defaultNorm, LL_defaultNormLog, MaxLL,
384
1.15M
                                         workspace, wkspSize);
385
1.15M
    cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, MaxML,
386
1.15M
                                         nbSeq, fseTables->matchlengthCTable, ML_bits,
387
1.15M
                                         ML_defaultNorm, ML_defaultNormLog, MaxML,
388
1.15M
                                         workspace, wkspSize);
389
1.15M
    if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
390
1.15M
    return cSeqSizeEstimate + sequencesSectionHeaderSize;
391
1.15M
}
392
393
typedef struct {
394
    size_t estLitSize;
395
    size_t estBlockSize;
396
} EstimatedBlockSize;
397
static EstimatedBlockSize ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
398
                                        const BYTE* ofCodeTable,
399
                                        const BYTE* llCodeTable,
400
                                        const BYTE* mlCodeTable,
401
                                        size_t nbSeq,
402
                                        const ZSTD_entropyCTables_t* entropy,
403
                                        const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
404
                                        void* workspace, size_t wkspSize,
405
                                        int writeLitEntropy, int writeSeqEntropy)
406
1.15M
{
407
1.15M
    EstimatedBlockSize ebs;
408
1.15M
    ebs.estLitSize = ZSTD_estimateSubBlockSize_literal(literals, litSize,
409
1.15M
                                                        &entropy->huf, &entropyMetadata->hufMetadata,
410
1.15M
                                                        workspace, wkspSize, writeLitEntropy);
411
1.15M
    ebs.estBlockSize = ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
412
1.15M
                                                         nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
413
1.15M
                                                         workspace, wkspSize, writeSeqEntropy);
414
1.15M
    ebs.estBlockSize += ebs.estLitSize + ZSTD_blockHeaderSize;
415
1.15M
    return ebs;
416
1.15M
}
417
418
static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMetadata)
419
145k
{
420
145k
    if (fseMetadata->llType == set_compressed || fseMetadata->llType == set_rle)
421
317
        return 1;
422
144k
    if (fseMetadata->mlType == set_compressed || fseMetadata->mlType == set_rle)
423
1.17k
        return 1;
424
143k
    if (fseMetadata->ofType == set_compressed || fseMetadata->ofType == set_rle)
425
310
        return 1;
426
143k
    return 0;
427
143k
}
428
429
static size_t countLiterals(SeqStore_t const* seqStore, const SeqDef* sp, size_t seqCount)
430
19.9k
{
431
19.9k
    size_t n, total = 0;
432
19.9k
    assert(sp != NULL);
433
1.01M
    for (n=0; n<seqCount; n++) {
434
991k
        total += ZSTD_getSequenceLength(seqStore, sp+n).litLength;
435
991k
    }
436
19.9k
    DEBUGLOG(6, "countLiterals for %zu sequences from %p => %zu bytes", seqCount, (const void*)sp, total);
437
19.9k
    return total;
438
19.9k
}
439
440
3.51M
#define BYTESCALE 256
441
442
static size_t sizeBlockSequences(const SeqDef* sp, size_t nbSeqs,
443
                size_t targetBudget, size_t avgLitCost, size_t avgSeqCost,
444
                int firstSubBlock)
445
23.3k
{
446
23.3k
    size_t n, budget = 0, inSize=0;
447
    /* entropy headers */
448
23.3k
    size_t const headerSize = (size_t)firstSubBlock * 120 * BYTESCALE; /* generous estimate */
449
23.3k
    assert(firstSubBlock==0 || firstSubBlock==1);
450
23.3k
    budget += headerSize;
451
452
    /* first sequence => at least one sequence*/
453
23.3k
    budget += sp[0].litLength * avgLitCost + avgSeqCost;
454
23.3k
    if (budget > targetBudget) return 1;
455
16.5k
    inSize = sp[0].litLength + (sp[0].mlBase+MINMATCH);
456
457
    /* loop over sequences */
458
1.04M
    for (n=1; n<nbSeqs; n++) {
459
1.04M
        size_t currentCost = sp[n].litLength * avgLitCost + avgSeqCost;
460
1.04M
        budget += currentCost;
461
1.04M
        inSize += sp[n].litLength + (sp[n].mlBase+MINMATCH);
462
        /* stop when sub-block budget is reached */
463
1.04M
        if ( (budget > targetBudget)
464
            /* though continue to expand until the sub-block is deemed compressible */
465
1.04M
          && (budget < inSize * BYTESCALE) )
466
13.5k
            break;
467
1.04M
    }
468
469
16.5k
    return n;
470
23.3k
}
471
472
/** ZSTD_compressSubBlock_multi() :
473
 *  Breaks super-block into multiple sub-blocks and compresses them.
474
 *  Entropy will be written into the first block.
475
 *  The following blocks use repeat_mode to compress.
476
 *  Sub-blocks are all compressed, except the last one when beneficial.
477
 *  @return : compressed size of the super block (which features multiple ZSTD blocks)
478
 *            or 0 if it failed to compress. */
479
static size_t ZSTD_compressSubBlock_multi(const SeqStore_t* seqStorePtr,
480
                            const ZSTD_compressedBlockState_t* prevCBlock,
481
                            ZSTD_compressedBlockState_t* nextCBlock,
482
                            const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
483
                            const ZSTD_CCtx_params* cctxParams,
484
                                  void* dst, size_t dstCapacity,
485
                            const void* src, size_t srcSize,
486
                            const int bmi2, U32 lastBlock,
487
                            void* workspace, size_t wkspSize)
488
1.27M
{
489
1.27M
    const SeqDef* const sstart = seqStorePtr->sequencesStart;
490
1.27M
    const SeqDef* const send = seqStorePtr->sequences;
491
1.27M
    const SeqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */
492
1.27M
    size_t const nbSeqs = (size_t)(send - sstart);
493
1.27M
    const BYTE* const lstart = seqStorePtr->litStart;
494
1.27M
    const BYTE* const lend = seqStorePtr->lit;
495
1.27M
    const BYTE* lp = lstart;
496
1.27M
    size_t const nbLiterals = (size_t)(lend - lstart);
497
1.27M
    BYTE const* ip = (BYTE const*)src;
498
1.27M
    BYTE const* const iend = ip + srcSize;
499
1.27M
    BYTE* const ostart = (BYTE*)dst;
500
1.27M
    BYTE* const oend = ostart + dstCapacity;
501
1.27M
    BYTE* op = ostart;
502
1.27M
    const BYTE* llCodePtr = seqStorePtr->llCode;
503
1.27M
    const BYTE* mlCodePtr = seqStorePtr->mlCode;
504
1.27M
    const BYTE* ofCodePtr = seqStorePtr->ofCode;
505
1.27M
    size_t const minTarget = ZSTD_TARGETCBLOCKSIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */
506
1.27M
    size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
507
1.27M
    int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
508
1.27M
    int writeSeqEntropy = 1;
509
510
1.27M
    DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",
511
1.27M
               (unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));
512
513
        /* let's start by a general estimation for the full block */
514
1.27M
    if (nbSeqs > 0) {
515
1.15M
        EstimatedBlockSize const ebs =
516
1.15M
                ZSTD_estimateSubBlockSize(lp, nbLiterals,
517
1.15M
                                        ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
518
1.15M
                                        &nextCBlock->entropy, entropyMetadata,
519
1.15M
                                        workspace, wkspSize,
520
1.15M
                                        writeLitEntropy, writeSeqEntropy);
521
        /* quick estimation */
522
1.15M
        size_t const avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
523
1.15M
        size_t const avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
524
1.15M
        const size_t nbSubBlocks = MAX((ebs.estBlockSize + (targetCBlockSize/2)) / targetCBlockSize, 1);
525
1.15M
        size_t n, avgBlockBudget, blockBudgetSupp=0;
526
1.15M
        avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;
527
1.15M
        DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
528
1.15M
                    (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
529
1.15M
                    (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
530
        /* simplification: if estimates states that the full superblock doesn't compress, just bail out immediately
531
         * this will result in the production of a single uncompressed block covering @srcSize.*/
532
1.15M
        if (ebs.estBlockSize > srcSize) return 0;
533
534
        /* compress and write sub-blocks */
535
1.13M
        assert(nbSubBlocks>0);
536
1.15M
        for (n=0; n < nbSubBlocks-1; n++) {
537
            /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
538
23.3k
            size_t const seqCount = sizeBlockSequences(sp, (size_t)(send-sp),
539
23.3k
                                        avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
540
            /* if reached last sequence : break to last sub-block (simplification) */
541
23.3k
            assert(seqCount <= (size_t)(send-sp));
542
23.3k
            if (sp + seqCount == send) break;
543
19.9k
            assert(seqCount > 0);
544
            /* compress sub-block */
545
19.9k
            {   int litEntropyWritten = 0;
546
19.9k
                int seqEntropyWritten = 0;
547
19.9k
                size_t litSize = countLiterals(seqStorePtr, sp, seqCount);
548
19.9k
                const size_t decompressedSize =
549
19.9k
                        ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 0);
550
19.9k
                size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
551
19.9k
                                                sp, seqCount,
552
19.9k
                                                lp, litSize,
553
19.9k
                                                llCodePtr, mlCodePtr, ofCodePtr,
554
19.9k
                                                cctxParams,
555
19.9k
                                                op, (size_t)(oend-op),
556
19.9k
                                                bmi2, writeLitEntropy, writeSeqEntropy,
557
19.9k
                                                &litEntropyWritten, &seqEntropyWritten,
558
19.9k
                                                0);
559
19.9k
                FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
560
561
                /* check compressibility, update state components */
562
19.9k
                if (cSize > 0 && cSize < decompressedSize) {
563
13.3k
                    DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",
564
13.3k
                                (unsigned)decompressedSize, (unsigned)cSize);
565
13.3k
                    assert(ip + decompressedSize <= iend);
566
13.3k
                    ip += decompressedSize;
567
13.3k
                    lp += litSize;
568
13.3k
                    op += cSize;
569
13.3k
                    llCodePtr += seqCount;
570
13.3k
                    mlCodePtr += seqCount;
571
13.3k
                    ofCodePtr += seqCount;
572
                    /* Entropy only needs to be written once */
573
13.3k
                    if (litEntropyWritten) {
574
7.42k
                        writeLitEntropy = 0;
575
7.42k
                    }
576
13.3k
                    if (seqEntropyWritten) {
577
13.3k
                        writeSeqEntropy = 0;
578
13.3k
                    }
579
13.3k
                    sp += seqCount;
580
13.3k
                    blockBudgetSupp = 0;
581
13.3k
            }   }
582
            /* otherwise : do not compress yet, coalesce current sub-block with following one */
583
19.9k
        }
584
1.13M
    } /* if (nbSeqs > 0) */
585
586
    /* write last block */
587
1.25M
    DEBUGLOG(5, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
588
1.25M
    {   int litEntropyWritten = 0;
589
1.25M
        int seqEntropyWritten = 0;
590
1.25M
        size_t litSize = (size_t)(lend - lp);
591
1.25M
        size_t seqCount = (size_t)(send - sp);
592
1.25M
        const size_t decompressedSize =
593
1.25M
                ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);
594
1.25M
        size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
595
1.25M
                                            sp, seqCount,
596
1.25M
                                            lp, litSize,
597
1.25M
                                            llCodePtr, mlCodePtr, ofCodePtr,
598
1.25M
                                            cctxParams,
599
1.25M
                                            op, (size_t)(oend-op),
600
1.25M
                                            bmi2, writeLitEntropy, writeSeqEntropy,
601
1.25M
                                            &litEntropyWritten, &seqEntropyWritten,
602
1.25M
                                            lastBlock);
603
1.25M
        FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
604
605
        /* update pointers, the nb of literals borrowed from next sequence must be preserved */
606
1.25M
        if (cSize > 0 && cSize < decompressedSize) {
607
1.13M
            DEBUGLOG(5, "Last sub-block compressed %u bytes => %u bytes",
608
1.13M
                        (unsigned)decompressedSize, (unsigned)cSize);
609
1.13M
            assert(ip + decompressedSize <= iend);
610
1.13M
            ip += decompressedSize;
611
1.13M
            lp += litSize;
612
1.13M
            op += cSize;
613
1.13M
            llCodePtr += seqCount;
614
1.13M
            mlCodePtr += seqCount;
615
1.13M
            ofCodePtr += seqCount;
616
            /* Entropy only needs to be written once */
617
1.13M
            if (litEntropyWritten) {
618
510k
                writeLitEntropy = 0;
619
510k
            }
620
1.13M
            if (seqEntropyWritten) {
621
1.11M
                writeSeqEntropy = 0;
622
1.11M
            }
623
1.13M
            sp += seqCount;
624
1.13M
        }
625
1.25M
    }
626
627
628
1.25M
    if (writeLitEntropy) {
629
3.19k
        DEBUGLOG(5, "Literal entropy tables were never written");
630
3.19k
        ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
631
3.19k
    }
632
1.25M
    if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {
633
        /* If we haven't written our entropy tables, then we've violated our contract and
634
         * must emit an uncompressed block.
635
         */
636
1.80k
        DEBUGLOG(5, "Sequence entropy tables were never written => cancel, emit an uncompressed block");
637
1.80k
        return 0;
638
1.80k
    }
639
640
1.25M
    if (ip < iend) {
641
        /* some data left : last part of the block sent uncompressed */
642
123k
        size_t const rSize = (size_t)((iend - ip));
643
123k
        size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);
644
123k
        DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
645
123k
        FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
646
123k
        assert(cSize != 0);
647
123k
        op += cSize;
648
        /* We have to regenerate the repcodes because we've skipped some sequences */
649
123k
        if (sp < send) {
650
20.0k
            const SeqDef* seq;
651
20.0k
            Repcodes_t rep;
652
20.0k
            ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
653
65.1k
            for (seq = sstart; seq < sp; ++seq) {
654
45.0k
                ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
655
45.0k
            }
656
20.0k
            ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
657
20.0k
        }
658
123k
    }
659
660
1.25M
    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed all subBlocks: total compressed size = %u",
661
1.25M
                (unsigned)(op-ostart));
662
1.25M
    return (size_t)(op-ostart);
663
1.25M
}
664
665
size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
666
                               void* dst, size_t dstCapacity,
667
                               const void* src, size_t srcSize,
668
                               unsigned lastBlock)
669
1.27M
{
670
1.27M
    ZSTD_entropyCTablesMetadata_t entropyMetadata;
671
672
1.27M
    FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,
673
1.27M
          &zc->blockState.prevCBlock->entropy,
674
1.27M
          &zc->blockState.nextCBlock->entropy,
675
1.27M
          &zc->appliedParams,
676
1.27M
          &entropyMetadata,
677
1.27M
          zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */), "");
678
679
1.27M
    return ZSTD_compressSubBlock_multi(&zc->seqStore,
680
1.27M
            zc->blockState.prevCBlock,
681
1.27M
            zc->blockState.nextCBlock,
682
1.27M
            &entropyMetadata,
683
1.27M
            &zc->appliedParams,
684
1.27M
            dst, dstCapacity,
685
1.27M
            src, srcSize,
686
1.27M
            zc->bmi2, lastBlock,
687
1.27M
            zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */);
688
1.27M
}