3
0

gzip.c 76 KB

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