Coverage Report

Created: 2026-11-23 06:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zlib-ng/inftrees.c
Line
Count
Source
1
/* inftrees.c -- generate Huffman trees for efficient decoding
2
 * Copyright (C) 1995-2026 Mark Adler
3
 * For conditions of distribution and use, see copyright notice in zlib.h
4
 */
5
6
#include "zbuild.h"
7
#include "zmemory.h"
8
#include "zutil.h"
9
#include "inftrees.h"
10
#include "inflate_p.h"
11
#include "fallback_builtins.h"
12
13
#if defined(__SSE2__)
14
#  include "arch/x86/x86_intrins.h"
15
#elif defined(__ARM_NEON) || defined(__ARM_NEON__)
16
#  include "arch/arm/neon_intrins.h"
17
#elif defined(__ALTIVEC__)
18
#  include "arch/power/power_intrins.h"
19
#endif
20
21
Z_INTERNAL const char PREFIX(inflate_copyright)[] = " inflate 1.3.2 Copyright 1995-2026 Mark Adler ";
22
/*
23
  If you use the zlib library in a product, an acknowledgment is welcome
24
  in the documentation of your product. If for some reason you cannot
25
  include such an acknowledgment, I would appreciate that you keep this
26
  copyright string in the executable of your product.
27
 */
28
29
/* Share of the 2^MAX_BITS code space that must sit above MAX_LEN_ROOT_BITS-1 bits before the
30
   larger literal/length root table is worth building. */
31
10.7k
#define ROOT_GROW_MIN_SPACE ((1U << MAX_BITS) / 256)
32
33
/* Count number of codes for each code length. */
34
48.8k
static inline void count_lengths(uint16_t *lens, int codes, uint16_t *count) {
35
    /* IBM...made some weird choices for VSX/VMX. Basically vec_ld has an inherent
36
     * endianness but we don't want to force VSX to be needed */
37
48.8k
    static const ALIGNED_(16) uint8_t one[256] = {
38
48.8k
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
39
48.8k
        0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
40
48.8k
        0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
41
48.8k
        0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
42
48.8k
        0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
43
48.8k
        0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
44
48.8k
        0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
45
48.8k
        0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
46
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
47
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
48
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
49
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
50
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
51
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
52
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
53
48.8k
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
54
48.8k
    };
55
56
#if defined(__ALTIVEC__)
57
    vector unsigned char s1 = vec_splat_u8(0);
58
    vector unsigned char s2 = vec_splat_u8(0);
59
60
    if (codes & 1) {
61
        s1 = vec_ld(16 * lens[0], one);
62
        --codes;
63
        ++lens;
64
    }
65
66
    while (codes) {
67
        s1 = vec_add(s1, vec_ld(16 * lens[0], one));
68
        s2 = vec_add(s2, vec_ld(16 * lens[1], one));
69
        codes -= 2;
70
        lens += 2;
71
    }
72
73
    vector unsigned short sum_lo = vec_add(vec_unpackh(s1), vec_unpackh(s2));
74
    vector unsigned short sum_hi = vec_add(vec_unpackl(s1), vec_unpackl(s2));
75
76
    vec_st(sum_lo, 0, &count[0]);
77
    vec_st(sum_hi, 0, &count[8]);
78
79
#elif defined(__ARM_NEON) || defined(__ARM_NEON__)
80
    int sym;
81
    uint8x16_t s1 = vdupq_n_u8(0);
82
    uint8x16_t s2 = vdupq_n_u8(0);
83
84
    if (codes & 1) {
85
        s1 = vld1q_u8(&one[16 * lens[0]]);
86
    }
87
    for (sym = codes & 1; sym < codes; sym += 2) {
88
        s1 = vaddq_u8(s1, vld1q_u8(&one[16 * lens[sym]]));
89
        s2 = vaddq_u8(s2, vld1q_u8(&one[16 * lens[sym+1]]));
90
    }
91
92
    vst1q_u16(&count[0], vaddl_u8(vget_low_u8(s1), vget_low_u8(s2)));
93
    vst1q_u16(&count[8], vaddl_u8(vget_high_u8(s1), vget_high_u8(s2)));
94
95
#elif defined(__SSE2__)
96
    int sym;
97
48.8k
    __m128i s1 = _mm_setzero_si128();
98
48.8k
    __m128i s2 = _mm_setzero_si128();
99
100
48.8k
    if (codes & 1) {
101
27.4k
        s1 = _mm_load_si128((const __m128i*)&one[16 * lens[0]]);
102
27.4k
    }
103
2.49M
    for (sym = codes & 1; sym < codes; sym += 2) {
104
2.44M
        s1 = _mm_add_epi8(s1, _mm_load_si128((const __m128i*)&one[16 * lens[sym]]));  // vaddq_u8
105
2.44M
        s2 = _mm_add_epi8(s2, _mm_load_si128((const __m128i*)&one[16 * lens[sym+1]]));
106
2.44M
    }
107
108
#  if defined(__AVX2__)
109
    __m256i w1 = _mm256_cvtepu8_epi16(s1);
110
    __m256i w2 = _mm256_cvtepu8_epi16(s2);
111
    __m256i sum = _mm256_add_epi16(w1, w2);
112
113
    _mm256_storeu_si256((__m256i*)&count[0], sum);
114
#  else
115
48.8k
    __m128i zero = _mm_setzero_si128();
116
117
48.8k
    __m128i s1_lo = _mm_unpacklo_epi8(s1, zero);
118
48.8k
    __m128i s2_lo = _mm_unpacklo_epi8(s2, zero);
119
48.8k
    __m128i sum_lo = _mm_add_epi16(s1_lo, s2_lo);
120
48.8k
    _mm_storeu_si128((__m128i*)&count[0], sum_lo);
121
122
48.8k
    __m128i s1_hi = _mm_unpackhi_epi8(s1, zero);
123
48.8k
    __m128i s2_hi = _mm_unpackhi_epi8(s2, zero);
124
48.8k
    __m128i sum_hi = _mm_add_epi16(s1_hi, s2_hi);
125
48.8k
    _mm_storeu_si128((__m128i*)&count[8], sum_hi);
126
48.8k
#  endif
127
#else
128
    int len, sym;
129
    for (len = 0; len <= MAX_BITS; len++)
130
        count[len] = 0;
131
    for (sym = 0; sym < codes; sym++)
132
        count[lens[sym]]++;
133
    Z_UNUSED(one);
134
#endif
135
48.8k
}
136
137
/*
138
   Build a set of tables to decode the provided canonical Huffman code.
139
   The code lengths are lens[0..codes-1].  The result starts at *table,
140
   whose indices are 0..2^bits-1.  work is a writable array of at least
141
   lens shorts, which is used as a work area.  type is the type of code
142
   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
143
   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
144
   on return points to the next available entry's address.  bits is the
145
   requested root table index bits, and on return it is the actual root
146
   table index bits.  It will differ if the request is greater than the
147
   longest code or if it is less than the shortest code.
148
 */
149
int Z_INTERNAL zng_inflate_table(codetype type, uint16_t *lens, unsigned codes,
150
48.8k
                                 code * *table, unsigned *bits, uint16_t *work) {
151
48.8k
    unsigned len;                 /* a code's length in bits */
152
48.8k
    unsigned sym;                 /* index of code symbols */
153
48.8k
    unsigned min, max;            /* minimum and maximum code lengths */
154
48.8k
    unsigned root;                /* number of index bits for root table */
155
48.8k
    unsigned curr;                /* number of index bits for current table */
156
48.8k
    unsigned drop;                /* code bits to drop for sub-table */
157
48.8k
    int left;                     /* number of prefix codes available */
158
48.8k
    unsigned used;                /* code entries in table used */
159
48.8k
    uint16_t rhuff;               /* Reversed huffman code */
160
48.8k
    unsigned huff;                /* Huffman code */
161
48.8k
    unsigned incr;                /* for incrementing code, index */
162
48.8k
    unsigned fill;                /* index for replicating entries */
163
48.8k
    unsigned low;                 /* low bits for current root entry */
164
48.8k
    unsigned mask;                /* mask for low root bits */
165
48.8k
    code here;                    /* table entry for duplication */
166
48.8k
    code *next;                   /* next available space in table */
167
48.8k
    const uint16_t *base = NULL;  /* base value table to use */
168
48.8k
    const uint16_t *extra = NULL; /* extra bits table to use */
169
48.8k
    unsigned match = 0;           /* use base and extra for symbol >= match */
170
48.8k
    uint16_t ALIGNED_(16) count[MAX_BITS+1]; /* number of codes of each length */
171
48.8k
    uint16_t offs[MAX_BITS+1];    /* offsets in table for each length */
172
48.8k
    static const uint16_t lbase[31] = { /* Length codes 257..285 base */
173
48.8k
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
174
48.8k
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
175
48.8k
    static const uint16_t lext[31] = { /* Length codes 257..285 extra */
176
48.8k
        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
177
48.8k
        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 199, 75};
178
48.8k
    static const uint16_t dbase[32] = { /* Distance codes 0..29 base */
179
48.8k
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
180
48.8k
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
181
48.8k
        8193, 12289, 16385, 24577, 0, 0};
182
48.8k
    static const uint16_t dext[32] = { /* Distance codes 0..29 extra */
183
48.8k
        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
184
48.8k
        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
185
48.8k
        28, 28, 29, 29, 64, 64};
186
187
    /*
188
       Process a set of code lengths to create a canonical Huffman code.  The
189
       code lengths are lens[0..codes-1].  Each length corresponds to the
190
       symbols 0..codes-1.  The Huffman code is generated by first sorting the
191
       symbols by length from short to long, and retaining the symbol order
192
       for codes with equal lengths.  Then the code starts with all zero bits
193
       for the first code of the shortest length, and the codes are integer
194
       increments for the same length, and zeros are appended as the length
195
       increases.  For the deflate format, these bits are stored backwards
196
       from their more natural integer increment ordering, and so when the
197
       decoding tables are built in the large loop below, the integer codes
198
       are incremented backwards.
199
200
       This routine assumes, but does not check, that all of the entries in
201
       lens[] are in the range 0..MAXBITS.  The caller must assure this.
202
       1..MAXBITS is interpreted as that code length.  zero means that that
203
       symbol does not occur in this code.
204
205
       The codes are sorted by computing a count of codes for each length,
206
       creating from that a table of starting indices for each length in the
207
       sorted table, and then entering the symbols in order in the sorted
208
       table.  The sorted table is work[], with that space being provided by
209
       the caller.
210
211
       The length counts are used for other purposes as well, i.e. finding
212
       the minimum and maximum length codes, determining if there are any
213
       codes at all, checking for a valid set of lengths, and looking ahead
214
       at length counts to determine sub-table sizes when building the
215
       decoding tables.
216
     */
217
218
    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
219
48.8k
    count_lengths(lens, codes, count);
220
221
    /* bound code lengths, force root to be within code lengths */
222
48.8k
    root = *bits;
223
450k
    for (max = MAX_BITS; max >= 1; max--)
224
450k
        if (count[max] != 0) break;
225
48.8k
    root = MIN(root, max);
226
48.8k
    if (UNLIKELY(max == 0)) {           /* no symbols to code at all */
227
0
        here.op = (unsigned char)64;    /* invalid code marker */
228
0
        here.bits = (unsigned char)1;
229
0
        here.val = (uint16_t)0;
230
0
        *(*table)++ = here;             /* make a table to force an error */
231
0
        *(*table)++ = here;
232
0
        *bits = 1;
233
0
        return 0;     /* no symbols, but wait for decoding to report error */
234
0
    }
235
107k
    for (min = 1; min < max; min++)
236
96.9k
        if (count[min] != 0) break;
237
48.8k
    root = MAX(root, min);
238
239
    /* Growing root doubles the table build and its footprint, a cost paid once per block, but it
240
       only pays off on the symbols that exceed the smaller root. Weighting count[] by the code
241
       space each length occupies estimates how often that happens, without decoding the block. */
242
48.8k
    if (type == LENS && root == MAX_LEN_ROOT_BITS) {
243
10.7k
        unsigned space = 0;
244
64.3k
        for (len = root; len <= MAX_BITS; len++)
245
53.6k
            space += (unsigned)count[len] << (MAX_BITS - len);
246
10.7k
        if (space < ROOT_GROW_MIN_SPACE)
247
5.56k
            root--;
248
10.7k
    }
249
250
    /* check for an over-subscribed or incomplete set of lengths */
251
48.8k
    left = 1;
252
780k
    for (len = 1; len <= MAX_BITS; len++) {
253
732k
        left <<= 1;
254
732k
        left -= count[len];
255
732k
        if (left < 0) return -1;        /* over-subscribed */
256
732k
    }
257
48.8k
    if (left > 0 && (type == CODES || max != 1))
258
0
        return -1;                      /* incomplete set */
259
260
    /* generate offsets into symbol table for each length for sorting */
261
48.8k
    offs[1] = 0;
262
732k
    for (len = 1; len < MAX_BITS; len++)
263
683k
        offs[len + 1] = offs[len] + count[len];
264
265
    /* sort symbols by length, by symbol order within each length */
266
4.97M
    for (sym = 0; sym < codes; sym++)
267
4.92M
        if (lens[sym] != 0) work[offs[lens[sym]]++] = (uint16_t)sym;
268
269
    /*
270
       Create and fill in decoding tables.  In this loop, the table being
271
       filled is at next and has curr index bits.  The code being used is huff
272
       with length len.  That code is converted to an index by dropping drop
273
       bits off of the bottom.  For codes where len is less than drop + curr,
274
       those top drop + curr - len bits are incremented through all values to
275
       fill the table with replicated entries.
276
277
       root is the number of index bits for the root table.  When len exceeds
278
       root, sub-tables are created pointed to by the root entry with an index
279
       of the low root bits of huff.  This is saved in low to check for when a
280
       new sub-table should be started.  drop is zero when the root table is
281
       being filled, and drop is root when sub-tables are being filled.
282
283
       When a new sub-table is needed, it is necessary to look ahead in the
284
       code lengths to determine what size sub-table is needed.  The length
285
       counts are used for this, and so count[] is decremented as codes are
286
       entered in the tables.
287
288
       used keeps track of how many table entries have been allocated from the
289
       provided *table space.  It is checked for LENS and DIST tables against
290
       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
291
       the initial root table size constants.  See the comments in inftrees.h
292
       for more information.
293
294
       sym increments through all symbols, and the loop terminates when
295
       all codes of length max, i.e. all codes, have been processed.  This
296
       routine permits incomplete codes, so another loop after this one fills
297
       in the rest of the decoding tables with invalid code markers.
298
     */
299
300
    /* The packed table fill below reads and writes each entry as a single uint32_t. */
301
48.8k
    Assert(sizeof(code) == 4, "code entry must be exactly 4 bytes");
302
303
    /* set up for code type */
304
48.8k
    switch (type) {
305
16.2k
    case CODES:
306
16.2k
        base = extra = work;    /* dummy value--not used */
307
16.2k
        match = 20;
308
16.2k
        break;
309
16.2k
    case LENS:
310
16.2k
        base = lbase;
311
16.2k
        extra = lext;
312
16.2k
        match = 257;
313
16.2k
        break;
314
16.2k
    case DISTS:
315
16.2k
        base = dbase;
316
16.2k
        extra = dext;
317
48.8k
    }
318
319
    /* initialize state for loop */
320
48.8k
    rhuff = 0;                  /* starting code, reversed */
321
48.8k
    huff = 0;                   /* starting code */
322
48.8k
    sym = 0;                    /* starting code symbol */
323
48.8k
    len = min;                  /* starting code length */
324
48.8k
    next = *table;              /* current table to fill in */
325
48.8k
    curr = root;                /* current table index bits */
326
48.8k
    drop = 0;                   /* current bits to drop from code for index */
327
48.8k
    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
328
48.8k
    used = 1U << root;          /* use root table entries */
329
48.8k
    mask = used - 1;            /* mask for comparing low */
330
331
    /* check available table space */
332
48.8k
    if ((type == LENS && used > ENOUGH_LENS) ||
333
48.8k
        (type == DISTS && used > ENOUGH_DISTS))
334
0
        return 1;
335
336
    /* process all codes and make table entries */
337
3.17M
    for (;;) {
338
        /* create table entry */
339
3.17M
        here.bits = (unsigned char)(len - drop);
340
3.17M
        if (LIKELY(work[sym] >= match)) {
341
288k
            unsigned op = extra[work[sym] - match];
342
288k
            here.op = COMBINE_OP(op, here.bits);
343
288k
            here.bits = COMBINE_BITS(here.bits, op);
344
288k
            here.val = base[work[sym] - match];
345
2.88M
        } else if (work[sym] + 1U < match) {
346
2.86M
            here.op = (unsigned char)0;
347
2.86M
            here.val = work[sym];
348
2.86M
        } else {
349
16.2k
            here.op = (unsigned char)(32 + 64);         /* end of block */
350
16.2k
            here.val = 0;
351
16.2k
        }
352
353
        /* replicate for those indices with low len bits equal to huff */
354
3.17M
        incr = 1U << (len - drop);
355
3.17M
        fill = 1U << curr;
356
3.17M
        min = fill;                 /* save offset to next table */
357
3.17M
        {
358
            /* `here` is a 4-byte struct that the compiler writes one field at a time.
359
               Read it as a packed uint32_t so each slot is filled by a single store. */
360
3.17M
            uint32_t here_u32 = zng_memread_4(&here);
361
3.17M
            code *base_ptr = next + (huff >> drop);
362
3.17M
            unsigned step4 = incr << 2;
363
            /* Unroll by four so the slot addresses are independent. */
364
8.15M
            while (fill >= step4) {
365
4.97M
                zng_memwrite_4(&base_ptr[fill - 1 * incr], here_u32);
366
4.97M
                zng_memwrite_4(&base_ptr[fill - 2 * incr], here_u32);
367
4.97M
                zng_memwrite_4(&base_ptr[fill - 3 * incr], here_u32);
368
4.97M
                zng_memwrite_4(&base_ptr[fill - 4 * incr], here_u32);
369
4.97M
                fill -= step4;
370
4.97M
            }
371
4.77M
            while (fill != 0) {
372
1.59M
                fill -= incr;
373
1.59M
                zng_memwrite_4(&base_ptr[fill], here_u32);
374
1.59M
            }
375
3.17M
        }
376
377
        /* backwards increment the len-bit code huff */
378
3.17M
        rhuff = (uint16_t)(rhuff + (0x8000u >> (len - 1)));
379
3.17M
        huff = zng_bitreverse16(rhuff);
380
381
        /* go to next symbol, update count, len */
382
3.17M
        sym++;
383
3.17M
        if (--(count[len]) == 0) {
384
236k
            if (len == max)
385
48.8k
                break;
386
187k
            len = lens[work[sym]];
387
187k
        }
388
389
        /* create new sub-table if needed */
390
3.12M
        if (len > root && (huff & mask) != low) {
391
            /* if first time, transition to sub-tables */
392
73.4k
            if (drop == 0)
393
11.8k
                drop = root;
394
395
            /* increment past last table */
396
73.4k
            next += min;            /* here min is 1 << curr */
397
398
            /* determine length of next table */
399
73.4k
            curr = len - drop;
400
73.4k
            left = (int)(1 << curr);
401
87.2k
            while (curr + drop < max) {
402
60.5k
                left -= count[curr + drop];
403
60.5k
                if (left <= 0)
404
46.7k
                    break;
405
13.8k
                curr++;
406
13.8k
                left <<= 1;
407
13.8k
            }
408
409
            /* check for enough space */
410
73.4k
            used += 1U << curr;
411
73.4k
            if ((type == LENS && used > ENOUGH_LENS) || (type == DISTS && used > ENOUGH_DISTS))
412
0
                return 1;
413
414
            /* point entry in root table to sub-table */
415
73.4k
            low = huff & mask;
416
73.4k
            (*table)[low].op = (unsigned char)curr;
417
73.4k
            (*table)[low].bits = (unsigned char)root;
418
73.4k
            (*table)[low].val = (uint16_t)(next - *table);
419
73.4k
        }
420
3.12M
    }
421
422
    /* fill in remaining table entry if code is incomplete (guaranteed to have
423
       at most one remaining entry, since if the code is incomplete, the
424
       maximum code length that was allowed to get this far is one bit) */
425
48.8k
    if (UNLIKELY(huff != 0)) {
426
0
        here.op = (unsigned char)64;            /* invalid code marker */
427
0
        here.bits = (unsigned char)(len - drop);
428
0
        here.val = (uint16_t)0;
429
0
        next[huff] = here;
430
0
    }
431
432
    /* set return parameters */
433
48.8k
    *table += used;
434
48.8k
    *bits = root;
435
48.8k
    return 0;
436
48.8k
}