Coverage Report

Created: 2026-10-28 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/common/fse_decompress.c
Line
Count
Source
1
/* ******************************************************************
2
 * FSE : Finite State Entropy decoder
3
 * Copyright (c) Meta Platforms, Inc. and affiliates.
4
 *
5
 *  You can contact the author at :
6
 *  - FSE 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
/* **************************************************************
17
*  Includes
18
****************************************************************/
19
#include "debug.h"      /* assert */
20
#include "bitstream.h"
21
#include "bmi2.h"
22
#include "compiler.h"
23
#define FSE_STATIC_LINKING_ONLY
24
#include "fse.h"
25
#include "error_private.h"
26
#include "zstd_deps.h"  /* ZSTD_memcpy */
27
#include "bits.h"       /* ZSTD_highbit32 */
28
29
30
/* **************************************************************
31
*  Error Management
32
****************************************************************/
33
10.3k
#define FSE_isError ERR_isError
34
20.6k
#define FSE_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)   /* use only *after* variable declarations */
35
36
37
/* **************************************************************
38
*  Templates
39
****************************************************************/
40
/*
41
  designed to be included
42
  for type-specific functions (template emulation in C)
43
  Objective is to write these functions only once, for improved maintenance
44
*/
45
46
/* safety checks */
47
#ifndef FSE_FUNCTION_EXTENSION
48
#  error "FSE_FUNCTION_EXTENSION must be defined"
49
#endif
50
#ifndef FSE_FUNCTION_TYPE
51
#  error "FSE_FUNCTION_TYPE must be defined"
52
#endif
53
54
/* Function names */
55
#define FSE_CAT(X,Y) X##Y
56
#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
57
#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
58
59
static size_t FSE_buildDTable_internal(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
60
10.1k
{
61
10.1k
    void* const tdPtr = dt+1;   /* because *dt is unsigned, 32-bits aligned on 32-bits */
62
10.1k
    FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr);
63
10.1k
    U16* symbolNext = (U16*)workSpace;
64
10.1k
    BYTE* spread = (BYTE*)(symbolNext + maxSymbolValue + 1);
65
66
10.1k
    U32 const maxSV1 = maxSymbolValue + 1;
67
10.1k
    U32 const tableSize = 1 << tableLog;
68
10.1k
    U32 highThreshold = tableSize-1;
69
70
    /* Sanity Checks */
71
10.1k
    if (FSE_BUILD_DTABLE_WKSP_SIZE(tableLog, maxSymbolValue) > wkspSize) return ERROR(maxSymbolValue_tooLarge);
72
10.1k
    if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
73
10.1k
    if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
74
75
    /* Init, lay down lowprob symbols */
76
10.1k
    {   FSE_DTableHeader DTableH;
77
10.1k
        DTableH.tableLog = (U16)tableLog;
78
10.1k
        DTableH.fastMode = 1;
79
10.1k
        {   S16 const largeLimit= (S16)(1 << (tableLog-1));
80
10.1k
            U32 s;
81
50.9k
            for (s=0; s<maxSV1; s++) {
82
40.7k
                if (normalizedCounter[s]==-1) {
83
7.80k
                    tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
84
7.80k
                    symbolNext[s] = 1;
85
32.9k
                } else {
86
32.9k
                    if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
87
32.9k
                    symbolNext[s] = (U16)normalizedCounter[s];
88
32.9k
        }   }   }
89
10.1k
        ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
90
10.1k
    }
91
92
    /* Spread symbols */
93
10.1k
    if (highThreshold == tableSize - 1) {
94
7.62k
        size_t const tableMask = tableSize-1;
95
7.62k
        size_t const step = FSE_TABLESTEP(tableSize);
96
        /* First lay down the symbols in order.
97
         * We use a uint64_t to lay down 8 bytes at a time. This reduces branch
98
         * misses since small blocks generally have small table logs, so nearly
99
         * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
100
         * our buffer to handle the over-write.
101
         */
102
7.62k
        {   U64 const add = 0x0101010101010101ull;
103
7.62k
            size_t pos = 0;
104
7.62k
            U64 sv = 0;
105
7.62k
            U32 s;
106
29.0k
            for (s=0; s<maxSV1; ++s, sv += add) {
107
21.4k
                int i;
108
21.4k
                int const n = normalizedCounter[s];
109
21.4k
                MEM_write64(spread + pos, sv);
110
41.4k
                for (i = 8; i < n; i += 8) {
111
19.9k
                    MEM_write64(spread + pos + i, sv);
112
19.9k
                }
113
21.4k
                pos += (size_t)n;
114
21.4k
        }   }
115
        /* Now we spread those positions across the table.
116
         * The benefit of doing it in two stages is that we avoid the
117
         * variable size inner loop, which caused lots of branch misses.
118
         * Now we can run through all the positions without any branch misses.
119
         * We unroll the loop twice, since that is what empirically worked best.
120
         */
121
7.62k
        {
122
7.62k
            size_t position = 0;
123
7.62k
            size_t s;
124
7.62k
            size_t const unroll = 2;
125
7.62k
            assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
126
142k
            for (s = 0; s < (size_t)tableSize; s += unroll) {
127
134k
                size_t u;
128
404k
                for (u = 0; u < unroll; ++u) {
129
269k
                    size_t const uPosition = (position + (u * step)) & tableMask;
130
269k
                    tableDecode[uPosition].symbol = spread[s + u];
131
269k
                }
132
134k
                position = (position + (unroll * step)) & tableMask;
133
134k
            }
134
7.62k
            assert(position == 0);
135
7.62k
        }
136
7.62k
    } else {
137
2.53k
        U32 const tableMask = tableSize-1;
138
2.53k
        U32 const step = FSE_TABLESTEP(tableSize);
139
2.53k
        U32 s, position = 0;
140
21.8k
        for (s=0; s<maxSV1; s++) {
141
19.3k
            int i;
142
96.8k
            for (i=0; i<normalizedCounter[s]; i++) {
143
77.4k
                tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
144
77.4k
                position = (position + step) & tableMask;
145
85.1k
                while (position > highThreshold) position = (position + step) & tableMask;   /* lowprob area */
146
77.4k
        }   }
147
2.53k
        if (position!=0) return ERROR(GENERIC);   /* position must reach all cells once, otherwise normalizedCounter is incorrect */
148
2.53k
    }
149
150
    /* Build Decoding table */
151
10.1k
    {   U32 u;
152
365k
        for (u=0; u<tableSize; u++) {
153
354k
            FSE_FUNCTION_TYPE const symbol = (FSE_FUNCTION_TYPE)(tableDecode[u].symbol);
154
354k
            U32 const nextState = symbolNext[symbol]++;
155
354k
            tableDecode[u].nbBits = (BYTE) (tableLog - ZSTD_highbit32(nextState) );
156
354k
            tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
157
354k
    }   }
158
159
10.1k
    return 0;
160
10.1k
}
161
162
size_t FSE_buildDTable_wksp(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
163
0
{
164
0
    return FSE_buildDTable_internal(dt, normalizedCounter, maxSymbolValue, tableLog, workSpace, wkspSize);
165
0
}
166
167
168
#ifndef FSE_COMMONDEFS_ONLY
169
170
/*-*******************************************************
171
*  Decompression (Byte symbols)
172
*********************************************************/
173
174
FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
175
          void* dst, size_t maxDstSize,
176
    const void* cSrc, size_t cSrcSize,
177
    const FSE_DTable* dt, const unsigned fast)
178
10.1k
{
179
10.1k
    BYTE* const ostart = (BYTE*) dst;
180
10.1k
    BYTE* op = ostart;
181
10.1k
    BYTE* const omax = op + maxDstSize;
182
10.1k
    BYTE* const olimit = omax-3;
183
184
10.1k
    BIT_DStream_t bitD;
185
10.1k
    FSE_DState_t state1;
186
10.1k
    FSE_DState_t state2;
187
188
    /* Init */
189
10.1k
    CHECK_F(BIT_initDStream(&bitD, cSrc, cSrcSize));
190
191
9.99k
    FSE_initDState(&state1, &bitD, dt);
192
9.99k
    FSE_initDState(&state2, &bitD, dt);
193
194
9.99k
    RETURN_ERROR_IF(BIT_reloadDStream(&bitD)==BIT_DStream_overflow, corruption_detected, "");
195
196
677k
#define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
197
198
    /* 4 symbols per loop */
199
77.9k
    for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) & (op<olimit) ; op+=4) {
200
67.9k
        op[0] = FSE_GETSYMBOL(&state1);
201
202
67.9k
        if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
203
0
            BIT_reloadDStream(&bitD);
204
205
67.9k
        op[1] = FSE_GETSYMBOL(&state2);
206
207
67.9k
        if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
208
0
            { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
209
210
67.9k
        op[2] = FSE_GETSYMBOL(&state1);
211
212
67.9k
        if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
213
0
            BIT_reloadDStream(&bitD);
214
215
67.9k
        op[3] = FSE_GETSYMBOL(&state2);
216
67.9k
    }
217
218
    /* tail */
219
    /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
220
199k
    while (1) {
221
199k
        if (op>(omax-2)) return ERROR(dstSize_tooSmall);
222
199k
        *op++ = FSE_GETSYMBOL(&state1);
223
199k
        if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
224
3.42k
            *op++ = FSE_GETSYMBOL(&state2);
225
3.42k
            break;
226
3.42k
        }
227
228
196k
        if (op>(omax-2)) return ERROR(dstSize_tooSmall);
229
196k
        *op++ = FSE_GETSYMBOL(&state2);
230
196k
        if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
231
6.45k
            *op++ = FSE_GETSYMBOL(&state1);
232
6.45k
            break;
233
6.45k
    }   }
234
235
9.87k
    assert(op >= ostart);
236
9.87k
    return (size_t)(op-ostart);
237
9.93k
}
238
239
typedef struct {
240
    short ncount[FSE_MAX_SYMBOL_VALUE + 1];
241
} FSE_DecompressWksp;
242
243
244
FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body(
245
        void* dst, size_t dstCapacity,
246
        const void* cSrc, size_t cSrcSize,
247
        unsigned maxLog, void* workSpace, size_t wkspSize,
248
        int bmi2)
249
10.3k
{
250
10.3k
    const BYTE* const istart = (const BYTE*)cSrc;
251
10.3k
    const BYTE* ip = istart;
252
10.3k
    unsigned tableLog;
253
10.3k
    unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
254
10.3k
    FSE_DecompressWksp* const wksp = (FSE_DecompressWksp*)workSpace;
255
10.3k
    size_t const dtablePos = sizeof(FSE_DecompressWksp) / sizeof(FSE_DTable);
256
10.3k
    FSE_DTable* const dtable = (FSE_DTable*)workSpace + dtablePos;
257
258
10.3k
    FSE_STATIC_ASSERT((FSE_MAX_SYMBOL_VALUE + 1) % 2 == 0);
259
10.3k
    if (wkspSize < sizeof(*wksp)) return ERROR(GENERIC);
260
261
    /* correct offset to dtable depends on this property */
262
10.3k
    FSE_STATIC_ASSERT(sizeof(FSE_DecompressWksp) % sizeof(FSE_DTable) == 0);
263
264
    /* normal FSE decoding mode */
265
10.3k
    {   size_t const NCountLength =
266
10.3k
            FSE_readNCount_bmi2(wksp->ncount, &maxSymbolValue, &tableLog, istart, cSrcSize, bmi2);
267
10.3k
        if (FSE_isError(NCountLength)) return NCountLength;
268
10.2k
        if (tableLog > maxLog) return ERROR(tableLog_tooLarge);
269
10.1k
        assert(NCountLength <= cSrcSize);
270
10.1k
        ip += NCountLength;
271
10.1k
        cSrcSize -= NCountLength;
272
10.1k
    }
273
274
10.1k
    if (FSE_DECOMPRESS_WKSP_SIZE(tableLog, maxSymbolValue) > wkspSize) return ERROR(tableLog_tooLarge);
275
10.1k
    assert(sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog) <= wkspSize);
276
10.1k
    workSpace = (BYTE*)workSpace + sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog);
277
10.1k
    wkspSize -= sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog);
278
279
10.1k
    CHECK_F( FSE_buildDTable_internal(dtable, wksp->ncount, maxSymbolValue, tableLog, workSpace, wkspSize) );
280
281
10.1k
    {
282
10.1k
        const void* ptr = dtable;
283
10.1k
        const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr;
284
10.1k
        const U32 fastMode = DTableH->fastMode;
285
286
        /* select fast mode (static) */
287
10.1k
        if (fastMode) return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 1);
288
8.68k
        return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 0);
289
10.1k
    }
290
10.1k
}
291
292
/* Avoids the FORCE_INLINE of the _body() function. */
293
static size_t FSE_decompress_wksp_body_default(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize)
294
0
{
295
0
    return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 0);
296
0
}
297
298
#if DYNAMIC_BMI2
299
BMI2_TARGET_ATTRIBUTE static size_t FSE_decompress_wksp_body_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize)
300
10.3k
{
301
10.3k
    return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 1);
302
10.3k
}
303
#else
304
#define FSE_decompress_wksp_body_bmi2 FSE_decompress_wksp_body_default
305
#endif
306
307
size_t FSE_decompress_wksp_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize, int bmi2)
308
10.3k
{
309
10.3k
    if (ZSTD_USE_BMI2(bmi2)) {
310
10.3k
        return FSE_decompress_wksp_body_bmi2(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize);
311
10.3k
    }
312
0
    (void)bmi2;
313
0
    return FSE_decompress_wksp_body_default(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize);
314
10.3k
}
315
316
#endif   /* FSE_COMMONDEFS_ONLY */