/* inftrees.c -- generate Huffman trees for efficient decoding1* Copyright (C) 1995-2024 Mark Adler2* For conditions of distribution and use, see copyright notice in zlib.h3*/45#include "zutil.h"6#include "inftrees.h"78#define MAXBITS 15910const char inflate_copyright[] =11" inflate 1.3.1 Copyright 1995-2024 Mark Adler ";12/*13If you use the zlib library in a product, an acknowledgment is welcome14in the documentation of your product. If for some reason you cannot15include such an acknowledgment, I would appreciate that you keep this16copyright string in the executable of your product.17*/1819/*20Build a set of tables to decode the provided canonical Huffman code.21The code lengths are lens[0..codes-1]. The result starts at *table,22whose indices are 0..2^bits-1. work is a writable array of at least23lens shorts, which is used as a work area. type is the type of code24to be generated, CODES, LENS, or DISTS. On return, zero is success,25-1 is an invalid code, and +1 means that ENOUGH isn't enough. table26on return points to the next available entry's address. bits is the27requested root table index bits, and on return it is the actual root28table index bits. It will differ if the request is greater than the29longest code or if it is less than the shortest code.30*/31int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,32unsigned codes, code FAR * FAR *table,33unsigned FAR *bits, unsigned short FAR *work) {34unsigned len; /* a code's length in bits */35unsigned sym; /* index of code symbols */36unsigned min, max; /* minimum and maximum code lengths */37unsigned root; /* number of index bits for root table */38unsigned curr; /* number of index bits for current table */39unsigned drop; /* code bits to drop for sub-table */40int left; /* number of prefix codes available */41unsigned used; /* code entries in table used */42unsigned huff; /* Huffman code */43unsigned incr; /* for incrementing code, index */44unsigned fill; /* index for replicating entries */45unsigned low; /* low bits for current root entry */46unsigned mask; /* mask for low root bits */47code here; /* table entry for duplication */48code FAR *next; /* next available space in table */49const unsigned short FAR *base; /* base value table to use */50const unsigned short FAR *extra; /* extra bits table to use */51unsigned match; /* use base and extra for symbol >= match */52unsigned short count[MAXBITS+1]; /* number of codes of each length */53unsigned short offs[MAXBITS+1]; /* offsets in table for each length */54static const unsigned short lbase[31] = { /* Length codes 257..285 base */553, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,5635, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};57static const unsigned short lext[31] = { /* Length codes 257..285 extra */5816, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,5919, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 203, 77};60static const unsigned short dbase[32] = { /* Distance codes 0..29 base */611, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,62257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,638193, 12289, 16385, 24577, 0, 0};64static const unsigned short dext[32] = { /* Distance codes 0..29 extra */6516, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,6623, 23, 24, 24, 25, 25, 26, 26, 27, 27,6728, 28, 29, 29, 64, 64};6869/*70Process a set of code lengths to create a canonical Huffman code. The71code lengths are lens[0..codes-1]. Each length corresponds to the72symbols 0..codes-1. The Huffman code is generated by first sorting the73symbols by length from short to long, and retaining the symbol order74for codes with equal lengths. Then the code starts with all zero bits75for the first code of the shortest length, and the codes are integer76increments for the same length, and zeros are appended as the length77increases. For the deflate format, these bits are stored backwards78from their more natural integer increment ordering, and so when the79decoding tables are built in the large loop below, the integer codes80are incremented backwards.8182This routine assumes, but does not check, that all of the entries in83lens[] are in the range 0..MAXBITS. The caller must assure this.841..MAXBITS is interpreted as that code length. zero means that that85symbol does not occur in this code.8687The codes are sorted by computing a count of codes for each length,88creating from that a table of starting indices for each length in the89sorted table, and then entering the symbols in order in the sorted90table. The sorted table is work[], with that space being provided by91the caller.9293The length counts are used for other purposes as well, i.e. finding94the minimum and maximum length codes, determining if there are any95codes at all, checking for a valid set of lengths, and looking ahead96at length counts to determine sub-table sizes when building the97decoding tables.98*/99100/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */101for (len = 0; len <= MAXBITS; len++)102count[len] = 0;103for (sym = 0; sym < codes; sym++)104count[lens[sym]]++;105106/* bound code lengths, force root to be within code lengths */107root = *bits;108for (max = MAXBITS; max >= 1; max--)109if (count[max] != 0) break;110if (root > max) root = max;111if (max == 0) { /* no symbols to code at all */112here.op = (unsigned char)64; /* invalid code marker */113here.bits = (unsigned char)1;114here.val = (unsigned short)0;115*(*table)++ = here; /* make a table to force an error */116*(*table)++ = here;117*bits = 1;118return 0; /* no symbols, but wait for decoding to report error */119}120for (min = 1; min < max; min++)121if (count[min] != 0) break;122if (root < min) root = min;123124/* check for an over-subscribed or incomplete set of lengths */125left = 1;126for (len = 1; len <= MAXBITS; len++) {127left <<= 1;128left -= count[len];129if (left < 0) return -1; /* over-subscribed */130}131if (left > 0 && (type == CODES || max != 1))132return -1; /* incomplete set */133134/* generate offsets into symbol table for each length for sorting */135offs[1] = 0;136for (len = 1; len < MAXBITS; len++)137offs[len + 1] = offs[len] + count[len];138139/* sort symbols by length, by symbol order within each length */140for (sym = 0; sym < codes; sym++)141if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;142143/*144Create and fill in decoding tables. In this loop, the table being145filled is at next and has curr index bits. The code being used is huff146with length len. That code is converted to an index by dropping drop147bits off of the bottom. For codes where len is less than drop + curr,148those top drop + curr - len bits are incremented through all values to149fill the table with replicated entries.150151root is the number of index bits for the root table. When len exceeds152root, sub-tables are created pointed to by the root entry with an index153of the low root bits of huff. This is saved in low to check for when a154new sub-table should be started. drop is zero when the root table is155being filled, and drop is root when sub-tables are being filled.156157When a new sub-table is needed, it is necessary to look ahead in the158code lengths to determine what size sub-table is needed. The length159counts are used for this, and so count[] is decremented as codes are160entered in the tables.161162used keeps track of how many table entries have been allocated from the163provided *table space. It is checked for LENS and DIST tables against164the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in165the initial root table size constants. See the comments in inftrees.h166for more information.167168sym increments through all symbols, and the loop terminates when169all codes of length max, i.e. all codes, have been processed. This170routine permits incomplete codes, so another loop after this one fills171in the rest of the decoding tables with invalid code markers.172*/173174/* set up for code type */175switch (type) {176case CODES:177base = extra = work; /* dummy value--not used */178match = 20;179break;180case LENS:181base = lbase;182extra = lext;183match = 257;184break;185default: /* DISTS */186base = dbase;187extra = dext;188match = 0;189}190191/* initialize state for loop */192huff = 0; /* starting code */193sym = 0; /* starting code symbol */194len = min; /* starting code length */195next = *table; /* current table to fill in */196curr = root; /* current table index bits */197drop = 0; /* current bits to drop from code for index */198low = (unsigned)(-1); /* trigger new sub-table when len > root */199used = 1U << root; /* use root table entries */200mask = used - 1; /* mask for comparing low */201202/* check available table space */203if ((type == LENS && used > ENOUGH_LENS) ||204(type == DISTS && used > ENOUGH_DISTS))205return 1;206207/* process all codes and make table entries */208for (;;) {209/* create table entry */210here.bits = (unsigned char)(len - drop);211if (work[sym] + 1U < match) {212here.op = (unsigned char)0;213here.val = work[sym];214}215else if (work[sym] >= match) {216here.op = (unsigned char)(extra[work[sym] - match]);217here.val = base[work[sym] - match];218}219else {220here.op = (unsigned char)(32 + 64); /* end of block */221here.val = 0;222}223224/* replicate for those indices with low len bits equal to huff */225incr = 1U << (len - drop);226fill = 1U << curr;227min = fill; /* save offset to next table */228do {229fill -= incr;230next[(huff >> drop) + fill] = here;231} while (fill != 0);232233/* backwards increment the len-bit code huff */234incr = 1U << (len - 1);235while (huff & incr)236incr >>= 1;237if (incr != 0) {238huff &= incr - 1;239huff += incr;240}241else242huff = 0;243244/* go to next symbol, update count, len */245sym++;246if (--(count[len]) == 0) {247if (len == max) break;248len = lens[work[sym]];249}250251/* create new sub-table if needed */252if (len > root && (huff & mask) != low) {253/* if first time, transition to sub-tables */254if (drop == 0)255drop = root;256257/* increment past last table */258next += min; /* here min is 1 << curr */259260/* determine length of next table */261curr = len - drop;262left = (int)(1 << curr);263while (curr + drop < max) {264left -= count[curr + drop];265if (left <= 0) break;266curr++;267left <<= 1;268}269270/* check for enough space */271used += 1U << curr;272if ((type == LENS && used > ENOUGH_LENS) ||273(type == DISTS && used > ENOUGH_DISTS))274return 1;275276/* point entry in root table to sub-table */277low = huff & mask;278(*table)[low].op = (unsigned char)curr;279(*table)[low].bits = (unsigned char)root;280(*table)[low].val = (unsigned short)(next - *table);281}282}283284/* fill in remaining table entry if code is incomplete (guaranteed to have285at most one remaining entry, since if the code is incomplete, the286maximum code length that was allowed to get this far is one bit) */287if (huff != 0) {288here.op = (unsigned char)64; /* invalid code marker */289here.bits = (unsigned char)(len - drop);290here.val = (unsigned short)0;291next[huff] = here;292}293294/* set return parameters */295*table += used;296*bits = root;297return 0;298}299300301