Coverage Report

Created: 2025-11-24 06:41

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
10
const char PREFIX(inflate_copyright)[] = " inflate 1.3.1 Copyright 1995-2024 Mark Adler ";
11
/*
12
  If you use the zlib library in a product, an acknowledgment is welcome
13
  in the documentation of your product. If for some reason you cannot
14
  include such an acknowledgment, I would appreciate that you keep this
15
  copyright string in the executable of your product.
16
 */
17
18
/*
19
   Build a set of tables to decode the provided canonical Huffman code.
20
   The code lengths are lens[0..codes-1].  The result starts at *table,
21
   whose indices are 0..2^bits-1.  work is a writable array of at least
22
   lens shorts, which is used as a work area.  type is the type of code
23
   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
24
   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
25
   on return points to the next available entry's address.  bits is the
26
   requested root table index bits, and on return it is the actual root
27
   table index bits.  It will differ if the request is greater than the
28
   longest code or if it is less than the shortest code.
29
 */
30
int Z_INTERNAL zng_inflate_table(codetype type, uint16_t *lens, unsigned codes,
31
74.6k
                                code * *table, unsigned *bits, uint16_t *work) {
32
74.6k
    unsigned len;               /* a code's length in bits */
33
74.6k
    unsigned sym;               /* index of code symbols */
34
74.6k
    unsigned min, max;          /* minimum and maximum code lengths */
35
74.6k
    unsigned root;              /* number of index bits for root table */
36
74.6k
    unsigned curr;              /* number of index bits for current table */
37
74.6k
    unsigned drop;              /* code bits to drop for sub-table */
38
74.6k
    int left;                   /* number of prefix codes available */
39
74.6k
    unsigned used;              /* code entries in table used */
40
74.6k
    unsigned huff;              /* Huffman code */
41
74.6k
    unsigned incr;              /* for incrementing code, index */
42
74.6k
    unsigned fill;              /* index for replicating entries */
43
74.6k
    unsigned low;               /* low bits for current root entry */
44
74.6k
    unsigned mask;              /* mask for low root bits */
45
74.6k
    code here;                  /* table entry for duplication */
46
74.6k
    code *next;                 /* next available space in table */
47
74.6k
    const uint16_t *base;       /* base value table to use */
48
74.6k
    const uint16_t *extra;      /* extra bits table to use */
49
74.6k
    unsigned match;             /* use base and extra for symbol >= match */
50
74.6k
    uint16_t count[MAX_BITS+1];  /* number of codes of each length */
51
74.6k
    uint16_t offs[MAX_BITS+1];   /* offsets in table for each length */
52
74.6k
    static const uint16_t lbase[31] = { /* Length codes 257..285 base */
53
74.6k
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
54
74.6k
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
55
74.6k
    static const uint16_t lext[31] = { /* Length codes 257..285 extra */
56
74.6k
        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
57
74.6k
        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 77};
58
74.6k
    static const uint16_t dbase[32] = { /* Distance codes 0..29 base */
59
74.6k
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
60
74.6k
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
61
74.6k
        8193, 12289, 16385, 24577, 0, 0};
62
74.6k
    static const uint16_t dext[32] = { /* Distance codes 0..29 extra */
63
74.6k
        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
64
74.6k
        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
65
74.6k
        28, 28, 29, 29, 64, 64};
66
67
    /*
68
       Process a set of code lengths to create a canonical Huffman code.  The
69
       code lengths are lens[0..codes-1].  Each length corresponds to the
70
       symbols 0..codes-1.  The Huffman code is generated by first sorting the
71
       symbols by length from short to long, and retaining the symbol order
72
       for codes with equal lengths.  Then the code starts with all zero bits
73
       for the first code of the shortest length, and the codes are integer
74
       increments for the same length, and zeros are appended as the length
75
       increases.  For the deflate format, these bits are stored backwards
76
       from their more natural integer increment ordering, and so when the
77
       decoding tables are built in the large loop below, the integer codes
78
       are incremented backwards.
79
80
       This routine assumes, but does not check, that all of the entries in
81
       lens[] are in the range 0..MAXBITS.  The caller must assure this.
82
       1..MAXBITS is interpreted as that code length.  zero means that that
83
       symbol does not occur in this code.
84
85
       The codes are sorted by computing a count of codes for each length,
86
       creating from that a table of starting indices for each length in the
87
       sorted table, and then entering the symbols in order in the sorted
88
       table.  The sorted table is work[], with that space being provided by
89
       the caller.
90
91
       The length counts are used for other purposes as well, i.e. finding
92
       the minimum and maximum length codes, determining if there are any
93
       codes at all, checking for a valid set of lengths, and looking ahead
94
       at length counts to determine sub-table sizes when building the
95
       decoding tables.
96
     */
97
98
    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
99
1.26M
    for (len = 0; len <= MAX_BITS; len++)
100
1.19M
        count[len] = 0;
101
7.65M
    for (sym = 0; sym < codes; sym++)
102
7.58M
        count[lens[sym]]++;
103
104
    /* bound code lengths, force root to be within code lengths */
105
74.6k
    root = *bits;
106
711k
    for (max = MAX_BITS; max >= 1; max--)
107
709k
        if (count[max] != 0) break;
108
74.6k
    root = MIN(root, max);
109
74.6k
    if (UNLIKELY(max == 0)) {           /* no symbols to code at all */
110
1.22k
        here.op = (unsigned char)64;    /* invalid code marker */
111
1.22k
        here.bits = (unsigned char)1;
112
1.22k
        here.val = (uint16_t)0;
113
1.22k
        *(*table)++ = here;             /* make a table to force an error */
114
1.22k
        *(*table)++ = here;
115
1.22k
        *bits = 1;
116
1.22k
        return 0;     /* no symbols, but wait for decoding to report error */
117
1.22k
    }
118
175k
    for (min = 1; min < max; min++)
119
157k
        if (count[min] != 0) break;
120
73.4k
    root = MAX(root, min);
121
122
    /* check for an over-subscribed or incomplete set of lengths */
123
73.4k
    left = 1;
124
1.17M
    for (len = 1; len <= MAX_BITS; len++) {
125
1.09M
        left <<= 1;
126
1.09M
        left -= count[len];
127
1.09M
        if (left < 0) return -1;        /* over-subscribed */
128
1.09M
    }
129
73.1k
    if (left > 0 && (type == CODES || max != 1))
130
244
        return -1;                      /* incomplete set */
131
132
    /* generate offsets into symbol table for each length for sorting */
133
72.8k
    offs[1] = 0;
134
1.09M
    for (len = 1; len < MAX_BITS; len++)
135
1.02M
        offs[len + 1] = offs[len] + count[len];
136
137
    /* sort symbols by length, by symbol order within each length */
138
7.61M
    for (sym = 0; sym < codes; sym++)
139
7.54M
        if (lens[sym] != 0) work[offs[lens[sym]]++] = (uint16_t)sym;
140
141
    /*
142
       Create and fill in decoding tables.  In this loop, the table being
143
       filled is at next and has curr index bits.  The code being used is huff
144
       with length len.  That code is converted to an index by dropping drop
145
       bits off of the bottom.  For codes where len is less than drop + curr,
146
       those top drop + curr - len bits are incremented through all values to
147
       fill the table with replicated entries.
148
149
       root is the number of index bits for the root table.  When len exceeds
150
       root, sub-tables are created pointed to by the root entry with an index
151
       of the low root bits of huff.  This is saved in low to check for when a
152
       new sub-table should be started.  drop is zero when the root table is
153
       being filled, and drop is root when sub-tables are being filled.
154
155
       When a new sub-table is needed, it is necessary to look ahead in the
156
       code lengths to determine what size sub-table is needed.  The length
157
       counts are used for this, and so count[] is decremented as codes are
158
       entered in the tables.
159
160
       used keeps track of how many table entries have been allocated from the
161
       provided *table space.  It is checked for LENS and DIST tables against
162
       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
163
       the initial root table size constants.  See the comments in inftrees.h
164
       for more information.
165
166
       sym increments through all symbols, and the loop terminates when
167
       all codes of length max, i.e. all codes, have been processed.  This
168
       routine permits incomplete codes, so another loop after this one fills
169
       in the rest of the decoding tables with invalid code markers.
170
     */
171
172
    /* set up for code type */
173
72.8k
    switch (type) {
174
24.8k
    case CODES:
175
24.8k
        base = extra = work;    /* dummy value--not used */
176
24.8k
        match = 20;
177
24.8k
        break;
178
24.5k
    case LENS:
179
24.5k
        base = lbase;
180
24.5k
        extra = lext;
181
24.5k
        match = 257;
182
24.5k
        break;
183
23.3k
    default:    /* DISTS */
184
23.3k
        base = dbase;
185
23.3k
        extra = dext;
186
23.3k
        match = 0;
187
72.8k
    }
188
189
    /* initialize state for loop */
190
72.8k
    huff = 0;                   /* starting code */
191
72.8k
    sym = 0;                    /* starting code symbol */
192
72.8k
    len = min;                  /* starting code length */
193
72.8k
    next = *table;              /* current table to fill in */
194
72.8k
    curr = root;                /* current table index bits */
195
72.8k
    drop = 0;                   /* current bits to drop from code for index */
196
72.8k
    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
197
72.8k
    used = 1U << root;          /* use root table entries */
198
72.8k
    mask = used - 1;            /* mask for comparing low */
199
200
    /* check available table space */
201
72.8k
    if ((type == LENS && used > ENOUGH_LENS) ||
202
72.8k
        (type == DISTS && used > ENOUGH_DISTS))
203
0
        return 1;
204
205
    /* process all codes and make table entries */
206
3.94M
    for (;;) {
207
        /* create table entry */
208
3.94M
        here.bits = (unsigned char)(len - drop);
209
3.94M
        if (LIKELY(work[sym] >= match)) {
210
420k
            here.op = (unsigned char)(extra[work[sym] - match]);
211
420k
            here.val = base[work[sym] - match];
212
3.52M
        } else if (work[sym] + 1U < match) {
213
3.50M
            here.op = (unsigned char)0;
214
3.50M
            here.val = work[sym];
215
3.50M
        } else {
216
24.5k
            here.op = (unsigned char)(32 + 64);         /* end of block */
217
24.5k
            here.val = 0;
218
24.5k
        }
219
220
        /* replicate for those indices with low len bits equal to huff */
221
3.94M
        incr = 1U << (len - drop);
222
3.94M
        fill = 1U << curr;
223
3.94M
        min = fill;                 /* save offset to next table */
224
21.2M
        do {
225
21.2M
            fill -= incr;
226
21.2M
            next[(huff >> drop) + fill] = here;
227
21.2M
        } while (fill != 0);
228
229
        /* backwards increment the len-bit code huff */
230
3.94M
        incr = 1U << (len - 1);
231
7.82M
        while (huff & incr)
232
3.87M
            incr >>= 1;
233
3.94M
        if (incr != 0) {
234
3.88M
            huff &= incr - 1;
235
3.88M
            huff += incr;
236
3.88M
        } else {
237
65.6k
            huff = 0;
238
65.6k
        }
239
240
        /* go to next symbol, update count, len */
241
3.94M
        sym++;
242
3.94M
        if (--(count[len]) == 0) {
243
341k
            if (len == max)
244
72.8k
                break;
245
268k
            len = lens[work[sym]];
246
268k
        }
247
248
        /* create new sub-table if needed */
249
3.87M
        if (len > root && (huff & mask) != low) {
250
            /* if first time, transition to sub-tables */
251
97.9k
            if (drop == 0)
252
16.1k
                drop = root;
253
254
            /* increment past last table */
255
97.9k
            next += min;            /* here min is 1 << curr */
256
257
            /* determine length of next table */
258
97.9k
            curr = len - drop;
259
97.9k
            left = (int)(1 << curr);
260
124k
            while (curr + drop < max) {
261
93.3k
                left -= count[curr + drop];
262
93.3k
                if (left <= 0)
263
67.1k
                    break;
264
26.2k
                curr++;
265
26.2k
                left <<= 1;
266
26.2k
            }
267
268
            /* check for enough space */
269
97.9k
            used += 1U << curr;
270
97.9k
            if ((type == LENS && used > ENOUGH_LENS) || (type == DISTS && used > ENOUGH_DISTS))
271
0
                return 1;
272
273
            /* point entry in root table to sub-table */
274
97.9k
            low = huff & mask;
275
97.9k
            (*table)[low].op = (unsigned char)curr;
276
97.9k
            (*table)[low].bits = (unsigned char)root;
277
97.9k
            (*table)[low].val = (uint16_t)(next - *table);
278
97.9k
        }
279
3.87M
    }
280
281
    /* fill in remaining table entry if code is incomplete (guaranteed to have
282
       at most one remaining entry, since if the code is incomplete, the
283
       maximum code length that was allowed to get this far is one bit) */
284
72.8k
    if (UNLIKELY(huff != 0)) {
285
7.18k
        here.op = (unsigned char)64;            /* invalid code marker */
286
7.18k
        here.bits = (unsigned char)(len - drop);
287
7.18k
        here.val = (uint16_t)0;
288
7.18k
        next[huff] = here;
289
7.18k
    }
290
291
    /* set return parameters */
292
72.8k
    *table += used;
293
72.8k
    *bits = root;
294
72.8k
    return 0;
295
72.8k
}