gzip.c 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Gzip implementation for busybox
  4. *
  5. * Based on GNU gzip Copyright (C) 1992-1993 Jean-loup Gailly.
  6. *
  7. * Originally adjusted for busybox by Charles P. Wright <cpw@unix.asb.com>
  8. * "this is a stripped down version of gzip I put into busybox, it does
  9. * only standard in to standard out with -9 compression. It also requires
  10. * the zcat module for some important functions."
  11. *
  12. * Adjusted further by Erik Andersen <andersen@codepoet.org> to support
  13. * files as well as stdin/stdout, and to generally behave itself wrt
  14. * command line handling.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  17. */
  18. /* These defines are very important for BusyBox. Without these,
  19. * huge chunks of ram are pre-allocated making the BusyBox bss
  20. * size Freaking Huge(tm), which is a bad thing.*/
  21. #define SMALL_MEM
  22. #define DYN_ALLOC
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25. #include <string.h>
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #include <sys/types.h>
  29. #include <signal.h>
  30. #include <utime.h>
  31. #include <ctype.h>
  32. #include <sys/types.h>
  33. #include <unistd.h>
  34. #include <dirent.h>
  35. #include <fcntl.h>
  36. #include <time.h>
  37. #include "busybox.h"
  38. typedef unsigned char uch;
  39. typedef unsigned short ush;
  40. typedef unsigned long ulg;
  41. /* Return codes from gzip */
  42. #define OK 0
  43. #define ERROR 1
  44. #define WARNING 2
  45. /* Compression methods (see algorithm.doc) */
  46. /* Only STORED and DEFLATED are supported by this BusyBox module */
  47. #define STORED 0
  48. /* methods 4 to 7 reserved */
  49. #define DEFLATED 8
  50. /* To save memory for 16 bit systems, some arrays are overlaid between
  51. * the various modules:
  52. * deflate: prev+head window d_buf l_buf outbuf
  53. * unlzw: tab_prefix tab_suffix stack inbuf outbuf
  54. * For compression, input is done in window[]. For decompression, output
  55. * is done in window except for unlzw.
  56. */
  57. #ifndef INBUFSIZ
  58. # ifdef SMALL_MEM
  59. # define INBUFSIZ 0x2000 /* input buffer size */
  60. # else
  61. # define INBUFSIZ 0x8000 /* input buffer size */
  62. # endif
  63. #endif
  64. #define INBUF_EXTRA 64 /* required by unlzw() */
  65. #ifndef OUTBUFSIZ
  66. # ifdef SMALL_MEM
  67. # define OUTBUFSIZ 8192 /* output buffer size */
  68. # else
  69. # define OUTBUFSIZ 16384 /* output buffer size */
  70. # endif
  71. #endif
  72. #define OUTBUF_EXTRA 2048 /* required by unlzw() */
  73. #ifndef DIST_BUFSIZE
  74. # ifdef SMALL_MEM
  75. # define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
  76. # else
  77. # define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
  78. # endif
  79. #endif
  80. #ifdef DYN_ALLOC
  81. # define DECLARE(type, array, size) static type * array
  82. # define ALLOC(type, array, size) { \
  83. array = (type*)xcalloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
  84. }
  85. # define FREE(array) {free(array), array=NULL;}
  86. #else
  87. # define DECLARE(type, array, size) static type array[size]
  88. # define ALLOC(type, array, size)
  89. # define FREE(array)
  90. #endif
  91. #define tab_suffix window
  92. #define tab_prefix prev /* hash link (see deflate.c) */
  93. #define head (prev+WSIZE) /* hash head (see deflate.c) */
  94. static long bytes_in; /* number of input bytes */
  95. #define isize bytes_in
  96. /* for compatibility with old zip sources (to be cleaned) */
  97. typedef int file_t; /* Do not use stdio */
  98. #define NO_FILE (-1) /* in memory compression */
  99. #define PACK_MAGIC "\037\036" /* Magic header for packed files */
  100. #define GZIP_MAGIC "\037\213" /* Magic header for gzip files, 1F 8B */
  101. #define OLD_GZIP_MAGIC "\037\236" /* Magic header for gzip 0.5 = freeze 1.x */
  102. #define LZH_MAGIC "\037\240" /* Magic header for SCO LZH Compress files */
  103. #define PKZIP_MAGIC "\120\113\003\004" /* Magic header for pkzip files */
  104. /* gzip flag byte */
  105. #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
  106. #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
  107. #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
  108. #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
  109. #define COMMENT 0x10 /* bit 4 set: file comment present */
  110. #define RESERVED 0xC0 /* bit 6,7: reserved */
  111. /* internal file attribute */
  112. #define UNKNOWN 0xffff
  113. #define BINARY 0
  114. #define ASCII 1
  115. #ifndef WSIZE
  116. # define WSIZE 0x8000 /* window size--must be a power of two, and */
  117. #endif /* at least 32K for zip's deflate method */
  118. #define MIN_MATCH 3
  119. #define MAX_MATCH 258
  120. /* The minimum and maximum match lengths */
  121. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  122. /* Minimum amount of lookahead, except at the end of the input file.
  123. * See deflate.c for comments about the MIN_MATCH+1.
  124. */
  125. #define MAX_DIST (WSIZE-MIN_LOOKAHEAD)
  126. /* In order to simplify the code, particularly on 16 bit machines, match
  127. * distances are limited to MAX_DIST instead of WSIZE.
  128. */
  129. /* put_byte is used for the compressed output */
  130. #define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
  131. flush_outbuf();}
  132. /* Output a 32 bit value to the bit stream, lsb first */
  133. #if 0
  134. #define put_long(n) { \
  135. put_short((n) & 0xffff); \
  136. put_short(((ulg)(n)) >> 16); \
  137. }
  138. #endif
  139. #define seekable() 0 /* force sequential output */
  140. #define translate_eol 0 /* no option -a yet */
  141. /* Diagnostic functions */
  142. #ifdef DEBUG
  143. # define Assert(cond,msg) {if(!(cond)) bb_error_msg(msg);}
  144. # define Trace(x) fprintf x
  145. # define Tracev(x) {if (verbose) fprintf x ;}
  146. # define Tracevv(x) {if (verbose>1) fprintf x ;}
  147. # define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
  148. # define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
  149. #else
  150. # define Assert(cond,msg)
  151. # define Trace(x)
  152. # define Tracev(x)
  153. # define Tracevv(x)
  154. # define Tracec(c,x)
  155. # define Tracecv(c,x)
  156. #endif
  157. #define WARN(msg) {if (!quiet) fprintf msg ; \
  158. if (exit_code == OK) exit_code = WARNING;}
  159. #ifndef MAX_PATH_LEN
  160. # define MAX_PATH_LEN 1024 /* max pathname length */
  161. #endif
  162. /* from zip.c: */
  163. static int zip(int in, int out);
  164. static int file_read(char *buf, unsigned size);
  165. /* from deflate.c */
  166. static void lm_init(ush * flags);
  167. static ulg deflate(void);
  168. /* from trees.c */
  169. static void ct_init(ush * attr, int *methodp);
  170. static int ct_tally(int dist, int lc);
  171. static ulg flush_block(char *buf, ulg stored_len, int eof);
  172. /* from bits.c */
  173. static void bi_init(file_t zipfile);
  174. static void send_bits(int value, int length);
  175. static unsigned bi_reverse(unsigned value, int length);
  176. static void bi_windup(void);
  177. static void copy_block(char *buf, unsigned len, int header);
  178. static int (*read_buf) (char *buf, unsigned size);
  179. /* from util.c: */
  180. static void flush_outbuf(void);
  181. /* lzw.h -- define the lzw functions.
  182. * Copyright (C) 1992-1993 Jean-loup Gailly.
  183. * This is free software; you can redistribute it and/or modify it under the
  184. * terms of the GNU General Public License, see the file COPYING.
  185. */
  186. #ifndef BITS
  187. # define BITS 16
  188. #endif
  189. #define INIT_BITS 9 /* Initial number of bits per code */
  190. #define BIT_MASK 0x1f /* Mask for 'number of compression bits' */
  191. /* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
  192. * It's a pity that old uncompress does not check bit 0x20. That makes
  193. * extension of the format actually undesirable because old compress
  194. * would just crash on the new format instead of giving a meaningful
  195. * error message. It does check the number of bits, but it's more
  196. * helpful to say "unsupported format, get a new version" than
  197. * "can only handle 16 bits".
  198. */
  199. /* tailor.h -- target dependent definitions
  200. * Copyright (C) 1992-1993 Jean-loup Gailly.
  201. * This is free software; you can redistribute it and/or modify it under the
  202. * terms of the GNU General Public License, see the file COPYING.
  203. */
  204. /* The target dependent definitions should be defined here only.
  205. * The target dependent functions should be defined in tailor.c.
  206. */
  207. /* Common defaults */
  208. #ifndef OS_CODE
  209. # define OS_CODE 0x03 /* assume Unix */
  210. #endif
  211. #ifndef PATH_SEP
  212. # define PATH_SEP '/'
  213. #endif
  214. #ifndef OPTIONS_VAR
  215. # define OPTIONS_VAR "GZIP"
  216. #endif
  217. #ifndef Z_SUFFIX
  218. # define Z_SUFFIX ".gz"
  219. #endif
  220. #ifdef MAX_EXT_CHARS
  221. # define MAX_SUFFIX MAX_EXT_CHARS
  222. #else
  223. # define MAX_SUFFIX 30
  224. #endif
  225. /* global buffers */
  226. DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
  227. DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
  228. DECLARE(ush, d_buf, DIST_BUFSIZE);
  229. DECLARE(uch, window, 2L * WSIZE);
  230. DECLARE(ush, tab_prefix, 1L << BITS);
  231. static int foreground; /* set if program run in foreground */
  232. static int method = DEFLATED; /* compression method */
  233. static int exit_code = OK; /* program exit code */
  234. static int part_nb; /* number of parts in .gz file */
  235. static long time_stamp; /* original time stamp (modification time) */
  236. static long ifile_size; /* input file size, -1 for devices (debug only) */
  237. static char z_suffix[MAX_SUFFIX + 1]; /* default suffix (can be set with --suffix) */
  238. static int z_len; /* strlen(z_suffix) */
  239. static int ifd; /* input file descriptor */
  240. static int ofd; /* output file descriptor */
  241. static unsigned insize; /* valid bytes in inbuf */
  242. static unsigned outcnt; /* bytes in output buffer */
  243. /* Output a 16 bit value, lsb first */
  244. static void put_short(ush w)
  245. {
  246. if (outcnt < OUTBUFSIZ - 2) {
  247. outbuf[outcnt++] = (uch) ((w) & 0xff);
  248. outbuf[outcnt++] = (uch) ((ush) (w) >> 8);
  249. } else {
  250. put_byte((uch) ((w) & 0xff));
  251. put_byte((uch) ((ush) (w) >> 8));
  252. }
  253. }
  254. /* ========================================================================
  255. * Signal and error handler.
  256. */
  257. static void abort_gzip(int ATTRIBUTE_UNUSED ignored)
  258. {
  259. exit(ERROR);
  260. }
  261. /* ===========================================================================
  262. * Clear input and output buffers
  263. */
  264. static void clear_bufs(void)
  265. {
  266. outcnt = 0;
  267. insize = 0;
  268. bytes_in = 0L;
  269. }
  270. /* ===========================================================================
  271. * Does the same as write(), but also handles partial pipe writes and checks
  272. * for error return.
  273. */
  274. static void write_buf(int fd, void *buf, unsigned cnt)
  275. {
  276. unsigned n;
  277. while ((n = write(fd, buf, cnt)) != cnt) {
  278. if (n == (unsigned) (-1)) bb_error_msg_and_die("can't write");
  279. cnt -= n;
  280. buf = (void *) ((char *) buf + n);
  281. }
  282. }
  283. /* ===========================================================================
  284. * Run a set of bytes through the crc shift register. If s is a NULL
  285. * pointer, then initialize the crc shift register contents instead.
  286. * Return the current crc in either case.
  287. */
  288. static ulg updcrc(uch * s, unsigned n)
  289. {
  290. static ulg crc = (ulg) 0xffffffffL; /* shift register contents */
  291. register ulg c; /* temporary variable */
  292. static unsigned long crc_32_tab[256];
  293. if (crc_32_tab[1] == 0x00000000L) {
  294. unsigned long csr; /* crc shift register */
  295. const unsigned long e = 0xedb88320L; /* polynomial exclusive-or pattern */
  296. int i; /* counter for all possible eight bit values */
  297. int k; /* byte being shifted into crc apparatus */
  298. /* Compute table of CRC's. */
  299. for (i = 1; i < 256; i++) {
  300. csr = i;
  301. /* The idea to initialize the register with the byte instead of
  302. * zero was stolen from Haruhiko Okumura's ar002
  303. */
  304. for (k = 8; k; k--)
  305. csr = csr & 1 ? (csr >> 1) ^ e : csr >> 1;
  306. crc_32_tab[i] = csr;
  307. }
  308. }
  309. if (s == NULL) {
  310. c = 0xffffffffL;
  311. } else {
  312. c = crc;
  313. if (n)
  314. do {
  315. c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
  316. } while (--n);
  317. }
  318. crc = c;
  319. return c ^ 0xffffffffL; /* (instead of ~c for 64-bit machines) */
  320. }
  321. /* bits.c -- output variable-length bit strings
  322. * Copyright (C) 1992-1993 Jean-loup Gailly
  323. * This is free software; you can redistribute it and/or modify it under the
  324. * terms of the GNU General Public License, see the file COPYING.
  325. */
  326. /*
  327. * PURPOSE
  328. *
  329. * Output variable-length bit strings. Compression can be done
  330. * to a file or to memory. (The latter is not supported in this version.)
  331. *
  332. * DISCUSSION
  333. *
  334. * The PKZIP "deflate" file format interprets compressed file data
  335. * as a sequence of bits. Multi-bit strings in the file may cross
  336. * byte boundaries without restriction.
  337. *
  338. * The first bit of each byte is the low-order bit.
  339. *
  340. * The routines in this file allow a variable-length bit value to
  341. * be output right-to-left (useful for literal values). For
  342. * left-to-right output (useful for code strings from the tree routines),
  343. * the bits must have been reversed first with bi_reverse().
  344. *
  345. * For in-memory compression, the compressed bit stream goes directly
  346. * into the requested output buffer. The input data is read in blocks
  347. * by the mem_read() function. The buffer is limited to 64K on 16 bit
  348. * machines.
  349. *
  350. * INTERFACE
  351. *
  352. * void bi_init (FILE *zipfile)
  353. * Initialize the bit string routines.
  354. *
  355. * void send_bits (int value, int length)
  356. * Write out a bit string, taking the source bits right to
  357. * left.
  358. *
  359. * int bi_reverse (int value, int length)
  360. * Reverse the bits of a bit string, taking the source bits left to
  361. * right and emitting them right to left.
  362. *
  363. * void bi_windup (void)
  364. * Write out any remaining bits in an incomplete byte.
  365. *
  366. * void copy_block(char *buf, unsigned len, int header)
  367. * Copy a stored block to the zip file, storing first the length and
  368. * its one's complement if requested.
  369. *
  370. */
  371. /* ===========================================================================
  372. * Local data used by the "bit string" routines.
  373. */
  374. static file_t zfile; /* output gzip file */
  375. static unsigned short bi_buf;
  376. /* Output buffer. bits are inserted starting at the bottom (least significant
  377. * bits).
  378. */
  379. #define Buf_size (8 * 2*sizeof(char))
  380. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  381. * more than 16 bits on some systems.)
  382. */
  383. static int bi_valid;
  384. /* Current input function. Set to mem_read for in-memory compression */
  385. #ifdef DEBUG
  386. ulg bits_sent; /* bit length of the compressed data */
  387. #endif
  388. /* ===========================================================================
  389. * Initialize the bit string routines.
  390. */
  391. static void bi_init(file_t zipfile)
  392. {
  393. zfile = zipfile;
  394. bi_buf = 0;
  395. bi_valid = 0;
  396. #ifdef DEBUG
  397. bits_sent = 0L;
  398. #endif
  399. /* Set the defaults for file compression. They are set by memcompress
  400. * for in-memory compression.
  401. */
  402. if (zfile != NO_FILE) {
  403. read_buf = file_read;
  404. }
  405. }
  406. /* ===========================================================================
  407. * Send a value on a given number of bits.
  408. * IN assertion: length <= 16 and value fits in length bits.
  409. */
  410. static void send_bits(int value, int length)
  411. {
  412. #ifdef DEBUG
  413. Tracev((stderr, " l %2d v %4x ", length, value));
  414. Assert(length > 0 && length <= 15, "invalid length");
  415. bits_sent += (ulg) length;
  416. #endif
  417. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  418. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  419. * unused bits in value.
  420. */
  421. if (bi_valid > (int) Buf_size - length) {
  422. bi_buf |= (value << bi_valid);
  423. put_short(bi_buf);
  424. bi_buf = (ush) value >> (Buf_size - bi_valid);
  425. bi_valid += length - Buf_size;
  426. } else {
  427. bi_buf |= value << bi_valid;
  428. bi_valid += length;
  429. }
  430. }
  431. /* ===========================================================================
  432. * Reverse the first len bits of a code, using straightforward code (a faster
  433. * method would use a table)
  434. * IN assertion: 1 <= len <= 15
  435. */
  436. static unsigned bi_reverse(unsigned code, int len)
  437. {
  438. register unsigned res = 0;
  439. do {
  440. res |= code & 1;
  441. code >>= 1, res <<= 1;
  442. } while (--len > 0);
  443. return res >> 1;
  444. }
  445. /* ===========================================================================
  446. * Write out any remaining bits in an incomplete byte.
  447. */
  448. static void bi_windup(void)
  449. {
  450. if (bi_valid > 8) {
  451. put_short(bi_buf);
  452. } else if (bi_valid > 0) {
  453. put_byte(bi_buf);
  454. }
  455. bi_buf = 0;
  456. bi_valid = 0;
  457. #ifdef DEBUG
  458. bits_sent = (bits_sent + 7) & ~7;
  459. #endif
  460. }
  461. /* ===========================================================================
  462. * Copy a stored block to the zip file, storing first the length and its
  463. * one's complement if requested.
  464. */
  465. static void copy_block(char *buf, unsigned len, int header)
  466. {
  467. bi_windup(); /* align on byte boundary */
  468. if (header) {
  469. put_short((ush) len);
  470. put_short((ush) ~ len);
  471. #ifdef DEBUG
  472. bits_sent += 2 * 16;
  473. #endif
  474. }
  475. #ifdef DEBUG
  476. bits_sent += (ulg) len << 3;
  477. #endif
  478. while (len--) {
  479. put_byte(*buf++);
  480. }
  481. }
  482. /* deflate.c -- compress data using the deflation algorithm
  483. * Copyright (C) 1992-1993 Jean-loup Gailly
  484. * This is free software; you can redistribute it and/or modify it under the
  485. * terms of the GNU General Public License, see the file COPYING.
  486. */
  487. /*
  488. * PURPOSE
  489. *
  490. * Identify new text as repetitions of old text within a fixed-
  491. * length sliding window trailing behind the new text.
  492. *
  493. * DISCUSSION
  494. *
  495. * The "deflation" process depends on being able to identify portions
  496. * of the input text which are identical to earlier input (within a
  497. * sliding window trailing behind the input currently being processed).
  498. *
  499. * The most straightforward technique turns out to be the fastest for
  500. * most input files: try all possible matches and select the longest.
  501. * The key feature of this algorithm is that insertions into the string
  502. * dictionary are very simple and thus fast, and deletions are avoided
  503. * completely. Insertions are performed at each input character, whereas
  504. * string matches are performed only when the previous match ends. So it
  505. * is preferable to spend more time in matches to allow very fast string
  506. * insertions and avoid deletions. The matching algorithm for small
  507. * strings is inspired from that of Rabin & Karp. A brute force approach
  508. * is used to find longer strings when a small match has been found.
  509. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  510. * (by Leonid Broukhis).
  511. * A previous version of this file used a more sophisticated algorithm
  512. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  513. * time, but has a larger average cost, uses more memory and is patented.
  514. * However the F&G algorithm may be faster for some highly redundant
  515. * files if the parameter max_chain_length (described below) is too large.
  516. *
  517. * ACKNOWLEDGMENTS
  518. *
  519. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  520. * I found it in 'freeze' written by Leonid Broukhis.
  521. * Thanks to many info-zippers for bug reports and testing.
  522. *
  523. * REFERENCES
  524. *
  525. * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  526. *
  527. * A description of the Rabin and Karp algorithm is given in the book
  528. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  529. *
  530. * Fiala,E.R., and Greene,D.H.
  531. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  532. *
  533. * INTERFACE
  534. *
  535. * void lm_init (int pack_level, ush *flags)
  536. * Initialize the "longest match" routines for a new file
  537. *
  538. * ulg deflate (void)
  539. * Processes a new input file and return its compressed length. Sets
  540. * the compressed length, crc, deflate flags and internal file
  541. * attributes.
  542. */
  543. /* ===========================================================================
  544. * Configuration parameters
  545. */
  546. /* Compile with MEDIUM_MEM to reduce the memory requirements or
  547. * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  548. * entire input file can be held in memory (not possible on 16 bit systems).
  549. * Warning: defining these symbols affects HASH_BITS (see below) and thus
  550. * affects the compression ratio. The compressed output
  551. * is still correct, and might even be smaller in some cases.
  552. */
  553. #ifdef SMALL_MEM
  554. # define HASH_BITS 13 /* Number of bits used to hash strings */
  555. #endif
  556. #ifdef MEDIUM_MEM
  557. # define HASH_BITS 14
  558. #endif
  559. #ifndef HASH_BITS
  560. # define HASH_BITS 15
  561. /* For portability to 16 bit machines, do not use values above 15. */
  562. #endif
  563. /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
  564. * window with tab_suffix. Check that we can do this:
  565. */
  566. #if (WSIZE<<1) > (1<<BITS)
  567. # error cannot overlay window with tab_suffix and prev with tab_prefix0
  568. #endif
  569. #if HASH_BITS > BITS-1
  570. # error cannot overlay head with tab_prefix1
  571. #endif
  572. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  573. #define HASH_MASK (HASH_SIZE-1)
  574. #define WMASK (WSIZE-1)
  575. /* HASH_SIZE and WSIZE must be powers of two */
  576. #define NIL 0
  577. /* Tail of hash chains */
  578. #define FAST 4
  579. #define SLOW 2
  580. /* speed options for the general purpose bit flag */
  581. #ifndef TOO_FAR
  582. # define TOO_FAR 4096
  583. #endif
  584. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  585. /* ===========================================================================
  586. * Local data used by the "longest match" routines.
  587. */
  588. typedef ush Pos;
  589. typedef unsigned IPos;
  590. /* A Pos is an index in the character window. We use short instead of int to
  591. * save space in the various tables. IPos is used only for parameter passing.
  592. */
  593. /* DECLARE(uch, window, 2L*WSIZE); */
  594. /* Sliding window. Input bytes are read into the second half of the window,
  595. * and move to the first half later to keep a dictionary of at least WSIZE
  596. * bytes. With this organization, matches are limited to a distance of
  597. * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  598. * performed with a length multiple of the block size. Also, it limits
  599. * the window size to 64K, which is quite useful on MSDOS.
  600. * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  601. * be less efficient).
  602. */
  603. /* DECLARE(Pos, prev, WSIZE); */
  604. /* Link to older string with same hash index. To limit the size of this
  605. * array to 64K, this link is maintained only for the last 32K strings.
  606. * An index in this array is thus a window index modulo 32K.
  607. */
  608. /* DECLARE(Pos, head, 1<<HASH_BITS); */
  609. /* Heads of the hash chains or NIL. */
  610. static const ulg window_size = (ulg) 2 * WSIZE;
  611. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  612. * input file length plus MIN_LOOKAHEAD.
  613. */
  614. static long block_start;
  615. /* window position at the beginning of the current output block. Gets
  616. * negative when the window is moved backwards.
  617. */
  618. static unsigned ins_h; /* hash index of string to be inserted */
  619. #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  620. /* Number of bits by which ins_h and del_h must be shifted at each
  621. * input step. It must be such that after MIN_MATCH steps, the oldest
  622. * byte no longer takes part in the hash key, that is:
  623. * H_SHIFT * MIN_MATCH >= HASH_BITS
  624. */
  625. static unsigned int prev_length;
  626. /* Length of the best match at previous step. Matches not greater than this
  627. * are discarded. This is used in the lazy match evaluation.
  628. */
  629. static unsigned strstart; /* start of string to insert */
  630. static unsigned match_start; /* start of matching string */
  631. static int eofile; /* flag set at end of input file */
  632. static unsigned lookahead; /* number of valid bytes ahead in window */
  633. enum {
  634. max_chain_length = 4096,
  635. /* To speed up deflation, hash chains are never searched beyond this length.
  636. * A higher limit improves compression ratio but degrades the speed.
  637. */
  638. max_lazy_match = 258,
  639. /* Attempt to find a better match only when the current match is strictly
  640. * smaller than this value. This mechanism is used only for compression
  641. * levels >= 4.
  642. */
  643. max_insert_length = max_lazy_match,
  644. /* Insert new strings in the hash table only if the match length
  645. * is not greater than this length. This saves time but degrades compression.
  646. * max_insert_length is used only for compression levels <= 3.
  647. */
  648. good_match = 32,
  649. /* Use a faster search when the previous match is longer than this */
  650. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  651. * the desired pack level (0..9). The values given below have been tuned to
  652. * exclude worst case performance for pathological files. Better values may be
  653. * found for specific files.
  654. */
  655. nice_match = 258 /* Stop searching when current match exceeds this */
  656. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  657. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  658. * meaning.
  659. */
  660. };
  661. #define EQUAL 0
  662. /* result of memcmp for equal strings */
  663. /* ===========================================================================
  664. * Prototypes for local functions.
  665. */
  666. static void fill_window(void);
  667. static int longest_match(IPos cur_match);
  668. #ifdef DEBUG
  669. static void check_match(IPos start, IPos match, int length);
  670. #endif
  671. /* ===========================================================================
  672. * Update a hash value with the given input byte
  673. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  674. * input characters, so that a running hash key can be computed from the
  675. * previous key instead of complete recalculation each time.
  676. */
  677. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  678. /* ===========================================================================
  679. * Insert string s in the dictionary and set match_head to the previous head
  680. * of the hash chain (the most recent string with same hash key). Return
  681. * the previous length of the hash chain.
  682. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  683. * input characters and the first MIN_MATCH bytes of s are valid
  684. * (except for the last MIN_MATCH-1 bytes of the input file).
  685. */
  686. #define INSERT_STRING(s, match_head) \
  687. (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  688. prev[(s) & WMASK] = match_head = head[ins_h], \
  689. head[ins_h] = (s))
  690. /* ===========================================================================
  691. * Initialize the "longest match" routines for a new file
  692. */
  693. static void lm_init(ush * flags)
  694. {
  695. register unsigned j;
  696. /* Initialize the hash table. */
  697. memset(head, 0, HASH_SIZE * sizeof(*head));
  698. /* prev will be initialized on the fly */
  699. *flags |= SLOW;
  700. /* ??? reduce max_chain_length for binary files */
  701. strstart = 0;
  702. block_start = 0L;
  703. lookahead = read_buf((char *) window,
  704. sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
  705. if (lookahead == 0 || lookahead == (unsigned) EOF) {
  706. eofile = 1, lookahead = 0;
  707. return;
  708. }
  709. eofile = 0;
  710. /* Make sure that we always have enough lookahead. This is important
  711. * if input comes from a device such as a tty.
  712. */
  713. while (lookahead < MIN_LOOKAHEAD && !eofile)
  714. fill_window();
  715. ins_h = 0;
  716. for (j = 0; j < MIN_MATCH - 1; j++)
  717. UPDATE_HASH(ins_h, window[j]);
  718. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  719. * not important since only literal bytes will be emitted.
  720. */
  721. }
  722. /* ===========================================================================
  723. * Set match_start to the longest match starting at the given string and
  724. * return its length. Matches shorter or equal to prev_length are discarded,
  725. * in which case the result is equal to prev_length and match_start is
  726. * garbage.
  727. * IN assertions: cur_match is the head of the hash chain for the current
  728. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  729. */
  730. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  731. * match.s. The code is functionally equivalent, so you can use the C version
  732. * if desired.
  733. */
  734. static int longest_match(IPos cur_match)
  735. {
  736. unsigned chain_length = max_chain_length; /* max hash chain length */
  737. register uch *scan = window + strstart; /* current string */
  738. register uch *match; /* matched string */
  739. register int len; /* length of current match */
  740. int best_len = prev_length; /* best match length so far */
  741. IPos limit =
  742. strstart > (IPos) MAX_DIST ? strstart - (IPos) MAX_DIST : NIL;
  743. /* Stop when cur_match becomes <= limit. To simplify the code,
  744. * we prevent matches with the string of window index 0.
  745. */
  746. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  747. * It is easy to get rid of this optimization if necessary.
  748. */
  749. #if HASH_BITS < 8 || MAX_MATCH != 258
  750. # error Code too clever
  751. #endif
  752. register uch *strend = window + strstart + MAX_MATCH;
  753. register uch scan_end1 = scan[best_len - 1];
  754. register uch scan_end = scan[best_len];
  755. /* Do not waste too much time if we already have a good match: */
  756. if (prev_length >= good_match) {
  757. chain_length >>= 2;
  758. }
  759. Assert(strstart <= window_size - MIN_LOOKAHEAD, "insufficient lookahead");
  760. do {
  761. Assert(cur_match < strstart, "no future");
  762. match = window + cur_match;
  763. /* Skip to next match if the match length cannot increase
  764. * or if the match length is less than 2:
  765. */
  766. if (match[best_len] != scan_end ||
  767. match[best_len - 1] != scan_end1 ||
  768. *match != *scan || *++match != scan[1])
  769. continue;
  770. /* The check at best_len-1 can be removed because it will be made
  771. * again later. (This heuristic is not always a win.)
  772. * It is not necessary to compare scan[2] and match[2] since they
  773. * are always equal when the other bytes match, given that
  774. * the hash keys are equal and that HASH_BITS >= 8.
  775. */
  776. scan += 2, match++;
  777. /* We check for insufficient lookahead only every 8th comparison;
  778. * the 256th check will be made at strstart+258.
  779. */
  780. do {
  781. } while (*++scan == *++match && *++scan == *++match &&
  782. *++scan == *++match && *++scan == *++match &&
  783. *++scan == *++match && *++scan == *++match &&
  784. *++scan == *++match && *++scan == *++match && scan < strend);
  785. len = MAX_MATCH - (int) (strend - scan);
  786. scan = strend - MAX_MATCH;
  787. if (len > best_len) {
  788. match_start = cur_match;
  789. best_len = len;
  790. if (len >= nice_match)
  791. break;
  792. scan_end1 = scan[best_len - 1];
  793. scan_end = scan[best_len];
  794. }
  795. } while ((cur_match = prev[cur_match & WMASK]) > limit
  796. && --chain_length != 0);
  797. return best_len;
  798. }
  799. #ifdef DEBUG
  800. /* ===========================================================================
  801. * Check that the match at match_start is indeed a match.
  802. */
  803. static void check_match(IPos start, IPos match, int length)
  804. {
  805. /* check that the match is indeed a match */
  806. if (memcmp((char *) window + match,
  807. (char *) window + start, length) != EQUAL) {
  808. bb_error_msg(" start %d, match %d, length %d", start, match, length);
  809. bb_error_msg("invalid match");
  810. }
  811. if (verbose > 1) {
  812. bb_error_msg("\\[%d,%d]", start - match, length);
  813. do {
  814. putc(window[start++], stderr);
  815. } while (--length != 0);
  816. }
  817. }
  818. #else
  819. # define check_match(start, match, length)
  820. #endif
  821. /* ===========================================================================
  822. * Fill the window when the lookahead becomes insufficient.
  823. * Updates strstart and lookahead, and sets eofile if end of input file.
  824. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  825. * OUT assertions: at least one byte has been read, or eofile is set;
  826. * file reads are performed for at least two bytes (required for the
  827. * translate_eol option).
  828. */
  829. static void fill_window(void)
  830. {
  831. register unsigned n, m;
  832. unsigned more =
  833. (unsigned) (window_size - (ulg) lookahead - (ulg) strstart);
  834. /* Amount of free space at the end of the window. */
  835. /* If the window is almost full and there is insufficient lookahead,
  836. * move the upper half to the lower one to make room in the upper half.
  837. */
  838. if (more == (unsigned) EOF) {
  839. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  840. * and lookahead == 1 (input done one byte at time)
  841. */
  842. more--;
  843. } else if (strstart >= WSIZE + MAX_DIST) {
  844. /* By the IN assertion, the window is not empty so we can't confuse
  845. * more == 0 with more == 64K on a 16 bit machine.
  846. */
  847. Assert(window_size == (ulg) 2 * WSIZE, "no sliding with BIG_MEM");
  848. memcpy((char *) window, (char *) window + WSIZE, (unsigned) WSIZE);
  849. match_start -= WSIZE;
  850. strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
  851. block_start -= (long) WSIZE;
  852. for (n = 0; n < HASH_SIZE; n++) {
  853. m = head[n];
  854. head[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
  855. }
  856. for (n = 0; n < WSIZE; n++) {
  857. m = prev[n];
  858. prev[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
  859. /* If n is not on any hash chain, prev[n] is garbage but
  860. * its value will never be used.
  861. */
  862. }
  863. more += WSIZE;
  864. }
  865. /* At this point, more >= 2 */
  866. if (!eofile) {
  867. n = read_buf((char *) window + strstart + lookahead, more);
  868. if (n == 0 || n == (unsigned) EOF) {
  869. eofile = 1;
  870. } else {
  871. lookahead += n;
  872. }
  873. }
  874. }
  875. /* ===========================================================================
  876. * Flush the current block, with given end-of-file flag.
  877. * IN assertion: strstart is set to the end of the current match.
  878. */
  879. #define FLUSH_BLOCK(eof) \
  880. flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
  881. (char*)NULL, (long)strstart - block_start, (eof))
  882. /* ===========================================================================
  883. * Same as above, but achieves better compression. We use a lazy
  884. * evaluation for matches: a match is finally adopted only if there is
  885. * no better match at the next window position.
  886. */
  887. static ulg deflate(void)
  888. {
  889. IPos hash_head; /* head of hash chain */
  890. IPos prev_match; /* previous match */
  891. int flush; /* set if current block must be flushed */
  892. int match_available = 0; /* set if previous match exists */
  893. register unsigned match_length = MIN_MATCH - 1; /* length of best match */
  894. /* Process the input block. */
  895. while (lookahead != 0) {
  896. /* Insert the string window[strstart .. strstart+2] in the
  897. * dictionary, and set hash_head to the head of the hash chain:
  898. */
  899. INSERT_STRING(strstart, hash_head);
  900. /* Find the longest match, discarding those <= prev_length.
  901. */
  902. prev_length = match_length, prev_match = match_start;
  903. match_length = MIN_MATCH - 1;
  904. if (hash_head != NIL && prev_length < max_lazy_match &&
  905. strstart - hash_head <= MAX_DIST) {
  906. /* To simplify the code, we prevent matches with the string
  907. * of window index 0 (in particular we have to avoid a match
  908. * of the string with itself at the start of the input file).
  909. */
  910. match_length = longest_match(hash_head);
  911. /* longest_match() sets match_start */
  912. if (match_length > lookahead)
  913. match_length = lookahead;
  914. /* Ignore a length 3 match if it is too distant: */
  915. if (match_length == MIN_MATCH && strstart - match_start > TOO_FAR) {
  916. /* If prev_match is also MIN_MATCH, match_start is garbage
  917. * but we will ignore the current match anyway.
  918. */
  919. match_length--;
  920. }
  921. }
  922. /* If there was a match at the previous step and the current
  923. * match is not better, output the previous match:
  924. */
  925. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  926. check_match(strstart - 1, prev_match, prev_length);
  927. flush =
  928. ct_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  929. /* Insert in hash table all strings up to the end of the match.
  930. * strstart-1 and strstart are already inserted.
  931. */
  932. lookahead -= prev_length - 1;
  933. prev_length -= 2;
  934. do {
  935. strstart++;
  936. INSERT_STRING(strstart, hash_head);
  937. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  938. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  939. * these bytes are garbage, but it does not matter since the
  940. * next lookahead bytes will always be emitted as literals.
  941. */
  942. } while (--prev_length != 0);
  943. match_available = 0;
  944. match_length = MIN_MATCH - 1;
  945. strstart++;
  946. if (flush)
  947. FLUSH_BLOCK(0), block_start = strstart;
  948. } else if (match_available) {
  949. /* If there was no match at the previous position, output a
  950. * single literal. If there was a match but the current match
  951. * is longer, truncate the previous match to a single literal.
  952. */
  953. Tracevv((stderr, "%c", window[strstart - 1]));
  954. if (ct_tally(0, window[strstart - 1])) {
  955. FLUSH_BLOCK(0), block_start = strstart;
  956. }
  957. strstart++;
  958. lookahead--;
  959. } else {
  960. /* There is no previous match to compare with, wait for
  961. * the next step to decide.
  962. */
  963. match_available = 1;
  964. strstart++;
  965. lookahead--;
  966. }
  967. Assert(strstart <= isize && lookahead <= isize, "a bit too far");
  968. /* Make sure that we always have enough lookahead, except
  969. * at the end of the input file. We need MAX_MATCH bytes
  970. * for the next match, plus MIN_MATCH bytes to insert the
  971. * string following the next match.
  972. */
  973. while (lookahead < MIN_LOOKAHEAD && !eofile)
  974. fill_window();
  975. }
  976. if (match_available)
  977. ct_tally(0, window[strstart - 1]);
  978. return FLUSH_BLOCK(1); /* eof */
  979. }
  980. /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
  981. * Copyright (C) 1992-1993 Jean-loup Gailly
  982. * The unzip code was written and put in the public domain by Mark Adler.
  983. * Portions of the lzw code are derived from the public domain 'compress'
  984. * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
  985. * Ken Turkowski, Dave Mack and Peter Jannesen.
  986. *
  987. * See the license_msg below and the file COPYING for the software license.
  988. * See the file algorithm.doc for the compression algorithms and file formats.
  989. */
  990. /* Compress files with zip algorithm and 'compress' interface.
  991. * See usage() and help() functions below for all options.
  992. * Outputs:
  993. * file.gz: compressed file with same mode, owner, and utimes
  994. * or stdout with -c option or if stdin used as input.
  995. * If the output file name had to be truncated, the original name is kept
  996. * in the compressed file.
  997. */
  998. /* configuration */
  999. typedef struct dirent dir_type;
  1000. /* ======================================================================== */
  1001. int gzip_main(int argc, char **argv)
  1002. {
  1003. int result;
  1004. int inFileNum;
  1005. int outFileNum;
  1006. struct stat statBuf;
  1007. char *delFileName;
  1008. int tostdout = 0;
  1009. int force = 0;
  1010. int opt;
  1011. while ((opt = getopt(argc, argv, "cf123456789dq")) != -1) {
  1012. switch (opt) {
  1013. case 'c':
  1014. tostdout = 1;
  1015. break;
  1016. case 'f':
  1017. force = 1;
  1018. break;
  1019. /* Ignore 1-9 (compression level) options */
  1020. case '1':
  1021. case '2':
  1022. case '3':
  1023. case '4':
  1024. case '5':
  1025. case '6':
  1026. case '7':
  1027. case '8':
  1028. case '9':
  1029. break;
  1030. case 'q':
  1031. break;
  1032. #ifdef CONFIG_GUNZIP
  1033. case 'd':
  1034. optind = 1;
  1035. return gunzip_main(argc, argv);
  1036. #endif
  1037. default:
  1038. bb_show_usage();
  1039. }
  1040. }
  1041. foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
  1042. if (foreground) {
  1043. (void) signal(SIGINT, abort_gzip);
  1044. }
  1045. #ifdef SIGTERM
  1046. if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
  1047. (void) signal(SIGTERM, abort_gzip);
  1048. }
  1049. #endif
  1050. #ifdef SIGHUP
  1051. if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
  1052. (void) signal(SIGHUP, abort_gzip);
  1053. }
  1054. #endif
  1055. strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix) - 1);
  1056. z_len = strlen(z_suffix);
  1057. /* Allocate all global buffers (for DYN_ALLOC option) */
  1058. ALLOC(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
  1059. ALLOC(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
  1060. ALLOC(ush, d_buf, DIST_BUFSIZE);
  1061. ALLOC(uch, window, 2L * WSIZE);
  1062. ALLOC(ush, tab_prefix, 1L << BITS);
  1063. clear_bufs();
  1064. part_nb = 0;
  1065. if (optind == argc) {
  1066. time_stamp = 0;
  1067. ifile_size = -1L;
  1068. zip(STDIN_FILENO, STDOUT_FILENO);
  1069. } else {
  1070. int i;
  1071. for (i = optind; i < argc; i++) {
  1072. char *path = NULL;
  1073. clear_bufs();
  1074. if (strcmp(argv[i], "-") == 0) {
  1075. time_stamp = 0;
  1076. ifile_size = -1L;
  1077. inFileNum = STDIN_FILENO;
  1078. outFileNum = STDOUT_FILENO;
  1079. } else {
  1080. inFileNum = open(argv[i], O_RDONLY);
  1081. if (inFileNum < 0 || fstat(inFileNum, &statBuf) < 0)
  1082. bb_perror_msg_and_die("%s", argv[i]);
  1083. time_stamp = statBuf.st_ctime;
  1084. ifile_size = statBuf.st_size;
  1085. if (!tostdout) {
  1086. path = xmalloc(strlen(argv[i]) + 4);
  1087. strcpy(path, argv[i]);
  1088. strcat(path, ".gz");
  1089. /* Open output file */
  1090. #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1) && defined O_NOFOLLOW
  1091. outFileNum =
  1092. open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
  1093. #else
  1094. outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL);
  1095. #endif
  1096. if (outFileNum < 0) {
  1097. bb_perror_msg("%s", path);
  1098. free(path);
  1099. continue;
  1100. }
  1101. /* Set permissions on the file */
  1102. fchmod(outFileNum, statBuf.st_mode);
  1103. } else
  1104. outFileNum = STDOUT_FILENO;
  1105. }
  1106. if (path == NULL && isatty(outFileNum) && force == 0) {
  1107. bb_error_msg
  1108. ("compressed data not written to a terminal. Use -f to force compression.");
  1109. free(path);
  1110. continue;
  1111. }
  1112. result = zip(inFileNum, outFileNum);
  1113. if (path != NULL) {
  1114. close(inFileNum);
  1115. close(outFileNum);
  1116. /* Delete the original file */
  1117. if (result == OK)
  1118. delFileName = argv[i];
  1119. else
  1120. delFileName = path;
  1121. if (unlink(delFileName) < 0)
  1122. bb_perror_msg("%s", delFileName);
  1123. }
  1124. free(path);
  1125. }
  1126. }
  1127. return (exit_code);
  1128. }
  1129. /* trees.c -- output deflated data using Huffman coding
  1130. * Copyright (C) 1992-1993 Jean-loup Gailly
  1131. * This is free software; you can redistribute it and/or modify it under the
  1132. * terms of the GNU General Public License, see the file COPYING.
  1133. */
  1134. /*
  1135. * PURPOSE
  1136. *
  1137. * Encode various sets of source values using variable-length
  1138. * binary code trees.
  1139. *
  1140. * DISCUSSION
  1141. *
  1142. * The PKZIP "deflation" process uses several Huffman trees. The more
  1143. * common source values are represented by shorter bit sequences.
  1144. *
  1145. * Each code tree is stored in the ZIP file in a compressed form
  1146. * which is itself a Huffman encoding of the lengths of
  1147. * all the code strings (in ascending order by source values).
  1148. * The actual code strings are reconstructed from the lengths in
  1149. * the UNZIP process, as described in the "application note"
  1150. * (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  1151. *
  1152. * REFERENCES
  1153. *
  1154. * Lynch, Thomas J.
  1155. * Data Compression: Techniques and Applications, pp. 53-55.
  1156. * Lifetime Learning Publications, 1985. ISBN 0-534-03418-7.
  1157. *
  1158. * Storer, James A.
  1159. * Data Compression: Methods and Theory, pp. 49-50.
  1160. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  1161. *
  1162. * Sedgewick, R.
  1163. * Algorithms, p290.
  1164. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  1165. *
  1166. * INTERFACE
  1167. *
  1168. * void ct_init (ush *attr, int *methodp)
  1169. * Allocate the match buffer, initialize the various tables and save
  1170. * the location of the internal file attribute (ascii/binary) and
  1171. * method (DEFLATE/STORE)
  1172. *
  1173. * void ct_tally (int dist, int lc);
  1174. * Save the match info and tally the frequency counts.
  1175. *
  1176. * long flush_block (char *buf, ulg stored_len, int eof)
  1177. * Determine the best encoding for the current block: dynamic trees,
  1178. * static trees or store, and output the encoded block to the zip
  1179. * file. Returns the total compressed length for the file so far.
  1180. *
  1181. */
  1182. /* ===========================================================================
  1183. * Constants
  1184. */
  1185. #define MAX_BITS 15
  1186. /* All codes must not exceed MAX_BITS bits */
  1187. #define MAX_BL_BITS 7
  1188. /* Bit length codes must not exceed MAX_BL_BITS bits */
  1189. #define LENGTH_CODES 29
  1190. /* number of length codes, not counting the special END_BLOCK code */
  1191. #define LITERALS 256
  1192. /* number of literal bytes 0..255 */
  1193. #define END_BLOCK 256
  1194. /* end of block literal code */
  1195. #define L_CODES (LITERALS+1+LENGTH_CODES)
  1196. /* number of Literal or Length codes, including the END_BLOCK code */
  1197. #define D_CODES 30
  1198. /* number of distance codes */
  1199. #define BL_CODES 19
  1200. /* number of codes used to transfer the bit lengths */
  1201. typedef uch extra_bits_t;
  1202. /* extra bits for each length code */
  1203. static const extra_bits_t extra_lbits[LENGTH_CODES]
  1204. = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  1205. 4, 4, 5, 5, 5, 5, 0
  1206. };
  1207. /* extra bits for each distance code */
  1208. static const extra_bits_t extra_dbits[D_CODES]
  1209. = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
  1210. 10, 10, 11, 11, 12, 12, 13, 13
  1211. };
  1212. /* extra bits for each bit length code */
  1213. static const extra_bits_t extra_blbits[BL_CODES]
  1214. = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 };
  1215. #define STORED_BLOCK 0
  1216. #define STATIC_TREES 1
  1217. #define DYN_TREES 2
  1218. /* The three kinds of block type */
  1219. #ifndef LIT_BUFSIZE
  1220. # ifdef SMALL_MEM
  1221. # define LIT_BUFSIZE 0x2000
  1222. # else
  1223. # ifdef MEDIUM_MEM
  1224. # define LIT_BUFSIZE 0x4000
  1225. # else
  1226. # define LIT_BUFSIZE 0x8000
  1227. # endif
  1228. # endif
  1229. #endif
  1230. #ifndef DIST_BUFSIZE
  1231. # define DIST_BUFSIZE LIT_BUFSIZE
  1232. #endif
  1233. /* Sizes of match buffers for literals/lengths and distances. There are
  1234. * 4 reasons for limiting LIT_BUFSIZE to 64K:
  1235. * - frequencies can be kept in 16 bit counters
  1236. * - if compression is not successful for the first block, all input data is
  1237. * still in the window so we can still emit a stored block even when input
  1238. * comes from standard input. (This can also be done for all blocks if
  1239. * LIT_BUFSIZE is not greater than 32K.)
  1240. * - if compression is not successful for a file smaller than 64K, we can
  1241. * even emit a stored file instead of a stored block (saving 5 bytes).
  1242. * - creating new Huffman trees less frequently may not provide fast
  1243. * adaptation to changes in the input data statistics. (Take for
  1244. * example a binary file with poorly compressible code followed by
  1245. * a highly compressible string table.) Smaller buffer sizes give
  1246. * fast adaptation but have of course the overhead of transmitting trees
  1247. * more frequently.
  1248. * - I can't count above 4
  1249. * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  1250. * memory at the expense of compression). Some optimizations would be possible
  1251. * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  1252. */
  1253. #if LIT_BUFSIZE > INBUFSIZ
  1254. #error cannot overlay l_buf and inbuf
  1255. #endif
  1256. #define REP_3_6 16
  1257. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  1258. #define REPZ_3_10 17
  1259. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  1260. #define REPZ_11_138 18
  1261. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  1262. /* ===========================================================================
  1263. * Local data
  1264. */
  1265. /* Data structure describing a single value and its code string. */
  1266. typedef struct ct_data {
  1267. union {
  1268. ush freq; /* frequency count */
  1269. ush code; /* bit string */
  1270. } fc;
  1271. union {
  1272. ush dad; /* father node in Huffman tree */
  1273. ush len; /* length of bit string */
  1274. } dl;
  1275. } ct_data;
  1276. #define Freq fc.freq
  1277. #define Code fc.code
  1278. #define Dad dl.dad
  1279. #define Len dl.len
  1280. #define HEAP_SIZE (2*L_CODES+1)
  1281. /* maximum heap size */
  1282. static ct_data dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  1283. static ct_data dyn_dtree[2 * D_CODES + 1]; /* distance tree */
  1284. static ct_data static_ltree[L_CODES + 2];
  1285. /* The static literal tree. Since the bit lengths are imposed, there is no
  1286. * need for the L_CODES extra codes used during heap construction. However
  1287. * The codes 286 and 287 are needed to build a canonical tree (see ct_init
  1288. * below).
  1289. */
  1290. static ct_data static_dtree[D_CODES];
  1291. /* The static distance tree. (Actually a trivial tree since all codes use
  1292. * 5 bits.)
  1293. */
  1294. static ct_data bl_tree[2 * BL_CODES + 1];
  1295. /* Huffman tree for the bit lengths */
  1296. typedef struct tree_desc {
  1297. ct_data *dyn_tree; /* the dynamic tree */
  1298. ct_data *static_tree; /* corresponding static tree or NULL */
  1299. const extra_bits_t *extra_bits; /* extra bits for each code or NULL */
  1300. int extra_base; /* base index for extra_bits */
  1301. int elems; /* max number of elements in the tree */
  1302. int max_length; /* max bit length for the codes */
  1303. int max_code; /* largest code with non zero frequency */
  1304. } tree_desc;
  1305. static tree_desc l_desc =
  1306. { dyn_ltree, static_ltree, extra_lbits, LITERALS + 1, L_CODES,
  1307. MAX_BITS, 0
  1308. };
  1309. static tree_desc d_desc =
  1310. { dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0 };
  1311. static tree_desc bl_desc =
  1312. { bl_tree, (ct_data *) 0, extra_blbits, 0, BL_CODES, MAX_BL_BITS,
  1313. 0
  1314. };
  1315. static ush bl_count[MAX_BITS + 1];
  1316. /* number of codes at each bit length for an optimal tree */
  1317. static const uch bl_order[BL_CODES]
  1318. = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  1319. /* The lengths of the bit length codes are sent in order of decreasing
  1320. * probability, to avoid transmitting the lengths for unused bit length codes.
  1321. */
  1322. static int heap[2 * L_CODES + 1]; /* heap used to build the Huffman trees */
  1323. static int heap_len; /* number of elements in the heap */
  1324. static int heap_max; /* element of largest frequency */
  1325. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  1326. * The same heap array is used to build all trees.
  1327. */
  1328. static uch depth[2 * L_CODES + 1];
  1329. /* Depth of each subtree used as tie breaker for trees of equal frequency */
  1330. static uch length_code[MAX_MATCH - MIN_MATCH + 1];
  1331. /* length code for each normalized match length (0 == MIN_MATCH) */
  1332. static uch dist_code[512];
  1333. /* distance codes. The first 256 values correspond to the distances
  1334. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  1335. * the 15 bit distances.
  1336. */
  1337. static int base_length[LENGTH_CODES];
  1338. /* First normalized length for each code (0 = MIN_MATCH) */
  1339. static int base_dist[D_CODES];
  1340. /* First normalized distance for each code (0 = distance of 1) */
  1341. #define l_buf inbuf
  1342. /* DECLARE(uch, l_buf, LIT_BUFSIZE); buffer for literals or lengths */
  1343. /* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
  1344. static uch flag_buf[(LIT_BUFSIZE / 8)];
  1345. /* flag_buf is a bit array distinguishing literals from lengths in
  1346. * l_buf, thus indicating the presence or absence of a distance.
  1347. */
  1348. static unsigned last_lit; /* running index in l_buf */
  1349. static unsigned last_dist; /* running index in d_buf */
  1350. static unsigned last_flags; /* running index in flag_buf */
  1351. static uch flags; /* current flags not yet saved in flag_buf */
  1352. static uch flag_bit; /* current bit used in flags */
  1353. /* bits are filled in flags starting at bit 0 (least significant).
  1354. * Note: these flags are overkill in the current code since we don't
  1355. * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  1356. */
  1357. static ulg opt_len; /* bit length of current block with optimal trees */
  1358. static ulg static_len; /* bit length of current block with static trees */
  1359. static ulg compressed_len; /* total bit length of compressed file */
  1360. static ush *file_type; /* pointer to UNKNOWN, BINARY or ASCII */
  1361. static int *file_method; /* pointer to DEFLATE or STORE */
  1362. /* ===========================================================================
  1363. * Local (static) routines in this file.
  1364. */
  1365. static void init_block(void);
  1366. static void pqdownheap(ct_data * tree, int k);
  1367. static void gen_bitlen(tree_desc * desc);
  1368. static void gen_codes(ct_data * tree, int max_code);
  1369. static void build_tree(tree_desc * desc);
  1370. static void scan_tree(ct_data * tree, int max_code);
  1371. static void send_tree(ct_data * tree, int max_code);
  1372. static int build_bl_tree(void);
  1373. static void send_all_trees(int lcodes, int dcodes, int blcodes);
  1374. static void compress_block(ct_data * ltree, ct_data * dtree);
  1375. static void set_file_type(void);
  1376. #ifndef DEBUG
  1377. # define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
  1378. /* Send a code of the given tree. c and tree must not have side effects */
  1379. #else /* DEBUG */
  1380. # define send_code(c, tree) \
  1381. { if (verbose>1) bb_error_msg("\ncd %3d ",(c)); \
  1382. send_bits(tree[c].Code, tree[c].Len); }
  1383. #endif
  1384. #define d_code(dist) \
  1385. ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  1386. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  1387. * must not have side effects. dist_code[256] and dist_code[257] are never
  1388. * used.
  1389. */
  1390. /* the arguments must not have side effects */
  1391. /* ===========================================================================
  1392. * Allocate the match buffer, initialize the various tables and save the
  1393. * location of the internal file attribute (ascii/binary) and method
  1394. * (DEFLATE/STORE).
  1395. */
  1396. static void ct_init(ush * attr, int *methodp)
  1397. {
  1398. int n; /* iterates over tree elements */
  1399. int bits; /* bit counter */
  1400. int length; /* length value */
  1401. int code; /* code value */
  1402. int dist; /* distance index */
  1403. file_type = attr;
  1404. file_method = methodp;
  1405. compressed_len = 0L;
  1406. if (static_dtree[0].Len != 0)
  1407. return; /* ct_init already called */
  1408. /* Initialize the mapping length (0..255) -> length code (0..28) */
  1409. length = 0;
  1410. for (code = 0; code < LENGTH_CODES - 1; code++) {
  1411. base_length[code] = length;
  1412. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  1413. length_code[length++] = (uch) code;
  1414. }
  1415. }
  1416. Assert(length == 256, "ct_init: length != 256");
  1417. /* Note that the length 255 (match length 258) can be represented
  1418. * in two different ways: code 284 + 5 bits or code 285, so we
  1419. * overwrite length_code[255] to use the best encoding:
  1420. */
  1421. length_code[length - 1] = (uch) code;
  1422. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  1423. dist = 0;
  1424. for (code = 0; code < 16; code++) {
  1425. base_dist[code] = dist;
  1426. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  1427. dist_code[dist++] = (uch) code;
  1428. }
  1429. }
  1430. Assert(dist == 256, "ct_init: dist != 256");
  1431. dist >>= 7; /* from now on, all distances are divided by 128 */
  1432. for (; code < D_CODES; code++) {
  1433. base_dist[code] = dist << 7;
  1434. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  1435. dist_code[256 + dist++] = (uch) code;
  1436. }
  1437. }
  1438. Assert(dist == 256, "ct_init: 256+dist != 512");
  1439. /* Construct the codes of the static literal tree */
  1440. for (bits = 0; bits <= MAX_BITS; bits++)
  1441. bl_count[bits] = 0;
  1442. n = 0;
  1443. while (n <= 143)
  1444. static_ltree[n++].Len = 8, bl_count[8]++;
  1445. while (n <= 255)
  1446. static_ltree[n++].Len = 9, bl_count[9]++;
  1447. while (n <= 279)
  1448. static_ltree[n++].Len = 7, bl_count[7]++;
  1449. while (n <= 287)
  1450. static_ltree[n++].Len = 8, bl_count[8]++;
  1451. /* Codes 286 and 287 do not exist, but we must include them in the
  1452. * tree construction to get a canonical Huffman tree (longest code
  1453. * all ones)
  1454. */
  1455. gen_codes((ct_data *) static_ltree, L_CODES + 1);
  1456. /* The static distance tree is trivial: */
  1457. for (n = 0; n < D_CODES; n++) {
  1458. static_dtree[n].Len = 5;
  1459. static_dtree[n].Code = bi_reverse(n, 5);
  1460. }
  1461. /* Initialize the first block of the first file: */
  1462. init_block();
  1463. }
  1464. /* ===========================================================================
  1465. * Initialize a new block.
  1466. */
  1467. static void init_block(void)
  1468. {
  1469. int n; /* iterates over tree elements */
  1470. /* Initialize the trees. */
  1471. for (n = 0; n < L_CODES; n++)
  1472. dyn_ltree[n].Freq = 0;
  1473. for (n = 0; n < D_CODES; n++)
  1474. dyn_dtree[n].Freq = 0;
  1475. for (n = 0; n < BL_CODES; n++)
  1476. bl_tree[n].Freq = 0;
  1477. dyn_ltree[END_BLOCK].Freq = 1;
  1478. opt_len = static_len = 0L;
  1479. last_lit = last_dist = last_flags = 0;
  1480. flags = 0;
  1481. flag_bit = 1;
  1482. }
  1483. #define SMALLEST 1
  1484. /* Index within the heap array of least frequent node in the Huffman tree */
  1485. /* ===========================================================================
  1486. * Remove the smallest element from the heap and recreate the heap with
  1487. * one less element. Updates heap and heap_len.
  1488. */
  1489. #define pqremove(tree, top) \
  1490. {\
  1491. top = heap[SMALLEST]; \
  1492. heap[SMALLEST] = heap[heap_len--]; \
  1493. pqdownheap(tree, SMALLEST); \
  1494. }
  1495. /* ===========================================================================
  1496. * Compares to subtrees, using the tree depth as tie breaker when
  1497. * the subtrees have equal frequency. This minimizes the worst case length.
  1498. */
  1499. #define smaller(tree, n, m) \
  1500. (tree[n].Freq < tree[m].Freq || \
  1501. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  1502. /* ===========================================================================
  1503. * Restore the heap property by moving down the tree starting at node k,
  1504. * exchanging a node with the smallest of its two sons if necessary, stopping
  1505. * when the heap property is re-established (each father smaller than its
  1506. * two sons).
  1507. */
  1508. static void pqdownheap(ct_data * tree, int k)
  1509. {
  1510. int v = heap[k];
  1511. int j = k << 1; /* left son of k */
  1512. while (j <= heap_len) {
  1513. /* Set j to the smallest of the two sons: */
  1514. if (j < heap_len && smaller(tree, heap[j + 1], heap[j]))
  1515. j++;
  1516. /* Exit if v is smaller than both sons */
  1517. if (smaller(tree, v, heap[j]))
  1518. break;
  1519. /* Exchange v with the smallest son */
  1520. heap[k] = heap[j];
  1521. k = j;
  1522. /* And continue down the tree, setting j to the left son of k */
  1523. j <<= 1;
  1524. }
  1525. heap[k] = v;
  1526. }
  1527. /* ===========================================================================
  1528. * Compute the optimal bit lengths for a tree and update the total bit length
  1529. * for the current block.
  1530. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  1531. * above are the tree nodes sorted by increasing frequency.
  1532. * OUT assertions: the field len is set to the optimal bit length, the
  1533. * array bl_count contains the frequencies for each bit length.
  1534. * The length opt_len is updated; static_len is also updated if stree is
  1535. * not null.
  1536. */
  1537. static void gen_bitlen(tree_desc * desc)
  1538. {
  1539. ct_data *tree = desc->dyn_tree;
  1540. const extra_bits_t *extra = desc->extra_bits;
  1541. int base = desc->extra_base;
  1542. int max_code = desc->max_code;
  1543. int max_length = desc->max_length;
  1544. ct_data *stree = desc->static_tree;
  1545. int h; /* heap index */
  1546. int n, m; /* iterate over the tree elements */
  1547. int bits; /* bit length */
  1548. int xbits; /* extra bits */
  1549. ush f; /* frequency */
  1550. int overflow = 0; /* number of elements with bit length too large */
  1551. for (bits = 0; bits <= MAX_BITS; bits++)
  1552. bl_count[bits] = 0;
  1553. /* In a first pass, compute the optimal bit lengths (which may
  1554. * overflow in the case of the bit length tree).
  1555. */
  1556. tree[heap[heap_max]].Len = 0; /* root of the heap */
  1557. for (h = heap_max + 1; h < HEAP_SIZE; h++) {
  1558. n = heap[h];
  1559. bits = tree[tree[n].Dad].Len + 1;
  1560. if (bits > max_length)
  1561. bits = max_length, overflow++;
  1562. tree[n].Len = (ush) bits;
  1563. /* We overwrite tree[n].Dad which is no longer needed */
  1564. if (n > max_code)
  1565. continue; /* not a leaf node */
  1566. bl_count[bits]++;
  1567. xbits = 0;
  1568. if (n >= base)
  1569. xbits = extra[n - base];
  1570. f = tree[n].Freq;
  1571. opt_len += (ulg) f *(bits + xbits);
  1572. if (stree)
  1573. static_len += (ulg) f *(stree[n].Len + xbits);
  1574. }
  1575. if (overflow == 0)
  1576. return;
  1577. Trace((stderr, "\nbit length overflow\n"));
  1578. /* This happens for example on obj2 and pic of the Calgary corpus */
  1579. /* Find the first bit length which could increase: */
  1580. do {
  1581. bits = max_length - 1;
  1582. while (bl_count[bits] == 0)
  1583. bits--;
  1584. bl_count[bits]--; /* move one leaf down the tree */
  1585. bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  1586. bl_count[max_length]--;
  1587. /* The brother of the overflow item also moves one step up,
  1588. * but this does not affect bl_count[max_length]
  1589. */
  1590. overflow -= 2;
  1591. } while (overflow > 0);
  1592. /* Now recompute all bit lengths, scanning in increasing frequency.
  1593. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  1594. * lengths instead of fixing only the wrong ones. This idea is taken
  1595. * from 'ar' written by Haruhiko Okumura.)
  1596. */
  1597. for (bits = max_length; bits != 0; bits--) {
  1598. n = bl_count[bits];
  1599. while (n != 0) {
  1600. m = heap[--h];
  1601. if (m > max_code)
  1602. continue;
  1603. if (tree[m].Len != (unsigned) bits) {
  1604. Trace((stderr, "code %d bits %d->%d\n", m, tree[m].Len,
  1605. bits));
  1606. opt_len +=
  1607. ((long) bits - (long) tree[m].Len) * (long) tree[m].Freq;
  1608. tree[m].Len = (ush) bits;
  1609. }
  1610. n--;
  1611. }
  1612. }
  1613. }
  1614. /* ===========================================================================
  1615. * Generate the codes for a given tree and bit counts (which need not be
  1616. * optimal).
  1617. * IN assertion: the array bl_count contains the bit length statistics for
  1618. * the given tree and the field len is set for all tree elements.
  1619. * OUT assertion: the field code is set for all tree elements of non
  1620. * zero code length.
  1621. */
  1622. static void gen_codes(ct_data * tree, int max_code)
  1623. {
  1624. ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
  1625. ush code = 0; /* running code value */
  1626. int bits; /* bit index */
  1627. int n; /* code index */
  1628. /* The distribution counts are first used to generate the code values
  1629. * without bit reversal.
  1630. */
  1631. for (bits = 1; bits <= MAX_BITS; bits++) {
  1632. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  1633. }
  1634. /* Check that the bit counts in bl_count are consistent. The last code
  1635. * must be all ones.
  1636. */
  1637. Assert(code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
  1638. "inconsistent bit counts");
  1639. Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
  1640. for (n = 0; n <= max_code; n++) {
  1641. int len = tree[n].Len;
  1642. if (len == 0)
  1643. continue;
  1644. /* Now reverse the bits */
  1645. tree[n].Code = bi_reverse(next_code[len]++, len);
  1646. Tracec(tree != static_ltree,
  1647. (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
  1648. (isgraph(n) ? n : ' '), len, tree[n].Code,
  1649. next_code[len] - 1));
  1650. }
  1651. }
  1652. /* ===========================================================================
  1653. * Construct one Huffman tree and assigns the code bit strings and lengths.
  1654. * Update the total bit length for the current block.
  1655. * IN assertion: the field freq is set for all tree elements.
  1656. * OUT assertions: the fields len and code are set to the optimal bit length
  1657. * and corresponding code. The length opt_len is updated; static_len is
  1658. * also updated if stree is not null. The field max_code is set.
  1659. */
  1660. static void build_tree(tree_desc * desc)
  1661. {
  1662. ct_data *tree = desc->dyn_tree;
  1663. ct_data *stree = desc->static_tree;
  1664. int elems = desc->elems;
  1665. int n, m; /* iterate over heap elements */
  1666. int max_code = -1; /* largest code with non zero frequency */
  1667. int node = elems; /* next internal node of the tree */
  1668. /* Construct the initial heap, with least frequent element in
  1669. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  1670. * heap[0] is not used.
  1671. */
  1672. heap_len = 0, heap_max = HEAP_SIZE;
  1673. for (n = 0; n < elems; n++) {
  1674. if (tree[n].Freq != 0) {
  1675. heap[++heap_len] = max_code = n;
  1676. depth[n] = 0;
  1677. } else {
  1678. tree[n].Len = 0;
  1679. }
  1680. }
  1681. /* The pkzip format requires that at least one distance code exists,
  1682. * and that at least one bit should be sent even if there is only one
  1683. * possible code. So to avoid special checks later on we force at least
  1684. * two codes of non zero frequency.
  1685. */
  1686. while (heap_len < 2) {
  1687. int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
  1688. tree[new].Freq = 1;
  1689. depth[new] = 0;
  1690. opt_len--;
  1691. if (stree)
  1692. static_len -= stree[new].Len;
  1693. /* new is 0 or 1 so it does not have extra bits */
  1694. }
  1695. desc->max_code = max_code;
  1696. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  1697. * establish sub-heaps of increasing lengths:
  1698. */
  1699. for (n = heap_len / 2; n >= 1; n--)
  1700. pqdownheap(tree, n);
  1701. /* Construct the Huffman tree by repeatedly combining the least two
  1702. * frequent nodes.
  1703. */
  1704. do {
  1705. pqremove(tree, n); /* n = node of least frequency */
  1706. m = heap[SMALLEST]; /* m = node of next least frequency */
  1707. heap[--heap_max] = n; /* keep the nodes sorted by frequency */
  1708. heap[--heap_max] = m;
  1709. /* Create a new node father of n and m */
  1710. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  1711. depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
  1712. tree[n].Dad = tree[m].Dad = (ush) node;
  1713. #ifdef DUMP_BL_TREE
  1714. if (tree == bl_tree) {
  1715. bb_error_msg("\nnode %d(%d), sons %d(%d) %d(%d)",
  1716. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  1717. }
  1718. #endif
  1719. /* and insert the new node in the heap */
  1720. heap[SMALLEST] = node++;
  1721. pqdownheap(tree, SMALLEST);
  1722. } while (heap_len >= 2);
  1723. heap[--heap_max] = heap[SMALLEST];
  1724. /* At this point, the fields freq and dad are set. We can now
  1725. * generate the bit lengths.
  1726. */
  1727. gen_bitlen((tree_desc *) desc);
  1728. /* The field len is now set, we can generate the bit codes */
  1729. gen_codes((ct_data *) tree, max_code);
  1730. }
  1731. /* ===========================================================================
  1732. * Scan a literal or distance tree to determine the frequencies of the codes
  1733. * in the bit length tree. Updates opt_len to take into account the repeat
  1734. * counts. (The contribution of the bit length codes will be added later
  1735. * during the construction of bl_tree.)
  1736. */
  1737. static void scan_tree(ct_data * tree, int max_code)
  1738. {
  1739. int n; /* iterates over all tree elements */
  1740. int prevlen = -1; /* last emitted length */
  1741. int curlen; /* length of current code */
  1742. int nextlen = tree[0].Len; /* length of next code */
  1743. int count = 0; /* repeat count of the current code */
  1744. int max_count = 7; /* max repeat count */
  1745. int min_count = 4; /* min repeat count */
  1746. if (nextlen == 0)
  1747. max_count = 138, min_count = 3;
  1748. tree[max_code + 1].Len = (ush) 0xffff; /* guard */
  1749. for (n = 0; n <= max_code; n++) {
  1750. curlen = nextlen;
  1751. nextlen = tree[n + 1].Len;
  1752. if (++count < max_count && curlen == nextlen) {
  1753. continue;
  1754. } else if (count < min_count) {
  1755. bl_tree[curlen].Freq += count;
  1756. } else if (curlen != 0) {
  1757. if (curlen != prevlen)
  1758. bl_tree[curlen].Freq++;
  1759. bl_tree[REP_3_6].Freq++;
  1760. } else if (count <= 10) {
  1761. bl_tree[REPZ_3_10].Freq++;
  1762. } else {
  1763. bl_tree[REPZ_11_138].Freq++;
  1764. }
  1765. count = 0;
  1766. prevlen = curlen;
  1767. if (nextlen == 0) {
  1768. max_count = 138, min_count = 3;
  1769. } else if (curlen == nextlen) {
  1770. max_count = 6, min_count = 3;
  1771. } else {
  1772. max_count = 7, min_count = 4;
  1773. }
  1774. }
  1775. }
  1776. /* ===========================================================================
  1777. * Send a literal or distance tree in compressed form, using the codes in
  1778. * bl_tree.
  1779. */
  1780. static void send_tree(ct_data * tree, int max_code)
  1781. {
  1782. int n; /* iterates over all tree elements */
  1783. int prevlen = -1; /* last emitted length */
  1784. int curlen; /* length of current code */
  1785. int nextlen = tree[0].Len; /* length of next code */
  1786. int count = 0; /* repeat count of the current code */
  1787. int max_count = 7; /* max repeat count */
  1788. int min_count = 4; /* min repeat count */
  1789. /* tree[max_code+1].Len = -1; *//* guard already set */
  1790. if (nextlen == 0)
  1791. max_count = 138, min_count = 3;
  1792. for (n = 0; n <= max_code; n++) {
  1793. curlen = nextlen;
  1794. nextlen = tree[n + 1].Len;
  1795. if (++count < max_count && curlen == nextlen) {
  1796. continue;
  1797. } else if (count < min_count) {
  1798. do {
  1799. send_code(curlen, bl_tree);
  1800. } while (--count != 0);
  1801. } else if (curlen != 0) {
  1802. if (curlen != prevlen) {
  1803. send_code(curlen, bl_tree);
  1804. count--;
  1805. }
  1806. Assert(count >= 3 && count <= 6, " 3_6?");
  1807. send_code(REP_3_6, bl_tree);
  1808. send_bits(count - 3, 2);
  1809. } else if (count <= 10) {
  1810. send_code(REPZ_3_10, bl_tree);
  1811. send_bits(count - 3, 3);
  1812. } else {
  1813. send_code(REPZ_11_138, bl_tree);
  1814. send_bits(count - 11, 7);
  1815. }
  1816. count = 0;
  1817. prevlen = curlen;
  1818. if (nextlen == 0) {
  1819. max_count = 138, min_count = 3;
  1820. } else if (curlen == nextlen) {
  1821. max_count = 6, min_count = 3;
  1822. } else {
  1823. max_count = 7, min_count = 4;
  1824. }
  1825. }
  1826. }
  1827. /* ===========================================================================
  1828. * Construct the Huffman tree for the bit lengths and return the index in
  1829. * bl_order of the last bit length code to send.
  1830. */
  1831. static int build_bl_tree(void)
  1832. {
  1833. int max_blindex; /* index of last bit length code of non zero freq */
  1834. /* Determine the bit length frequencies for literal and distance trees */
  1835. scan_tree((ct_data *) dyn_ltree, l_desc.max_code);
  1836. scan_tree((ct_data *) dyn_dtree, d_desc.max_code);
  1837. /* Build the bit length tree: */
  1838. build_tree((tree_desc *) (&bl_desc));
  1839. /* opt_len now includes the length of the tree representations, except
  1840. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1841. */
  1842. /* Determine the number of bit length codes to send. The pkzip format
  1843. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1844. * 3 but the actual value used is 4.)
  1845. */
  1846. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  1847. if (bl_tree[bl_order[max_blindex]].Len != 0)
  1848. break;
  1849. }
  1850. /* Update opt_len to include the bit length tree and counts */
  1851. opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  1852. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len, static_len));
  1853. return max_blindex;
  1854. }
  1855. /* ===========================================================================
  1856. * Send the header for a block using dynamic Huffman trees: the counts, the
  1857. * lengths of the bit length codes, the literal tree and the distance tree.
  1858. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  1859. */
  1860. static void send_all_trees(int lcodes, int dcodes, int blcodes)
  1861. {
  1862. int rank; /* index in bl_order */
  1863. Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  1864. Assert(lcodes <= L_CODES && dcodes <= D_CODES
  1865. && blcodes <= BL_CODES, "too many codes");
  1866. Tracev((stderr, "\nbl counts: "));
  1867. send_bits(lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  1868. send_bits(dcodes - 1, 5);
  1869. send_bits(blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  1870. for (rank = 0; rank < blcodes; rank++) {
  1871. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  1872. send_bits(bl_tree[bl_order[rank]].Len, 3);
  1873. }
  1874. Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
  1875. send_tree((ct_data *) dyn_ltree, lcodes - 1); /* send the literal tree */
  1876. Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
  1877. send_tree((ct_data *) dyn_dtree, dcodes - 1); /* send the distance tree */
  1878. Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
  1879. }
  1880. /* ===========================================================================
  1881. * Determine the best encoding for the current block: dynamic trees, static
  1882. * trees or store, and output the encoded block to the zip file. This function
  1883. * returns the total compressed length for the file so far.
  1884. */
  1885. static ulg flush_block(char *buf, ulg stored_len, int eof)
  1886. {
  1887. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  1888. int max_blindex; /* index of last bit length code of non zero freq */
  1889. flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
  1890. /* Check if the file is ascii or binary */
  1891. if (*file_type == (ush) UNKNOWN)
  1892. set_file_type();
  1893. /* Construct the literal and distance trees */
  1894. build_tree((tree_desc *) (&l_desc));
  1895. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
  1896. build_tree((tree_desc *) (&d_desc));
  1897. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", opt_len, static_len));
  1898. /* At this point, opt_len and static_len are the total bit lengths of
  1899. * the compressed block data, excluding the tree representations.
  1900. */
  1901. /* Build the bit length tree for the above two trees, and get the index
  1902. * in bl_order of the last bit length code to send.
  1903. */
  1904. max_blindex = build_bl_tree();
  1905. /* Determine the best encoding. Compute first the block length in bytes */
  1906. opt_lenb = (opt_len + 3 + 7) >> 3;
  1907. static_lenb = (static_len + 3 + 7) >> 3;
  1908. Trace((stderr,
  1909. "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  1910. opt_lenb, opt_len, static_lenb, static_len, stored_len,
  1911. last_lit, last_dist));
  1912. if (static_lenb <= opt_lenb)
  1913. opt_lenb = static_lenb;
  1914. /* If compression failed and this is the first and last block,
  1915. * and if the zip file can be seeked (to rewrite the local header),
  1916. * the whole file is transformed into a stored file:
  1917. */
  1918. if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) {
  1919. /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  1920. if (buf == (char *) 0)
  1921. bb_error_msg("block vanished");
  1922. copy_block(buf, (unsigned) stored_len, 0); /* without header */
  1923. compressed_len = stored_len << 3;
  1924. *file_method = STORED;
  1925. } else if (stored_len + 4 <= opt_lenb && buf != (char *) 0) {
  1926. /* 4: two words for the lengths */
  1927. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1928. * Otherwise we can't have processed more than WSIZE input bytes since
  1929. * the last block flush, because compression would have been
  1930. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1931. * transform a block into a stored block.
  1932. */
  1933. send_bits((STORED_BLOCK << 1) + eof, 3); /* send block type */
  1934. compressed_len = (compressed_len + 3 + 7) & ~7L;
  1935. compressed_len += (stored_len + 4) << 3;
  1936. copy_block(buf, (unsigned) stored_len, 1); /* with header */
  1937. } else if (static_lenb == opt_lenb) {
  1938. send_bits((STATIC_TREES << 1) + eof, 3);
  1939. compress_block((ct_data *) static_ltree, (ct_data *) static_dtree);
  1940. compressed_len += 3 + static_len;
  1941. } else {
  1942. send_bits((DYN_TREES << 1) + eof, 3);
  1943. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
  1944. max_blindex + 1);
  1945. compress_block((ct_data *) dyn_ltree, (ct_data *) dyn_dtree);
  1946. compressed_len += 3 + opt_len;
  1947. }
  1948. Assert(compressed_len == bits_sent, "bad compressed size");
  1949. init_block();
  1950. if (eof) {
  1951. bi_windup();
  1952. compressed_len += 7; /* align on byte boundary */
  1953. }
  1954. Tracev((stderr, "\ncomprlen %lu(%lu) ", compressed_len >> 3,
  1955. compressed_len - 7 * eof));
  1956. return compressed_len >> 3;
  1957. }
  1958. /* ===========================================================================
  1959. * Save the match info and tally the frequency counts. Return true if
  1960. * the current block must be flushed.
  1961. */
  1962. static int ct_tally(int dist, int lc)
  1963. {
  1964. l_buf[last_lit++] = (uch) lc;
  1965. if (dist == 0) {
  1966. /* lc is the unmatched char */
  1967. dyn_ltree[lc].Freq++;
  1968. } else {
  1969. /* Here, lc is the match length - MIN_MATCH */
  1970. dist--; /* dist = match distance - 1 */
  1971. Assert((ush) dist < (ush) MAX_DIST &&
  1972. (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH) &&
  1973. (ush) d_code(dist) < (ush) D_CODES, "ct_tally: bad match");
  1974. dyn_ltree[length_code[lc] + LITERALS + 1].Freq++;
  1975. dyn_dtree[d_code(dist)].Freq++;
  1976. d_buf[last_dist++] = (ush) dist;
  1977. flags |= flag_bit;
  1978. }
  1979. flag_bit <<= 1;
  1980. /* Output the flags if they fill a byte: */
  1981. if ((last_lit & 7) == 0) {
  1982. flag_buf[last_flags++] = flags;
  1983. flags = 0, flag_bit = 1;
  1984. }
  1985. /* Try to guess if it is profitable to stop the current block here */
  1986. if ((last_lit & 0xfff) == 0) {
  1987. /* Compute an upper bound for the compressed length */
  1988. ulg out_length = (ulg) last_lit * 8L;
  1989. ulg in_length = (ulg) strstart - block_start;
  1990. int dcode;
  1991. for (dcode = 0; dcode < D_CODES; dcode++) {
  1992. out_length +=
  1993. (ulg) dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
  1994. }
  1995. out_length >>= 3;
  1996. Trace((stderr,
  1997. "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  1998. last_lit, last_dist, in_length, out_length,
  1999. 100L - out_length * 100L / in_length));
  2000. if (last_dist < last_lit / 2 && out_length < in_length / 2)
  2001. return 1;
  2002. }
  2003. return (last_lit == LIT_BUFSIZE - 1 || last_dist == DIST_BUFSIZE);
  2004. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  2005. * on 16 bit machines and because stored blocks are restricted to
  2006. * 64K-1 bytes.
  2007. */
  2008. }
  2009. /* ===========================================================================
  2010. * Send the block data compressed using the given Huffman trees
  2011. */
  2012. static void compress_block(ct_data * ltree, ct_data * dtree)
  2013. {
  2014. unsigned dist; /* distance of matched string */
  2015. int lc; /* match length or unmatched char (if dist == 0) */
  2016. unsigned lx = 0; /* running index in l_buf */
  2017. unsigned dx = 0; /* running index in d_buf */
  2018. unsigned fx = 0; /* running index in flag_buf */
  2019. uch flag = 0; /* current flags */
  2020. unsigned code; /* the code to send */
  2021. int extra; /* number of extra bits to send */
  2022. if (last_lit != 0)
  2023. do {
  2024. if ((lx & 7) == 0)
  2025. flag = flag_buf[fx++];
  2026. lc = l_buf[lx++];
  2027. if ((flag & 1) == 0) {
  2028. send_code(lc, ltree); /* send a literal byte */
  2029. Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
  2030. } else {
  2031. /* Here, lc is the match length - MIN_MATCH */
  2032. code = length_code[lc];
  2033. send_code(code + LITERALS + 1, ltree); /* send the length code */
  2034. extra = extra_lbits[code];
  2035. if (extra != 0) {
  2036. lc -= base_length[code];
  2037. send_bits(lc, extra); /* send the extra length bits */
  2038. }
  2039. dist = d_buf[dx++];
  2040. /* Here, dist is the match distance - 1 */
  2041. code = d_code(dist);
  2042. Assert(code < D_CODES, "bad d_code");
  2043. send_code(code, dtree); /* send the distance code */
  2044. extra = extra_dbits[code];
  2045. if (extra != 0) {
  2046. dist -= base_dist[code];
  2047. send_bits(dist, extra); /* send the extra distance bits */
  2048. }
  2049. } /* literal or match pair ? */
  2050. flag >>= 1;
  2051. } while (lx < last_lit);
  2052. send_code(END_BLOCK, ltree);
  2053. }
  2054. /* ===========================================================================
  2055. * Set the file type to ASCII or BINARY, using a crude approximation:
  2056. * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  2057. * IN assertion: the fields freq of dyn_ltree are set and the total of all
  2058. * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  2059. */
  2060. static void set_file_type(void)
  2061. {
  2062. int n = 0;
  2063. unsigned ascii_freq = 0;
  2064. unsigned bin_freq = 0;
  2065. while (n < 7)
  2066. bin_freq += dyn_ltree[n++].Freq;
  2067. while (n < 128)
  2068. ascii_freq += dyn_ltree[n++].Freq;
  2069. while (n < LITERALS)
  2070. bin_freq += dyn_ltree[n++].Freq;
  2071. *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
  2072. if (*file_type == BINARY && translate_eol) {
  2073. bb_error_msg("-l used on binary file");
  2074. }
  2075. }
  2076. /* zip.c -- compress files to the gzip or pkzip format
  2077. * Copyright (C) 1992-1993 Jean-loup Gailly
  2078. * This is free software; you can redistribute it and/or modify it under the
  2079. * terms of the GNU General Public License, see the file COPYING.
  2080. */
  2081. static ulg crc; /* crc on uncompressed file data */
  2082. static long header_bytes; /* number of bytes in gzip header */
  2083. static void put_long(ulg n)
  2084. {
  2085. put_short((n) & 0xffff);
  2086. put_short(((ulg) (n)) >> 16);
  2087. }
  2088. /* put_header_byte is used for the compressed output
  2089. * - for the initial 4 bytes that can't overflow the buffer.
  2090. */
  2091. #define put_header_byte(c) {outbuf[outcnt++]=(uch)(c);}
  2092. /* ===========================================================================
  2093. * Deflate in to out.
  2094. * IN assertions: the input and output buffers are cleared.
  2095. * The variables time_stamp and save_orig_name are initialized.
  2096. */
  2097. static int zip(int in, int out)
  2098. {
  2099. uch my_flags = 0; /* general purpose bit flags */
  2100. ush attr = 0; /* ascii/binary flag */
  2101. ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
  2102. ifd = in;
  2103. ofd = out;
  2104. outcnt = 0;
  2105. /* Write the header to the gzip file. See algorithm.doc for the format */
  2106. method = DEFLATED;
  2107. put_header_byte(GZIP_MAGIC[0]); /* magic header */
  2108. put_header_byte(GZIP_MAGIC[1]);
  2109. put_header_byte(DEFLATED); /* compression method */
  2110. put_header_byte(my_flags); /* general flags */
  2111. put_long(time_stamp);
  2112. /* Write deflated file to zip file */
  2113. crc = updcrc(0, 0);
  2114. bi_init(out);
  2115. ct_init(&attr, &method);
  2116. lm_init(&deflate_flags);
  2117. put_byte((uch) deflate_flags); /* extra flags */
  2118. put_byte(OS_CODE); /* OS identifier */
  2119. header_bytes = (long) outcnt;
  2120. (void) deflate();
  2121. /* Write the crc and uncompressed size */
  2122. put_long(crc);
  2123. put_long(isize);
  2124. header_bytes += 2 * sizeof(long);
  2125. flush_outbuf();
  2126. return OK;
  2127. }
  2128. /* ===========================================================================
  2129. * Read a new buffer from the current input file, perform end-of-line
  2130. * translation, and update the crc and input file size.
  2131. * IN assertion: size >= 2 (for end-of-line translation)
  2132. */
  2133. static int file_read(char *buf, unsigned size)
  2134. {
  2135. unsigned len;
  2136. Assert(insize == 0, "inbuf not empty");
  2137. len = read(ifd, buf, size);
  2138. if (len == (unsigned) (-1) || len == 0)
  2139. return (int) len;
  2140. crc = updcrc((uch *) buf, len);
  2141. isize += (ulg) len;
  2142. return (int) len;
  2143. }
  2144. /* ===========================================================================
  2145. * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
  2146. * (used for the compressed data only)
  2147. */
  2148. static void flush_outbuf(void)
  2149. {
  2150. if (outcnt == 0)
  2151. return;
  2152. write_buf(ofd, (char *) outbuf, outcnt);
  2153. outcnt = 0;
  2154. }