Coverage Report

Created: 2026-10-28 07:26

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.24k
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
1.79k
{
46
1.79k
    const BYTE* const istart = (const BYTE*) headerBuffer;
47
1.79k
    const BYTE* const iend = istart + hbSize;
48
1.79k
    const BYTE* ip = istart;
49
1.79k
    int nbBits;
50
1.79k
    int remaining;
51
1.79k
    int threshold;
52
1.79k
    U32 bitStream;
53
1.79k
    int bitCount;
54
1.79k
    unsigned charnum = 0;
55
1.79k
    unsigned const maxSV1 = *maxSVPtr + 1;
56
1.79k
    int previous0 = 0;
57
58
1.79k
    if (hbSize < 8) {
59
        /* This function only works when hbSize >= 8 */
60
68
        char buffer[8] = {0};
61
68
        ZSTD_memcpy(buffer, headerBuffer, hbSize);
62
68
        {   size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
63
68
                                                    buffer, sizeof(buffer));
64
68
            if (FSE_isError(countSize)) return countSize;
65
47
            if (countSize > hbSize) return ERROR(corruption_detected);
66
32
            return countSize;
67
47
    }   }
68
1.73k
    assert(hbSize >= 8);
69
70
    /* init */
71
1.73k
    ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0]));   /* all symbols not present in NCount have a frequency of 0 */
72
1.73k
    bitStream = MEM_readLE32(ip);
73
1.73k
    nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG;   /* extract tableLog */
74
1.73k
    if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
75
1.72k
    bitStream >>= 4;
76
1.72k
    bitCount = 4;
77
1.72k
    *tableLogPtr = nbBits;
78
1.72k
    remaining = (1<<nbBits)+1;
79
1.72k
    threshold = 1<<nbBits;
80
1.72k
    nbBits++;
81
82
25.2k
    for (;;) {
83
25.2k
        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
3.94k
            int repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;
90
4.52k
            while (repeats >= 12) {
91
583
                charnum += 3 * 12;
92
583
                if (LIKELY(ip <= iend-7)) {
93
534
                    ip += 3;
94
534
                } else {
95
49
                    bitCount -= (int)(8 * (iend - 7 - ip));
96
49
                    bitCount &= 31;
97
49
                    ip = iend - 4;
98
49
                }
99
583
                bitStream = MEM_readLE32(ip) >> bitCount;
100
583
                repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;
101
583
            }
102
3.94k
            charnum += 3 * repeats;
103
3.94k
            bitStream >>= 2 * repeats;
104
3.94k
            bitCount += 2 * repeats;
105
106
            /* Add the final repeat which isn't 0b11. */
107
3.94k
            assert((bitStream & 3) < 3);
108
3.94k
            charnum += bitStream & 3;
109
3.94k
            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
3.94k
            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
3.88k
            if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
122
2.49k
                assert((bitCount >> 3) <= 3); /* For first condition to work */
123
2.49k
                ip += bitCount>>3;
124
2.49k
                bitCount &= 7;
125
2.49k
            } else {
126
1.39k
                bitCount -= (int)(8 * (iend - 4 - ip));
127
1.39k
                bitCount &= 31;
128
1.39k
                ip = iend - 4;
129
1.39k
            }
130
3.88k
            bitStream = MEM_readLE32(ip) >> bitCount;
131
3.88k
        }
132
25.1k
        {
133
25.1k
            int const max = (2*threshold-1) - remaining;
134
25.1k
            int count;
135
136
25.1k
            if ((bitStream & (threshold-1)) < (U32)max) {
137
18.4k
                count = bitStream & (threshold-1);
138
18.4k
                bitCount += nbBits-1;
139
18.4k
            } else {
140
6.75k
                count = bitStream & (2*threshold-1);
141
6.75k
                if (count >= threshold) count -= max;
142
6.75k
                bitCount += nbBits;
143
6.75k
            }
144
145
25.1k
            count--;   /* extra accuracy */
146
            /* When it matters (small blocks), this is a
147
             * predictable branch, because we don't use -1.
148
             */
149
25.1k
            if (count >= 0) {
150
11.0k
                remaining -= count;
151
14.1k
            } else {
152
14.1k
                assert(count == -1);
153
14.1k
                remaining += count;
154
14.1k
            }
155
25.1k
            normalizedCounter[charnum++] = (short)count;
156
25.1k
            previous0 = !count;
157
158
25.1k
            assert(threshold > 1);
159
25.1k
            if (remaining < threshold) {
160
                /* This branch can be folded into the
161
                 * threshold update condition because we
162
                 * know that threshold > 1.
163
                 */
164
7.28k
                if (remaining <= 1) break;
165
5.66k
                nbBits = ZSTD_highbit32(remaining) + 1;
166
5.66k
                threshold = 1 << (nbBits - 1);
167
5.66k
            }
168
23.5k
            if (charnum >= maxSV1) break;
169
170
23.5k
            if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
171
15.6k
                ip += bitCount>>3;
172
15.6k
                bitCount &= 7;
173
15.6k
            } else {
174
7.81k
                bitCount -= (int)(8 * (iend - 4 - ip));
175
7.81k
                bitCount &= 31;
176
7.81k
                ip = iend - 4;
177
7.81k
            }
178
23.5k
            bitStream = MEM_readLE32(ip) >> bitCount;
179
23.5k
    }   }
180
1.72k
    if (remaining != 1) return ERROR(corruption_detected);
181
    /* Only possible when there are too many zeros. */
182
1.62k
    if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
183
1.62k
    if (bitCount > 32) return ERROR(corruption_detected);
184
1.62k
    *maxSVPtr = charnum-1;
185
186
1.62k
    ip += (bitCount+7)>>3;
187
1.62k
    return ip-istart;
188
1.62k
}
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
619
{
195
619
    return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
196
619
}
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
1.18k
{
203
1.18k
    return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
204
1.18k
}
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
1.79k
{
213
1.79k
    if (ZSTD_USE_BMI2(bmi2)) {
214
1.18k
        return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
215
1.18k
    }
216
619
    (void)bmi2;
217
619
    return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
218
1.79k
}
219
220
size_t FSE_readNCount(
221
        short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
222
        const void* headerBuffer, size_t hbSize)
223
619
{
224
619
    return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
225
619
}
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
0
{
239
0
    U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
240
0
    return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* flags */ 0);
241
0
}
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.22k
{
250
1.22k
    U32 weightTotal;
251
1.22k
    const BYTE* ip = (const BYTE*) src;
252
1.22k
    size_t iSize;
253
1.22k
    size_t oSize;
254
255
1.22k
    if (!srcSize) return ERROR(srcSize_wrong);
256
1.21k
    iSize = ip[0];
257
    /* ZSTD_memset(huffWeight, 0, hwSize);   *//* is not necessary, even though some analyzer complain ... */
258
259
1.21k
    if (iSize >= 128) {  /* special header */
260
34
        oSize = iSize - 127;
261
34
        iSize = ((oSize+1)/2);
262
34
        if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
263
31
        if (oSize >= hwSize) return ERROR(corruption_detected);
264
31
        ip += 1;
265
31
        {   U32 n;
266
460
            for (n=0; n<oSize; n+=2) {
267
429
                huffWeight[n]   = ip[n/2] >> 4;
268
429
                huffWeight[n+1] = ip[n/2] & 15;
269
429
    }   }   }
270
1.18k
    else  {   /* header compressed with FSE (normal case) */
271
1.18k
        if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
272
        /* max (hwSize-1) values decoded, as last one is implied */
273
1.18k
        oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
274
1.18k
        if (FSE_isError(oSize)) return oSize;
275
1.18k
    }
276
277
    /* collect weight stats */
278
1.04k
    ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
279
1.04k
    weightTotal = 0;
280
152k
    {   U32 n; for (n=0; n<oSize; n++) {
281
151k
            if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
282
151k
            rankStats[huffWeight[n]]++;
283
151k
            weightTotal += (1 << huffWeight[n]) >> 1;
284
151k
    }   }
285
996
    if (weightTotal == 0) return ERROR(corruption_detected);
286
287
    /* get last non-null symbol weight (implied, total must be 2^n) */
288
991
    {   U32 const tableLog = ZSTD_highbit32(weightTotal) + 1;
289
991
        if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
290
986
        *tableLogPtr = tableLog;
291
        /* determine last weight */
292
986
        {   U32 const total = 1 << tableLog;
293
986
            U32 const rest = total - weightTotal;
294
986
            U32 const verif = 1 << ZSTD_highbit32(rest);
295
986
            U32 const lastWeight = ZSTD_highbit32(rest) + 1;
296
986
            if (verif != rest) return ERROR(corruption_detected);    /* last value must be a clean power of 2 */
297
944
            huffWeight[oSize] = (BYTE)lastWeight;
298
944
            rankStats[lastWeight]++;
299
944
    }   }
300
301
    /* check tree construction validity */
302
944
    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
940
    *nbSymbolsPtr = (U32)(oSize+1);
306
940
    return iSize+1;
307
944
}
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
0
{
315
0
    return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
316
0
}
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
1.22k
{
324
1.22k
    return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
325
1.22k
}
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.22k
{
336
1.22k
    if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) {
337
1.22k
        return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
338
1.22k
    }
339
0
    (void)flags;
340
0
    return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
341
1.22k
}