inftrees.c 13 KB

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