xref: /minix3/common/dist/zlib/contrib/puff/puff.c (revision 44bedb31d842b4b0444105519bcf929a69fe2dc1)
1*44bedb31SLionel Sambuc /*	$NetBSD: puff.c,v 1.1.1.1 2006/01/14 20:11:02 christos Exp $	*/
2*44bedb31SLionel Sambuc 
3*44bedb31SLionel Sambuc /*
4*44bedb31SLionel Sambuc  * puff.c
5*44bedb31SLionel Sambuc  * Copyright (C) 2002-2004 Mark Adler
6*44bedb31SLionel Sambuc  * For conditions of distribution and use, see copyright notice in puff.h
7*44bedb31SLionel Sambuc  * version 1.8, 9 Jan 2004
8*44bedb31SLionel Sambuc  *
9*44bedb31SLionel Sambuc  * puff.c is a simple inflate written to be an unambiguous way to specify the
10*44bedb31SLionel Sambuc  * deflate format.  It is not written for speed but rather simplicity.  As a
11*44bedb31SLionel Sambuc  * side benefit, this code might actually be useful when small code is more
12*44bedb31SLionel Sambuc  * important than speed, such as bootstrap applications.  For typical deflate
13*44bedb31SLionel Sambuc  * data, zlib's inflate() is about four times as fast as puff().  zlib's
14*44bedb31SLionel Sambuc  * inflate compiles to around 20K on my machine, whereas puff.c compiles to
15*44bedb31SLionel Sambuc  * around 4K on my machine (a PowerPC using GNU cc).  If the faster decode()
16*44bedb31SLionel Sambuc  * function here is used, then puff() is only twice as slow as zlib's
17*44bedb31SLionel Sambuc  * inflate().
18*44bedb31SLionel Sambuc  *
19*44bedb31SLionel Sambuc  * All dynamically allocated memory comes from the stack.  The stack required
20*44bedb31SLionel Sambuc  * is less than 2K bytes.  This code is compatible with 16-bit int's and
21*44bedb31SLionel Sambuc  * assumes that long's are at least 32 bits.  puff.c uses the short data type,
22*44bedb31SLionel Sambuc  * assumed to be 16 bits, for arrays in order to to conserve memory.  The code
23*44bedb31SLionel Sambuc  * works whether integers are stored big endian or little endian.
24*44bedb31SLionel Sambuc  *
25*44bedb31SLionel Sambuc  * In the comments below are "Format notes" that describe the inflate process
26*44bedb31SLionel Sambuc  * and document some of the less obvious aspects of the format.  This source
27*44bedb31SLionel Sambuc  * code is meant to supplement RFC 1951, which formally describes the deflate
28*44bedb31SLionel Sambuc  * format:
29*44bedb31SLionel Sambuc  *
30*44bedb31SLionel Sambuc  *    http://www.zlib.org/rfc-deflate.html
31*44bedb31SLionel Sambuc  */
32*44bedb31SLionel Sambuc 
33*44bedb31SLionel Sambuc /*
34*44bedb31SLionel Sambuc  * Change history:
35*44bedb31SLionel Sambuc  *
36*44bedb31SLionel Sambuc  * 1.0  10 Feb 2002     - First version
37*44bedb31SLionel Sambuc  * 1.1  17 Feb 2002     - Clarifications of some comments and notes
38*44bedb31SLionel Sambuc  *                      - Update puff() dest and source pointers on negative
39*44bedb31SLionel Sambuc  *                        errors to facilitate debugging deflators
40*44bedb31SLionel Sambuc  *                      - Remove longest from struct huffman -- not needed
41*44bedb31SLionel Sambuc  *                      - Simplify offs[] index in construct()
42*44bedb31SLionel Sambuc  *                      - Add input size and checking, using longjmp() to
43*44bedb31SLionel Sambuc  *                        maintain easy readability
44*44bedb31SLionel Sambuc  *                      - Use short data type for large arrays
45*44bedb31SLionel Sambuc  *                      - Use pointers instead of long to specify source and
46*44bedb31SLionel Sambuc  *                        destination sizes to avoid arbitrary 4 GB limits
47*44bedb31SLionel Sambuc  * 1.2  17 Mar 2002     - Add faster version of decode(), doubles speed (!),
48*44bedb31SLionel Sambuc  *                        but leave simple version for readabilty
49*44bedb31SLionel Sambuc  *                      - Make sure invalid distances detected if pointers
50*44bedb31SLionel Sambuc  *                        are 16 bits
51*44bedb31SLionel Sambuc  *                      - Fix fixed codes table error
52*44bedb31SLionel Sambuc  *                      - Provide a scanning mode for determining size of
53*44bedb31SLionel Sambuc  *                        uncompressed data
54*44bedb31SLionel Sambuc  * 1.3  20 Mar 2002     - Go back to lengths for puff() parameters [Jean-loup]
55*44bedb31SLionel Sambuc  *                      - Add a puff.h file for the interface
56*44bedb31SLionel Sambuc  *                      - Add braces in puff() for else do [Jean-loup]
57*44bedb31SLionel Sambuc  *                      - Use indexes instead of pointers for readability
58*44bedb31SLionel Sambuc  * 1.4  31 Mar 2002     - Simplify construct() code set check
59*44bedb31SLionel Sambuc  *                      - Fix some comments
60*44bedb31SLionel Sambuc  *                      - Add FIXLCODES #define
61*44bedb31SLionel Sambuc  * 1.5   6 Apr 2002     - Minor comment fixes
62*44bedb31SLionel Sambuc  * 1.6   7 Aug 2002     - Minor format changes
63*44bedb31SLionel Sambuc  * 1.7   3 Mar 2003     - Added test code for distribution
64*44bedb31SLionel Sambuc  *                      - Added zlib-like license
65*44bedb31SLionel Sambuc  * 1.8   9 Jan 2004     - Added some comments on no distance codes case
66*44bedb31SLionel Sambuc  */
67*44bedb31SLionel Sambuc 
68*44bedb31SLionel Sambuc #include <setjmp.h>             /* for setjmp(), longjmp(), and jmp_buf */
69*44bedb31SLionel Sambuc #include "puff.h"               /* prototype for puff() */
70*44bedb31SLionel Sambuc 
71*44bedb31SLionel Sambuc #define local static            /* for local function definitions */
72*44bedb31SLionel Sambuc #define NIL ((unsigned char *)0)        /* for no output option */
73*44bedb31SLionel Sambuc 
74*44bedb31SLionel Sambuc /*
75*44bedb31SLionel Sambuc  * Maximums for allocations and loops.  It is not useful to change these --
76*44bedb31SLionel Sambuc  * they are fixed by the deflate format.
77*44bedb31SLionel Sambuc  */
78*44bedb31SLionel Sambuc #define MAXBITS 15              /* maximum bits in a code */
79*44bedb31SLionel Sambuc #define MAXLCODES 286           /* maximum number of literal/length codes */
80*44bedb31SLionel Sambuc #define MAXDCODES 30            /* maximum number of distance codes */
81*44bedb31SLionel Sambuc #define MAXCODES (MAXLCODES+MAXDCODES)  /* maximum codes lengths to read */
82*44bedb31SLionel Sambuc #define FIXLCODES 288           /* number of fixed literal/length codes */
83*44bedb31SLionel Sambuc 
84*44bedb31SLionel Sambuc /* input and output state */
85*44bedb31SLionel Sambuc struct state {
86*44bedb31SLionel Sambuc     /* output state */
87*44bedb31SLionel Sambuc     unsigned char *out;         /* output buffer */
88*44bedb31SLionel Sambuc     unsigned long outlen;       /* available space at out */
89*44bedb31SLionel Sambuc     unsigned long outcnt;       /* bytes written to out so far */
90*44bedb31SLionel Sambuc 
91*44bedb31SLionel Sambuc     /* input state */
92*44bedb31SLionel Sambuc     unsigned char *in;          /* input buffer */
93*44bedb31SLionel Sambuc     unsigned long inlen;        /* available input at in */
94*44bedb31SLionel Sambuc     unsigned long incnt;        /* bytes read so far */
95*44bedb31SLionel Sambuc     int bitbuf;                 /* bit buffer */
96*44bedb31SLionel Sambuc     int bitcnt;                 /* number of bits in bit buffer */
97*44bedb31SLionel Sambuc 
98*44bedb31SLionel Sambuc     /* input limit error return state for bits() and decode() */
99*44bedb31SLionel Sambuc     jmp_buf env;
100*44bedb31SLionel Sambuc };
101*44bedb31SLionel Sambuc 
102*44bedb31SLionel Sambuc /*
103*44bedb31SLionel Sambuc  * Return need bits from the input stream.  This always leaves less than
104*44bedb31SLionel Sambuc  * eight bits in the buffer.  bits() works properly for need == 0.
105*44bedb31SLionel Sambuc  *
106*44bedb31SLionel Sambuc  * Format notes:
107*44bedb31SLionel Sambuc  *
108*44bedb31SLionel Sambuc  * - Bits are stored in bytes from the least significant bit to the most
109*44bedb31SLionel Sambuc  *   significant bit.  Therefore bits are dropped from the bottom of the bit
110*44bedb31SLionel Sambuc  *   buffer, using shift right, and new bytes are appended to the top of the
111*44bedb31SLionel Sambuc  *   bit buffer, using shift left.
112*44bedb31SLionel Sambuc  */
bits(struct state * s,int need)113*44bedb31SLionel Sambuc local int bits(struct state *s, int need)
114*44bedb31SLionel Sambuc {
115*44bedb31SLionel Sambuc     long val;           /* bit accumulator (can use up to 20 bits) */
116*44bedb31SLionel Sambuc 
117*44bedb31SLionel Sambuc     /* load at least need bits into val */
118*44bedb31SLionel Sambuc     val = s->bitbuf;
119*44bedb31SLionel Sambuc     while (s->bitcnt < need) {
120*44bedb31SLionel Sambuc         if (s->incnt == s->inlen) longjmp(s->env, 1);   /* out of input */
121*44bedb31SLionel Sambuc         val |= (long)(s->in[s->incnt++]) << s->bitcnt;  /* load eight bits */
122*44bedb31SLionel Sambuc         s->bitcnt += 8;
123*44bedb31SLionel Sambuc     }
124*44bedb31SLionel Sambuc 
125*44bedb31SLionel Sambuc     /* drop need bits and update buffer, always zero to seven bits left */
126*44bedb31SLionel Sambuc     s->bitbuf = (int)(val >> need);
127*44bedb31SLionel Sambuc     s->bitcnt -= need;
128*44bedb31SLionel Sambuc 
129*44bedb31SLionel Sambuc     /* return need bits, zeroing the bits above that */
130*44bedb31SLionel Sambuc     return (int)(val & ((1L << need) - 1));
131*44bedb31SLionel Sambuc }
132*44bedb31SLionel Sambuc 
133*44bedb31SLionel Sambuc /*
134*44bedb31SLionel Sambuc  * Process a stored block.
135*44bedb31SLionel Sambuc  *
136*44bedb31SLionel Sambuc  * Format notes:
137*44bedb31SLionel Sambuc  *
138*44bedb31SLionel Sambuc  * - After the two-bit stored block type (00), the stored block length and
139*44bedb31SLionel Sambuc  *   stored bytes are byte-aligned for fast copying.  Therefore any leftover
140*44bedb31SLionel Sambuc  *   bits in the byte that has the last bit of the type, as many as seven, are
141*44bedb31SLionel Sambuc  *   discarded.  The value of the discarded bits are not defined and should not
142*44bedb31SLionel Sambuc  *   be checked against any expectation.
143*44bedb31SLionel Sambuc  *
144*44bedb31SLionel Sambuc  * - The second inverted copy of the stored block length does not have to be
145*44bedb31SLionel Sambuc  *   checked, but it's probably a good idea to do so anyway.
146*44bedb31SLionel Sambuc  *
147*44bedb31SLionel Sambuc  * - A stored block can have zero length.  This is sometimes used to byte-align
148*44bedb31SLionel Sambuc  *   subsets of the compressed data for random access or partial recovery.
149*44bedb31SLionel Sambuc  */
stored(struct state * s)150*44bedb31SLionel Sambuc local int stored(struct state *s)
151*44bedb31SLionel Sambuc {
152*44bedb31SLionel Sambuc     unsigned len;       /* length of stored block */
153*44bedb31SLionel Sambuc 
154*44bedb31SLionel Sambuc     /* discard leftover bits from current byte (assumes s->bitcnt < 8) */
155*44bedb31SLionel Sambuc     s->bitbuf = 0;
156*44bedb31SLionel Sambuc     s->bitcnt = 0;
157*44bedb31SLionel Sambuc 
158*44bedb31SLionel Sambuc     /* get length and check against its one's complement */
159*44bedb31SLionel Sambuc     if (s->incnt + 4 > s->inlen) return 2;      /* not enough input */
160*44bedb31SLionel Sambuc     len = s->in[s->incnt++];
161*44bedb31SLionel Sambuc     len |= s->in[s->incnt++] << 8;
162*44bedb31SLionel Sambuc     if (s->in[s->incnt++] != (~len & 0xff) ||
163*44bedb31SLionel Sambuc         s->in[s->incnt++] != ((~len >> 8) & 0xff))
164*44bedb31SLionel Sambuc         return -2;                              /* didn't match complement! */
165*44bedb31SLionel Sambuc 
166*44bedb31SLionel Sambuc     /* copy len bytes from in to out */
167*44bedb31SLionel Sambuc     if (s->incnt + len > s->inlen) return 2;    /* not enough input */
168*44bedb31SLionel Sambuc     if (s->out != NIL) {
169*44bedb31SLionel Sambuc         if (s->outcnt + len > s->outlen)
170*44bedb31SLionel Sambuc             return 1;                           /* not enough output space */
171*44bedb31SLionel Sambuc         while (len--)
172*44bedb31SLionel Sambuc             s->out[s->outcnt++] = s->in[s->incnt++];
173*44bedb31SLionel Sambuc     }
174*44bedb31SLionel Sambuc     else {                                      /* just scanning */
175*44bedb31SLionel Sambuc         s->outcnt += len;
176*44bedb31SLionel Sambuc         s->incnt += len;
177*44bedb31SLionel Sambuc     }
178*44bedb31SLionel Sambuc 
179*44bedb31SLionel Sambuc     /* done with a valid stored block */
180*44bedb31SLionel Sambuc     return 0;
181*44bedb31SLionel Sambuc }
182*44bedb31SLionel Sambuc 
183*44bedb31SLionel Sambuc /*
184*44bedb31SLionel Sambuc  * Huffman code decoding tables.  count[1..MAXBITS] is the number of symbols of
185*44bedb31SLionel Sambuc  * each length, which for a canonical code are stepped through in order.
186*44bedb31SLionel Sambuc  * symbol[] are the symbol values in canonical order, where the number of
187*44bedb31SLionel Sambuc  * entries is the sum of the counts in count[].  The decoding process can be
188*44bedb31SLionel Sambuc  * seen in the function decode() below.
189*44bedb31SLionel Sambuc  */
190*44bedb31SLionel Sambuc struct huffman {
191*44bedb31SLionel Sambuc     short *count;       /* number of symbols of each length */
192*44bedb31SLionel Sambuc     short *symbol;      /* canonically ordered symbols */
193*44bedb31SLionel Sambuc };
194*44bedb31SLionel Sambuc 
195*44bedb31SLionel Sambuc /*
196*44bedb31SLionel Sambuc  * Decode a code from the stream s using huffman table h.  Return the symbol or
197*44bedb31SLionel Sambuc  * a negative value if there is an error.  If all of the lengths are zero, i.e.
198*44bedb31SLionel Sambuc  * an empty code, or if the code is incomplete and an invalid code is received,
199*44bedb31SLionel Sambuc  * then -9 is returned after reading MAXBITS bits.
200*44bedb31SLionel Sambuc  *
201*44bedb31SLionel Sambuc  * Format notes:
202*44bedb31SLionel Sambuc  *
203*44bedb31SLionel Sambuc  * - The codes as stored in the compressed data are bit-reversed relative to
204*44bedb31SLionel Sambuc  *   a simple integer ordering of codes of the same lengths.  Hence below the
205*44bedb31SLionel Sambuc  *   bits are pulled from the compressed data one at a time and used to
206*44bedb31SLionel Sambuc  *   build the code value reversed from what is in the stream in order to
207*44bedb31SLionel Sambuc  *   permit simple integer comparisons for decoding.  A table-based decoding
208*44bedb31SLionel Sambuc  *   scheme (as used in zlib) does not need to do this reversal.
209*44bedb31SLionel Sambuc  *
210*44bedb31SLionel Sambuc  * - The first code for the shortest length is all zeros.  Subsequent codes of
211*44bedb31SLionel Sambuc  *   the same length are simply integer increments of the previous code.  When
212*44bedb31SLionel Sambuc  *   moving up a length, a zero bit is appended to the code.  For a complete
213*44bedb31SLionel Sambuc  *   code, the last code of the longest length will be all ones.
214*44bedb31SLionel Sambuc  *
215*44bedb31SLionel Sambuc  * - Incomplete codes are handled by this decoder, since they are permitted
216*44bedb31SLionel Sambuc  *   in the deflate format.  See the format notes for fixed() and dynamic().
217*44bedb31SLionel Sambuc  */
218*44bedb31SLionel Sambuc #ifdef SLOW
decode(struct state * s,struct huffman * h)219*44bedb31SLionel Sambuc local int decode(struct state *s, struct huffman *h)
220*44bedb31SLionel Sambuc {
221*44bedb31SLionel Sambuc     int len;            /* current number of bits in code */
222*44bedb31SLionel Sambuc     int code;           /* len bits being decoded */
223*44bedb31SLionel Sambuc     int first;          /* first code of length len */
224*44bedb31SLionel Sambuc     int count;          /* number of codes of length len */
225*44bedb31SLionel Sambuc     int index;          /* index of first code of length len in symbol table */
226*44bedb31SLionel Sambuc 
227*44bedb31SLionel Sambuc     code = first = index = 0;
228*44bedb31SLionel Sambuc     for (len = 1; len <= MAXBITS; len++) {
229*44bedb31SLionel Sambuc         code |= bits(s, 1);             /* get next bit */
230*44bedb31SLionel Sambuc         count = h->count[len];
231*44bedb31SLionel Sambuc         if (code < first + count)       /* if length len, return symbol */
232*44bedb31SLionel Sambuc             return h->symbol[index + (code - first)];
233*44bedb31SLionel Sambuc         index += count;                 /* else update for next length */
234*44bedb31SLionel Sambuc         first += count;
235*44bedb31SLionel Sambuc         first <<= 1;
236*44bedb31SLionel Sambuc         code <<= 1;
237*44bedb31SLionel Sambuc     }
238*44bedb31SLionel Sambuc     return -9;                          /* ran out of codes */
239*44bedb31SLionel Sambuc }
240*44bedb31SLionel Sambuc 
241*44bedb31SLionel Sambuc /*
242*44bedb31SLionel Sambuc  * A faster version of decode() for real applications of this code.   It's not
243*44bedb31SLionel Sambuc  * as readable, but it makes puff() twice as fast.  And it only makes the code
244*44bedb31SLionel Sambuc  * a few percent larger.
245*44bedb31SLionel Sambuc  */
246*44bedb31SLionel Sambuc #else /* !SLOW */
decode(struct state * s,struct huffman * h)247*44bedb31SLionel Sambuc local int decode(struct state *s, struct huffman *h)
248*44bedb31SLionel Sambuc {
249*44bedb31SLionel Sambuc     int len;            /* current number of bits in code */
250*44bedb31SLionel Sambuc     int code;           /* len bits being decoded */
251*44bedb31SLionel Sambuc     int first;          /* first code of length len */
252*44bedb31SLionel Sambuc     int count;          /* number of codes of length len */
253*44bedb31SLionel Sambuc     int index;          /* index of first code of length len in symbol table */
254*44bedb31SLionel Sambuc     int bitbuf;         /* bits from stream */
255*44bedb31SLionel Sambuc     int left;           /* bits left in next or left to process */
256*44bedb31SLionel Sambuc     short *next;        /* next number of codes */
257*44bedb31SLionel Sambuc 
258*44bedb31SLionel Sambuc     bitbuf = s->bitbuf;
259*44bedb31SLionel Sambuc     left = s->bitcnt;
260*44bedb31SLionel Sambuc     code = first = index = 0;
261*44bedb31SLionel Sambuc     len = 1;
262*44bedb31SLionel Sambuc     next = h->count + 1;
263*44bedb31SLionel Sambuc     while (1) {
264*44bedb31SLionel Sambuc         while (left--) {
265*44bedb31SLionel Sambuc             code |= bitbuf & 1;
266*44bedb31SLionel Sambuc             bitbuf >>= 1;
267*44bedb31SLionel Sambuc             count = *next++;
268*44bedb31SLionel Sambuc             if (code < first + count) { /* if length len, return symbol */
269*44bedb31SLionel Sambuc                 s->bitbuf = bitbuf;
270*44bedb31SLionel Sambuc                 s->bitcnt = (s->bitcnt - len) & 7;
271*44bedb31SLionel Sambuc                 return h->symbol[index + (code - first)];
272*44bedb31SLionel Sambuc             }
273*44bedb31SLionel Sambuc             index += count;             /* else update for next length */
274*44bedb31SLionel Sambuc             first += count;
275*44bedb31SLionel Sambuc             first <<= 1;
276*44bedb31SLionel Sambuc             code <<= 1;
277*44bedb31SLionel Sambuc             len++;
278*44bedb31SLionel Sambuc         }
279*44bedb31SLionel Sambuc         left = (MAXBITS+1) - len;
280*44bedb31SLionel Sambuc         if (left == 0) break;
281*44bedb31SLionel Sambuc         if (s->incnt == s->inlen) longjmp(s->env, 1);   /* out of input */
282*44bedb31SLionel Sambuc         bitbuf = s->in[s->incnt++];
283*44bedb31SLionel Sambuc         if (left > 8) left = 8;
284*44bedb31SLionel Sambuc     }
285*44bedb31SLionel Sambuc     return -9;                          /* ran out of codes */
286*44bedb31SLionel Sambuc }
287*44bedb31SLionel Sambuc #endif /* SLOW */
288*44bedb31SLionel Sambuc 
289*44bedb31SLionel Sambuc /*
290*44bedb31SLionel Sambuc  * Given the list of code lengths length[0..n-1] representing a canonical
291*44bedb31SLionel Sambuc  * Huffman code for n symbols, construct the tables required to decode those
292*44bedb31SLionel Sambuc  * codes.  Those tables are the number of codes of each length, and the symbols
293*44bedb31SLionel Sambuc  * sorted by length, retaining their original order within each length.  The
294*44bedb31SLionel Sambuc  * return value is zero for a complete code set, negative for an over-
295*44bedb31SLionel Sambuc  * subscribed code set, and positive for an incomplete code set.  The tables
296*44bedb31SLionel Sambuc  * can be used if the return value is zero or positive, but they cannot be used
297*44bedb31SLionel Sambuc  * if the return value is negative.  If the return value is zero, it is not
298*44bedb31SLionel Sambuc  * possible for decode() using that table to return an error--any stream of
299*44bedb31SLionel Sambuc  * enough bits will resolve to a symbol.  If the return value is positive, then
300*44bedb31SLionel Sambuc  * it is possible for decode() using that table to return an error for received
301*44bedb31SLionel Sambuc  * codes past the end of the incomplete lengths.
302*44bedb31SLionel Sambuc  *
303*44bedb31SLionel Sambuc  * Not used by decode(), but used for error checking, h->count[0] is the number
304*44bedb31SLionel Sambuc  * of the n symbols not in the code.  So n - h->count[0] is the number of
305*44bedb31SLionel Sambuc  * codes.  This is useful for checking for incomplete codes that have more than
306*44bedb31SLionel Sambuc  * one symbol, which is an error in a dynamic block.
307*44bedb31SLionel Sambuc  *
308*44bedb31SLionel Sambuc  * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS
309*44bedb31SLionel Sambuc  * This is assured by the construction of the length arrays in dynamic() and
310*44bedb31SLionel Sambuc  * fixed() and is not verified by construct().
311*44bedb31SLionel Sambuc  *
312*44bedb31SLionel Sambuc  * Format notes:
313*44bedb31SLionel Sambuc  *
314*44bedb31SLionel Sambuc  * - Permitted and expected examples of incomplete codes are one of the fixed
315*44bedb31SLionel Sambuc  *   codes and any code with a single symbol which in deflate is coded as one
316*44bedb31SLionel Sambuc  *   bit instead of zero bits.  See the format notes for fixed() and dynamic().
317*44bedb31SLionel Sambuc  *
318*44bedb31SLionel Sambuc  * - Within a given code length, the symbols are kept in ascending order for
319*44bedb31SLionel Sambuc  *   the code bits definition.
320*44bedb31SLionel Sambuc  */
construct(struct huffman * h,short * length,int n)321*44bedb31SLionel Sambuc local int construct(struct huffman *h, short *length, int n)
322*44bedb31SLionel Sambuc {
323*44bedb31SLionel Sambuc     int symbol;         /* current symbol when stepping through length[] */
324*44bedb31SLionel Sambuc     int len;            /* current length when stepping through h->count[] */
325*44bedb31SLionel Sambuc     int left;           /* number of possible codes left of current length */
326*44bedb31SLionel Sambuc     short offs[MAXBITS+1];      /* offsets in symbol table for each length */
327*44bedb31SLionel Sambuc 
328*44bedb31SLionel Sambuc     /* count number of codes of each length */
329*44bedb31SLionel Sambuc     for (len = 0; len <= MAXBITS; len++)
330*44bedb31SLionel Sambuc         h->count[len] = 0;
331*44bedb31SLionel Sambuc     for (symbol = 0; symbol < n; symbol++)
332*44bedb31SLionel Sambuc         (h->count[length[symbol]])++;   /* assumes lengths are within bounds */
333*44bedb31SLionel Sambuc     if (h->count[0] == n)               /* no codes! */
334*44bedb31SLionel Sambuc         return 0;                       /* complete, but decode() will fail */
335*44bedb31SLionel Sambuc 
336*44bedb31SLionel Sambuc     /* check for an over-subscribed or incomplete set of lengths */
337*44bedb31SLionel Sambuc     left = 1;                           /* one possible code of zero length */
338*44bedb31SLionel Sambuc     for (len = 1; len <= MAXBITS; len++) {
339*44bedb31SLionel Sambuc         left <<= 1;                     /* one more bit, double codes left */
340*44bedb31SLionel Sambuc         left -= h->count[len];          /* deduct count from possible codes */
341*44bedb31SLionel Sambuc         if (left < 0) return left;      /* over-subscribed--return negative */
342*44bedb31SLionel Sambuc     }                                   /* left > 0 means incomplete */
343*44bedb31SLionel Sambuc 
344*44bedb31SLionel Sambuc     /* generate offsets into symbol table for each length for sorting */
345*44bedb31SLionel Sambuc     offs[1] = 0;
346*44bedb31SLionel Sambuc     for (len = 1; len < MAXBITS; len++)
347*44bedb31SLionel Sambuc         offs[len + 1] = offs[len] + h->count[len];
348*44bedb31SLionel Sambuc 
349*44bedb31SLionel Sambuc     /*
350*44bedb31SLionel Sambuc      * put symbols in table sorted by length, by symbol order within each
351*44bedb31SLionel Sambuc      * length
352*44bedb31SLionel Sambuc      */
353*44bedb31SLionel Sambuc     for (symbol = 0; symbol < n; symbol++)
354*44bedb31SLionel Sambuc         if (length[symbol] != 0)
355*44bedb31SLionel Sambuc             h->symbol[offs[length[symbol]]++] = symbol;
356*44bedb31SLionel Sambuc 
357*44bedb31SLionel Sambuc     /* return zero for complete set, positive for incomplete set */
358*44bedb31SLionel Sambuc     return left;
359*44bedb31SLionel Sambuc }
360*44bedb31SLionel Sambuc 
361*44bedb31SLionel Sambuc /*
362*44bedb31SLionel Sambuc  * Decode literal/length and distance codes until an end-of-block code.
363*44bedb31SLionel Sambuc  *
364*44bedb31SLionel Sambuc  * Format notes:
365*44bedb31SLionel Sambuc  *
366*44bedb31SLionel Sambuc  * - Compressed data that is after the block type if fixed or after the code
367*44bedb31SLionel Sambuc  *   description if dynamic is a combination of literals and length/distance
368*44bedb31SLionel Sambuc  *   pairs terminated by and end-of-block code.  Literals are simply Huffman
369*44bedb31SLionel Sambuc  *   coded bytes.  A length/distance pair is a coded length followed by a
370*44bedb31SLionel Sambuc  *   coded distance to represent a string that occurs earlier in the
371*44bedb31SLionel Sambuc  *   uncompressed data that occurs again at the current location.
372*44bedb31SLionel Sambuc  *
373*44bedb31SLionel Sambuc  * - Literals, lengths, and the end-of-block code are combined into a single
374*44bedb31SLionel Sambuc  *   code of up to 286 symbols.  They are 256 literals (0..255), 29 length
375*44bedb31SLionel Sambuc  *   symbols (257..285), and the end-of-block symbol (256).
376*44bedb31SLionel Sambuc  *
377*44bedb31SLionel Sambuc  * - There are 256 possible lengths (3..258), and so 29 symbols are not enough
378*44bedb31SLionel Sambuc  *   to represent all of those.  Lengths 3..10 and 258 are in fact represented
379*44bedb31SLionel Sambuc  *   by just a length symbol.  Lengths 11..257 are represented as a symbol and
380*44bedb31SLionel Sambuc  *   some number of extra bits that are added as an integer to the base length
381*44bedb31SLionel Sambuc  *   of the length symbol.  The number of extra bits is determined by the base
382*44bedb31SLionel Sambuc  *   length symbol.  These are in the static arrays below, lens[] for the base
383*44bedb31SLionel Sambuc  *   lengths and lext[] for the corresponding number of extra bits.
384*44bedb31SLionel Sambuc  *
385*44bedb31SLionel Sambuc  * - The reason that 258 gets its own symbol is that the longest length is used
386*44bedb31SLionel Sambuc  *   often in highly redundant files.  Note that 258 can also be coded as the
387*44bedb31SLionel Sambuc  *   base value 227 plus the maximum extra value of 31.  While a good deflate
388*44bedb31SLionel Sambuc  *   should never do this, it is not an error, and should be decoded properly.
389*44bedb31SLionel Sambuc  *
390*44bedb31SLionel Sambuc  * - If a length is decoded, including its extra bits if any, then it is
391*44bedb31SLionel Sambuc  *   followed a distance code.  There are up to 30 distance symbols.  Again
392*44bedb31SLionel Sambuc  *   there are many more possible distances (1..32768), so extra bits are added
393*44bedb31SLionel Sambuc  *   to a base value represented by the symbol.  The distances 1..4 get their
394*44bedb31SLionel Sambuc  *   own symbol, but the rest require extra bits.  The base distances and
395*44bedb31SLionel Sambuc  *   corresponding number of extra bits are below in the static arrays dist[]
396*44bedb31SLionel Sambuc  *   and dext[].
397*44bedb31SLionel Sambuc  *
398*44bedb31SLionel Sambuc  * - Literal bytes are simply written to the output.  A length/distance pair is
399*44bedb31SLionel Sambuc  *   an instruction to copy previously uncompressed bytes to the output.  The
400*44bedb31SLionel Sambuc  *   copy is from distance bytes back in the output stream, copying for length
401*44bedb31SLionel Sambuc  *   bytes.
402*44bedb31SLionel Sambuc  *
403*44bedb31SLionel Sambuc  * - Distances pointing before the beginning of the output data are not
404*44bedb31SLionel Sambuc  *   permitted.
405*44bedb31SLionel Sambuc  *
406*44bedb31SLionel Sambuc  * - Overlapped copies, where the length is greater than the distance, are
407*44bedb31SLionel Sambuc  *   allowed and common.  For example, a distance of one and a length of 258
408*44bedb31SLionel Sambuc  *   simply copies the last byte 258 times.  A distance of four and a length of
409*44bedb31SLionel Sambuc  *   twelve copies the last four bytes three times.  A simple forward copy
410*44bedb31SLionel Sambuc  *   ignoring whether the length is greater than the distance or not implements
411*44bedb31SLionel Sambuc  *   this correctly.  You should not use memcpy() since its behavior is not
412*44bedb31SLionel Sambuc  *   defined for overlapped arrays.  You should not use memmove() or bcopy()
413*44bedb31SLionel Sambuc  *   since though their behavior -is- defined for overlapping arrays, it is
414*44bedb31SLionel Sambuc  *   defined to do the wrong thing in this case.
415*44bedb31SLionel Sambuc  */
codes(struct state * s,struct huffman * lencode,struct huffman * distcode)416*44bedb31SLionel Sambuc local int codes(struct state *s,
417*44bedb31SLionel Sambuc                 struct huffman *lencode,
418*44bedb31SLionel Sambuc                 struct huffman *distcode)
419*44bedb31SLionel Sambuc {
420*44bedb31SLionel Sambuc     int symbol;         /* decoded symbol */
421*44bedb31SLionel Sambuc     int len;            /* length for copy */
422*44bedb31SLionel Sambuc     unsigned dist;      /* distance for copy */
423*44bedb31SLionel Sambuc     static const short lens[29] = { /* Size base for length codes 257..285 */
424*44bedb31SLionel Sambuc         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
425*44bedb31SLionel Sambuc         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
426*44bedb31SLionel Sambuc     static const short lext[29] = { /* Extra bits for length codes 257..285 */
427*44bedb31SLionel Sambuc         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
428*44bedb31SLionel Sambuc         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
429*44bedb31SLionel Sambuc     static const short dists[30] = { /* Offset base for distance codes 0..29 */
430*44bedb31SLionel Sambuc         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
431*44bedb31SLionel Sambuc         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
432*44bedb31SLionel Sambuc         8193, 12289, 16385, 24577};
433*44bedb31SLionel Sambuc     static const short dext[30] = { /* Extra bits for distance codes 0..29 */
434*44bedb31SLionel Sambuc         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
435*44bedb31SLionel Sambuc         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
436*44bedb31SLionel Sambuc         12, 12, 13, 13};
437*44bedb31SLionel Sambuc 
438*44bedb31SLionel Sambuc     /* decode literals and length/distance pairs */
439*44bedb31SLionel Sambuc     do {
440*44bedb31SLionel Sambuc         symbol = decode(s, lencode);
441*44bedb31SLionel Sambuc         if (symbol < 0) return symbol;  /* invalid symbol */
442*44bedb31SLionel Sambuc         if (symbol < 256) {             /* literal: symbol is the byte */
443*44bedb31SLionel Sambuc             /* write out the literal */
444*44bedb31SLionel Sambuc             if (s->out != NIL) {
445*44bedb31SLionel Sambuc                 if (s->outcnt == s->outlen) return 1;
446*44bedb31SLionel Sambuc                 s->out[s->outcnt] = symbol;
447*44bedb31SLionel Sambuc             }
448*44bedb31SLionel Sambuc             s->outcnt++;
449*44bedb31SLionel Sambuc         }
450*44bedb31SLionel Sambuc         else if (symbol > 256) {        /* length */
451*44bedb31SLionel Sambuc             /* get and compute length */
452*44bedb31SLionel Sambuc             symbol -= 257;
453*44bedb31SLionel Sambuc             if (symbol >= 29) return -9;        /* invalid fixed code */
454*44bedb31SLionel Sambuc             len = lens[symbol] + bits(s, lext[symbol]);
455*44bedb31SLionel Sambuc 
456*44bedb31SLionel Sambuc             /* get and check distance */
457*44bedb31SLionel Sambuc             symbol = decode(s, distcode);
458*44bedb31SLionel Sambuc             if (symbol < 0) return symbol;      /* invalid symbol */
459*44bedb31SLionel Sambuc             dist = dists[symbol] + bits(s, dext[symbol]);
460*44bedb31SLionel Sambuc             if (dist > s->outcnt)
461*44bedb31SLionel Sambuc                 return -10;     /* distance too far back */
462*44bedb31SLionel Sambuc 
463*44bedb31SLionel Sambuc             /* copy length bytes from distance bytes back */
464*44bedb31SLionel Sambuc             if (s->out != NIL) {
465*44bedb31SLionel Sambuc                 if (s->outcnt + len > s->outlen) return 1;
466*44bedb31SLionel Sambuc                 while (len--) {
467*44bedb31SLionel Sambuc                     s->out[s->outcnt] = s->out[s->outcnt - dist];
468*44bedb31SLionel Sambuc                     s->outcnt++;
469*44bedb31SLionel Sambuc                 }
470*44bedb31SLionel Sambuc             }
471*44bedb31SLionel Sambuc             else
472*44bedb31SLionel Sambuc                 s->outcnt += len;
473*44bedb31SLionel Sambuc         }
474*44bedb31SLionel Sambuc     } while (symbol != 256);            /* end of block symbol */
475*44bedb31SLionel Sambuc 
476*44bedb31SLionel Sambuc     /* done with a valid fixed or dynamic block */
477*44bedb31SLionel Sambuc     return 0;
478*44bedb31SLionel Sambuc }
479*44bedb31SLionel Sambuc 
480*44bedb31SLionel Sambuc /*
481*44bedb31SLionel Sambuc  * Process a fixed codes block.
482*44bedb31SLionel Sambuc  *
483*44bedb31SLionel Sambuc  * Format notes:
484*44bedb31SLionel Sambuc  *
485*44bedb31SLionel Sambuc  * - This block type can be useful for compressing small amounts of data for
486*44bedb31SLionel Sambuc  *   which the size of the code descriptions in a dynamic block exceeds the
487*44bedb31SLionel Sambuc  *   benefit of custom codes for that block.  For fixed codes, no bits are
488*44bedb31SLionel Sambuc  *   spent on code descriptions.  Instead the code lengths for literal/length
489*44bedb31SLionel Sambuc  *   codes and distance codes are fixed.  The specific lengths for each symbol
490*44bedb31SLionel Sambuc  *   can be seen in the "for" loops below.
491*44bedb31SLionel Sambuc  *
492*44bedb31SLionel Sambuc  * - The literal/length code is complete, but has two symbols that are invalid
493*44bedb31SLionel Sambuc  *   and should result in an error if received.  This cannot be implemented
494*44bedb31SLionel Sambuc  *   simply as an incomplete code since those two symbols are in the "middle"
495*44bedb31SLionel Sambuc  *   of the code.  They are eight bits long and the longest literal/length\
496*44bedb31SLionel Sambuc  *   code is nine bits.  Therefore the code must be constructed with those
497*44bedb31SLionel Sambuc  *   symbols, and the invalid symbols must be detected after decoding.
498*44bedb31SLionel Sambuc  *
499*44bedb31SLionel Sambuc  * - The fixed distance codes also have two invalid symbols that should result
500*44bedb31SLionel Sambuc  *   in an error if received.  Since all of the distance codes are the same
501*44bedb31SLionel Sambuc  *   length, this can be implemented as an incomplete code.  Then the invalid
502*44bedb31SLionel Sambuc  *   codes are detected while decoding.
503*44bedb31SLionel Sambuc  */
fixed(struct state * s)504*44bedb31SLionel Sambuc local int fixed(struct state *s)
505*44bedb31SLionel Sambuc {
506*44bedb31SLionel Sambuc     static int virgin = 1;
507*44bedb31SLionel Sambuc     static short lencnt[MAXBITS+1], lensym[FIXLCODES];
508*44bedb31SLionel Sambuc     static short distcnt[MAXBITS+1], distsym[MAXDCODES];
509*44bedb31SLionel Sambuc     static struct huffman lencode = {lencnt, lensym};
510*44bedb31SLionel Sambuc     static struct huffman distcode = {distcnt, distsym};
511*44bedb31SLionel Sambuc 
512*44bedb31SLionel Sambuc     /* build fixed huffman tables if first call (may not be thread safe) */
513*44bedb31SLionel Sambuc     if (virgin) {
514*44bedb31SLionel Sambuc         int symbol;
515*44bedb31SLionel Sambuc         short lengths[FIXLCODES];
516*44bedb31SLionel Sambuc 
517*44bedb31SLionel Sambuc         /* literal/length table */
518*44bedb31SLionel Sambuc         for (symbol = 0; symbol < 144; symbol++)
519*44bedb31SLionel Sambuc             lengths[symbol] = 8;
520*44bedb31SLionel Sambuc         for (; symbol < 256; symbol++)
521*44bedb31SLionel Sambuc             lengths[symbol] = 9;
522*44bedb31SLionel Sambuc         for (; symbol < 280; symbol++)
523*44bedb31SLionel Sambuc             lengths[symbol] = 7;
524*44bedb31SLionel Sambuc         for (; symbol < FIXLCODES; symbol++)
525*44bedb31SLionel Sambuc             lengths[symbol] = 8;
526*44bedb31SLionel Sambuc         construct(&lencode, lengths, FIXLCODES);
527*44bedb31SLionel Sambuc 
528*44bedb31SLionel Sambuc         /* distance table */
529*44bedb31SLionel Sambuc         for (symbol = 0; symbol < MAXDCODES; symbol++)
530*44bedb31SLionel Sambuc             lengths[symbol] = 5;
531*44bedb31SLionel Sambuc         construct(&distcode, lengths, MAXDCODES);
532*44bedb31SLionel Sambuc 
533*44bedb31SLionel Sambuc         /* do this just once */
534*44bedb31SLionel Sambuc         virgin = 0;
535*44bedb31SLionel Sambuc     }
536*44bedb31SLionel Sambuc 
537*44bedb31SLionel Sambuc     /* decode data until end-of-block code */
538*44bedb31SLionel Sambuc     return codes(s, &lencode, &distcode);
539*44bedb31SLionel Sambuc }
540*44bedb31SLionel Sambuc 
541*44bedb31SLionel Sambuc /*
542*44bedb31SLionel Sambuc  * Process a dynamic codes block.
543*44bedb31SLionel Sambuc  *
544*44bedb31SLionel Sambuc  * Format notes:
545*44bedb31SLionel Sambuc  *
546*44bedb31SLionel Sambuc  * - A dynamic block starts with a description of the literal/length and
547*44bedb31SLionel Sambuc  *   distance codes for that block.  New dynamic blocks allow the compressor to
548*44bedb31SLionel Sambuc  *   rapidly adapt to changing data with new codes optimized for that data.
549*44bedb31SLionel Sambuc  *
550*44bedb31SLionel Sambuc  * - The codes used by the deflate format are "canonical", which means that
551*44bedb31SLionel Sambuc  *   the actual bits of the codes are generated in an unambiguous way simply
552*44bedb31SLionel Sambuc  *   from the number of bits in each code.  Therefore the code descriptions
553*44bedb31SLionel Sambuc  *   are simply a list of code lengths for each symbol.
554*44bedb31SLionel Sambuc  *
555*44bedb31SLionel Sambuc  * - The code lengths are stored in order for the symbols, so lengths are
556*44bedb31SLionel Sambuc  *   provided for each of the literal/length symbols, and for each of the
557*44bedb31SLionel Sambuc  *   distance symbols.
558*44bedb31SLionel Sambuc  *
559*44bedb31SLionel Sambuc  * - If a symbol is not used in the block, this is represented by a zero as
560*44bedb31SLionel Sambuc  *   as the code length.  This does not mean a zero-length code, but rather
561*44bedb31SLionel Sambuc  *   that no code should be created for this symbol.  There is no way in the
562*44bedb31SLionel Sambuc  *   deflate format to represent a zero-length code.
563*44bedb31SLionel Sambuc  *
564*44bedb31SLionel Sambuc  * - The maximum number of bits in a code is 15, so the possible lengths for
565*44bedb31SLionel Sambuc  *   any code are 1..15.
566*44bedb31SLionel Sambuc  *
567*44bedb31SLionel Sambuc  * - The fact that a length of zero is not permitted for a code has an
568*44bedb31SLionel Sambuc  *   interesting consequence.  Normally if only one symbol is used for a given
569*44bedb31SLionel Sambuc  *   code, then in fact that code could be represented with zero bits.  However
570*44bedb31SLionel Sambuc  *   in deflate, that code has to be at least one bit.  So for example, if
571*44bedb31SLionel Sambuc  *   only a single distance base symbol appears in a block, then it will be
572*44bedb31SLionel Sambuc  *   represented by a single code of length one, in particular one 0 bit.  This
573*44bedb31SLionel Sambuc  *   is an incomplete code, since if a 1 bit is received, it has no meaning,
574*44bedb31SLionel Sambuc  *   and should result in an error.  So incomplete distance codes of one symbol
575*44bedb31SLionel Sambuc  *   should be permitted, and the receipt of invalid codes should be handled.
576*44bedb31SLionel Sambuc  *
577*44bedb31SLionel Sambuc  * - It is also possible to have a single literal/length code, but that code
578*44bedb31SLionel Sambuc  *   must be the end-of-block code, since every dynamic block has one.  This
579*44bedb31SLionel Sambuc  *   is not the most efficient way to create an empty block (an empty fixed
580*44bedb31SLionel Sambuc  *   block is fewer bits), but it is allowed by the format.  So incomplete
581*44bedb31SLionel Sambuc  *   literal/length codes of one symbol should also be permitted.
582*44bedb31SLionel Sambuc  *
583*44bedb31SLionel Sambuc  * - If there are only literal codes and no lengths, then there are no distance
584*44bedb31SLionel Sambuc  *   codes.  This is represented by one distance code with zero bits.
585*44bedb31SLionel Sambuc  *
586*44bedb31SLionel Sambuc  * - The list of up to 286 length/literal lengths and up to 30 distance lengths
587*44bedb31SLionel Sambuc  *   are themselves compressed using Huffman codes and run-length encoding.  In
588*44bedb31SLionel Sambuc  *   the list of code lengths, a 0 symbol means no code, a 1..15 symbol means
589*44bedb31SLionel Sambuc  *   that length, and the symbols 16, 17, and 18 are run-length instructions.
590*44bedb31SLionel Sambuc  *   Each of 16, 17, and 18 are follwed by extra bits to define the length of
591*44bedb31SLionel Sambuc  *   the run.  16 copies the last length 3 to 6 times.  17 represents 3 to 10
592*44bedb31SLionel Sambuc  *   zero lengths, and 18 represents 11 to 138 zero lengths.  Unused symbols
593*44bedb31SLionel Sambuc  *   are common, hence the special coding for zero lengths.
594*44bedb31SLionel Sambuc  *
595*44bedb31SLionel Sambuc  * - The symbols for 0..18 are Huffman coded, and so that code must be
596*44bedb31SLionel Sambuc  *   described first.  This is simply a sequence of up to 19 three-bit values
597*44bedb31SLionel Sambuc  *   representing no code (0) or the code length for that symbol (1..7).
598*44bedb31SLionel Sambuc  *
599*44bedb31SLionel Sambuc  * - A dynamic block starts with three fixed-size counts from which is computed
600*44bedb31SLionel Sambuc  *   the number of literal/length code lengths, the number of distance code
601*44bedb31SLionel Sambuc  *   lengths, and the number of code length code lengths (ok, you come up with
602*44bedb31SLionel Sambuc  *   a better name!) in the code descriptions.  For the literal/length and
603*44bedb31SLionel Sambuc  *   distance codes, lengths after those provided are considered zero, i.e. no
604*44bedb31SLionel Sambuc  *   code.  The code length code lengths are received in a permuted order (see
605*44bedb31SLionel Sambuc  *   the order[] array below) to make a short code length code length list more
606*44bedb31SLionel Sambuc  *   likely.  As it turns out, very short and very long codes are less likely
607*44bedb31SLionel Sambuc  *   to be seen in a dynamic code description, hence what may appear initially
608*44bedb31SLionel Sambuc  *   to be a peculiar ordering.
609*44bedb31SLionel Sambuc  *
610*44bedb31SLionel Sambuc  * - Given the number of literal/length code lengths (nlen) and distance code
611*44bedb31SLionel Sambuc  *   lengths (ndist), then they are treated as one long list of nlen + ndist
612*44bedb31SLionel Sambuc  *   code lengths.  Therefore run-length coding can and often does cross the
613*44bedb31SLionel Sambuc  *   boundary between the two sets of lengths.
614*44bedb31SLionel Sambuc  *
615*44bedb31SLionel Sambuc  * - So to summarize, the code description at the start of a dynamic block is
616*44bedb31SLionel Sambuc  *   three counts for the number of code lengths for the literal/length codes,
617*44bedb31SLionel Sambuc  *   the distance codes, and the code length codes.  This is followed by the
618*44bedb31SLionel Sambuc  *   code length code lengths, three bits each.  This is used to construct the
619*44bedb31SLionel Sambuc  *   code length code which is used to read the remainder of the lengths.  Then
620*44bedb31SLionel Sambuc  *   the literal/length code lengths and distance lengths are read as a single
621*44bedb31SLionel Sambuc  *   set of lengths using the code length codes.  Codes are constructed from
622*44bedb31SLionel Sambuc  *   the resulting two sets of lengths, and then finally you can start
623*44bedb31SLionel Sambuc  *   decoding actual compressed data in the block.
624*44bedb31SLionel Sambuc  *
625*44bedb31SLionel Sambuc  * - For reference, a "typical" size for the code description in a dynamic
626*44bedb31SLionel Sambuc  *   block is around 80 bytes.
627*44bedb31SLionel Sambuc  */
dynamic(struct state * s)628*44bedb31SLionel Sambuc local int dynamic(struct state *s)
629*44bedb31SLionel Sambuc {
630*44bedb31SLionel Sambuc     int nlen, ndist, ncode;             /* number of lengths in descriptor */
631*44bedb31SLionel Sambuc     int index;                          /* index of lengths[] */
632*44bedb31SLionel Sambuc     int err;                            /* construct() return value */
633*44bedb31SLionel Sambuc     short lengths[MAXCODES];            /* descriptor code lengths */
634*44bedb31SLionel Sambuc     short lencnt[MAXBITS+1], lensym[MAXLCODES];         /* lencode memory */
635*44bedb31SLionel Sambuc     short distcnt[MAXBITS+1], distsym[MAXDCODES];       /* distcode memory */
636*44bedb31SLionel Sambuc     struct huffman lencode = {lencnt, lensym};          /* length code */
637*44bedb31SLionel Sambuc     struct huffman distcode = {distcnt, distsym};       /* distance code */
638*44bedb31SLionel Sambuc     static const short order[19] =      /* permutation of code length codes */
639*44bedb31SLionel Sambuc         {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
640*44bedb31SLionel Sambuc 
641*44bedb31SLionel Sambuc     /* get number of lengths in each table, check lengths */
642*44bedb31SLionel Sambuc     nlen = bits(s, 5) + 257;
643*44bedb31SLionel Sambuc     ndist = bits(s, 5) + 1;
644*44bedb31SLionel Sambuc     ncode = bits(s, 4) + 4;
645*44bedb31SLionel Sambuc     if (nlen > MAXLCODES || ndist > MAXDCODES)
646*44bedb31SLionel Sambuc         return -3;                      /* bad counts */
647*44bedb31SLionel Sambuc 
648*44bedb31SLionel Sambuc     /* read code length code lengths (really), missing lengths are zero */
649*44bedb31SLionel Sambuc     for (index = 0; index < ncode; index++)
650*44bedb31SLionel Sambuc         lengths[order[index]] = bits(s, 3);
651*44bedb31SLionel Sambuc     for (; index < 19; index++)
652*44bedb31SLionel Sambuc         lengths[order[index]] = 0;
653*44bedb31SLionel Sambuc 
654*44bedb31SLionel Sambuc     /* build huffman table for code lengths codes (use lencode temporarily) */
655*44bedb31SLionel Sambuc     err = construct(&lencode, lengths, 19);
656*44bedb31SLionel Sambuc     if (err != 0) return -4;            /* require complete code set here */
657*44bedb31SLionel Sambuc 
658*44bedb31SLionel Sambuc     /* read length/literal and distance code length tables */
659*44bedb31SLionel Sambuc     index = 0;
660*44bedb31SLionel Sambuc     while (index < nlen + ndist) {
661*44bedb31SLionel Sambuc         int symbol;             /* decoded value */
662*44bedb31SLionel Sambuc         int len;                /* last length to repeat */
663*44bedb31SLionel Sambuc 
664*44bedb31SLionel Sambuc         symbol = decode(s, &lencode);
665*44bedb31SLionel Sambuc         if (symbol < 16)                /* length in 0..15 */
666*44bedb31SLionel Sambuc             lengths[index++] = symbol;
667*44bedb31SLionel Sambuc         else {                          /* repeat instruction */
668*44bedb31SLionel Sambuc             len = 0;                    /* assume repeating zeros */
669*44bedb31SLionel Sambuc             if (symbol == 16) {         /* repeat last length 3..6 times */
670*44bedb31SLionel Sambuc                 if (index == 0) return -5;      /* no last length! */
671*44bedb31SLionel Sambuc                 len = lengths[index - 1];       /* last length */
672*44bedb31SLionel Sambuc                 symbol = 3 + bits(s, 2);
673*44bedb31SLionel Sambuc             }
674*44bedb31SLionel Sambuc             else if (symbol == 17)      /* repeat zero 3..10 times */
675*44bedb31SLionel Sambuc                 symbol = 3 + bits(s, 3);
676*44bedb31SLionel Sambuc             else                        /* == 18, repeat zero 11..138 times */
677*44bedb31SLionel Sambuc                 symbol = 11 + bits(s, 7);
678*44bedb31SLionel Sambuc             if (index + symbol > nlen + ndist)
679*44bedb31SLionel Sambuc                 return -6;              /* too many lengths! */
680*44bedb31SLionel Sambuc             while (symbol--)            /* repeat last or zero symbol times */
681*44bedb31SLionel Sambuc                 lengths[index++] = len;
682*44bedb31SLionel Sambuc         }
683*44bedb31SLionel Sambuc     }
684*44bedb31SLionel Sambuc 
685*44bedb31SLionel Sambuc     /* build huffman table for literal/length codes */
686*44bedb31SLionel Sambuc     err = construct(&lencode, lengths, nlen);
687*44bedb31SLionel Sambuc     if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1))
688*44bedb31SLionel Sambuc         return -7;      /* only allow incomplete codes if just one code */
689*44bedb31SLionel Sambuc 
690*44bedb31SLionel Sambuc     /* build huffman table for distance codes */
691*44bedb31SLionel Sambuc     err = construct(&distcode, lengths + nlen, ndist);
692*44bedb31SLionel Sambuc     if (err < 0 || (err > 0 && ndist - distcode.count[0] != 1))
693*44bedb31SLionel Sambuc         return -8;      /* only allow incomplete codes if just one code */
694*44bedb31SLionel Sambuc 
695*44bedb31SLionel Sambuc     /* decode data until end-of-block code */
696*44bedb31SLionel Sambuc     return codes(s, &lencode, &distcode);
697*44bedb31SLionel Sambuc }
698*44bedb31SLionel Sambuc 
699*44bedb31SLionel Sambuc /*
700*44bedb31SLionel Sambuc  * Inflate source to dest.  On return, destlen and sourcelen are updated to the
701*44bedb31SLionel Sambuc  * size of the uncompressed data and the size of the deflate data respectively.
702*44bedb31SLionel Sambuc  * On success, the return value of puff() is zero.  If there is an error in the
703*44bedb31SLionel Sambuc  * source data, i.e. it is not in the deflate format, then a negative value is
704*44bedb31SLionel Sambuc  * returned.  If there is not enough input available or there is not enough
705*44bedb31SLionel Sambuc  * output space, then a positive error is returned.  In that case, destlen and
706*44bedb31SLionel Sambuc  * sourcelen are not updated to facilitate retrying from the beginning with the
707*44bedb31SLionel Sambuc  * provision of more input data or more output space.  In the case of invalid
708*44bedb31SLionel Sambuc  * inflate data (a negative error), the dest and source pointers are updated to
709*44bedb31SLionel Sambuc  * facilitate the debugging of deflators.
710*44bedb31SLionel Sambuc  *
711*44bedb31SLionel Sambuc  * puff() also has a mode to determine the size of the uncompressed output with
712*44bedb31SLionel Sambuc  * no output written.  For this dest must be (unsigned char *)0.  In this case,
713*44bedb31SLionel Sambuc  * the input value of *destlen is ignored, and on return *destlen is set to the
714*44bedb31SLionel Sambuc  * size of the uncompressed output.
715*44bedb31SLionel Sambuc  *
716*44bedb31SLionel Sambuc  * The return codes are:
717*44bedb31SLionel Sambuc  *
718*44bedb31SLionel Sambuc  *   2:  available inflate data did not terminate
719*44bedb31SLionel Sambuc  *   1:  output space exhausted before completing inflate
720*44bedb31SLionel Sambuc  *   0:  successful inflate
721*44bedb31SLionel Sambuc  *  -1:  invalid block type (type == 3)
722*44bedb31SLionel Sambuc  *  -2:  stored block length did not match one's complement
723*44bedb31SLionel Sambuc  *  -3:  dynamic block code description: too many length or distance codes
724*44bedb31SLionel Sambuc  *  -4:  dynamic block code description: code lengths codes incomplete
725*44bedb31SLionel Sambuc  *  -5:  dynamic block code description: repeat lengths with no first length
726*44bedb31SLionel Sambuc  *  -6:  dynamic block code description: repeat more than specified lengths
727*44bedb31SLionel Sambuc  *  -7:  dynamic block code description: invalid literal/length code lengths
728*44bedb31SLionel Sambuc  *  -8:  dynamic block code description: invalid distance code lengths
729*44bedb31SLionel Sambuc  *  -9:  invalid literal/length or distance code in fixed or dynamic block
730*44bedb31SLionel Sambuc  * -10:  distance is too far back in fixed or dynamic block
731*44bedb31SLionel Sambuc  *
732*44bedb31SLionel Sambuc  * Format notes:
733*44bedb31SLionel Sambuc  *
734*44bedb31SLionel Sambuc  * - Three bits are read for each block to determine the kind of block and
735*44bedb31SLionel Sambuc  *   whether or not it is the last block.  Then the block is decoded and the
736*44bedb31SLionel Sambuc  *   process repeated if it was not the last block.
737*44bedb31SLionel Sambuc  *
738*44bedb31SLionel Sambuc  * - The leftover bits in the last byte of the deflate data after the last
739*44bedb31SLionel Sambuc  *   block (if it was a fixed or dynamic block) are undefined and have no
740*44bedb31SLionel Sambuc  *   expected values to check.
741*44bedb31SLionel Sambuc  */
puff(unsigned char * dest,unsigned long * destlen,unsigned char * source,unsigned long * sourcelen)742*44bedb31SLionel Sambuc int puff(unsigned char *dest,           /* pointer to destination pointer */
743*44bedb31SLionel Sambuc          unsigned long *destlen,        /* amount of output space */
744*44bedb31SLionel Sambuc          unsigned char *source,         /* pointer to source data pointer */
745*44bedb31SLionel Sambuc          unsigned long *sourcelen)      /* amount of input available */
746*44bedb31SLionel Sambuc {
747*44bedb31SLionel Sambuc     struct state s;             /* input/output state */
748*44bedb31SLionel Sambuc     int last, type;             /* block information */
749*44bedb31SLionel Sambuc     int err;                    /* return value */
750*44bedb31SLionel Sambuc 
751*44bedb31SLionel Sambuc     /* initialize output state */
752*44bedb31SLionel Sambuc     s.out = dest;
753*44bedb31SLionel Sambuc     s.outlen = *destlen;                /* ignored if dest is NIL */
754*44bedb31SLionel Sambuc     s.outcnt = 0;
755*44bedb31SLionel Sambuc 
756*44bedb31SLionel Sambuc     /* initialize input state */
757*44bedb31SLionel Sambuc     s.in = source;
758*44bedb31SLionel Sambuc     s.inlen = *sourcelen;
759*44bedb31SLionel Sambuc     s.incnt = 0;
760*44bedb31SLionel Sambuc     s.bitbuf = 0;
761*44bedb31SLionel Sambuc     s.bitcnt = 0;
762*44bedb31SLionel Sambuc 
763*44bedb31SLionel Sambuc     /* return if bits() or decode() tries to read past available input */
764*44bedb31SLionel Sambuc     if (setjmp(s.env) != 0)             /* if came back here via longjmp() */
765*44bedb31SLionel Sambuc         err = 2;                        /* then skip do-loop, return error */
766*44bedb31SLionel Sambuc     else {
767*44bedb31SLionel Sambuc         /* process blocks until last block or error */
768*44bedb31SLionel Sambuc         do {
769*44bedb31SLionel Sambuc             last = bits(&s, 1);         /* one if last block */
770*44bedb31SLionel Sambuc             type = bits(&s, 2);         /* block type 0..3 */
771*44bedb31SLionel Sambuc             err = type == 0 ? stored(&s) :
772*44bedb31SLionel Sambuc                   (type == 1 ? fixed(&s) :
773*44bedb31SLionel Sambuc                    (type == 2 ? dynamic(&s) :
774*44bedb31SLionel Sambuc                     -1));               /* type == 3, invalid */
775*44bedb31SLionel Sambuc             if (err != 0) break;        /* return with error */
776*44bedb31SLionel Sambuc         } while (!last);
777*44bedb31SLionel Sambuc     }
778*44bedb31SLionel Sambuc 
779*44bedb31SLionel Sambuc     /* update the lengths and return */
780*44bedb31SLionel Sambuc     if (err <= 0) {
781*44bedb31SLionel Sambuc         *destlen = s.outcnt;
782*44bedb31SLionel Sambuc         *sourcelen = s.incnt;
783*44bedb31SLionel Sambuc     }
784*44bedb31SLionel Sambuc     return err;
785*44bedb31SLionel Sambuc }
786*44bedb31SLionel Sambuc 
787*44bedb31SLionel Sambuc #ifdef TEST
788*44bedb31SLionel Sambuc /* Example of how to use puff() */
789*44bedb31SLionel Sambuc #include <stdio.h>
790*44bedb31SLionel Sambuc #include <stdlib.h>
791*44bedb31SLionel Sambuc #include <sys/types.h>
792*44bedb31SLionel Sambuc #include <sys/stat.h>
793*44bedb31SLionel Sambuc 
yank(char * name,unsigned long * len)794*44bedb31SLionel Sambuc local unsigned char *yank(char *name, unsigned long *len)
795*44bedb31SLionel Sambuc {
796*44bedb31SLionel Sambuc     unsigned long size;
797*44bedb31SLionel Sambuc     unsigned char *buf;
798*44bedb31SLionel Sambuc     FILE *in;
799*44bedb31SLionel Sambuc     struct stat s;
800*44bedb31SLionel Sambuc 
801*44bedb31SLionel Sambuc     *len = 0;
802*44bedb31SLionel Sambuc     if (stat(name, &s)) return NULL;
803*44bedb31SLionel Sambuc     if ((s.st_mode & S_IFMT) != S_IFREG) return NULL;
804*44bedb31SLionel Sambuc     size = (unsigned long)(s.st_size);
805*44bedb31SLionel Sambuc     if (size == 0 || (off_t)size != s.st_size) return NULL;
806*44bedb31SLionel Sambuc     in = fopen(name, "r");
807*44bedb31SLionel Sambuc     if (in == NULL) return NULL;
808*44bedb31SLionel Sambuc     buf = malloc(size);
809*44bedb31SLionel Sambuc     if (buf != NULL && fread(buf, 1, size, in) != size) {
810*44bedb31SLionel Sambuc         free(buf);
811*44bedb31SLionel Sambuc         buf = NULL;
812*44bedb31SLionel Sambuc     }
813*44bedb31SLionel Sambuc     fclose(in);
814*44bedb31SLionel Sambuc     *len = size;
815*44bedb31SLionel Sambuc     return buf;
816*44bedb31SLionel Sambuc }
817*44bedb31SLionel Sambuc 
main(int argc,char ** argv)818*44bedb31SLionel Sambuc int main(int argc, char **argv)
819*44bedb31SLionel Sambuc {
820*44bedb31SLionel Sambuc     int ret;
821*44bedb31SLionel Sambuc     unsigned char *source;
822*44bedb31SLionel Sambuc     unsigned long len, sourcelen, destlen;
823*44bedb31SLionel Sambuc 
824*44bedb31SLionel Sambuc     if (argc < 2) return 2;
825*44bedb31SLionel Sambuc     source = yank(argv[1], &len);
826*44bedb31SLionel Sambuc     if (source == NULL) return 2;
827*44bedb31SLionel Sambuc     sourcelen = len;
828*44bedb31SLionel Sambuc     ret = puff(NIL, &destlen, source, &sourcelen);
829*44bedb31SLionel Sambuc     if (ret)
830*44bedb31SLionel Sambuc         printf("puff() failed with return code %d\n", ret);
831*44bedb31SLionel Sambuc     else {
832*44bedb31SLionel Sambuc         printf("puff() succeeded uncompressing %lu bytes\n", destlen);
833*44bedb31SLionel Sambuc         if (sourcelen < len) printf("%lu compressed bytes unused\n",
834*44bedb31SLionel Sambuc                                     len - sourcelen);
835*44bedb31SLionel Sambuc     }
836*44bedb31SLionel Sambuc     free(source);
837*44bedb31SLionel Sambuc     return ret;
838*44bedb31SLionel Sambuc }
839*44bedb31SLionel Sambuc #endif
840