unshrink.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /*
  2. Copyright (c) 1990-2008 Info-ZIP. All rights reserved.
  3. See the accompanying file LICENSE, version 2000-Apr-09 or later
  4. (the contents of which are also included in unzip.h) for terms of use.
  5. If, for some reason, all these files are missing, the Info-ZIP license
  6. also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
  7. */
  8. /*---------------------------------------------------------------------------
  9. unshrink.c version 1.22 19 Mar 2008
  10. NOTE: This code may or may not infringe on the so-called "Welch
  11. patent" owned by Unisys. (From reading the patent, it appears
  12. that a pure LZW decompressor is *not* covered, but this claim has
  13. not been tested in court, and Unisys is reported to believe other-
  14. wise.) It is therefore the responsibility of the user to acquire
  15. whatever license(s) may be required for legal use of this code.
  16. THE INFO-ZIP GROUP DISCLAIMS ALL LIABILITY FOR USE OF THIS CODE
  17. IN VIOLATION OF APPLICABLE PATENT LAW.
  18. Shrinking is basically a dynamic LZW algorithm with allowed code sizes of
  19. up to 13 bits; in addition, there is provision for partial clearing of
  20. leaf nodes. PKWARE uses the special code 256 (decimal) to indicate a
  21. change in code size or a partial clear of the code tree: 256,1 for the
  22. former and 256,2 for the latter. [Note that partial clearing can "orphan"
  23. nodes: the parent-to-be can be cleared before its new child is added,
  24. but the child is added anyway (as an orphan, as though the parent still
  25. existed). When the tree fills up to the point where the parent node is
  26. reused, the orphan is effectively "adopted." Versions prior to 1.05 were
  27. affected more due to greater use of pointers (to children and siblings
  28. as well as parents).]
  29. This replacement version of unshrink.c was written from scratch. It is
  30. based only on the algorithms described in Mark Nelson's _The Data Compres-
  31. sion Book_ and in Terry Welch's original paper in the June 1984 issue of
  32. IEEE _Computer_; no existing source code, including any in Nelson's book,
  33. was used.
  34. Memory requirements have been reduced in this version and are now no more
  35. than the original Sam Smith code. This is still larger than any of the
  36. other algorithms: at a minimum, 8K+8K+16K (stack+values+parents) assuming
  37. 16-bit short ints, and this does not even include the output buffer (the
  38. other algorithms leave the uncompressed data in the work area, typically
  39. called slide[]). For machines with a 64KB data space this is a problem,
  40. particularly when text conversion is required and line endings have more
  41. than one character. UnZip's solution is to use two roughly equal halves
  42. of outbuf for the ASCII conversion in such a case; the "unshrink" argument
  43. to flush() signals that this is the case.
  44. For large-memory machines, a second outbuf is allocated for translations,
  45. but only if unshrinking and only if translations are required.
  46. | binary mode | text mode
  47. ---------------------------------------------------
  48. big mem | big outbuf | big outbuf + big outbuf2 <- malloc'd here
  49. small mem | small outbuf | half + half small outbuf
  50. Copyright 1994, 1995 Greg Roelofs. See the accompanying file "COPYING"
  51. in UnZip 5.20 (or later) source or binary distributions.
  52. ---------------------------------------------------------------------------*/
  53. #define __UNSHRINK_C /* identifies this source module */
  54. #define UNZIP_INTERNAL
  55. #include "unzip.h"
  56. #ifndef LZW_CLEAN
  57. static void partial_clear OF((__GPRO__ int lastcodeused));
  58. #ifdef DEBUG
  59. # define OUTDBG(c) \
  60. if ((c)<32 || (c)>=127) fprintf(stderr,"\\x%02x",(c)); else putc((c),stderr);
  61. #else
  62. # define OUTDBG(c)
  63. #endif
  64. /* HSIZE is defined as 2^13 (8192) in unzip.h (resp. unzpriv.h */
  65. #define BOGUSCODE 256
  66. #define FLAG_BITS parent /* upper bits of parent[] used as flag bits */
  67. #define CODE_MASK (HSIZE - 1) /* 0x1fff (lower bits are parent's index) */
  68. #define FREE_CODE HSIZE /* 0x2000 (code is unused or was cleared) */
  69. #define HAS_CHILD (HSIZE << 1) /* 0x4000 (code has a child--do not clear) */
  70. #define parent G.area.shrink.Parent
  71. #define Value G.area.shrink.value /* "value" conflicts with Pyramid ioctl.h */
  72. #define stack G.area.shrink.Stack
  73. /***********************/
  74. /* Function unshrink() */
  75. /***********************/
  76. int unshrink(__G)
  77. __GDEF
  78. {
  79. uch *stacktop = stack + (HSIZE - 1);
  80. register uch *newstr;
  81. uch finalval;
  82. int codesize=9, len, error;
  83. shrint code, oldcode, curcode;
  84. shrint lastfreecode;
  85. unsigned int outbufsiz;
  86. #if (defined(DLL) && !defined(NO_SLIDE_REDIR))
  87. /* Normally realbuf and outbuf will be the same. However, if the data
  88. * are redirected to a large memory buffer, realbuf will point to the
  89. * new location while outbuf will remain pointing to the malloc'd
  90. * memory buffer. */
  91. uch *realbuf = G.outbuf;
  92. #else
  93. # define realbuf G.outbuf
  94. #endif
  95. /*---------------------------------------------------------------------------
  96. Initialize various variables.
  97. ---------------------------------------------------------------------------*/
  98. lastfreecode = BOGUSCODE;
  99. #ifndef VMS /* VMS uses its own buffer scheme for textmode flush(). */
  100. #ifndef SMALL_MEM
  101. /* non-memory-limited machines: allocate second (large) buffer for
  102. * textmode conversion in flush(), but only if needed */
  103. if (G.pInfo->textmode && !G.outbuf2 &&
  104. (G.outbuf2 = (uch *)malloc(TRANSBUFSIZ)) == (uch *)NULL)
  105. return PK_MEM3;
  106. #endif
  107. #endif /* !VMS */
  108. for (code = 0; code < BOGUSCODE; ++code) {
  109. Value[code] = (uch)code;
  110. parent[code] = BOGUSCODE;
  111. }
  112. for (code = BOGUSCODE+1; code < HSIZE; ++code)
  113. parent[code] = FREE_CODE;
  114. #if (defined(DLL) && !defined(NO_SLIDE_REDIR))
  115. if (G.redirect_slide) { /* use normal outbuf unless we're a DLL routine */
  116. realbuf = G.redirect_buffer;
  117. outbufsiz = (unsigned)G.redirect_size;
  118. } else
  119. #endif
  120. #ifdef DLL
  121. if (G.pInfo->textmode && !G.redirect_data)
  122. #else
  123. if (G.pInfo->textmode)
  124. #endif
  125. outbufsiz = RAWBUFSIZ;
  126. else
  127. outbufsiz = OUTBUFSIZ;
  128. G.outptr = realbuf;
  129. G.outcnt = 0L;
  130. /*---------------------------------------------------------------------------
  131. Get and output first code, then loop over remaining ones.
  132. ---------------------------------------------------------------------------*/
  133. READBITS(codesize, oldcode)
  134. if (G.zipeof)
  135. return PK_OK;
  136. finalval = (uch)oldcode;
  137. OUTDBG(finalval)
  138. *G.outptr++ = finalval;
  139. ++G.outcnt;
  140. while (TRUE) {
  141. READBITS(codesize, code)
  142. if (G.zipeof)
  143. break;
  144. if (code == BOGUSCODE) { /* possible to have consecutive escapes? */
  145. READBITS(codesize, code)
  146. if (G.zipeof)
  147. break;
  148. if (code == 1) {
  149. ++codesize;
  150. Trace((stderr, " (codesize now %d bits)\n", codesize));
  151. if (codesize > MAX_BITS) return PK_ERR;
  152. } else if (code == 2) {
  153. Trace((stderr, " (partial clear code)\n"));
  154. /* clear leafs (nodes with no children) */
  155. partial_clear(__G__ lastfreecode);
  156. Trace((stderr, " (done with partial clear)\n"));
  157. lastfreecode = BOGUSCODE; /* reset start of free-node search */
  158. }
  159. continue;
  160. }
  161. /*-----------------------------------------------------------------------
  162. Translate code: traverse tree from leaf back to root.
  163. -----------------------------------------------------------------------*/
  164. newstr = stacktop;
  165. curcode = code;
  166. if (parent[code] == FREE_CODE) {
  167. /* or (FLAG_BITS[code] & FREE_CODE)? */
  168. Trace((stderr, " (found a KwKwK code %d; oldcode = %d)\n", code,
  169. oldcode));
  170. *newstr-- = finalval;
  171. code = oldcode;
  172. }
  173. while (code != BOGUSCODE) {
  174. if (newstr < stack) {
  175. /* Bogus compression stream caused buffer underflow! */
  176. Trace((stderr, "unshrink stack overflow!\n"));
  177. return PK_ERR;
  178. }
  179. if (parent[code] == FREE_CODE) {
  180. /* or (FLAG_BITS[code] & FREE_CODE)? */
  181. Trace((stderr, " (found a KwKwK code %d; oldcode = %d)\n",
  182. code, oldcode));
  183. *newstr-- = finalval;
  184. code = oldcode;
  185. } else {
  186. *newstr-- = Value[code];
  187. code = (shrint)(parent[code] & CODE_MASK);
  188. }
  189. }
  190. len = (int)(stacktop - newstr++);
  191. finalval = *newstr;
  192. /*-----------------------------------------------------------------------
  193. Write expanded string in reverse order to output buffer.
  194. -----------------------------------------------------------------------*/
  195. Trace((stderr,
  196. "code %4d; oldcode %4d; char %3d (%c); len %d; string [", curcode,
  197. oldcode, (int)(*newstr), (*newstr<32 || *newstr>=127)? ' ':*newstr,
  198. len));
  199. {
  200. register uch *p;
  201. for (p = newstr; p < newstr+len; ++p) {
  202. *G.outptr++ = *p;
  203. OUTDBG(*p)
  204. if (++G.outcnt == outbufsiz) {
  205. Trace((stderr, "doing flush(), outcnt = %lu\n", G.outcnt));
  206. if ((error = flush(__G__ realbuf, G.outcnt, TRUE)) != 0) {
  207. Trace((stderr, "unshrink: flush() error (%d)\n",
  208. error));
  209. return error;
  210. }
  211. G.outptr = realbuf;
  212. G.outcnt = 0L;
  213. Trace((stderr, "done with flush()\n"));
  214. }
  215. }
  216. }
  217. /*-----------------------------------------------------------------------
  218. Add new leaf (first character of newstr) to tree as child of oldcode.
  219. -----------------------------------------------------------------------*/
  220. /* search for freecode */
  221. code = (shrint)(lastfreecode + 1);
  222. /* add if-test before loop for speed? */
  223. while ((code < HSIZE) && (parent[code] != FREE_CODE))
  224. ++code;
  225. lastfreecode = code;
  226. Trace((stderr, "]; newcode %d\n", code));
  227. if (code >= HSIZE)
  228. /* invalid compressed data caused max-code overflow! */
  229. return PK_ERR;
  230. Value[code] = finalval;
  231. parent[code] = oldcode;
  232. oldcode = curcode;
  233. }
  234. /*---------------------------------------------------------------------------
  235. Flush any remaining data and return to sender...
  236. ---------------------------------------------------------------------------*/
  237. if (G.outcnt > 0L) {
  238. Trace((stderr, "doing final flush(), outcnt = %lu\n", G.outcnt));
  239. if ((error = flush(__G__ realbuf, G.outcnt, TRUE)) != 0) {
  240. Trace((stderr, "unshrink: flush() error (%d)\n", error));
  241. return error;
  242. }
  243. Trace((stderr, "done with flush()\n"));
  244. }
  245. return PK_OK;
  246. } /* end function unshrink() */
  247. /****************************/
  248. /* Function partial_clear() */ /* no longer recursive... */
  249. /****************************/
  250. static void partial_clear(__G__ lastcodeused)
  251. __GDEF
  252. int lastcodeused;
  253. {
  254. register shrint code;
  255. /* clear all nodes which have no children (i.e., leaf nodes only) */
  256. /* first loop: mark each parent as such */
  257. for (code = BOGUSCODE+1; code <= lastcodeused; ++code) {
  258. register shrint cparent = (shrint)(parent[code] & CODE_MASK);
  259. if (cparent > BOGUSCODE)
  260. FLAG_BITS[cparent] |= HAS_CHILD; /* set parent's child-bit */
  261. }
  262. /* second loop: clear all nodes *not* marked as parents; reset flag bits */
  263. for (code = BOGUSCODE+1; code <= lastcodeused; ++code) {
  264. if (FLAG_BITS[code] & HAS_CHILD) /* just clear child-bit */
  265. FLAG_BITS[code] &= ~HAS_CHILD;
  266. else { /* leaf: lose it */
  267. Trace((stderr, "%d\n", code));
  268. parent[code] = FREE_CODE;
  269. }
  270. }
  271. return;
  272. }
  273. #endif /* !LZW_CLEAN */