1
0

inflate.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. /*
  2. * Changes by Gunnar Ritter, Freiburg i. Br., Germany, May 2003.
  3. *
  4. * Derived from Info-ZIP 5.50.
  5. *
  6. * Sccsid @(#)inflate.c 1.6 (gritter) 10/13/04
  7. */
  8. /*
  9. This is version 2002-Feb-16 of the Info-ZIP copyright and license.
  10. The definitive version of this document should be available at
  11. ftp://ftp.info-zip.org/pub/infozip/license.html indefinitely.
  12. Copyright (c) 1990-2002 Info-ZIP. All rights reserved.
  13. For the purposes of this copyright and license, "Info-ZIP" is defined as
  14. the following set of individuals:
  15. Mark Adler, John Bush, Karl Davis, Harald Denker, Jean-Michel Dubois,
  16. Jean-loup Gailly, Hunter Goatley, Ian Gorman, Chris Herborth, Dirk Haase,
  17. Greg Hartwig, Robert Heath, Jonathan Hudson, Paul Kienitz, David Kirschbaum,
  18. Johnny Lee, Onno van der Linden, Igor Mandrichenko, Steve P. Miller,
  19. Sergio Monesi, Keith Owens, George Petrov, Greg Roelofs, Kai Uwe Rommel,
  20. Steve Salisbury, Dave Smith, Christian Spieler, Antoine Verheijen,
  21. Paul von Behren, Rich Wales, Mike White
  22. This software is provided "as is," without warranty of any kind, express
  23. or implied. In no event shall Info-ZIP or its contributors be held liable
  24. for any direct, indirect, incidental, special or consequential damages
  25. arising out of the use of or inability to use this software.
  26. Permission is granted to anyone to use this software for any purpose,
  27. including commercial applications, and to alter it and redistribute it
  28. freely, subject to the following restrictions:
  29. 1. Redistributions of source code must retain the above copyright notice,
  30. definition, disclaimer, and this list of conditions.
  31. 2. Redistributions in binary form (compiled executables) must reproduce
  32. the above copyright notice, definition, disclaimer, and this list of
  33. conditions in documentation and/or other materials provided with the
  34. distribution. The sole exception to this condition is redistribution
  35. of a standard UnZipSFX binary as part of a self-extracting archive;
  36. that is permitted without inclusion of this license, as long as the
  37. normal UnZipSFX banner has not been removed from the binary or disabled.
  38. 3. Altered versions--including, but not limited to, ports to new operating
  39. systems, existing ports with new graphical interfaces, and dynamic,
  40. shared, or static library versions--must be plainly marked as such
  41. and must not be misrepresented as being the original source. Such
  42. altered versions also must not be misrepresented as being Info-ZIP
  43. releases--including, but not limited to, labeling of the altered
  44. versions with the names "Info-ZIP" (or any variation thereof, including,
  45. but not limited to, different capitalizations), "Pocket UnZip," "WiZ"
  46. or "MacZip" without the explicit permission of Info-ZIP. Such altered
  47. versions are further prohibited from misrepresentative use of the
  48. Zip-Bugs or Info-ZIP e-mail addresses or of the Info-ZIP URL(s).
  49. 4. Info-ZIP retains the right to use the names "Info-ZIP," "Zip," "UnZip,"
  50. "UnZipSFX," "WiZ," "Pocket UnZip," "Pocket Zip," and "MacZip" for its
  51. own source and binary releases.
  52. */
  53. /*
  54. Copyright (c) 1990-2002 Info-ZIP. All rights reserved.
  55. See the accompanying file LICENSE, version 2000-Apr-09 or later
  56. (the contents of which are also included in unzip.h) for terms of use.
  57. If, for some reason, all these files are missing, the Info-ZIP license
  58. also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
  59. */
  60. /* inflate.c -- by Mark Adler
  61. version c17a, 04 Feb 2001 */
  62. /* Copyright history:
  63. - Starting with UnZip 5.41 of 16-April-2000, this source file
  64. is covered by the Info-Zip LICENSE cited above.
  65. - Prior versions of this source file, found in UnZip source packages
  66. up to UnZip 5.40, were put in the public domain.
  67. The original copyright note by Mark Adler was:
  68. "You can do whatever you like with this source file,
  69. though I would prefer that if you modify it and
  70. redistribute it that you include comments to that effect
  71. with your name and the date. Thank you."
  72. History:
  73. vers date who what
  74. ---- --------- -------------- ------------------------------------
  75. a ~~ Feb 92 M. Adler used full (large, one-step) lookup table
  76. b1 21 Mar 92 M. Adler first version with partial lookup tables
  77. b2 21 Mar 92 M. Adler fixed bug in fixed-code blocks
  78. b3 22 Mar 92 M. Adler sped up match copies, cleaned up some
  79. b4 25 Mar 92 M. Adler added prototypes; removed window[] (now
  80. is the responsibility of unzip.h--also
  81. changed name to slide[]), so needs diffs
  82. for unzip.c and unzip.h (this allows
  83. compiling in the small model on MSDOS);
  84. fixed cast of q in huft_build();
  85. b5 26 Mar 92 M. Adler got rid of unintended macro recursion.
  86. b6 27 Mar 92 M. Adler got rid of nextbyte() routine. fixed
  87. bug in inflate_fixed().
  88. c1 30 Mar 92 M. Adler removed lbits, dbits environment variables.
  89. changed BMAX to 16 for explode. Removed
  90. OUTB usage, and replaced it with flush()--
  91. this was a 20% speed improvement! Added
  92. an explode.c (to replace unimplod.c) that
  93. uses the huft routines here. Removed
  94. register union.
  95. c2 4 Apr 92 M. Adler fixed bug for file sizes a multiple of 32k.
  96. c3 10 Apr 92 M. Adler reduced memory of code tables made by
  97. huft_build significantly (factor of two to
  98. three).
  99. c4 15 Apr 92 M. Adler added NOMEMCPY do kill use of memcpy().
  100. worked around a Turbo C optimization bug.
  101. c5 21 Apr 92 M. Adler added the WSIZE #define to allow reducing
  102. the 32K window size for specialized
  103. applications.
  104. c6 31 May 92 M. Adler added some typecasts to eliminate warnings
  105. c7 27 Jun 92 G. Roelofs added some more typecasts (444: MSC bug).
  106. c8 5 Oct 92 J-l. Gailly added ifdef'd code to deal with PKZIP bug.
  107. c9 9 Oct 92 M. Adler removed a memory error message (~line 416).
  108. c10 17 Oct 92 G. Roelofs changed ULONG/UWORD/byte to ulg/ush/uch,
  109. removed old inflate, renamed inflate_entry
  110. to inflate, added Mark's fix to a comment.
  111. c10.5 14 Dec 92 M. Adler fix up error messages for incomplete trees.
  112. c11 2 Jan 93 M. Adler fixed bug in detection of incomplete
  113. tables, and removed assumption that EOB is
  114. the longest code (bad assumption).
  115. c12 3 Jan 93 M. Adler make tables for fixed blocks only once.
  116. c13 5 Jan 93 M. Adler allow all zero length codes (pkzip 2.04c
  117. outputs one zero length code for an empty
  118. distance tree).
  119. c14 12 Mar 93 M. Adler made inflate.c standalone with the
  120. introduction of inflate.h.
  121. c14b 16 Jul 93 G. Roelofs added (unsigned) typecast to w at 470.
  122. c14c 19 Jul 93 J. Bush changed v[N_MAX], l[288], ll[28x+3x] arrays
  123. to static for Amiga.
  124. c14d 13 Aug 93 J-l. Gailly de-complicatified Mark's c[*p++]++ thing.
  125. c14e 8 Oct 93 G. Roelofs changed memset() to memzero().
  126. c14f 22 Oct 93 G. Roelofs renamed quietflg to qflag; made Trace()
  127. conditional; added inflate_free().
  128. c14g 28 Oct 93 G. Roelofs changed l/(lx+1) macro to pointer (Cray bug)
  129. c14h 7 Dec 93 C. Ghisler huft_build() optimizations.
  130. c14i 9 Jan 94 A. Verheijen set fixed_t{d,l} to NULL after freeing;
  131. G. Roelofs check NEXTBYTE macro for EOF.
  132. c14j 23 Jan 94 G. Roelofs removed Ghisler "optimizations"; ifdef'd
  133. EOF check.
  134. c14k 27 Feb 94 G. Roelofs added some typecasts to avoid warnings.
  135. c14l 9 Apr 94 G. Roelofs fixed split comments on preprocessor lines
  136. to avoid bug in Encore compiler.
  137. c14m 7 Jul 94 P. Kienitz modified to allow assembler version of
  138. inflate_codes() (define ASM_INFLATECODES)
  139. c14n 22 Jul 94 G. Roelofs changed fprintf to macro for DLL versions
  140. c14o 23 Aug 94 C. Spieler added a newline to a debug statement;
  141. G. Roelofs added another typecast to avoid MSC warning
  142. c14p 4 Oct 94 G. Roelofs added (voidp *) cast to free() argument
  143. c14q 30 Oct 94 G. Roelofs changed fprintf macro to MESSAGE()
  144. c14r 1 Nov 94 G. Roelofs fixed possible redefinition of CHECK_EOF
  145. c14s 7 May 95 S. Maxwell OS/2 DLL globals stuff incorporated;
  146. P. Kienitz "fixed" ASM_INFLATECODES macro/prototype
  147. c14t 18 Aug 95 G. Roelofs added UZinflate() to use zlib functions;
  148. changed voidp to zvoid; moved huft_build()
  149. and huft_free() to end of file
  150. c14u 1 Oct 95 G. Roelofs moved G into definition of MESSAGE macro
  151. c14v 8 Nov 95 P. Kienitz changed ASM_INFLATECODES to use a regular
  152. call with __G__ instead of a macro
  153. c15 3 Aug 96 M. Adler fixed bomb-bug on random input data (Adobe)
  154. c15b 24 Aug 96 M. Adler more fixes for random input data
  155. c15c 28 Mar 97 G. Roelofs changed USE_ZLIB fatal exit code from
  156. PK_MEM2 to PK_MEM3
  157. c16 20 Apr 97 J. Altman added memzero(v[]) in huft_build()
  158. c16b 29 Mar 98 C. Spieler modified DLL code for slide redirection
  159. c16c 04 Apr 99 C. Spieler fixed memory leaks when processing gets
  160. stopped because of input data errors
  161. c16d 05 Jul 99 C. Spieler take care of FLUSH() return values and
  162. stop processing in case of errors
  163. c17 31 Dec 00 C. Spieler added preliminary support for Deflate64
  164. c17a 04 Feb 01 C. Spieler complete integration of Deflate64 support
  165. c17b 16 Feb 02 C. Spieler changed type of "extra bits" arrays and
  166. corresponding huft_buid() parameter e from
  167. ush into uch, to save space
  168. */
  169. /*
  170. Inflate deflated (PKZIP's method 8 compressed) data. The compression
  171. method searches for as much of the current string of bytes (up to a
  172. length of 258) in the previous 32K bytes. If it doesn't find any
  173. matches (of at least length 3), it codes the next byte. Otherwise, it
  174. codes the length of the matched string and its distance backwards from
  175. the current position. There is a single Huffman code that codes both
  176. single bytes (called "literals") and match lengths. A second Huffman
  177. code codes the distance information, which follows a length code. Each
  178. length or distance code actually represents a base value and a number
  179. of "extra" (sometimes zero) bits to get to add to the base value. At
  180. the end of each deflated block is a special end-of-block (EOB) literal/
  181. length code. The decoding process is basically: get a literal/length
  182. code; if EOB then done; if a literal, emit the decoded byte; if a
  183. length then get the distance and emit the referred-to bytes from the
  184. sliding window of previously emitted data.
  185. There are (currently) three kinds of inflate blocks: stored, fixed, and
  186. dynamic. The compressor outputs a chunk of data at a time and decides
  187. which method to use on a chunk-by-chunk basis. A chunk might typically
  188. be 32K to 64K, uncompressed. If the chunk is uncompressible, then the
  189. "stored" method is used. In this case, the bytes are simply stored as
  190. is, eight bits per byte, with none of the above coding. The bytes are
  191. preceded by a count, since there is no longer an EOB code.
  192. If the data are compressible, then either the fixed or dynamic methods
  193. are used. In the dynamic method, the compressed data are preceded by
  194. an encoding of the literal/length and distance Huffman codes that are
  195. to be used to decode this block. The representation is itself Huffman
  196. coded, and so is preceded by a description of that code. These code
  197. descriptions take up a little space, and so for small blocks, there is
  198. a predefined set of codes, called the fixed codes. The fixed method is
  199. used if the block ends up smaller that way (usually for quite small
  200. chunks); otherwise the dynamic method is used. In the latter case, the
  201. codes are customized to the probabilities in the current block and so
  202. can code it much better than the pre-determined fixed codes can.
  203. The Huffman codes themselves are decoded using a multi-level table
  204. lookup, in order to maximize the speed of decoding plus the speed of
  205. building the decoding tables. See the comments below that precede the
  206. lbits and dbits tuning parameters.
  207. GRR: return values(?)
  208. 0 OK
  209. 1 incomplete table
  210. 2 bad input
  211. 3 not enough memory
  212. the following return codes are passed through from FLUSH() errors
  213. 50 (PK_DISK) "overflow of output space"
  214. 80 (IZ_CTRLC) "canceled by user's request"
  215. */
  216. /*
  217. Notes beyond the 1.93a appnote.txt:
  218. 1. Distance pointers never point before the beginning of the output
  219. stream.
  220. 2. Distance pointers can point back across blocks, up to 32k away.
  221. 3. There is an implied maximum of 7 bits for the bit length table and
  222. 15 bits for the actual data.
  223. 4. If only one code exists, then it is encoded using one bit. (Zero
  224. would be more efficient, but perhaps a little confusing.) If two
  225. codes exist, they are coded using one bit each (0 and 1).
  226. 5. There is no way of sending zero distance codes--a dummy must be
  227. sent if there are none. (History: a pre 2.0 version of PKZIP would
  228. store blocks with no distance codes, but this was discovered to be
  229. too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
  230. zero distance codes, which is sent as one code of zero bits in
  231. length.
  232. 6. There are up to 286 literal/length codes. Code 256 represents the
  233. end-of-block. Note however that the static length tree defines
  234. 288 codes just to fill out the Huffman codes. Codes 286 and 287
  235. cannot be used though, since there is no length base or extra bits
  236. defined for them. Similarily, there are up to 30 distance codes.
  237. However, static trees define 32 codes (all 5 bits) to fill out the
  238. Huffman codes, but the last two had better not show up in the data.
  239. 7. Unzip can check dynamic Huffman blocks for complete code sets.
  240. The exception is that a single code would not be complete (see #4).
  241. 8. The five bits following the block type is really the number of
  242. literal codes sent minus 257.
  243. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  244. (1+6+6). Therefore, to output three times the length, you output
  245. three codes (1+1+1), whereas to output four times the same length,
  246. you only need two codes (1+3). Hmm.
  247. 10. In the tree reconstruction algorithm, Code = Code + Increment
  248. only if BitLength(i) is not zero. (Pretty obvious.)
  249. 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
  250. 12. Note: length code 284 can represent 227-258, but length code 285
  251. really is 258. The last length deserves its own, short code
  252. since it gets used a lot in very redundant files. The length
  253. 258 is special since 258 - 3 (the min match length) is 255.
  254. 13. The literal/length and distance code bit lengths are read as a
  255. single stream of lengths. It is possible (and advantageous) for
  256. a repeat code (16, 17, or 18) to go across the boundary between
  257. the two sets of lengths.
  258. 14. The Deflate64 (PKZIP method 9) variant of the compression algorithm
  259. differs from "classic" deflate in the following 3 aspect:
  260. a) The size of the sliding history window is expanded to 64 kByte.
  261. b) The previously unused distance codes #30 and #31 code distances
  262. from 32769 to 49152 and 49153 to 65536. Both codes take 14 bits
  263. of extra data to determine the exact position in their 16 kByte
  264. range.
  265. c) The last lit/length code #285 gets a different meaning. Instead
  266. of coding a fixed maximum match length of 258, it is used as a
  267. "generic" match length code, capable of coding any length from
  268. 3 (min match length + 0) to 65538 (min match length + 65535).
  269. This means that the length code #285 takes 16 bits (!) of uncoded
  270. extra data, added to a fixed min length of 3.
  271. Changes a) and b) would have been transparent for valid deflated
  272. data, but change c) requires to switch decoder configurations between
  273. Deflate and Deflate64 modes.
  274. */
  275. #include <stdlib.h>
  276. #include <stdio.h>
  277. #include <string.h>
  278. #include "cpio.h"
  279. #include "unzip.h"
  280. /*
  281. inflate.h must supply the uch slide[WSIZE] array, the zvoid typedef
  282. (void if (void *) is accepted, else char) and the NEXTBYTE,
  283. FLUSH() and memzero macros. If the window size is not 32K, it
  284. should also define WSIZE. If INFMOD is defined, it can include
  285. compiled functions to support the NEXTBYTE and/or FLUSH() macros.
  286. There are defaults for NEXTBYTE and FLUSH() below for use as
  287. examples of what those functions need to do. Normally, you would
  288. also want FLUSH() to compute a crc on the data. inflate.h also
  289. needs to provide these typedefs:
  290. typedef unsigned char uch;
  291. typedef unsigned short ush;
  292. typedef unsigned long ulg;
  293. This module uses the external functions malloc() and free() (and
  294. probably memset() or bzero() in the memzero() macro). Their
  295. prototypes are normally found in <string.h> and <stdlib.h>.
  296. */
  297. /* marker for "unused" huft code, and corresponding check macro */
  298. #define INVALID_CODE 99
  299. #define IS_INVALID_CODE(c) ((c) == INVALID_CODE)
  300. static int inflate_codes(struct globals *Gp,
  301. struct huft *tl, struct huft *td,
  302. int bl, int bd);
  303. static int inflate_stored(struct globals *Gp);
  304. static int inflate_fixed(struct globals *Gp);
  305. static int inflate_dynamic(struct globals *Gp);
  306. static int inflate_block(struct globals *Gp, int *e);
  307. #define FLUSH(n) (flush(&G, redirSlide, (n)), 0)
  308. /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
  309. stream to find repeated byte strings. This is implemented here as a
  310. circular buffer. The index is updated simply by incrementing and then
  311. and'ing with 0x7fff (32K-1). */
  312. /* It is left to other modules to supply the 32K area. It is assumed
  313. to be usable as if it were declared "uch slide[32768];" or as just
  314. "uch *slide;" and then malloc'ed in the latter case. The definition
  315. must be in unzip.h, included above. */
  316. /* Tables for deflate from PKZIP's appnote.txt. */
  317. /* - Order of the bit length code lengths */
  318. static const unsigned border[] = {
  319. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  320. /* - Copy lengths for literal codes 257..285 */
  321. static const uint16_t cplens64[] = {
  322. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  323. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 3, 0, 0};
  324. /* For Deflate64, the code 285 is defined differently. */
  325. static const uint16_t cplens32[] = {
  326. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  327. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  328. /* note: see note #13 above about the 258 in this list. */
  329. /* - Extra bits for literal codes 257..285 */
  330. static const uint8_t cplext64[] = {
  331. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  332. 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 16, INVALID_CODE, INVALID_CODE};
  333. static const uint8_t cplext32[] = {
  334. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  335. 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, INVALID_CODE, INVALID_CODE};
  336. /* - Copy offsets for distance codes 0..29 (0..31 for Deflate64) */
  337. static const uint16_t cpdist[] = {
  338. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  339. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  340. 8193, 12289, 16385, 24577, 32769, 49153};
  341. /* - Extra bits for distance codes 0..29 (0..31 for Deflate64) */
  342. static const uint8_t cpdext64[] = {
  343. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  344. 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  345. 12, 12, 13, 13, 14, 14};
  346. static const uint8_t cpdext32[] = {
  347. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  348. 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  349. 12, 12, 13, 13, INVALID_CODE, INVALID_CODE};
  350. # define MAXLITLENS 288
  351. # define MAXDISTS 32
  352. /* Macros for inflate() bit peeking and grabbing.
  353. The usage is:
  354. NEEDBITS(j)
  355. x = b & mask_bits[j];
  356. DUMPBITS(j)
  357. where NEEDBITS makes sure that b has at least j bits in it, and
  358. DUMPBITS removes the bits from b. The macros use the variable k
  359. for the number of bits in b. Normally, b and k are register
  360. variables for speed and are initialized at the begining of a
  361. routine that uses these macros from a global bit buffer and count.
  362. In order to not ask for more bits than there are in the compressed
  363. stream, the Huffman tables are constructed to only ask for just
  364. enough bits to make up the end-of-block code (value 256). Then no
  365. bytes need to be "returned" to the buffer at the end of the last
  366. block. See the huft_build() routine.
  367. */
  368. # define NEEDBITS(n) {while(k<(n)){int c=NEXTBYTE;\
  369. if(c==EOF){retval=1;goto cleanup_and_exit;}\
  370. b|=((uint32_t)c)<<k;k+=8;}}
  371. #define DUMPBITS(n) {b>>=(n);k-=(n);}
  372. #define Bits 32
  373. #define Nob 32
  374. #define Eob 31
  375. /*
  376. Huffman code decoding is performed using a multi-level table lookup.
  377. The fastest way to decode is to simply build a lookup table whose
  378. size is determined by the longest code. However, the time it takes
  379. to build this table can also be a factor if the data being decoded
  380. are not very long. The most common codes are necessarily the
  381. shortest codes, so those codes dominate the decoding time, and hence
  382. the speed. The idea is you can have a shorter table that decodes the
  383. shorter, more probable codes, and then point to subsidiary tables for
  384. the longer codes. The time it costs to decode the longer codes is
  385. then traded against the time it takes to make longer tables.
  386. This results of this trade are in the variables lbits and dbits
  387. below. lbits is the number of bits the first level table for literal/
  388. length codes can decode in one step, and dbits is the same thing for
  389. the distance codes. Subsequent tables are also less than or equal to
  390. those sizes. These values may be adjusted either when all of the
  391. codes are shorter than that, in which case the longest code length in
  392. bits is used, or when the shortest code is *longer* than the requested
  393. table size, in which case the length of the shortest code in bits is
  394. used.
  395. There are two different values for the two tables, since they code a
  396. different number of possibilities each. The literal/length table
  397. codes 286 possible values, or in a flat code, a little over eight
  398. bits. The distance table codes 30 possible values, or a little less
  399. than five bits, flat. The optimum values for speed end up being
  400. about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  401. The optimum values may differ though from machine to machine, and
  402. possibly even between compilers. Your mileage may vary.
  403. */
  404. static const int lbits = 9; /* bits in base literal/length lookup table */
  405. static const int dbits = 6; /* bits in base distance lookup table */
  406. #define G (*Gp)
  407. static int
  408. inflate_codes(struct globals *Gp,
  409. struct huft *tl, struct huft *td, int bl, int bd)
  410. /*struct huft *tl, *td;*/ /* literal/length and distance decoder tables */
  411. /*int bl, bd;*/ /* number of bits decoded by tl[] and td[] */
  412. /* inflate (decompress) the codes in a deflated (compressed) block.
  413. Return an error code or zero if it all goes ok. */
  414. {
  415. register unsigned e; /* table entry flag/number of extra bits */
  416. unsigned d; /* index for copy */
  417. uint32_t n; /* length for copy (deflate64: might be 64k+2) */
  418. uint32_t w; /* current window position (deflate64: up to 64k) */
  419. struct huft *t; /* pointer to table entry */
  420. unsigned ml, md; /* masks for bl and bd bits */
  421. register uint32_t b; /* bit buffer */
  422. register unsigned k; /* number of bits in bit buffer */
  423. int retval = 0; /* error code returned: initialized to "no error" */
  424. /* make local copies of globals */
  425. b = G.bb; /* initialize bit buffer */
  426. k = G.bk;
  427. w = G.wp; /* initialize window position */
  428. /* inflate the coded data */
  429. ml = mask_bits[bl]; /* precompute masks for speed */
  430. md = mask_bits[bd];
  431. while (1) /* do until end of block */
  432. {
  433. NEEDBITS((unsigned)bl)
  434. t = tl + ((unsigned)b & ml);
  435. while (1) {
  436. DUMPBITS(t->b)
  437. if ((e = t->e) == 32) /* then it's a literal */
  438. {
  439. redirSlide[w++] = (uint8_t)t->v.n;
  440. if (w == WSIZE)
  441. {
  442. if ((retval = FLUSH(w)) != 0) goto cleanup_and_exit;
  443. w = 0;
  444. }
  445. break;
  446. }
  447. if (e < 31) /* then it's a length */
  448. {
  449. /* get length of block to copy */
  450. NEEDBITS(e)
  451. n = t->v.n + ((unsigned)b & mask_bits[e]);
  452. DUMPBITS(e)
  453. /* decode distance of block to copy */
  454. NEEDBITS((unsigned)bd)
  455. t = td + ((unsigned)b & md);
  456. while (1) {
  457. DUMPBITS(t->b)
  458. if ((e = t->e) < 32)
  459. break;
  460. if (IS_INVALID_CODE(e))
  461. return 1;
  462. e &= 31;
  463. NEEDBITS(e)
  464. t = t->v.t + ((unsigned)b & mask_bits[e]);
  465. }
  466. NEEDBITS(e)
  467. d = (unsigned)w - t->v.n - ((unsigned)b & mask_bits[e]);
  468. DUMPBITS(e)
  469. /* do the copy */
  470. do {
  471. e = (unsigned)(WSIZE -
  472. ((d &= (unsigned)(WSIZE-1)) > (unsigned)w ?
  473. (uint32_t)d : w));
  474. if ((uint32_t)e > n) e = (unsigned)n;
  475. n -= e;
  476. #ifndef NOMEMCPY
  477. if ((unsigned)w - d >= e)
  478. /* (this test assumes unsigned comparison) */
  479. {
  480. memcpy(redirSlide + (unsigned)w, redirSlide + d, e);
  481. w += e;
  482. d += e;
  483. }
  484. else /* do it slowly to avoid memcpy() overlap */
  485. #endif /* !NOMEMCPY */
  486. do {
  487. redirSlide[w++] = redirSlide[d++];
  488. } while (--e);
  489. if (w == WSIZE)
  490. {
  491. if ((retval = FLUSH(w)) != 0) goto cleanup_and_exit;
  492. w = 0;
  493. }
  494. } while (n);
  495. break;
  496. }
  497. if (e == 31) /* it's the EOB signal */
  498. {
  499. /* sorry for this goto, but we have to exit two loops at once */
  500. goto cleanup_decode;
  501. }
  502. if (IS_INVALID_CODE(e))
  503. return 1;
  504. e &= 31;
  505. NEEDBITS(e)
  506. t = t->v.t + ((unsigned)b & mask_bits[e]);
  507. }
  508. }
  509. cleanup_decode:
  510. /* restore the globals from the locals */
  511. G.wp = (unsigned)w; /* restore global window pointer */
  512. G.bb = b; /* restore global bit buffer */
  513. G.bk = k;
  514. cleanup_and_exit:
  515. /* done */
  516. return retval;
  517. }
  518. static int
  519. inflate_stored(struct globals *Gp)
  520. /* "decompress" an inflated type 0 (stored) block. */
  521. {
  522. uint32_t w; /* current window position (deflate64: up to 64k!) */
  523. unsigned n; /* number of bytes in block */
  524. register uint32_t b; /* bit buffer */
  525. register unsigned k; /* number of bits in bit buffer */
  526. int retval = 0; /* error code returned: initialized to "no error" */
  527. /* make local copies of globals */
  528. Trace((stderr, "\nstored block"));
  529. b = G.bb; /* initialize bit buffer */
  530. k = G.bk;
  531. w = G.wp; /* initialize window position */
  532. /* go to byte boundary */
  533. n = k & 7;
  534. DUMPBITS(n);
  535. /* get the length and its complement */
  536. NEEDBITS(16)
  537. n = ((unsigned)b & 0xffff);
  538. DUMPBITS(16)
  539. NEEDBITS(16)
  540. if (n != (unsigned)((~b) & 0xffff))
  541. return 1; /* error in compressed data */
  542. DUMPBITS(16)
  543. /* read and output the compressed data */
  544. while (n--)
  545. {
  546. NEEDBITS(8)
  547. redirSlide[w++] = (uint8_t)b;
  548. if (w == WSIZE)
  549. {
  550. if ((retval = FLUSH(w)) != 0) goto cleanup_and_exit;
  551. w = 0;
  552. }
  553. DUMPBITS(8)
  554. }
  555. /* restore the globals from the locals */
  556. G.wp = (unsigned)w; /* restore global window pointer */
  557. G.bb = b; /* restore global bit buffer */
  558. G.bk = k;
  559. cleanup_and_exit:
  560. return retval;
  561. }
  562. static int
  563. inflate_fixed(struct globals *Gp)
  564. /* decompress an inflated type 1 (fixed Huffman codes) block. We should
  565. either replace this with a custom decoder, or at least precompute the
  566. Huffman tables. */
  567. {
  568. /* if first time, set up tables for fixed blocks */
  569. Trace((stderr, "\nliteral block"));
  570. if (G.fixed_tl == NULL)
  571. {
  572. int i; /* temporary variable */
  573. unsigned l[288]; /* length list for huft_build */
  574. /* literal table */
  575. for (i = 0; i < 144; i++)
  576. l[i] = 8;
  577. for (; i < 256; i++)
  578. l[i] = 9;
  579. for (; i < 280; i++)
  580. l[i] = 7;
  581. for (; i < 288; i++) /* make a complete, but wrong code set */
  582. l[i] = 8;
  583. G.fixed_bl = 7;
  584. if ((i = huft_build(l, 288, 257, G.cplens, G.cplext,
  585. &G.fixed_tl, &G.fixed_bl,
  586. Bits, Nob, Eob)) != 0)
  587. {
  588. G.fixed_tl = NULL;
  589. return i;
  590. }
  591. /* distance table */
  592. for (i = 0; i < MAXDISTS; i++) /* make an incomplete code set */
  593. l[i] = 5;
  594. G.fixed_bd = 5;
  595. if ((i = huft_build(l, MAXDISTS, 0, cpdist, G.cpdext,
  596. &G.fixed_td, &G.fixed_bd,
  597. Bits, Nob, Eob)) > 1)
  598. {
  599. huft_free(G.fixed_tl);
  600. G.fixed_td = G.fixed_tl = NULL;
  601. return i;
  602. }
  603. }
  604. /* decompress until an end-of-block code */
  605. return inflate_codes(&G, G.fixed_tl, G.fixed_td,
  606. G.fixed_bl, G.fixed_bd);
  607. }
  608. static int inflate_dynamic(struct globals *Gp)
  609. /* decompress an inflated type 2 (dynamic Huffman codes) block. */
  610. {
  611. int i; /* temporary variables */
  612. unsigned j;
  613. unsigned l; /* last length */
  614. unsigned m; /* mask for bit lengths table */
  615. unsigned n; /* number of lengths to get */
  616. struct huft *tl; /* literal/length code table */
  617. struct huft *td; /* distance code table */
  618. int bl; /* lookup bits for tl */
  619. int bd; /* lookup bits for td */
  620. unsigned nb; /* number of bit length codes */
  621. unsigned nl; /* number of literal/length codes */
  622. unsigned nd; /* number of distance codes */
  623. unsigned ll[MAXLITLENS+MAXDISTS]; /* lit./length and distance code lengths */
  624. register uint32_t b; /* bit buffer */
  625. register unsigned k; /* number of bits in bit buffer */
  626. int retval = 0; /* error code returned: initialized to "no error" */
  627. /* make local bit buffer */
  628. Trace((stderr, "\ndynamic block"));
  629. b = G.bb;
  630. k = G.bk;
  631. /* read in table lengths */
  632. NEEDBITS(5)
  633. nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */
  634. DUMPBITS(5)
  635. NEEDBITS(5)
  636. nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */
  637. DUMPBITS(5)
  638. NEEDBITS(4)
  639. nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */
  640. DUMPBITS(4)
  641. if (nl > MAXLITLENS || nd > MAXDISTS)
  642. return 1; /* bad lengths */
  643. /* read in bit-length-code lengths */
  644. for (j = 0; j < nb; j++)
  645. {
  646. NEEDBITS(3)
  647. ll[border[j]] = (unsigned)b & 7;
  648. DUMPBITS(3)
  649. }
  650. for (; j < 19; j++)
  651. ll[border[j]] = 0;
  652. /* build decoding table for trees--single level, 7 bit lookup */
  653. bl = 7;
  654. retval = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl,
  655. Bits, Nob, Eob);
  656. if (bl == 0) /* no bit lengths */
  657. retval = 1;
  658. if (retval)
  659. {
  660. if (retval == 1)
  661. huft_free(tl);
  662. return retval; /* incomplete code set */
  663. }
  664. /* read in literal and distance code lengths */
  665. n = nl + nd;
  666. m = mask_bits[bl];
  667. i = l = 0;
  668. while ((unsigned)i < n)
  669. {
  670. NEEDBITS((unsigned)bl)
  671. j = (td = tl + ((unsigned)b & m))->b;
  672. DUMPBITS(j)
  673. j = td->v.n;
  674. if (j < 16) /* length of code in bits (0..15) */
  675. ll[i++] = l = j; /* save last length in l */
  676. else if (j == 16) /* repeat last length 3 to 6 times */
  677. {
  678. NEEDBITS(2)
  679. j = 3 + ((unsigned)b & 3);
  680. DUMPBITS(2)
  681. if ((unsigned)i + j > n)
  682. return 1;
  683. while (j--)
  684. ll[i++] = l;
  685. }
  686. else if (j == 17) /* 3 to 10 zero length codes */
  687. {
  688. NEEDBITS(3)
  689. j = 3 + ((unsigned)b & 7);
  690. DUMPBITS(3)
  691. if ((unsigned)i + j > n)
  692. return 1;
  693. while (j--)
  694. ll[i++] = 0;
  695. l = 0;
  696. }
  697. else /* j == 18: 11 to 138 zero length codes */
  698. {
  699. NEEDBITS(7)
  700. j = 11 + ((unsigned)b & 0x7f);
  701. DUMPBITS(7)
  702. if ((unsigned)i + j > n)
  703. return 1;
  704. while (j--)
  705. ll[i++] = 0;
  706. l = 0;
  707. }
  708. }
  709. /* free decoding table for trees */
  710. huft_free(tl);
  711. /* restore the global bit buffer */
  712. G.bb = b;
  713. G.bk = k;
  714. /* build the decoding tables for literal/length and distance codes */
  715. bl = lbits;
  716. retval = huft_build(ll, nl, 257, G.cplens, G.cplext, &tl, &bl,
  717. Bits, Nob, Eob);
  718. if (bl == 0) /* no literals or lengths */
  719. retval = 1;
  720. if (retval)
  721. {
  722. if (retval == 1) {
  723. /*if (!uO.qflag)
  724. MESSAGE((uint8_t *)"(incomplete l-tree) ", 21L, 1);*/
  725. huft_free(tl);
  726. }
  727. return retval; /* incomplete code set */
  728. }
  729. bd = dbits;
  730. retval = huft_build(ll + nl, nd, 0, cpdist, G.cpdext, &td, &bd,
  731. Bits, Nob, Eob);
  732. if (retval == 1)
  733. retval = 0;
  734. if (bd == 0 && nl > 257) /* lengths but no distances */
  735. retval = 1;
  736. if (retval)
  737. {
  738. if (retval == 1) {
  739. /*if (!uO.qflag)
  740. MESSAGE((uint8_t *)"(incomplete d-tree) ", 21L, 1);*/
  741. huft_free(td);
  742. }
  743. huft_free(tl);
  744. return retval;
  745. }
  746. /* decompress until an end-of-block code */
  747. retval = inflate_codes(&G, tl, td, bl, bd);
  748. cleanup_and_exit:
  749. /* free the decoding tables, return */
  750. huft_free(tl);
  751. huft_free(td);
  752. return retval;
  753. }
  754. static int inflate_block(struct globals *Gp, int *e)
  755. /*int *e;*/ /* last block flag */
  756. /* decompress an inflated block */
  757. {
  758. unsigned t; /* block type */
  759. register uint32_t b; /* bit buffer */
  760. register unsigned k; /* number of bits in bit buffer */
  761. int retval = 0; /* error code returned: initialized to "no error" */
  762. /* make local bit buffer */
  763. b = G.bb;
  764. k = G.bk;
  765. /* read in last block bit */
  766. NEEDBITS(1)
  767. *e = (int)b & 1;
  768. DUMPBITS(1)
  769. /* read in block type */
  770. NEEDBITS(2)
  771. t = (unsigned)b & 3;
  772. DUMPBITS(2)
  773. /* restore the global bit buffer */
  774. G.bb = b;
  775. G.bk = k;
  776. /* inflate that block type */
  777. if (t == 2)
  778. return inflate_dynamic(&G);
  779. if (t == 0)
  780. return inflate_stored(&G);
  781. if (t == 1)
  782. return inflate_fixed(&G);
  783. /* bad block type */
  784. retval = 2;
  785. cleanup_and_exit:
  786. return retval;
  787. }
  788. #undef G
  789. int
  790. zipinflate(struct file *f, const char *tgt, int tfd, int doswap, uint32_t *crc)
  791. /* decompress an inflated entry */
  792. {
  793. struct globals G;
  794. int e = 0; /* last block flag */
  795. int r; /* result code */
  796. int is_defl64;
  797. #ifdef DEBUG
  798. unsigned h = 0; /* maximum struct huft's malloc'ed */
  799. #endif
  800. is_defl64 = f->f_cmethod == C_ENHDEFLD;
  801. memset(&G, 0, sizeof G);
  802. G.tgt = tgt;
  803. G.tfd = tfd;
  804. G.doswap = doswap;
  805. G.crc = crc;
  806. G.zsize = G.uzsize = f->f_csize;
  807. G.ucsize = f->f_st.st_size;
  808. /* initialize window, bit buffer */
  809. G.wp = 0;
  810. G.bk = 0;
  811. G.bb = 0;
  812. if (is_defl64) {
  813. G.cplens = cplens64;
  814. G.cplext = cplext64;
  815. G.cpdext = cpdext64;
  816. G.fixed_tl = G.fixed_tl64;
  817. G.fixed_bl = G.fixed_bl64;
  818. G.fixed_td = G.fixed_td64;
  819. G.fixed_bd = G.fixed_bd64;
  820. } else {
  821. G.cplens = cplens32;
  822. G.cplext = cplext32;
  823. G.cpdext = cpdext32;
  824. G.fixed_tl = G.fixed_tl32;
  825. G.fixed_bl = G.fixed_bl32;
  826. G.fixed_td = G.fixed_td32;
  827. G.fixed_bd = G.fixed_bd32;
  828. }
  829. /* decompress until the last block */
  830. do {
  831. #ifdef DEBUG
  832. G.hufts = 0;
  833. #endif
  834. if ((r = inflate_block(&G, &e)) != 0) {
  835. if ((f->f_gflag & FG_DESC) == 0)
  836. while (G.uzsize > 0)
  837. NEXTBYTE;
  838. msg(3, 0, "compression error on \"%s\"\n", f->f_name);
  839. return -1;
  840. }
  841. #ifdef DEBUG
  842. if (G.hufts > h)
  843. h = G.hufts;
  844. #endif
  845. } while (!e);
  846. Trace((stderr, "\n%u bytes in Huffman tables (%u/entry)\n",
  847. h * (unsigned)sizeof(struct huft), (unsigned)sizeof(struct huft)));
  848. if (is_defl64) {
  849. G.fixed_tl64 = G.fixed_tl;
  850. G.fixed_bl64 = G.fixed_bl;
  851. G.fixed_td64 = G.fixed_td;
  852. G.fixed_bd64 = G.fixed_bd;
  853. } else {
  854. G.fixed_tl32 = G.fixed_tl;
  855. G.fixed_bl32 = G.fixed_bl;
  856. G.fixed_td32 = G.fixed_td;
  857. G.fixed_bd32 = G.fixed_bd;
  858. }
  859. /* flush out redirSlide and return (success, unless final FLUSH failed) */
  860. (FLUSH(G.wp));
  861. if (f->f_gflag & FG_DESC)
  862. bunread((char *)G.inptr, G.incnt);
  863. return G.status;
  864. }