Coverage Report

Created: 2026-08-13 06:29

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