zlib.c 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379
  1. /*
  2. * This file is derived from various .h and .c files from the zlib-1.0.4
  3. * distribution by Jean-loup Gailly and Mark Adler, with some additions
  4. * by Paul Mackerras to aid in implementing Deflate compression and
  5. * decompression for PPP packets. See zlib.h for conditions of
  6. * distribution and use.
  7. *
  8. * Changes that have been made include:
  9. * - added Z_PACKET_FLUSH (see zlib.h for details)
  10. * - added inflateIncomp and deflateOutputPending
  11. * - allow strm->next_out to be NULL, meaning discard the output
  12. *
  13. * $Id: zlib.c,v 1.12 2002/04/02 13:34:03 dfs Exp $
  14. */
  15. /*
  16. * ==FILEVERSION 971210==
  17. *
  18. * This marker is used by the Linux installation script to determine
  19. * whether an up-to-date version of this file is already installed.
  20. */
  21. #define NO_DUMMY_DECL
  22. #define NO_ZCFUNCS
  23. #define MY_ZCALLOC
  24. #if defined(__FreeBSD__) && (defined(KERNEL) || defined(_KERNEL))
  25. #define inflate inflate_ppp /* FreeBSD already has an inflate :-( */
  26. #endif
  27. /* +++ zutil.h */
  28. /* zutil.h -- internal interface and configuration of the compression library
  29. * Copyright (C) 1995-1996 Jean-loup Gailly.
  30. * For conditions of distribution and use, see copyright notice in zlib.h
  31. */
  32. /* WARNING: this file should *not* be used by applications. It is
  33. part of the implementation of the compression library and is
  34. subject to change. Applications should only use zlib.h.
  35. */
  36. /* From: zutil.h,v 1.16 1996/07/24 13:41:13 me Exp $ */
  37. #ifndef _Z_UTIL_H
  38. #define _Z_UTIL_H
  39. #include "zlib.h"
  40. #if defined(KERNEL) || defined(_KERNEL)
  41. /* Assume this is a *BSD or SVR4 kernel */
  42. #include <sys/types.h>
  43. #include <sys/time.h>
  44. #include <sys/systm.h>
  45. #undef u
  46. # define HAVE_MEMCPY
  47. # define memcpy(d, s, n) bcopy((s), (d), (n))
  48. # define memset(d, v, n) bzero((d), (n))
  49. # define memcmp bcmp
  50. #else
  51. #if defined(__KERNEL__)
  52. /* Assume this is a Linux kernel */
  53. #include <linux/string.h>
  54. #define HAVE_MEMCPY
  55. #else /* not kernel */
  56. #if defined(MSDOS)||defined(VMS)||defined(CRAY)||defined(WIN32)||defined(RISCOS)
  57. # include <stddef.h>
  58. # include <errno.h>
  59. #else
  60. extern int errno;
  61. #endif
  62. #ifdef STDC
  63. # include <string.h>
  64. # include <stdlib.h>
  65. #endif
  66. #endif /* __KERNEL__ */
  67. #endif /* _KERNEL || KERNEL */
  68. #ifndef local
  69. # define local static
  70. #endif
  71. /* compile with -Dlocal if your debugger can't find static symbols */
  72. typedef unsigned char uch;
  73. typedef uch FAR uchf;
  74. typedef unsigned short ush;
  75. typedef ush FAR ushf;
  76. typedef unsigned long ulg;
  77. extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */
  78. /* (size given to avoid silly warnings with Visual C++) */
  79. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80. #define ERR_RETURN(strm,err) \
  81. return (strm->msg = (char*)ERR_MSG(err), (err))
  82. /* To be used only when the state is known to be valid */
  83. /* common constants */
  84. #ifndef DEF_WBITS
  85. # define DEF_WBITS MAX_WBITS
  86. #endif
  87. /* default windowBits for decompression. MAX_WBITS is for compression only */
  88. #if MAX_MEM_LEVEL >= 8
  89. # define DEF_MEM_LEVEL 8
  90. #else
  91. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  92. #endif
  93. /* default memLevel */
  94. #define STORED_BLOCK 0
  95. #define STATIC_TREES 1
  96. #define DYN_TREES 2
  97. /* The three kinds of block type */
  98. #define MIN_MATCH 3
  99. #define MAX_MATCH 258
  100. /* The minimum and maximum match lengths */
  101. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  102. /* target dependencies */
  103. #ifdef MSDOS
  104. # define OS_CODE 0x00
  105. # ifdef __TURBOC__
  106. # include <alloc.h>
  107. # else /* MSC or DJGPP */
  108. # include <malloc.h>
  109. # endif
  110. #endif
  111. #ifdef OS2
  112. # define OS_CODE 0x06
  113. #endif
  114. #ifdef WIN32 /* Window 95 & Windows NT */
  115. # define OS_CODE 0x0b
  116. #endif
  117. #if defined(VAXC) || defined(VMS)
  118. # define OS_CODE 0x02
  119. # define FOPEN(name, mode) \
  120. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  121. #endif
  122. #ifdef AMIGA
  123. # define OS_CODE 0x01
  124. #endif
  125. #if defined(ATARI) || defined(atarist)
  126. # define OS_CODE 0x05
  127. #endif
  128. #ifdef MACOS
  129. # define OS_CODE 0x07
  130. #endif
  131. #ifdef __50SERIES /* Prime/PRIMOS */
  132. # define OS_CODE 0x0F
  133. #endif
  134. #ifdef TOPS20
  135. # define OS_CODE 0x0a
  136. #endif
  137. #if defined(_BEOS_) || defined(RISCOS)
  138. # define fdopen(fd,mode) NULL /* No fdopen() */
  139. #endif
  140. /* Common defaults */
  141. #ifndef OS_CODE
  142. # define OS_CODE 0x03 /* assume Unix */
  143. #endif
  144. #ifndef FOPEN
  145. # define FOPEN(name, mode) fopen((name), (mode))
  146. #endif
  147. /* functions */
  148. #ifdef HAVE_STRERROR
  149. extern char *strerror OF((int));
  150. # define zstrerror(errnum) strerror(errnum)
  151. #else
  152. # define zstrerror(errnum) ""
  153. #endif
  154. #if defined(pyr)
  155. # define NO_MEMCPY
  156. #endif
  157. #if (defined(M_I86SM) || defined(M_I86MM)) && !defined(_MSC_VER)
  158. /* Use our own functions for small and medium model with MSC <= 5.0.
  159. * You may have to use the same strategy for Borland C (untested).
  160. */
  161. # define NO_MEMCPY
  162. #endif
  163. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  164. # define HAVE_MEMCPY
  165. #endif
  166. #ifdef HAVE_MEMCPY
  167. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  168. # define zmemcpy _fmemcpy
  169. # define zmemcmp _fmemcmp
  170. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  171. # else
  172. # define zmemcpy memcpy
  173. # define zmemcmp memcmp
  174. # define zmemzero(dest, len) memset(dest, 0, len)
  175. # endif
  176. #else
  177. extern void zmemcpy OF((Bytef* dest, Bytef* source, uInt len));
  178. extern int zmemcmp OF((Bytef* s1, Bytef* s2, uInt len));
  179. extern void zmemzero OF((Bytef* dest, uInt len));
  180. #endif
  181. /* Diagnostic functions */
  182. #ifdef DEBUG_ZLIB
  183. # include <stdio.h>
  184. # ifndef verbose
  185. # define verbose 0
  186. # endif
  187. extern void z_error OF((char *m));
  188. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  189. # define Trace(x) fprintf x
  190. # define Tracev(x) {if (verbose) fprintf x ;}
  191. # define Tracevv(x) {if (verbose>1) fprintf x ;}
  192. # define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
  193. # define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
  194. #else
  195. # define Assert(cond,msg)
  196. # define Trace(x)
  197. # define Tracev(x)
  198. # define Tracevv(x)
  199. # define Tracec(c,x)
  200. # define Tracecv(c,x)
  201. #endif
  202. typedef uLong (*check_func) OF((uLong check, const Bytef *buf, uInt len));
  203. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  204. void zcfree OF((voidpf opaque, voidpf ptr));
  205. #define ZALLOC(strm, items, size) \
  206. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  207. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  208. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  209. #endif /* _Z_UTIL_H */
  210. /* --- zutil.h */
  211. /* +++ deflate.h */
  212. /* deflate.h -- internal compression state
  213. * Copyright (C) 1995-1996 Jean-loup Gailly
  214. * For conditions of distribution and use, see copyright notice in zlib.h
  215. */
  216. /* WARNING: this file should *not* be used by applications. It is
  217. part of the implementation of the compression library and is
  218. subject to change. Applications should only use zlib.h.
  219. */
  220. /* From: deflate.h,v 1.10 1996/07/02 12:41:00 me Exp $ */
  221. #ifndef _DEFLATE_H
  222. #define _DEFLATE_H
  223. /* #include "zutil.h" */
  224. /* ===========================================================================
  225. * Internal compression state.
  226. */
  227. #define LENGTH_CODES 29
  228. /* number of length codes, not counting the special END_BLOCK code */
  229. #define LITERALS 256
  230. /* number of literal bytes 0..255 */
  231. #define L_CODES (LITERALS+1+LENGTH_CODES)
  232. /* number of Literal or Length codes, including the END_BLOCK code */
  233. #define D_CODES 30
  234. /* number of distance codes */
  235. #define BL_CODES 19
  236. /* number of codes used to transfer the bit lengths */
  237. #define HEAP_SIZE (2*L_CODES+1)
  238. /* maximum heap size */
  239. #define MAX_BITS 15
  240. /* All codes must not exceed MAX_BITS bits */
  241. #define INIT_STATE 42
  242. #define BUSY_STATE 113
  243. #define FINISH_STATE 666
  244. /* Stream status */
  245. /* Data structure describing a single value and its code string. */
  246. typedef struct ct_data_s {
  247. union {
  248. ush freq; /* frequency count */
  249. ush code; /* bit string */
  250. } fc;
  251. union {
  252. ush dad; /* father node in Huffman tree */
  253. ush len; /* length of bit string */
  254. } dl;
  255. } FAR ct_data;
  256. #define Freq fc.freq
  257. #define Code fc.code
  258. #define Dad dl.dad
  259. #define Len dl.len
  260. typedef struct static_tree_desc_s static_tree_desc;
  261. typedef struct tree_desc_s {
  262. ct_data *dyn_tree; /* the dynamic tree */
  263. int max_code; /* largest code with non zero frequency */
  264. static_tree_desc *stat_desc; /* the corresponding static tree */
  265. } FAR tree_desc;
  266. typedef ush Pos;
  267. typedef Pos FAR Posf;
  268. typedef unsigned IPos;
  269. /* A Pos is an index in the character window. We use short instead of int to
  270. * save space in the various tables. IPos is used only for parameter passing.
  271. */
  272. typedef struct deflate_state {
  273. z_streamp strm; /* pointer back to this zlib stream */
  274. int status; /* as the name implies */
  275. Bytef *pending_buf; /* output still pending */
  276. ulg pending_buf_size; /* size of pending_buf */
  277. Bytef *pending_out; /* next pending byte to output to the stream */
  278. int pending; /* nb of bytes in the pending buffer */
  279. int noheader; /* suppress zlib header and adler32 */
  280. Byte data_type; /* UNKNOWN, BINARY or ASCII */
  281. Byte method; /* STORED (for zip only) or DEFLATED */
  282. int last_flush; /* value of flush param for previous deflate call */
  283. /* used by deflate.c: */
  284. uInt w_size; /* LZ77 window size (32K by default) */
  285. uInt w_bits; /* log2(w_size) (8..16) */
  286. uInt w_mask; /* w_size - 1 */
  287. Bytef *window;
  288. /* Sliding window. Input bytes are read into the second half of the window,
  289. * and move to the first half later to keep a dictionary of at least wSize
  290. * bytes. With this organization, matches are limited to a distance of
  291. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  292. * performed with a length multiple of the block size. Also, it limits
  293. * the window size to 64K, which is quite useful on MSDOS.
  294. * To do: use the user input buffer as sliding window.
  295. */
  296. ulg window_size;
  297. /* Actual size of window: 2*wSize, except when the user input buffer
  298. * is directly used as sliding window.
  299. */
  300. Posf *prev;
  301. /* Link to older string with same hash index. To limit the size of this
  302. * array to 64K, this link is maintained only for the last 32K strings.
  303. * An index in this array is thus a window index modulo 32K.
  304. */
  305. Posf *head; /* Heads of the hash chains or NIL. */
  306. uInt ins_h; /* hash index of string to be inserted */
  307. uInt hash_size; /* number of elements in hash table */
  308. uInt hash_bits; /* log2(hash_size) */
  309. uInt hash_mask; /* hash_size-1 */
  310. uInt hash_shift;
  311. /* Number of bits by which ins_h must be shifted at each input
  312. * step. It must be such that after MIN_MATCH steps, the oldest
  313. * byte no longer takes part in the hash key, that is:
  314. * hash_shift * MIN_MATCH >= hash_bits
  315. */
  316. long block_start;
  317. /* Window position at the beginning of the current output block. Gets
  318. * negative when the window is moved backwards.
  319. */
  320. uInt match_length; /* length of best match */
  321. IPos prev_match; /* previous match */
  322. int match_available; /* set if previous match exists */
  323. uInt strstart; /* start of string to insert */
  324. uInt match_start; /* start of matching string */
  325. uInt lookahead; /* number of valid bytes ahead in window */
  326. uInt prev_length;
  327. /* Length of the best match at previous step. Matches not greater than this
  328. * are discarded. This is used in the lazy match evaluation.
  329. */
  330. uInt max_chain_length;
  331. /* To speed up deflation, hash chains are never searched beyond this
  332. * length. A higher limit improves compression ratio but degrades the
  333. * speed.
  334. */
  335. uInt max_lazy_match;
  336. /* Attempt to find a better match only when the current match is strictly
  337. * smaller than this value. This mechanism is used only for compression
  338. * levels >= 4.
  339. */
  340. # define max_insert_length max_lazy_match
  341. /* Insert new strings in the hash table only if the match length is not
  342. * greater than this length. This saves time but degrades compression.
  343. * max_insert_length is used only for compression levels <= 3.
  344. */
  345. int level; /* compression level (1..9) */
  346. int strategy; /* favor or force Huffman coding*/
  347. uInt good_match;
  348. /* Use a faster search when the previous match is longer than this */
  349. int nice_match; /* Stop searching when current match exceeds this */
  350. /* used by trees.c: */
  351. /* Didn't use ct_data typedef below to supress compiler warning */
  352. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  353. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  354. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  355. struct tree_desc_s l_desc; /* desc. for literal tree */
  356. struct tree_desc_s d_desc; /* desc. for distance tree */
  357. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  358. ush bl_count[MAX_BITS+1];
  359. /* number of codes at each bit length for an optimal tree */
  360. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  361. int heap_len; /* number of elements in the heap */
  362. int heap_max; /* element of largest frequency */
  363. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  364. * The same heap array is used to build all trees.
  365. */
  366. uch depth[2*L_CODES+1];
  367. /* Depth of each subtree used as tie breaker for trees of equal frequency
  368. */
  369. uchf *l_buf; /* buffer for literals or lengths */
  370. uInt lit_bufsize;
  371. /* Size of match buffer for literals/lengths. There are 4 reasons for
  372. * limiting lit_bufsize to 64K:
  373. * - frequencies can be kept in 16 bit counters
  374. * - if compression is not successful for the first block, all input
  375. * data is still in the window so we can still emit a stored block even
  376. * when input comes from standard input. (This can also be done for
  377. * all blocks if lit_bufsize is not greater than 32K.)
  378. * - if compression is not successful for a file smaller than 64K, we can
  379. * even emit a stored file instead of a stored block (saving 5 bytes).
  380. * This is applicable only for zip (not gzip or zlib).
  381. * - creating new Huffman trees less frequently may not provide fast
  382. * adaptation to changes in the input data statistics. (Take for
  383. * example a binary file with poorly compressible code followed by
  384. * a highly compressible string table.) Smaller buffer sizes give
  385. * fast adaptation but have of course the overhead of transmitting
  386. * trees more frequently.
  387. * - I can't count above 4
  388. */
  389. uInt last_lit; /* running index in l_buf */
  390. ushf *d_buf;
  391. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  392. * the same number of elements. To use different lengths, an extra flag
  393. * array would be necessary.
  394. */
  395. ulg opt_len; /* bit length of current block with optimal trees */
  396. ulg static_len; /* bit length of current block with static trees */
  397. ulg compressed_len; /* total bit length of compressed file */
  398. uInt matches; /* number of string matches in current block */
  399. int last_eob_len; /* bit length of EOB code for last block */
  400. #ifdef DEBUG_ZLIB
  401. ulg bits_sent; /* bit length of the compressed data */
  402. #endif
  403. ush bi_buf;
  404. /* Output buffer. bits are inserted starting at the bottom (least
  405. * significant bits).
  406. */
  407. int bi_valid;
  408. /* Number of valid bits in bi_buf. All bits above the last valid bit
  409. * are always zero.
  410. */
  411. } FAR deflate_state;
  412. /* Output a byte on the stream.
  413. * IN assertion: there is enough room in pending_buf.
  414. */
  415. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  416. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  417. /* Minimum amount of lookahead, except at the end of the input file.
  418. * See deflate.c for comments about the MIN_MATCH+1.
  419. */
  420. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  421. /* In order to simplify the code, particularly on 16 bit machines, match
  422. * distances are limited to MAX_DIST instead of WSIZE.
  423. */
  424. /* in trees.c */
  425. void _tr_init OF((deflate_state *s));
  426. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  427. ulg _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  428. int eof));
  429. void _tr_align OF((deflate_state *s));
  430. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  431. int eof));
  432. void _tr_stored_type_only OF((deflate_state *));
  433. #endif
  434. /* --- deflate.h */
  435. /* +++ deflate.c */
  436. /* deflate.c -- compress data using the deflation algorithm
  437. * Copyright (C) 1995-1996 Jean-loup Gailly.
  438. * For conditions of distribution and use, see copyright notice in zlib.h
  439. */
  440. /*
  441. * ALGORITHM
  442. *
  443. * The "deflation" process depends on being able to identify portions
  444. * of the input text which are identical to earlier input (within a
  445. * sliding window trailing behind the input currently being processed).
  446. *
  447. * The most straightforward technique turns out to be the fastest for
  448. * most input files: try all possible matches and select the longest.
  449. * The key feature of this algorithm is that insertions into the string
  450. * dictionary are very simple and thus fast, and deletions are avoided
  451. * completely. Insertions are performed at each input character, whereas
  452. * string matches are performed only when the previous match ends. So it
  453. * is preferable to spend more time in matches to allow very fast string
  454. * insertions and avoid deletions. The matching algorithm for small
  455. * strings is inspired from that of Rabin & Karp. A brute force approach
  456. * is used to find longer strings when a small match has been found.
  457. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  458. * (by Leonid Broukhis).
  459. * A previous version of this file used a more sophisticated algorithm
  460. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  461. * time, but has a larger average cost, uses more memory and is patented.
  462. * However the F&G algorithm may be faster for some highly redundant
  463. * files if the parameter max_chain_length (described below) is too large.
  464. *
  465. * ACKNOWLEDGEMENTS
  466. *
  467. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  468. * I found it in 'freeze' written by Leonid Broukhis.
  469. * Thanks to many people for bug reports and testing.
  470. *
  471. * REFERENCES
  472. *
  473. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  474. * Available in ftp://ds.internic.net/rfc/rfc1951.txt
  475. *
  476. * A description of the Rabin and Karp algorithm is given in the book
  477. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  478. *
  479. * Fiala,E.R., and Greene,D.H.
  480. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  481. *
  482. */
  483. /* From: deflate.c,v 1.15 1996/07/24 13:40:58 me Exp $ */
  484. /* #include "deflate.h" */
  485. char deflate_copyright[] = " deflate 1.0.4 Copyright 1995-1996 Jean-loup Gailly ";
  486. /*
  487. If you use the zlib library in a product, an acknowledgment is welcome
  488. in the documentation of your product. If for some reason you cannot
  489. include such an acknowledgment, I would appreciate that you keep this
  490. copyright string in the executable of your product.
  491. */
  492. /* ===========================================================================
  493. * Function prototypes.
  494. */
  495. typedef enum {
  496. need_more, /* block not completed, need more input or more output */
  497. block_done, /* block flush performed */
  498. finish_started, /* finish started, need only more output at next deflate */
  499. finish_done /* finish done, accept no more input or output */
  500. } block_state;
  501. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  502. /* Compression function. Returns the block state after the call. */
  503. local void fill_window OF((deflate_state *s));
  504. local block_state deflate_stored OF((deflate_state *s, int flush));
  505. local block_state deflate_fast OF((deflate_state *s, int flush));
  506. local block_state deflate_slow OF((deflate_state *s, int flush));
  507. local void lm_init OF((deflate_state *s));
  508. local void putShortMSB OF((deflate_state *s, uInt b));
  509. local void flush_pending OF((z_streamp strm));
  510. local int read_buf OF((z_streamp strm, charf *buf, unsigned size));
  511. #ifdef ASMV
  512. void match_init OF((void)); /* asm code initialization */
  513. uInt longest_match OF((deflate_state *s, IPos cur_match));
  514. #else
  515. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  516. #endif
  517. #ifdef DEBUG_ZLIB
  518. local void check_match OF((deflate_state *s, IPos start, IPos match,
  519. int length));
  520. #endif
  521. /* ===========================================================================
  522. * Local data
  523. */
  524. #define NIL 0
  525. /* Tail of hash chains */
  526. #ifndef TOO_FAR
  527. # define TOO_FAR 4096
  528. #endif
  529. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  530. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  531. /* Minimum amount of lookahead, except at the end of the input file.
  532. * See deflate.c for comments about the MIN_MATCH+1.
  533. */
  534. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  535. * the desired pack level (0..9). The values given below have been tuned to
  536. * exclude worst case performance for pathological files. Better values may be
  537. * found for specific files.
  538. */
  539. typedef struct config_s {
  540. ush good_length; /* reduce lazy search above this match length */
  541. ush max_lazy; /* do not perform lazy search above this match length */
  542. ush nice_length; /* quit search above this match length */
  543. ush max_chain;
  544. compress_func func;
  545. } config;
  546. local config configuration_table[10] = {
  547. /* good lazy nice chain */
  548. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  549. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */
  550. /* 2 */ {4, 5, 16, 8, deflate_fast},
  551. /* 3 */ {4, 6, 32, 32, deflate_fast},
  552. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  553. /* 5 */ {8, 16, 32, 32, deflate_slow},
  554. /* 6 */ {8, 16, 128, 128, deflate_slow},
  555. /* 7 */ {8, 32, 128, 256, deflate_slow},
  556. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  557. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
  558. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  559. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  560. * meaning.
  561. */
  562. #define EQUAL 0
  563. /* result of memcmp for equal strings */
  564. #ifndef NO_DUMMY_DECL
  565. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  566. #endif
  567. /* ===========================================================================
  568. * Update a hash value with the given input byte
  569. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  570. * input characters, so that a running hash key can be computed from the
  571. * previous key instead of complete recalculation each time.
  572. */
  573. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  574. /* ===========================================================================
  575. * Insert string str in the dictionary and set match_head to the previous head
  576. * of the hash chain (the most recent string with same hash key). Return
  577. * the previous length of the hash chain.
  578. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  579. * input characters and the first MIN_MATCH bytes of str are valid
  580. * (except for the last MIN_MATCH-1 bytes of the input file).
  581. */
  582. #define INSERT_STRING(s, str, match_head) \
  583. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  584. s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
  585. s->head[s->ins_h] = (Pos)(str))
  586. /* ===========================================================================
  587. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  588. * prev[] will be initialized on the fly.
  589. */
  590. #define CLEAR_HASH(s) \
  591. s->head[s->hash_size-1] = NIL; \
  592. zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  593. /* ========================================================================= */
  594. int deflateInit_(strm, level, version, stream_size)
  595. z_streamp strm;
  596. int level;
  597. const char *version;
  598. int stream_size;
  599. {
  600. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  601. Z_DEFAULT_STRATEGY, version, stream_size);
  602. /* To do: ignore strm->next_in if we use it as window */
  603. }
  604. /* ========================================================================= */
  605. int deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
  606. version, stream_size)
  607. z_streamp strm;
  608. int level;
  609. int method;
  610. int windowBits;
  611. int memLevel;
  612. int strategy;
  613. const char *version;
  614. int stream_size;
  615. {
  616. deflate_state *s;
  617. int noheader = 0;
  618. static char* my_version = ZLIB_VERSION;
  619. ushf *overlay;
  620. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  621. * output size for (length,distance) codes is <= 24 bits.
  622. */
  623. if (version == Z_NULL || version[0] != my_version[0] ||
  624. stream_size != sizeof(z_stream)) {
  625. return Z_VERSION_ERROR;
  626. }
  627. if (strm == Z_NULL) return Z_STREAM_ERROR;
  628. strm->msg = Z_NULL;
  629. #ifndef NO_ZCFUNCS
  630. if (strm->zalloc == Z_NULL) {
  631. strm->zalloc = zcalloc;
  632. strm->opaque = (voidpf)0;
  633. }
  634. if (strm->zfree == Z_NULL) strm->zfree = zcfree;
  635. #endif
  636. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  637. if (windowBits < 0) { /* undocumented feature: suppress zlib header */
  638. noheader = 1;
  639. windowBits = -windowBits;
  640. }
  641. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  642. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  643. strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  644. return Z_STREAM_ERROR;
  645. }
  646. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  647. if (s == Z_NULL) return Z_MEM_ERROR;
  648. strm->state = (struct internal_state FAR *)s;
  649. s->strm = strm;
  650. s->noheader = noheader;
  651. s->w_bits = windowBits;
  652. s->w_size = 1 << s->w_bits;
  653. s->w_mask = s->w_size - 1;
  654. s->hash_bits = memLevel + 7;
  655. s->hash_size = 1 << s->hash_bits;
  656. s->hash_mask = s->hash_size - 1;
  657. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  658. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  659. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  660. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  661. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  662. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  663. s->pending_buf = (uchf *) overlay;
  664. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  665. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  666. s->pending_buf == Z_NULL) {
  667. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  668. deflateEnd (strm);
  669. return Z_MEM_ERROR;
  670. }
  671. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  672. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  673. s->level = level;
  674. s->strategy = strategy;
  675. s->method = (Byte)method;
  676. return deflateReset(strm);
  677. }
  678. /* ========================================================================= */
  679. int deflateSetDictionary (strm, dictionary, dictLength)
  680. z_streamp strm;
  681. const Bytef *dictionary;
  682. uInt dictLength;
  683. {
  684. deflate_state *s;
  685. uInt length = dictLength;
  686. uInt n;
  687. IPos hash_head = 0;
  688. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)
  689. return Z_STREAM_ERROR;
  690. s = (deflate_state *) strm->state;
  691. if (s->status != INIT_STATE) return Z_STREAM_ERROR;
  692. strm->adler = adler32(strm->adler, dictionary, dictLength);
  693. if (length < MIN_MATCH) return Z_OK;
  694. if (length > MAX_DIST(s)) {
  695. length = MAX_DIST(s);
  696. #ifndef USE_DICT_HEAD
  697. dictionary += dictLength - length; /* use the tail of the dictionary */
  698. #endif
  699. }
  700. zmemcpy((charf *)s->window, dictionary, length);
  701. s->strstart = length;
  702. s->block_start = (long)length;
  703. /* Insert all strings in the hash table (except for the last two bytes).
  704. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  705. * call of fill_window.
  706. */
  707. s->ins_h = s->window[0];
  708. UPDATE_HASH(s, s->ins_h, s->window[1]);
  709. for (n = 0; n <= length - MIN_MATCH; n++) {
  710. INSERT_STRING(s, n, hash_head);
  711. }
  712. if (hash_head) hash_head = 0; /* to make compiler happy */
  713. return Z_OK;
  714. }
  715. /* ========================================================================= */
  716. int deflateReset (strm)
  717. z_streamp strm;
  718. {
  719. deflate_state *s;
  720. if (strm == Z_NULL || strm->state == Z_NULL ||
  721. strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
  722. strm->total_in = strm->total_out = 0;
  723. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  724. strm->data_type = Z_UNKNOWN;
  725. s = (deflate_state *)strm->state;
  726. s->pending = 0;
  727. s->pending_out = s->pending_buf;
  728. if (s->noheader < 0) {
  729. s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
  730. }
  731. s->status = s->noheader ? BUSY_STATE : INIT_STATE;
  732. strm->adler = 1;
  733. s->last_flush = Z_NO_FLUSH;
  734. _tr_init(s);
  735. lm_init(s);
  736. return Z_OK;
  737. }
  738. /* ========================================================================= */
  739. int deflateParams(strm, level, strategy)
  740. z_streamp strm;
  741. int level;
  742. int strategy;
  743. {
  744. deflate_state *s;
  745. compress_func func;
  746. int err = Z_OK;
  747. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  748. s = (deflate_state *) strm->state;
  749. if (level == Z_DEFAULT_COMPRESSION) {
  750. level = 6;
  751. }
  752. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  753. return Z_STREAM_ERROR;
  754. }
  755. func = configuration_table[s->level].func;
  756. if (func != configuration_table[level].func && strm->total_in != 0) {
  757. /* Flush the last buffer: */
  758. err = deflate(strm, Z_PARTIAL_FLUSH);
  759. }
  760. if (s->level != level) {
  761. s->level = level;
  762. s->max_lazy_match = configuration_table[level].max_lazy;
  763. s->good_match = configuration_table[level].good_length;
  764. s->nice_match = configuration_table[level].nice_length;
  765. s->max_chain_length = configuration_table[level].max_chain;
  766. }
  767. s->strategy = strategy;
  768. return err;
  769. }
  770. /* =========================================================================
  771. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  772. * IN assertion: the stream state is correct and there is enough room in
  773. * pending_buf.
  774. */
  775. local void putShortMSB (s, b)
  776. deflate_state *s;
  777. uInt b;
  778. {
  779. put_byte(s, (Byte)(b >> 8));
  780. put_byte(s, (Byte)(b & 0xff));
  781. }
  782. /* =========================================================================
  783. * Flush as much pending output as possible. All deflate() output goes
  784. * through this function so some applications may wish to modify it
  785. * to avoid allocating a large strm->next_out buffer and copying into it.
  786. * (See also read_buf()).
  787. */
  788. local void flush_pending(strm)
  789. z_streamp strm;
  790. {
  791. deflate_state *s = (deflate_state *) strm->state;
  792. unsigned len = s->pending;
  793. if (len > strm->avail_out) len = strm->avail_out;
  794. if (len == 0) return;
  795. if (strm->next_out != Z_NULL) {
  796. zmemcpy(strm->next_out, s->pending_out, len);
  797. strm->next_out += len;
  798. }
  799. s->pending_out += len;
  800. strm->total_out += len;
  801. strm->avail_out -= len;
  802. s->pending -= len;
  803. if (s->pending == 0) {
  804. s->pending_out = s->pending_buf;
  805. }
  806. }
  807. /* ========================================================================= */
  808. int deflate (strm, flush)
  809. z_streamp strm;
  810. int flush;
  811. {
  812. int old_flush; /* value of flush param for previous deflate call */
  813. deflate_state *s;
  814. if (strm == Z_NULL || strm->state == Z_NULL ||
  815. flush > Z_FINISH || flush < 0) {
  816. return Z_STREAM_ERROR;
  817. }
  818. s = (deflate_state *) strm->state;
  819. if ((strm->next_in == Z_NULL && strm->avail_in != 0) ||
  820. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  821. ERR_RETURN(strm, Z_STREAM_ERROR);
  822. }
  823. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  824. s->strm = strm; /* just in case */
  825. old_flush = s->last_flush;
  826. s->last_flush = flush;
  827. /* Write the zlib header */
  828. if (s->status == INIT_STATE) {
  829. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  830. uInt level_flags = (s->level-1) >> 1;
  831. if (level_flags > 3) level_flags = 3;
  832. header |= (level_flags << 6);
  833. if (s->strstart != 0) header |= PRESET_DICT;
  834. header += 31 - (header % 31);
  835. s->status = BUSY_STATE;
  836. putShortMSB(s, header);
  837. /* Save the adler32 of the preset dictionary: */
  838. if (s->strstart != 0) {
  839. putShortMSB(s, (uInt)(strm->adler >> 16));
  840. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  841. }
  842. strm->adler = 1L;
  843. }
  844. /* Flush as much pending output as possible */
  845. if (s->pending != 0) {
  846. flush_pending(strm);
  847. if (strm->avail_out == 0) {
  848. /* Since avail_out is 0, deflate will be called again with
  849. * more output space, but possibly with both pending and
  850. * avail_in equal to zero. There won't be anything to do,
  851. * but this is not an error situation so make sure we
  852. * return OK instead of BUF_ERROR at next call of deflate:
  853. */
  854. s->last_flush = -1;
  855. return Z_OK;
  856. }
  857. /* Make sure there is something to do and avoid duplicate consecutive
  858. * flushes. For repeated and useless calls with Z_FINISH, we keep
  859. * returning Z_STREAM_END instead of Z_BUFF_ERROR.
  860. */
  861. } else if (strm->avail_in == 0 && flush <= old_flush &&
  862. flush != Z_FINISH) {
  863. ERR_RETURN(strm, Z_BUF_ERROR);
  864. }
  865. /* User must not provide more input after the first FINISH: */
  866. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  867. ERR_RETURN(strm, Z_BUF_ERROR);
  868. }
  869. /* Start a new block or continue the current one.
  870. */
  871. if (strm->avail_in != 0 || s->lookahead != 0 ||
  872. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  873. block_state bstate;
  874. bstate = (*(configuration_table[s->level].func))(s, flush);
  875. if (bstate == finish_started || bstate == finish_done) {
  876. s->status = FINISH_STATE;
  877. }
  878. if (bstate == need_more || bstate == finish_started) {
  879. if (strm->avail_out == 0) {
  880. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  881. }
  882. return Z_OK;
  883. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  884. * of deflate should use the same flush parameter to make sure
  885. * that the flush is complete. So we don't have to output an
  886. * empty block here, this will be done at next call. This also
  887. * ensures that for a very small output buffer, we emit at most
  888. * one empty block.
  889. */
  890. }
  891. if (bstate == block_done) {
  892. if (flush == Z_PARTIAL_FLUSH) {
  893. _tr_align(s);
  894. } else if (flush == Z_PACKET_FLUSH) {
  895. /* Output just the 3-bit `stored' block type value,
  896. but not a zero length. */
  897. _tr_stored_type_only(s);
  898. } else { /* FULL_FLUSH or SYNC_FLUSH */
  899. _tr_stored_block(s, (char*)0, 0L, 0);
  900. /* For a full flush, this empty block will be recognized
  901. * as a special marker by inflate_sync().
  902. */
  903. if (flush == Z_FULL_FLUSH) {
  904. CLEAR_HASH(s); /* forget history */
  905. }
  906. }
  907. flush_pending(strm);
  908. if (strm->avail_out == 0) {
  909. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  910. return Z_OK;
  911. }
  912. }
  913. }
  914. Assert(strm->avail_out > 0, "bug2");
  915. if (flush != Z_FINISH) return Z_OK;
  916. if (s->noheader) return Z_STREAM_END;
  917. /* Write the zlib trailer (adler32) */
  918. putShortMSB(s, (uInt)(strm->adler >> 16));
  919. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  920. flush_pending(strm);
  921. /* If avail_out is zero, the application will call deflate again
  922. * to flush the rest.
  923. */
  924. s->noheader = -1; /* write the trailer only once! */
  925. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  926. }
  927. /* ========================================================================= */
  928. int deflateEnd (strm)
  929. z_streamp strm;
  930. {
  931. int status;
  932. deflate_state *s;
  933. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  934. s = (deflate_state *) strm->state;
  935. status = s->status;
  936. if (status != INIT_STATE && status != BUSY_STATE &&
  937. status != FINISH_STATE) {
  938. return Z_STREAM_ERROR;
  939. }
  940. /* Deallocate in reverse order of allocations: */
  941. TRY_FREE(strm, s->pending_buf);
  942. TRY_FREE(strm, s->head);
  943. TRY_FREE(strm, s->prev);
  944. TRY_FREE(strm, s->window);
  945. ZFREE(strm, s);
  946. strm->state = Z_NULL;
  947. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  948. }
  949. /* =========================================================================
  950. * Copy the source state to the destination state.
  951. */
  952. int deflateCopy (dest, source)
  953. z_streamp dest;
  954. z_streamp source;
  955. {
  956. deflate_state *ds;
  957. deflate_state *ss;
  958. ushf *overlay;
  959. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL)
  960. return Z_STREAM_ERROR;
  961. ss = (deflate_state *) source->state;
  962. zmemcpy(dest, source, sizeof(*dest));
  963. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  964. if (ds == Z_NULL) return Z_MEM_ERROR;
  965. dest->state = (struct internal_state FAR *) ds;
  966. zmemcpy(ds, ss, sizeof(*ds));
  967. ds->strm = dest;
  968. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  969. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  970. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  971. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  972. ds->pending_buf = (uchf *) overlay;
  973. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  974. ds->pending_buf == Z_NULL) {
  975. deflateEnd (dest);
  976. return Z_MEM_ERROR;
  977. }
  978. /* ??? following zmemcpy doesn't work for 16-bit MSDOS */
  979. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  980. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  981. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  982. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  983. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  984. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  985. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  986. ds->l_desc.dyn_tree = ds->dyn_ltree;
  987. ds->d_desc.dyn_tree = ds->dyn_dtree;
  988. ds->bl_desc.dyn_tree = ds->bl_tree;
  989. return Z_OK;
  990. }
  991. /* ===========================================================================
  992. * Return the number of bytes of output which are immediately available
  993. * for output from the decompressor.
  994. */
  995. int deflateOutputPending (strm)
  996. z_streamp strm;
  997. {
  998. if (strm == Z_NULL || strm->state == Z_NULL) return 0;
  999. return ((deflate_state *)(strm->state))->pending;
  1000. }
  1001. /* ===========================================================================
  1002. * Read a new buffer from the current input stream, update the adler32
  1003. * and total number of bytes read. All deflate() input goes through
  1004. * this function so some applications may wish to modify it to avoid
  1005. * allocating a large strm->next_in buffer and copying from it.
  1006. * (See also flush_pending()).
  1007. */
  1008. local int read_buf(strm, buf, size)
  1009. z_streamp strm;
  1010. charf *buf;
  1011. unsigned size;
  1012. {
  1013. unsigned len = strm->avail_in;
  1014. if (len > size) len = size;
  1015. if (len == 0) return 0;
  1016. strm->avail_in -= len;
  1017. if (!((deflate_state *)(strm->state))->noheader) {
  1018. strm->adler = adler32(strm->adler, strm->next_in, len);
  1019. }
  1020. zmemcpy(buf, strm->next_in, len);
  1021. strm->next_in += len;
  1022. strm->total_in += len;
  1023. return (int)len;
  1024. }
  1025. /* ===========================================================================
  1026. * Initialize the "longest match" routines for a new zlib stream
  1027. */
  1028. local void lm_init (s)
  1029. deflate_state *s;
  1030. {
  1031. s->window_size = (ulg)2L*s->w_size;
  1032. CLEAR_HASH(s);
  1033. /* Set the default configuration parameters:
  1034. */
  1035. s->max_lazy_match = configuration_table[s->level].max_lazy;
  1036. s->good_match = configuration_table[s->level].good_length;
  1037. s->nice_match = configuration_table[s->level].nice_length;
  1038. s->max_chain_length = configuration_table[s->level].max_chain;
  1039. s->strstart = 0;
  1040. s->block_start = 0L;
  1041. s->lookahead = 0;
  1042. s->match_length = s->prev_length = MIN_MATCH-1;
  1043. s->match_available = 0;
  1044. s->ins_h = 0;
  1045. #ifdef ASMV
  1046. match_init(); /* initialize the asm code */
  1047. #endif
  1048. }
  1049. /* ===========================================================================
  1050. * Set match_start to the longest match starting at the given string and
  1051. * return its length. Matches shorter or equal to prev_length are discarded,
  1052. * in which case the result is equal to prev_length and match_start is
  1053. * garbage.
  1054. * IN assertions: cur_match is the head of the hash chain for the current
  1055. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1056. * OUT assertion: the match length is not greater than s->lookahead.
  1057. */
  1058. #ifndef ASMV
  1059. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1060. * match.S. The code will be functionally equivalent.
  1061. */
  1062. local uInt longest_match(s, cur_match)
  1063. deflate_state *s;
  1064. IPos cur_match; /* current match */
  1065. {
  1066. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  1067. register Bytef *scan = s->window + s->strstart; /* current string */
  1068. register Bytef *match; /* matched string */
  1069. register int len; /* length of current match */
  1070. int best_len = s->prev_length; /* best match length so far */
  1071. int nice_match = s->nice_match; /* stop if match long enough */
  1072. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  1073. s->strstart - (IPos)MAX_DIST(s) : NIL;
  1074. /* Stop when cur_match becomes <= limit. To simplify the code,
  1075. * we prevent matches with the string of window index 0.
  1076. */
  1077. Posf *prev = s->prev;
  1078. uInt wmask = s->w_mask;
  1079. #ifdef UNALIGNED_OK
  1080. /* Compare two bytes at a time. Note: this is not always beneficial.
  1081. * Try with and without -DUNALIGNED_OK to check.
  1082. */
  1083. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  1084. register ush scan_start = *(ushf*)scan;
  1085. register ush scan_end = *(ushf*)(scan+best_len-1);
  1086. #else
  1087. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  1088. register Byte scan_end1 = scan[best_len-1];
  1089. register Byte scan_end = scan[best_len];
  1090. #endif
  1091. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1092. * It is easy to get rid of this optimization if necessary.
  1093. */
  1094. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1095. /* Do not waste too much time if we already have a good match: */
  1096. if (s->prev_length >= s->good_match) {
  1097. chain_length >>= 2;
  1098. }
  1099. /* Do not look for matches beyond the end of the input. This is necessary
  1100. * to make deflate deterministic.
  1101. */
  1102. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  1103. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1104. do {
  1105. Assert(cur_match < s->strstart, "no future");
  1106. match = s->window + cur_match;
  1107. /* Skip to next match if the match length cannot increase
  1108. * or if the match length is less than 2:
  1109. */
  1110. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  1111. /* This code assumes sizeof(unsigned short) == 2. Do not use
  1112. * UNALIGNED_OK if your compiler uses a different size.
  1113. */
  1114. if (*(ushf*)(match+best_len-1) != scan_end ||
  1115. *(ushf*)match != scan_start) continue;
  1116. /* It is not necessary to compare scan[2] and match[2] since they are
  1117. * always equal when the other bytes match, given that the hash keys
  1118. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1119. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  1120. * lookahead only every 4th comparison; the 128th check will be made
  1121. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1122. * necessary to put more guard bytes at the end of the window, or
  1123. * to check more often for insufficient lookahead.
  1124. */
  1125. Assert(scan[2] == match[2], "scan[2]?");
  1126. scan++, match++;
  1127. do {
  1128. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1129. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1130. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1131. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1132. scan < strend);
  1133. /* The funny "do {}" generates better code on most compilers */
  1134. /* Here, scan <= window+strstart+257 */
  1135. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1136. if (*scan == *match) scan++;
  1137. len = (MAX_MATCH - 1) - (int)(strend-scan);
  1138. scan = strend - (MAX_MATCH-1);
  1139. #else /* UNALIGNED_OK */
  1140. if (match[best_len] != scan_end ||
  1141. match[best_len-1] != scan_end1 ||
  1142. *match != *scan ||
  1143. *++match != scan[1]) continue;
  1144. /* The check at best_len-1 can be removed because it will be made
  1145. * again later. (This heuristic is not always a win.)
  1146. * It is not necessary to compare scan[2] and match[2] since they
  1147. * are always equal when the other bytes match, given that
  1148. * the hash keys are equal and that HASH_BITS >= 8.
  1149. */
  1150. scan += 2, match++;
  1151. Assert(*scan == *match, "match[2]?");
  1152. /* We check for insufficient lookahead only every 8th comparison;
  1153. * the 256th check will be made at strstart+258.
  1154. */
  1155. do {
  1156. } while (*++scan == *++match && *++scan == *++match &&
  1157. *++scan == *++match && *++scan == *++match &&
  1158. *++scan == *++match && *++scan == *++match &&
  1159. *++scan == *++match && *++scan == *++match &&
  1160. scan < strend);
  1161. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1162. len = MAX_MATCH - (int)(strend - scan);
  1163. scan = strend - MAX_MATCH;
  1164. #endif /* UNALIGNED_OK */
  1165. if (len > best_len) {
  1166. s->match_start = cur_match;
  1167. best_len = len;
  1168. if (len >= nice_match) break;
  1169. #ifdef UNALIGNED_OK
  1170. scan_end = *(ushf*)(scan+best_len-1);
  1171. #else
  1172. scan_end1 = scan[best_len-1];
  1173. scan_end = scan[best_len];
  1174. #endif
  1175. }
  1176. } while ((cur_match = prev[cur_match & wmask]) > limit
  1177. && --chain_length != 0);
  1178. if ((uInt)best_len <= s->lookahead) return best_len;
  1179. return s->lookahead;
  1180. }
  1181. #endif /* ASMV */
  1182. #ifdef DEBUG_ZLIB
  1183. /* ===========================================================================
  1184. * Check that the match at match_start is indeed a match.
  1185. */
  1186. local void check_match(s, start, match, length)
  1187. deflate_state *s;
  1188. IPos start, match;
  1189. int length;
  1190. {
  1191. /* check that the match is indeed a match */
  1192. if (zmemcmp((charf *)s->window + match,
  1193. (charf *)s->window + start, length) != EQUAL) {
  1194. fprintf(stderr, " start %u, match %u, length %d\n",
  1195. start, match, length);
  1196. do {
  1197. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  1198. } while (--length != 0);
  1199. z_error("invalid match");
  1200. }
  1201. if (z_verbose > 1) {
  1202. fprintf(stderr,"\\[%d,%d]", start-match, length);
  1203. do { putc(s->window[start++], stderr); } while (--length != 0);
  1204. }
  1205. }
  1206. #else
  1207. # define check_match(s, start, match, length)
  1208. #endif
  1209. /* ===========================================================================
  1210. * Fill the window when the lookahead becomes insufficient.
  1211. * Updates strstart and lookahead.
  1212. *
  1213. * IN assertion: lookahead < MIN_LOOKAHEAD
  1214. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1215. * At least one byte has been read, or avail_in == 0; reads are
  1216. * performed for at least two bytes (required for the zip translate_eol
  1217. * option -- not supported here).
  1218. */
  1219. local void fill_window(s)
  1220. deflate_state *s;
  1221. {
  1222. register unsigned n, m;
  1223. register Posf *p;
  1224. unsigned more; /* Amount of free space at the end of the window. */
  1225. uInt wsize = s->w_size;
  1226. do {
  1227. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  1228. /* Deal with !@#$% 64K limit: */
  1229. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  1230. more = wsize;
  1231. } else if (more == (unsigned)(-1)) {
  1232. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  1233. * and lookahead == 1 (input done one byte at time)
  1234. */
  1235. more--;
  1236. /* If the window is almost full and there is insufficient lookahead,
  1237. * move the upper half to the lower one to make room in the upper half.
  1238. */
  1239. } else if (s->strstart >= wsize+MAX_DIST(s)) {
  1240. zmemcpy((charf *)s->window, (charf *)s->window+wsize,
  1241. (unsigned)wsize);
  1242. s->match_start -= wsize;
  1243. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  1244. s->block_start -= (long) wsize;
  1245. /* Slide the hash table (could be avoided with 32 bit values
  1246. at the expense of memory usage). We slide even when level == 0
  1247. to keep the hash table consistent if we switch back to level > 0
  1248. later. (Using level 0 permanently is not an optimal usage of
  1249. zlib, so we don't care about this pathological case.)
  1250. */
  1251. n = s->hash_size;
  1252. p = &s->head[n];
  1253. do {
  1254. m = *--p;
  1255. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  1256. } while (--n);
  1257. n = wsize;
  1258. p = &s->prev[n];
  1259. do {
  1260. m = *--p;
  1261. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  1262. /* If n is not on any hash chain, prev[n] is garbage but
  1263. * its value will never be used.
  1264. */
  1265. } while (--n);
  1266. more += wsize;
  1267. }
  1268. if (s->strm->avail_in == 0) return;
  1269. /* If there was no sliding:
  1270. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1271. * more == window_size - lookahead - strstart
  1272. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1273. * => more >= window_size - 2*WSIZE + 2
  1274. * In the BIG_MEM or MMAP case (not yet supported),
  1275. * window_size == input_size + MIN_LOOKAHEAD &&
  1276. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1277. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1278. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1279. */
  1280. Assert(more >= 2, "more < 2");
  1281. n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
  1282. more);
  1283. s->lookahead += n;
  1284. /* Initialize the hash value now that we have some input: */
  1285. if (s->lookahead >= MIN_MATCH) {
  1286. s->ins_h = s->window[s->strstart];
  1287. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1288. #if MIN_MATCH != 3
  1289. Call UPDATE_HASH() MIN_MATCH-3 more times
  1290. #endif
  1291. }
  1292. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1293. * but this is not important since only literal bytes will be emitted.
  1294. */
  1295. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  1296. }
  1297. /* ===========================================================================
  1298. * Flush the current block, with given end-of-file flag.
  1299. * IN assertion: strstart is set to the end of the current match.
  1300. */
  1301. #define FLUSH_BLOCK_ONLY(s, eof) { \
  1302. _tr_flush_block(s, (s->block_start >= 0L ? \
  1303. (charf *)&s->window[(unsigned)s->block_start] : \
  1304. (charf *)Z_NULL), \
  1305. (ulg)((long)s->strstart - s->block_start), \
  1306. (eof)); \
  1307. s->block_start = s->strstart; \
  1308. flush_pending(s->strm); \
  1309. Tracev((stderr,"[FLUSH]")); \
  1310. }
  1311. /* Same but force premature exit if necessary. */
  1312. #define FLUSH_BLOCK(s, eof) { \
  1313. FLUSH_BLOCK_ONLY(s, eof); \
  1314. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  1315. }
  1316. /* ===========================================================================
  1317. * Copy without compression as much as possible from the input stream, return
  1318. * the current block state.
  1319. * This function does not insert new strings in the dictionary since
  1320. * uncompressible data is probably not useful. This function is used
  1321. * only for the level=0 compression option.
  1322. * NOTE: this function should be optimized to avoid extra copying from
  1323. * window to pending_buf.
  1324. */
  1325. local block_state deflate_stored(s, flush)
  1326. deflate_state *s;
  1327. int flush;
  1328. {
  1329. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1330. * to pending_buf_size, and each stored block has a 5 byte header:
  1331. */
  1332. ulg max_block_size = 0xffff;
  1333. ulg max_start;
  1334. if (max_block_size > s->pending_buf_size - 5) {
  1335. max_block_size = s->pending_buf_size - 5;
  1336. }
  1337. /* Copy as much as possible from input to output: */
  1338. for (;;) {
  1339. /* Fill the window as much as possible: */
  1340. if (s->lookahead <= 1) {
  1341. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  1342. s->block_start >= (long)s->w_size, "slide too late");
  1343. fill_window(s);
  1344. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  1345. if (s->lookahead == 0) break; /* flush the current block */
  1346. }
  1347. Assert(s->block_start >= 0L, "block gone");
  1348. s->strstart += s->lookahead;
  1349. s->lookahead = 0;
  1350. /* Emit a stored block if pending_buf will be full: */
  1351. max_start = s->block_start + max_block_size;
  1352. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  1353. /* strstart == 0 is possible when wraparound on 16-bit machine */
  1354. s->lookahead = (uInt)(s->strstart - max_start);
  1355. s->strstart = (uInt)max_start;
  1356. FLUSH_BLOCK(s, 0);
  1357. }
  1358. /* Flush if we may have to slide, otherwise block_start may become
  1359. * negative and the data will be gone:
  1360. */
  1361. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  1362. FLUSH_BLOCK(s, 0);
  1363. }
  1364. }
  1365. FLUSH_BLOCK(s, flush == Z_FINISH);
  1366. return flush == Z_FINISH ? finish_done : block_done;
  1367. }
  1368. /* ===========================================================================
  1369. * Compress as much as possible from the input stream, return the current
  1370. * block state.
  1371. * This function does not perform lazy evaluation of matches and inserts
  1372. * new strings in the dictionary only for unmatched strings or for short
  1373. * matches. It is used only for the fast compression options.
  1374. */
  1375. local block_state deflate_fast(s, flush)
  1376. deflate_state *s;
  1377. int flush;
  1378. {
  1379. IPos hash_head = NIL; /* head of the hash chain */
  1380. int bflush; /* set if current block must be flushed */
  1381. for (;;) {
  1382. /* Make sure that we always have enough lookahead, except
  1383. * at the end of the input file. We need MAX_MATCH bytes
  1384. * for the next match, plus MIN_MATCH bytes to insert the
  1385. * string following the next match.
  1386. */
  1387. if (s->lookahead < MIN_LOOKAHEAD) {
  1388. fill_window(s);
  1389. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1390. return need_more;
  1391. }
  1392. if (s->lookahead == 0) break; /* flush the current block */
  1393. }
  1394. /* Insert the string window[strstart .. strstart+2] in the
  1395. * dictionary, and set hash_head to the head of the hash chain:
  1396. */
  1397. if (s->lookahead >= MIN_MATCH) {
  1398. INSERT_STRING(s, s->strstart, hash_head);
  1399. }
  1400. /* Find the longest match, discarding those <= prev_length.
  1401. * At this point we have always match_length < MIN_MATCH
  1402. */
  1403. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  1404. /* To simplify the code, we prevent matches with the string
  1405. * of window index 0 (in particular we have to avoid a match
  1406. * of the string with itself at the start of the input file).
  1407. */
  1408. if (s->strategy != Z_HUFFMAN_ONLY) {
  1409. s->match_length = longest_match (s, hash_head);
  1410. }
  1411. /* longest_match() sets match_start */
  1412. }
  1413. if (s->match_length >= MIN_MATCH) {
  1414. check_match(s, s->strstart, s->match_start, s->match_length);
  1415. bflush = _tr_tally(s, s->strstart - s->match_start,
  1416. s->match_length - MIN_MATCH);
  1417. s->lookahead -= s->match_length;
  1418. /* Insert new strings in the hash table only if the match length
  1419. * is not too large. This saves time but degrades compression.
  1420. */
  1421. if (s->match_length <= s->max_insert_length &&
  1422. s->lookahead >= MIN_MATCH) {
  1423. s->match_length--; /* string at strstart already in hash table */
  1424. do {
  1425. s->strstart++;
  1426. INSERT_STRING(s, s->strstart, hash_head);
  1427. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1428. * always MIN_MATCH bytes ahead.
  1429. */
  1430. } while (--s->match_length != 0);
  1431. s->strstart++;
  1432. } else {
  1433. s->strstart += s->match_length;
  1434. s->match_length = 0;
  1435. s->ins_h = s->window[s->strstart];
  1436. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1437. #if MIN_MATCH != 3
  1438. Call UPDATE_HASH() MIN_MATCH-3 more times
  1439. #endif
  1440. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1441. * matter since it will be recomputed at next deflate call.
  1442. */
  1443. }
  1444. } else {
  1445. /* No match, output a literal byte */
  1446. Tracevv((stderr,"%c", s->window[s->strstart]));
  1447. bflush = _tr_tally (s, 0, s->window[s->strstart]);
  1448. s->lookahead--;
  1449. s->strstart++;
  1450. }
  1451. if (bflush) FLUSH_BLOCK(s, 0);
  1452. }
  1453. FLUSH_BLOCK(s, flush == Z_FINISH);
  1454. return flush == Z_FINISH ? finish_done : block_done;
  1455. }
  1456. /* ===========================================================================
  1457. * Same as above, but achieves better compression. We use a lazy
  1458. * evaluation for matches: a match is finally adopted only if there is
  1459. * no better match at the next window position.
  1460. */
  1461. local block_state deflate_slow(s, flush)
  1462. deflate_state *s;
  1463. int flush;
  1464. {
  1465. IPos hash_head = NIL; /* head of hash chain */
  1466. int bflush; /* set if current block must be flushed */
  1467. /* Process the input block. */
  1468. for (;;) {
  1469. /* Make sure that we always have enough lookahead, except
  1470. * at the end of the input file. We need MAX_MATCH bytes
  1471. * for the next match, plus MIN_MATCH bytes to insert the
  1472. * string following the next match.
  1473. */
  1474. if (s->lookahead < MIN_LOOKAHEAD) {
  1475. fill_window(s);
  1476. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1477. return need_more;
  1478. }
  1479. if (s->lookahead == 0) break; /* flush the current block */
  1480. }
  1481. /* Insert the string window[strstart .. strstart+2] in the
  1482. * dictionary, and set hash_head to the head of the hash chain:
  1483. */
  1484. if (s->lookahead >= MIN_MATCH) {
  1485. INSERT_STRING(s, s->strstart, hash_head);
  1486. }
  1487. /* Find the longest match, discarding those <= prev_length.
  1488. */
  1489. s->prev_length = s->match_length, s->prev_match = s->match_start;
  1490. s->match_length = MIN_MATCH-1;
  1491. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1492. s->strstart - hash_head <= MAX_DIST(s)) {
  1493. /* To simplify the code, we prevent matches with the string
  1494. * of window index 0 (in particular we have to avoid a match
  1495. * of the string with itself at the start of the input file).
  1496. */
  1497. if (s->strategy != Z_HUFFMAN_ONLY) {
  1498. s->match_length = longest_match (s, hash_head);
  1499. }
  1500. /* longest_match() sets match_start */
  1501. if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
  1502. (s->match_length == MIN_MATCH &&
  1503. s->strstart - s->match_start > TOO_FAR))) {
  1504. /* If prev_match is also MIN_MATCH, match_start is garbage
  1505. * but we will ignore the current match anyway.
  1506. */
  1507. s->match_length = MIN_MATCH-1;
  1508. }
  1509. }
  1510. /* If there was a match at the previous step and the current
  1511. * match is not better, output the previous match:
  1512. */
  1513. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1514. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  1515. /* Do not insert strings in hash table beyond this. */
  1516. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1517. bflush = _tr_tally(s, s->strstart -1 - s->prev_match,
  1518. s->prev_length - MIN_MATCH);
  1519. /* Insert in hash table all strings up to the end of the match.
  1520. * strstart-1 and strstart are already inserted. If there is not
  1521. * enough lookahead, the last two strings are not inserted in
  1522. * the hash table.
  1523. */
  1524. s->lookahead -= s->prev_length-1;
  1525. s->prev_length -= 2;
  1526. do {
  1527. if (++s->strstart <= max_insert) {
  1528. INSERT_STRING(s, s->strstart, hash_head);
  1529. }
  1530. } while (--s->prev_length != 0);
  1531. s->match_available = 0;
  1532. s->match_length = MIN_MATCH-1;
  1533. s->strstart++;
  1534. if (bflush) FLUSH_BLOCK(s, 0);
  1535. } else if (s->match_available) {
  1536. /* If there was no match at the previous position, output a
  1537. * single literal. If there was a match but the current match
  1538. * is longer, truncate the previous match to a single literal.
  1539. */
  1540. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1541. if (_tr_tally (s, 0, s->window[s->strstart-1])) {
  1542. FLUSH_BLOCK_ONLY(s, 0);
  1543. }
  1544. s->strstart++;
  1545. s->lookahead--;
  1546. if (s->strm->avail_out == 0) return need_more;
  1547. } else {
  1548. /* There is no previous match to compare with, wait for
  1549. * the next step to decide.
  1550. */
  1551. s->match_available = 1;
  1552. s->strstart++;
  1553. s->lookahead--;
  1554. }
  1555. }
  1556. Assert (flush != Z_NO_FLUSH, "no flush?");
  1557. if (s->match_available) {
  1558. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1559. _tr_tally (s, 0, s->window[s->strstart-1]);
  1560. s->match_available = 0;
  1561. }
  1562. FLUSH_BLOCK(s, flush == Z_FINISH);
  1563. return flush == Z_FINISH ? finish_done : block_done;
  1564. }
  1565. /* --- deflate.c */
  1566. /* +++ trees.c */
  1567. /* trees.c -- output deflated data using Huffman coding
  1568. * Copyright (C) 1995-1996 Jean-loup Gailly
  1569. * For conditions of distribution and use, see copyright notice in zlib.h
  1570. */
  1571. /*
  1572. * ALGORITHM
  1573. *
  1574. * The "deflation" process uses several Huffman trees. The more
  1575. * common source values are represented by shorter bit sequences.
  1576. *
  1577. * Each code tree is stored in a compressed form which is itself
  1578. * a Huffman encoding of the lengths of all the code strings (in
  1579. * ascending order by source values). The actual code strings are
  1580. * reconstructed from the lengths in the inflate process, as described
  1581. * in the deflate specification.
  1582. *
  1583. * REFERENCES
  1584. *
  1585. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  1586. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  1587. *
  1588. * Storer, James A.
  1589. * Data Compression: Methods and Theory, pp. 49-50.
  1590. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  1591. *
  1592. * Sedgewick, R.
  1593. * Algorithms, p290.
  1594. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  1595. */
  1596. /* From: trees.c,v 1.11 1996/07/24 13:41:06 me Exp $ */
  1597. /* #include "deflate.h" */
  1598. #ifdef DEBUG_ZLIB
  1599. # include <ctype.h>
  1600. #endif
  1601. /* ===========================================================================
  1602. * Constants
  1603. */
  1604. #define MAX_BL_BITS 7
  1605. /* Bit length codes must not exceed MAX_BL_BITS bits */
  1606. #define END_BLOCK 256
  1607. /* end of block literal code */
  1608. #define REP_3_6 16
  1609. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  1610. #define REPZ_3_10 17
  1611. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  1612. #define REPZ_11_138 18
  1613. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  1614. local int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  1615. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  1616. local int extra_dbits[D_CODES] /* extra bits for each distance code */
  1617. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  1618. local int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  1619. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  1620. local uch bl_order[BL_CODES]
  1621. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  1622. /* The lengths of the bit length codes are sent in order of decreasing
  1623. * probability, to avoid transmitting the lengths for unused bit length codes.
  1624. */
  1625. #define Buf_size (8 * 2*sizeof(char))
  1626. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  1627. * more than 16 bits on some systems.)
  1628. */
  1629. /* ===========================================================================
  1630. * Local data. These are initialized only once.
  1631. */
  1632. local ct_data static_ltree[L_CODES+2];
  1633. /* The static literal tree. Since the bit lengths are imposed, there is no
  1634. * need for the L_CODES extra codes used during heap construction. However
  1635. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  1636. * below).
  1637. */
  1638. local ct_data static_dtree[D_CODES];
  1639. /* The static distance tree. (Actually a trivial tree since all codes use
  1640. * 5 bits.)
  1641. */
  1642. local uch dist_code[512];
  1643. /* distance codes. The first 256 values correspond to the distances
  1644. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  1645. * the 15 bit distances.
  1646. */
  1647. local uch length_code[MAX_MATCH-MIN_MATCH+1];
  1648. /* length code for each normalized match length (0 == MIN_MATCH) */
  1649. local int base_length[LENGTH_CODES];
  1650. /* First normalized length for each code (0 = MIN_MATCH) */
  1651. local int base_dist[D_CODES];
  1652. /* First normalized distance for each code (0 = distance of 1) */
  1653. struct static_tree_desc_s {
  1654. ct_data *static_tree; /* static tree or NULL */
  1655. intf *extra_bits; /* extra bits for each code or NULL */
  1656. int extra_base; /* base index for extra_bits */
  1657. int elems; /* max number of elements in the tree */
  1658. int max_length; /* max bit length for the codes */
  1659. };
  1660. local static_tree_desc static_l_desc =
  1661. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  1662. local static_tree_desc static_d_desc =
  1663. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  1664. local static_tree_desc static_bl_desc =
  1665. {(ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  1666. /* ===========================================================================
  1667. * Local (static) routines in this file.
  1668. */
  1669. local void tr_static_init OF((void));
  1670. local void init_block OF((deflate_state *s));
  1671. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  1672. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  1673. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  1674. local void build_tree OF((deflate_state *s, tree_desc *desc));
  1675. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  1676. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  1677. local int build_bl_tree OF((deflate_state *s));
  1678. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  1679. int blcodes));
  1680. local void compress_block OF((deflate_state *s, ct_data *ltree,
  1681. ct_data *dtree));
  1682. local void set_data_type OF((deflate_state *s));
  1683. local unsigned bi_reverse OF((unsigned value, int length));
  1684. local void bi_windup OF((deflate_state *s));
  1685. local void bi_flush OF((deflate_state *s));
  1686. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  1687. int header));
  1688. #ifndef DEBUG_ZLIB
  1689. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  1690. /* Send a code of the given tree. c and tree must not have side effects */
  1691. #else /* DEBUG_ZLIB */
  1692. # define send_code(s, c, tree) \
  1693. { if (verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  1694. send_bits(s, tree[c].Code, tree[c].Len); }
  1695. #endif
  1696. #define d_code(dist) \
  1697. ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  1698. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  1699. * must not have side effects. dist_code[256] and dist_code[257] are never
  1700. * used.
  1701. */
  1702. /* ===========================================================================
  1703. * Output a short LSB first on the stream.
  1704. * IN assertion: there is enough room in pendingBuf.
  1705. */
  1706. #define put_short(s, w) { \
  1707. put_byte(s, (uch)((w) & 0xff)); \
  1708. put_byte(s, (uch)((ush)(w) >> 8)); \
  1709. }
  1710. /* ===========================================================================
  1711. * Send a value on a given number of bits.
  1712. * IN assertion: length <= 16 and value fits in length bits.
  1713. */
  1714. #ifdef DEBUG_ZLIB
  1715. local void send_bits OF((deflate_state *s, int value, int length));
  1716. local void send_bits(s, value, length)
  1717. deflate_state *s;
  1718. int value; /* value to send */
  1719. int length; /* number of bits */
  1720. {
  1721. Tracevv((stderr," l %2d v %4x ", length, value));
  1722. Assert(length > 0 && length <= 15, "invalid length");
  1723. s->bits_sent += (ulg)length;
  1724. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  1725. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  1726. * unused bits in value.
  1727. */
  1728. if (s->bi_valid > (int)Buf_size - length) {
  1729. s->bi_buf |= (value << s->bi_valid);
  1730. put_short(s, s->bi_buf);
  1731. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  1732. s->bi_valid += length - Buf_size;
  1733. } else {
  1734. s->bi_buf |= value << s->bi_valid;
  1735. s->bi_valid += length;
  1736. }
  1737. }
  1738. #else /* !DEBUG_ZLIB */
  1739. #define send_bits(s, value, length) \
  1740. { int len = length;\
  1741. if (s->bi_valid > (int)Buf_size - len) {\
  1742. int val = value;\
  1743. s->bi_buf |= (val << s->bi_valid);\
  1744. put_short(s, s->bi_buf);\
  1745. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  1746. s->bi_valid += len - Buf_size;\
  1747. } else {\
  1748. s->bi_buf |= (value) << s->bi_valid;\
  1749. s->bi_valid += len;\
  1750. }\
  1751. }
  1752. #endif /* DEBUG_ZLIB */
  1753. #define MAX(a,b) (a >= b ? a : b)
  1754. /* the arguments must not have side effects */
  1755. /* ===========================================================================
  1756. * Initialize the various 'constant' tables. In a multi-threaded environment,
  1757. * this function may be called by two threads concurrently, but this is
  1758. * harmless since both invocations do exactly the same thing.
  1759. */
  1760. local void tr_static_init()
  1761. {
  1762. static int static_init_done = 0;
  1763. int n; /* iterates over tree elements */
  1764. int bits; /* bit counter */
  1765. int length; /* length value */
  1766. int code; /* code value */
  1767. int dist; /* distance index */
  1768. ush bl_count[MAX_BITS+1];
  1769. /* number of codes at each bit length for an optimal tree */
  1770. if (static_init_done) return;
  1771. /* Initialize the mapping length (0..255) -> length code (0..28) */
  1772. length = 0;
  1773. for (code = 0; code < LENGTH_CODES-1; code++) {
  1774. base_length[code] = length;
  1775. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  1776. length_code[length++] = (uch)code;
  1777. }
  1778. }
  1779. Assert (length == 256, "tr_static_init: length != 256");
  1780. /* Note that the length 255 (match length 258) can be represented
  1781. * in two different ways: code 284 + 5 bits or code 285, so we
  1782. * overwrite length_code[255] to use the best encoding:
  1783. */
  1784. length_code[length-1] = (uch)code;
  1785. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  1786. dist = 0;
  1787. for (code = 0 ; code < 16; code++) {
  1788. base_dist[code] = dist;
  1789. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  1790. dist_code[dist++] = (uch)code;
  1791. }
  1792. }
  1793. Assert (dist == 256, "tr_static_init: dist != 256");
  1794. dist >>= 7; /* from now on, all distances are divided by 128 */
  1795. for ( ; code < D_CODES; code++) {
  1796. base_dist[code] = dist << 7;
  1797. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  1798. dist_code[256 + dist++] = (uch)code;
  1799. }
  1800. }
  1801. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  1802. /* Construct the codes of the static literal tree */
  1803. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  1804. n = 0;
  1805. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  1806. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  1807. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  1808. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  1809. /* Codes 286 and 287 do not exist, but we must include them in the
  1810. * tree construction to get a canonical Huffman tree (longest code
  1811. * all ones)
  1812. */
  1813. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  1814. /* The static distance tree is trivial: */
  1815. for (n = 0; n < D_CODES; n++) {
  1816. static_dtree[n].Len = 5;
  1817. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  1818. }
  1819. static_init_done = 1;
  1820. }
  1821. /* ===========================================================================
  1822. * Initialize the tree data structures for a new zlib stream.
  1823. */
  1824. void _tr_init(s)
  1825. deflate_state *s;
  1826. {
  1827. tr_static_init();
  1828. s->compressed_len = 0L;
  1829. s->l_desc.dyn_tree = s->dyn_ltree;
  1830. s->l_desc.stat_desc = &static_l_desc;
  1831. s->d_desc.dyn_tree = s->dyn_dtree;
  1832. s->d_desc.stat_desc = &static_d_desc;
  1833. s->bl_desc.dyn_tree = s->bl_tree;
  1834. s->bl_desc.stat_desc = &static_bl_desc;
  1835. s->bi_buf = 0;
  1836. s->bi_valid = 0;
  1837. s->last_eob_len = 8; /* enough lookahead for inflate */
  1838. #ifdef DEBUG_ZLIB
  1839. s->bits_sent = 0L;
  1840. #endif
  1841. /* Initialize the first block of the first file: */
  1842. init_block(s);
  1843. }
  1844. /* ===========================================================================
  1845. * Initialize a new block.
  1846. */
  1847. local void init_block(s)
  1848. deflate_state *s;
  1849. {
  1850. int n; /* iterates over tree elements */
  1851. /* Initialize the trees. */
  1852. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  1853. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  1854. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  1855. s->dyn_ltree[END_BLOCK].Freq = 1;
  1856. s->opt_len = s->static_len = 0L;
  1857. s->last_lit = s->matches = 0;
  1858. }
  1859. #define SMALLEST 1
  1860. /* Index within the heap array of least frequent node in the Huffman tree */
  1861. /* ===========================================================================
  1862. * Remove the smallest element from the heap and recreate the heap with
  1863. * one less element. Updates heap and heap_len.
  1864. */
  1865. #define pqremove(s, tree, top) \
  1866. {\
  1867. top = s->heap[SMALLEST]; \
  1868. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  1869. pqdownheap(s, tree, SMALLEST); \
  1870. }
  1871. /* ===========================================================================
  1872. * Compares to subtrees, using the tree depth as tie breaker when
  1873. * the subtrees have equal frequency. This minimizes the worst case length.
  1874. */
  1875. #define smaller(tree, n, m, depth) \
  1876. (tree[n].Freq < tree[m].Freq || \
  1877. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  1878. /* ===========================================================================
  1879. * Restore the heap property by moving down the tree starting at node k,
  1880. * exchanging a node with the smallest of its two sons if necessary, stopping
  1881. * when the heap property is re-established (each father smaller than its
  1882. * two sons).
  1883. */
  1884. local void pqdownheap(s, tree, k)
  1885. deflate_state *s;
  1886. ct_data *tree; /* the tree to restore */
  1887. int k; /* node to move down */
  1888. {
  1889. int v = s->heap[k];
  1890. int j = k << 1; /* left son of k */
  1891. while (j <= s->heap_len) {
  1892. /* Set j to the smallest of the two sons: */
  1893. if (j < s->heap_len &&
  1894. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  1895. j++;
  1896. }
  1897. /* Exit if v is smaller than both sons */
  1898. if (smaller(tree, v, s->heap[j], s->depth)) break;
  1899. /* Exchange v with the smallest son */
  1900. s->heap[k] = s->heap[j]; k = j;
  1901. /* And continue down the tree, setting j to the left son of k */
  1902. j <<= 1;
  1903. }
  1904. s->heap[k] = v;
  1905. }
  1906. /* ===========================================================================
  1907. * Compute the optimal bit lengths for a tree and update the total bit length
  1908. * for the current block.
  1909. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  1910. * above are the tree nodes sorted by increasing frequency.
  1911. * OUT assertions: the field len is set to the optimal bit length, the
  1912. * array bl_count contains the frequencies for each bit length.
  1913. * The length opt_len is updated; static_len is also updated if stree is
  1914. * not null.
  1915. */
  1916. local void gen_bitlen(s, desc)
  1917. deflate_state *s;
  1918. tree_desc *desc; /* the tree descriptor */
  1919. {
  1920. ct_data *tree = desc->dyn_tree;
  1921. int max_code = desc->max_code;
  1922. ct_data *stree = desc->stat_desc->static_tree;
  1923. intf *extra = desc->stat_desc->extra_bits;
  1924. int base = desc->stat_desc->extra_base;
  1925. int max_length = desc->stat_desc->max_length;
  1926. int h; /* heap index */
  1927. int n, m; /* iterate over the tree elements */
  1928. int bits; /* bit length */
  1929. int xbits; /* extra bits */
  1930. ush f; /* frequency */
  1931. int overflow = 0; /* number of elements with bit length too large */
  1932. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  1933. /* In a first pass, compute the optimal bit lengths (which may
  1934. * overflow in the case of the bit length tree).
  1935. */
  1936. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  1937. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  1938. n = s->heap[h];
  1939. bits = tree[tree[n].Dad].Len + 1;
  1940. if (bits > max_length) bits = max_length, overflow++;
  1941. tree[n].Len = (ush)bits;
  1942. /* We overwrite tree[n].Dad which is no longer needed */
  1943. if (n > max_code) continue; /* not a leaf node */
  1944. s->bl_count[bits]++;
  1945. xbits = 0;
  1946. if (n >= base) xbits = extra[n-base];
  1947. f = tree[n].Freq;
  1948. s->opt_len += (ulg)f * (bits + xbits);
  1949. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  1950. }
  1951. if (overflow == 0) return;
  1952. Trace((stderr,"\nbit length overflow\n"));
  1953. /* This happens for example on obj2 and pic of the Calgary corpus */
  1954. /* Find the first bit length which could increase: */
  1955. do {
  1956. bits = max_length-1;
  1957. while (s->bl_count[bits] == 0) bits--;
  1958. s->bl_count[bits]--; /* move one leaf down the tree */
  1959. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  1960. s->bl_count[max_length]--;
  1961. /* The brother of the overflow item also moves one step up,
  1962. * but this does not affect bl_count[max_length]
  1963. */
  1964. overflow -= 2;
  1965. } while (overflow > 0);
  1966. /* Now recompute all bit lengths, scanning in increasing frequency.
  1967. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  1968. * lengths instead of fixing only the wrong ones. This idea is taken
  1969. * from 'ar' written by Haruhiko Okumura.)
  1970. */
  1971. for (bits = max_length; bits != 0; bits--) {
  1972. n = s->bl_count[bits];
  1973. while (n != 0) {
  1974. m = s->heap[--h];
  1975. if (m > max_code) continue;
  1976. if (tree[m].Len != (unsigned) bits) {
  1977. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  1978. s->opt_len += ((long)bits - (long)tree[m].Len)
  1979. *(long)tree[m].Freq;
  1980. tree[m].Len = (ush)bits;
  1981. }
  1982. n--;
  1983. }
  1984. }
  1985. }
  1986. /* ===========================================================================
  1987. * Generate the codes for a given tree and bit counts (which need not be
  1988. * optimal).
  1989. * IN assertion: the array bl_count contains the bit length statistics for
  1990. * the given tree and the field len is set for all tree elements.
  1991. * OUT assertion: the field code is set for all tree elements of non
  1992. * zero code length.
  1993. */
  1994. local void gen_codes (tree, max_code, bl_count)
  1995. ct_data *tree; /* the tree to decorate */
  1996. int max_code; /* largest code with non zero frequency */
  1997. ushf *bl_count; /* number of codes at each bit length */
  1998. {
  1999. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  2000. ush code = 0; /* running code value */
  2001. int bits; /* bit index */
  2002. int n; /* code index */
  2003. /* The distribution counts are first used to generate the code values
  2004. * without bit reversal.
  2005. */
  2006. for (bits = 1; bits <= MAX_BITS; bits++) {
  2007. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  2008. }
  2009. /* Check that the bit counts in bl_count are consistent. The last code
  2010. * must be all ones.
  2011. */
  2012. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  2013. "inconsistent bit counts");
  2014. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  2015. for (n = 0; n <= max_code; n++) {
  2016. int len = tree[n].Len;
  2017. if (len == 0) continue;
  2018. /* Now reverse the bits */
  2019. tree[n].Code = bi_reverse(next_code[len]++, len);
  2020. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  2021. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  2022. }
  2023. }
  2024. /* ===========================================================================
  2025. * Construct one Huffman tree and assigns the code bit strings and lengths.
  2026. * Update the total bit length for the current block.
  2027. * IN assertion: the field freq is set for all tree elements.
  2028. * OUT assertions: the fields len and code are set to the optimal bit length
  2029. * and corresponding code. The length opt_len is updated; static_len is
  2030. * also updated if stree is not null. The field max_code is set.
  2031. */
  2032. local void build_tree(s, desc)
  2033. deflate_state *s;
  2034. tree_desc *desc; /* the tree descriptor */
  2035. {
  2036. ct_data *tree = desc->dyn_tree;
  2037. ct_data *stree = desc->stat_desc->static_tree;
  2038. int elems = desc->stat_desc->elems;
  2039. int n, m; /* iterate over heap elements */
  2040. int max_code = -1; /* largest code with non zero frequency */
  2041. int node; /* new node being created */
  2042. /* Construct the initial heap, with least frequent element in
  2043. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  2044. * heap[0] is not used.
  2045. */
  2046. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  2047. for (n = 0; n < elems; n++) {
  2048. if (tree[n].Freq != 0) {
  2049. s->heap[++(s->heap_len)] = max_code = n;
  2050. s->depth[n] = 0;
  2051. } else {
  2052. tree[n].Len = 0;
  2053. }
  2054. }
  2055. /* The pkzip format requires that at least one distance code exists,
  2056. * and that at least one bit should be sent even if there is only one
  2057. * possible code. So to avoid special checks later on we force at least
  2058. * two codes of non zero frequency.
  2059. */
  2060. while (s->heap_len < 2) {
  2061. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  2062. tree[node].Freq = 1;
  2063. s->depth[node] = 0;
  2064. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  2065. /* node is 0 or 1 so it does not have extra bits */
  2066. }
  2067. desc->max_code = max_code;
  2068. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  2069. * establish sub-heaps of increasing lengths:
  2070. */
  2071. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  2072. /* Construct the Huffman tree by repeatedly combining the least two
  2073. * frequent nodes.
  2074. */
  2075. node = elems; /* next internal node of the tree */
  2076. do {
  2077. pqremove(s, tree, n); /* n = node of least frequency */
  2078. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  2079. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  2080. s->heap[--(s->heap_max)] = m;
  2081. /* Create a new node father of n and m */
  2082. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  2083. s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
  2084. tree[n].Dad = tree[m].Dad = (ush)node;
  2085. #ifdef DUMP_BL_TREE
  2086. if (tree == s->bl_tree) {
  2087. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  2088. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  2089. }
  2090. #endif
  2091. /* and insert the new node in the heap */
  2092. s->heap[SMALLEST] = node++;
  2093. pqdownheap(s, tree, SMALLEST);
  2094. } while (s->heap_len >= 2);
  2095. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  2096. /* At this point, the fields freq and dad are set. We can now
  2097. * generate the bit lengths.
  2098. */
  2099. gen_bitlen(s, (tree_desc *)desc);
  2100. /* The field len is now set, we can generate the bit codes */
  2101. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  2102. }
  2103. /* ===========================================================================
  2104. * Scan a literal or distance tree to determine the frequencies of the codes
  2105. * in the bit length tree.
  2106. */
  2107. local void scan_tree (s, tree, max_code)
  2108. deflate_state *s;
  2109. ct_data *tree; /* the tree to be scanned */
  2110. int max_code; /* and its largest code of non zero frequency */
  2111. {
  2112. int n; /* iterates over all tree elements */
  2113. int prevlen = -1; /* last emitted length */
  2114. int curlen; /* length of current code */
  2115. int nextlen = tree[0].Len; /* length of next code */
  2116. int count = 0; /* repeat count of the current code */
  2117. int max_count = 7; /* max repeat count */
  2118. int min_count = 4; /* min repeat count */
  2119. if (nextlen == 0) max_count = 138, min_count = 3;
  2120. tree[max_code+1].Len = (ush)0xffff; /* guard */
  2121. for (n = 0; n <= max_code; n++) {
  2122. curlen = nextlen; nextlen = tree[n+1].Len;
  2123. if (++count < max_count && curlen == nextlen) {
  2124. continue;
  2125. } else if (count < min_count) {
  2126. s->bl_tree[curlen].Freq += count;
  2127. } else if (curlen != 0) {
  2128. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  2129. s->bl_tree[REP_3_6].Freq++;
  2130. } else if (count <= 10) {
  2131. s->bl_tree[REPZ_3_10].Freq++;
  2132. } else {
  2133. s->bl_tree[REPZ_11_138].Freq++;
  2134. }
  2135. count = 0; prevlen = curlen;
  2136. if (nextlen == 0) {
  2137. max_count = 138, min_count = 3;
  2138. } else if (curlen == nextlen) {
  2139. max_count = 6, min_count = 3;
  2140. } else {
  2141. max_count = 7, min_count = 4;
  2142. }
  2143. }
  2144. }
  2145. /* ===========================================================================
  2146. * Send a literal or distance tree in compressed form, using the codes in
  2147. * bl_tree.
  2148. */
  2149. local void send_tree (s, tree, max_code)
  2150. deflate_state *s;
  2151. ct_data *tree; /* the tree to be scanned */
  2152. int max_code; /* and its largest code of non zero frequency */
  2153. {
  2154. int n; /* iterates over all tree elements */
  2155. int prevlen = -1; /* last emitted length */
  2156. int curlen; /* length of current code */
  2157. int nextlen = tree[0].Len; /* length of next code */
  2158. int count = 0; /* repeat count of the current code */
  2159. int max_count = 7; /* max repeat count */
  2160. int min_count = 4; /* min repeat count */
  2161. /* tree[max_code+1].Len = -1; */ /* guard already set */
  2162. if (nextlen == 0) max_count = 138, min_count = 3;
  2163. for (n = 0; n <= max_code; n++) {
  2164. curlen = nextlen; nextlen = tree[n+1].Len;
  2165. if (++count < max_count && curlen == nextlen) {
  2166. continue;
  2167. } else if (count < min_count) {
  2168. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  2169. } else if (curlen != 0) {
  2170. if (curlen != prevlen) {
  2171. send_code(s, curlen, s->bl_tree); count--;
  2172. }
  2173. Assert(count >= 3 && count <= 6, " 3_6?");
  2174. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  2175. } else if (count <= 10) {
  2176. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  2177. } else {
  2178. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  2179. }
  2180. count = 0; prevlen = curlen;
  2181. if (nextlen == 0) {
  2182. max_count = 138, min_count = 3;
  2183. } else if (curlen == nextlen) {
  2184. max_count = 6, min_count = 3;
  2185. } else {
  2186. max_count = 7, min_count = 4;
  2187. }
  2188. }
  2189. }
  2190. /* ===========================================================================
  2191. * Construct the Huffman tree for the bit lengths and return the index in
  2192. * bl_order of the last bit length code to send.
  2193. */
  2194. local int build_bl_tree(s)
  2195. deflate_state *s;
  2196. {
  2197. int max_blindex; /* index of last bit length code of non zero freq */
  2198. /* Determine the bit length frequencies for literal and distance trees */
  2199. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  2200. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  2201. /* Build the bit length tree: */
  2202. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  2203. /* opt_len now includes the length of the tree representations, except
  2204. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  2205. */
  2206. /* Determine the number of bit length codes to send. The pkzip format
  2207. * requires that at least 4 bit length codes be sent. (appnote.txt says
  2208. * 3 but the actual value used is 4.)
  2209. */
  2210. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  2211. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  2212. }
  2213. /* Update opt_len to include the bit length tree and counts */
  2214. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  2215. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  2216. s->opt_len, s->static_len));
  2217. return max_blindex;
  2218. }
  2219. /* ===========================================================================
  2220. * Send the header for a block using dynamic Huffman trees: the counts, the
  2221. * lengths of the bit length codes, the literal tree and the distance tree.
  2222. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  2223. */
  2224. local void send_all_trees(s, lcodes, dcodes, blcodes)
  2225. deflate_state *s;
  2226. int lcodes, dcodes, blcodes; /* number of codes for each tree */
  2227. {
  2228. int rank; /* index in bl_order */
  2229. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  2230. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  2231. "too many codes");
  2232. Tracev((stderr, "\nbl counts: "));
  2233. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  2234. send_bits(s, dcodes-1, 5);
  2235. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  2236. for (rank = 0; rank < blcodes; rank++) {
  2237. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  2238. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  2239. }
  2240. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  2241. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  2242. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  2243. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  2244. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  2245. }
  2246. /* ===========================================================================
  2247. * Send a stored block
  2248. */
  2249. void _tr_stored_block(s, buf, stored_len, eof)
  2250. deflate_state *s;
  2251. charf *buf; /* input block */
  2252. ulg stored_len; /* length of input block */
  2253. int eof; /* true if this is the last block for a file */
  2254. {
  2255. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  2256. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  2257. s->compressed_len += (stored_len + 4) << 3;
  2258. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  2259. }
  2260. /* Send just the `stored block' type code without any length bytes or data.
  2261. */
  2262. void _tr_stored_type_only(s)
  2263. deflate_state *s;
  2264. {
  2265. send_bits(s, (STORED_BLOCK << 1), 3);
  2266. bi_windup(s);
  2267. s->compressed_len = (s->compressed_len + 3) & ~7L;
  2268. }
  2269. /* ===========================================================================
  2270. * Send one empty static block to give enough lookahead for inflate.
  2271. * This takes 10 bits, of which 7 may remain in the bit buffer.
  2272. * The current inflate code requires 9 bits of lookahead. If the
  2273. * last two codes for the previous block (real code plus EOB) were coded
  2274. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  2275. * the last real code. In this case we send two empty static blocks instead
  2276. * of one. (There are no problems if the previous block is stored or fixed.)
  2277. * To simplify the code, we assume the worst case of last real code encoded
  2278. * on one bit only.
  2279. */
  2280. void _tr_align(s)
  2281. deflate_state *s;
  2282. {
  2283. send_bits(s, STATIC_TREES<<1, 3);
  2284. send_code(s, END_BLOCK, static_ltree);
  2285. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  2286. bi_flush(s);
  2287. /* Of the 10 bits for the empty block, we have already sent
  2288. * (10 - bi_valid) bits. The lookahead for the last real code (before
  2289. * the EOB of the previous block) was thus at least one plus the length
  2290. * of the EOB plus what we have just sent of the empty static block.
  2291. */
  2292. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  2293. send_bits(s, STATIC_TREES<<1, 3);
  2294. send_code(s, END_BLOCK, static_ltree);
  2295. s->compressed_len += 10L;
  2296. bi_flush(s);
  2297. }
  2298. s->last_eob_len = 7;
  2299. }
  2300. /* ===========================================================================
  2301. * Determine the best encoding for the current block: dynamic trees, static
  2302. * trees or store, and output the encoded block to the zip file. This function
  2303. * returns the total compressed length for the file so far.
  2304. */
  2305. ulg _tr_flush_block(s, buf, stored_len, eof)
  2306. deflate_state *s;
  2307. charf *buf; /* input block, or NULL if too old */
  2308. ulg stored_len; /* length of input block */
  2309. int eof; /* true if this is the last block for a file */
  2310. {
  2311. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  2312. int max_blindex = 0; /* index of last bit length code of non zero freq */
  2313. /* Build the Huffman trees unless a stored block is forced */
  2314. if (s->level > 0) {
  2315. /* Check if the file is ascii or binary */
  2316. if (s->data_type == Z_UNKNOWN) set_data_type(s);
  2317. /* Construct the literal and distance trees */
  2318. build_tree(s, (tree_desc *)(&(s->l_desc)));
  2319. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  2320. s->static_len));
  2321. build_tree(s, (tree_desc *)(&(s->d_desc)));
  2322. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  2323. s->static_len));
  2324. /* At this point, opt_len and static_len are the total bit lengths of
  2325. * the compressed block data, excluding the tree representations.
  2326. */
  2327. /* Build the bit length tree for the above two trees, and get the index
  2328. * in bl_order of the last bit length code to send.
  2329. */
  2330. max_blindex = build_bl_tree(s);
  2331. /* Determine the best encoding. Compute first the block length in bytes*/
  2332. opt_lenb = (s->opt_len+3+7)>>3;
  2333. static_lenb = (s->static_len+3+7)>>3;
  2334. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  2335. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  2336. s->last_lit));
  2337. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  2338. } else {
  2339. Assert(buf != (char*)0, "lost buf");
  2340. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  2341. }
  2342. /* If compression failed and this is the first and last block,
  2343. * and if the .zip file can be seeked (to rewrite the local header),
  2344. * the whole file is transformed into a stored file:
  2345. */
  2346. #ifdef STORED_FILE_OK
  2347. # ifdef FORCE_STORED_FILE
  2348. if (eof && s->compressed_len == 0L) { /* force stored file */
  2349. # else
  2350. if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable()) {
  2351. # endif
  2352. /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  2353. if (buf == (charf*)0) error ("block vanished");
  2354. copy_block(s, buf, (unsigned)stored_len, 0); /* without header */
  2355. s->compressed_len = stored_len << 3;
  2356. s->method = STORED;
  2357. } else
  2358. #endif /* STORED_FILE_OK */
  2359. #ifdef FORCE_STORED
  2360. if (buf != (char*)0) { /* force stored block */
  2361. #else
  2362. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  2363. /* 4: two words for the lengths */
  2364. #endif
  2365. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  2366. * Otherwise we can't have processed more than WSIZE input bytes since
  2367. * the last block flush, because compression would have been
  2368. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  2369. * transform a block into a stored block.
  2370. */
  2371. _tr_stored_block(s, buf, stored_len, eof);
  2372. #ifdef FORCE_STATIC
  2373. } else if (static_lenb >= 0) { /* force static trees */
  2374. #else
  2375. } else if (static_lenb == opt_lenb) {
  2376. #endif
  2377. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  2378. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  2379. s->compressed_len += 3 + s->static_len;
  2380. } else {
  2381. send_bits(s, (DYN_TREES<<1)+eof, 3);
  2382. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  2383. max_blindex+1);
  2384. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  2385. s->compressed_len += 3 + s->opt_len;
  2386. }
  2387. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  2388. init_block(s);
  2389. if (eof) {
  2390. bi_windup(s);
  2391. s->compressed_len += 7; /* align on byte boundary */
  2392. }
  2393. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  2394. s->compressed_len-7*eof));
  2395. return s->compressed_len >> 3;
  2396. }
  2397. /* ===========================================================================
  2398. * Save the match info and tally the frequency counts. Return true if
  2399. * the current block must be flushed.
  2400. */
  2401. int _tr_tally (s, dist, lc)
  2402. deflate_state *s;
  2403. unsigned dist; /* distance of matched string */
  2404. unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  2405. {
  2406. s->d_buf[s->last_lit] = (ush)dist;
  2407. s->l_buf[s->last_lit++] = (uch)lc;
  2408. if (dist == 0) {
  2409. /* lc is the unmatched char */
  2410. s->dyn_ltree[lc].Freq++;
  2411. } else {
  2412. s->matches++;
  2413. /* Here, lc is the match length - MIN_MATCH */
  2414. dist--; /* dist = match distance - 1 */
  2415. Assert((ush)dist < (ush)MAX_DIST(s) &&
  2416. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  2417. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  2418. s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
  2419. s->dyn_dtree[d_code(dist)].Freq++;
  2420. }
  2421. /* Try to guess if it is profitable to stop the current block here */
  2422. if (s->level > 2 && (s->last_lit & 0xfff) == 0) {
  2423. /* Compute an upper bound for the compressed length */
  2424. ulg out_length = (ulg)s->last_lit*8L;
  2425. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  2426. int dcode;
  2427. for (dcode = 0; dcode < D_CODES; dcode++) {
  2428. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  2429. (5L+extra_dbits[dcode]);
  2430. }
  2431. out_length >>= 3;
  2432. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  2433. s->last_lit, in_length, out_length,
  2434. 100L - out_length*100L/in_length));
  2435. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  2436. }
  2437. return (s->last_lit == s->lit_bufsize-1);
  2438. /* We avoid equality with lit_bufsize because of wraparound at 64K
  2439. * on 16 bit machines and because stored blocks are restricted to
  2440. * 64K-1 bytes.
  2441. */
  2442. }
  2443. /* ===========================================================================
  2444. * Send the block data compressed using the given Huffman trees
  2445. */
  2446. local void compress_block(s, ltree, dtree)
  2447. deflate_state *s;
  2448. ct_data *ltree; /* literal tree */
  2449. ct_data *dtree; /* distance tree */
  2450. {
  2451. unsigned dist; /* distance of matched string */
  2452. int lc; /* match length or unmatched char (if dist == 0) */
  2453. unsigned lx = 0; /* running index in l_buf */
  2454. unsigned code; /* the code to send */
  2455. int extra; /* number of extra bits to send */
  2456. if (s->last_lit != 0) do {
  2457. dist = s->d_buf[lx];
  2458. lc = s->l_buf[lx++];
  2459. if (dist == 0) {
  2460. send_code(s, lc, ltree); /* send a literal byte */
  2461. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  2462. } else {
  2463. /* Here, lc is the match length - MIN_MATCH */
  2464. code = length_code[lc];
  2465. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  2466. extra = extra_lbits[code];
  2467. if (extra != 0) {
  2468. lc -= base_length[code];
  2469. send_bits(s, lc, extra); /* send the extra length bits */
  2470. }
  2471. dist--; /* dist is now the match distance - 1 */
  2472. code = d_code(dist);
  2473. Assert (code < D_CODES, "bad d_code");
  2474. send_code(s, code, dtree); /* send the distance code */
  2475. extra = extra_dbits[code];
  2476. if (extra != 0) {
  2477. dist -= base_dist[code];
  2478. send_bits(s, dist, extra); /* send the extra distance bits */
  2479. }
  2480. } /* literal or match pair ? */
  2481. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  2482. Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
  2483. } while (lx < s->last_lit);
  2484. send_code(s, END_BLOCK, ltree);
  2485. s->last_eob_len = ltree[END_BLOCK].Len;
  2486. }
  2487. /* ===========================================================================
  2488. * Set the data type to ASCII or BINARY, using a crude approximation:
  2489. * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  2490. * IN assertion: the fields freq of dyn_ltree are set and the total of all
  2491. * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  2492. */
  2493. local void set_data_type(s)
  2494. deflate_state *s;
  2495. {
  2496. int n = 0;
  2497. unsigned ascii_freq = 0;
  2498. unsigned bin_freq = 0;
  2499. while (n < 7) bin_freq += s->dyn_ltree[n++].Freq;
  2500. while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq;
  2501. while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
  2502. s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
  2503. }
  2504. /* ===========================================================================
  2505. * Reverse the first len bits of a code, using straightforward code (a faster
  2506. * method would use a table)
  2507. * IN assertion: 1 <= len <= 15
  2508. */
  2509. local unsigned bi_reverse(code, len)
  2510. unsigned code; /* the value to invert */
  2511. int len; /* its bit length */
  2512. {
  2513. register unsigned res = 0;
  2514. do {
  2515. res |= code & 1;
  2516. code >>= 1, res <<= 1;
  2517. } while (--len > 0);
  2518. return res >> 1;
  2519. }
  2520. /* ===========================================================================
  2521. * Flush the bit buffer, keeping at most 7 bits in it.
  2522. */
  2523. local void bi_flush(s)
  2524. deflate_state *s;
  2525. {
  2526. if (s->bi_valid == 16) {
  2527. put_short(s, s->bi_buf);
  2528. s->bi_buf = 0;
  2529. s->bi_valid = 0;
  2530. } else if (s->bi_valid >= 8) {
  2531. put_byte(s, (Byte)s->bi_buf);
  2532. s->bi_buf >>= 8;
  2533. s->bi_valid -= 8;
  2534. }
  2535. }
  2536. /* ===========================================================================
  2537. * Flush the bit buffer and align the output on a byte boundary
  2538. */
  2539. local void bi_windup(s)
  2540. deflate_state *s;
  2541. {
  2542. if (s->bi_valid > 8) {
  2543. put_short(s, s->bi_buf);
  2544. } else if (s->bi_valid > 0) {
  2545. put_byte(s, (Byte)s->bi_buf);
  2546. }
  2547. s->bi_buf = 0;
  2548. s->bi_valid = 0;
  2549. #ifdef DEBUG_ZLIB
  2550. s->bits_sent = (s->bits_sent+7) & ~7;
  2551. #endif
  2552. }
  2553. /* ===========================================================================
  2554. * Copy a stored block, storing first the length and its
  2555. * one's complement if requested.
  2556. */
  2557. local void copy_block(s, buf, len, header)
  2558. deflate_state *s;
  2559. charf *buf; /* the input data */
  2560. unsigned len; /* its length */
  2561. int header; /* true if block header must be written */
  2562. {
  2563. bi_windup(s); /* align on byte boundary */
  2564. s->last_eob_len = 8; /* enough lookahead for inflate */
  2565. if (header) {
  2566. put_short(s, (ush)len);
  2567. put_short(s, (ush)~len);
  2568. #ifdef DEBUG_ZLIB
  2569. s->bits_sent += 2*16;
  2570. #endif
  2571. }
  2572. #ifdef DEBUG_ZLIB
  2573. s->bits_sent += (ulg)len<<3;
  2574. #endif
  2575. /* bundle up the put_byte(s, *buf++) calls */
  2576. zmemcpy(&s->pending_buf[s->pending], buf, len);
  2577. s->pending += len;
  2578. }
  2579. /* --- trees.c */
  2580. /* +++ inflate.c */
  2581. /* inflate.c -- zlib interface to inflate modules
  2582. * Copyright (C) 1995-1996 Mark Adler
  2583. * For conditions of distribution and use, see copyright notice in zlib.h
  2584. */
  2585. /* #include "zutil.h" */
  2586. /* +++ infblock.h */
  2587. /* infblock.h -- header to use infblock.c
  2588. * Copyright (C) 1995-1996 Mark Adler
  2589. * For conditions of distribution and use, see copyright notice in zlib.h
  2590. */
  2591. /* WARNING: this file should *not* be used by applications. It is
  2592. part of the implementation of the compression library and is
  2593. subject to change. Applications should only use zlib.h.
  2594. */
  2595. struct inflate_blocks_state;
  2596. typedef struct inflate_blocks_state FAR inflate_blocks_statef;
  2597. extern inflate_blocks_statef * inflate_blocks_new OF((
  2598. z_streamp z,
  2599. check_func c, /* check function */
  2600. uInt w)); /* window size */
  2601. extern int inflate_blocks OF((
  2602. inflate_blocks_statef *,
  2603. z_streamp ,
  2604. int)); /* initial return code */
  2605. extern void inflate_blocks_reset OF((
  2606. inflate_blocks_statef *,
  2607. z_streamp ,
  2608. uLongf *)); /* check value on output */
  2609. extern int inflate_blocks_free OF((
  2610. inflate_blocks_statef *,
  2611. z_streamp ,
  2612. uLongf *)); /* check value on output */
  2613. extern void inflate_set_dictionary OF((
  2614. inflate_blocks_statef *s,
  2615. const Bytef *d, /* dictionary */
  2616. uInt n)); /* dictionary length */
  2617. extern int inflate_addhistory OF((
  2618. inflate_blocks_statef *,
  2619. z_streamp));
  2620. extern int inflate_packet_flush OF((
  2621. inflate_blocks_statef *));
  2622. /* --- infblock.h */
  2623. #ifndef NO_DUMMY_DECL
  2624. struct inflate_blocks_state {int dummy;}; /* for buggy compilers */
  2625. #endif
  2626. /* inflate private state */
  2627. struct internal_state {
  2628. /* mode */
  2629. enum {
  2630. METHOD, /* waiting for method byte */
  2631. FLAG, /* waiting for flag byte */
  2632. DICT4, /* four dictionary check bytes to go */
  2633. DICT3, /* three dictionary check bytes to go */
  2634. DICT2, /* two dictionary check bytes to go */
  2635. DICT1, /* one dictionary check byte to go */
  2636. DICT0, /* waiting for inflateSetDictionary */
  2637. BLOCKS, /* decompressing blocks */
  2638. CHECK4, /* four check bytes to go */
  2639. CHECK3, /* three check bytes to go */
  2640. CHECK2, /* two check bytes to go */
  2641. CHECK1, /* one check byte to go */
  2642. DONE, /* finished check, done */
  2643. BAD} /* got an error--stay here */
  2644. mode; /* current inflate mode */
  2645. /* mode dependent information */
  2646. union {
  2647. uInt method; /* if FLAGS, method byte */
  2648. struct {
  2649. uLong was; /* computed check value */
  2650. uLong need; /* stream check value */
  2651. } check; /* if CHECK, check values to compare */
  2652. uInt marker; /* if BAD, inflateSync's marker bytes count */
  2653. } sub; /* submode */
  2654. /* mode independent information */
  2655. int nowrap; /* flag for no wrapper */
  2656. uInt wbits; /* log2(window size) (8..15, defaults to 15) */
  2657. inflate_blocks_statef
  2658. *blocks; /* current inflate_blocks state */
  2659. };
  2660. int inflateReset(z)
  2661. z_streamp z;
  2662. {
  2663. uLong c;
  2664. if (z == Z_NULL || z->state == Z_NULL)
  2665. return Z_STREAM_ERROR;
  2666. z->total_in = z->total_out = 0;
  2667. z->msg = Z_NULL;
  2668. z->state->mode = z->state->nowrap ? BLOCKS : METHOD;
  2669. inflate_blocks_reset(z->state->blocks, z, &c);
  2670. Trace((stderr, "inflate: reset\n"));
  2671. return Z_OK;
  2672. }
  2673. int inflateEnd(z)
  2674. z_streamp z;
  2675. {
  2676. uLong c;
  2677. if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
  2678. return Z_STREAM_ERROR;
  2679. if (z->state->blocks != Z_NULL)
  2680. inflate_blocks_free(z->state->blocks, z, &c);
  2681. ZFREE(z, z->state);
  2682. z->state = Z_NULL;
  2683. Trace((stderr, "inflate: end\n"));
  2684. return Z_OK;
  2685. }
  2686. int inflateInit2_(z, w, version, stream_size)
  2687. z_streamp z;
  2688. int w;
  2689. const char *version;
  2690. int stream_size;
  2691. {
  2692. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  2693. stream_size != sizeof(z_stream))
  2694. return Z_VERSION_ERROR;
  2695. /* initialize state */
  2696. if (z == Z_NULL)
  2697. return Z_STREAM_ERROR;
  2698. z->msg = Z_NULL;
  2699. #ifndef NO_ZCFUNCS
  2700. if (z->zalloc == Z_NULL)
  2701. {
  2702. z->zalloc = zcalloc;
  2703. z->opaque = (voidpf)0;
  2704. }
  2705. if (z->zfree == Z_NULL) z->zfree = zcfree;
  2706. #endif
  2707. if ((z->state = (struct internal_state FAR *)
  2708. ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
  2709. return Z_MEM_ERROR;
  2710. z->state->blocks = Z_NULL;
  2711. /* handle undocumented nowrap option (no zlib header or check) */
  2712. z->state->nowrap = 0;
  2713. if (w < 0)
  2714. {
  2715. w = - w;
  2716. z->state->nowrap = 1;
  2717. }
  2718. /* set window size */
  2719. if (w < 8 || w > 15)
  2720. {
  2721. inflateEnd(z);
  2722. return Z_STREAM_ERROR;
  2723. }
  2724. z->state->wbits = (uInt)w;
  2725. /* create inflate_blocks state */
  2726. if ((z->state->blocks =
  2727. inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
  2728. == Z_NULL)
  2729. {
  2730. inflateEnd(z);
  2731. return Z_MEM_ERROR;
  2732. }
  2733. Trace((stderr, "inflate: allocated\n"));
  2734. /* reset state */
  2735. inflateReset(z);
  2736. return Z_OK;
  2737. }
  2738. int inflateInit_(z, version, stream_size)
  2739. z_streamp z;
  2740. const char *version;
  2741. int stream_size;
  2742. {
  2743. return inflateInit2_(z, DEF_WBITS, version, stream_size);
  2744. }
  2745. #define NEEDBYTE {if(z->avail_in==0)goto empty;r=Z_OK;}
  2746. #define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
  2747. int inflate(z, f)
  2748. z_streamp z;
  2749. int f;
  2750. {
  2751. int r;
  2752. uInt b;
  2753. if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL || f < 0)
  2754. return Z_STREAM_ERROR;
  2755. r = Z_BUF_ERROR;
  2756. while (1) switch (z->state->mode)
  2757. {
  2758. case METHOD:
  2759. NEEDBYTE
  2760. if (((z->state->sub.method = NEXTBYTE) & 0xf) != Z_DEFLATED)
  2761. {
  2762. z->state->mode = BAD;
  2763. z->msg = (char*)"unknown compression method";
  2764. z->state->sub.marker = 5; /* can't try inflateSync */
  2765. break;
  2766. }
  2767. if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
  2768. {
  2769. z->state->mode = BAD;
  2770. z->msg = (char*)"invalid window size";
  2771. z->state->sub.marker = 5; /* can't try inflateSync */
  2772. break;
  2773. }
  2774. z->state->mode = FLAG;
  2775. case FLAG:
  2776. NEEDBYTE
  2777. b = NEXTBYTE;
  2778. if (((z->state->sub.method << 8) + b) % 31)
  2779. {
  2780. z->state->mode = BAD;
  2781. z->msg = (char*)"incorrect header check";
  2782. z->state->sub.marker = 5; /* can't try inflateSync */
  2783. break;
  2784. }
  2785. Trace((stderr, "inflate: zlib header ok\n"));
  2786. if (!(b & PRESET_DICT))
  2787. {
  2788. z->state->mode = BLOCKS;
  2789. break;
  2790. }
  2791. z->state->mode = DICT4;
  2792. case DICT4:
  2793. NEEDBYTE
  2794. z->state->sub.check.need = (uLong)NEXTBYTE << 24;
  2795. z->state->mode = DICT3;
  2796. case DICT3:
  2797. NEEDBYTE
  2798. z->state->sub.check.need += (uLong)NEXTBYTE << 16;
  2799. z->state->mode = DICT2;
  2800. case DICT2:
  2801. NEEDBYTE
  2802. z->state->sub.check.need += (uLong)NEXTBYTE << 8;
  2803. z->state->mode = DICT1;
  2804. case DICT1:
  2805. NEEDBYTE
  2806. z->state->sub.check.need += (uLong)NEXTBYTE;
  2807. z->adler = z->state->sub.check.need;
  2808. z->state->mode = DICT0;
  2809. return Z_NEED_DICT;
  2810. case DICT0:
  2811. z->state->mode = BAD;
  2812. z->msg = (char*)"need dictionary";
  2813. z->state->sub.marker = 0; /* can try inflateSync */
  2814. return Z_STREAM_ERROR;
  2815. case BLOCKS:
  2816. r = inflate_blocks(z->state->blocks, z, r);
  2817. if (f == Z_PACKET_FLUSH && z->avail_in == 0 && z->avail_out != 0)
  2818. r = inflate_packet_flush(z->state->blocks);
  2819. if (r == Z_DATA_ERROR)
  2820. {
  2821. z->state->mode = BAD;
  2822. z->state->sub.marker = 0; /* can try inflateSync */
  2823. break;
  2824. }
  2825. if (r != Z_STREAM_END)
  2826. return r;
  2827. r = Z_OK;
  2828. inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
  2829. if (z->state->nowrap)
  2830. {
  2831. z->state->mode = DONE;
  2832. break;
  2833. }
  2834. z->state->mode = CHECK4;
  2835. case CHECK4:
  2836. NEEDBYTE
  2837. z->state->sub.check.need = (uLong)NEXTBYTE << 24;
  2838. z->state->mode = CHECK3;
  2839. case CHECK3:
  2840. NEEDBYTE
  2841. z->state->sub.check.need += (uLong)NEXTBYTE << 16;
  2842. z->state->mode = CHECK2;
  2843. case CHECK2:
  2844. NEEDBYTE
  2845. z->state->sub.check.need += (uLong)NEXTBYTE << 8;
  2846. z->state->mode = CHECK1;
  2847. case CHECK1:
  2848. NEEDBYTE
  2849. z->state->sub.check.need += (uLong)NEXTBYTE;
  2850. if (z->state->sub.check.was != z->state->sub.check.need)
  2851. {
  2852. z->state->mode = BAD;
  2853. z->msg = (char*)"incorrect data check";
  2854. z->state->sub.marker = 5; /* can't try inflateSync */
  2855. break;
  2856. }
  2857. Trace((stderr, "inflate: zlib check ok\n"));
  2858. z->state->mode = DONE;
  2859. case DONE:
  2860. return Z_STREAM_END;
  2861. case BAD:
  2862. return Z_DATA_ERROR;
  2863. default:
  2864. return Z_STREAM_ERROR;
  2865. }
  2866. empty:
  2867. if (f != Z_PACKET_FLUSH)
  2868. return r;
  2869. z->state->mode = BAD;
  2870. z->msg = (char *)"need more for packet flush";
  2871. z->state->sub.marker = 0; /* can try inflateSync */
  2872. return Z_DATA_ERROR;
  2873. }
  2874. int inflateSetDictionary(z, dictionary, dictLength)
  2875. z_streamp z;
  2876. const Bytef *dictionary;
  2877. uInt dictLength;
  2878. {
  2879. uInt length = dictLength;
  2880. if (z == Z_NULL || z->state == Z_NULL || z->state->mode != DICT0)
  2881. return Z_STREAM_ERROR;
  2882. if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR;
  2883. z->adler = 1L;
  2884. if (length >= ((uInt)1<<z->state->wbits))
  2885. {
  2886. length = (1<<z->state->wbits)-1;
  2887. dictionary += dictLength - length;
  2888. }
  2889. inflate_set_dictionary(z->state->blocks, dictionary, length);
  2890. z->state->mode = BLOCKS;
  2891. return Z_OK;
  2892. }
  2893. /*
  2894. * This subroutine adds the data at next_in/avail_in to the output history
  2895. * without performing any output. The output buffer must be "caught up";
  2896. * i.e. no pending output (hence s->read equals s->write), and the state must
  2897. * be BLOCKS (i.e. we should be willing to see the start of a series of
  2898. * BLOCKS). On exit, the output will also be caught up, and the checksum
  2899. * will have been updated if need be.
  2900. */
  2901. int inflateIncomp(z)
  2902. z_stream *z;
  2903. {
  2904. if (z->state->mode != BLOCKS)
  2905. return Z_DATA_ERROR;
  2906. return inflate_addhistory(z->state->blocks, z);
  2907. }
  2908. int inflateSync(z)
  2909. z_streamp z;
  2910. {
  2911. uInt n; /* number of bytes to look at */
  2912. Bytef *p; /* pointer to bytes */
  2913. uInt m; /* number of marker bytes found in a row */
  2914. uLong r, w; /* temporaries to save total_in and total_out */
  2915. /* set up */
  2916. if (z == Z_NULL || z->state == Z_NULL)
  2917. return Z_STREAM_ERROR;
  2918. if (z->state->mode != BAD)
  2919. {
  2920. z->state->mode = BAD;
  2921. z->state->sub.marker = 0;
  2922. }
  2923. if ((n = z->avail_in) == 0)
  2924. return Z_BUF_ERROR;
  2925. p = z->next_in;
  2926. m = z->state->sub.marker;
  2927. /* search */
  2928. while (n && m < 4)
  2929. {
  2930. if (*p == (Byte)(m < 2 ? 0 : 0xff))
  2931. m++;
  2932. else if (*p)
  2933. m = 0;
  2934. else
  2935. m = 4 - m;
  2936. p++, n--;
  2937. }
  2938. /* restore */
  2939. z->total_in += p - z->next_in;
  2940. z->next_in = p;
  2941. z->avail_in = n;
  2942. z->state->sub.marker = m;
  2943. /* return no joy or set up to restart on a new block */
  2944. if (m != 4)
  2945. return Z_DATA_ERROR;
  2946. r = z->total_in; w = z->total_out;
  2947. inflateReset(z);
  2948. z->total_in = r; z->total_out = w;
  2949. z->state->mode = BLOCKS;
  2950. return Z_OK;
  2951. }
  2952. #undef NEEDBYTE
  2953. #undef NEXTBYTE
  2954. /* --- inflate.c */
  2955. /* +++ infblock.c */
  2956. /* infblock.c -- interpret and process block types to last block
  2957. * Copyright (C) 1995-1996 Mark Adler
  2958. * For conditions of distribution and use, see copyright notice in zlib.h
  2959. */
  2960. /* #include "zutil.h" */
  2961. /* #include "infblock.h" */
  2962. /* +++ inftrees.h */
  2963. /* inftrees.h -- header to use inftrees.c
  2964. * Copyright (C) 1995-1996 Mark Adler
  2965. * For conditions of distribution and use, see copyright notice in zlib.h
  2966. */
  2967. /* WARNING: this file should *not* be used by applications. It is
  2968. part of the implementation of the compression library and is
  2969. subject to change. Applications should only use zlib.h.
  2970. */
  2971. /* Huffman code lookup table entry--this entry is four bytes for machines
  2972. that have 16-bit pointers (e.g. PC's in the small or medium model). */
  2973. typedef struct inflate_huft_s FAR inflate_huft;
  2974. struct inflate_huft_s {
  2975. union {
  2976. struct {
  2977. Byte Exop; /* number of extra bits or operation */
  2978. Byte Bits; /* number of bits in this code or subcode */
  2979. } what;
  2980. Bytef *pad; /* pad structure to a power of 2 (4 bytes for */
  2981. } word; /* 16-bit, 8 bytes for 32-bit machines) */
  2982. union {
  2983. uInt Base; /* literal, length base, or distance base */
  2984. inflate_huft *Next; /* pointer to next level of table */
  2985. } more;
  2986. };
  2987. #ifdef DEBUG_ZLIB
  2988. extern uInt inflate_hufts;
  2989. #endif
  2990. extern int inflate_trees_bits OF((
  2991. uIntf *, /* 19 code lengths */
  2992. uIntf *, /* bits tree desired/actual depth */
  2993. inflate_huft * FAR *, /* bits tree result */
  2994. z_streamp )); /* for zalloc, zfree functions */
  2995. extern int inflate_trees_dynamic OF((
  2996. uInt, /* number of literal/length codes */
  2997. uInt, /* number of distance codes */
  2998. uIntf *, /* that many (total) code lengths */
  2999. uIntf *, /* literal desired/actual bit depth */
  3000. uIntf *, /* distance desired/actual bit depth */
  3001. inflate_huft * FAR *, /* literal/length tree result */
  3002. inflate_huft * FAR *, /* distance tree result */
  3003. z_streamp )); /* for zalloc, zfree functions */
  3004. extern int inflate_trees_fixed OF((
  3005. uIntf *, /* literal desired/actual bit depth */
  3006. uIntf *, /* distance desired/actual bit depth */
  3007. inflate_huft * FAR *, /* literal/length tree result */
  3008. inflate_huft * FAR *)); /* distance tree result */
  3009. extern int inflate_trees_free OF((
  3010. inflate_huft *, /* tables to free */
  3011. z_streamp )); /* for zfree function */
  3012. /* --- inftrees.h */
  3013. /* +++ infcodes.h */
  3014. /* infcodes.h -- header to use infcodes.c
  3015. * Copyright (C) 1995-1996 Mark Adler
  3016. * For conditions of distribution and use, see copyright notice in zlib.h
  3017. */
  3018. /* WARNING: this file should *not* be used by applications. It is
  3019. part of the implementation of the compression library and is
  3020. subject to change. Applications should only use zlib.h.
  3021. */
  3022. struct inflate_codes_state;
  3023. typedef struct inflate_codes_state FAR inflate_codes_statef;
  3024. extern inflate_codes_statef *inflate_codes_new OF((
  3025. uInt, uInt,
  3026. inflate_huft *, inflate_huft *,
  3027. z_streamp ));
  3028. extern int inflate_codes OF((
  3029. inflate_blocks_statef *,
  3030. z_streamp ,
  3031. int));
  3032. extern void inflate_codes_free OF((
  3033. inflate_codes_statef *,
  3034. z_streamp ));
  3035. /* --- infcodes.h */
  3036. /* +++ infutil.h */
  3037. /* infutil.h -- types and macros common to blocks and codes
  3038. * Copyright (C) 1995-1996 Mark Adler
  3039. * For conditions of distribution and use, see copyright notice in zlib.h
  3040. */
  3041. /* WARNING: this file should *not* be used by applications. It is
  3042. part of the implementation of the compression library and is
  3043. subject to change. Applications should only use zlib.h.
  3044. */
  3045. #ifndef _INFUTIL_H
  3046. #define _INFUTIL_H
  3047. typedef enum {
  3048. TYPE, /* get type bits (3, including end bit) */
  3049. LENS, /* get lengths for stored */
  3050. STORED, /* processing stored block */
  3051. TABLE, /* get table lengths */
  3052. BTREE, /* get bit lengths tree for a dynamic block */
  3053. DTREE, /* get length, distance trees for a dynamic block */
  3054. CODES, /* processing fixed or dynamic block */
  3055. DRY, /* output remaining window bytes */
  3056. DONEB, /* finished last block, done */
  3057. BADB} /* got a data error--stuck here */
  3058. inflate_block_mode;
  3059. /* inflate blocks semi-private state */
  3060. struct inflate_blocks_state {
  3061. /* mode */
  3062. inflate_block_mode mode; /* current inflate_block mode */
  3063. /* mode dependent information */
  3064. union {
  3065. uInt left; /* if STORED, bytes left to copy */
  3066. struct {
  3067. uInt table; /* table lengths (14 bits) */
  3068. uInt index; /* index into blens (or border) */
  3069. uIntf *blens; /* bit lengths of codes */
  3070. uInt bb; /* bit length tree depth */
  3071. inflate_huft *tb; /* bit length decoding tree */
  3072. } trees; /* if DTREE, decoding info for trees */
  3073. struct {
  3074. inflate_huft *tl;
  3075. inflate_huft *td; /* trees to free */
  3076. inflate_codes_statef
  3077. *codes;
  3078. } decode; /* if CODES, current state */
  3079. } sub; /* submode */
  3080. uInt last; /* true if this block is the last block */
  3081. /* mode independent information */
  3082. uInt bitk; /* bits in bit buffer */
  3083. uLong bitb; /* bit buffer */
  3084. Bytef *window; /* sliding window */
  3085. Bytef *end; /* one byte after sliding window */
  3086. Bytef *read; /* window read pointer */
  3087. Bytef *write; /* window write pointer */
  3088. check_func checkfn; /* check function */
  3089. uLong check; /* check on output */
  3090. };
  3091. /* defines for inflate input/output */
  3092. /* update pointers and return */
  3093. #define UPDBITS {s->bitb=b;s->bitk=k;}
  3094. #define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
  3095. #define UPDOUT {s->write=q;}
  3096. #define UPDATE {UPDBITS UPDIN UPDOUT}
  3097. #define LEAVE {UPDATE return inflate_flush(s,z,r);}
  3098. /* get bytes and bits */
  3099. #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
  3100. #define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
  3101. #define NEXTBYTE (n--,*p++)
  3102. #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
  3103. #define DUMPBITS(j) {b>>=(j);k-=(j);}
  3104. /* output bytes */
  3105. #define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
  3106. #define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
  3107. #define WWRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
  3108. #define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
  3109. #define NEEDOUT {if(m==0){WWRAP if(m==0){FLUSH WWRAP if(m==0) LEAVE}}r=Z_OK;}
  3110. #define OUTBYTE(a) {*q++=(Byte)(a);m--;}
  3111. /* load local pointers */
  3112. #define LOAD {LOADIN LOADOUT}
  3113. /* masks for lower bits (size given to avoid silly warnings with Visual C++) */
  3114. extern uInt inflate_mask[17];
  3115. /* copy as much as possible from the sliding window to the output area */
  3116. extern int inflate_flush OF((
  3117. inflate_blocks_statef *,
  3118. z_streamp ,
  3119. int));
  3120. #ifndef NO_DUMMY_DECL
  3121. struct internal_state {int dummy;}; /* for buggy compilers */
  3122. #endif
  3123. #endif
  3124. /* --- infutil.h */
  3125. #ifndef NO_DUMMY_DECL
  3126. struct inflate_codes_state {int dummy;}; /* for buggy compilers */
  3127. #endif
  3128. /* Table for deflate from PKZIP's appnote.txt. */
  3129. local const uInt border[] = { /* Order of the bit length code lengths */
  3130. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  3131. /*
  3132. Notes beyond the 1.93a appnote.txt:
  3133. 1. Distance pointers never point before the beginning of the output
  3134. stream.
  3135. 2. Distance pointers can point back across blocks, up to 32k away.
  3136. 3. There is an implied maximum of 7 bits for the bit length table and
  3137. 15 bits for the actual data.
  3138. 4. If only one code exists, then it is encoded using one bit. (Zero
  3139. would be more efficient, but perhaps a little confusing.) If two
  3140. codes exist, they are coded using one bit each (0 and 1).
  3141. 5. There is no way of sending zero distance codes--a dummy must be
  3142. sent if there are none. (History: a pre 2.0 version of PKZIP would
  3143. store blocks with no distance codes, but this was discovered to be
  3144. too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
  3145. zero distance codes, which is sent as one code of zero bits in
  3146. length.
  3147. 6. There are up to 286 literal/length codes. Code 256 represents the
  3148. end-of-block. Note however that the static length tree defines
  3149. 288 codes just to fill out the Huffman codes. Codes 286 and 287
  3150. cannot be used though, since there is no length base or extra bits
  3151. defined for them. Similarily, there are up to 30 distance codes.
  3152. However, static trees define 32 codes (all 5 bits) to fill out the
  3153. Huffman codes, but the last two had better not show up in the data.
  3154. 7. Unzip can check dynamic Huffman blocks for complete code sets.
  3155. The exception is that a single code would not be complete (see #4).
  3156. 8. The five bits following the block type is really the number of
  3157. literal codes sent minus 257.
  3158. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  3159. (1+6+6). Therefore, to output three times the length, you output
  3160. three codes (1+1+1), whereas to output four times the same length,
  3161. you only need two codes (1+3). Hmm.
  3162. 10. In the tree reconstruction algorithm, Code = Code + Increment
  3163. only if BitLength(i) is not zero. (Pretty obvious.)
  3164. 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
  3165. 12. Note: length code 284 can represent 227-258, but length code 285
  3166. really is 258. The last length deserves its own, short code
  3167. since it gets used a lot in very redundant files. The length
  3168. 258 is special since 258 - 3 (the min match length) is 255.
  3169. 13. The literal/length and distance code bit lengths are read as a
  3170. single stream of lengths. It is possible (and advantageous) for
  3171. a repeat code (16, 17, or 18) to go across the boundary between
  3172. the two sets of lengths.
  3173. */
  3174. void inflate_blocks_reset(s, z, c)
  3175. inflate_blocks_statef *s;
  3176. z_streamp z;
  3177. uLongf *c;
  3178. {
  3179. if (s->checkfn != Z_NULL)
  3180. *c = s->check;
  3181. if (s->mode == BTREE || s->mode == DTREE)
  3182. ZFREE(z, s->sub.trees.blens);
  3183. if (s->mode == CODES)
  3184. {
  3185. inflate_codes_free(s->sub.decode.codes, z);
  3186. inflate_trees_free(s->sub.decode.td, z);
  3187. inflate_trees_free(s->sub.decode.tl, z);
  3188. }
  3189. s->mode = TYPE;
  3190. s->bitk = 0;
  3191. s->bitb = 0;
  3192. s->read = s->write = s->window;
  3193. if (s->checkfn != Z_NULL)
  3194. z->adler = s->check = (*s->checkfn)(0L, Z_NULL, 0);
  3195. Trace((stderr, "inflate: blocks reset\n"));
  3196. }
  3197. inflate_blocks_statef *inflate_blocks_new(z, c, w)
  3198. z_streamp z;
  3199. check_func c;
  3200. uInt w;
  3201. {
  3202. inflate_blocks_statef *s;
  3203. if ((s = (inflate_blocks_statef *)ZALLOC
  3204. (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
  3205. return s;
  3206. if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL)
  3207. {
  3208. ZFREE(z, s);
  3209. return Z_NULL;
  3210. }
  3211. s->end = s->window + w;
  3212. s->checkfn = c;
  3213. s->mode = TYPE;
  3214. Trace((stderr, "inflate: blocks allocated\n"));
  3215. inflate_blocks_reset(s, z, &s->check);
  3216. return s;
  3217. }
  3218. #ifdef DEBUG_ZLIB
  3219. extern uInt inflate_hufts;
  3220. #endif
  3221. int inflate_blocks(s, z, r)
  3222. inflate_blocks_statef *s;
  3223. z_streamp z;
  3224. int r;
  3225. {
  3226. uInt t; /* temporary storage */
  3227. uLong b; /* bit buffer */
  3228. uInt k; /* bits in bit buffer */
  3229. Bytef *p; /* input data pointer */
  3230. uInt n; /* bytes available there */
  3231. Bytef *q; /* output window write pointer */
  3232. uInt m; /* bytes to end of window or read pointer */
  3233. /* copy input/output information to locals (UPDATE macro restores) */
  3234. LOAD
  3235. /* process input based on current state */
  3236. while (1) switch (s->mode)
  3237. {
  3238. case TYPE:
  3239. NEEDBITS(3)
  3240. t = (uInt)b & 7;
  3241. s->last = t & 1;
  3242. switch (t >> 1)
  3243. {
  3244. case 0: /* stored */
  3245. Trace((stderr, "inflate: stored block%s\n",
  3246. s->last ? " (last)" : ""));
  3247. DUMPBITS(3)
  3248. t = k & 7; /* go to byte boundary */
  3249. DUMPBITS(t)
  3250. s->mode = LENS; /* get length of stored block */
  3251. break;
  3252. case 1: /* fixed */
  3253. Trace((stderr, "inflate: fixed codes block%s\n",
  3254. s->last ? " (last)" : ""));
  3255. {
  3256. uInt bl, bd;
  3257. inflate_huft *tl, *td;
  3258. inflate_trees_fixed(&bl, &bd, &tl, &td);
  3259. s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
  3260. if (s->sub.decode.codes == Z_NULL)
  3261. {
  3262. r = Z_MEM_ERROR;
  3263. LEAVE
  3264. }
  3265. s->sub.decode.tl = Z_NULL; /* don't try to free these */
  3266. s->sub.decode.td = Z_NULL;
  3267. }
  3268. DUMPBITS(3)
  3269. s->mode = CODES;
  3270. break;
  3271. case 2: /* dynamic */
  3272. Trace((stderr, "inflate: dynamic codes block%s\n",
  3273. s->last ? " (last)" : ""));
  3274. DUMPBITS(3)
  3275. s->mode = TABLE;
  3276. break;
  3277. case 3: /* illegal */
  3278. DUMPBITS(3)
  3279. s->mode = BADB;
  3280. z->msg = (char*)"invalid block type";
  3281. r = Z_DATA_ERROR;
  3282. LEAVE
  3283. }
  3284. break;
  3285. case LENS:
  3286. NEEDBITS(32)
  3287. if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
  3288. {
  3289. s->mode = BADB;
  3290. z->msg = (char*)"invalid stored block lengths";
  3291. r = Z_DATA_ERROR;
  3292. LEAVE
  3293. }
  3294. s->sub.left = (uInt)b & 0xffff;
  3295. b = k = 0; /* dump bits */
  3296. Tracev((stderr, "inflate: stored length %u\n", s->sub.left));
  3297. s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
  3298. break;
  3299. case STORED:
  3300. if (n == 0)
  3301. LEAVE
  3302. NEEDOUT
  3303. t = s->sub.left;
  3304. if (t > n) t = n;
  3305. if (t > m) t = m;
  3306. zmemcpy(q, p, t);
  3307. p += t; n -= t;
  3308. q += t; m -= t;
  3309. if ((s->sub.left -= t) != 0)
  3310. break;
  3311. Tracev((stderr, "inflate: stored end, %lu total out\n",
  3312. z->total_out + (q >= s->read ? q - s->read :
  3313. (s->end - s->read) + (q - s->window))));
  3314. s->mode = s->last ? DRY : TYPE;
  3315. break;
  3316. case TABLE:
  3317. NEEDBITS(14)
  3318. s->sub.trees.table = t = (uInt)b & 0x3fff;
  3319. #ifndef PKZIP_BUG_WORKAROUND
  3320. if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
  3321. {
  3322. s->mode = BADB;
  3323. z->msg = (char*)"too many length or distance symbols";
  3324. r = Z_DATA_ERROR;
  3325. LEAVE
  3326. }
  3327. #endif
  3328. t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
  3329. if (t < 19)
  3330. t = 19;
  3331. if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
  3332. {
  3333. r = Z_MEM_ERROR;
  3334. LEAVE
  3335. }
  3336. DUMPBITS(14)
  3337. s->sub.trees.index = 0;
  3338. Tracev((stderr, "inflate: table sizes ok\n"));
  3339. s->mode = BTREE;
  3340. case BTREE:
  3341. while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
  3342. {
  3343. NEEDBITS(3)
  3344. s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
  3345. DUMPBITS(3)
  3346. }
  3347. while (s->sub.trees.index < 19)
  3348. s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
  3349. s->sub.trees.bb = 7;
  3350. t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
  3351. &s->sub.trees.tb, z);
  3352. if (t != Z_OK)
  3353. {
  3354. r = t;
  3355. if (r == Z_DATA_ERROR) {
  3356. s->mode = BADB;
  3357. ZFREE(z, s->sub.trees.blens);
  3358. }
  3359. LEAVE
  3360. }
  3361. s->sub.trees.index = 0;
  3362. Tracev((stderr, "inflate: bits tree ok\n"));
  3363. s->mode = DTREE;
  3364. case DTREE:
  3365. while (t = s->sub.trees.table,
  3366. s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
  3367. {
  3368. inflate_huft *h;
  3369. uInt i, j, c;
  3370. t = s->sub.trees.bb;
  3371. NEEDBITS(t)
  3372. h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
  3373. t = h->word.what.Bits;
  3374. c = h->more.Base;
  3375. if (c < 16)
  3376. {
  3377. DUMPBITS(t)
  3378. s->sub.trees.blens[s->sub.trees.index++] = c;
  3379. }
  3380. else /* c == 16..18 */
  3381. {
  3382. i = c == 18 ? 7 : c - 14;
  3383. j = c == 18 ? 11 : 3;
  3384. NEEDBITS(t + i)
  3385. DUMPBITS(t)
  3386. j += (uInt)b & inflate_mask[i];
  3387. DUMPBITS(i)
  3388. i = s->sub.trees.index;
  3389. t = s->sub.trees.table;
  3390. if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
  3391. (c == 16 && i < 1))
  3392. {
  3393. inflate_trees_free(s->sub.trees.tb, z);
  3394. ZFREE(z, s->sub.trees.blens);
  3395. s->mode = BADB;
  3396. z->msg = (char*)"invalid bit length repeat";
  3397. r = Z_DATA_ERROR;
  3398. LEAVE
  3399. }
  3400. c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
  3401. do {
  3402. s->sub.trees.blens[i++] = c;
  3403. } while (--j);
  3404. s->sub.trees.index = i;
  3405. }
  3406. }
  3407. inflate_trees_free(s->sub.trees.tb, z);
  3408. s->sub.trees.tb = Z_NULL;
  3409. {
  3410. uInt bl, bd;
  3411. inflate_huft *tl, *td;
  3412. inflate_codes_statef *c;
  3413. bl = 9; /* must be <= 9 for lookahead assumptions */
  3414. bd = 6; /* must be <= 9 for lookahead assumptions */
  3415. t = s->sub.trees.table;
  3416. #ifdef DEBUG_ZLIB
  3417. inflate_hufts = 0;
  3418. #endif
  3419. t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
  3420. s->sub.trees.blens, &bl, &bd, &tl, &td, z);
  3421. if (t != Z_OK)
  3422. {
  3423. if (t == (uInt)Z_DATA_ERROR) {
  3424. s->mode = BADB;
  3425. ZFREE(z, s->sub.trees.blens);
  3426. }
  3427. r = t;
  3428. LEAVE
  3429. }
  3430. ZFREE(z, s->sub.trees.blens);
  3431. Tracev((stderr, "inflate: trees ok, %d * %d bytes used\n",
  3432. inflate_hufts, sizeof(inflate_huft)));
  3433. if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
  3434. {
  3435. inflate_trees_free(td, z);
  3436. inflate_trees_free(tl, z);
  3437. r = Z_MEM_ERROR;
  3438. LEAVE
  3439. }
  3440. s->sub.decode.codes = c;
  3441. s->sub.decode.tl = tl;
  3442. s->sub.decode.td = td;
  3443. }
  3444. s->mode = CODES;
  3445. case CODES:
  3446. UPDATE
  3447. if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
  3448. return inflate_flush(s, z, r);
  3449. r = Z_OK;
  3450. inflate_codes_free(s->sub.decode.codes, z);
  3451. inflate_trees_free(s->sub.decode.td, z);
  3452. inflate_trees_free(s->sub.decode.tl, z);
  3453. LOAD
  3454. Tracev((stderr, "inflate: codes end, %lu total out\n",
  3455. z->total_out + (q >= s->read ? q - s->read :
  3456. (s->end - s->read) + (q - s->window))));
  3457. if (!s->last)
  3458. {
  3459. s->mode = TYPE;
  3460. break;
  3461. }
  3462. if (k > 7) /* return unused byte, if any */
  3463. {
  3464. Assert(k < 16, "inflate_codes grabbed too many bytes")
  3465. k -= 8;
  3466. n++;
  3467. p--; /* can always return one */
  3468. }
  3469. s->mode = DRY;
  3470. case DRY:
  3471. FLUSH
  3472. if (s->read != s->write)
  3473. LEAVE
  3474. s->mode = DONEB;
  3475. case DONEB:
  3476. r = Z_STREAM_END;
  3477. LEAVE
  3478. case BADB:
  3479. r = Z_DATA_ERROR;
  3480. LEAVE
  3481. default:
  3482. r = Z_STREAM_ERROR;
  3483. LEAVE
  3484. }
  3485. }
  3486. int inflate_blocks_free(s, z, c)
  3487. inflate_blocks_statef *s;
  3488. z_streamp z;
  3489. uLongf *c;
  3490. {
  3491. inflate_blocks_reset(s, z, c);
  3492. ZFREE(z, s->window);
  3493. ZFREE(z, s);
  3494. Trace((stderr, "inflate: blocks freed\n"));
  3495. return Z_OK;
  3496. }
  3497. void inflate_set_dictionary(s, d, n)
  3498. inflate_blocks_statef *s;
  3499. const Bytef *d;
  3500. uInt n;
  3501. {
  3502. zmemcpy((charf *)s->window, d, n);
  3503. s->read = s->write = s->window + n;
  3504. }
  3505. /*
  3506. * This subroutine adds the data at next_in/avail_in to the output history
  3507. * without performing any output. The output buffer must be "caught up";
  3508. * i.e. no pending output (hence s->read equals s->write), and the state must
  3509. * be BLOCKS (i.e. we should be willing to see the start of a series of
  3510. * BLOCKS). On exit, the output will also be caught up, and the checksum
  3511. * will have been updated if need be.
  3512. */
  3513. int inflate_addhistory(s, z)
  3514. inflate_blocks_statef *s;
  3515. z_stream *z;
  3516. {
  3517. uLong b; /* bit buffer */ /* NOT USED HERE */
  3518. uInt k; /* bits in bit buffer */ /* NOT USED HERE */
  3519. uInt t; /* temporary storage */
  3520. Bytef *p; /* input data pointer */
  3521. uInt n; /* bytes available there */
  3522. Bytef *q; /* output window write pointer */
  3523. uInt m; /* bytes to end of window or read pointer */
  3524. if (s->read != s->write)
  3525. return Z_STREAM_ERROR;
  3526. if (s->mode != TYPE)
  3527. return Z_DATA_ERROR;
  3528. /* we're ready to rock */
  3529. LOAD
  3530. /* while there is input ready, copy to output buffer, moving
  3531. * pointers as needed.
  3532. */
  3533. while (n) {
  3534. t = n; /* how many to do */
  3535. /* is there room until end of buffer? */
  3536. if (t > m) t = m;
  3537. /* update check information */
  3538. if (s->checkfn != Z_NULL)
  3539. s->check = (*s->checkfn)(s->check, q, t);
  3540. zmemcpy(q, p, t);
  3541. q += t;
  3542. p += t;
  3543. n -= t;
  3544. z->total_out += t;
  3545. s->read = q; /* drag read pointer forward */
  3546. /* WWRAP */ /* expand WWRAP macro by hand to handle s->read */
  3547. if (q == s->end) {
  3548. s->read = q = s->window;
  3549. m = WAVAIL;
  3550. }
  3551. }
  3552. UPDATE
  3553. return Z_OK;
  3554. }
  3555. /*
  3556. * At the end of a Deflate-compressed PPP packet, we expect to have seen
  3557. * a `stored' block type value but not the (zero) length bytes.
  3558. */
  3559. int inflate_packet_flush(s)
  3560. inflate_blocks_statef *s;
  3561. {
  3562. if (s->mode != LENS)
  3563. return Z_DATA_ERROR;
  3564. s->mode = TYPE;
  3565. return Z_OK;
  3566. }
  3567. /* --- infblock.c */
  3568. /* +++ inftrees.c */
  3569. /* inftrees.c -- generate Huffman trees for efficient decoding
  3570. * Copyright (C) 1995-1996 Mark Adler
  3571. * For conditions of distribution and use, see copyright notice in zlib.h
  3572. */
  3573. /* #include "zutil.h" */
  3574. /* #include "inftrees.h" */
  3575. char inflate_copyright[] = " inflate 1.0.4 Copyright 1995-1996 Mark Adler ";
  3576. /*
  3577. If you use the zlib library in a product, an acknowledgment is welcome
  3578. in the documentation of your product. If for some reason you cannot
  3579. include such an acknowledgment, I would appreciate that you keep this
  3580. copyright string in the executable of your product.
  3581. */
  3582. #ifndef NO_DUMMY_DECL
  3583. struct internal_state {int dummy;}; /* for buggy compilers */
  3584. #endif
  3585. /* simplify the use of the inflate_huft type with some defines */
  3586. #define base more.Base
  3587. #define next more.Next
  3588. #define exop word.what.Exop
  3589. #define bits word.what.Bits
  3590. local int huft_build OF((
  3591. uIntf *, /* code lengths in bits */
  3592. uInt, /* number of codes */
  3593. uInt, /* number of "simple" codes */
  3594. const uIntf *, /* list of base values for non-simple codes */
  3595. const uIntf *, /* list of extra bits for non-simple codes */
  3596. inflate_huft * FAR*,/* result: starting table */
  3597. uIntf *, /* maximum lookup bits (returns actual) */
  3598. z_streamp )); /* for zalloc function */
  3599. local voidpf falloc OF((
  3600. voidpf, /* opaque pointer (not used) */
  3601. uInt, /* number of items */
  3602. uInt)); /* size of item */
  3603. /* Tables for deflate from PKZIP's appnote.txt. */
  3604. local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
  3605. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  3606. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  3607. /* see note #13 above about 258 */
  3608. local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
  3609. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  3610. 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
  3611. local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
  3612. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  3613. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  3614. 8193, 12289, 16385, 24577};
  3615. local const uInt cpdext[30] = { /* Extra bits for distance codes */
  3616. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  3617. 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  3618. 12, 12, 13, 13};
  3619. /*
  3620. Huffman code decoding is performed using a multi-level table lookup.
  3621. The fastest way to decode is to simply build a lookup table whose
  3622. size is determined by the longest code. However, the time it takes
  3623. to build this table can also be a factor if the data being decoded
  3624. is not very long. The most common codes are necessarily the
  3625. shortest codes, so those codes dominate the decoding time, and hence
  3626. the speed. The idea is you can have a shorter table that decodes the
  3627. shorter, more probable codes, and then point to subsidiary tables for
  3628. the longer codes. The time it costs to decode the longer codes is
  3629. then traded against the time it takes to make longer tables.
  3630. This results of this trade are in the variables lbits and dbits
  3631. below. lbits is the number of bits the first level table for literal/
  3632. length codes can decode in one step, and dbits is the same thing for
  3633. the distance codes. Subsequent tables are also less than or equal to
  3634. those sizes. These values may be adjusted either when all of the
  3635. codes are shorter than that, in which case the longest code length in
  3636. bits is used, or when the shortest code is *longer* than the requested
  3637. table size, in which case the length of the shortest code in bits is
  3638. used.
  3639. There are two different values for the two tables, since they code a
  3640. different number of possibilities each. The literal/length table
  3641. codes 286 possible values, or in a flat code, a little over eight
  3642. bits. The distance table codes 30 possible values, or a little less
  3643. than five bits, flat. The optimum values for speed end up being
  3644. about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  3645. The optimum values may differ though from machine to machine, and
  3646. possibly even between compilers. Your mileage may vary.
  3647. */
  3648. /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
  3649. #define BMAX 15 /* maximum bit length of any code */
  3650. #define N_MAX 288 /* maximum number of codes in any set */
  3651. #ifdef DEBUG_ZLIB
  3652. uInt inflate_hufts;
  3653. #endif
  3654. local int huft_build(b, n, s, d, e, t, m, zs)
  3655. uIntf *b; /* code lengths in bits (all assumed <= BMAX) */
  3656. uInt n; /* number of codes (assumed <= N_MAX) */
  3657. uInt s; /* number of simple-valued codes (0..s-1) */
  3658. const uIntf *d; /* list of base values for non-simple codes */
  3659. const uIntf *e; /* list of extra bits for non-simple codes */
  3660. inflate_huft * FAR *t; /* result: starting table */
  3661. uIntf *m; /* maximum lookup bits, returns actual */
  3662. z_streamp zs; /* for zalloc function */
  3663. /* Given a list of code lengths and a maximum table size, make a set of
  3664. tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
  3665. if the given code set is incomplete (the tables are still built in this
  3666. case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
  3667. lengths), or Z_MEM_ERROR if not enough memory. */
  3668. {
  3669. uInt a; /* counter for codes of length k */
  3670. uInt c[BMAX+1]; /* bit length count table */
  3671. uInt f; /* i repeats in table every f entries */
  3672. int g; /* maximum code length */
  3673. int h; /* table level */
  3674. register uInt i; /* counter, current code */
  3675. register uInt j; /* counter */
  3676. register int k; /* number of bits in current code */
  3677. int l; /* bits per table (returned in m) */
  3678. register uIntf *p; /* pointer into c[], b[], or v[] */
  3679. inflate_huft *q; /* points to current table */
  3680. struct inflate_huft_s r; /* table entry for structure assignment */
  3681. inflate_huft *u[BMAX]; /* table stack */
  3682. uInt v[N_MAX]; /* values in order of bit length */
  3683. register int w; /* bits before this table == (l * h) */
  3684. uInt x[BMAX+1]; /* bit offsets, then code stack */
  3685. uIntf *xp; /* pointer into x */
  3686. int y; /* number of dummy codes added */
  3687. uInt z; /* number of entries in current table */
  3688. /* Generate counts for each bit length */
  3689. p = c;
  3690. #define C0 *p++ = 0;
  3691. #define C2 C0 C0 C0 C0
  3692. #define C4 C2 C2 C2 C2
  3693. C4 /* clear c[]--assume BMAX+1 is 16 */
  3694. p = b; i = n;
  3695. do {
  3696. c[*p++]++; /* assume all entries <= BMAX */
  3697. } while (--i);
  3698. if (c[0] == n) /* null input--all zero length codes */
  3699. {
  3700. *t = (inflate_huft *)Z_NULL;
  3701. *m = 0;
  3702. return Z_OK;
  3703. }
  3704. /* Find minimum and maximum length, bound *m by those */
  3705. l = *m;
  3706. for (j = 1; j <= BMAX; j++)
  3707. if (c[j])
  3708. break;
  3709. k = j; /* minimum code length */
  3710. if ((uInt)l < j)
  3711. l = j;
  3712. for (i = BMAX; i; i--)
  3713. if (c[i])
  3714. break;
  3715. g = i; /* maximum code length */
  3716. if ((uInt)l > i)
  3717. l = i;
  3718. *m = l;
  3719. /* Adjust last length count to fill out codes, if needed */
  3720. for (y = 1 << j; j < i; j++, y <<= 1)
  3721. if ((y -= c[j]) < 0)
  3722. return Z_DATA_ERROR;
  3723. if ((y -= c[i]) < 0)
  3724. return Z_DATA_ERROR;
  3725. c[i] += y;
  3726. /* Generate starting offsets into the value table for each length */
  3727. x[1] = j = 0;
  3728. p = c + 1; xp = x + 2;
  3729. while (--i) { /* note that i == g from above */
  3730. *xp++ = (j += *p++);
  3731. }
  3732. /* Make a table of values in order of bit lengths */
  3733. p = b; i = 0;
  3734. do {
  3735. if ((j = *p++) != 0)
  3736. v[x[j]++] = i;
  3737. } while (++i < n);
  3738. n = x[g]; /* set n to length of v */
  3739. /* Generate the Huffman codes and for each, make the table entries */
  3740. x[0] = i = 0; /* first Huffman code is zero */
  3741. p = v; /* grab values in bit order */
  3742. h = -1; /* no tables yet--level -1 */
  3743. w = -l; /* bits decoded == (l * h) */
  3744. u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */
  3745. q = (inflate_huft *)Z_NULL; /* ditto */
  3746. z = 0; /* ditto */
  3747. /* go through the bit lengths (k already is bits in shortest code) */
  3748. for (; k <= g; k++)
  3749. {
  3750. a = c[k];
  3751. while (a--)
  3752. {
  3753. /* here i is the Huffman code of length k bits for value *p */
  3754. /* make tables up to required level */
  3755. while (k > w + l)
  3756. {
  3757. h++;
  3758. w += l; /* previous table always l bits */
  3759. /* compute minimum size table less than or equal to l bits */
  3760. z = g - w;
  3761. z = z > (uInt)l ? l : z; /* table size upper limit */
  3762. if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */
  3763. { /* too few codes for k-w bit table */
  3764. f -= a + 1; /* deduct codes from patterns left */
  3765. xp = c + k;
  3766. if (j < z)
  3767. while (++j < z) /* try smaller tables up to z bits */
  3768. {
  3769. if ((f <<= 1) <= *++xp)
  3770. break; /* enough codes to use up j bits */
  3771. f -= *xp; /* else deduct codes from patterns */
  3772. }
  3773. }
  3774. z = 1 << j; /* table entries for j-bit table */
  3775. /* allocate and link in new table */
  3776. if ((q = (inflate_huft *)ZALLOC
  3777. (zs,z + 1,sizeof(inflate_huft))) == Z_NULL)
  3778. {
  3779. if (h)
  3780. inflate_trees_free(u[0], zs);
  3781. return Z_MEM_ERROR; /* not enough memory */
  3782. }
  3783. #ifdef DEBUG_ZLIB
  3784. inflate_hufts += z + 1;
  3785. #endif
  3786. *t = q + 1; /* link to list for huft_free() */
  3787. *(t = &(q->next)) = Z_NULL;
  3788. u[h] = ++q; /* table starts after link */
  3789. /* connect to last table, if there is one */
  3790. if (h)
  3791. {
  3792. x[h] = i; /* save pattern for backing up */
  3793. r.bits = (Byte)l; /* bits to dump before this table */
  3794. r.exop = (Byte)j; /* bits in this table */
  3795. r.next = q; /* pointer to this table */
  3796. j = i >> (w - l); /* (get around Turbo C bug) */
  3797. u[h-1][j] = r; /* connect to last table */
  3798. }
  3799. }
  3800. /* set up table entry in r */
  3801. r.bits = (Byte)(k - w);
  3802. if (p >= v + n)
  3803. r.exop = 128 + 64; /* out of values--invalid code */
  3804. else if (*p < s)
  3805. {
  3806. r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */
  3807. r.base = *p++; /* simple code is just the value */
  3808. }
  3809. else
  3810. {
  3811. r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
  3812. r.base = d[*p++ - s];
  3813. }
  3814. /* fill code-like entries with r */
  3815. f = 1 << (k - w);
  3816. for (j = i >> w; j < z; j += f)
  3817. q[j] = r;
  3818. /* backwards increment the k-bit code i */
  3819. for (j = 1 << (k - 1); i & j; j >>= 1)
  3820. i ^= j;
  3821. i ^= j;
  3822. /* backup over finished tables */
  3823. while ((i & ((1 << w) - 1)) != x[h])
  3824. {
  3825. h--; /* don't need to update q */
  3826. w -= l;
  3827. }
  3828. }
  3829. }
  3830. /* Return Z_BUF_ERROR if we were given an incomplete table */
  3831. return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
  3832. }
  3833. int inflate_trees_bits(c, bb, tb, z)
  3834. uIntf *c; /* 19 code lengths */
  3835. uIntf *bb; /* bits tree desired/actual depth */
  3836. inflate_huft * FAR *tb; /* bits tree result */
  3837. z_streamp z; /* for zfree function */
  3838. {
  3839. int r;
  3840. r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL, tb, bb, z);
  3841. if (r == Z_DATA_ERROR)
  3842. z->msg = (char*)"oversubscribed dynamic bit lengths tree";
  3843. else if (r == Z_BUF_ERROR || *bb == 0)
  3844. {
  3845. inflate_trees_free(*tb, z);
  3846. z->msg = (char*)"incomplete dynamic bit lengths tree";
  3847. r = Z_DATA_ERROR;
  3848. }
  3849. return r;
  3850. }
  3851. int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, z)
  3852. uInt nl; /* number of literal/length codes */
  3853. uInt nd; /* number of distance codes */
  3854. uIntf *c; /* that many (total) code lengths */
  3855. uIntf *bl; /* literal desired/actual bit depth */
  3856. uIntf *bd; /* distance desired/actual bit depth */
  3857. inflate_huft * FAR *tl; /* literal/length tree result */
  3858. inflate_huft * FAR *td; /* distance tree result */
  3859. z_streamp z; /* for zfree function */
  3860. {
  3861. int r;
  3862. /* build literal/length tree */
  3863. r = huft_build(c, nl, 257, cplens, cplext, tl, bl, z);
  3864. if (r != Z_OK || *bl == 0)
  3865. {
  3866. if (r == Z_DATA_ERROR)
  3867. z->msg = (char*)"oversubscribed literal/length tree";
  3868. else if (r != Z_MEM_ERROR)
  3869. {
  3870. inflate_trees_free(*tl, z);
  3871. z->msg = (char*)"incomplete literal/length tree";
  3872. r = Z_DATA_ERROR;
  3873. }
  3874. return r;
  3875. }
  3876. /* build distance tree */
  3877. r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, z);
  3878. if (r != Z_OK || (*bd == 0 && nl > 257))
  3879. {
  3880. if (r == Z_DATA_ERROR)
  3881. z->msg = (char*)"oversubscribed distance tree";
  3882. else if (r == Z_BUF_ERROR) {
  3883. #ifdef PKZIP_BUG_WORKAROUND
  3884. r = Z_OK;
  3885. }
  3886. #else
  3887. inflate_trees_free(*td, z);
  3888. z->msg = (char*)"incomplete distance tree";
  3889. r = Z_DATA_ERROR;
  3890. }
  3891. else if (r != Z_MEM_ERROR)
  3892. {
  3893. z->msg = (char*)"empty distance tree with lengths";
  3894. r = Z_DATA_ERROR;
  3895. }
  3896. inflate_trees_free(*tl, z);
  3897. return r;
  3898. #endif
  3899. }
  3900. /* done */
  3901. return Z_OK;
  3902. }
  3903. /* build fixed tables only once--keep them here */
  3904. local int fixed_built = 0;
  3905. #define FIXEDH 530 /* number of hufts used by fixed tables */
  3906. local inflate_huft fixed_mem[FIXEDH];
  3907. local uInt fixed_bl;
  3908. local uInt fixed_bd;
  3909. local inflate_huft *fixed_tl;
  3910. local inflate_huft *fixed_td;
  3911. local voidpf falloc(q, n, s)
  3912. voidpf q; /* opaque pointer */
  3913. uInt n; /* number of items */
  3914. uInt s; /* size of item */
  3915. {
  3916. Assert(s == sizeof(inflate_huft) && n <= *(intf *)q,
  3917. "inflate_trees falloc overflow");
  3918. *(intf *)q -= n+s-s; /* s-s to avoid warning */
  3919. return (voidpf)(fixed_mem + *(intf *)q);
  3920. }
  3921. int inflate_trees_fixed(bl, bd, tl, td)
  3922. uIntf *bl; /* literal desired/actual bit depth */
  3923. uIntf *bd; /* distance desired/actual bit depth */
  3924. inflate_huft * FAR *tl; /* literal/length tree result */
  3925. inflate_huft * FAR *td; /* distance tree result */
  3926. {
  3927. /* build fixed tables if not already (multiple overlapped executions ok) */
  3928. if (!fixed_built)
  3929. {
  3930. int k; /* temporary variable */
  3931. unsigned c[288]; /* length list for huft_build */
  3932. z_stream z; /* for falloc function */
  3933. int f = FIXEDH; /* number of hufts left in fixed_mem */
  3934. /* set up fake z_stream for memory routines */
  3935. z.zalloc = falloc;
  3936. z.zfree = Z_NULL;
  3937. z.opaque = (voidpf)&f;
  3938. /* literal table */
  3939. for (k = 0; k < 144; k++)
  3940. c[k] = 8;
  3941. for (; k < 256; k++)
  3942. c[k] = 9;
  3943. for (; k < 280; k++)
  3944. c[k] = 7;
  3945. for (; k < 288; k++)
  3946. c[k] = 8;
  3947. fixed_bl = 7;
  3948. huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl, &z);
  3949. /* distance table */
  3950. for (k = 0; k < 30; k++)
  3951. c[k] = 5;
  3952. fixed_bd = 5;
  3953. huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd, &z);
  3954. /* done */
  3955. Assert(f == 0, "invalid build of fixed tables");
  3956. fixed_built = 1;
  3957. }
  3958. *bl = fixed_bl;
  3959. *bd = fixed_bd;
  3960. *tl = fixed_tl;
  3961. *td = fixed_td;
  3962. return Z_OK;
  3963. }
  3964. int inflate_trees_free(t, z)
  3965. inflate_huft *t; /* table to free */
  3966. z_streamp z; /* for zfree function */
  3967. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  3968. list of the tables it made, with the links in a dummy first entry of
  3969. each table. */
  3970. {
  3971. register inflate_huft *p, *q, *r;
  3972. /* Reverse linked list */
  3973. p = Z_NULL;
  3974. q = t;
  3975. while (q != Z_NULL)
  3976. {
  3977. r = (q - 1)->next;
  3978. (q - 1)->next = p;
  3979. p = q;
  3980. q = r;
  3981. }
  3982. /* Go through linked list, freeing from the malloced (t[-1]) address. */
  3983. while (p != Z_NULL)
  3984. {
  3985. q = (--p)->next;
  3986. ZFREE(z,p);
  3987. p = q;
  3988. }
  3989. return Z_OK;
  3990. }
  3991. /* --- inftrees.c */
  3992. /* +++ infcodes.c */
  3993. /* infcodes.c -- process literals and length/distance pairs
  3994. * Copyright (C) 1995-1996 Mark Adler
  3995. * For conditions of distribution and use, see copyright notice in zlib.h
  3996. */
  3997. /* #include "zutil.h" */
  3998. /* #include "inftrees.h" */
  3999. /* #include "infblock.h" */
  4000. /* #include "infcodes.h" */
  4001. /* #include "infutil.h" */
  4002. /* +++ inffast.h */
  4003. /* inffast.h -- header to use inffast.c
  4004. * Copyright (C) 1995-1996 Mark Adler
  4005. * For conditions of distribution and use, see copyright notice in zlib.h
  4006. */
  4007. /* WARNING: this file should *not* be used by applications. It is
  4008. part of the implementation of the compression library and is
  4009. subject to change. Applications should only use zlib.h.
  4010. */
  4011. extern int inflate_fast OF((
  4012. uInt,
  4013. uInt,
  4014. inflate_huft *,
  4015. inflate_huft *,
  4016. inflate_blocks_statef *,
  4017. z_streamp ));
  4018. /* --- inffast.h */
  4019. /* simplify the use of the inflate_huft type with some defines */
  4020. #define base more.Base
  4021. #define next more.Next
  4022. #define exop word.what.Exop
  4023. #define bits word.what.Bits
  4024. /* inflate codes private state */
  4025. struct inflate_codes_state {
  4026. /* mode */
  4027. enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
  4028. START, /* x: set up for LEN */
  4029. LEN, /* i: get length/literal/eob next */
  4030. LENEXT, /* i: getting length extra (have base) */
  4031. DIST, /* i: get distance next */
  4032. DISTEXT, /* i: getting distance extra */
  4033. COPY, /* o: copying bytes in window, waiting for space */
  4034. LIT, /* o: got literal, waiting for output space */
  4035. WASH, /* o: got eob, possibly still output waiting */
  4036. END, /* x: got eob and all data flushed */
  4037. BADCODE} /* x: got error */
  4038. mode; /* current inflate_codes mode */
  4039. /* mode dependent information */
  4040. uInt len;
  4041. union {
  4042. struct {
  4043. inflate_huft *tree; /* pointer into tree */
  4044. uInt need; /* bits needed */
  4045. } code; /* if LEN or DIST, where in tree */
  4046. uInt lit; /* if LIT, literal */
  4047. struct {
  4048. uInt get; /* bits to get for extra */
  4049. uInt dist; /* distance back to copy from */
  4050. } copy; /* if EXT or COPY, where and how much */
  4051. } sub; /* submode */
  4052. /* mode independent information */
  4053. Byte lbits; /* ltree bits decoded per branch */
  4054. Byte dbits; /* dtree bits decoder per branch */
  4055. inflate_huft *ltree; /* literal/length/eob tree */
  4056. inflate_huft *dtree; /* distance tree */
  4057. };
  4058. inflate_codes_statef *inflate_codes_new(bl, bd, tl, td, z)
  4059. uInt bl, bd;
  4060. inflate_huft *tl;
  4061. inflate_huft *td; /* need separate declaration for Borland C++ */
  4062. z_streamp z;
  4063. {
  4064. inflate_codes_statef *c;
  4065. if ((c = (inflate_codes_statef *)
  4066. ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
  4067. {
  4068. c->mode = START;
  4069. c->lbits = (Byte)bl;
  4070. c->dbits = (Byte)bd;
  4071. c->ltree = tl;
  4072. c->dtree = td;
  4073. Tracev((stderr, "inflate: codes new\n"));
  4074. }
  4075. return c;
  4076. }
  4077. int inflate_codes(s, z, r)
  4078. inflate_blocks_statef *s;
  4079. z_streamp z;
  4080. int r;
  4081. {
  4082. uInt j; /* temporary storage */
  4083. inflate_huft *t; /* temporary pointer */
  4084. uInt e; /* extra bits or operation */
  4085. uLong b; /* bit buffer */
  4086. uInt k; /* bits in bit buffer */
  4087. Bytef *p; /* input data pointer */
  4088. uInt n; /* bytes available there */
  4089. Bytef *q; /* output window write pointer */
  4090. uInt m; /* bytes to end of window or read pointer */
  4091. Bytef *f; /* pointer to copy strings from */
  4092. inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
  4093. /* copy input/output information to locals (UPDATE macro restores) */
  4094. LOAD
  4095. /* process input and output based on current state */
  4096. while (1) switch (c->mode)
  4097. { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
  4098. case START: /* x: set up for LEN */
  4099. #ifndef SLOW
  4100. if (m >= 258 && n >= 10)
  4101. {
  4102. UPDATE
  4103. r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
  4104. LOAD
  4105. if (r != Z_OK)
  4106. {
  4107. c->mode = r == Z_STREAM_END ? WASH : BADCODE;
  4108. break;
  4109. }
  4110. }
  4111. #endif /* !SLOW */
  4112. c->sub.code.need = c->lbits;
  4113. c->sub.code.tree = c->ltree;
  4114. c->mode = LEN;
  4115. case LEN: /* i: get length/literal/eob next */
  4116. j = c->sub.code.need;
  4117. NEEDBITS(j)
  4118. t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
  4119. DUMPBITS(t->bits)
  4120. e = (uInt)(t->exop);
  4121. if (e == 0) /* literal */
  4122. {
  4123. c->sub.lit = t->base;
  4124. Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
  4125. "inflate: literal '%c'\n" :
  4126. "inflate: literal 0x%02x\n", t->base));
  4127. c->mode = LIT;
  4128. break;
  4129. }
  4130. if (e & 16) /* length */
  4131. {
  4132. c->sub.copy.get = e & 15;
  4133. c->len = t->base;
  4134. c->mode = LENEXT;
  4135. break;
  4136. }
  4137. if ((e & 64) == 0) /* next table */
  4138. {
  4139. c->sub.code.need = e;
  4140. c->sub.code.tree = t->next;
  4141. break;
  4142. }
  4143. if (e & 32) /* end of block */
  4144. {
  4145. Tracevv((stderr, "inflate: end of block\n"));
  4146. c->mode = WASH;
  4147. break;
  4148. }
  4149. c->mode = BADCODE; /* invalid code */
  4150. z->msg = (char*)"invalid literal/length code";
  4151. r = Z_DATA_ERROR;
  4152. LEAVE
  4153. case LENEXT: /* i: getting length extra (have base) */
  4154. j = c->sub.copy.get;
  4155. NEEDBITS(j)
  4156. c->len += (uInt)b & inflate_mask[j];
  4157. DUMPBITS(j)
  4158. c->sub.code.need = c->dbits;
  4159. c->sub.code.tree = c->dtree;
  4160. Tracevv((stderr, "inflate: length %u\n", c->len));
  4161. c->mode = DIST;
  4162. case DIST: /* i: get distance next */
  4163. j = c->sub.code.need;
  4164. NEEDBITS(j)
  4165. t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
  4166. DUMPBITS(t->bits)
  4167. e = (uInt)(t->exop);
  4168. if (e & 16) /* distance */
  4169. {
  4170. c->sub.copy.get = e & 15;
  4171. c->sub.copy.dist = t->base;
  4172. c->mode = DISTEXT;
  4173. break;
  4174. }
  4175. if ((e & 64) == 0) /* next table */
  4176. {
  4177. c->sub.code.need = e;
  4178. c->sub.code.tree = t->next;
  4179. break;
  4180. }
  4181. c->mode = BADCODE; /* invalid code */
  4182. z->msg = (char*)"invalid distance code";
  4183. r = Z_DATA_ERROR;
  4184. LEAVE
  4185. case DISTEXT: /* i: getting distance extra */
  4186. j = c->sub.copy.get;
  4187. NEEDBITS(j)
  4188. c->sub.copy.dist += (uInt)b & inflate_mask[j];
  4189. DUMPBITS(j)
  4190. Tracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist));
  4191. c->mode = COPY;
  4192. case COPY: /* o: copying bytes in window, waiting for space */
  4193. #ifndef __TURBOC__ /* Turbo C bug for following expression */
  4194. f = (uInt)(q - s->window) < c->sub.copy.dist ?
  4195. s->end - (c->sub.copy.dist - (q - s->window)) :
  4196. q - c->sub.copy.dist;
  4197. #else
  4198. f = q - c->sub.copy.dist;
  4199. if ((uInt)(q - s->window) < c->sub.copy.dist)
  4200. f = s->end - (c->sub.copy.dist - (uInt)(q - s->window));
  4201. #endif
  4202. while (c->len)
  4203. {
  4204. NEEDOUT
  4205. OUTBYTE(*f++)
  4206. if (f == s->end)
  4207. f = s->window;
  4208. c->len--;
  4209. }
  4210. c->mode = START;
  4211. break;
  4212. case LIT: /* o: got literal, waiting for output space */
  4213. NEEDOUT
  4214. OUTBYTE(c->sub.lit)
  4215. c->mode = START;
  4216. break;
  4217. case WASH: /* o: got eob, possibly more output */
  4218. FLUSH
  4219. if (s->read != s->write)
  4220. LEAVE
  4221. c->mode = END;
  4222. case END:
  4223. r = Z_STREAM_END;
  4224. LEAVE
  4225. case BADCODE: /* x: got error */
  4226. r = Z_DATA_ERROR;
  4227. LEAVE
  4228. default:
  4229. r = Z_STREAM_ERROR;
  4230. LEAVE
  4231. }
  4232. }
  4233. void inflate_codes_free(c, z)
  4234. inflate_codes_statef *c;
  4235. z_streamp z;
  4236. {
  4237. ZFREE(z, c);
  4238. Tracev((stderr, "inflate: codes free\n"));
  4239. }
  4240. /* --- infcodes.c */
  4241. /* +++ infutil.c */
  4242. /* inflate_util.c -- data and routines common to blocks and codes
  4243. * Copyright (C) 1995-1996 Mark Adler
  4244. * For conditions of distribution and use, see copyright notice in zlib.h
  4245. */
  4246. /* #include "zutil.h" */
  4247. /* #include "infblock.h" */
  4248. /* #include "inftrees.h" */
  4249. /* #include "infcodes.h" */
  4250. /* #include "infutil.h" */
  4251. #ifndef NO_DUMMY_DECL
  4252. struct inflate_codes_state {int dummy;}; /* for buggy compilers */
  4253. #endif
  4254. /* And'ing with mask[n] masks the lower n bits */
  4255. uInt inflate_mask[17] = {
  4256. 0x0000,
  4257. 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  4258. 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  4259. };
  4260. /* copy as much as possible from the sliding window to the output area */
  4261. int inflate_flush(s, z, r)
  4262. inflate_blocks_statef *s;
  4263. z_streamp z;
  4264. int r;
  4265. {
  4266. uInt n;
  4267. Bytef *p;
  4268. Bytef *q;
  4269. /* local copies of source and destination pointers */
  4270. p = z->next_out;
  4271. q = s->read;
  4272. /* compute number of bytes to copy as far as end of window */
  4273. n = (uInt)((q <= s->write ? s->write : s->end) - q);
  4274. if (n > z->avail_out) n = z->avail_out;
  4275. if (n && r == Z_BUF_ERROR) r = Z_OK;
  4276. /* update counters */
  4277. z->avail_out -= n;
  4278. z->total_out += n;
  4279. /* update check information */
  4280. if (s->checkfn != Z_NULL)
  4281. z->adler = s->check = (*s->checkfn)(s->check, q, n);
  4282. /* copy as far as end of window */
  4283. if (p != Z_NULL) {
  4284. zmemcpy(p, q, n);
  4285. p += n;
  4286. }
  4287. q += n;
  4288. /* see if more to copy at beginning of window */
  4289. if (q == s->end)
  4290. {
  4291. /* wrap pointers */
  4292. q = s->window;
  4293. if (s->write == s->end)
  4294. s->write = s->window;
  4295. /* compute bytes to copy */
  4296. n = (uInt)(s->write - q);
  4297. if (n > z->avail_out) n = z->avail_out;
  4298. if (n && r == Z_BUF_ERROR) r = Z_OK;
  4299. /* update counters */
  4300. z->avail_out -= n;
  4301. z->total_out += n;
  4302. /* update check information */
  4303. if (s->checkfn != Z_NULL)
  4304. z->adler = s->check = (*s->checkfn)(s->check, q, n);
  4305. /* copy */
  4306. if (p != Z_NULL) {
  4307. zmemcpy(p, q, n);
  4308. p += n;
  4309. }
  4310. q += n;
  4311. }
  4312. /* update pointers */
  4313. z->next_out = p;
  4314. s->read = q;
  4315. /* done */
  4316. return r;
  4317. }
  4318. /* --- infutil.c */
  4319. /* +++ inffast.c */
  4320. /* inffast.c -- process literals and length/distance pairs fast
  4321. * Copyright (C) 1995-1996 Mark Adler
  4322. * For conditions of distribution and use, see copyright notice in zlib.h
  4323. */
  4324. /* #include "zutil.h" */
  4325. /* #include "inftrees.h" */
  4326. /* #include "infblock.h" */
  4327. /* #include "infcodes.h" */
  4328. /* #include "infutil.h" */
  4329. /* #include "inffast.h" */
  4330. #ifndef NO_DUMMY_DECL
  4331. struct inflate_codes_state {int dummy;}; /* for buggy compilers */
  4332. #endif
  4333. /* simplify the use of the inflate_huft type with some defines */
  4334. #define base more.Base
  4335. #define next more.Next
  4336. #define exop word.what.Exop
  4337. #define bits word.what.Bits
  4338. /* macros for bit input with no checking and for returning unused bytes */
  4339. #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
  4340. #define UNGRAB {n+=(c=k>>3);p-=c;k&=7;}
  4341. /* Called with number of bytes left to write in window at least 258
  4342. (the maximum string length) and number of input bytes available
  4343. at least ten. The ten bytes are six bytes for the longest length/
  4344. distance pair plus four bytes for overloading the bit buffer. */
  4345. int inflate_fast(bl, bd, tl, td, s, z)
  4346. uInt bl, bd;
  4347. inflate_huft *tl;
  4348. inflate_huft *td; /* need separate declaration for Borland C++ */
  4349. inflate_blocks_statef *s;
  4350. z_streamp z;
  4351. {
  4352. inflate_huft *t; /* temporary pointer */
  4353. uInt e; /* extra bits or operation */
  4354. uLong b; /* bit buffer */
  4355. uInt k; /* bits in bit buffer */
  4356. Bytef *p; /* input data pointer */
  4357. uInt n; /* bytes available there */
  4358. Bytef *q; /* output window write pointer */
  4359. uInt m; /* bytes to end of window or read pointer */
  4360. uInt ml; /* mask for literal/length tree */
  4361. uInt md; /* mask for distance tree */
  4362. uInt c; /* bytes to copy */
  4363. uInt d; /* distance back to copy from */
  4364. Bytef *r; /* copy source pointer */
  4365. /* load input, output, bit values */
  4366. LOAD
  4367. /* initialize masks */
  4368. ml = inflate_mask[bl];
  4369. md = inflate_mask[bd];
  4370. /* do until not enough input or output space for fast loop */
  4371. do { /* assume called with m >= 258 && n >= 10 */
  4372. /* get literal/length code */
  4373. GRABBITS(20) /* max bits for literal/length code */
  4374. if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
  4375. {
  4376. DUMPBITS(t->bits)
  4377. Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
  4378. "inflate: * literal '%c'\n" :
  4379. "inflate: * literal 0x%02x\n", t->base));
  4380. *q++ = (Byte)t->base;
  4381. m--;
  4382. continue;
  4383. }
  4384. do {
  4385. DUMPBITS(t->bits)
  4386. if (e & 16)
  4387. {
  4388. /* get extra bits for length */
  4389. e &= 15;
  4390. c = t->base + ((uInt)b & inflate_mask[e]);
  4391. DUMPBITS(e)
  4392. Tracevv((stderr, "inflate: * length %u\n", c));
  4393. /* decode distance base of block to copy */
  4394. GRABBITS(15); /* max bits for distance code */
  4395. e = (t = td + ((uInt)b & md))->exop;
  4396. do {
  4397. DUMPBITS(t->bits)
  4398. if (e & 16)
  4399. {
  4400. /* get extra bits to add to distance base */
  4401. e &= 15;
  4402. GRABBITS(e) /* get extra bits (up to 13) */
  4403. d = t->base + ((uInt)b & inflate_mask[e]);
  4404. DUMPBITS(e)
  4405. Tracevv((stderr, "inflate: * distance %u\n", d));
  4406. /* do the copy */
  4407. m -= c;
  4408. if ((uInt)(q - s->window) >= d) /* offset before dest */
  4409. { /* just copy */
  4410. r = q - d;
  4411. *q++ = *r++; c--; /* minimum count is three, */
  4412. *q++ = *r++; c--; /* so unroll loop a little */
  4413. }
  4414. else /* else offset after destination */
  4415. {
  4416. e = d - (uInt)(q - s->window); /* bytes from offset to end */
  4417. r = s->end - e; /* pointer to offset */
  4418. if (c > e) /* if source crosses, */
  4419. {
  4420. c -= e; /* copy to end of window */
  4421. do {
  4422. *q++ = *r++;
  4423. } while (--e);
  4424. r = s->window; /* copy rest from start of window */
  4425. }
  4426. }
  4427. do { /* copy all or what's left */
  4428. *q++ = *r++;
  4429. } while (--c);
  4430. break;
  4431. }
  4432. else if ((e & 64) == 0)
  4433. e = (t = t->next + ((uInt)b & inflate_mask[e]))->exop;
  4434. else
  4435. {
  4436. z->msg = (char*)"invalid distance code";
  4437. UNGRAB
  4438. UPDATE
  4439. return Z_DATA_ERROR;
  4440. }
  4441. } while (1);
  4442. break;
  4443. }
  4444. if ((e & 64) == 0)
  4445. {
  4446. if ((e = (t = t->next + ((uInt)b & inflate_mask[e]))->exop) == 0)
  4447. {
  4448. DUMPBITS(t->bits)
  4449. Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
  4450. "inflate: * literal '%c'\n" :
  4451. "inflate: * literal 0x%02x\n", t->base));
  4452. *q++ = (Byte)t->base;
  4453. m--;
  4454. break;
  4455. }
  4456. }
  4457. else if (e & 32)
  4458. {
  4459. Tracevv((stderr, "inflate: * end of block\n"));
  4460. UNGRAB
  4461. UPDATE
  4462. return Z_STREAM_END;
  4463. }
  4464. else
  4465. {
  4466. z->msg = (char*)"invalid literal/length code";
  4467. UNGRAB
  4468. UPDATE
  4469. return Z_DATA_ERROR;
  4470. }
  4471. } while (1);
  4472. } while (m >= 258 && n >= 10);
  4473. /* not enough input or output--restore pointers and return */
  4474. UNGRAB
  4475. UPDATE
  4476. return Z_OK;
  4477. }
  4478. /* --- inffast.c */
  4479. /* +++ zutil.c */
  4480. /* zutil.c -- target dependent utility functions for the compression library
  4481. * Copyright (C) 1995-1996 Jean-loup Gailly.
  4482. * For conditions of distribution and use, see copyright notice in zlib.h
  4483. */
  4484. /* From: zutil.c,v 1.17 1996/07/24 13:41:12 me Exp $ */
  4485. #ifdef DEBUG_ZLIB
  4486. #include <stdio.h>
  4487. #endif
  4488. /* #include "zutil.h" */
  4489. #ifndef NO_DUMMY_DECL
  4490. struct internal_state {int dummy;}; /* for buggy compilers */
  4491. #endif
  4492. #ifndef STDC
  4493. extern void exit OF((int));
  4494. #endif
  4495. const char *z_errmsg[10] = {
  4496. "need dictionary", /* Z_NEED_DICT 2 */
  4497. "stream end", /* Z_STREAM_END 1 */
  4498. "", /* Z_OK 0 */
  4499. "file error", /* Z_ERRNO (-1) */
  4500. "stream error", /* Z_STREAM_ERROR (-2) */
  4501. "data error", /* Z_DATA_ERROR (-3) */
  4502. "insufficient memory", /* Z_MEM_ERROR (-4) */
  4503. "buffer error", /* Z_BUF_ERROR (-5) */
  4504. "incompatible version",/* Z_VERSION_ERROR (-6) */
  4505. ""};
  4506. const char *zlibVersion()
  4507. {
  4508. return ZLIB_VERSION;
  4509. }
  4510. #ifdef DEBUG_ZLIB
  4511. void z_error (m)
  4512. char *m;
  4513. {
  4514. fprintf(stderr, "%s\n", m);
  4515. exit(1);
  4516. }
  4517. #endif
  4518. #ifndef HAVE_MEMCPY
  4519. void zmemcpy(dest, source, len)
  4520. Bytef* dest;
  4521. Bytef* source;
  4522. uInt len;
  4523. {
  4524. if (len == 0) return;
  4525. do {
  4526. *dest++ = *source++; /* ??? to be unrolled */
  4527. } while (--len != 0);
  4528. }
  4529. int zmemcmp(s1, s2, len)
  4530. Bytef* s1;
  4531. Bytef* s2;
  4532. uInt len;
  4533. {
  4534. uInt j;
  4535. for (j = 0; j < len; j++) {
  4536. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  4537. }
  4538. return 0;
  4539. }
  4540. void zmemzero(dest, len)
  4541. Bytef* dest;
  4542. uInt len;
  4543. {
  4544. if (len == 0) return;
  4545. do {
  4546. *dest++ = 0; /* ??? to be unrolled */
  4547. } while (--len != 0);
  4548. }
  4549. #endif
  4550. #ifdef __TURBOC__
  4551. #if (defined( __BORLANDC__) || !defined(SMALL_MEDIUM)) && !defined(__32BIT__)
  4552. /* Small and medium model in Turbo C are for now limited to near allocation
  4553. * with reduced MAX_WBITS and MAX_MEM_LEVEL
  4554. */
  4555. # define MY_ZCALLOC
  4556. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  4557. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  4558. * must fix the pointer. Warning: the pointer must be put back to its
  4559. * original form in order to free it, use zcfree().
  4560. */
  4561. #define MAX_PTR 10
  4562. /* 10*64K = 640K */
  4563. local int next_ptr = 0;
  4564. typedef struct ptr_table_s {
  4565. voidpf org_ptr;
  4566. voidpf new_ptr;
  4567. } ptr_table;
  4568. local ptr_table table[MAX_PTR];
  4569. /* This table is used to remember the original form of pointers
  4570. * to large buffers (64K). Such pointers are normalized with a zero offset.
  4571. * Since MSDOS is not a preemptive multitasking OS, this table is not
  4572. * protected from concurrent access. This hack doesn't work anyway on
  4573. * a protected system like OS/2. Use Microsoft C instead.
  4574. */
  4575. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  4576. {
  4577. voidpf buf = opaque; /* just to make some compilers happy */
  4578. ulg bsize = (ulg)items*size;
  4579. /* If we allocate less than 65520 bytes, we assume that farmalloc
  4580. * will return a usable pointer which doesn't have to be normalized.
  4581. */
  4582. if (bsize < 65520L) {
  4583. buf = farmalloc(bsize);
  4584. if (*(ush*)&buf != 0) return buf;
  4585. } else {
  4586. buf = farmalloc(bsize + 16L);
  4587. }
  4588. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  4589. table[next_ptr].org_ptr = buf;
  4590. /* Normalize the pointer to seg:0 */
  4591. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  4592. *(ush*)&buf = 0;
  4593. table[next_ptr++].new_ptr = buf;
  4594. return buf;
  4595. }
  4596. void zcfree (voidpf opaque, voidpf ptr)
  4597. {
  4598. int n;
  4599. if (*(ush*)&ptr != 0) { /* object < 64K */
  4600. farfree(ptr);
  4601. return;
  4602. }
  4603. /* Find the original pointer */
  4604. for (n = 0; n < next_ptr; n++) {
  4605. if (ptr != table[n].new_ptr) continue;
  4606. farfree(table[n].org_ptr);
  4607. while (++n < next_ptr) {
  4608. table[n-1] = table[n];
  4609. }
  4610. next_ptr--;
  4611. return;
  4612. }
  4613. ptr = opaque; /* just to make some compilers happy */
  4614. Assert(0, "zcfree: ptr not found");
  4615. }
  4616. #endif
  4617. #endif /* __TURBOC__ */
  4618. #if defined(M_I86) && !defined(__32BIT__)
  4619. /* Microsoft C in 16-bit mode */
  4620. # define MY_ZCALLOC
  4621. #if (!defined(_MSC_VER) || (_MSC_VER < 600))
  4622. # define _halloc halloc
  4623. # define _hfree hfree
  4624. #endif
  4625. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  4626. {
  4627. if (opaque) opaque = 0; /* to make compiler happy */
  4628. return _halloc((long)items, size);
  4629. }
  4630. void zcfree (voidpf opaque, voidpf ptr)
  4631. {
  4632. if (opaque) opaque = 0; /* to make compiler happy */
  4633. _hfree(ptr);
  4634. }
  4635. #endif /* MSC */
  4636. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  4637. #ifndef STDC
  4638. extern voidp calloc OF((uInt items, uInt size));
  4639. extern void free OF((voidpf ptr));
  4640. #endif
  4641. voidpf zcalloc (opaque, items, size)
  4642. voidpf opaque;
  4643. unsigned items;
  4644. unsigned size;
  4645. {
  4646. if (opaque) items += size - size; /* make compiler happy */
  4647. return (voidpf)calloc(items, size);
  4648. }
  4649. void zcfree (opaque, ptr)
  4650. voidpf opaque;
  4651. voidpf ptr;
  4652. {
  4653. free(ptr);
  4654. if (opaque) return; /* make compiler happy */
  4655. }
  4656. #endif /* MY_ZCALLOC */
  4657. /* --- zutil.c */
  4658. /* +++ adler32.c */
  4659. /* adler32.c -- compute the Adler-32 checksum of a data stream
  4660. * Copyright (C) 1995-1996 Mark Adler
  4661. * For conditions of distribution and use, see copyright notice in zlib.h
  4662. */
  4663. /* From: adler32.c,v 1.10 1996/05/22 11:52:18 me Exp $ */
  4664. /* #include "zlib.h" */
  4665. #define BASE 65521L /* largest prime smaller than 65536 */
  4666. #define NMAX 5552
  4667. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  4668. #define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
  4669. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  4670. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  4671. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  4672. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  4673. /* ========================================================================= */
  4674. uLong adler32(adler, buf, len)
  4675. uLong adler;
  4676. const Bytef *buf;
  4677. uInt len;
  4678. {
  4679. unsigned long s1 = adler & 0xffff;
  4680. unsigned long s2 = (adler >> 16) & 0xffff;
  4681. int k;
  4682. if (buf == Z_NULL) return 1L;
  4683. while (len > 0) {
  4684. k = len < NMAX ? len : NMAX;
  4685. len -= k;
  4686. while (k >= 16) {
  4687. DO16(buf);
  4688. buf += 16;
  4689. k -= 16;
  4690. }
  4691. if (k != 0) do {
  4692. s1 += *buf++;
  4693. s2 += s1;
  4694. } while (--k);
  4695. s1 %= BASE;
  4696. s2 %= BASE;
  4697. }
  4698. return (s2 << 16) | s1;
  4699. }
  4700. /* --- adler32.c */