Coverage Report

Created: 2024-09-08 06:32

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