1/* inftrees.c -- generate Huffman trees for efficient decoding
2 * Copyright (C) 1995-1998 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include <linux/zutil.h>
7#include "inftrees.h"
8#include "infutil.h"
9
10static const char inflate_copyright[] =
11   " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
12/*
13  If you use the zlib library in a product, an acknowledgment is welcome
14  in the documentation of your product. If for some reason you cannot
15  include such an acknowledgment, I would appreciate that you keep this
16  copyright string in the executable of your product.
17 */
18struct internal_state;
19
20/* simplify the use of the inflate_huft type with some defines */
21#define exop word.what.Exop
22#define bits word.what.Bits
23
24
25local int huft_build OF((
26    uIntf *,            /* code lengths in bits */
27    uInt,               /* number of codes */
28    uInt,               /* number of "simple" codes */
29    const uIntf *,      /* list of base values for non-simple codes */
30    const uIntf *,      /* list of extra bits for non-simple codes */
31    inflate_huft * FAR*,/* result: starting table */
32    uIntf *,            /* maximum lookup bits (returns actual) */
33    inflate_huft *,     /* space for trees */
34    uInt *,             /* hufts used in space */
35    uIntf * ));         /* space for values */
36
37/* Tables for deflate from PKZIP's appnote.txt. */
38local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
39        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
40        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
41        /* see note #13 above about 258 */
42local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
43        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
44        3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
45local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
46        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
47        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
48        8193, 12289, 16385, 24577};
49local const uInt cpdext[30] = { /* Extra bits for distance codes */
50        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
51        7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
52        12, 12, 13, 13};
53
54/*
55   Huffman code decoding is performed using a multi-level table lookup.
56   The fastest way to decode is to simply build a lookup table whose
57   size is determined by the longest code.  However, the time it takes
58   to build this table can also be a factor if the data being decoded
59   is not very long.  The most common codes are necessarily the
60   shortest codes, so those codes dominate the decoding time, and hence
61   the speed.  The idea is you can have a shorter table that decodes the
62   shorter, more probable codes, and then point to subsidiary tables for
63   the longer codes.  The time it costs to decode the longer codes is
64   then traded against the time it takes to make longer tables.
65
66   This results of this trade are in the variables lbits and dbits
67   below.  lbits is the number of bits the first level table for literal/
68   length codes can decode in one step, and dbits is the same thing for
69   the distance codes.  Subsequent tables are also less than or equal to
70   those sizes.  These values may be adjusted either when all of the
71   codes are shorter than that, in which case the longest code length in
72   bits is used, or when the shortest code is *longer* than the requested
73   table size, in which case the length of the shortest code in bits is
74   used.
75
76   There are two different values for the two tables, since they code a
77   different number of possibilities each.  The literal/length table
78   codes 286 possible values, or in a flat code, a little over eight
79   bits.  The distance table codes 30 possible values, or a little less
80   than five bits, flat.  The optimum values for speed end up being
81   about one bit more than those, so lbits is 8+1 and dbits is 5+1.
82   The optimum values may differ though from machine to machine, and
83   possibly even between compilers.  Your mileage may vary.
84 */
85
86
87/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
88#define BMAX 15         /* maximum bit length of any code */
89
90local int huft_build(b, n, s, d, e, t, m, hp, hn, v)
91uIntf *b;               /* code lengths in bits (all assumed <= BMAX) */
92uInt n;                 /* number of codes (assumed <= 288) */
93uInt s;                 /* number of simple-valued codes (0..s-1) */
94const uIntf *d;         /* list of base values for non-simple codes */
95const uIntf *e;         /* list of extra bits for non-simple codes */
96inflate_huft * FAR *t;  /* result: starting table */
97uIntf *m;               /* maximum lookup bits, returns actual */
98inflate_huft *hp;       /* space for trees */
99uInt *hn;               /* hufts used in space */
100uIntf *v;               /* working area: values in order of bit length */
101/* Given a list of code lengths and a maximum table size, make a set of
102   tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
103   if the given code set is incomplete (the tables are still built in this
104   case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
105   lengths), or Z_MEM_ERROR if not enough memory. */
106{
107
108  uInt a;                       /* counter for codes of length k */
109  uInt c[BMAX+1];               /* bit length count table */
110  uInt f;                       /* i repeats in table every f entries */
111  int g;                        /* maximum code length */
112  int h;                        /* table level */
113  register uInt i;              /* counter, current code */
114  register uInt j;              /* counter */
115  register int k;               /* number of bits in current code */
116  int l;                        /* bits per table (returned in m) */
117  uInt mask;                    /* (1 << w) - 1, to avoid cc -O bug on HP */
118  register uIntf *p;            /* pointer into c[], b[], or v[] */
119  inflate_huft *q;              /* points to current table */
120  struct inflate_huft_s r;      /* table entry for structure assignment */
121  inflate_huft *u[BMAX];        /* table stack */
122  register int w;               /* bits before this table == (l * h) */
123  uInt x[BMAX+1];               /* bit offsets, then code stack */
124  uIntf *xp;                    /* pointer into x */
125  int y;                        /* number of dummy codes added */
126  uInt z;                       /* number of entries in current table */
127
128
129  /* Generate counts for each bit length */
130  p = c;
131#define C0 *p++ = 0;
132#define C2 C0 C0 C0 C0
133#define C4 C2 C2 C2 C2
134  C4                            /* clear c[]--assume BMAX+1 is 16 */
135  p = b;  i = n;
136  do {
137    c[*p++]++;                  /* assume all entries <= BMAX */
138  } while (--i);
139  if (c[0] == n)                /* null input--all zero length codes */
140  {
141    *t = (inflate_huft *)Z_NULL;
142    *m = 0;
143    return Z_OK;
144  }
145
146
147  /* Find minimum and maximum length, bound *m by those */
148  l = *m;
149  for (j = 1; j <= BMAX; j++)
150    if (c[j])
151      break;
152  k = j;                        /* minimum code length */
153  if ((uInt)l < j)
154    l = j;
155  for (i = BMAX; i; i--)
156    if (c[i])
157      break;
158  g = i;                        /* maximum code length */
159  if ((uInt)l > i)
160    l = i;
161  *m = l;
162
163
164  /* Adjust last length count to fill out codes, if needed */
165  for (y = 1 << j; j < i; j++, y <<= 1)
166    if ((y -= c[j]) < 0)
167      return Z_DATA_ERROR;
168  if ((y -= c[i]) < 0)
169    return Z_DATA_ERROR;
170  c[i] += y;
171
172
173  /* Generate starting offsets into the value table for each length */
174  x[1] = j = 0;
175  p = c + 1;  xp = x + 2;
176  while (--i) {                 /* note that i == g from above */
177    *xp++ = (j += *p++);
178  }
179
180
181  /* Make a table of values in order of bit lengths */
182  p = b;  i = 0;
183  do {
184    if ((j = *p++) != 0)
185      v[x[j]++] = i;
186  } while (++i < n);
187  n = x[g];                     /* set n to length of v */
188
189
190  /* Generate the Huffman codes and for each, make the table entries */
191  x[0] = i = 0;                 /* first Huffman code is zero */
192  p = v;                        /* grab values in bit order */
193  h = -1;                       /* no tables yet--level -1 */
194  w = -l;                       /* bits decoded == (l * h) */
195  u[0] = (inflate_huft *)Z_NULL;        /* just to keep compilers happy */
196  q = (inflate_huft *)Z_NULL;   /* ditto */
197  z = 0;                        /* ditto */
198
199  /* go through the bit lengths (k already is bits in shortest code) */
200  for (; k <= g; k++)
201  {
202    a = c[k];
203    while (a--)
204    {
205      /* here i is the Huffman code of length k bits for value *p */
206      /* make tables up to required level */
207      while (k > w + l)
208      {
209        h++;
210        w += l;                 /* previous table always l bits */
211
212        /* compute minimum size table less than or equal to l bits */
213        z = g - w;
214        z = z > (uInt)l ? l : z;        /* table size upper limit */
215        if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
216        {                       /* too few codes for k-w bit table */
217          f -= a + 1;           /* deduct codes from patterns left */
218          xp = c + k;
219          if (j < z)
220            while (++j < z)     /* try smaller tables up to z bits */
221            {
222              if ((f <<= 1) <= *++xp)
223                break;          /* enough codes to use up j bits */
224              f -= *xp;         /* else deduct codes from patterns */
225            }
226        }
227        z = 1 << j;             /* table entries for j-bit table */
228
229        /* allocate new table */
230        if (*hn + z > MANY)     /* (note: doesn't matter for fixed) */
231          return Z_MEM_ERROR;   /* not enough memory */
232        u[h] = q = hp + *hn;
233        *hn += z;
234
235        /* connect to last table, if there is one */
236        if (h)
237        {
238          x[h] = i;             /* save pattern for backing up */
239          r.bits = (Byte)l;     /* bits to dump before this table */
240          r.exop = (Byte)j;     /* bits in this table */
241          j = i >> (w - l);
242          r.base = (uInt)(q - u[h-1] - j);   /* offset to this table */
243          u[h-1][j] = r;        /* connect to last table */
244        }
245        else
246          *t = q;               /* first table is returned result */
247      }
248
249      /* set up table entry in r */
250      r.bits = (Byte)(k - w);
251      if (p >= v + n)
252        r.exop = 128 + 64;      /* out of values--invalid code */
253      else if (*p < s)
254      {
255        r.exop = (Byte)(*p < 256 ? 0 : 32 + 64);     /* 256 is end-of-block */
256        r.base = *p++;          /* simple code is just the value */
257      }
258      else
259      {
260        r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
261        r.base = d[*p++ - s];
262      }
263
264      /* fill code-like entries with r */
265      f = 1 << (k - w);
266      for (j = i >> w; j < z; j += f)
267        q[j] = r;
268
269      /* backwards increment the k-bit code i */
270      for (j = 1 << (k - 1); i & j; j >>= 1)
271        i ^= j;
272      i ^= j;
273
274      /* backup over finished tables */
275      mask = (1 << w) - 1;      /* needed on HP, cc -O bug */
276      while ((i & mask) != x[h])
277      {
278        h--;                    /* don't need to update q */
279        w -= l;
280        mask = (1 << w) - 1;
281      }
282    }
283  }
284
285
286  /* Return Z_BUF_ERROR if we were given an incomplete table */
287  return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
288}
289
290
291int zlib_inflate_trees_bits(c, bb, tb, hp, z)
292uIntf *c;               /* 19 code lengths */
293uIntf *bb;              /* bits tree desired/actual depth */
294inflate_huft * FAR *tb; /* bits tree result */
295inflate_huft *hp;       /* space for trees */
296z_streamp z;            /* for messages */
297{
298  int r;
299  uInt hn = 0;          /* hufts used in space */
300  uIntf *v;             /* work area for huft_build */
301
302  v = WS(z)->tree_work_area_1;
303  r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL,
304                 tb, bb, hp, &hn, v);
305  if (r == Z_DATA_ERROR)
306    z->msg = (char*)"oversubscribed dynamic bit lengths tree";
307  else if (r == Z_BUF_ERROR || *bb == 0)
308  {
309    z->msg = (char*)"incomplete dynamic bit lengths tree";
310    r = Z_DATA_ERROR;
311  }
312  return r;
313}
314
315int zlib_inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, hp, z)
316uInt nl;                /* number of literal/length codes */
317uInt nd;                /* number of distance codes */
318uIntf *c;               /* that many (total) code lengths */
319uIntf *bl;              /* literal desired/actual bit depth */
320uIntf *bd;              /* distance desired/actual bit depth */
321inflate_huft * FAR *tl; /* literal/length tree result */
322inflate_huft * FAR *td; /* distance tree result */
323inflate_huft *hp;       /* space for trees */
324z_streamp z;            /* for messages */
325{
326  int r;
327  uInt hn = 0;          /* hufts used in space */
328  uIntf *v;             /* work area for huft_build */
329
330  /* allocate work area */
331  v = WS(z)->tree_work_area_2;
332
333  /* build literal/length tree */
334  r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
335  if (r != Z_OK || *bl == 0)
336  {
337    if (r == Z_DATA_ERROR)
338      z->msg = (char*)"oversubscribed literal/length tree";
339    else if (r != Z_MEM_ERROR)
340    {
341      z->msg = (char*)"incomplete literal/length tree";
342      r = Z_DATA_ERROR;
343    }
344    return r;
345  }
346
347  /* build distance tree */
348  r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
349  if (r != Z_OK || (*bd == 0 && nl > 257))
350  {
351    if (r == Z_DATA_ERROR)
352      z->msg = (char*)"oversubscribed distance tree";
353    else if (r == Z_BUF_ERROR) {
354#ifdef PKZIP_BUG_WORKAROUND
355      r = Z_OK;
356    }
357#else
358      z->msg = (char*)"incomplete distance tree";
359      r = Z_DATA_ERROR;
360    }
361    else if (r != Z_MEM_ERROR)
362    {
363      z->msg = (char*)"empty distance tree with lengths";
364      r = Z_DATA_ERROR;
365    }
366    return r;
367#endif
368  }
369
370  /* done */
371  return Z_OK;
372}
373
374
375/* build fixed tables only once--keep them here */
376#include "inffixed.h"
377
378
379int zlib_inflate_trees_fixed(bl, bd, tl, td, z)
380uIntf *bl;               /* literal desired/actual bit depth */
381uIntf *bd;               /* distance desired/actual bit depth */
382inflate_huft * FAR *tl;  /* literal/length tree result */
383inflate_huft * FAR *td;  /* distance tree result */
384z_streamp z;             /* for memory allocation */
385{
386  *bl = fixed_bl;
387  *bd = fixed_bd;
388  *tl = fixed_tl;
389  *td = fixed_td;
390  return Z_OK;
391}
392