Coverage Report

Created: 2026-01-17 06:26

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