Coverage Report

Created: 2026-02-14 06:26

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
5.12M
#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
105k
                                unsigned FAR *bits, unsigned short FAR *work) {
45
105k
    unsigned len;               /* a code's length in bits */
46
105k
    unsigned sym;               /* index of code symbols */
47
105k
    unsigned min, max;          /* minimum and maximum code lengths */
48
105k
    unsigned root;              /* number of index bits for root table */
49
105k
    unsigned curr;              /* number of index bits for current table */
50
105k
    unsigned drop;              /* code bits to drop for sub-table */
51
105k
    int left;                   /* number of prefix codes available */
52
105k
    unsigned used;              /* code entries in table used */
53
105k
    unsigned huff;              /* Huffman code */
54
105k
    unsigned incr;              /* for incrementing code, index */
55
105k
    unsigned fill;              /* index for replicating entries */
56
105k
    unsigned low;               /* low bits for current root entry */
57
105k
    unsigned mask;              /* mask for low root bits */
58
105k
    code here;                  /* table entry for duplication */
59
105k
    code FAR *next;             /* next available space in table */
60
105k
    const unsigned short FAR *base = NULL;  /* base value table to use */
61
105k
    const unsigned short FAR *extra = NULL; /* extra bits table to use */
62
105k
    unsigned match = 0;         /* use base and extra for symbol >= match */
63
105k
    unsigned short count[MAXBITS+1];    /* number of codes of each length */
64
105k
    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
65
105k
    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
66
105k
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
67
105k
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
68
105k
    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
69
105k
        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
70
105k
        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 64, 204};
71
105k
    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
72
105k
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
73
105k
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
74
105k
        8193, 12289, 16385, 24577, 0, 0};
75
105k
    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
76
105k
        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
77
105k
        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
78
105k
        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
1.79M
    for (len = 0; len <= MAXBITS; len++)
113
1.68M
        count[len] = 0;
114
10.9M
    for (sym = 0; sym < codes; sym++)
115
10.8M
        count[lens[sym]]++;
116
117
    /* bound code lengths, force root to be within code lengths */
118
105k
    root = *bits;
119
1.04M
    for (max = MAXBITS; max >= 1; max--)
120
1.04M
        if (count[max] != 0) break;
121
105k
    if (root > max) root = max;
122
105k
    if (max == 0) {                     /* no symbols to code at all */
123
92
        here.op = (unsigned char)64;    /* invalid code marker */
124
92
        here.bits = (unsigned char)1;
125
92
        here.val = (unsigned short)0;
126
92
        *(*table)++ = here;             /* make a table to force an error */
127
92
        *(*table)++ = here;
128
92
        *bits = 1;
129
92
        return 0;     /* no symbols, but wait for decoding to report error */
130
92
    }
131
227k
    for (min = 1; min < max; min++)
132
227k
        if (count[min] != 0) break;
133
105k
    if (root < min) root = min;
134
135
    /* check for an over-subscribed or incomplete set of lengths */
136
105k
    left = 1;
137
1.67M
    for (len = 1; len <= MAXBITS; len++) {
138
1.56M
        left <<= 1;
139
1.56M
        left -= count[len];
140
1.56M
        if (left < 0) return -1;        /* over-subscribed */
141
1.56M
    }
142
104k
    if (left > 0 && (type == CODES || max != 1))
143
463
        return -1;                      /* incomplete set */
144
145
    /* generate offsets into symbol table for each length for sorting */
146
103k
    offs[1] = 0;
147
1.55M
    for (len = 1; len < MAXBITS; len++)
148
1.45M
        offs[len + 1] = offs[len] + count[len];
149
150
    /* sort symbols by length, by symbol order within each length */
151
10.6M
    for (sym = 0; sym < codes; sym++)
152
10.5M
        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
103k
    switch (type) {
187
36.1k
    case CODES:
188
36.1k
        match = 20;
189
36.1k
        break;
190
33.9k
    case LENS:
191
33.9k
        base = lbase;
192
33.9k
        extra = lext;
193
33.9k
        match = 257;
194
33.9k
        break;
195
33.5k
    case DISTS:
196
33.5k
        base = dbase;
197
33.5k
        extra = dext;
198
103k
    }
199
200
    /* initialize state for loop */
201
103k
    huff = 0;                   /* starting code */
202
103k
    sym = 0;                    /* starting code symbol */
203
103k
    len = min;                  /* starting code length */
204
103k
    next = *table;              /* current table to fill in */
205
103k
    curr = root;                /* current table index bits */
206
103k
    drop = 0;                   /* current bits to drop from code for index */
207
103k
    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
208
103k
    used = 1U << root;          /* use root table entries */
209
103k
    mask = used - 1;            /* mask for comparing low */
210
211
    /* check available table space */
212
103k
    if ((type == LENS && used > ENOUGH_LENS) ||
213
103k
        (type == DISTS && used > ENOUGH_DISTS))
214
0
        return 1;
215
216
    /* process all codes and make table entries */
217
2.42M
    for (;;) {
218
        /* create table entry */
219
2.42M
        here.bits = (unsigned char)(len - drop);
220
2.42M
        if (work[sym] + 1U < match) {
221
1.74M
            here.op = (unsigned char)0;
222
1.74M
            here.val = work[sym];
223
1.74M
        }
224
682k
        else if (work[sym] >= match) {
225
648k
            here.op = (unsigned char)(extra[work[sym] - match]);
226
648k
            here.val = base[work[sym] - match];
227
648k
        }
228
33.9k
        else {
229
33.9k
            here.op = (unsigned char)(32 + 64);         /* end of block */
230
33.9k
            here.val = 0;
231
33.9k
        }
232
233
        /* replicate for those indices with low len bits equal to huff */
234
2.42M
        incr = 1U << (len - drop);
235
2.42M
        fill = 1U << curr;
236
2.42M
        min = fill;                 /* save offset to next table */
237
10.0M
        do {
238
10.0M
            fill -= incr;
239
10.0M
            next[(huff >> drop) + fill] = here;
240
10.0M
        } while (fill != 0);
241
242
        /* backwards increment the len-bit code huff */
243
2.42M
        incr = 1U << (len - 1);
244
4.74M
        while (huff & incr)
245
2.31M
            incr >>= 1;
246
2.42M
        if (incr != 0) {
247
2.31M
            huff &= incr - 1;
248
2.31M
            huff += incr;
249
2.31M
        }
250
103k
        else
251
103k
            huff = 0;
252
253
        /* go to next symbol, update count, len */
254
2.42M
        sym++;
255
2.42M
        if (--(count[len]) == 0) {
256
454k
            if (len == max) break;
257
351k
            len = lens[work[sym]];
258
351k
        }
259
260
        /* create new sub-table if needed */
261
2.31M
        if (len > root && (huff & mask) != low) {
262
            /* if first time, transition to sub-tables */
263
84.8k
            if (drop == 0)
264
11.4k
                drop = root;
265
266
            /* increment past last table */
267
84.8k
            next += min;            /* here min is 1 << curr */
268
269
            /* determine length of next table */
270
84.8k
            curr = len - drop;
271
84.8k
            left = (int)(1 << curr);
272
89.0k
            while (curr + drop < max) {
273
27.9k
                left -= count[curr + drop];
274
27.9k
                if (left <= 0) break;
275
4.20k
                curr++;
276
4.20k
                left <<= 1;
277
4.20k
            }
278
279
            /* check for enough space */
280
84.8k
            used += 1U << curr;
281
84.8k
            if ((type == LENS && used > ENOUGH_LENS) ||
282
84.8k
                (type == DISTS && used > ENOUGH_DISTS))
283
0
                return 1;
284
285
            /* point entry in root table to sub-table */
286
84.8k
            low = huff & mask;
287
84.8k
            (*table)[low].op = (unsigned char)curr;
288
84.8k
            (*table)[low].bits = (unsigned char)root;
289
84.8k
            (*table)[low].val = (unsigned short)(next - *table);
290
84.8k
        }
291
2.31M
    }
292
293
    /* fill in remaining table entry if code is incomplete (guaranteed to have
294
       at most one remaining entry, since if the code is incomplete, the
295
       maximum code length that was allowed to get this far is one bit) */
296
103k
    if (huff != 0) {
297
11
        here.op = (unsigned char)64;            /* invalid code marker */
298
11
        here.bits = (unsigned char)(len - drop);
299
11
        here.val = (unsigned short)0;
300
11
        next[huff] = here;
301
11
    }
302
303
    /* set return parameters */
304
103k
    *table += used;
305
103k
    *bits = root;
306
103k
    return 0;
307
103k
}
308
309
#ifdef BUILDFIXED
310
/*
311
  If this is compiled with BUILDFIXED defined, and if inflate will be used in
312
  multiple threads, and if atomics are not available, then inflate() must be
313
  called with a fixed block (e.g. 0x03 0x00) to initialize the tables and must
314
  return before any other threads are allowed to call inflate.
315
 */
316
317
static code *lenfix, *distfix;
318
static code fixed[544];
319
320
/* State for z_once(). */
321
local z_once_t built = Z_ONCE_INIT;
322
323
local void buildtables(void) {
324
    unsigned sym, bits;
325
    static code *next;
326
    unsigned short lens[288], work[288];
327
328
    /* literal/length table */
329
    sym = 0;
330
    while (sym < 144) lens[sym++] = 8;
331
    while (sym < 256) lens[sym++] = 9;
332
    while (sym < 280) lens[sym++] = 7;
333
    while (sym < 288) lens[sym++] = 8;
334
    next = fixed;
335
    lenfix = next;
336
    bits = 9;
337
    inflate_table(LENS, lens, 288, &(next), &(bits), work);
338
339
    /* distance table */
340
    sym = 0;
341
    while (sym < 32) lens[sym++] = 5;
342
    distfix = next;
343
    bits = 5;
344
    inflate_table(DISTS, lens, 32, &(next), &(bits), work);
345
}
346
#else /* !BUILDFIXED */
347
#  include "inffixed.h"
348
#endif /* BUILDFIXED */
349
350
/*
351
   Return state with length and distance decoding tables and index sizes set to
352
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
353
   If BUILDFIXED is defined, then instead this routine builds the tables the
354
   first time it's called, and returns those tables the first time and
355
   thereafter.  This reduces the size of the code by about 2K bytes, in
356
   exchange for a little execution time.  However, BUILDFIXED should not be
357
   used for threaded applications if atomics are not available, as it will
358
   not be thread-safe.
359
 */
360
42.2k
void inflate_fixed(struct inflate_state FAR *state) {
361
#ifdef BUILDFIXED
362
    z_once(&built, buildtables);
363
#endif /* BUILDFIXED */
364
42.2k
    state->lencode = lenfix;
365
42.2k
    state->lenbits = 9;
366
42.2k
    state->distcode = distfix;
367
42.2k
    state->distbits = 5;
368
42.2k
}
369
370
#ifdef MAKEFIXED
371
#include <stdio.h>
372
373
/*
374
   Write out the inffixed.h that will be #include'd above.  Defining MAKEFIXED
375
   also defines BUILDFIXED, so the tables are built on the fly.  main() writes
376
   those tables to stdout, which would directed to inffixed.h. Compile this
377
   along with zutil.c:
378
379
       cc -DMAKEFIXED -o fix inftrees.c zutil.c
380
       ./fix > inffixed.h
381
 */
382
int main(void) {
383
    unsigned low, size;
384
    struct inflate_state state;
385
386
    inflate_fixed(&state);
387
    puts("/* inffixed.h -- table for decoding fixed codes");
388
    puts(" * Generated automatically by makefixed().");
389
    puts(" */");
390
    puts("");
391
    puts("/* WARNING: this file should *not* be used by applications.");
392
    puts("   It is part of the implementation of this library and is");
393
    puts("   subject to change. Applications should only use zlib.h.");
394
    puts(" */");
395
    puts("");
396
    size = 1U << 9;
397
    printf("static const code lenfix[%u] = {", size);
398
    low = 0;
399
    for (;;) {
400
        if ((low % 7) == 0) printf("\n    ");
401
        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
402
               state.lencode[low].bits, state.lencode[low].val);
403
        if (++low == size) break;
404
        putchar(',');
405
    }
406
    puts("\n};");
407
    size = 1U << 5;
408
    printf("\nstatic const code distfix[%u] = {", size);
409
    low = 0;
410
    for (;;) {
411
        if ((low % 6) == 0) printf("\n    ");
412
        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
413
               state.distcode[low].val);
414
        if (++low == size) break;
415
        putchar(',');
416
    }
417
    puts("\n};");
418
    return 0;
419
}
420
#endif /* MAKEFIXED */