]> git.cworth.org Git - gzip/blob - unpack.c
Imported Debian patch 1.3.5-10sarge2
[gzip] / unpack.c
1 /* unpack.c -- decompress files in pack format.
2  * Copyright (C) 1992-1993 Jean-loup Gailly
3  * This is free software; you can redistribute it and/or modify it under the
4  * terms of the GNU General Public License, see the file COPYING.
5  */
6
7 #ifdef RCSID
8 static char rcsid[] = "$Id: unpack.c,v 1.4 1993/06/11 19:25:36 jloup Exp $";
9 #endif
10
11 #include <config.h>
12 #include "tailor.h"
13 #include "gzip.h"
14 #include "crypt.h"
15
16 #define MIN(a,b) ((a) <= (b) ? (a) : (b))
17 /* The arguments must not have side effects. */
18
19 #define MAX_BITLEN 25
20 /* Maximum length of Huffman codes. (Minor modifications to the code
21  * would be needed to support 32 bits codes, but pack never generates
22  * more than 24 bits anyway.)
23  */
24
25 #define LITERALS 256
26 /* Number of literals, excluding the End of Block (EOB) code */
27
28 #define MAX_PEEK 12
29 /* Maximum number of 'peek' bits used to optimize traversal of the
30  * Huffman tree.
31  */
32
33 local ulg orig_len;       /* original uncompressed length */
34 local int max_len;        /* maximum bit length of Huffman codes */
35
36 local uch literal[LITERALS];
37 /* The literal bytes present in the Huffman tree. The EOB code is not
38  * represented.
39  */
40
41 local int lit_base[MAX_BITLEN+1];
42 /* All literals of a given bit length are contiguous in literal[] and
43  * have contiguous codes. literal[code+lit_base[len]] is the literal
44  * for a code of len bits.
45  */
46
47 local int leaves [MAX_BITLEN+1]; /* Number of leaves for each bit length */
48 local int parents[MAX_BITLEN+1]; /* Number of parents for each bit length */
49
50 local int peek_bits; /* Number of peek bits currently used */
51
52 /* local uch prefix_len[1 << MAX_PEEK]; */
53 #define prefix_len outbuf
54 /* For each bit pattern b of peek_bits bits, prefix_len[b] is the length
55  * of the Huffman code starting with a prefix of b (upper bits), or 0
56  * if all codes of prefix b have more than peek_bits bits. It is not
57  * necessary to have a huge table (large MAX_PEEK) because most of the
58  * codes encountered in the input stream are short codes (by construction).
59  * So for most codes a single lookup will be necessary.
60  */
61 #if (1<<MAX_PEEK) > OUTBUFSIZ
62     error cannot overlay prefix_len and outbuf
63 #endif
64
65 local ulg bitbuf;
66 /* Bits are added on the low part of bitbuf and read from the high part. */
67
68 local int valid;                  /* number of valid bits in bitbuf */
69 /* all bits above the last valid bit are always zero */
70
71 /* Set code to the next 'bits' input bits without skipping them. code
72  * must be the name of a simple variable and bits must not have side effects.
73  * IN assertions: bits <= 25 (so that we still have room for an extra byte
74  * when valid is only 24), and mask = (1<<bits)-1.
75  */
76 #define look_bits(code,bits,mask) \
77 { \
78   while (valid < (bits)) bitbuf = (bitbuf<<8) | (ulg)get_byte(), valid += 8; \
79   code = (bitbuf >> (valid-(bits))) & (mask); \
80 }
81
82 /* Skip the given number of bits (after having peeked at them): */
83 #define skip_bits(bits)  (valid -= (bits))
84
85 #define clear_bitbuf() (valid = 0, bitbuf = 0)
86
87 /* Local functions */
88
89 local void read_tree  OF((void));
90 local void build_tree OF((void));
91
92 /* ===========================================================================
93  * Read the Huffman tree.
94  */
95 local void read_tree()
96 {
97     int len;  /* bit length */
98     int base; /* base offset for a sequence of leaves */
99     int n;
100     int max_leaves;
101
102     /* Read the original input size, MSB first */
103     orig_len = 0;
104     for (n = 1; n <= 4; n++) orig_len = (orig_len << 8) | (ulg)get_byte();
105
106     max_len = (int)get_byte(); /* maximum bit length of Huffman codes */
107     if (max_len > MAX_BITLEN) {
108         error("invalid compressed data -- Huffman code > 32 bits");
109     }
110
111     /* Get the number of leaves at each bit length */
112     n = 0;
113     max_leaves = 1;
114     for (len = 1; len <= max_len; len++) {
115         leaves[len] = (int)get_byte();
116         if (leaves[len] > max_leaves - (len == max_len))
117             error("too many leaves in Huffman tree");
118         max_leaves = (max_leaves - leaves[len] + 1) * 2 - 1;
119         n += leaves[len];
120     }
121     if (n >= LITERALS) {
122         error("too many leaves in Huffman tree");
123     }
124     Trace((stderr, "orig_len %lu, max_len %d, leaves %d\n",
125            orig_len, max_len, n));
126     /* There are at least 2 and at most 256 leaves of length max_len.
127      * (Pack arbitrarily rejects empty files and files consisting of
128      * a single byte even repeated.) To fit the last leaf count in a
129      * byte, it is offset by 2. However, the last literal is the EOB
130      * code, and is not transmitted explicitly in the tree, so we must
131      * adjust here by one only.
132      */
133     leaves[max_len]++;
134
135     /* Now read the leaves themselves */
136     base = 0;
137     for (len = 1; len <= max_len; len++) {
138         /* Remember where the literals of this length start in literal[] : */
139         lit_base[len] = base;
140         /* And read the literals: */
141         for (n = leaves[len]; n > 0; n--) {
142             literal[base++] = (uch)get_byte();
143         }
144     }
145     leaves[max_len]++; /* Now include the EOB code in the Huffman tree */
146 }
147
148 /* ===========================================================================
149  * Build the Huffman tree and the prefix table.
150  */
151 local void build_tree()
152 {
153     int nodes = 0; /* number of nodes (parents+leaves) at current bit length */
154     int len;       /* current bit length */
155     uch *prefixp;  /* pointer in prefix_len */
156
157     for (len = max_len; len >= 1; len--) {
158         /* The number of parent nodes at this level is half the total
159          * number of nodes at parent level:
160          */
161         nodes >>= 1;
162         parents[len] = nodes;
163         /* Update lit_base by the appropriate bias to skip the parent nodes
164          * (which are not represented in the literal array):
165          */
166         lit_base[len] -= nodes;
167         /* Restore nodes to be parents+leaves: */
168         nodes += leaves[len];
169     }
170     /* Construct the prefix table, from shortest leaves to longest ones.
171      * The shortest code is all ones, so we start at the end of the table.
172      */
173     peek_bits = MIN(max_len, MAX_PEEK);
174     prefixp = &prefix_len[1<<peek_bits];
175     for (len = 1; len <= peek_bits; len++) {
176         int prefixes = leaves[len] << (peek_bits-len); /* may be 0 */
177         while (prefixes--) *--prefixp = (uch)len;
178     }
179     /* The length of all other codes is unknown: */
180     while (prefixp > prefix_len) *--prefixp = 0;
181 }
182
183 /* ===========================================================================
184  * Unpack in to out.  This routine does not support the old pack format
185  * with magic header \037\037.
186  *
187  * IN assertions: the buffer inbuf contains already the beginning of
188  *   the compressed data, from offsets inptr to insize-1 included.
189  *   The magic header has already been checked. The output buffer is cleared.
190  */
191 int unpack(in, out)
192     int in, out;            /* input and output file descriptors */
193 {
194     int len;                /* Bit length of current code */
195     unsigned eob;           /* End Of Block code */
196     register unsigned peek; /* lookahead bits */
197     unsigned peek_mask;     /* Mask for peek_bits bits */
198
199     ifd = in;
200     ofd = out;
201
202     read_tree();     /* Read the Huffman tree */
203     build_tree();    /* Build the prefix table */
204     clear_bitbuf();  /* Initialize bit input */
205     peek_mask = (1<<peek_bits)-1;
206
207     /* The eob code is the largest code among all leaves of maximal length: */
208     eob = leaves[max_len]-1;
209     Trace((stderr, "eob %d %x\n", max_len, eob));
210
211     /* Decode the input data: */
212     for (;;) {
213         /* Since eob is the longest code and not shorter than max_len,
214          * we can peek at max_len bits without having the risk of reading
215          * beyond the end of file.
216          */
217         look_bits(peek, peek_bits, peek_mask);
218         len = prefix_len[peek];
219         if (len > 0) {
220             peek >>= peek_bits - len; /* discard the extra bits */
221         } else {
222             /* Code of more than peek_bits bits, we must traverse the tree */
223             ulg mask = peek_mask;
224             len = peek_bits;
225             do {
226                 len++, mask = (mask<<1)+1;
227                 look_bits(peek, len, mask);
228             } while (peek < (unsigned)parents[len]);
229             /* loop as long as peek is a parent node */
230         }
231         /* At this point, peek is the next complete code, of len bits */
232         if (peek == eob && len == max_len) break; /* end of file? */
233         put_ubyte(literal[peek+lit_base[len]]);
234         Tracev((stderr,"%02d %04x %c\n", len, peek,
235                 literal[peek+lit_base[len]]));
236         skip_bits(len);
237     } /* for (;;) */
238
239     flush_window();
240     if (orig_len != (ulg)(bytes_out & 0xffffffff)) {
241         error("invalid compressed data--length error");
242     }
243     return OK;
244 }