Coverage Report

Created: 2025-11-16 07:22

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