Coverage Report

Created: 2026-10-17 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/common/entropy_common.c
Line
Count
Source
1
/* ******************************************************************
2
 * Common functions of New Generation Entropy library
3
 * Copyright (c) Meta Platforms, Inc. and affiliates.
4
 *
5
 *  You can contact the author at :
6
 *  - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
7
 *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
8
 *
9
 * This source code is licensed under both the BSD-style license (found in the
10
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11
 * in the COPYING file in the root directory of this source tree).
12
 * You may select, at your option, one of the above-listed licenses.
13
****************************************************************** */
14
15
/* *************************************
16
*  Dependencies
17
***************************************/
18
#include "bmi2.h"
19
#include "mem.h"
20
#include "error_private.h"       /* ERR_*, ERROR */
21
#define FSE_STATIC_LINKING_ONLY  /* FSE_MIN_TABLELOG */
22
#include "fse.h"
23
#include "huf.h"
24
#include "bits.h"                /* ZSDT_highbit32, ZSTD_countTrailingZeros32 */
25
26
27
/*===   Version   ===*/
28
0
unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
29
30
31
/*===   Error Management   ===*/
32
1.09M
unsigned FSE_isError(size_t code) { return ERR_isError(code); }
33
0
const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
34
35
0
unsigned HUF_isError(size_t code) { return ERR_isError(code); }
36
0
const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
37
38
39
/*-**************************************************************
40
*  FSE NCount encoding-decoding
41
****************************************************************/
42
FORCE_INLINE_TEMPLATE
43
size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
44
                           const void* headerBuffer, size_t hbSize)
45
3.30M
{
46
3.30M
    const BYTE* const istart = (const BYTE*) headerBuffer;
47
3.30M
    const BYTE* const iend = istart + hbSize;
48
3.30M
    const BYTE* ip = istart;
49
3.30M
    int nbBits;
50
3.30M
    int remaining;
51
3.30M
    int threshold;
52
3.30M
    U32 bitStream;
53
3.30M
    int bitCount;
54
3.30M
    unsigned charnum = 0;
55
3.30M
    unsigned const maxSV1 = *maxSVPtr + 1;
56
3.30M
    int previous0 = 0;
57
58
3.30M
    if (hbSize < 8) {
59
        /* This function only works when hbSize >= 8 */
60
59.9k
        char buffer[8] = {0};
61
59.9k
        ZSTD_memcpy(buffer, headerBuffer, hbSize);
62
59.9k
        {   size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
63
59.9k
                                                    buffer, sizeof(buffer));
64
59.9k
            if (FSE_isError(countSize)) return countSize;
65
59.7k
            if (countSize > hbSize) return ERROR(corruption_detected);
66
59.3k
            return countSize;
67
59.7k
    }   }
68
3.30M
    assert(hbSize >= 8);
69
70
    /* init */
71
3.24M
    ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0]));   /* all symbols not present in NCount have a frequency of 0 */
72
3.24M
    bitStream = MEM_readLE32(ip);
73
3.24M
    nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG;   /* extract tableLog */
74
3.24M
    if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
75
3.24M
    bitStream >>= 4;
76
3.24M
    bitCount = 4;
77
3.24M
    *tableLogPtr = nbBits;
78
3.24M
    remaining = (1<<nbBits)+1;
79
3.24M
    threshold = 1<<nbBits;
80
3.24M
    nbBits++;
81
82
42.1M
    for (;;) {
83
42.1M
        if (previous0) {
84
            /* Count the number of repeats. Each time the
85
             * 2-bit repeat code is 0b11 there is another
86
             * repeat.
87
             * Avoid UB by setting the high bit to 1.
88
             */
89
4.94M
            int repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;
90
4.96M
            while (repeats >= 12) {
91
16.4k
                charnum += 3 * 12;
92
16.4k
                if (LIKELY(ip <= iend-7)) {
93
15.5k
                    ip += 3;
94
15.5k
                } else {
95
853
                    bitCount -= (int)(8 * (iend - 7 - ip));
96
853
                    bitCount &= 31;
97
853
                    ip = iend - 4;
98
853
                }
99
16.4k
                bitStream = MEM_readLE32(ip) >> bitCount;
100
16.4k
                repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;
101
16.4k
            }
102
4.94M
            charnum += 3 * repeats;
103
4.94M
            bitStream >>= 2 * repeats;
104
4.94M
            bitCount += 2 * repeats;
105
106
            /* Add the final repeat which isn't 0b11. */
107
4.94M
            assert((bitStream & 3) < 3);
108
4.94M
            charnum += bitStream & 3;
109
4.94M
            bitCount += 2;
110
111
            /* This is an error, but break and return an error
112
             * at the end, because returning out of a loop makes
113
             * it harder for the compiler to optimize.
114
             */
115
4.94M
            if (charnum >= maxSV1) break;
116
117
            /* We don't need to set the normalized count to 0
118
             * because we already memset the whole buffer to 0.
119
             */
120
121
4.94M
            if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
122
4.93M
                assert((bitCount >> 3) <= 3); /* For first condition to work */
123
4.93M
                ip += bitCount>>3;
124
4.93M
                bitCount &= 7;
125
4.93M
            } else {
126
12.6k
                bitCount -= (int)(8 * (iend - 4 - ip));
127
12.6k
                bitCount &= 31;
128
12.6k
                ip = iend - 4;
129
12.6k
            }
130
4.94M
            bitStream = MEM_readLE32(ip) >> bitCount;
131
4.94M
        }
132
42.1M
        {
133
42.1M
            int const max = (2*threshold-1) - remaining;
134
42.1M
            int count;
135
136
42.1M
            if ((bitStream & (threshold-1)) < (U32)max) {
137
24.8M
                count = bitStream & (threshold-1);
138
24.8M
                bitCount += nbBits-1;
139
24.8M
            } else {
140
17.3M
                count = bitStream & (2*threshold-1);
141
17.3M
                if (count >= threshold) count -= max;
142
17.3M
                bitCount += nbBits;
143
17.3M
            }
144
145
42.1M
            count--;   /* extra accuracy */
146
            /* When it matters (small blocks), this is a
147
             * predictable branch, because we don't use -1.
148
             */
149
42.1M
            if (count >= 0) {
150
41.3M
                remaining -= count;
151
41.3M
            } else {
152
801k
                assert(count == -1);
153
801k
                remaining += count;
154
801k
            }
155
42.1M
            normalizedCounter[charnum++] = (short)count;
156
42.1M
            previous0 = !count;
157
158
42.1M
            assert(threshold > 1);
159
42.1M
            if (remaining < threshold) {
160
                /* This branch can be folded into the
161
                 * threshold update condition because we
162
                 * know that threshold > 1.
163
                 */
164
14.7M
                if (remaining <= 1) break;
165
11.4M
                nbBits = ZSTD_highbit32(remaining) + 1;
166
11.4M
                threshold = 1 << (nbBits - 1);
167
11.4M
            }
168
38.8M
            if (charnum >= maxSV1) break;
169
170
38.8M
            if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
171
38.8M
                ip += bitCount>>3;
172
38.8M
                bitCount &= 7;
173
38.8M
            } else {
174
66.0k
                bitCount -= (int)(8 * (iend - 4 - ip));
175
66.0k
                bitCount &= 31;
176
66.0k
                ip = iend - 4;
177
66.0k
            }
178
38.8M
            bitStream = MEM_readLE32(ip) >> bitCount;
179
38.8M
    }   }
180
3.24M
    if (remaining != 1) return ERROR(corruption_detected);
181
    /* Only possible when there are too many zeros. */
182
3.23M
    if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
183
3.23M
    if (bitCount > 32) return ERROR(corruption_detected);
184
3.23M
    *maxSVPtr = charnum-1;
185
186
3.23M
    ip += (bitCount+7)>>3;
187
3.23M
    return ip-istart;
188
3.23M
}
189
190
/* Avoids the FORCE_INLINE of the _body() function. */
191
static size_t FSE_readNCount_body_default(
192
        short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
193
        const void* headerBuffer, size_t hbSize)
194
2.39M
{
195
2.39M
    return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
196
2.39M
}
197
198
#if DYNAMIC_BMI2
199
BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(
200
        short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
201
        const void* headerBuffer, size_t hbSize)
202
906k
{
203
906k
    return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
204
906k
}
205
#else
206
#define FSE_readNCount_body_bmi2 FSE_readNCount_body_default
207
#endif
208
209
size_t FSE_readNCount_bmi2(
210
        short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
211
        const void* headerBuffer, size_t hbSize, int bmi2)
212
3.30M
{
213
3.30M
    if (ZSTD_USE_BMI2(bmi2)) {
214
906k
        return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
215
906k
    }
216
2.39M
    (void)bmi2;
217
2.39M
    return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
218
3.30M
}
219
220
size_t FSE_readNCount(
221
        short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
222
        const void* headerBuffer, size_t hbSize)
223
2.26M
{
224
2.26M
    return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
225
2.26M
}
226
227
228
/*! HUF_readStats() :
229
    Read compact Huffman tree, saved by HUF_writeCTable().
230
    `huffWeight` is destination buffer.
231
    `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
232
    @return : size read from `src` , or an error Code .
233
    Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
234
*/
235
size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
236
                     U32* nbSymbolsPtr, U32* tableLogPtr,
237
                     const void* src, size_t srcSize)
238
62.0k
{
239
62.0k
    U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
240
62.0k
    return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* flags */ 0);
241
62.0k
}
242
243
FORCE_INLINE_TEMPLATE size_t
244
HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
245
                   U32* nbSymbolsPtr, U32* tableLogPtr,
246
                   const void* src, size_t srcSize,
247
                   void* workSpace, size_t wkspSize,
248
                   int bmi2)
249
1.05M
{
250
1.05M
    U32 weightTotal;
251
1.05M
    const BYTE* ip = (const BYTE*) src;
252
1.05M
    size_t iSize;
253
1.05M
    size_t oSize;
254
255
1.05M
    if (!srcSize) return ERROR(srcSize_wrong);
256
1.05M
    iSize = ip[0];
257
    /* ZSTD_memset(huffWeight, 0, hwSize);   *//* is not necessary, even though some analyzer complain ... */
258
259
1.05M
    if (iSize >= 128) {  /* special header */
260
15.4k
        oSize = iSize - 127;
261
15.4k
        iSize = ((oSize+1)/2);
262
15.4k
        if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
263
15.4k
        if (oSize >= hwSize) return ERROR(corruption_detected);
264
15.4k
        ip += 1;
265
15.4k
        {   U32 n;
266
90.1k
            for (n=0; n<oSize; n+=2) {
267
74.7k
                huffWeight[n]   = ip[n/2] >> 4;
268
74.7k
                huffWeight[n+1] = ip[n/2] & 15;
269
74.7k
    }   }   }
270
1.03M
    else  {   /* header compressed with FSE (normal case) */
271
1.03M
        if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
272
        /* max (hwSize-1) values decoded, as last one is implied */
273
1.03M
        oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
274
1.03M
        if (FSE_isError(oSize)) return oSize;
275
1.03M
    }
276
277
    /* collect weight stats */
278
1.05M
    ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
279
1.05M
    weightTotal = 0;
280
232M
    {   U32 n; for (n=0; n<oSize; n++) {
281
231M
            if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
282
231M
            rankStats[huffWeight[n]]++;
283
231M
            weightTotal += (1 << huffWeight[n]) >> 1;
284
231M
    }   }
285
1.05M
    if (weightTotal == 0) return ERROR(corruption_detected);
286
287
    /* get last non-null symbol weight (implied, total must be 2^n) */
288
1.05M
    {   U32 const tableLog = ZSTD_highbit32(weightTotal) + 1;
289
1.05M
        if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
290
1.05M
        *tableLogPtr = tableLog;
291
        /* determine last weight */
292
1.05M
        {   U32 const total = 1 << tableLog;
293
1.05M
            U32 const rest = total - weightTotal;
294
1.05M
            U32 const verif = 1 << ZSTD_highbit32(rest);
295
1.05M
            U32 const lastWeight = ZSTD_highbit32(rest) + 1;
296
1.05M
            if (verif != rest) return ERROR(corruption_detected);    /* last value must be a clean power of 2 */
297
1.05M
            huffWeight[oSize] = (BYTE)lastWeight;
298
1.05M
            rankStats[lastWeight]++;
299
1.05M
    }   }
300
301
    /* check tree construction validity */
302
1.05M
    if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected);   /* by construction : at least 2 elts of rank 1, must be even */
303
304
    /* results */
305
1.05M
    *nbSymbolsPtr = (U32)(oSize+1);
306
1.05M
    return iSize+1;
307
1.05M
}
308
309
/* Avoids the FORCE_INLINE of the _body() function. */
310
static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
311
                     U32* nbSymbolsPtr, U32* tableLogPtr,
312
                     const void* src, size_t srcSize,
313
                     void* workSpace, size_t wkspSize)
314
133k
{
315
133k
    return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
316
133k
}
317
318
#if DYNAMIC_BMI2
319
static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
320
                     U32* nbSymbolsPtr, U32* tableLogPtr,
321
                     const void* src, size_t srcSize,
322
                     void* workSpace, size_t wkspSize)
323
921k
{
324
921k
    return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
325
921k
}
326
#else
327
#define HUF_readStats_body_bmi2 HUF_readStats_body_default
328
#endif
329
330
size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
331
                     U32* nbSymbolsPtr, U32* tableLogPtr,
332
                     const void* src, size_t srcSize,
333
                     void* workSpace, size_t wkspSize,
334
                     int flags)
335
1.05M
{
336
1.05M
    if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) {
337
921k
        return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
338
921k
    }
339
133k
    (void)flags;
340
133k
    return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
341
1.05M
}