Coverage Report

Created: 2026-01-25 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zlib/inftrees.c
Line
Count
Source
1
/* inftrees.c -- generate Huffman trees for efficient decoding
2
 * Copyright (C) 1995-2025 Mark Adler
3
 * For conditions of distribution and use, see copyright notice in zlib.h
4
 */
5
6
#ifdef MAKEFIXED
7
#  ifndef BUILDFIXED
8
#    define BUILDFIXED
9
#  endif
10
#endif
11
#ifdef BUILDFIXED
12
#  define Z_ONCE
13
#endif
14
15
#include "zutil.h"
16
#include "inftrees.h"
17
#include "inflate.h"
18
19
711k
#define MAXBITS 15
20
21
const char inflate_copyright[] =
22
   " inflate 1.3.1.2 Copyright 1995-2025 Mark Adler ";
23
/*
24
  If you use the zlib library in a product, an acknowledgment is welcome
25
  in the documentation of your product. If for some reason you cannot
26
  include such an acknowledgment, I would appreciate that you keep this
27
  copyright string in the executable of your product.
28
 */
29
30
/*
31
   Build a set of tables to decode the provided canonical Huffman code.
32
   The code lengths are lens[0..codes-1].  The result starts at *table,
33
   whose indices are 0..2^bits-1.  work is a writable array of at least
34
   lens shorts, which is used as a work area.  type is the type of code
35
   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
36
   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
37
   on return points to the next available entry's address.  bits is the
38
   requested root table index bits, and on return it is the actual root
39
   table index bits.  It will differ if the request is greater than the
40
   longest code or if it is less than the shortest code.
41
 */
42
int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
43
                                unsigned codes, code FAR * FAR *table,
44
14.6k
                                unsigned FAR *bits, unsigned short FAR *work) {
45
14.6k
    unsigned len;               /* a code's length in bits */
46
14.6k
    unsigned sym;               /* index of code symbols */
47
14.6k
    unsigned min, max;          /* minimum and maximum code lengths */
48
14.6k
    unsigned root;              /* number of index bits for root table */
49
14.6k
    unsigned curr;              /* number of index bits for current table */
50
14.6k
    unsigned drop;              /* code bits to drop for sub-table */
51
14.6k
    int left;                   /* number of prefix codes available */
52
14.6k
    unsigned used;              /* code entries in table used */
53
14.6k
    unsigned huff;              /* Huffman code */
54
14.6k
    unsigned incr;              /* for incrementing code, index */
55
14.6k
    unsigned fill;              /* index for replicating entries */
56
14.6k
    unsigned low;               /* low bits for current root entry */
57
14.6k
    unsigned mask;              /* mask for low root bits */
58
14.6k
    code here;                  /* table entry for duplication */
59
14.6k
    code FAR *next;             /* next available space in table */
60
14.6k
    const unsigned short FAR *base;     /* base value table to use */
61
14.6k
    const unsigned short FAR *extra;    /* extra bits table to use */
62
14.6k
    unsigned match;             /* use base and extra for symbol >= match */
63
14.6k
    unsigned short count[MAXBITS+1];    /* number of codes of each length */
64
14.6k
    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
65
14.6k
    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
66
14.6k
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
67
14.6k
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
68
14.6k
    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
69
14.6k
        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
70
14.6k
        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 64, 204};
71
14.6k
    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
72
14.6k
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
73
14.6k
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
74
14.6k
        8193, 12289, 16385, 24577, 0, 0};
75
14.6k
    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
76
14.6k
        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
77
14.6k
        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
78
14.6k
        28, 28, 29, 29, 64, 64};
79
80
    /*
81
       Process a set of code lengths to create a canonical Huffman code.  The
82
       code lengths are lens[0..codes-1].  Each length corresponds to the
83
       symbols 0..codes-1.  The Huffman code is generated by first sorting the
84
       symbols by length from short to long, and retaining the symbol order
85
       for codes with equal lengths.  Then the code starts with all zero bits
86
       for the first code of the shortest length, and the codes are integer
87
       increments for the same length, and zeros are appended as the length
88
       increases.  For the deflate format, these bits are stored backwards
89
       from their more natural integer increment ordering, and so when the
90
       decoding tables are built in the large loop below, the integer codes
91
       are incremented backwards.
92
93
       This routine assumes, but does not check, that all of the entries in
94
       lens[] are in the range 0..MAXBITS.  The caller must assure this.
95
       1..MAXBITS is interpreted as that code length.  zero means that that
96
       symbol does not occur in this code.
97
98
       The codes are sorted by computing a count of codes for each length,
99
       creating from that a table of starting indices for each length in the
100
       sorted table, and then entering the symbols in order in the sorted
101
       table.  The sorted table is work[], with that space being provided by
102
       the caller.
103
104
       The length counts are used for other purposes as well, i.e. finding
105
       the minimum and maximum length codes, determining if there are any
106
       codes at all, checking for a valid set of lengths, and looking ahead
107
       at length counts to determine sub-table sizes when building the
108
       decoding tables.
109
     */
110
111
    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
112
249k
    for (len = 0; len <= MAXBITS; len++)
113
235k
        count[len] = 0;
114
1.55M
    for (sym = 0; sym < codes; sym++)
115
1.53M
        count[lens[sym]]++;
116
117
    /* bound code lengths, force root to be within code lengths */
118
14.6k
    root = *bits;
119
140k
    for (max = MAXBITS; max >= 1; max--)
120
140k
        if (count[max] != 0) break;
121
14.6k
    if (root > max) root = max;
122
14.6k
    if (max == 0) {                     /* no symbols to code at all */
123
71
        here.op = (unsigned char)64;    /* invalid code marker */
124
71
        here.bits = (unsigned char)1;
125
71
        here.val = (unsigned short)0;
126
71
        *(*table)++ = here;             /* make a table to force an error */
127
71
        *(*table)++ = here;
128
71
        *bits = 1;
129
71
        return 0;     /* no symbols, but wait for decoding to report error */
130
71
    }
131
32.5k
    for (min = 1; min < max; min++)
132
32.4k
        if (count[min] != 0) break;
133
14.6k
    if (root < min) root = min;
134
135
    /* check for an over-subscribed or incomplete set of lengths */
136
14.6k
    left = 1;
137
231k
    for (len = 1; len <= MAXBITS; len++) {
138
217k
        left <<= 1;
139
217k
        left -= count[len];
140
217k
        if (left < 0) return -1;        /* over-subscribed */
141
217k
    }
142
14.4k
    if (left > 0 && (type == CODES || max != 1))
143
85
        return -1;                      /* incomplete set */
144
145
    /* generate offsets into symbol table for each length for sorting */
146
14.3k
    offs[1] = 0;
147
215k
    for (len = 1; len < MAXBITS; len++)
148
200k
        offs[len + 1] = offs[len] + count[len];
149
150
    /* sort symbols by length, by symbol order within each length */
151
1.51M
    for (sym = 0; sym < codes; sym++)
152
1.49M
        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
153
154
    /*
155
       Create and fill in decoding tables.  In this loop, the table being
156
       filled is at next and has curr index bits.  The code being used is huff
157
       with length len.  That code is converted to an index by dropping drop
158
       bits off of the bottom.  For codes where len is less than drop + curr,
159
       those top drop + curr - len bits are incremented through all values to
160
       fill the table with replicated entries.
161
162
       root is the number of index bits for the root table.  When len exceeds
163
       root, sub-tables are created pointed to by the root entry with an index
164
       of the low root bits of huff.  This is saved in low to check for when a
165
       new sub-table should be started.  drop is zero when the root table is
166
       being filled, and drop is root when sub-tables are being filled.
167
168
       When a new sub-table is needed, it is necessary to look ahead in the
169
       code lengths to determine what size sub-table is needed.  The length
170
       counts are used for this, and so count[] is decremented as codes are
171
       entered in the tables.
172
173
       used keeps track of how many table entries have been allocated from the
174
       provided *table space.  It is checked for LENS and DIST tables against
175
       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
176
       the initial root table size constants.  See the comments in inftrees.h
177
       for more information.
178
179
       sym increments through all symbols, and the loop terminates when
180
       all codes of length max, i.e. all codes, have been processed.  This
181
       routine permits incomplete codes, so another loop after this one fills
182
       in the rest of the decoding tables with invalid code markers.
183
     */
184
185
    /* set up for code type */
186
14.3k
    switch (type) {
187
5.05k
    case CODES:
188
5.05k
        base = extra = work;    /* dummy value--not used */
189
5.05k
        match = 20;
190
5.05k
        break;
191
4.68k
    case LENS:
192
4.68k
        base = lbase;
193
4.68k
        extra = lext;
194
4.68k
        match = 257;
195
4.68k
        break;
196
4.62k
    default:    /* DISTS */
197
4.62k
        base = dbase;
198
4.62k
        extra = dext;
199
4.62k
        match = 0;
200
14.3k
    }
201
202
    /* initialize state for loop */
203
14.3k
    huff = 0;                   /* starting code */
204
14.3k
    sym = 0;                    /* starting code symbol */
205
14.3k
    len = min;                  /* starting code length */
206
14.3k
    next = *table;              /* current table to fill in */
207
14.3k
    curr = root;                /* current table index bits */
208
14.3k
    drop = 0;                   /* current bits to drop from code for index */
209
14.3k
    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
210
14.3k
    used = 1U << root;          /* use root table entries */
211
14.3k
    mask = used - 1;            /* mask for comparing low */
212
213
    /* check available table space */
214
14.3k
    if ((type == LENS && used > ENOUGH_LENS) ||
215
14.3k
        (type == DISTS && used > ENOUGH_DISTS))
216
0
        return 1;
217
218
    /* process all codes and make table entries */
219
417k
    for (;;) {
220
        /* create table entry */
221
417k
        here.bits = (unsigned char)(len - drop);
222
417k
        if (work[sym] + 1U < match) {
223
295k
            here.op = (unsigned char)0;
224
295k
            here.val = work[sym];
225
295k
        }
226
121k
        else if (work[sym] >= match) {
227
117k
            here.op = (unsigned char)(extra[work[sym] - match]);
228
117k
            here.val = base[work[sym] - match];
229
117k
        }
230
4.68k
        else {
231
4.68k
            here.op = (unsigned char)(32 + 64);         /* end of block */
232
4.68k
            here.val = 0;
233
4.68k
        }
234
235
        /* replicate for those indices with low len bits equal to huff */
236
417k
        incr = 1U << (len - drop);
237
417k
        fill = 1U << curr;
238
417k
        min = fill;                 /* save offset to next table */
239
1.95M
        do {
240
1.95M
            fill -= incr;
241
1.95M
            next[(huff >> drop) + fill] = here;
242
1.95M
        } while (fill != 0);
243
244
        /* backwards increment the len-bit code huff */
245
417k
        incr = 1U << (len - 1);
246
820k
        while (huff & incr)
247
402k
            incr >>= 1;
248
417k
        if (incr != 0) {
249
402k
            huff &= incr - 1;
250
402k
            huff += incr;
251
402k
        }
252
14.3k
        else
253
14.3k
            huff = 0;
254
255
        /* go to next symbol, update count, len */
256
417k
        sym++;
257
417k
        if (--(count[len]) == 0) {
258
70.8k
            if (len == max) break;
259
56.4k
            len = lens[work[sym]];
260
56.4k
        }
261
262
        /* create new sub-table if needed */
263
402k
        if (len > root && (huff & mask) != low) {
264
            /* if first time, transition to sub-tables */
265
25.3k
            if (drop == 0)
266
4.28k
                drop = root;
267
268
            /* increment past last table */
269
25.3k
            next += min;            /* here min is 1 << curr */
270
271
            /* determine length of next table */
272
25.3k
            curr = len - drop;
273
25.3k
            left = (int)(1 << curr);
274
29.0k
            while (curr + drop < max) {
275
15.6k
                left -= count[curr + drop];
276
15.6k
                if (left <= 0) break;
277
3.70k
                curr++;
278
3.70k
                left <<= 1;
279
3.70k
            }
280
281
            /* check for enough space */
282
25.3k
            used += 1U << curr;
283
25.3k
            if ((type == LENS && used > ENOUGH_LENS) ||
284
25.3k
                (type == DISTS && used > ENOUGH_DISTS))
285
0
                return 1;
286
287
            /* point entry in root table to sub-table */
288
25.3k
            low = huff & mask;
289
25.3k
            (*table)[low].op = (unsigned char)curr;
290
25.3k
            (*table)[low].bits = (unsigned char)root;
291
25.3k
            (*table)[low].val = (unsigned short)(next - *table);
292
25.3k
        }
293
402k
    }
294
295
    /* fill in remaining table entry if code is incomplete (guaranteed to have
296
       at most one remaining entry, since if the code is incomplete, the
297
       maximum code length that was allowed to get this far is one bit) */
298
14.3k
    if (huff != 0) {
299
10
        here.op = (unsigned char)64;            /* invalid code marker */
300
10
        here.bits = (unsigned char)(len - drop);
301
10
        here.val = (unsigned short)0;
302
10
        next[huff] = here;
303
10
    }
304
305
    /* set return parameters */
306
14.3k
    *table += used;
307
14.3k
    *bits = root;
308
14.3k
    return 0;
309
14.3k
}
310
311
#ifdef BUILDFIXED
312
/*
313
  If this is compiled with BUILDFIXED defined, and if inflate will be used in
314
  multiple threads, and if atomics are not available, then inflate() must be
315
  called with a fixed block (e.g. 0x03 0x00) to initialize the tables and must
316
  return before any other threads are allowed to call inflate.
317
 */
318
319
static code *lenfix, *distfix;
320
static code fixed[544];
321
322
/* State for z_once(). */
323
local z_once_t built = Z_ONCE_INIT;
324
325
local void buildtables(void) {
326
    unsigned sym, bits;
327
    static code *next;
328
    unsigned short lens[288], work[288];
329
330
    /* literal/length table */
331
    sym = 0;
332
    while (sym < 144) lens[sym++] = 8;
333
    while (sym < 256) lens[sym++] = 9;
334
    while (sym < 280) lens[sym++] = 7;
335
    while (sym < 288) lens[sym++] = 8;
336
    next = fixed;
337
    lenfix = next;
338
    bits = 9;
339
    inflate_table(LENS, lens, 288, &(next), &(bits), work);
340
341
    /* distance table */
342
    sym = 0;
343
    while (sym < 32) lens[sym++] = 5;
344
    distfix = next;
345
    bits = 5;
346
    inflate_table(DISTS, lens, 32, &(next), &(bits), work);
347
}
348
#else /* !BUILDFIXED */
349
#  include "inffixed.h"
350
#endif /* BUILDFIXED */
351
352
/*
353
   Return state with length and distance decoding tables and index sizes set to
354
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
355
   If BUILDFIXED is defined, then instead this routine builds the tables the
356
   first time it's called, and returns those tables the first time and
357
   thereafter.  This reduces the size of the code by about 2K bytes, in
358
   exchange for a little execution time.  However, BUILDFIXED should not be
359
   used for threaded applications if atomics are not available, as it will
360
   not be thread-safe.
361
 */
362
7.20k
void inflate_fixed(struct inflate_state FAR *state) {
363
#ifdef BUILDFIXED
364
    z_once(&built, buildtables);
365
#endif /* BUILDFIXED */
366
7.20k
    state->lencode = lenfix;
367
7.20k
    state->lenbits = 9;
368
7.20k
    state->distcode = distfix;
369
7.20k
    state->distbits = 5;
370
7.20k
}
371
372
#ifdef MAKEFIXED
373
#include <stdio.h>
374
375
/*
376
   Write out the inffixed.h that will be #include'd above.  Defining MAKEFIXED
377
   also defines BUILDFIXED, so the tables are built on the fly.  main() writes
378
   those tables to stdout, which would directed to inffixed.h. Compile this
379
   along with zutil.c:
380
381
       cc -DMAKEFIXED -o fix inftrees.c zutil.c
382
       ./fix > inffixed.h
383
 */
384
int main(void) {
385
    unsigned low, size;
386
    struct inflate_state state;
387
388
    inflate_fixed(&state);
389
    puts("/* inffixed.h -- table for decoding fixed codes");
390
    puts(" * Generated automatically by makefixed().");
391
    puts(" */");
392
    puts("");
393
    puts("/* WARNING: this file should *not* be used by applications.");
394
    puts("   It is part of the implementation of this library and is");
395
    puts("   subject to change. Applications should only use zlib.h.");
396
    puts(" */");
397
    puts("");
398
    size = 1U << 9;
399
    printf("static const code lenfix[%u] = {", size);
400
    low = 0;
401
    for (;;) {
402
        if ((low % 7) == 0) printf("\n    ");
403
        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
404
               state.lencode[low].bits, state.lencode[low].val);
405
        if (++low == size) break;
406
        putchar(',');
407
    }
408
    puts("\n};");
409
    size = 1U << 5;
410
    printf("\nstatic const code distfix[%u] = {", size);
411
    low = 0;
412
    for (;;) {
413
        if ((low % 6) == 0) printf("\n    ");
414
        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
415
               state.distcode[low].val);
416
        if (++low == size) break;
417
        putchar(',');
418
    }
419
    puts("\n};");
420
    return 0;
421
}
422
#endif /* MAKEFIXED */